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/Sema/Overload.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/DeclObjC.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/TargetInfo.h" 25 #include "clang/Sema/Initialization.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/SemaInternal.h" 28 #include "clang/Sema/Template.h" 29 #include "clang/Sema/TemplateDeduction.h" 30 #include "llvm/ADT/DenseSet.h" 31 #include "llvm/ADT/Optional.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 using AllowedExplicit = Sema::AllowedExplicit; 42 43 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 44 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 45 return P->hasAttr<PassObjectSizeAttr>(); 46 }); 47 } 48 49 /// A convenience routine for creating a decayed reference to a function. 50 static ExprResult 51 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 52 const Expr *Base, bool HadMultipleCandidates, 53 SourceLocation Loc = SourceLocation(), 54 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 55 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 56 return ExprError(); 57 // If FoundDecl is different from Fn (such as if one is a template 58 // and the other a specialization), make sure DiagnoseUseOfDecl is 59 // called on both. 60 // FIXME: This would be more comprehensively addressed by modifying 61 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 62 // being used. 63 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 64 return ExprError(); 65 DeclRefExpr *DRE = new (S.Context) 66 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 67 if (HadMultipleCandidates) 68 DRE->setHadMultipleCandidates(true); 69 70 S.MarkDeclRefReferenced(DRE, Base); 71 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 72 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 73 S.ResolveExceptionSpec(Loc, FPT); 74 DRE->setType(Fn->getType()); 75 } 76 } 77 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 78 CK_FunctionToPointerDecay); 79 } 80 81 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 82 bool InOverloadResolution, 83 StandardConversionSequence &SCS, 84 bool CStyle, 85 bool AllowObjCWritebackConversion); 86 87 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 88 QualType &ToType, 89 bool InOverloadResolution, 90 StandardConversionSequence &SCS, 91 bool CStyle); 92 static OverloadingResult 93 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 94 UserDefinedConversionSequence& User, 95 OverloadCandidateSet& Conversions, 96 AllowedExplicit AllowExplicit, 97 bool AllowObjCConversionOnExplicit); 98 99 static ImplicitConversionSequence::CompareKind 100 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 101 const StandardConversionSequence& SCS1, 102 const StandardConversionSequence& SCS2); 103 104 static ImplicitConversionSequence::CompareKind 105 CompareQualificationConversions(Sema &S, 106 const StandardConversionSequence& SCS1, 107 const StandardConversionSequence& SCS2); 108 109 static ImplicitConversionSequence::CompareKind 110 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 111 const StandardConversionSequence& SCS1, 112 const StandardConversionSequence& SCS2); 113 114 /// GetConversionRank - Retrieve the implicit conversion rank 115 /// corresponding to the given implicit conversion kind. 116 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 117 static const ImplicitConversionRank 118 Rank[(int)ICK_Num_Conversion_Kinds] = { 119 ICR_Exact_Match, 120 ICR_Exact_Match, 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Exact_Match, 125 ICR_Promotion, 126 ICR_Promotion, 127 ICR_Promotion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_OCL_Scalar_Widening, 139 ICR_Complex_Real_Conversion, 140 ICR_Conversion, 141 ICR_Conversion, 142 ICR_Writeback_Conversion, 143 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 144 // it was omitted by the patch that added 145 // ICK_Zero_Event_Conversion 146 ICR_C_Conversion, 147 ICR_C_Conversion_Extension 148 }; 149 return Rank[(int)Kind]; 150 } 151 152 /// GetImplicitConversionName - Return the name of this kind of 153 /// implicit conversion. 154 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 155 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 156 "No conversion", 157 "Lvalue-to-rvalue", 158 "Array-to-pointer", 159 "Function-to-pointer", 160 "Function pointer conversion", 161 "Qualification", 162 "Integral promotion", 163 "Floating point promotion", 164 "Complex promotion", 165 "Integral conversion", 166 "Floating conversion", 167 "Complex conversion", 168 "Floating-integral conversion", 169 "Pointer conversion", 170 "Pointer-to-member conversion", 171 "Boolean conversion", 172 "Compatible-types conversion", 173 "Derived-to-base conversion", 174 "Vector conversion", 175 "Vector splat", 176 "Complex-real conversion", 177 "Block Pointer conversion", 178 "Transparent Union Conversion", 179 "Writeback conversion", 180 "OpenCL Zero Event Conversion", 181 "C specific type conversion", 182 "Incompatible pointer conversion" 183 }; 184 return Name[Kind]; 185 } 186 187 /// StandardConversionSequence - Set the standard conversion 188 /// sequence to the identity conversion. 189 void StandardConversionSequence::setAsIdentityConversion() { 190 First = ICK_Identity; 191 Second = ICK_Identity; 192 Third = ICK_Identity; 193 DeprecatedStringLiteralToCharPtr = false; 194 QualificationIncludesObjCLifetime = false; 195 ReferenceBinding = false; 196 DirectBinding = false; 197 IsLvalueReference = true; 198 BindsToFunctionLvalue = false; 199 BindsToRvalue = false; 200 BindsImplicitObjectArgumentWithoutRefQualifier = false; 201 ObjCLifetimeConversionBinding = false; 202 CopyConstructor = nullptr; 203 } 204 205 /// getRank - Retrieve the rank of this standard conversion sequence 206 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 207 /// implicit conversions. 208 ImplicitConversionRank StandardConversionSequence::getRank() const { 209 ImplicitConversionRank Rank = ICR_Exact_Match; 210 if (GetConversionRank(First) > Rank) 211 Rank = GetConversionRank(First); 212 if (GetConversionRank(Second) > Rank) 213 Rank = GetConversionRank(Second); 214 if (GetConversionRank(Third) > Rank) 215 Rank = GetConversionRank(Third); 216 return Rank; 217 } 218 219 /// isPointerConversionToBool - Determines whether this conversion is 220 /// a conversion of a pointer or pointer-to-member to bool. This is 221 /// used as part of the ranking of standard conversion sequences 222 /// (C++ 13.3.3.2p4). 223 bool StandardConversionSequence::isPointerConversionToBool() const { 224 // Note that FromType has not necessarily been transformed by the 225 // array-to-pointer or function-to-pointer implicit conversions, so 226 // check for their presence as well as checking whether FromType is 227 // a pointer. 228 if (getToType(1)->isBooleanType() && 229 (getFromType()->isPointerType() || 230 getFromType()->isMemberPointerType() || 231 getFromType()->isObjCObjectPointerType() || 232 getFromType()->isBlockPointerType() || 233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 234 return true; 235 236 return false; 237 } 238 239 /// isPointerConversionToVoidPointer - Determines whether this 240 /// conversion is a conversion of a pointer to a void pointer. This is 241 /// used as part of the ranking of standard conversion sequences (C++ 242 /// 13.3.3.2p4). 243 bool 244 StandardConversionSequence:: 245 isPointerConversionToVoidPointer(ASTContext& Context) const { 246 QualType FromType = getFromType(); 247 QualType ToType = getToType(1); 248 249 // Note that FromType has not necessarily been transformed by the 250 // array-to-pointer implicit conversion, so check for its presence 251 // and redo the conversion to get a pointer. 252 if (First == ICK_Array_To_Pointer) 253 FromType = Context.getArrayDecayedType(FromType); 254 255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 257 return ToPtrType->getPointeeType()->isVoidType(); 258 259 return false; 260 } 261 262 /// Skip any implicit casts which could be either part of a narrowing conversion 263 /// or after one in an implicit conversion. 264 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 265 const Expr *Converted) { 266 // We can have cleanups wrapping the converted expression; these need to be 267 // preserved so that destructors run if necessary. 268 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 269 Expr *Inner = 270 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 271 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 272 EWC->getObjects()); 273 } 274 275 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 276 switch (ICE->getCastKind()) { 277 case CK_NoOp: 278 case CK_IntegralCast: 279 case CK_IntegralToBoolean: 280 case CK_IntegralToFloating: 281 case CK_BooleanToSignedIntegral: 282 case CK_FloatingToIntegral: 283 case CK_FloatingToBoolean: 284 case CK_FloatingCast: 285 Converted = ICE->getSubExpr(); 286 continue; 287 288 default: 289 return Converted; 290 } 291 } 292 293 return Converted; 294 } 295 296 /// Check if this standard conversion sequence represents a narrowing 297 /// conversion, according to C++11 [dcl.init.list]p7. 298 /// 299 /// \param Ctx The AST context. 300 /// \param Converted The result of applying this standard conversion sequence. 301 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 302 /// value of the expression prior to the narrowing conversion. 303 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 304 /// type of the expression prior to the narrowing conversion. 305 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 306 /// from floating point types to integral types should be ignored. 307 NarrowingKind StandardConversionSequence::getNarrowingKind( 308 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 309 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 310 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 311 312 // C++11 [dcl.init.list]p7: 313 // A narrowing conversion is an implicit conversion ... 314 QualType FromType = getToType(0); 315 QualType ToType = getToType(1); 316 317 // A conversion to an enumeration type is narrowing if the conversion to 318 // the underlying type is narrowing. This only arises for expressions of 319 // the form 'Enum{init}'. 320 if (auto *ET = ToType->getAs<EnumType>()) 321 ToType = ET->getDecl()->getIntegerType(); 322 323 switch (Second) { 324 // 'bool' is an integral type; dispatch to the right place to handle it. 325 case ICK_Boolean_Conversion: 326 if (FromType->isRealFloatingType()) 327 goto FloatingIntegralConversion; 328 if (FromType->isIntegralOrUnscopedEnumerationType()) 329 goto IntegralConversion; 330 // -- from a pointer type or pointer-to-member type to bool, or 331 return NK_Type_Narrowing; 332 333 // -- from a floating-point type to an integer type, or 334 // 335 // -- from an integer type or unscoped enumeration type to a floating-point 336 // type, except where the source is a constant expression and the actual 337 // value after conversion will fit into the target type and will produce 338 // the original value when converted back to the original type, or 339 case ICK_Floating_Integral: 340 FloatingIntegralConversion: 341 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 342 return NK_Type_Narrowing; 343 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 344 ToType->isRealFloatingType()) { 345 if (IgnoreFloatToIntegralConversion) 346 return NK_Not_Narrowing; 347 llvm::APSInt IntConstantValue; 348 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 349 assert(Initializer && "Unknown conversion expression"); 350 351 // If it's value-dependent, we can't tell whether it's narrowing. 352 if (Initializer->isValueDependent()) 353 return NK_Dependent_Narrowing; 354 355 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 356 // Convert the integer to the floating type. 357 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 358 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 359 llvm::APFloat::rmNearestTiesToEven); 360 // And back. 361 llvm::APSInt ConvertedValue = IntConstantValue; 362 bool ignored; 363 Result.convertToInteger(ConvertedValue, 364 llvm::APFloat::rmTowardZero, &ignored); 365 // If the resulting value is different, this was a narrowing conversion. 366 if (IntConstantValue != ConvertedValue) { 367 ConstantValue = APValue(IntConstantValue); 368 ConstantType = Initializer->getType(); 369 return NK_Constant_Narrowing; 370 } 371 } else { 372 // Variables are always narrowings. 373 return NK_Variable_Narrowing; 374 } 375 } 376 return NK_Not_Narrowing; 377 378 // -- from long double to double or float, or from double to float, except 379 // where the source is a constant expression and the actual value after 380 // conversion is within the range of values that can be represented (even 381 // if it cannot be represented exactly), or 382 case ICK_Floating_Conversion: 383 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 384 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 385 // FromType is larger than ToType. 386 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 387 388 // If it's value-dependent, we can't tell whether it's narrowing. 389 if (Initializer->isValueDependent()) 390 return NK_Dependent_Narrowing; 391 392 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 393 // Constant! 394 assert(ConstantValue.isFloat()); 395 llvm::APFloat FloatVal = ConstantValue.getFloat(); 396 // Convert the source value into the target type. 397 bool ignored; 398 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 399 Ctx.getFloatTypeSemantics(ToType), 400 llvm::APFloat::rmNearestTiesToEven, &ignored); 401 // If there was no overflow, the source value is within the range of 402 // values that can be represented. 403 if (ConvertStatus & llvm::APFloat::opOverflow) { 404 ConstantType = Initializer->getType(); 405 return NK_Constant_Narrowing; 406 } 407 } else { 408 return NK_Variable_Narrowing; 409 } 410 } 411 return NK_Not_Narrowing; 412 413 // -- from an integer type or unscoped enumeration type to an integer type 414 // that cannot represent all the values of the original type, except where 415 // the source is a constant expression and the actual value after 416 // conversion will fit into the target type and will produce the original 417 // value when converted back to the original type. 418 case ICK_Integral_Conversion: 419 IntegralConversion: { 420 assert(FromType->isIntegralOrUnscopedEnumerationType()); 421 assert(ToType->isIntegralOrUnscopedEnumerationType()); 422 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 423 const unsigned FromWidth = Ctx.getIntWidth(FromType); 424 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 425 const unsigned ToWidth = Ctx.getIntWidth(ToType); 426 427 if (FromWidth > ToWidth || 428 (FromWidth == ToWidth && FromSigned != ToSigned) || 429 (FromSigned && !ToSigned)) { 430 // Not all values of FromType can be represented in ToType. 431 llvm::APSInt InitializerValue; 432 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 433 434 // If it's value-dependent, we can't tell whether it's narrowing. 435 if (Initializer->isValueDependent()) 436 return NK_Dependent_Narrowing; 437 438 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 439 // Such conversions on variables are always narrowing. 440 return NK_Variable_Narrowing; 441 } 442 bool Narrowing = false; 443 if (FromWidth < ToWidth) { 444 // Negative -> unsigned is narrowing. Otherwise, more bits is never 445 // narrowing. 446 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 447 Narrowing = true; 448 } else { 449 // Add a bit to the InitializerValue so we don't have to worry about 450 // signed vs. unsigned comparisons. 451 InitializerValue = InitializerValue.extend( 452 InitializerValue.getBitWidth() + 1); 453 // Convert the initializer to and from the target width and signed-ness. 454 llvm::APSInt ConvertedValue = InitializerValue; 455 ConvertedValue = ConvertedValue.trunc(ToWidth); 456 ConvertedValue.setIsSigned(ToSigned); 457 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 458 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 459 // If the result is different, this was a narrowing conversion. 460 if (ConvertedValue != InitializerValue) 461 Narrowing = true; 462 } 463 if (Narrowing) { 464 ConstantType = Initializer->getType(); 465 ConstantValue = APValue(InitializerValue); 466 return NK_Constant_Narrowing; 467 } 468 } 469 return NK_Not_Narrowing; 470 } 471 472 default: 473 // Other kinds of conversions are not narrowings. 474 return NK_Not_Narrowing; 475 } 476 } 477 478 /// dump - Print this standard conversion sequence to standard 479 /// error. Useful for debugging overloading issues. 480 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 481 raw_ostream &OS = llvm::errs(); 482 bool PrintedSomething = false; 483 if (First != ICK_Identity) { 484 OS << GetImplicitConversionName(First); 485 PrintedSomething = true; 486 } 487 488 if (Second != ICK_Identity) { 489 if (PrintedSomething) { 490 OS << " -> "; 491 } 492 OS << GetImplicitConversionName(Second); 493 494 if (CopyConstructor) { 495 OS << " (by copy constructor)"; 496 } else if (DirectBinding) { 497 OS << " (direct reference binding)"; 498 } else if (ReferenceBinding) { 499 OS << " (reference binding)"; 500 } 501 PrintedSomething = true; 502 } 503 504 if (Third != ICK_Identity) { 505 if (PrintedSomething) { 506 OS << " -> "; 507 } 508 OS << GetImplicitConversionName(Third); 509 PrintedSomething = true; 510 } 511 512 if (!PrintedSomething) { 513 OS << "No conversions required"; 514 } 515 } 516 517 /// dump - Print this user-defined conversion sequence to standard 518 /// error. Useful for debugging overloading issues. 519 void UserDefinedConversionSequence::dump() const { 520 raw_ostream &OS = llvm::errs(); 521 if (Before.First || Before.Second || Before.Third) { 522 Before.dump(); 523 OS << " -> "; 524 } 525 if (ConversionFunction) 526 OS << '\'' << *ConversionFunction << '\''; 527 else 528 OS << "aggregate initialization"; 529 if (After.First || After.Second || After.Third) { 530 OS << " -> "; 531 After.dump(); 532 } 533 } 534 535 /// dump - Print this implicit conversion sequence to standard 536 /// error. Useful for debugging overloading issues. 537 void ImplicitConversionSequence::dump() const { 538 raw_ostream &OS = llvm::errs(); 539 if (isStdInitializerListElement()) 540 OS << "Worst std::initializer_list element conversion: "; 541 switch (ConversionKind) { 542 case StandardConversion: 543 OS << "Standard conversion: "; 544 Standard.dump(); 545 break; 546 case UserDefinedConversion: 547 OS << "User-defined conversion: "; 548 UserDefined.dump(); 549 break; 550 case EllipsisConversion: 551 OS << "Ellipsis conversion"; 552 break; 553 case AmbiguousConversion: 554 OS << "Ambiguous conversion"; 555 break; 556 case BadConversion: 557 OS << "Bad conversion"; 558 break; 559 } 560 561 OS << "\n"; 562 } 563 564 void AmbiguousConversionSequence::construct() { 565 new (&conversions()) ConversionSet(); 566 } 567 568 void AmbiguousConversionSequence::destruct() { 569 conversions().~ConversionSet(); 570 } 571 572 void 573 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 574 FromTypePtr = O.FromTypePtr; 575 ToTypePtr = O.ToTypePtr; 576 new (&conversions()) ConversionSet(O.conversions()); 577 } 578 579 namespace { 580 // Structure used by DeductionFailureInfo to store 581 // template argument information. 582 struct DFIArguments { 583 TemplateArgument FirstArg; 584 TemplateArgument SecondArg; 585 }; 586 // Structure used by DeductionFailureInfo to store 587 // template parameter and template argument information. 588 struct DFIParamWithArguments : DFIArguments { 589 TemplateParameter Param; 590 }; 591 // Structure used by DeductionFailureInfo to store template argument 592 // information and the index of the problematic call argument. 593 struct DFIDeducedMismatchArgs : DFIArguments { 594 TemplateArgumentList *TemplateArgs; 595 unsigned CallArgIndex; 596 }; 597 // Structure used by DeductionFailureInfo to store information about 598 // unsatisfied constraints. 599 struct CNSInfo { 600 TemplateArgumentList *TemplateArgs; 601 ConstraintSatisfaction Satisfaction; 602 }; 603 } 604 605 /// Convert from Sema's representation of template deduction information 606 /// to the form used in overload-candidate information. 607 DeductionFailureInfo 608 clang::MakeDeductionFailureInfo(ASTContext &Context, 609 Sema::TemplateDeductionResult TDK, 610 TemplateDeductionInfo &Info) { 611 DeductionFailureInfo Result; 612 Result.Result = static_cast<unsigned>(TDK); 613 Result.HasDiagnostic = false; 614 switch (TDK) { 615 case Sema::TDK_Invalid: 616 case Sema::TDK_InstantiationDepth: 617 case Sema::TDK_TooManyArguments: 618 case Sema::TDK_TooFewArguments: 619 case Sema::TDK_MiscellaneousDeductionFailure: 620 case Sema::TDK_CUDATargetMismatch: 621 Result.Data = nullptr; 622 break; 623 624 case Sema::TDK_Incomplete: 625 case Sema::TDK_InvalidExplicitArguments: 626 Result.Data = Info.Param.getOpaqueValue(); 627 break; 628 629 case Sema::TDK_DeducedMismatch: 630 case Sema::TDK_DeducedMismatchNested: { 631 // FIXME: Should allocate from normal heap so that we can free this later. 632 auto *Saved = new (Context) DFIDeducedMismatchArgs; 633 Saved->FirstArg = Info.FirstArg; 634 Saved->SecondArg = Info.SecondArg; 635 Saved->TemplateArgs = Info.take(); 636 Saved->CallArgIndex = Info.CallArgIndex; 637 Result.Data = Saved; 638 break; 639 } 640 641 case Sema::TDK_NonDeducedMismatch: { 642 // FIXME: Should allocate from normal heap so that we can free this later. 643 DFIArguments *Saved = new (Context) DFIArguments; 644 Saved->FirstArg = Info.FirstArg; 645 Saved->SecondArg = Info.SecondArg; 646 Result.Data = Saved; 647 break; 648 } 649 650 case Sema::TDK_IncompletePack: 651 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 652 case Sema::TDK_Inconsistent: 653 case Sema::TDK_Underqualified: { 654 // FIXME: Should allocate from normal heap so that we can free this later. 655 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 656 Saved->Param = Info.Param; 657 Saved->FirstArg = Info.FirstArg; 658 Saved->SecondArg = Info.SecondArg; 659 Result.Data = Saved; 660 break; 661 } 662 663 case Sema::TDK_SubstitutionFailure: 664 Result.Data = Info.take(); 665 if (Info.hasSFINAEDiagnostic()) { 666 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 667 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 668 Info.takeSFINAEDiagnostic(*Diag); 669 Result.HasDiagnostic = true; 670 } 671 break; 672 673 case Sema::TDK_ConstraintsNotSatisfied: { 674 CNSInfo *Saved = new (Context) CNSInfo; 675 Saved->TemplateArgs = Info.take(); 676 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 677 Result.Data = Saved; 678 break; 679 } 680 681 case Sema::TDK_Success: 682 case Sema::TDK_NonDependentConversionFailure: 683 llvm_unreachable("not a deduction failure"); 684 } 685 686 return Result; 687 } 688 689 void DeductionFailureInfo::Destroy() { 690 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 691 case Sema::TDK_Success: 692 case Sema::TDK_Invalid: 693 case Sema::TDK_InstantiationDepth: 694 case Sema::TDK_Incomplete: 695 case Sema::TDK_TooManyArguments: 696 case Sema::TDK_TooFewArguments: 697 case Sema::TDK_InvalidExplicitArguments: 698 case Sema::TDK_CUDATargetMismatch: 699 case Sema::TDK_NonDependentConversionFailure: 700 break; 701 702 case Sema::TDK_IncompletePack: 703 case Sema::TDK_Inconsistent: 704 case Sema::TDK_Underqualified: 705 case Sema::TDK_DeducedMismatch: 706 case Sema::TDK_DeducedMismatchNested: 707 case Sema::TDK_NonDeducedMismatch: 708 // FIXME: Destroy the data? 709 Data = nullptr; 710 break; 711 712 case Sema::TDK_SubstitutionFailure: 713 // FIXME: Destroy the template argument list? 714 Data = nullptr; 715 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 716 Diag->~PartialDiagnosticAt(); 717 HasDiagnostic = false; 718 } 719 break; 720 721 case Sema::TDK_ConstraintsNotSatisfied: 722 // FIXME: Destroy the template argument list? 723 Data = nullptr; 724 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 725 Diag->~PartialDiagnosticAt(); 726 HasDiagnostic = false; 727 } 728 break; 729 730 // Unhandled 731 case Sema::TDK_MiscellaneousDeductionFailure: 732 break; 733 } 734 } 735 736 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 737 if (HasDiagnostic) 738 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 739 return nullptr; 740 } 741 742 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 743 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 744 case Sema::TDK_Success: 745 case Sema::TDK_Invalid: 746 case Sema::TDK_InstantiationDepth: 747 case Sema::TDK_TooManyArguments: 748 case Sema::TDK_TooFewArguments: 749 case Sema::TDK_SubstitutionFailure: 750 case Sema::TDK_DeducedMismatch: 751 case Sema::TDK_DeducedMismatchNested: 752 case Sema::TDK_NonDeducedMismatch: 753 case Sema::TDK_CUDATargetMismatch: 754 case Sema::TDK_NonDependentConversionFailure: 755 case Sema::TDK_ConstraintsNotSatisfied: 756 return TemplateParameter(); 757 758 case Sema::TDK_Incomplete: 759 case Sema::TDK_InvalidExplicitArguments: 760 return TemplateParameter::getFromOpaqueValue(Data); 761 762 case Sema::TDK_IncompletePack: 763 case Sema::TDK_Inconsistent: 764 case Sema::TDK_Underqualified: 765 return static_cast<DFIParamWithArguments*>(Data)->Param; 766 767 // Unhandled 768 case Sema::TDK_MiscellaneousDeductionFailure: 769 break; 770 } 771 772 return TemplateParameter(); 773 } 774 775 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 776 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 777 case Sema::TDK_Success: 778 case Sema::TDK_Invalid: 779 case Sema::TDK_InstantiationDepth: 780 case Sema::TDK_TooManyArguments: 781 case Sema::TDK_TooFewArguments: 782 case Sema::TDK_Incomplete: 783 case Sema::TDK_IncompletePack: 784 case Sema::TDK_InvalidExplicitArguments: 785 case Sema::TDK_Inconsistent: 786 case Sema::TDK_Underqualified: 787 case Sema::TDK_NonDeducedMismatch: 788 case Sema::TDK_CUDATargetMismatch: 789 case Sema::TDK_NonDependentConversionFailure: 790 return nullptr; 791 792 case Sema::TDK_DeducedMismatch: 793 case Sema::TDK_DeducedMismatchNested: 794 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 795 796 case Sema::TDK_SubstitutionFailure: 797 return static_cast<TemplateArgumentList*>(Data); 798 799 case Sema::TDK_ConstraintsNotSatisfied: 800 return static_cast<CNSInfo*>(Data)->TemplateArgs; 801 802 // Unhandled 803 case Sema::TDK_MiscellaneousDeductionFailure: 804 break; 805 } 806 807 return nullptr; 808 } 809 810 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 811 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 812 case Sema::TDK_Success: 813 case Sema::TDK_Invalid: 814 case Sema::TDK_InstantiationDepth: 815 case Sema::TDK_Incomplete: 816 case Sema::TDK_TooManyArguments: 817 case Sema::TDK_TooFewArguments: 818 case Sema::TDK_InvalidExplicitArguments: 819 case Sema::TDK_SubstitutionFailure: 820 case Sema::TDK_CUDATargetMismatch: 821 case Sema::TDK_NonDependentConversionFailure: 822 case Sema::TDK_ConstraintsNotSatisfied: 823 return nullptr; 824 825 case Sema::TDK_IncompletePack: 826 case Sema::TDK_Inconsistent: 827 case Sema::TDK_Underqualified: 828 case Sema::TDK_DeducedMismatch: 829 case Sema::TDK_DeducedMismatchNested: 830 case Sema::TDK_NonDeducedMismatch: 831 return &static_cast<DFIArguments*>(Data)->FirstArg; 832 833 // Unhandled 834 case Sema::TDK_MiscellaneousDeductionFailure: 835 break; 836 } 837 838 return nullptr; 839 } 840 841 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 842 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 843 case Sema::TDK_Success: 844 case Sema::TDK_Invalid: 845 case Sema::TDK_InstantiationDepth: 846 case Sema::TDK_Incomplete: 847 case Sema::TDK_IncompletePack: 848 case Sema::TDK_TooManyArguments: 849 case Sema::TDK_TooFewArguments: 850 case Sema::TDK_InvalidExplicitArguments: 851 case Sema::TDK_SubstitutionFailure: 852 case Sema::TDK_CUDATargetMismatch: 853 case Sema::TDK_NonDependentConversionFailure: 854 case Sema::TDK_ConstraintsNotSatisfied: 855 return nullptr; 856 857 case Sema::TDK_Inconsistent: 858 case Sema::TDK_Underqualified: 859 case Sema::TDK_DeducedMismatch: 860 case Sema::TDK_DeducedMismatchNested: 861 case Sema::TDK_NonDeducedMismatch: 862 return &static_cast<DFIArguments*>(Data)->SecondArg; 863 864 // Unhandled 865 case Sema::TDK_MiscellaneousDeductionFailure: 866 break; 867 } 868 869 return nullptr; 870 } 871 872 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 873 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 874 case Sema::TDK_DeducedMismatch: 875 case Sema::TDK_DeducedMismatchNested: 876 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 877 878 default: 879 return llvm::None; 880 } 881 } 882 883 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 884 OverloadedOperatorKind Op) { 885 if (!AllowRewrittenCandidates) 886 return false; 887 return Op == OO_EqualEqual || Op == OO_Spaceship; 888 } 889 890 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 891 ASTContext &Ctx, const FunctionDecl *FD) { 892 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 893 return false; 894 // Don't bother adding a reversed candidate that can never be a better 895 // match than the non-reversed version. 896 return FD->getNumParams() != 2 || 897 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 898 FD->getParamDecl(1)->getType()) || 899 FD->hasAttr<EnableIfAttr>(); 900 } 901 902 void OverloadCandidateSet::destroyCandidates() { 903 for (iterator i = begin(), e = end(); i != e; ++i) { 904 for (auto &C : i->Conversions) 905 C.~ImplicitConversionSequence(); 906 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 907 i->DeductionFailure.Destroy(); 908 } 909 } 910 911 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 912 destroyCandidates(); 913 SlabAllocator.Reset(); 914 NumInlineBytesUsed = 0; 915 Candidates.clear(); 916 Functions.clear(); 917 Kind = CSK; 918 } 919 920 namespace { 921 class UnbridgedCastsSet { 922 struct Entry { 923 Expr **Addr; 924 Expr *Saved; 925 }; 926 SmallVector<Entry, 2> Entries; 927 928 public: 929 void save(Sema &S, Expr *&E) { 930 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 931 Entry entry = { &E, E }; 932 Entries.push_back(entry); 933 E = S.stripARCUnbridgedCast(E); 934 } 935 936 void restore() { 937 for (SmallVectorImpl<Entry>::iterator 938 i = Entries.begin(), e = Entries.end(); i != e; ++i) 939 *i->Addr = i->Saved; 940 } 941 }; 942 } 943 944 /// checkPlaceholderForOverload - Do any interesting placeholder-like 945 /// preprocessing on the given expression. 946 /// 947 /// \param unbridgedCasts a collection to which to add unbridged casts; 948 /// without this, they will be immediately diagnosed as errors 949 /// 950 /// Return true on unrecoverable error. 951 static bool 952 checkPlaceholderForOverload(Sema &S, Expr *&E, 953 UnbridgedCastsSet *unbridgedCasts = nullptr) { 954 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 955 // We can't handle overloaded expressions here because overload 956 // resolution might reasonably tweak them. 957 if (placeholder->getKind() == BuiltinType::Overload) return false; 958 959 // If the context potentially accepts unbridged ARC casts, strip 960 // the unbridged cast and add it to the collection for later restoration. 961 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 962 unbridgedCasts) { 963 unbridgedCasts->save(S, E); 964 return false; 965 } 966 967 // Go ahead and check everything else. 968 ExprResult result = S.CheckPlaceholderExpr(E); 969 if (result.isInvalid()) 970 return true; 971 972 E = result.get(); 973 return false; 974 } 975 976 // Nothing to do. 977 return false; 978 } 979 980 /// checkArgPlaceholdersForOverload - Check a set of call operands for 981 /// placeholders. 982 static bool checkArgPlaceholdersForOverload(Sema &S, 983 MultiExprArg Args, 984 UnbridgedCastsSet &unbridged) { 985 for (unsigned i = 0, e = Args.size(); i != e; ++i) 986 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 987 return true; 988 989 return false; 990 } 991 992 /// Determine whether the given New declaration is an overload of the 993 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 994 /// New and Old cannot be overloaded, e.g., if New has the same signature as 995 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 996 /// functions (or function templates) at all. When it does return Ovl_Match or 997 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 998 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 999 /// declaration. 1000 /// 1001 /// Example: Given the following input: 1002 /// 1003 /// void f(int, float); // #1 1004 /// void f(int, int); // #2 1005 /// int f(int, int); // #3 1006 /// 1007 /// When we process #1, there is no previous declaration of "f", so IsOverload 1008 /// will not be used. 1009 /// 1010 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1011 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1012 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1013 /// unchanged. 1014 /// 1015 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1016 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1017 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1018 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1019 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1020 /// 1021 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1022 /// by a using declaration. The rules for whether to hide shadow declarations 1023 /// ignore some properties which otherwise figure into a function template's 1024 /// signature. 1025 Sema::OverloadKind 1026 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1027 NamedDecl *&Match, bool NewIsUsingDecl) { 1028 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1029 I != E; ++I) { 1030 NamedDecl *OldD = *I; 1031 1032 bool OldIsUsingDecl = false; 1033 if (isa<UsingShadowDecl>(OldD)) { 1034 OldIsUsingDecl = true; 1035 1036 // We can always introduce two using declarations into the same 1037 // context, even if they have identical signatures. 1038 if (NewIsUsingDecl) continue; 1039 1040 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1041 } 1042 1043 // A using-declaration does not conflict with another declaration 1044 // if one of them is hidden. 1045 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1046 continue; 1047 1048 // If either declaration was introduced by a using declaration, 1049 // we'll need to use slightly different rules for matching. 1050 // Essentially, these rules are the normal rules, except that 1051 // function templates hide function templates with different 1052 // return types or template parameter lists. 1053 bool UseMemberUsingDeclRules = 1054 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1055 !New->getFriendObjectKind(); 1056 1057 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1058 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1059 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1060 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1061 continue; 1062 } 1063 1064 if (!isa<FunctionTemplateDecl>(OldD) && 1065 !shouldLinkPossiblyHiddenDecl(*I, New)) 1066 continue; 1067 1068 Match = *I; 1069 return Ovl_Match; 1070 } 1071 1072 // Builtins that have custom typechecking or have a reference should 1073 // not be overloadable or redeclarable. 1074 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1075 Match = *I; 1076 return Ovl_NonFunction; 1077 } 1078 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1079 // We can overload with these, which can show up when doing 1080 // redeclaration checks for UsingDecls. 1081 assert(Old.getLookupKind() == LookupUsingDeclName); 1082 } else if (isa<TagDecl>(OldD)) { 1083 // We can always overload with tags by hiding them. 1084 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1085 // Optimistically assume that an unresolved using decl will 1086 // overload; if it doesn't, we'll have to diagnose during 1087 // template instantiation. 1088 // 1089 // Exception: if the scope is dependent and this is not a class 1090 // member, the using declaration can only introduce an enumerator. 1091 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1092 Match = *I; 1093 return Ovl_NonFunction; 1094 } 1095 } else { 1096 // (C++ 13p1): 1097 // Only function declarations can be overloaded; object and type 1098 // declarations cannot be overloaded. 1099 Match = *I; 1100 return Ovl_NonFunction; 1101 } 1102 } 1103 1104 // C++ [temp.friend]p1: 1105 // For a friend function declaration that is not a template declaration: 1106 // -- if the name of the friend is a qualified or unqualified template-id, 1107 // [...], otherwise 1108 // -- if the name of the friend is a qualified-id and a matching 1109 // non-template function is found in the specified class or namespace, 1110 // the friend declaration refers to that function, otherwise, 1111 // -- if the name of the friend is a qualified-id and a matching function 1112 // template is found in the specified class or namespace, the friend 1113 // declaration refers to the deduced specialization of that function 1114 // template, otherwise 1115 // -- the name shall be an unqualified-id [...] 1116 // If we get here for a qualified friend declaration, we've just reached the 1117 // third bullet. If the type of the friend is dependent, skip this lookup 1118 // until instantiation. 1119 if (New->getFriendObjectKind() && New->getQualifier() && 1120 !New->getDescribedFunctionTemplate() && 1121 !New->getDependentSpecializationInfo() && 1122 !New->getType()->isDependentType()) { 1123 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1124 TemplateSpecResult.addAllDecls(Old); 1125 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1126 /*QualifiedFriend*/true)) { 1127 New->setInvalidDecl(); 1128 return Ovl_Overload; 1129 } 1130 1131 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1132 return Ovl_Match; 1133 } 1134 1135 return Ovl_Overload; 1136 } 1137 1138 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1139 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1140 bool ConsiderRequiresClauses) { 1141 // C++ [basic.start.main]p2: This function shall not be overloaded. 1142 if (New->isMain()) 1143 return false; 1144 1145 // MSVCRT user defined entry points cannot be overloaded. 1146 if (New->isMSVCRTEntryPoint()) 1147 return false; 1148 1149 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1150 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1151 1152 // C++ [temp.fct]p2: 1153 // A function template can be overloaded with other function templates 1154 // and with normal (non-template) functions. 1155 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1156 return true; 1157 1158 // Is the function New an overload of the function Old? 1159 QualType OldQType = Context.getCanonicalType(Old->getType()); 1160 QualType NewQType = Context.getCanonicalType(New->getType()); 1161 1162 // Compare the signatures (C++ 1.3.10) of the two functions to 1163 // determine whether they are overloads. If we find any mismatch 1164 // in the signature, they are overloads. 1165 1166 // If either of these functions is a K&R-style function (no 1167 // prototype), then we consider them to have matching signatures. 1168 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1169 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1170 return false; 1171 1172 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1173 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1174 1175 // The signature of a function includes the types of its 1176 // parameters (C++ 1.3.10), which includes the presence or absence 1177 // of the ellipsis; see C++ DR 357). 1178 if (OldQType != NewQType && 1179 (OldType->getNumParams() != NewType->getNumParams() || 1180 OldType->isVariadic() != NewType->isVariadic() || 1181 !FunctionParamTypesAreEqual(OldType, NewType))) 1182 return true; 1183 1184 // C++ [temp.over.link]p4: 1185 // The signature of a function template consists of its function 1186 // signature, its return type and its template parameter list. The names 1187 // of the template parameters are significant only for establishing the 1188 // relationship between the template parameters and the rest of the 1189 // signature. 1190 // 1191 // We check the return type and template parameter lists for function 1192 // templates first; the remaining checks follow. 1193 // 1194 // However, we don't consider either of these when deciding whether 1195 // a member introduced by a shadow declaration is hidden. 1196 if (!UseMemberUsingDeclRules && NewTemplate && 1197 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1198 OldTemplate->getTemplateParameters(), 1199 false, TPL_TemplateMatch) || 1200 !Context.hasSameType(Old->getDeclaredReturnType(), 1201 New->getDeclaredReturnType()))) 1202 return true; 1203 1204 // If the function is a class member, its signature includes the 1205 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1206 // 1207 // As part of this, also check whether one of the member functions 1208 // is static, in which case they are not overloads (C++ 1209 // 13.1p2). While not part of the definition of the signature, 1210 // this check is important to determine whether these functions 1211 // can be overloaded. 1212 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1213 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1214 if (OldMethod && NewMethod && 1215 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1216 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1217 if (!UseMemberUsingDeclRules && 1218 (OldMethod->getRefQualifier() == RQ_None || 1219 NewMethod->getRefQualifier() == RQ_None)) { 1220 // C++0x [over.load]p2: 1221 // - Member function declarations with the same name and the same 1222 // parameter-type-list as well as member function template 1223 // declarations with the same name, the same parameter-type-list, and 1224 // the same template parameter lists cannot be overloaded if any of 1225 // them, but not all, have a ref-qualifier (8.3.5). 1226 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1227 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1228 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1229 } 1230 return true; 1231 } 1232 1233 // We may not have applied the implicit const for a constexpr member 1234 // function yet (because we haven't yet resolved whether this is a static 1235 // or non-static member function). Add it now, on the assumption that this 1236 // is a redeclaration of OldMethod. 1237 auto OldQuals = OldMethod->getMethodQualifiers(); 1238 auto NewQuals = NewMethod->getMethodQualifiers(); 1239 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1240 !isa<CXXConstructorDecl>(NewMethod)) 1241 NewQuals.addConst(); 1242 // We do not allow overloading based off of '__restrict'. 1243 OldQuals.removeRestrict(); 1244 NewQuals.removeRestrict(); 1245 if (OldQuals != NewQuals) 1246 return true; 1247 } 1248 1249 // Though pass_object_size is placed on parameters and takes an argument, we 1250 // consider it to be a function-level modifier for the sake of function 1251 // identity. Either the function has one or more parameters with 1252 // pass_object_size or it doesn't. 1253 if (functionHasPassObjectSizeParams(New) != 1254 functionHasPassObjectSizeParams(Old)) 1255 return true; 1256 1257 // enable_if attributes are an order-sensitive part of the signature. 1258 for (specific_attr_iterator<EnableIfAttr> 1259 NewI = New->specific_attr_begin<EnableIfAttr>(), 1260 NewE = New->specific_attr_end<EnableIfAttr>(), 1261 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1262 OldE = Old->specific_attr_end<EnableIfAttr>(); 1263 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1264 if (NewI == NewE || OldI == OldE) 1265 return true; 1266 llvm::FoldingSetNodeID NewID, OldID; 1267 NewI->getCond()->Profile(NewID, Context, true); 1268 OldI->getCond()->Profile(OldID, Context, true); 1269 if (NewID != OldID) 1270 return true; 1271 } 1272 1273 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1274 // Don't allow overloading of destructors. (In theory we could, but it 1275 // would be a giant change to clang.) 1276 if (!isa<CXXDestructorDecl>(New)) { 1277 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1278 OldTarget = IdentifyCUDATarget(Old); 1279 if (NewTarget != CFT_InvalidTarget) { 1280 assert((OldTarget != CFT_InvalidTarget) && 1281 "Unexpected invalid target."); 1282 1283 // Allow overloading of functions with same signature and different CUDA 1284 // target attributes. 1285 if (NewTarget != OldTarget) 1286 return true; 1287 } 1288 } 1289 } 1290 1291 if (ConsiderRequiresClauses) { 1292 Expr *NewRC = New->getTrailingRequiresClause(), 1293 *OldRC = Old->getTrailingRequiresClause(); 1294 if ((NewRC != nullptr) != (OldRC != nullptr)) 1295 // RC are most certainly different - these are overloads. 1296 return true; 1297 1298 if (NewRC) { 1299 llvm::FoldingSetNodeID NewID, OldID; 1300 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1301 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1302 if (NewID != OldID) 1303 // RCs are not equivalent - these are overloads. 1304 return true; 1305 } 1306 } 1307 1308 // The signatures match; this is not an overload. 1309 return false; 1310 } 1311 1312 /// Tries a user-defined conversion from From to ToType. 1313 /// 1314 /// Produces an implicit conversion sequence for when a standard conversion 1315 /// is not an option. See TryImplicitConversion for more information. 1316 static ImplicitConversionSequence 1317 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1318 bool SuppressUserConversions, 1319 AllowedExplicit AllowExplicit, 1320 bool InOverloadResolution, 1321 bool CStyle, 1322 bool AllowObjCWritebackConversion, 1323 bool AllowObjCConversionOnExplicit) { 1324 ImplicitConversionSequence ICS; 1325 1326 if (SuppressUserConversions) { 1327 // We're not in the case above, so there is no conversion that 1328 // we can perform. 1329 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1330 return ICS; 1331 } 1332 1333 // Attempt user-defined conversion. 1334 OverloadCandidateSet Conversions(From->getExprLoc(), 1335 OverloadCandidateSet::CSK_Normal); 1336 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1337 Conversions, AllowExplicit, 1338 AllowObjCConversionOnExplicit)) { 1339 case OR_Success: 1340 case OR_Deleted: 1341 ICS.setUserDefined(); 1342 // C++ [over.ics.user]p4: 1343 // A conversion of an expression of class type to the same class 1344 // type is given Exact Match rank, and a conversion of an 1345 // expression of class type to a base class of that type is 1346 // given Conversion rank, in spite of the fact that a copy 1347 // constructor (i.e., a user-defined conversion function) is 1348 // called for those cases. 1349 if (CXXConstructorDecl *Constructor 1350 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1351 QualType FromCanon 1352 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1353 QualType ToCanon 1354 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1355 if (Constructor->isCopyConstructor() && 1356 (FromCanon == ToCanon || 1357 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1358 // Turn this into a "standard" conversion sequence, so that it 1359 // gets ranked with standard conversion sequences. 1360 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1361 ICS.setStandard(); 1362 ICS.Standard.setAsIdentityConversion(); 1363 ICS.Standard.setFromType(From->getType()); 1364 ICS.Standard.setAllToTypes(ToType); 1365 ICS.Standard.CopyConstructor = Constructor; 1366 ICS.Standard.FoundCopyConstructor = Found; 1367 if (ToCanon != FromCanon) 1368 ICS.Standard.Second = ICK_Derived_To_Base; 1369 } 1370 } 1371 break; 1372 1373 case OR_Ambiguous: 1374 ICS.setAmbiguous(); 1375 ICS.Ambiguous.setFromType(From->getType()); 1376 ICS.Ambiguous.setToType(ToType); 1377 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1378 Cand != Conversions.end(); ++Cand) 1379 if (Cand->Best) 1380 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1381 break; 1382 1383 // Fall through. 1384 case OR_No_Viable_Function: 1385 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1386 break; 1387 } 1388 1389 return ICS; 1390 } 1391 1392 /// TryImplicitConversion - Attempt to perform an implicit conversion 1393 /// from the given expression (Expr) to the given type (ToType). This 1394 /// function returns an implicit conversion sequence that can be used 1395 /// to perform the initialization. Given 1396 /// 1397 /// void f(float f); 1398 /// void g(int i) { f(i); } 1399 /// 1400 /// this routine would produce an implicit conversion sequence to 1401 /// describe the initialization of f from i, which will be a standard 1402 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1403 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1404 // 1405 /// Note that this routine only determines how the conversion can be 1406 /// performed; it does not actually perform the conversion. As such, 1407 /// it will not produce any diagnostics if no conversion is available, 1408 /// but will instead return an implicit conversion sequence of kind 1409 /// "BadConversion". 1410 /// 1411 /// If @p SuppressUserConversions, then user-defined conversions are 1412 /// not permitted. 1413 /// If @p AllowExplicit, then explicit user-defined conversions are 1414 /// permitted. 1415 /// 1416 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1417 /// writeback conversion, which allows __autoreleasing id* parameters to 1418 /// be initialized with __strong id* or __weak id* arguments. 1419 static ImplicitConversionSequence 1420 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1421 bool SuppressUserConversions, 1422 AllowedExplicit AllowExplicit, 1423 bool InOverloadResolution, 1424 bool CStyle, 1425 bool AllowObjCWritebackConversion, 1426 bool AllowObjCConversionOnExplicit) { 1427 ImplicitConversionSequence ICS; 1428 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1429 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1430 ICS.setStandard(); 1431 return ICS; 1432 } 1433 1434 if (!S.getLangOpts().CPlusPlus) { 1435 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1436 return ICS; 1437 } 1438 1439 // C++ [over.ics.user]p4: 1440 // A conversion of an expression of class type to the same class 1441 // type is given Exact Match rank, and a conversion of an 1442 // expression of class type to a base class of that type is 1443 // given Conversion rank, in spite of the fact that a copy/move 1444 // constructor (i.e., a user-defined conversion function) is 1445 // called for those cases. 1446 QualType FromType = From->getType(); 1447 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1448 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1449 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1450 ICS.setStandard(); 1451 ICS.Standard.setAsIdentityConversion(); 1452 ICS.Standard.setFromType(FromType); 1453 ICS.Standard.setAllToTypes(ToType); 1454 1455 // We don't actually check at this point whether there is a valid 1456 // copy/move constructor, since overloading just assumes that it 1457 // exists. When we actually perform initialization, we'll find the 1458 // appropriate constructor to copy the returned object, if needed. 1459 ICS.Standard.CopyConstructor = nullptr; 1460 1461 // Determine whether this is considered a derived-to-base conversion. 1462 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1463 ICS.Standard.Second = ICK_Derived_To_Base; 1464 1465 return ICS; 1466 } 1467 1468 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1469 AllowExplicit, InOverloadResolution, CStyle, 1470 AllowObjCWritebackConversion, 1471 AllowObjCConversionOnExplicit); 1472 } 1473 1474 ImplicitConversionSequence 1475 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1476 bool SuppressUserConversions, 1477 AllowedExplicit AllowExplicit, 1478 bool InOverloadResolution, 1479 bool CStyle, 1480 bool AllowObjCWritebackConversion) { 1481 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1482 AllowExplicit, InOverloadResolution, CStyle, 1483 AllowObjCWritebackConversion, 1484 /*AllowObjCConversionOnExplicit=*/false); 1485 } 1486 1487 /// PerformImplicitConversion - Perform an implicit conversion of the 1488 /// expression From to the type ToType. Returns the 1489 /// converted expression. Flavor is the kind of conversion we're 1490 /// performing, used in the error message. If @p AllowExplicit, 1491 /// explicit user-defined conversions are permitted. 1492 ExprResult 1493 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1494 AssignmentAction Action, bool AllowExplicit) { 1495 ImplicitConversionSequence ICS; 1496 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1497 } 1498 1499 ExprResult 1500 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1501 AssignmentAction Action, bool AllowExplicit, 1502 ImplicitConversionSequence& ICS) { 1503 if (checkPlaceholderForOverload(*this, From)) 1504 return ExprError(); 1505 1506 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1507 bool AllowObjCWritebackConversion 1508 = getLangOpts().ObjCAutoRefCount && 1509 (Action == AA_Passing || Action == AA_Sending); 1510 if (getLangOpts().ObjC) 1511 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1512 From->getType(), From); 1513 ICS = ::TryImplicitConversion(*this, From, ToType, 1514 /*SuppressUserConversions=*/false, 1515 AllowExplicit ? AllowedExplicit::All 1516 : AllowedExplicit::None, 1517 /*InOverloadResolution=*/false, 1518 /*CStyle=*/false, AllowObjCWritebackConversion, 1519 /*AllowObjCConversionOnExplicit=*/false); 1520 return PerformImplicitConversion(From, ToType, ICS, Action); 1521 } 1522 1523 /// Determine whether the conversion from FromType to ToType is a valid 1524 /// conversion that strips "noexcept" or "noreturn" off the nested function 1525 /// type. 1526 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1527 QualType &ResultTy) { 1528 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1529 return false; 1530 1531 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1532 // or F(t noexcept) -> F(t) 1533 // where F adds one of the following at most once: 1534 // - a pointer 1535 // - a member pointer 1536 // - a block pointer 1537 // Changes here need matching changes in FindCompositePointerType. 1538 CanQualType CanTo = Context.getCanonicalType(ToType); 1539 CanQualType CanFrom = Context.getCanonicalType(FromType); 1540 Type::TypeClass TyClass = CanTo->getTypeClass(); 1541 if (TyClass != CanFrom->getTypeClass()) return false; 1542 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1543 if (TyClass == Type::Pointer) { 1544 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1545 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1546 } else if (TyClass == Type::BlockPointer) { 1547 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1548 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1549 } else if (TyClass == Type::MemberPointer) { 1550 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1551 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1552 // A function pointer conversion cannot change the class of the function. 1553 if (ToMPT->getClass() != FromMPT->getClass()) 1554 return false; 1555 CanTo = ToMPT->getPointeeType(); 1556 CanFrom = FromMPT->getPointeeType(); 1557 } else { 1558 return false; 1559 } 1560 1561 TyClass = CanTo->getTypeClass(); 1562 if (TyClass != CanFrom->getTypeClass()) return false; 1563 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1564 return false; 1565 } 1566 1567 const auto *FromFn = cast<FunctionType>(CanFrom); 1568 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1569 1570 const auto *ToFn = cast<FunctionType>(CanTo); 1571 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1572 1573 bool Changed = false; 1574 1575 // Drop 'noreturn' if not present in target type. 1576 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1577 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1578 Changed = true; 1579 } 1580 1581 // Drop 'noexcept' if not present in target type. 1582 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1583 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1584 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1585 FromFn = cast<FunctionType>( 1586 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1587 EST_None) 1588 .getTypePtr()); 1589 Changed = true; 1590 } 1591 1592 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1593 // only if the ExtParameterInfo lists of the two function prototypes can be 1594 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1595 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1596 bool CanUseToFPT, CanUseFromFPT; 1597 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1598 CanUseFromFPT, NewParamInfos) && 1599 CanUseToFPT && !CanUseFromFPT) { 1600 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1601 ExtInfo.ExtParameterInfos = 1602 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1603 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1604 FromFPT->getParamTypes(), ExtInfo); 1605 FromFn = QT->getAs<FunctionType>(); 1606 Changed = true; 1607 } 1608 } 1609 1610 if (!Changed) 1611 return false; 1612 1613 assert(QualType(FromFn, 0).isCanonical()); 1614 if (QualType(FromFn, 0) != CanTo) return false; 1615 1616 ResultTy = ToType; 1617 return true; 1618 } 1619 1620 /// Determine whether the conversion from FromType to ToType is a valid 1621 /// vector conversion. 1622 /// 1623 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1624 /// conversion. 1625 static bool IsVectorConversion(Sema &S, QualType FromType, 1626 QualType ToType, ImplicitConversionKind &ICK) { 1627 // We need at least one of these types to be a vector type to have a vector 1628 // conversion. 1629 if (!ToType->isVectorType() && !FromType->isVectorType()) 1630 return false; 1631 1632 // Identical types require no conversions. 1633 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1634 return false; 1635 1636 // There are no conversions between extended vector types, only identity. 1637 if (ToType->isExtVectorType()) { 1638 // There are no conversions between extended vector types other than the 1639 // identity conversion. 1640 if (FromType->isExtVectorType()) 1641 return false; 1642 1643 // Vector splat from any arithmetic type to a vector. 1644 if (FromType->isArithmeticType()) { 1645 ICK = ICK_Vector_Splat; 1646 return true; 1647 } 1648 } 1649 1650 // We can perform the conversion between vector types in the following cases: 1651 // 1)vector types are equivalent AltiVec and GCC vector types 1652 // 2)lax vector conversions are permitted and the vector types are of the 1653 // same size 1654 // 3)the destination type does not have the ARM MVE strict-polymorphism 1655 // attribute, which inhibits lax vector conversion for overload resolution 1656 // only 1657 if (ToType->isVectorType() && FromType->isVectorType()) { 1658 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1659 (S.isLaxVectorConversion(FromType, ToType) && 1660 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1661 ICK = ICK_Vector_Conversion; 1662 return true; 1663 } 1664 } 1665 1666 return false; 1667 } 1668 1669 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1670 bool InOverloadResolution, 1671 StandardConversionSequence &SCS, 1672 bool CStyle); 1673 1674 /// IsStandardConversion - Determines whether there is a standard 1675 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1676 /// expression From to the type ToType. Standard conversion sequences 1677 /// only consider non-class types; for conversions that involve class 1678 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1679 /// contain the standard conversion sequence required to perform this 1680 /// conversion and this routine will return true. Otherwise, this 1681 /// routine will return false and the value of SCS is unspecified. 1682 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1683 bool InOverloadResolution, 1684 StandardConversionSequence &SCS, 1685 bool CStyle, 1686 bool AllowObjCWritebackConversion) { 1687 QualType FromType = From->getType(); 1688 1689 // Standard conversions (C++ [conv]) 1690 SCS.setAsIdentityConversion(); 1691 SCS.IncompatibleObjC = false; 1692 SCS.setFromType(FromType); 1693 SCS.CopyConstructor = nullptr; 1694 1695 // There are no standard conversions for class types in C++, so 1696 // abort early. When overloading in C, however, we do permit them. 1697 if (S.getLangOpts().CPlusPlus && 1698 (FromType->isRecordType() || ToType->isRecordType())) 1699 return false; 1700 1701 // The first conversion can be an lvalue-to-rvalue conversion, 1702 // array-to-pointer conversion, or function-to-pointer conversion 1703 // (C++ 4p1). 1704 1705 if (FromType == S.Context.OverloadTy) { 1706 DeclAccessPair AccessPair; 1707 if (FunctionDecl *Fn 1708 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1709 AccessPair)) { 1710 // We were able to resolve the address of the overloaded function, 1711 // so we can convert to the type of that function. 1712 FromType = Fn->getType(); 1713 SCS.setFromType(FromType); 1714 1715 // we can sometimes resolve &foo<int> regardless of ToType, so check 1716 // if the type matches (identity) or we are converting to bool 1717 if (!S.Context.hasSameUnqualifiedType( 1718 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1719 QualType resultTy; 1720 // if the function type matches except for [[noreturn]], it's ok 1721 if (!S.IsFunctionConversion(FromType, 1722 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1723 // otherwise, only a boolean conversion is standard 1724 if (!ToType->isBooleanType()) 1725 return false; 1726 } 1727 1728 // Check if the "from" expression is taking the address of an overloaded 1729 // function and recompute the FromType accordingly. Take advantage of the 1730 // fact that non-static member functions *must* have such an address-of 1731 // expression. 1732 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1733 if (Method && !Method->isStatic()) { 1734 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1735 "Non-unary operator on non-static member address"); 1736 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1737 == UO_AddrOf && 1738 "Non-address-of operator on non-static member address"); 1739 const Type *ClassType 1740 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1741 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1742 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1743 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1744 UO_AddrOf && 1745 "Non-address-of operator for overloaded function expression"); 1746 FromType = S.Context.getPointerType(FromType); 1747 } 1748 1749 // Check that we've computed the proper type after overload resolution. 1750 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1751 // be calling it from within an NDEBUG block. 1752 assert(S.Context.hasSameType( 1753 FromType, 1754 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1755 } else { 1756 return false; 1757 } 1758 } 1759 // Lvalue-to-rvalue conversion (C++11 4.1): 1760 // A glvalue (3.10) of a non-function, non-array type T can 1761 // be converted to a prvalue. 1762 bool argIsLValue = From->isGLValue(); 1763 if (argIsLValue && 1764 !FromType->isFunctionType() && !FromType->isArrayType() && 1765 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1766 SCS.First = ICK_Lvalue_To_Rvalue; 1767 1768 // C11 6.3.2.1p2: 1769 // ... if the lvalue has atomic type, the value has the non-atomic version 1770 // of the type of the lvalue ... 1771 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1772 FromType = Atomic->getValueType(); 1773 1774 // If T is a non-class type, the type of the rvalue is the 1775 // cv-unqualified version of T. Otherwise, the type of the rvalue 1776 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1777 // just strip the qualifiers because they don't matter. 1778 FromType = FromType.getUnqualifiedType(); 1779 } else if (FromType->isArrayType()) { 1780 // Array-to-pointer conversion (C++ 4.2) 1781 SCS.First = ICK_Array_To_Pointer; 1782 1783 // An lvalue or rvalue of type "array of N T" or "array of unknown 1784 // bound of T" can be converted to an rvalue of type "pointer to 1785 // T" (C++ 4.2p1). 1786 FromType = S.Context.getArrayDecayedType(FromType); 1787 1788 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1789 // This conversion is deprecated in C++03 (D.4) 1790 SCS.DeprecatedStringLiteralToCharPtr = true; 1791 1792 // For the purpose of ranking in overload resolution 1793 // (13.3.3.1.1), this conversion is considered an 1794 // array-to-pointer conversion followed by a qualification 1795 // conversion (4.4). (C++ 4.2p2) 1796 SCS.Second = ICK_Identity; 1797 SCS.Third = ICK_Qualification; 1798 SCS.QualificationIncludesObjCLifetime = false; 1799 SCS.setAllToTypes(FromType); 1800 return true; 1801 } 1802 } else if (FromType->isFunctionType() && argIsLValue) { 1803 // Function-to-pointer conversion (C++ 4.3). 1804 SCS.First = ICK_Function_To_Pointer; 1805 1806 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1807 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1808 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1809 return false; 1810 1811 // An lvalue of function type T can be converted to an rvalue of 1812 // type "pointer to T." The result is a pointer to the 1813 // function. (C++ 4.3p1). 1814 FromType = S.Context.getPointerType(FromType); 1815 } else { 1816 // We don't require any conversions for the first step. 1817 SCS.First = ICK_Identity; 1818 } 1819 SCS.setToType(0, FromType); 1820 1821 // The second conversion can be an integral promotion, floating 1822 // point promotion, integral conversion, floating point conversion, 1823 // floating-integral conversion, pointer conversion, 1824 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1825 // For overloading in C, this can also be a "compatible-type" 1826 // conversion. 1827 bool IncompatibleObjC = false; 1828 ImplicitConversionKind SecondICK = ICK_Identity; 1829 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1830 // The unqualified versions of the types are the same: there's no 1831 // conversion to do. 1832 SCS.Second = ICK_Identity; 1833 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1834 // Integral promotion (C++ 4.5). 1835 SCS.Second = ICK_Integral_Promotion; 1836 FromType = ToType.getUnqualifiedType(); 1837 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1838 // Floating point promotion (C++ 4.6). 1839 SCS.Second = ICK_Floating_Promotion; 1840 FromType = ToType.getUnqualifiedType(); 1841 } else if (S.IsComplexPromotion(FromType, ToType)) { 1842 // Complex promotion (Clang extension) 1843 SCS.Second = ICK_Complex_Promotion; 1844 FromType = ToType.getUnqualifiedType(); 1845 } else if (ToType->isBooleanType() && 1846 (FromType->isArithmeticType() || 1847 FromType->isAnyPointerType() || 1848 FromType->isBlockPointerType() || 1849 FromType->isMemberPointerType())) { 1850 // Boolean conversions (C++ 4.12). 1851 SCS.Second = ICK_Boolean_Conversion; 1852 FromType = S.Context.BoolTy; 1853 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1854 ToType->isIntegralType(S.Context)) { 1855 // Integral conversions (C++ 4.7). 1856 SCS.Second = ICK_Integral_Conversion; 1857 FromType = ToType.getUnqualifiedType(); 1858 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1859 // Complex conversions (C99 6.3.1.6) 1860 SCS.Second = ICK_Complex_Conversion; 1861 FromType = ToType.getUnqualifiedType(); 1862 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1863 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1864 // Complex-real conversions (C99 6.3.1.7) 1865 SCS.Second = ICK_Complex_Real; 1866 FromType = ToType.getUnqualifiedType(); 1867 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1868 // FIXME: disable conversions between long double and __float128 if 1869 // their representation is different until there is back end support 1870 // We of course allow this conversion if long double is really double. 1871 if (&S.Context.getFloatTypeSemantics(FromType) != 1872 &S.Context.getFloatTypeSemantics(ToType)) { 1873 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1874 ToType == S.Context.LongDoubleTy) || 1875 (FromType == S.Context.LongDoubleTy && 1876 ToType == S.Context.Float128Ty)); 1877 if (Float128AndLongDouble && 1878 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1879 &llvm::APFloat::PPCDoubleDouble())) 1880 return false; 1881 } 1882 // Floating point conversions (C++ 4.8). 1883 SCS.Second = ICK_Floating_Conversion; 1884 FromType = ToType.getUnqualifiedType(); 1885 } else if ((FromType->isRealFloatingType() && 1886 ToType->isIntegralType(S.Context)) || 1887 (FromType->isIntegralOrUnscopedEnumerationType() && 1888 ToType->isRealFloatingType())) { 1889 // Floating-integral conversions (C++ 4.9). 1890 SCS.Second = ICK_Floating_Integral; 1891 FromType = ToType.getUnqualifiedType(); 1892 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1893 SCS.Second = ICK_Block_Pointer_Conversion; 1894 } else if (AllowObjCWritebackConversion && 1895 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1896 SCS.Second = ICK_Writeback_Conversion; 1897 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1898 FromType, IncompatibleObjC)) { 1899 // Pointer conversions (C++ 4.10). 1900 SCS.Second = ICK_Pointer_Conversion; 1901 SCS.IncompatibleObjC = IncompatibleObjC; 1902 FromType = FromType.getUnqualifiedType(); 1903 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1904 InOverloadResolution, FromType)) { 1905 // Pointer to member conversions (4.11). 1906 SCS.Second = ICK_Pointer_Member; 1907 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1908 SCS.Second = SecondICK; 1909 FromType = ToType.getUnqualifiedType(); 1910 } else if (!S.getLangOpts().CPlusPlus && 1911 S.Context.typesAreCompatible(ToType, FromType)) { 1912 // Compatible conversions (Clang extension for C function overloading) 1913 SCS.Second = ICK_Compatible_Conversion; 1914 FromType = ToType.getUnqualifiedType(); 1915 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1916 InOverloadResolution, 1917 SCS, CStyle)) { 1918 SCS.Second = ICK_TransparentUnionConversion; 1919 FromType = ToType; 1920 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1921 CStyle)) { 1922 // tryAtomicConversion has updated the standard conversion sequence 1923 // appropriately. 1924 return true; 1925 } else if (ToType->isEventT() && 1926 From->isIntegerConstantExpr(S.getASTContext()) && 1927 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1928 SCS.Second = ICK_Zero_Event_Conversion; 1929 FromType = ToType; 1930 } else if (ToType->isQueueT() && 1931 From->isIntegerConstantExpr(S.getASTContext()) && 1932 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1933 SCS.Second = ICK_Zero_Queue_Conversion; 1934 FromType = ToType; 1935 } else if (ToType->isSamplerT() && 1936 From->isIntegerConstantExpr(S.getASTContext())) { 1937 SCS.Second = ICK_Compatible_Conversion; 1938 FromType = ToType; 1939 } else { 1940 // No second conversion required. 1941 SCS.Second = ICK_Identity; 1942 } 1943 SCS.setToType(1, FromType); 1944 1945 // The third conversion can be a function pointer conversion or a 1946 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1947 bool ObjCLifetimeConversion; 1948 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1949 // Function pointer conversions (removing 'noexcept') including removal of 1950 // 'noreturn' (Clang extension). 1951 SCS.Third = ICK_Function_Conversion; 1952 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1953 ObjCLifetimeConversion)) { 1954 SCS.Third = ICK_Qualification; 1955 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1956 FromType = ToType; 1957 } else { 1958 // No conversion required 1959 SCS.Third = ICK_Identity; 1960 } 1961 1962 // C++ [over.best.ics]p6: 1963 // [...] Any difference in top-level cv-qualification is 1964 // subsumed by the initialization itself and does not constitute 1965 // a conversion. [...] 1966 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1967 QualType CanonTo = S.Context.getCanonicalType(ToType); 1968 if (CanonFrom.getLocalUnqualifiedType() 1969 == CanonTo.getLocalUnqualifiedType() && 1970 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1971 FromType = ToType; 1972 CanonFrom = CanonTo; 1973 } 1974 1975 SCS.setToType(2, FromType); 1976 1977 if (CanonFrom == CanonTo) 1978 return true; 1979 1980 // If we have not converted the argument type to the parameter type, 1981 // this is a bad conversion sequence, unless we're resolving an overload in C. 1982 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1983 return false; 1984 1985 ExprResult ER = ExprResult{From}; 1986 Sema::AssignConvertType Conv = 1987 S.CheckSingleAssignmentConstraints(ToType, ER, 1988 /*Diagnose=*/false, 1989 /*DiagnoseCFAudited=*/false, 1990 /*ConvertRHS=*/false); 1991 ImplicitConversionKind SecondConv; 1992 switch (Conv) { 1993 case Sema::Compatible: 1994 SecondConv = ICK_C_Only_Conversion; 1995 break; 1996 // For our purposes, discarding qualifiers is just as bad as using an 1997 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1998 // qualifiers, as well. 1999 case Sema::CompatiblePointerDiscardsQualifiers: 2000 case Sema::IncompatiblePointer: 2001 case Sema::IncompatiblePointerSign: 2002 SecondConv = ICK_Incompatible_Pointer_Conversion; 2003 break; 2004 default: 2005 return false; 2006 } 2007 2008 // First can only be an lvalue conversion, so we pretend that this was the 2009 // second conversion. First should already be valid from earlier in the 2010 // function. 2011 SCS.Second = SecondConv; 2012 SCS.setToType(1, ToType); 2013 2014 // Third is Identity, because Second should rank us worse than any other 2015 // conversion. This could also be ICK_Qualification, but it's simpler to just 2016 // lump everything in with the second conversion, and we don't gain anything 2017 // from making this ICK_Qualification. 2018 SCS.Third = ICK_Identity; 2019 SCS.setToType(2, ToType); 2020 return true; 2021 } 2022 2023 static bool 2024 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2025 QualType &ToType, 2026 bool InOverloadResolution, 2027 StandardConversionSequence &SCS, 2028 bool CStyle) { 2029 2030 const RecordType *UT = ToType->getAsUnionType(); 2031 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2032 return false; 2033 // The field to initialize within the transparent union. 2034 RecordDecl *UD = UT->getDecl(); 2035 // It's compatible if the expression matches any of the fields. 2036 for (const auto *it : UD->fields()) { 2037 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2038 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2039 ToType = it->getType(); 2040 return true; 2041 } 2042 } 2043 return false; 2044 } 2045 2046 /// IsIntegralPromotion - Determines whether the conversion from the 2047 /// expression From (whose potentially-adjusted type is FromType) to 2048 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2049 /// sets PromotedType to the promoted type. 2050 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2051 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2052 // All integers are built-in. 2053 if (!To) { 2054 return false; 2055 } 2056 2057 // An rvalue of type char, signed char, unsigned char, short int, or 2058 // unsigned short int can be converted to an rvalue of type int if 2059 // int can represent all the values of the source type; otherwise, 2060 // the source rvalue can be converted to an rvalue of type unsigned 2061 // int (C++ 4.5p1). 2062 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2063 !FromType->isEnumeralType()) { 2064 if (// We can promote any signed, promotable integer type to an int 2065 (FromType->isSignedIntegerType() || 2066 // We can promote any unsigned integer type whose size is 2067 // less than int to an int. 2068 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2069 return To->getKind() == BuiltinType::Int; 2070 } 2071 2072 return To->getKind() == BuiltinType::UInt; 2073 } 2074 2075 // C++11 [conv.prom]p3: 2076 // A prvalue of an unscoped enumeration type whose underlying type is not 2077 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2078 // following types that can represent all the values of the enumeration 2079 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2080 // unsigned int, long int, unsigned long int, long long int, or unsigned 2081 // long long int. If none of the types in that list can represent all the 2082 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2083 // type can be converted to an rvalue a prvalue of the extended integer type 2084 // with lowest integer conversion rank (4.13) greater than the rank of long 2085 // long in which all the values of the enumeration can be represented. If 2086 // there are two such extended types, the signed one is chosen. 2087 // C++11 [conv.prom]p4: 2088 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2089 // can be converted to a prvalue of its underlying type. Moreover, if 2090 // integral promotion can be applied to its underlying type, a prvalue of an 2091 // unscoped enumeration type whose underlying type is fixed can also be 2092 // converted to a prvalue of the promoted underlying type. 2093 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2094 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2095 // provided for a scoped enumeration. 2096 if (FromEnumType->getDecl()->isScoped()) 2097 return false; 2098 2099 // We can perform an integral promotion to the underlying type of the enum, 2100 // even if that's not the promoted type. Note that the check for promoting 2101 // the underlying type is based on the type alone, and does not consider 2102 // the bitfield-ness of the actual source expression. 2103 if (FromEnumType->getDecl()->isFixed()) { 2104 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2105 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2106 IsIntegralPromotion(nullptr, Underlying, ToType); 2107 } 2108 2109 // We have already pre-calculated the promotion type, so this is trivial. 2110 if (ToType->isIntegerType() && 2111 isCompleteType(From->getBeginLoc(), FromType)) 2112 return Context.hasSameUnqualifiedType( 2113 ToType, FromEnumType->getDecl()->getPromotionType()); 2114 2115 // C++ [conv.prom]p5: 2116 // If the bit-field has an enumerated type, it is treated as any other 2117 // value of that type for promotion purposes. 2118 // 2119 // ... so do not fall through into the bit-field checks below in C++. 2120 if (getLangOpts().CPlusPlus) 2121 return false; 2122 } 2123 2124 // C++0x [conv.prom]p2: 2125 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2126 // to an rvalue a prvalue of the first of the following types that can 2127 // represent all the values of its underlying type: int, unsigned int, 2128 // long int, unsigned long int, long long int, or unsigned long long int. 2129 // If none of the types in that list can represent all the values of its 2130 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2131 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2132 // type. 2133 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2134 ToType->isIntegerType()) { 2135 // Determine whether the type we're converting from is signed or 2136 // unsigned. 2137 bool FromIsSigned = FromType->isSignedIntegerType(); 2138 uint64_t FromSize = Context.getTypeSize(FromType); 2139 2140 // The types we'll try to promote to, in the appropriate 2141 // order. Try each of these types. 2142 QualType PromoteTypes[6] = { 2143 Context.IntTy, Context.UnsignedIntTy, 2144 Context.LongTy, Context.UnsignedLongTy , 2145 Context.LongLongTy, Context.UnsignedLongLongTy 2146 }; 2147 for (int Idx = 0; Idx < 6; ++Idx) { 2148 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2149 if (FromSize < ToSize || 2150 (FromSize == ToSize && 2151 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2152 // We found the type that we can promote to. If this is the 2153 // type we wanted, we have a promotion. Otherwise, no 2154 // promotion. 2155 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2156 } 2157 } 2158 } 2159 2160 // An rvalue for an integral bit-field (9.6) can be converted to an 2161 // rvalue of type int if int can represent all the values of the 2162 // bit-field; otherwise, it can be converted to unsigned int if 2163 // unsigned int can represent all the values of the bit-field. If 2164 // the bit-field is larger yet, no integral promotion applies to 2165 // it. If the bit-field has an enumerated type, it is treated as any 2166 // other value of that type for promotion purposes (C++ 4.5p3). 2167 // FIXME: We should delay checking of bit-fields until we actually perform the 2168 // conversion. 2169 // 2170 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2171 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2172 // bit-fields and those whose underlying type is larger than int) for GCC 2173 // compatibility. 2174 if (From) { 2175 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2176 llvm::APSInt BitWidth; 2177 if (FromType->isIntegralType(Context) && 2178 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2179 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2180 ToSize = Context.getTypeSize(ToType); 2181 2182 // Are we promoting to an int from a bitfield that fits in an int? 2183 if (BitWidth < ToSize || 2184 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2185 return To->getKind() == BuiltinType::Int; 2186 } 2187 2188 // Are we promoting to an unsigned int from an unsigned bitfield 2189 // that fits into an unsigned int? 2190 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2191 return To->getKind() == BuiltinType::UInt; 2192 } 2193 2194 return false; 2195 } 2196 } 2197 } 2198 2199 // An rvalue of type bool can be converted to an rvalue of type int, 2200 // with false becoming zero and true becoming one (C++ 4.5p4). 2201 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2202 return true; 2203 } 2204 2205 return false; 2206 } 2207 2208 /// IsFloatingPointPromotion - Determines whether the conversion from 2209 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2210 /// returns true and sets PromotedType to the promoted type. 2211 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2212 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2213 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2214 /// An rvalue of type float can be converted to an rvalue of type 2215 /// double. (C++ 4.6p1). 2216 if (FromBuiltin->getKind() == BuiltinType::Float && 2217 ToBuiltin->getKind() == BuiltinType::Double) 2218 return true; 2219 2220 // C99 6.3.1.5p1: 2221 // When a float is promoted to double or long double, or a 2222 // double is promoted to long double [...]. 2223 if (!getLangOpts().CPlusPlus && 2224 (FromBuiltin->getKind() == BuiltinType::Float || 2225 FromBuiltin->getKind() == BuiltinType::Double) && 2226 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2227 ToBuiltin->getKind() == BuiltinType::Float128)) 2228 return true; 2229 2230 // Half can be promoted to float. 2231 if (!getLangOpts().NativeHalfType && 2232 FromBuiltin->getKind() == BuiltinType::Half && 2233 ToBuiltin->getKind() == BuiltinType::Float) 2234 return true; 2235 } 2236 2237 return false; 2238 } 2239 2240 /// Determine if a conversion is a complex promotion. 2241 /// 2242 /// A complex promotion is defined as a complex -> complex conversion 2243 /// where the conversion between the underlying real types is a 2244 /// floating-point or integral promotion. 2245 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2246 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2247 if (!FromComplex) 2248 return false; 2249 2250 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2251 if (!ToComplex) 2252 return false; 2253 2254 return IsFloatingPointPromotion(FromComplex->getElementType(), 2255 ToComplex->getElementType()) || 2256 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2257 ToComplex->getElementType()); 2258 } 2259 2260 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2261 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2262 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2263 /// if non-empty, will be a pointer to ToType that may or may not have 2264 /// the right set of qualifiers on its pointee. 2265 /// 2266 static QualType 2267 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2268 QualType ToPointee, QualType ToType, 2269 ASTContext &Context, 2270 bool StripObjCLifetime = false) { 2271 assert((FromPtr->getTypeClass() == Type::Pointer || 2272 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2273 "Invalid similarly-qualified pointer type"); 2274 2275 /// Conversions to 'id' subsume cv-qualifier conversions. 2276 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2277 return ToType.getUnqualifiedType(); 2278 2279 QualType CanonFromPointee 2280 = Context.getCanonicalType(FromPtr->getPointeeType()); 2281 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2282 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2283 2284 if (StripObjCLifetime) 2285 Quals.removeObjCLifetime(); 2286 2287 // Exact qualifier match -> return the pointer type we're converting to. 2288 if (CanonToPointee.getLocalQualifiers() == Quals) { 2289 // ToType is exactly what we need. Return it. 2290 if (!ToType.isNull()) 2291 return ToType.getUnqualifiedType(); 2292 2293 // Build a pointer to ToPointee. It has the right qualifiers 2294 // already. 2295 if (isa<ObjCObjectPointerType>(ToType)) 2296 return Context.getObjCObjectPointerType(ToPointee); 2297 return Context.getPointerType(ToPointee); 2298 } 2299 2300 // Just build a canonical type that has the right qualifiers. 2301 QualType QualifiedCanonToPointee 2302 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2303 2304 if (isa<ObjCObjectPointerType>(ToType)) 2305 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2306 return Context.getPointerType(QualifiedCanonToPointee); 2307 } 2308 2309 static bool isNullPointerConstantForConversion(Expr *Expr, 2310 bool InOverloadResolution, 2311 ASTContext &Context) { 2312 // Handle value-dependent integral null pointer constants correctly. 2313 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2314 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2315 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2316 return !InOverloadResolution; 2317 2318 return Expr->isNullPointerConstant(Context, 2319 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2320 : Expr::NPC_ValueDependentIsNull); 2321 } 2322 2323 /// IsPointerConversion - Determines whether the conversion of the 2324 /// expression From, which has the (possibly adjusted) type FromType, 2325 /// can be converted to the type ToType via a pointer conversion (C++ 2326 /// 4.10). If so, returns true and places the converted type (that 2327 /// might differ from ToType in its cv-qualifiers at some level) into 2328 /// ConvertedType. 2329 /// 2330 /// This routine also supports conversions to and from block pointers 2331 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2332 /// pointers to interfaces. FIXME: Once we've determined the 2333 /// appropriate overloading rules for Objective-C, we may want to 2334 /// split the Objective-C checks into a different routine; however, 2335 /// GCC seems to consider all of these conversions to be pointer 2336 /// conversions, so for now they live here. IncompatibleObjC will be 2337 /// set if the conversion is an allowed Objective-C conversion that 2338 /// should result in a warning. 2339 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2340 bool InOverloadResolution, 2341 QualType& ConvertedType, 2342 bool &IncompatibleObjC) { 2343 IncompatibleObjC = false; 2344 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2345 IncompatibleObjC)) 2346 return true; 2347 2348 // Conversion from a null pointer constant to any Objective-C pointer type. 2349 if (ToType->isObjCObjectPointerType() && 2350 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2351 ConvertedType = ToType; 2352 return true; 2353 } 2354 2355 // Blocks: Block pointers can be converted to void*. 2356 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2357 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2358 ConvertedType = ToType; 2359 return true; 2360 } 2361 // Blocks: A null pointer constant can be converted to a block 2362 // pointer type. 2363 if (ToType->isBlockPointerType() && 2364 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2365 ConvertedType = ToType; 2366 return true; 2367 } 2368 2369 // If the left-hand-side is nullptr_t, the right side can be a null 2370 // pointer constant. 2371 if (ToType->isNullPtrType() && 2372 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2373 ConvertedType = ToType; 2374 return true; 2375 } 2376 2377 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2378 if (!ToTypePtr) 2379 return false; 2380 2381 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2382 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2383 ConvertedType = ToType; 2384 return true; 2385 } 2386 2387 // Beyond this point, both types need to be pointers 2388 // , including objective-c pointers. 2389 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2390 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2391 !getLangOpts().ObjCAutoRefCount) { 2392 ConvertedType = BuildSimilarlyQualifiedPointerType( 2393 FromType->getAs<ObjCObjectPointerType>(), 2394 ToPointeeType, 2395 ToType, Context); 2396 return true; 2397 } 2398 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2399 if (!FromTypePtr) 2400 return false; 2401 2402 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2403 2404 // If the unqualified pointee types are the same, this can't be a 2405 // pointer conversion, so don't do all of the work below. 2406 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2407 return false; 2408 2409 // An rvalue of type "pointer to cv T," where T is an object type, 2410 // can be converted to an rvalue of type "pointer to cv void" (C++ 2411 // 4.10p2). 2412 if (FromPointeeType->isIncompleteOrObjectType() && 2413 ToPointeeType->isVoidType()) { 2414 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2415 ToPointeeType, 2416 ToType, Context, 2417 /*StripObjCLifetime=*/true); 2418 return true; 2419 } 2420 2421 // MSVC allows implicit function to void* type conversion. 2422 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2423 ToPointeeType->isVoidType()) { 2424 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2425 ToPointeeType, 2426 ToType, Context); 2427 return true; 2428 } 2429 2430 // When we're overloading in C, we allow a special kind of pointer 2431 // conversion for compatible-but-not-identical pointee types. 2432 if (!getLangOpts().CPlusPlus && 2433 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2434 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2435 ToPointeeType, 2436 ToType, Context); 2437 return true; 2438 } 2439 2440 // C++ [conv.ptr]p3: 2441 // 2442 // An rvalue of type "pointer to cv D," where D is a class type, 2443 // can be converted to an rvalue of type "pointer to cv B," where 2444 // B is a base class (clause 10) of D. If B is an inaccessible 2445 // (clause 11) or ambiguous (10.2) base class of D, a program that 2446 // necessitates this conversion is ill-formed. The result of the 2447 // conversion is a pointer to the base class sub-object of the 2448 // derived class object. The null pointer value is converted to 2449 // the null pointer value of the destination type. 2450 // 2451 // Note that we do not check for ambiguity or inaccessibility 2452 // here. That is handled by CheckPointerConversion. 2453 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2454 ToPointeeType->isRecordType() && 2455 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2456 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2457 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2458 ToPointeeType, 2459 ToType, Context); 2460 return true; 2461 } 2462 2463 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2464 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2465 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2466 ToPointeeType, 2467 ToType, Context); 2468 return true; 2469 } 2470 2471 return false; 2472 } 2473 2474 /// Adopt the given qualifiers for the given type. 2475 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2476 Qualifiers TQs = T.getQualifiers(); 2477 2478 // Check whether qualifiers already match. 2479 if (TQs == Qs) 2480 return T; 2481 2482 if (Qs.compatiblyIncludes(TQs)) 2483 return Context.getQualifiedType(T, Qs); 2484 2485 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2486 } 2487 2488 /// isObjCPointerConversion - Determines whether this is an 2489 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2490 /// with the same arguments and return values. 2491 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2492 QualType& ConvertedType, 2493 bool &IncompatibleObjC) { 2494 if (!getLangOpts().ObjC) 2495 return false; 2496 2497 // The set of qualifiers on the type we're converting from. 2498 Qualifiers FromQualifiers = FromType.getQualifiers(); 2499 2500 // First, we handle all conversions on ObjC object pointer types. 2501 const ObjCObjectPointerType* ToObjCPtr = 2502 ToType->getAs<ObjCObjectPointerType>(); 2503 const ObjCObjectPointerType *FromObjCPtr = 2504 FromType->getAs<ObjCObjectPointerType>(); 2505 2506 if (ToObjCPtr && FromObjCPtr) { 2507 // If the pointee types are the same (ignoring qualifications), 2508 // then this is not a pointer conversion. 2509 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2510 FromObjCPtr->getPointeeType())) 2511 return false; 2512 2513 // Conversion between Objective-C pointers. 2514 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2515 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2516 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2517 if (getLangOpts().CPlusPlus && LHS && RHS && 2518 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2519 FromObjCPtr->getPointeeType())) 2520 return false; 2521 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2522 ToObjCPtr->getPointeeType(), 2523 ToType, Context); 2524 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2525 return true; 2526 } 2527 2528 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2529 // Okay: this is some kind of implicit downcast of Objective-C 2530 // interfaces, which is permitted. However, we're going to 2531 // complain about it. 2532 IncompatibleObjC = true; 2533 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2534 ToObjCPtr->getPointeeType(), 2535 ToType, Context); 2536 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2537 return true; 2538 } 2539 } 2540 // Beyond this point, both types need to be C pointers or block pointers. 2541 QualType ToPointeeType; 2542 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2543 ToPointeeType = ToCPtr->getPointeeType(); 2544 else if (const BlockPointerType *ToBlockPtr = 2545 ToType->getAs<BlockPointerType>()) { 2546 // Objective C++: We're able to convert from a pointer to any object 2547 // to a block pointer type. 2548 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2549 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2550 return true; 2551 } 2552 ToPointeeType = ToBlockPtr->getPointeeType(); 2553 } 2554 else if (FromType->getAs<BlockPointerType>() && 2555 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2556 // Objective C++: We're able to convert from a block pointer type to a 2557 // pointer to any object. 2558 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2559 return true; 2560 } 2561 else 2562 return false; 2563 2564 QualType FromPointeeType; 2565 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2566 FromPointeeType = FromCPtr->getPointeeType(); 2567 else if (const BlockPointerType *FromBlockPtr = 2568 FromType->getAs<BlockPointerType>()) 2569 FromPointeeType = FromBlockPtr->getPointeeType(); 2570 else 2571 return false; 2572 2573 // If we have pointers to pointers, recursively check whether this 2574 // is an Objective-C conversion. 2575 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2576 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2577 IncompatibleObjC)) { 2578 // We always complain about this conversion. 2579 IncompatibleObjC = true; 2580 ConvertedType = Context.getPointerType(ConvertedType); 2581 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2582 return true; 2583 } 2584 // Allow conversion of pointee being objective-c pointer to another one; 2585 // as in I* to id. 2586 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2587 ToPointeeType->getAs<ObjCObjectPointerType>() && 2588 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2589 IncompatibleObjC)) { 2590 2591 ConvertedType = Context.getPointerType(ConvertedType); 2592 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2593 return true; 2594 } 2595 2596 // If we have pointers to functions or blocks, check whether the only 2597 // differences in the argument and result types are in Objective-C 2598 // pointer conversions. If so, we permit the conversion (but 2599 // complain about it). 2600 const FunctionProtoType *FromFunctionType 2601 = FromPointeeType->getAs<FunctionProtoType>(); 2602 const FunctionProtoType *ToFunctionType 2603 = ToPointeeType->getAs<FunctionProtoType>(); 2604 if (FromFunctionType && ToFunctionType) { 2605 // If the function types are exactly the same, this isn't an 2606 // Objective-C pointer conversion. 2607 if (Context.getCanonicalType(FromPointeeType) 2608 == Context.getCanonicalType(ToPointeeType)) 2609 return false; 2610 2611 // Perform the quick checks that will tell us whether these 2612 // function types are obviously different. 2613 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2614 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2615 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2616 return false; 2617 2618 bool HasObjCConversion = false; 2619 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2620 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2621 // Okay, the types match exactly. Nothing to do. 2622 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2623 ToFunctionType->getReturnType(), 2624 ConvertedType, IncompatibleObjC)) { 2625 // Okay, we have an Objective-C pointer conversion. 2626 HasObjCConversion = true; 2627 } else { 2628 // Function types are too different. Abort. 2629 return false; 2630 } 2631 2632 // Check argument types. 2633 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2634 ArgIdx != NumArgs; ++ArgIdx) { 2635 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2636 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2637 if (Context.getCanonicalType(FromArgType) 2638 == Context.getCanonicalType(ToArgType)) { 2639 // Okay, the types match exactly. Nothing to do. 2640 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2641 ConvertedType, IncompatibleObjC)) { 2642 // Okay, we have an Objective-C pointer conversion. 2643 HasObjCConversion = true; 2644 } else { 2645 // Argument types are too different. Abort. 2646 return false; 2647 } 2648 } 2649 2650 if (HasObjCConversion) { 2651 // We had an Objective-C conversion. Allow this pointer 2652 // conversion, but complain about it. 2653 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2654 IncompatibleObjC = true; 2655 return true; 2656 } 2657 } 2658 2659 return false; 2660 } 2661 2662 /// Determine whether this is an Objective-C writeback conversion, 2663 /// used for parameter passing when performing automatic reference counting. 2664 /// 2665 /// \param FromType The type we're converting form. 2666 /// 2667 /// \param ToType The type we're converting to. 2668 /// 2669 /// \param ConvertedType The type that will be produced after applying 2670 /// this conversion. 2671 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2672 QualType &ConvertedType) { 2673 if (!getLangOpts().ObjCAutoRefCount || 2674 Context.hasSameUnqualifiedType(FromType, ToType)) 2675 return false; 2676 2677 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2678 QualType ToPointee; 2679 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2680 ToPointee = ToPointer->getPointeeType(); 2681 else 2682 return false; 2683 2684 Qualifiers ToQuals = ToPointee.getQualifiers(); 2685 if (!ToPointee->isObjCLifetimeType() || 2686 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2687 !ToQuals.withoutObjCLifetime().empty()) 2688 return false; 2689 2690 // Argument must be a pointer to __strong to __weak. 2691 QualType FromPointee; 2692 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2693 FromPointee = FromPointer->getPointeeType(); 2694 else 2695 return false; 2696 2697 Qualifiers FromQuals = FromPointee.getQualifiers(); 2698 if (!FromPointee->isObjCLifetimeType() || 2699 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2700 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2701 return false; 2702 2703 // Make sure that we have compatible qualifiers. 2704 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2705 if (!ToQuals.compatiblyIncludes(FromQuals)) 2706 return false; 2707 2708 // Remove qualifiers from the pointee type we're converting from; they 2709 // aren't used in the compatibility check belong, and we'll be adding back 2710 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2711 FromPointee = FromPointee.getUnqualifiedType(); 2712 2713 // The unqualified form of the pointee types must be compatible. 2714 ToPointee = ToPointee.getUnqualifiedType(); 2715 bool IncompatibleObjC; 2716 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2717 FromPointee = ToPointee; 2718 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2719 IncompatibleObjC)) 2720 return false; 2721 2722 /// Construct the type we're converting to, which is a pointer to 2723 /// __autoreleasing pointee. 2724 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2725 ConvertedType = Context.getPointerType(FromPointee); 2726 return true; 2727 } 2728 2729 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2730 QualType& ConvertedType) { 2731 QualType ToPointeeType; 2732 if (const BlockPointerType *ToBlockPtr = 2733 ToType->getAs<BlockPointerType>()) 2734 ToPointeeType = ToBlockPtr->getPointeeType(); 2735 else 2736 return false; 2737 2738 QualType FromPointeeType; 2739 if (const BlockPointerType *FromBlockPtr = 2740 FromType->getAs<BlockPointerType>()) 2741 FromPointeeType = FromBlockPtr->getPointeeType(); 2742 else 2743 return false; 2744 // We have pointer to blocks, check whether the only 2745 // differences in the argument and result types are in Objective-C 2746 // pointer conversions. If so, we permit the conversion. 2747 2748 const FunctionProtoType *FromFunctionType 2749 = FromPointeeType->getAs<FunctionProtoType>(); 2750 const FunctionProtoType *ToFunctionType 2751 = ToPointeeType->getAs<FunctionProtoType>(); 2752 2753 if (!FromFunctionType || !ToFunctionType) 2754 return false; 2755 2756 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2757 return true; 2758 2759 // Perform the quick checks that will tell us whether these 2760 // function types are obviously different. 2761 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2762 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2763 return false; 2764 2765 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2766 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2767 if (FromEInfo != ToEInfo) 2768 return false; 2769 2770 bool IncompatibleObjC = false; 2771 if (Context.hasSameType(FromFunctionType->getReturnType(), 2772 ToFunctionType->getReturnType())) { 2773 // Okay, the types match exactly. Nothing to do. 2774 } else { 2775 QualType RHS = FromFunctionType->getReturnType(); 2776 QualType LHS = ToFunctionType->getReturnType(); 2777 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2778 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2779 LHS = LHS.getUnqualifiedType(); 2780 2781 if (Context.hasSameType(RHS,LHS)) { 2782 // OK exact match. 2783 } else if (isObjCPointerConversion(RHS, LHS, 2784 ConvertedType, IncompatibleObjC)) { 2785 if (IncompatibleObjC) 2786 return false; 2787 // Okay, we have an Objective-C pointer conversion. 2788 } 2789 else 2790 return false; 2791 } 2792 2793 // Check argument types. 2794 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2795 ArgIdx != NumArgs; ++ArgIdx) { 2796 IncompatibleObjC = false; 2797 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2798 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2799 if (Context.hasSameType(FromArgType, ToArgType)) { 2800 // Okay, the types match exactly. Nothing to do. 2801 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2802 ConvertedType, IncompatibleObjC)) { 2803 if (IncompatibleObjC) 2804 return false; 2805 // Okay, we have an Objective-C pointer conversion. 2806 } else 2807 // Argument types are too different. Abort. 2808 return false; 2809 } 2810 2811 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2812 bool CanUseToFPT, CanUseFromFPT; 2813 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2814 CanUseToFPT, CanUseFromFPT, 2815 NewParamInfos)) 2816 return false; 2817 2818 ConvertedType = ToType; 2819 return true; 2820 } 2821 2822 enum { 2823 ft_default, 2824 ft_different_class, 2825 ft_parameter_arity, 2826 ft_parameter_mismatch, 2827 ft_return_type, 2828 ft_qualifer_mismatch, 2829 ft_noexcept 2830 }; 2831 2832 /// Attempts to get the FunctionProtoType from a Type. Handles 2833 /// MemberFunctionPointers properly. 2834 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2835 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2836 return FPT; 2837 2838 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2839 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2840 2841 return nullptr; 2842 } 2843 2844 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2845 /// function types. Catches different number of parameter, mismatch in 2846 /// parameter types, and different return types. 2847 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2848 QualType FromType, QualType ToType) { 2849 // If either type is not valid, include no extra info. 2850 if (FromType.isNull() || ToType.isNull()) { 2851 PDiag << ft_default; 2852 return; 2853 } 2854 2855 // Get the function type from the pointers. 2856 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2857 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2858 *ToMember = ToType->castAs<MemberPointerType>(); 2859 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2860 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2861 << QualType(FromMember->getClass(), 0); 2862 return; 2863 } 2864 FromType = FromMember->getPointeeType(); 2865 ToType = ToMember->getPointeeType(); 2866 } 2867 2868 if (FromType->isPointerType()) 2869 FromType = FromType->getPointeeType(); 2870 if (ToType->isPointerType()) 2871 ToType = ToType->getPointeeType(); 2872 2873 // Remove references. 2874 FromType = FromType.getNonReferenceType(); 2875 ToType = ToType.getNonReferenceType(); 2876 2877 // Don't print extra info for non-specialized template functions. 2878 if (FromType->isInstantiationDependentType() && 2879 !FromType->getAs<TemplateSpecializationType>()) { 2880 PDiag << ft_default; 2881 return; 2882 } 2883 2884 // No extra info for same types. 2885 if (Context.hasSameType(FromType, ToType)) { 2886 PDiag << ft_default; 2887 return; 2888 } 2889 2890 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2891 *ToFunction = tryGetFunctionProtoType(ToType); 2892 2893 // Both types need to be function types. 2894 if (!FromFunction || !ToFunction) { 2895 PDiag << ft_default; 2896 return; 2897 } 2898 2899 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2900 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2901 << FromFunction->getNumParams(); 2902 return; 2903 } 2904 2905 // Handle different parameter types. 2906 unsigned ArgPos; 2907 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2908 PDiag << ft_parameter_mismatch << ArgPos + 1 2909 << ToFunction->getParamType(ArgPos) 2910 << FromFunction->getParamType(ArgPos); 2911 return; 2912 } 2913 2914 // Handle different return type. 2915 if (!Context.hasSameType(FromFunction->getReturnType(), 2916 ToFunction->getReturnType())) { 2917 PDiag << ft_return_type << ToFunction->getReturnType() 2918 << FromFunction->getReturnType(); 2919 return; 2920 } 2921 2922 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2923 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2924 << FromFunction->getMethodQuals(); 2925 return; 2926 } 2927 2928 // Handle exception specification differences on canonical type (in C++17 2929 // onwards). 2930 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2931 ->isNothrow() != 2932 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2933 ->isNothrow()) { 2934 PDiag << ft_noexcept; 2935 return; 2936 } 2937 2938 // Unable to find a difference, so add no extra info. 2939 PDiag << ft_default; 2940 } 2941 2942 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2943 /// for equality of their argument types. Caller has already checked that 2944 /// they have same number of arguments. If the parameters are different, 2945 /// ArgPos will have the parameter index of the first different parameter. 2946 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2947 const FunctionProtoType *NewType, 2948 unsigned *ArgPos) { 2949 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2950 N = NewType->param_type_begin(), 2951 E = OldType->param_type_end(); 2952 O && (O != E); ++O, ++N) { 2953 // Ignore address spaces in pointee type. This is to disallow overloading 2954 // on __ptr32/__ptr64 address spaces. 2955 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2956 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2957 2958 if (!Context.hasSameType(Old, New)) { 2959 if (ArgPos) 2960 *ArgPos = O - OldType->param_type_begin(); 2961 return false; 2962 } 2963 } 2964 return true; 2965 } 2966 2967 /// CheckPointerConversion - Check the pointer conversion from the 2968 /// expression From to the type ToType. This routine checks for 2969 /// ambiguous or inaccessible derived-to-base pointer 2970 /// conversions for which IsPointerConversion has already returned 2971 /// true. It returns true and produces a diagnostic if there was an 2972 /// error, or returns false otherwise. 2973 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2974 CastKind &Kind, 2975 CXXCastPath& BasePath, 2976 bool IgnoreBaseAccess, 2977 bool Diagnose) { 2978 QualType FromType = From->getType(); 2979 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2980 2981 Kind = CK_BitCast; 2982 2983 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2984 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2985 Expr::NPCK_ZeroExpression) { 2986 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2987 DiagRuntimeBehavior(From->getExprLoc(), From, 2988 PDiag(diag::warn_impcast_bool_to_null_pointer) 2989 << ToType << From->getSourceRange()); 2990 else if (!isUnevaluatedContext()) 2991 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2992 << ToType << From->getSourceRange(); 2993 } 2994 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2995 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2996 QualType FromPointeeType = FromPtrType->getPointeeType(), 2997 ToPointeeType = ToPtrType->getPointeeType(); 2998 2999 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3000 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3001 // We must have a derived-to-base conversion. Check an 3002 // ambiguous or inaccessible conversion. 3003 unsigned InaccessibleID = 0; 3004 unsigned AmbigiousID = 0; 3005 if (Diagnose) { 3006 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3007 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 3008 } 3009 if (CheckDerivedToBaseConversion( 3010 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 3011 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3012 &BasePath, IgnoreBaseAccess)) 3013 return true; 3014 3015 // The conversion was successful. 3016 Kind = CK_DerivedToBase; 3017 } 3018 3019 if (Diagnose && !IsCStyleOrFunctionalCast && 3020 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3021 assert(getLangOpts().MSVCCompat && 3022 "this should only be possible with MSVCCompat!"); 3023 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3024 << From->getSourceRange(); 3025 } 3026 } 3027 } else if (const ObjCObjectPointerType *ToPtrType = 3028 ToType->getAs<ObjCObjectPointerType>()) { 3029 if (const ObjCObjectPointerType *FromPtrType = 3030 FromType->getAs<ObjCObjectPointerType>()) { 3031 // Objective-C++ conversions are always okay. 3032 // FIXME: We should have a different class of conversions for the 3033 // Objective-C++ implicit conversions. 3034 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3035 return false; 3036 } else if (FromType->isBlockPointerType()) { 3037 Kind = CK_BlockPointerToObjCPointerCast; 3038 } else { 3039 Kind = CK_CPointerToObjCPointerCast; 3040 } 3041 } else if (ToType->isBlockPointerType()) { 3042 if (!FromType->isBlockPointerType()) 3043 Kind = CK_AnyPointerToBlockPointerCast; 3044 } 3045 3046 // We shouldn't fall into this case unless it's valid for other 3047 // reasons. 3048 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3049 Kind = CK_NullToPointer; 3050 3051 return false; 3052 } 3053 3054 /// IsMemberPointerConversion - Determines whether the conversion of the 3055 /// expression From, which has the (possibly adjusted) type FromType, can be 3056 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3057 /// If so, returns true and places the converted type (that might differ from 3058 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3059 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3060 QualType ToType, 3061 bool InOverloadResolution, 3062 QualType &ConvertedType) { 3063 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3064 if (!ToTypePtr) 3065 return false; 3066 3067 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3068 if (From->isNullPointerConstant(Context, 3069 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3070 : Expr::NPC_ValueDependentIsNull)) { 3071 ConvertedType = ToType; 3072 return true; 3073 } 3074 3075 // Otherwise, both types have to be member pointers. 3076 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3077 if (!FromTypePtr) 3078 return false; 3079 3080 // A pointer to member of B can be converted to a pointer to member of D, 3081 // where D is derived from B (C++ 4.11p2). 3082 QualType FromClass(FromTypePtr->getClass(), 0); 3083 QualType ToClass(ToTypePtr->getClass(), 0); 3084 3085 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3086 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3087 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3088 ToClass.getTypePtr()); 3089 return true; 3090 } 3091 3092 return false; 3093 } 3094 3095 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3096 /// expression From to the type ToType. This routine checks for ambiguous or 3097 /// virtual or inaccessible base-to-derived member pointer conversions 3098 /// for which IsMemberPointerConversion has already returned true. It returns 3099 /// true and produces a diagnostic if there was an error, or returns false 3100 /// otherwise. 3101 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3102 CastKind &Kind, 3103 CXXCastPath &BasePath, 3104 bool IgnoreBaseAccess) { 3105 QualType FromType = From->getType(); 3106 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3107 if (!FromPtrType) { 3108 // This must be a null pointer to member pointer conversion 3109 assert(From->isNullPointerConstant(Context, 3110 Expr::NPC_ValueDependentIsNull) && 3111 "Expr must be null pointer constant!"); 3112 Kind = CK_NullToMemberPointer; 3113 return false; 3114 } 3115 3116 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3117 assert(ToPtrType && "No member pointer cast has a target type " 3118 "that is not a member pointer."); 3119 3120 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3121 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3122 3123 // FIXME: What about dependent types? 3124 assert(FromClass->isRecordType() && "Pointer into non-class."); 3125 assert(ToClass->isRecordType() && "Pointer into non-class."); 3126 3127 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3128 /*DetectVirtual=*/true); 3129 bool DerivationOkay = 3130 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3131 assert(DerivationOkay && 3132 "Should not have been called if derivation isn't OK."); 3133 (void)DerivationOkay; 3134 3135 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3136 getUnqualifiedType())) { 3137 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3138 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3139 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3140 return true; 3141 } 3142 3143 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3144 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3145 << FromClass << ToClass << QualType(VBase, 0) 3146 << From->getSourceRange(); 3147 return true; 3148 } 3149 3150 if (!IgnoreBaseAccess) 3151 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3152 Paths.front(), 3153 diag::err_downcast_from_inaccessible_base); 3154 3155 // Must be a base to derived member conversion. 3156 BuildBasePathArray(Paths, BasePath); 3157 Kind = CK_BaseToDerivedMemberPointer; 3158 return false; 3159 } 3160 3161 /// Determine whether the lifetime conversion between the two given 3162 /// qualifiers sets is nontrivial. 3163 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3164 Qualifiers ToQuals) { 3165 // Converting anything to const __unsafe_unretained is trivial. 3166 if (ToQuals.hasConst() && 3167 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3168 return false; 3169 3170 return true; 3171 } 3172 3173 /// Perform a single iteration of the loop for checking if a qualification 3174 /// conversion is valid. 3175 /// 3176 /// Specifically, check whether any change between the qualifiers of \p 3177 /// FromType and \p ToType is permissible, given knowledge about whether every 3178 /// outer layer is const-qualified. 3179 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3180 bool CStyle, bool IsTopLevel, 3181 bool &PreviousToQualsIncludeConst, 3182 bool &ObjCLifetimeConversion) { 3183 Qualifiers FromQuals = FromType.getQualifiers(); 3184 Qualifiers ToQuals = ToType.getQualifiers(); 3185 3186 // Ignore __unaligned qualifier if this type is void. 3187 if (ToType.getUnqualifiedType()->isVoidType()) 3188 FromQuals.removeUnaligned(); 3189 3190 // Objective-C ARC: 3191 // Check Objective-C lifetime conversions. 3192 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3193 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3194 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3195 ObjCLifetimeConversion = true; 3196 FromQuals.removeObjCLifetime(); 3197 ToQuals.removeObjCLifetime(); 3198 } else { 3199 // Qualification conversions cannot cast between different 3200 // Objective-C lifetime qualifiers. 3201 return false; 3202 } 3203 } 3204 3205 // Allow addition/removal of GC attributes but not changing GC attributes. 3206 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3207 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3208 FromQuals.removeObjCGCAttr(); 3209 ToQuals.removeObjCGCAttr(); 3210 } 3211 3212 // -- for every j > 0, if const is in cv 1,j then const is in cv 3213 // 2,j, and similarly for volatile. 3214 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3215 return false; 3216 3217 // If address spaces mismatch: 3218 // - in top level it is only valid to convert to addr space that is a 3219 // superset in all cases apart from C-style casts where we allow 3220 // conversions between overlapping address spaces. 3221 // - in non-top levels it is not a valid conversion. 3222 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3223 (!IsTopLevel || 3224 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3225 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3226 return false; 3227 3228 // -- if the cv 1,j and cv 2,j are different, then const is in 3229 // every cv for 0 < k < j. 3230 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3231 !PreviousToQualsIncludeConst) 3232 return false; 3233 3234 // Keep track of whether all prior cv-qualifiers in the "to" type 3235 // include const. 3236 PreviousToQualsIncludeConst = 3237 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3238 return true; 3239 } 3240 3241 /// IsQualificationConversion - Determines whether the conversion from 3242 /// an rvalue of type FromType to ToType is a qualification conversion 3243 /// (C++ 4.4). 3244 /// 3245 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3246 /// when the qualification conversion involves a change in the Objective-C 3247 /// object lifetime. 3248 bool 3249 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3250 bool CStyle, bool &ObjCLifetimeConversion) { 3251 FromType = Context.getCanonicalType(FromType); 3252 ToType = Context.getCanonicalType(ToType); 3253 ObjCLifetimeConversion = false; 3254 3255 // If FromType and ToType are the same type, this is not a 3256 // qualification conversion. 3257 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3258 return false; 3259 3260 // (C++ 4.4p4): 3261 // A conversion can add cv-qualifiers at levels other than the first 3262 // in multi-level pointers, subject to the following rules: [...] 3263 bool PreviousToQualsIncludeConst = true; 3264 bool UnwrappedAnyPointer = false; 3265 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3266 if (!isQualificationConversionStep( 3267 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3268 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3269 return false; 3270 UnwrappedAnyPointer = true; 3271 } 3272 3273 // We are left with FromType and ToType being the pointee types 3274 // after unwrapping the original FromType and ToType the same number 3275 // of times. If we unwrapped any pointers, and if FromType and 3276 // ToType have the same unqualified type (since we checked 3277 // qualifiers above), then this is a qualification conversion. 3278 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3279 } 3280 3281 /// - Determine whether this is a conversion from a scalar type to an 3282 /// atomic type. 3283 /// 3284 /// If successful, updates \c SCS's second and third steps in the conversion 3285 /// sequence to finish the conversion. 3286 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3287 bool InOverloadResolution, 3288 StandardConversionSequence &SCS, 3289 bool CStyle) { 3290 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3291 if (!ToAtomic) 3292 return false; 3293 3294 StandardConversionSequence InnerSCS; 3295 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3296 InOverloadResolution, InnerSCS, 3297 CStyle, /*AllowObjCWritebackConversion=*/false)) 3298 return false; 3299 3300 SCS.Second = InnerSCS.Second; 3301 SCS.setToType(1, InnerSCS.getToType(1)); 3302 SCS.Third = InnerSCS.Third; 3303 SCS.QualificationIncludesObjCLifetime 3304 = InnerSCS.QualificationIncludesObjCLifetime; 3305 SCS.setToType(2, InnerSCS.getToType(2)); 3306 return true; 3307 } 3308 3309 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3310 CXXConstructorDecl *Constructor, 3311 QualType Type) { 3312 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3313 if (CtorType->getNumParams() > 0) { 3314 QualType FirstArg = CtorType->getParamType(0); 3315 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3316 return true; 3317 } 3318 return false; 3319 } 3320 3321 static OverloadingResult 3322 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3323 CXXRecordDecl *To, 3324 UserDefinedConversionSequence &User, 3325 OverloadCandidateSet &CandidateSet, 3326 bool AllowExplicit) { 3327 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3328 for (auto *D : S.LookupConstructors(To)) { 3329 auto Info = getConstructorInfo(D); 3330 if (!Info) 3331 continue; 3332 3333 bool Usable = !Info.Constructor->isInvalidDecl() && 3334 S.isInitListConstructor(Info.Constructor); 3335 if (Usable) { 3336 // If the first argument is (a reference to) the target type, 3337 // suppress conversions. 3338 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3339 S.Context, Info.Constructor, ToType); 3340 if (Info.ConstructorTmpl) 3341 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3342 /*ExplicitArgs*/ nullptr, From, 3343 CandidateSet, SuppressUserConversions, 3344 /*PartialOverloading*/ false, 3345 AllowExplicit); 3346 else 3347 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3348 CandidateSet, SuppressUserConversions, 3349 /*PartialOverloading*/ false, AllowExplicit); 3350 } 3351 } 3352 3353 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3354 3355 OverloadCandidateSet::iterator Best; 3356 switch (auto Result = 3357 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3358 case OR_Deleted: 3359 case OR_Success: { 3360 // Record the standard conversion we used and the conversion function. 3361 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3362 QualType ThisType = Constructor->getThisType(); 3363 // Initializer lists don't have conversions as such. 3364 User.Before.setAsIdentityConversion(); 3365 User.HadMultipleCandidates = HadMultipleCandidates; 3366 User.ConversionFunction = Constructor; 3367 User.FoundConversionFunction = Best->FoundDecl; 3368 User.After.setAsIdentityConversion(); 3369 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3370 User.After.setAllToTypes(ToType); 3371 return Result; 3372 } 3373 3374 case OR_No_Viable_Function: 3375 return OR_No_Viable_Function; 3376 case OR_Ambiguous: 3377 return OR_Ambiguous; 3378 } 3379 3380 llvm_unreachable("Invalid OverloadResult!"); 3381 } 3382 3383 /// Determines whether there is a user-defined conversion sequence 3384 /// (C++ [over.ics.user]) that converts expression From to the type 3385 /// ToType. If such a conversion exists, User will contain the 3386 /// user-defined conversion sequence that performs such a conversion 3387 /// and this routine will return true. Otherwise, this routine returns 3388 /// false and User is unspecified. 3389 /// 3390 /// \param AllowExplicit true if the conversion should consider C++0x 3391 /// "explicit" conversion functions as well as non-explicit conversion 3392 /// functions (C++0x [class.conv.fct]p2). 3393 /// 3394 /// \param AllowObjCConversionOnExplicit true if the conversion should 3395 /// allow an extra Objective-C pointer conversion on uses of explicit 3396 /// constructors. Requires \c AllowExplicit to also be set. 3397 static OverloadingResult 3398 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3399 UserDefinedConversionSequence &User, 3400 OverloadCandidateSet &CandidateSet, 3401 AllowedExplicit AllowExplicit, 3402 bool AllowObjCConversionOnExplicit) { 3403 assert(AllowExplicit != AllowedExplicit::None || 3404 !AllowObjCConversionOnExplicit); 3405 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3406 3407 // Whether we will only visit constructors. 3408 bool ConstructorsOnly = false; 3409 3410 // If the type we are conversion to is a class type, enumerate its 3411 // constructors. 3412 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3413 // C++ [over.match.ctor]p1: 3414 // When objects of class type are direct-initialized (8.5), or 3415 // copy-initialized from an expression of the same or a 3416 // derived class type (8.5), overload resolution selects the 3417 // constructor. [...] For copy-initialization, the candidate 3418 // functions are all the converting constructors (12.3.1) of 3419 // that class. The argument list is the expression-list within 3420 // the parentheses of the initializer. 3421 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3422 (From->getType()->getAs<RecordType>() && 3423 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3424 ConstructorsOnly = true; 3425 3426 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3427 // We're not going to find any constructors. 3428 } else if (CXXRecordDecl *ToRecordDecl 3429 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3430 3431 Expr **Args = &From; 3432 unsigned NumArgs = 1; 3433 bool ListInitializing = false; 3434 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3435 // But first, see if there is an init-list-constructor that will work. 3436 OverloadingResult Result = IsInitializerListConstructorConversion( 3437 S, From, ToType, ToRecordDecl, User, CandidateSet, 3438 AllowExplicit == AllowedExplicit::All); 3439 if (Result != OR_No_Viable_Function) 3440 return Result; 3441 // Never mind. 3442 CandidateSet.clear( 3443 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3444 3445 // If we're list-initializing, we pass the individual elements as 3446 // arguments, not the entire list. 3447 Args = InitList->getInits(); 3448 NumArgs = InitList->getNumInits(); 3449 ListInitializing = true; 3450 } 3451 3452 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3453 auto Info = getConstructorInfo(D); 3454 if (!Info) 3455 continue; 3456 3457 bool Usable = !Info.Constructor->isInvalidDecl(); 3458 if (!ListInitializing) 3459 Usable = Usable && Info.Constructor->isConvertingConstructor( 3460 /*AllowExplicit*/ true); 3461 if (Usable) { 3462 bool SuppressUserConversions = !ConstructorsOnly; 3463 if (SuppressUserConversions && ListInitializing) { 3464 SuppressUserConversions = false; 3465 if (NumArgs == 1) { 3466 // If the first argument is (a reference to) the target type, 3467 // suppress conversions. 3468 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3469 S.Context, Info.Constructor, ToType); 3470 } 3471 } 3472 if (Info.ConstructorTmpl) 3473 S.AddTemplateOverloadCandidate( 3474 Info.ConstructorTmpl, Info.FoundDecl, 3475 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3476 CandidateSet, SuppressUserConversions, 3477 /*PartialOverloading*/ false, 3478 AllowExplicit == AllowedExplicit::All); 3479 else 3480 // Allow one user-defined conversion when user specifies a 3481 // From->ToType conversion via an static cast (c-style, etc). 3482 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3483 llvm::makeArrayRef(Args, NumArgs), 3484 CandidateSet, SuppressUserConversions, 3485 /*PartialOverloading*/ false, 3486 AllowExplicit == AllowedExplicit::All); 3487 } 3488 } 3489 } 3490 } 3491 3492 // Enumerate conversion functions, if we're allowed to. 3493 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3494 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3495 // No conversion functions from incomplete types. 3496 } else if (const RecordType *FromRecordType = 3497 From->getType()->getAs<RecordType>()) { 3498 if (CXXRecordDecl *FromRecordDecl 3499 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3500 // Add all of the conversion functions as candidates. 3501 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3502 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3503 DeclAccessPair FoundDecl = I.getPair(); 3504 NamedDecl *D = FoundDecl.getDecl(); 3505 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3506 if (isa<UsingShadowDecl>(D)) 3507 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3508 3509 CXXConversionDecl *Conv; 3510 FunctionTemplateDecl *ConvTemplate; 3511 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3512 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3513 else 3514 Conv = cast<CXXConversionDecl>(D); 3515 3516 if (ConvTemplate) 3517 S.AddTemplateConversionCandidate( 3518 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3519 CandidateSet, AllowObjCConversionOnExplicit, 3520 AllowExplicit != AllowedExplicit::None); 3521 else 3522 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3523 CandidateSet, AllowObjCConversionOnExplicit, 3524 AllowExplicit != AllowedExplicit::None); 3525 } 3526 } 3527 } 3528 3529 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3530 3531 OverloadCandidateSet::iterator Best; 3532 switch (auto Result = 3533 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3534 case OR_Success: 3535 case OR_Deleted: 3536 // Record the standard conversion we used and the conversion function. 3537 if (CXXConstructorDecl *Constructor 3538 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3539 // C++ [over.ics.user]p1: 3540 // If the user-defined conversion is specified by a 3541 // constructor (12.3.1), the initial standard conversion 3542 // sequence converts the source type to the type required by 3543 // the argument of the constructor. 3544 // 3545 QualType ThisType = Constructor->getThisType(); 3546 if (isa<InitListExpr>(From)) { 3547 // Initializer lists don't have conversions as such. 3548 User.Before.setAsIdentityConversion(); 3549 } else { 3550 if (Best->Conversions[0].isEllipsis()) 3551 User.EllipsisConversion = true; 3552 else { 3553 User.Before = Best->Conversions[0].Standard; 3554 User.EllipsisConversion = false; 3555 } 3556 } 3557 User.HadMultipleCandidates = HadMultipleCandidates; 3558 User.ConversionFunction = Constructor; 3559 User.FoundConversionFunction = Best->FoundDecl; 3560 User.After.setAsIdentityConversion(); 3561 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3562 User.After.setAllToTypes(ToType); 3563 return Result; 3564 } 3565 if (CXXConversionDecl *Conversion 3566 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3567 // C++ [over.ics.user]p1: 3568 // 3569 // [...] If the user-defined conversion is specified by a 3570 // conversion function (12.3.2), the initial standard 3571 // conversion sequence converts the source type to the 3572 // implicit object parameter of the conversion function. 3573 User.Before = Best->Conversions[0].Standard; 3574 User.HadMultipleCandidates = HadMultipleCandidates; 3575 User.ConversionFunction = Conversion; 3576 User.FoundConversionFunction = Best->FoundDecl; 3577 User.EllipsisConversion = false; 3578 3579 // C++ [over.ics.user]p2: 3580 // The second standard conversion sequence converts the 3581 // result of the user-defined conversion to the target type 3582 // for the sequence. Since an implicit conversion sequence 3583 // is an initialization, the special rules for 3584 // initialization by user-defined conversion apply when 3585 // selecting the best user-defined conversion for a 3586 // user-defined conversion sequence (see 13.3.3 and 3587 // 13.3.3.1). 3588 User.After = Best->FinalConversion; 3589 return Result; 3590 } 3591 llvm_unreachable("Not a constructor or conversion function?"); 3592 3593 case OR_No_Viable_Function: 3594 return OR_No_Viable_Function; 3595 3596 case OR_Ambiguous: 3597 return OR_Ambiguous; 3598 } 3599 3600 llvm_unreachable("Invalid OverloadResult!"); 3601 } 3602 3603 bool 3604 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3605 ImplicitConversionSequence ICS; 3606 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3607 OverloadCandidateSet::CSK_Normal); 3608 OverloadingResult OvResult = 3609 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3610 CandidateSet, AllowedExplicit::None, false); 3611 3612 if (!(OvResult == OR_Ambiguous || 3613 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3614 return false; 3615 3616 auto Cands = CandidateSet.CompleteCandidates( 3617 *this, 3618 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3619 From); 3620 if (OvResult == OR_Ambiguous) 3621 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3622 << From->getType() << ToType << From->getSourceRange(); 3623 else { // OR_No_Viable_Function && !CandidateSet.empty() 3624 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3625 diag::err_typecheck_nonviable_condition_incomplete, 3626 From->getType(), From->getSourceRange())) 3627 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3628 << false << From->getType() << From->getSourceRange() << ToType; 3629 } 3630 3631 CandidateSet.NoteCandidates( 3632 *this, From, Cands); 3633 return true; 3634 } 3635 3636 /// Compare the user-defined conversion functions or constructors 3637 /// of two user-defined conversion sequences to determine whether any ordering 3638 /// is possible. 3639 static ImplicitConversionSequence::CompareKind 3640 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3641 FunctionDecl *Function2) { 3642 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3643 return ImplicitConversionSequence::Indistinguishable; 3644 3645 // Objective-C++: 3646 // If both conversion functions are implicitly-declared conversions from 3647 // a lambda closure type to a function pointer and a block pointer, 3648 // respectively, always prefer the conversion to a function pointer, 3649 // because the function pointer is more lightweight and is more likely 3650 // to keep code working. 3651 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3652 if (!Conv1) 3653 return ImplicitConversionSequence::Indistinguishable; 3654 3655 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3656 if (!Conv2) 3657 return ImplicitConversionSequence::Indistinguishable; 3658 3659 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3660 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3661 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3662 if (Block1 != Block2) 3663 return Block1 ? ImplicitConversionSequence::Worse 3664 : ImplicitConversionSequence::Better; 3665 } 3666 3667 return ImplicitConversionSequence::Indistinguishable; 3668 } 3669 3670 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3671 const ImplicitConversionSequence &ICS) { 3672 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3673 (ICS.isUserDefined() && 3674 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3675 } 3676 3677 /// CompareImplicitConversionSequences - Compare two implicit 3678 /// conversion sequences to determine whether one is better than the 3679 /// other or if they are indistinguishable (C++ 13.3.3.2). 3680 static ImplicitConversionSequence::CompareKind 3681 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3682 const ImplicitConversionSequence& ICS1, 3683 const ImplicitConversionSequence& ICS2) 3684 { 3685 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3686 // conversion sequences (as defined in 13.3.3.1) 3687 // -- a standard conversion sequence (13.3.3.1.1) is a better 3688 // conversion sequence than a user-defined conversion sequence or 3689 // an ellipsis conversion sequence, and 3690 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3691 // conversion sequence than an ellipsis conversion sequence 3692 // (13.3.3.1.3). 3693 // 3694 // C++0x [over.best.ics]p10: 3695 // For the purpose of ranking implicit conversion sequences as 3696 // described in 13.3.3.2, the ambiguous conversion sequence is 3697 // treated as a user-defined sequence that is indistinguishable 3698 // from any other user-defined conversion sequence. 3699 3700 // String literal to 'char *' conversion has been deprecated in C++03. It has 3701 // been removed from C++11. We still accept this conversion, if it happens at 3702 // the best viable function. Otherwise, this conversion is considered worse 3703 // than ellipsis conversion. Consider this as an extension; this is not in the 3704 // standard. For example: 3705 // 3706 // int &f(...); // #1 3707 // void f(char*); // #2 3708 // void g() { int &r = f("foo"); } 3709 // 3710 // In C++03, we pick #2 as the best viable function. 3711 // In C++11, we pick #1 as the best viable function, because ellipsis 3712 // conversion is better than string-literal to char* conversion (since there 3713 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3714 // convert arguments, #2 would be the best viable function in C++11. 3715 // If the best viable function has this conversion, a warning will be issued 3716 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3717 3718 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3719 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3720 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3721 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3722 ? ImplicitConversionSequence::Worse 3723 : ImplicitConversionSequence::Better; 3724 3725 if (ICS1.getKindRank() < ICS2.getKindRank()) 3726 return ImplicitConversionSequence::Better; 3727 if (ICS2.getKindRank() < ICS1.getKindRank()) 3728 return ImplicitConversionSequence::Worse; 3729 3730 // The following checks require both conversion sequences to be of 3731 // the same kind. 3732 if (ICS1.getKind() != ICS2.getKind()) 3733 return ImplicitConversionSequence::Indistinguishable; 3734 3735 ImplicitConversionSequence::CompareKind Result = 3736 ImplicitConversionSequence::Indistinguishable; 3737 3738 // Two implicit conversion sequences of the same form are 3739 // indistinguishable conversion sequences unless one of the 3740 // following rules apply: (C++ 13.3.3.2p3): 3741 3742 // List-initialization sequence L1 is a better conversion sequence than 3743 // list-initialization sequence L2 if: 3744 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3745 // if not that, 3746 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3747 // and N1 is smaller than N2., 3748 // even if one of the other rules in this paragraph would otherwise apply. 3749 if (!ICS1.isBad()) { 3750 if (ICS1.isStdInitializerListElement() && 3751 !ICS2.isStdInitializerListElement()) 3752 return ImplicitConversionSequence::Better; 3753 if (!ICS1.isStdInitializerListElement() && 3754 ICS2.isStdInitializerListElement()) 3755 return ImplicitConversionSequence::Worse; 3756 } 3757 3758 if (ICS1.isStandard()) 3759 // Standard conversion sequence S1 is a better conversion sequence than 3760 // standard conversion sequence S2 if [...] 3761 Result = CompareStandardConversionSequences(S, Loc, 3762 ICS1.Standard, ICS2.Standard); 3763 else if (ICS1.isUserDefined()) { 3764 // User-defined conversion sequence U1 is a better conversion 3765 // sequence than another user-defined conversion sequence U2 if 3766 // they contain the same user-defined conversion function or 3767 // constructor and if the second standard conversion sequence of 3768 // U1 is better than the second standard conversion sequence of 3769 // U2 (C++ 13.3.3.2p3). 3770 if (ICS1.UserDefined.ConversionFunction == 3771 ICS2.UserDefined.ConversionFunction) 3772 Result = CompareStandardConversionSequences(S, Loc, 3773 ICS1.UserDefined.After, 3774 ICS2.UserDefined.After); 3775 else 3776 Result = compareConversionFunctions(S, 3777 ICS1.UserDefined.ConversionFunction, 3778 ICS2.UserDefined.ConversionFunction); 3779 } 3780 3781 return Result; 3782 } 3783 3784 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3785 // determine if one is a proper subset of the other. 3786 static ImplicitConversionSequence::CompareKind 3787 compareStandardConversionSubsets(ASTContext &Context, 3788 const StandardConversionSequence& SCS1, 3789 const StandardConversionSequence& SCS2) { 3790 ImplicitConversionSequence::CompareKind Result 3791 = ImplicitConversionSequence::Indistinguishable; 3792 3793 // the identity conversion sequence is considered to be a subsequence of 3794 // any non-identity conversion sequence 3795 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3796 return ImplicitConversionSequence::Better; 3797 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3798 return ImplicitConversionSequence::Worse; 3799 3800 if (SCS1.Second != SCS2.Second) { 3801 if (SCS1.Second == ICK_Identity) 3802 Result = ImplicitConversionSequence::Better; 3803 else if (SCS2.Second == ICK_Identity) 3804 Result = ImplicitConversionSequence::Worse; 3805 else 3806 return ImplicitConversionSequence::Indistinguishable; 3807 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3808 return ImplicitConversionSequence::Indistinguishable; 3809 3810 if (SCS1.Third == SCS2.Third) { 3811 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3812 : ImplicitConversionSequence::Indistinguishable; 3813 } 3814 3815 if (SCS1.Third == ICK_Identity) 3816 return Result == ImplicitConversionSequence::Worse 3817 ? ImplicitConversionSequence::Indistinguishable 3818 : ImplicitConversionSequence::Better; 3819 3820 if (SCS2.Third == ICK_Identity) 3821 return Result == ImplicitConversionSequence::Better 3822 ? ImplicitConversionSequence::Indistinguishable 3823 : ImplicitConversionSequence::Worse; 3824 3825 return ImplicitConversionSequence::Indistinguishable; 3826 } 3827 3828 /// Determine whether one of the given reference bindings is better 3829 /// than the other based on what kind of bindings they are. 3830 static bool 3831 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3832 const StandardConversionSequence &SCS2) { 3833 // C++0x [over.ics.rank]p3b4: 3834 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3835 // implicit object parameter of a non-static member function declared 3836 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3837 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3838 // lvalue reference to a function lvalue and S2 binds an rvalue 3839 // reference*. 3840 // 3841 // FIXME: Rvalue references. We're going rogue with the above edits, 3842 // because the semantics in the current C++0x working paper (N3225 at the 3843 // time of this writing) break the standard definition of std::forward 3844 // and std::reference_wrapper when dealing with references to functions. 3845 // Proposed wording changes submitted to CWG for consideration. 3846 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3847 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3848 return false; 3849 3850 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3851 SCS2.IsLvalueReference) || 3852 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3853 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3854 } 3855 3856 enum class FixedEnumPromotion { 3857 None, 3858 ToUnderlyingType, 3859 ToPromotedUnderlyingType 3860 }; 3861 3862 /// Returns kind of fixed enum promotion the \a SCS uses. 3863 static FixedEnumPromotion 3864 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3865 3866 if (SCS.Second != ICK_Integral_Promotion) 3867 return FixedEnumPromotion::None; 3868 3869 QualType FromType = SCS.getFromType(); 3870 if (!FromType->isEnumeralType()) 3871 return FixedEnumPromotion::None; 3872 3873 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3874 if (!Enum->isFixed()) 3875 return FixedEnumPromotion::None; 3876 3877 QualType UnderlyingType = Enum->getIntegerType(); 3878 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3879 return FixedEnumPromotion::ToUnderlyingType; 3880 3881 return FixedEnumPromotion::ToPromotedUnderlyingType; 3882 } 3883 3884 /// CompareStandardConversionSequences - Compare two standard 3885 /// conversion sequences to determine whether one is better than the 3886 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3887 static ImplicitConversionSequence::CompareKind 3888 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3889 const StandardConversionSequence& SCS1, 3890 const StandardConversionSequence& SCS2) 3891 { 3892 // Standard conversion sequence S1 is a better conversion sequence 3893 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3894 3895 // -- S1 is a proper subsequence of S2 (comparing the conversion 3896 // sequences in the canonical form defined by 13.3.3.1.1, 3897 // excluding any Lvalue Transformation; the identity conversion 3898 // sequence is considered to be a subsequence of any 3899 // non-identity conversion sequence) or, if not that, 3900 if (ImplicitConversionSequence::CompareKind CK 3901 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3902 return CK; 3903 3904 // -- the rank of S1 is better than the rank of S2 (by the rules 3905 // defined below), or, if not that, 3906 ImplicitConversionRank Rank1 = SCS1.getRank(); 3907 ImplicitConversionRank Rank2 = SCS2.getRank(); 3908 if (Rank1 < Rank2) 3909 return ImplicitConversionSequence::Better; 3910 else if (Rank2 < Rank1) 3911 return ImplicitConversionSequence::Worse; 3912 3913 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3914 // are indistinguishable unless one of the following rules 3915 // applies: 3916 3917 // A conversion that is not a conversion of a pointer, or 3918 // pointer to member, to bool is better than another conversion 3919 // that is such a conversion. 3920 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3921 return SCS2.isPointerConversionToBool() 3922 ? ImplicitConversionSequence::Better 3923 : ImplicitConversionSequence::Worse; 3924 3925 // C++14 [over.ics.rank]p4b2: 3926 // This is retroactively applied to C++11 by CWG 1601. 3927 // 3928 // A conversion that promotes an enumeration whose underlying type is fixed 3929 // to its underlying type is better than one that promotes to the promoted 3930 // underlying type, if the two are different. 3931 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3932 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3933 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3934 FEP1 != FEP2) 3935 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3936 ? ImplicitConversionSequence::Better 3937 : ImplicitConversionSequence::Worse; 3938 3939 // C++ [over.ics.rank]p4b2: 3940 // 3941 // If class B is derived directly or indirectly from class A, 3942 // conversion of B* to A* is better than conversion of B* to 3943 // void*, and conversion of A* to void* is better than conversion 3944 // of B* to void*. 3945 bool SCS1ConvertsToVoid 3946 = SCS1.isPointerConversionToVoidPointer(S.Context); 3947 bool SCS2ConvertsToVoid 3948 = SCS2.isPointerConversionToVoidPointer(S.Context); 3949 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3950 // Exactly one of the conversion sequences is a conversion to 3951 // a void pointer; it's the worse conversion. 3952 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3953 : ImplicitConversionSequence::Worse; 3954 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3955 // Neither conversion sequence converts to a void pointer; compare 3956 // their derived-to-base conversions. 3957 if (ImplicitConversionSequence::CompareKind DerivedCK 3958 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3959 return DerivedCK; 3960 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3961 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3962 // Both conversion sequences are conversions to void 3963 // pointers. Compare the source types to determine if there's an 3964 // inheritance relationship in their sources. 3965 QualType FromType1 = SCS1.getFromType(); 3966 QualType FromType2 = SCS2.getFromType(); 3967 3968 // Adjust the types we're converting from via the array-to-pointer 3969 // conversion, if we need to. 3970 if (SCS1.First == ICK_Array_To_Pointer) 3971 FromType1 = S.Context.getArrayDecayedType(FromType1); 3972 if (SCS2.First == ICK_Array_To_Pointer) 3973 FromType2 = S.Context.getArrayDecayedType(FromType2); 3974 3975 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3976 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3977 3978 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3979 return ImplicitConversionSequence::Better; 3980 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3981 return ImplicitConversionSequence::Worse; 3982 3983 // Objective-C++: If one interface is more specific than the 3984 // other, it is the better one. 3985 const ObjCObjectPointerType* FromObjCPtr1 3986 = FromType1->getAs<ObjCObjectPointerType>(); 3987 const ObjCObjectPointerType* FromObjCPtr2 3988 = FromType2->getAs<ObjCObjectPointerType>(); 3989 if (FromObjCPtr1 && FromObjCPtr2) { 3990 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3991 FromObjCPtr2); 3992 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3993 FromObjCPtr1); 3994 if (AssignLeft != AssignRight) { 3995 return AssignLeft? ImplicitConversionSequence::Better 3996 : ImplicitConversionSequence::Worse; 3997 } 3998 } 3999 } 4000 4001 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4002 // Check for a better reference binding based on the kind of bindings. 4003 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4004 return ImplicitConversionSequence::Better; 4005 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4006 return ImplicitConversionSequence::Worse; 4007 } 4008 4009 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4010 // bullet 3). 4011 if (ImplicitConversionSequence::CompareKind QualCK 4012 = CompareQualificationConversions(S, SCS1, SCS2)) 4013 return QualCK; 4014 4015 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4016 // C++ [over.ics.rank]p3b4: 4017 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4018 // which the references refer are the same type except for 4019 // top-level cv-qualifiers, and the type to which the reference 4020 // initialized by S2 refers is more cv-qualified than the type 4021 // to which the reference initialized by S1 refers. 4022 QualType T1 = SCS1.getToType(2); 4023 QualType T2 = SCS2.getToType(2); 4024 T1 = S.Context.getCanonicalType(T1); 4025 T2 = S.Context.getCanonicalType(T2); 4026 Qualifiers T1Quals, T2Quals; 4027 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4028 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4029 if (UnqualT1 == UnqualT2) { 4030 // Objective-C++ ARC: If the references refer to objects with different 4031 // lifetimes, prefer bindings that don't change lifetime. 4032 if (SCS1.ObjCLifetimeConversionBinding != 4033 SCS2.ObjCLifetimeConversionBinding) { 4034 return SCS1.ObjCLifetimeConversionBinding 4035 ? ImplicitConversionSequence::Worse 4036 : ImplicitConversionSequence::Better; 4037 } 4038 4039 // If the type is an array type, promote the element qualifiers to the 4040 // type for comparison. 4041 if (isa<ArrayType>(T1) && T1Quals) 4042 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4043 if (isa<ArrayType>(T2) && T2Quals) 4044 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4045 if (T2.isMoreQualifiedThan(T1)) 4046 return ImplicitConversionSequence::Better; 4047 if (T1.isMoreQualifiedThan(T2)) 4048 return ImplicitConversionSequence::Worse; 4049 } 4050 } 4051 4052 // In Microsoft mode, prefer an integral conversion to a 4053 // floating-to-integral conversion if the integral conversion 4054 // is between types of the same size. 4055 // For example: 4056 // void f(float); 4057 // void f(int); 4058 // int main { 4059 // long a; 4060 // f(a); 4061 // } 4062 // Here, MSVC will call f(int) instead of generating a compile error 4063 // as clang will do in standard mode. 4064 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 4065 SCS2.Second == ICK_Floating_Integral && 4066 S.Context.getTypeSize(SCS1.getFromType()) == 4067 S.Context.getTypeSize(SCS1.getToType(2))) 4068 return ImplicitConversionSequence::Better; 4069 4070 // Prefer a compatible vector conversion over a lax vector conversion 4071 // For example: 4072 // 4073 // typedef float __v4sf __attribute__((__vector_size__(16))); 4074 // void f(vector float); 4075 // void f(vector signed int); 4076 // int main() { 4077 // __v4sf a; 4078 // f(a); 4079 // } 4080 // Here, we'd like to choose f(vector float) and not 4081 // report an ambiguous call error 4082 if (SCS1.Second == ICK_Vector_Conversion && 4083 SCS2.Second == ICK_Vector_Conversion) { 4084 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4085 SCS1.getFromType(), SCS1.getToType(2)); 4086 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4087 SCS2.getFromType(), SCS2.getToType(2)); 4088 4089 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4090 return SCS1IsCompatibleVectorConversion 4091 ? ImplicitConversionSequence::Better 4092 : ImplicitConversionSequence::Worse; 4093 } 4094 4095 return ImplicitConversionSequence::Indistinguishable; 4096 } 4097 4098 /// CompareQualificationConversions - Compares two standard conversion 4099 /// sequences to determine whether they can be ranked based on their 4100 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4101 static ImplicitConversionSequence::CompareKind 4102 CompareQualificationConversions(Sema &S, 4103 const StandardConversionSequence& SCS1, 4104 const StandardConversionSequence& SCS2) { 4105 // C++ 13.3.3.2p3: 4106 // -- S1 and S2 differ only in their qualification conversion and 4107 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4108 // cv-qualification signature of type T1 is a proper subset of 4109 // the cv-qualification signature of type T2, and S1 is not the 4110 // deprecated string literal array-to-pointer conversion (4.2). 4111 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4112 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4113 return ImplicitConversionSequence::Indistinguishable; 4114 4115 // FIXME: the example in the standard doesn't use a qualification 4116 // conversion (!) 4117 QualType T1 = SCS1.getToType(2); 4118 QualType T2 = SCS2.getToType(2); 4119 T1 = S.Context.getCanonicalType(T1); 4120 T2 = S.Context.getCanonicalType(T2); 4121 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4122 Qualifiers T1Quals, T2Quals; 4123 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4124 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4125 4126 // If the types are the same, we won't learn anything by unwrapping 4127 // them. 4128 if (UnqualT1 == UnqualT2) 4129 return ImplicitConversionSequence::Indistinguishable; 4130 4131 ImplicitConversionSequence::CompareKind Result 4132 = ImplicitConversionSequence::Indistinguishable; 4133 4134 // Objective-C++ ARC: 4135 // Prefer qualification conversions not involving a change in lifetime 4136 // to qualification conversions that do not change lifetime. 4137 if (SCS1.QualificationIncludesObjCLifetime != 4138 SCS2.QualificationIncludesObjCLifetime) { 4139 Result = SCS1.QualificationIncludesObjCLifetime 4140 ? ImplicitConversionSequence::Worse 4141 : ImplicitConversionSequence::Better; 4142 } 4143 4144 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4145 // Within each iteration of the loop, we check the qualifiers to 4146 // determine if this still looks like a qualification 4147 // conversion. Then, if all is well, we unwrap one more level of 4148 // pointers or pointers-to-members and do it all again 4149 // until there are no more pointers or pointers-to-members left 4150 // to unwrap. This essentially mimics what 4151 // IsQualificationConversion does, but here we're checking for a 4152 // strict subset of qualifiers. 4153 if (T1.getQualifiers().withoutObjCLifetime() == 4154 T2.getQualifiers().withoutObjCLifetime()) 4155 // The qualifiers are the same, so this doesn't tell us anything 4156 // about how the sequences rank. 4157 // ObjC ownership quals are omitted above as they interfere with 4158 // the ARC overload rule. 4159 ; 4160 else if (T2.isMoreQualifiedThan(T1)) { 4161 // T1 has fewer qualifiers, so it could be the better sequence. 4162 if (Result == ImplicitConversionSequence::Worse) 4163 // Neither has qualifiers that are a subset of the other's 4164 // qualifiers. 4165 return ImplicitConversionSequence::Indistinguishable; 4166 4167 Result = ImplicitConversionSequence::Better; 4168 } else if (T1.isMoreQualifiedThan(T2)) { 4169 // T2 has fewer qualifiers, so it could be the better sequence. 4170 if (Result == ImplicitConversionSequence::Better) 4171 // Neither has qualifiers that are a subset of the other's 4172 // qualifiers. 4173 return ImplicitConversionSequence::Indistinguishable; 4174 4175 Result = ImplicitConversionSequence::Worse; 4176 } else { 4177 // Qualifiers are disjoint. 4178 return ImplicitConversionSequence::Indistinguishable; 4179 } 4180 4181 // If the types after this point are equivalent, we're done. 4182 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4183 break; 4184 } 4185 4186 // Check that the winning standard conversion sequence isn't using 4187 // the deprecated string literal array to pointer conversion. 4188 switch (Result) { 4189 case ImplicitConversionSequence::Better: 4190 if (SCS1.DeprecatedStringLiteralToCharPtr) 4191 Result = ImplicitConversionSequence::Indistinguishable; 4192 break; 4193 4194 case ImplicitConversionSequence::Indistinguishable: 4195 break; 4196 4197 case ImplicitConversionSequence::Worse: 4198 if (SCS2.DeprecatedStringLiteralToCharPtr) 4199 Result = ImplicitConversionSequence::Indistinguishable; 4200 break; 4201 } 4202 4203 return Result; 4204 } 4205 4206 /// CompareDerivedToBaseConversions - Compares two standard conversion 4207 /// sequences to determine whether they can be ranked based on their 4208 /// various kinds of derived-to-base conversions (C++ 4209 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4210 /// conversions between Objective-C interface types. 4211 static ImplicitConversionSequence::CompareKind 4212 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4213 const StandardConversionSequence& SCS1, 4214 const StandardConversionSequence& SCS2) { 4215 QualType FromType1 = SCS1.getFromType(); 4216 QualType ToType1 = SCS1.getToType(1); 4217 QualType FromType2 = SCS2.getFromType(); 4218 QualType ToType2 = SCS2.getToType(1); 4219 4220 // Adjust the types we're converting from via the array-to-pointer 4221 // conversion, if we need to. 4222 if (SCS1.First == ICK_Array_To_Pointer) 4223 FromType1 = S.Context.getArrayDecayedType(FromType1); 4224 if (SCS2.First == ICK_Array_To_Pointer) 4225 FromType2 = S.Context.getArrayDecayedType(FromType2); 4226 4227 // Canonicalize all of the types. 4228 FromType1 = S.Context.getCanonicalType(FromType1); 4229 ToType1 = S.Context.getCanonicalType(ToType1); 4230 FromType2 = S.Context.getCanonicalType(FromType2); 4231 ToType2 = S.Context.getCanonicalType(ToType2); 4232 4233 // C++ [over.ics.rank]p4b3: 4234 // 4235 // If class B is derived directly or indirectly from class A and 4236 // class C is derived directly or indirectly from B, 4237 // 4238 // Compare based on pointer conversions. 4239 if (SCS1.Second == ICK_Pointer_Conversion && 4240 SCS2.Second == ICK_Pointer_Conversion && 4241 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4242 FromType1->isPointerType() && FromType2->isPointerType() && 4243 ToType1->isPointerType() && ToType2->isPointerType()) { 4244 QualType FromPointee1 = 4245 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4246 QualType ToPointee1 = 4247 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4248 QualType FromPointee2 = 4249 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4250 QualType ToPointee2 = 4251 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4252 4253 // -- conversion of C* to B* is better than conversion of C* to A*, 4254 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4255 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4256 return ImplicitConversionSequence::Better; 4257 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4258 return ImplicitConversionSequence::Worse; 4259 } 4260 4261 // -- conversion of B* to A* is better than conversion of C* to A*, 4262 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4263 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4264 return ImplicitConversionSequence::Better; 4265 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4266 return ImplicitConversionSequence::Worse; 4267 } 4268 } else if (SCS1.Second == ICK_Pointer_Conversion && 4269 SCS2.Second == ICK_Pointer_Conversion) { 4270 const ObjCObjectPointerType *FromPtr1 4271 = FromType1->getAs<ObjCObjectPointerType>(); 4272 const ObjCObjectPointerType *FromPtr2 4273 = FromType2->getAs<ObjCObjectPointerType>(); 4274 const ObjCObjectPointerType *ToPtr1 4275 = ToType1->getAs<ObjCObjectPointerType>(); 4276 const ObjCObjectPointerType *ToPtr2 4277 = ToType2->getAs<ObjCObjectPointerType>(); 4278 4279 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4280 // Apply the same conversion ranking rules for Objective-C pointer types 4281 // that we do for C++ pointers to class types. However, we employ the 4282 // Objective-C pseudo-subtyping relationship used for assignment of 4283 // Objective-C pointer types. 4284 bool FromAssignLeft 4285 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4286 bool FromAssignRight 4287 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4288 bool ToAssignLeft 4289 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4290 bool ToAssignRight 4291 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4292 4293 // A conversion to an a non-id object pointer type or qualified 'id' 4294 // type is better than a conversion to 'id'. 4295 if (ToPtr1->isObjCIdType() && 4296 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4297 return ImplicitConversionSequence::Worse; 4298 if (ToPtr2->isObjCIdType() && 4299 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4300 return ImplicitConversionSequence::Better; 4301 4302 // A conversion to a non-id object pointer type is better than a 4303 // conversion to a qualified 'id' type 4304 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4305 return ImplicitConversionSequence::Worse; 4306 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4307 return ImplicitConversionSequence::Better; 4308 4309 // A conversion to an a non-Class object pointer type or qualified 'Class' 4310 // type is better than a conversion to 'Class'. 4311 if (ToPtr1->isObjCClassType() && 4312 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4313 return ImplicitConversionSequence::Worse; 4314 if (ToPtr2->isObjCClassType() && 4315 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4316 return ImplicitConversionSequence::Better; 4317 4318 // A conversion to a non-Class object pointer type is better than a 4319 // conversion to a qualified 'Class' type. 4320 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4321 return ImplicitConversionSequence::Worse; 4322 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4323 return ImplicitConversionSequence::Better; 4324 4325 // -- "conversion of C* to B* is better than conversion of C* to A*," 4326 if (S.Context.hasSameType(FromType1, FromType2) && 4327 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4328 (ToAssignLeft != ToAssignRight)) { 4329 if (FromPtr1->isSpecialized()) { 4330 // "conversion of B<A> * to B * is better than conversion of B * to 4331 // C *. 4332 bool IsFirstSame = 4333 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4334 bool IsSecondSame = 4335 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4336 if (IsFirstSame) { 4337 if (!IsSecondSame) 4338 return ImplicitConversionSequence::Better; 4339 } else if (IsSecondSame) 4340 return ImplicitConversionSequence::Worse; 4341 } 4342 return ToAssignLeft? ImplicitConversionSequence::Worse 4343 : ImplicitConversionSequence::Better; 4344 } 4345 4346 // -- "conversion of B* to A* is better than conversion of C* to A*," 4347 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4348 (FromAssignLeft != FromAssignRight)) 4349 return FromAssignLeft? ImplicitConversionSequence::Better 4350 : ImplicitConversionSequence::Worse; 4351 } 4352 } 4353 4354 // Ranking of member-pointer types. 4355 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4356 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4357 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4358 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4359 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4360 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4361 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4362 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4363 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4364 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4365 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4366 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4367 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4368 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4369 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4370 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4371 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4372 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4373 return ImplicitConversionSequence::Worse; 4374 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4375 return ImplicitConversionSequence::Better; 4376 } 4377 // conversion of B::* to C::* is better than conversion of A::* to C::* 4378 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4379 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4380 return ImplicitConversionSequence::Better; 4381 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4382 return ImplicitConversionSequence::Worse; 4383 } 4384 } 4385 4386 if (SCS1.Second == ICK_Derived_To_Base) { 4387 // -- conversion of C to B is better than conversion of C to A, 4388 // -- binding of an expression of type C to a reference of type 4389 // B& is better than binding an expression of type C to a 4390 // reference of type A&, 4391 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4392 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4393 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4394 return ImplicitConversionSequence::Better; 4395 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4396 return ImplicitConversionSequence::Worse; 4397 } 4398 4399 // -- conversion of B to A is better than conversion of C to A. 4400 // -- binding of an expression of type B to a reference of type 4401 // A& is better than binding an expression of type C to a 4402 // reference of type A&, 4403 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4404 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4405 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4406 return ImplicitConversionSequence::Better; 4407 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4408 return ImplicitConversionSequence::Worse; 4409 } 4410 } 4411 4412 return ImplicitConversionSequence::Indistinguishable; 4413 } 4414 4415 /// Determine whether the given type is valid, e.g., it is not an invalid 4416 /// C++ class. 4417 static bool isTypeValid(QualType T) { 4418 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4419 return !Record->isInvalidDecl(); 4420 4421 return true; 4422 } 4423 4424 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4425 if (!T.getQualifiers().hasUnaligned()) 4426 return T; 4427 4428 Qualifiers Q; 4429 T = Ctx.getUnqualifiedArrayType(T, Q); 4430 Q.removeUnaligned(); 4431 return Ctx.getQualifiedType(T, Q); 4432 } 4433 4434 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4435 /// determine whether they are reference-compatible, 4436 /// reference-related, or incompatible, for use in C++ initialization by 4437 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4438 /// type, and the first type (T1) is the pointee type of the reference 4439 /// type being initialized. 4440 Sema::ReferenceCompareResult 4441 Sema::CompareReferenceRelationship(SourceLocation Loc, 4442 QualType OrigT1, QualType OrigT2, 4443 ReferenceConversions *ConvOut) { 4444 assert(!OrigT1->isReferenceType() && 4445 "T1 must be the pointee type of the reference type"); 4446 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4447 4448 QualType T1 = Context.getCanonicalType(OrigT1); 4449 QualType T2 = Context.getCanonicalType(OrigT2); 4450 Qualifiers T1Quals, T2Quals; 4451 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4452 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4453 4454 ReferenceConversions ConvTmp; 4455 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4456 Conv = ReferenceConversions(); 4457 4458 // C++2a [dcl.init.ref]p4: 4459 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4460 // reference-related to "cv2 T2" if T1 is similar to T2, or 4461 // T1 is a base class of T2. 4462 // "cv1 T1" is reference-compatible with "cv2 T2" if 4463 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4464 // "pointer to cv1 T1" via a standard conversion sequence. 4465 4466 // Check for standard conversions we can apply to pointers: derived-to-base 4467 // conversions, ObjC pointer conversions, and function pointer conversions. 4468 // (Qualification conversions are checked last.) 4469 QualType ConvertedT2; 4470 if (UnqualT1 == UnqualT2) { 4471 // Nothing to do. 4472 } else if (isCompleteType(Loc, OrigT2) && 4473 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4474 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4475 Conv |= ReferenceConversions::DerivedToBase; 4476 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4477 UnqualT2->isObjCObjectOrInterfaceType() && 4478 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4479 Conv |= ReferenceConversions::ObjC; 4480 else if (UnqualT2->isFunctionType() && 4481 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4482 Conv |= ReferenceConversions::Function; 4483 // No need to check qualifiers; function types don't have them. 4484 return Ref_Compatible; 4485 } 4486 bool ConvertedReferent = Conv != 0; 4487 4488 // We can have a qualification conversion. Compute whether the types are 4489 // similar at the same time. 4490 bool PreviousToQualsIncludeConst = true; 4491 bool TopLevel = true; 4492 do { 4493 if (T1 == T2) 4494 break; 4495 4496 // We will need a qualification conversion. 4497 Conv |= ReferenceConversions::Qualification; 4498 4499 // Track whether we performed a qualification conversion anywhere other 4500 // than the top level. This matters for ranking reference bindings in 4501 // overload resolution. 4502 if (!TopLevel) 4503 Conv |= ReferenceConversions::NestedQualification; 4504 4505 // MS compiler ignores __unaligned qualifier for references; do the same. 4506 T1 = withoutUnaligned(Context, T1); 4507 T2 = withoutUnaligned(Context, T2); 4508 4509 // If we find a qualifier mismatch, the types are not reference-compatible, 4510 // but are still be reference-related if they're similar. 4511 bool ObjCLifetimeConversion = false; 4512 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4513 PreviousToQualsIncludeConst, 4514 ObjCLifetimeConversion)) 4515 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4516 ? Ref_Related 4517 : Ref_Incompatible; 4518 4519 // FIXME: Should we track this for any level other than the first? 4520 if (ObjCLifetimeConversion) 4521 Conv |= ReferenceConversions::ObjCLifetime; 4522 4523 TopLevel = false; 4524 } while (Context.UnwrapSimilarTypes(T1, T2)); 4525 4526 // At this point, if the types are reference-related, we must either have the 4527 // same inner type (ignoring qualifiers), or must have already worked out how 4528 // to convert the referent. 4529 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4530 ? Ref_Compatible 4531 : Ref_Incompatible; 4532 } 4533 4534 /// Look for a user-defined conversion to a value reference-compatible 4535 /// with DeclType. Return true if something definite is found. 4536 static bool 4537 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4538 QualType DeclType, SourceLocation DeclLoc, 4539 Expr *Init, QualType T2, bool AllowRvalues, 4540 bool AllowExplicit) { 4541 assert(T2->isRecordType() && "Can only find conversions of record types."); 4542 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4543 4544 OverloadCandidateSet CandidateSet( 4545 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4546 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4547 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4548 NamedDecl *D = *I; 4549 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4550 if (isa<UsingShadowDecl>(D)) 4551 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4552 4553 FunctionTemplateDecl *ConvTemplate 4554 = dyn_cast<FunctionTemplateDecl>(D); 4555 CXXConversionDecl *Conv; 4556 if (ConvTemplate) 4557 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4558 else 4559 Conv = cast<CXXConversionDecl>(D); 4560 4561 if (AllowRvalues) { 4562 // If we are initializing an rvalue reference, don't permit conversion 4563 // functions that return lvalues. 4564 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4565 const ReferenceType *RefType 4566 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4567 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4568 continue; 4569 } 4570 4571 if (!ConvTemplate && 4572 S.CompareReferenceRelationship( 4573 DeclLoc, 4574 Conv->getConversionType() 4575 .getNonReferenceType() 4576 .getUnqualifiedType(), 4577 DeclType.getNonReferenceType().getUnqualifiedType()) == 4578 Sema::Ref_Incompatible) 4579 continue; 4580 } else { 4581 // If the conversion function doesn't return a reference type, 4582 // it can't be considered for this conversion. An rvalue reference 4583 // is only acceptable if its referencee is a function type. 4584 4585 const ReferenceType *RefType = 4586 Conv->getConversionType()->getAs<ReferenceType>(); 4587 if (!RefType || 4588 (!RefType->isLValueReferenceType() && 4589 !RefType->getPointeeType()->isFunctionType())) 4590 continue; 4591 } 4592 4593 if (ConvTemplate) 4594 S.AddTemplateConversionCandidate( 4595 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4596 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4597 else 4598 S.AddConversionCandidate( 4599 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4600 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4601 } 4602 4603 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4604 4605 OverloadCandidateSet::iterator Best; 4606 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4607 case OR_Success: 4608 // C++ [over.ics.ref]p1: 4609 // 4610 // [...] If the parameter binds directly to the result of 4611 // applying a conversion function to the argument 4612 // expression, the implicit conversion sequence is a 4613 // user-defined conversion sequence (13.3.3.1.2), with the 4614 // second standard conversion sequence either an identity 4615 // conversion or, if the conversion function returns an 4616 // entity of a type that is a derived class of the parameter 4617 // type, a derived-to-base Conversion. 4618 if (!Best->FinalConversion.DirectBinding) 4619 return false; 4620 4621 ICS.setUserDefined(); 4622 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4623 ICS.UserDefined.After = Best->FinalConversion; 4624 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4625 ICS.UserDefined.ConversionFunction = Best->Function; 4626 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4627 ICS.UserDefined.EllipsisConversion = false; 4628 assert(ICS.UserDefined.After.ReferenceBinding && 4629 ICS.UserDefined.After.DirectBinding && 4630 "Expected a direct reference binding!"); 4631 return true; 4632 4633 case OR_Ambiguous: 4634 ICS.setAmbiguous(); 4635 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4636 Cand != CandidateSet.end(); ++Cand) 4637 if (Cand->Best) 4638 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4639 return true; 4640 4641 case OR_No_Viable_Function: 4642 case OR_Deleted: 4643 // There was no suitable conversion, or we found a deleted 4644 // conversion; continue with other checks. 4645 return false; 4646 } 4647 4648 llvm_unreachable("Invalid OverloadResult!"); 4649 } 4650 4651 /// Compute an implicit conversion sequence for reference 4652 /// initialization. 4653 static ImplicitConversionSequence 4654 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4655 SourceLocation DeclLoc, 4656 bool SuppressUserConversions, 4657 bool AllowExplicit) { 4658 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4659 4660 // Most paths end in a failed conversion. 4661 ImplicitConversionSequence ICS; 4662 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4663 4664 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4665 QualType T2 = Init->getType(); 4666 4667 // If the initializer is the address of an overloaded function, try 4668 // to resolve the overloaded function. If all goes well, T2 is the 4669 // type of the resulting function. 4670 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4671 DeclAccessPair Found; 4672 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4673 false, Found)) 4674 T2 = Fn->getType(); 4675 } 4676 4677 // Compute some basic properties of the types and the initializer. 4678 bool isRValRef = DeclType->isRValueReferenceType(); 4679 Expr::Classification InitCategory = Init->Classify(S.Context); 4680 4681 Sema::ReferenceConversions RefConv; 4682 Sema::ReferenceCompareResult RefRelationship = 4683 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4684 4685 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4686 ICS.setStandard(); 4687 ICS.Standard.First = ICK_Identity; 4688 // FIXME: A reference binding can be a function conversion too. We should 4689 // consider that when ordering reference-to-function bindings. 4690 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4691 ? ICK_Derived_To_Base 4692 : (RefConv & Sema::ReferenceConversions::ObjC) 4693 ? ICK_Compatible_Conversion 4694 : ICK_Identity; 4695 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4696 // a reference binding that performs a non-top-level qualification 4697 // conversion as a qualification conversion, not as an identity conversion. 4698 ICS.Standard.Third = (RefConv & 4699 Sema::ReferenceConversions::NestedQualification) 4700 ? ICK_Qualification 4701 : ICK_Identity; 4702 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4703 ICS.Standard.setToType(0, T2); 4704 ICS.Standard.setToType(1, T1); 4705 ICS.Standard.setToType(2, T1); 4706 ICS.Standard.ReferenceBinding = true; 4707 ICS.Standard.DirectBinding = BindsDirectly; 4708 ICS.Standard.IsLvalueReference = !isRValRef; 4709 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4710 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4711 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4712 ICS.Standard.ObjCLifetimeConversionBinding = 4713 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4714 ICS.Standard.CopyConstructor = nullptr; 4715 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4716 }; 4717 4718 // C++0x [dcl.init.ref]p5: 4719 // A reference to type "cv1 T1" is initialized by an expression 4720 // of type "cv2 T2" as follows: 4721 4722 // -- If reference is an lvalue reference and the initializer expression 4723 if (!isRValRef) { 4724 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4725 // reference-compatible with "cv2 T2," or 4726 // 4727 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4728 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4729 // C++ [over.ics.ref]p1: 4730 // When a parameter of reference type binds directly (8.5.3) 4731 // to an argument expression, the implicit conversion sequence 4732 // is the identity conversion, unless the argument expression 4733 // has a type that is a derived class of the parameter type, 4734 // in which case the implicit conversion sequence is a 4735 // derived-to-base Conversion (13.3.3.1). 4736 SetAsReferenceBinding(/*BindsDirectly=*/true); 4737 4738 // Nothing more to do: the inaccessibility/ambiguity check for 4739 // derived-to-base conversions is suppressed when we're 4740 // computing the implicit conversion sequence (C++ 4741 // [over.best.ics]p2). 4742 return ICS; 4743 } 4744 4745 // -- has a class type (i.e., T2 is a class type), where T1 is 4746 // not reference-related to T2, and can be implicitly 4747 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4748 // is reference-compatible with "cv3 T3" 92) (this 4749 // conversion is selected by enumerating the applicable 4750 // conversion functions (13.3.1.6) and choosing the best 4751 // one through overload resolution (13.3)), 4752 if (!SuppressUserConversions && T2->isRecordType() && 4753 S.isCompleteType(DeclLoc, T2) && 4754 RefRelationship == Sema::Ref_Incompatible) { 4755 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4756 Init, T2, /*AllowRvalues=*/false, 4757 AllowExplicit)) 4758 return ICS; 4759 } 4760 } 4761 4762 // -- Otherwise, the reference shall be an lvalue reference to a 4763 // non-volatile const type (i.e., cv1 shall be const), or the reference 4764 // shall be an rvalue reference. 4765 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4766 return ICS; 4767 4768 // -- If the initializer expression 4769 // 4770 // -- is an xvalue, class prvalue, array prvalue or function 4771 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4772 if (RefRelationship == Sema::Ref_Compatible && 4773 (InitCategory.isXValue() || 4774 (InitCategory.isPRValue() && 4775 (T2->isRecordType() || T2->isArrayType())) || 4776 (InitCategory.isLValue() && T2->isFunctionType()))) { 4777 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4778 // binding unless we're binding to a class prvalue. 4779 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4780 // allow the use of rvalue references in C++98/03 for the benefit of 4781 // standard library implementors; therefore, we need the xvalue check here. 4782 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4783 !(InitCategory.isPRValue() || T2->isRecordType())); 4784 return ICS; 4785 } 4786 4787 // -- has a class type (i.e., T2 is a class type), where T1 is not 4788 // reference-related to T2, and can be implicitly converted to 4789 // an xvalue, class prvalue, or function lvalue of type 4790 // "cv3 T3", where "cv1 T1" is reference-compatible with 4791 // "cv3 T3", 4792 // 4793 // then the reference is bound to the value of the initializer 4794 // expression in the first case and to the result of the conversion 4795 // in the second case (or, in either case, to an appropriate base 4796 // class subobject). 4797 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4798 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4799 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4800 Init, T2, /*AllowRvalues=*/true, 4801 AllowExplicit)) { 4802 // In the second case, if the reference is an rvalue reference 4803 // and the second standard conversion sequence of the 4804 // user-defined conversion sequence includes an lvalue-to-rvalue 4805 // conversion, the program is ill-formed. 4806 if (ICS.isUserDefined() && isRValRef && 4807 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4808 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4809 4810 return ICS; 4811 } 4812 4813 // A temporary of function type cannot be created; don't even try. 4814 if (T1->isFunctionType()) 4815 return ICS; 4816 4817 // -- Otherwise, a temporary of type "cv1 T1" is created and 4818 // initialized from the initializer expression using the 4819 // rules for a non-reference copy initialization (8.5). The 4820 // reference is then bound to the temporary. If T1 is 4821 // reference-related to T2, cv1 must be the same 4822 // cv-qualification as, or greater cv-qualification than, 4823 // cv2; otherwise, the program is ill-formed. 4824 if (RefRelationship == Sema::Ref_Related) { 4825 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4826 // we would be reference-compatible or reference-compatible with 4827 // added qualification. But that wasn't the case, so the reference 4828 // initialization fails. 4829 // 4830 // Note that we only want to check address spaces and cvr-qualifiers here. 4831 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4832 Qualifiers T1Quals = T1.getQualifiers(); 4833 Qualifiers T2Quals = T2.getQualifiers(); 4834 T1Quals.removeObjCGCAttr(); 4835 T1Quals.removeObjCLifetime(); 4836 T2Quals.removeObjCGCAttr(); 4837 T2Quals.removeObjCLifetime(); 4838 // MS compiler ignores __unaligned qualifier for references; do the same. 4839 T1Quals.removeUnaligned(); 4840 T2Quals.removeUnaligned(); 4841 if (!T1Quals.compatiblyIncludes(T2Quals)) 4842 return ICS; 4843 } 4844 4845 // If at least one of the types is a class type, the types are not 4846 // related, and we aren't allowed any user conversions, the 4847 // reference binding fails. This case is important for breaking 4848 // recursion, since TryImplicitConversion below will attempt to 4849 // create a temporary through the use of a copy constructor. 4850 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4851 (T1->isRecordType() || T2->isRecordType())) 4852 return ICS; 4853 4854 // If T1 is reference-related to T2 and the reference is an rvalue 4855 // reference, the initializer expression shall not be an lvalue. 4856 if (RefRelationship >= Sema::Ref_Related && 4857 isRValRef && Init->Classify(S.Context).isLValue()) 4858 return ICS; 4859 4860 // C++ [over.ics.ref]p2: 4861 // When a parameter of reference type is not bound directly to 4862 // an argument expression, the conversion sequence is the one 4863 // required to convert the argument expression to the 4864 // underlying type of the reference according to 4865 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4866 // to copy-initializing a temporary of the underlying type with 4867 // the argument expression. Any difference in top-level 4868 // cv-qualification is subsumed by the initialization itself 4869 // and does not constitute a conversion. 4870 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4871 AllowedExplicit::None, 4872 /*InOverloadResolution=*/false, 4873 /*CStyle=*/false, 4874 /*AllowObjCWritebackConversion=*/false, 4875 /*AllowObjCConversionOnExplicit=*/false); 4876 4877 // Of course, that's still a reference binding. 4878 if (ICS.isStandard()) { 4879 ICS.Standard.ReferenceBinding = true; 4880 ICS.Standard.IsLvalueReference = !isRValRef; 4881 ICS.Standard.BindsToFunctionLvalue = false; 4882 ICS.Standard.BindsToRvalue = true; 4883 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4884 ICS.Standard.ObjCLifetimeConversionBinding = false; 4885 } else if (ICS.isUserDefined()) { 4886 const ReferenceType *LValRefType = 4887 ICS.UserDefined.ConversionFunction->getReturnType() 4888 ->getAs<LValueReferenceType>(); 4889 4890 // C++ [over.ics.ref]p3: 4891 // Except for an implicit object parameter, for which see 13.3.1, a 4892 // standard conversion sequence cannot be formed if it requires [...] 4893 // binding an rvalue reference to an lvalue other than a function 4894 // lvalue. 4895 // Note that the function case is not possible here. 4896 if (DeclType->isRValueReferenceType() && LValRefType) { 4897 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4898 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4899 // reference to an rvalue! 4900 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4901 return ICS; 4902 } 4903 4904 ICS.UserDefined.After.ReferenceBinding = true; 4905 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4906 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4907 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4908 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4909 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4910 } 4911 4912 return ICS; 4913 } 4914 4915 static ImplicitConversionSequence 4916 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4917 bool SuppressUserConversions, 4918 bool InOverloadResolution, 4919 bool AllowObjCWritebackConversion, 4920 bool AllowExplicit = false); 4921 4922 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4923 /// initializer list From. 4924 static ImplicitConversionSequence 4925 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4926 bool SuppressUserConversions, 4927 bool InOverloadResolution, 4928 bool AllowObjCWritebackConversion) { 4929 // C++11 [over.ics.list]p1: 4930 // When an argument is an initializer list, it is not an expression and 4931 // special rules apply for converting it to a parameter type. 4932 4933 ImplicitConversionSequence Result; 4934 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4935 4936 // We need a complete type for what follows. Incomplete types can never be 4937 // initialized from init lists. 4938 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4939 return Result; 4940 4941 // Per DR1467: 4942 // If the parameter type is a class X and the initializer list has a single 4943 // element of type cv U, where U is X or a class derived from X, the 4944 // implicit conversion sequence is the one required to convert the element 4945 // to the parameter type. 4946 // 4947 // Otherwise, if the parameter type is a character array [... ] 4948 // and the initializer list has a single element that is an 4949 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4950 // implicit conversion sequence is the identity conversion. 4951 if (From->getNumInits() == 1) { 4952 if (ToType->isRecordType()) { 4953 QualType InitType = From->getInit(0)->getType(); 4954 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4955 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4956 return TryCopyInitialization(S, From->getInit(0), ToType, 4957 SuppressUserConversions, 4958 InOverloadResolution, 4959 AllowObjCWritebackConversion); 4960 } 4961 // FIXME: Check the other conditions here: array of character type, 4962 // initializer is a string literal. 4963 if (ToType->isArrayType()) { 4964 InitializedEntity Entity = 4965 InitializedEntity::InitializeParameter(S.Context, ToType, 4966 /*Consumed=*/false); 4967 if (S.CanPerformCopyInitialization(Entity, From)) { 4968 Result.setStandard(); 4969 Result.Standard.setAsIdentityConversion(); 4970 Result.Standard.setFromType(ToType); 4971 Result.Standard.setAllToTypes(ToType); 4972 return Result; 4973 } 4974 } 4975 } 4976 4977 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4978 // C++11 [over.ics.list]p2: 4979 // If the parameter type is std::initializer_list<X> or "array of X" and 4980 // all the elements can be implicitly converted to X, the implicit 4981 // conversion sequence is the worst conversion necessary to convert an 4982 // element of the list to X. 4983 // 4984 // C++14 [over.ics.list]p3: 4985 // Otherwise, if the parameter type is "array of N X", if the initializer 4986 // list has exactly N elements or if it has fewer than N elements and X is 4987 // default-constructible, and if all the elements of the initializer list 4988 // can be implicitly converted to X, the implicit conversion sequence is 4989 // the worst conversion necessary to convert an element of the list to X. 4990 // 4991 // FIXME: We're missing a lot of these checks. 4992 bool toStdInitializerList = false; 4993 QualType X; 4994 if (ToType->isArrayType()) 4995 X = S.Context.getAsArrayType(ToType)->getElementType(); 4996 else 4997 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4998 if (!X.isNull()) { 4999 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 5000 Expr *Init = From->getInit(i); 5001 ImplicitConversionSequence ICS = 5002 TryCopyInitialization(S, Init, X, SuppressUserConversions, 5003 InOverloadResolution, 5004 AllowObjCWritebackConversion); 5005 // If a single element isn't convertible, fail. 5006 if (ICS.isBad()) { 5007 Result = ICS; 5008 break; 5009 } 5010 // Otherwise, look for the worst conversion. 5011 if (Result.isBad() || CompareImplicitConversionSequences( 5012 S, From->getBeginLoc(), ICS, Result) == 5013 ImplicitConversionSequence::Worse) 5014 Result = ICS; 5015 } 5016 5017 // For an empty list, we won't have computed any conversion sequence. 5018 // Introduce the identity conversion sequence. 5019 if (From->getNumInits() == 0) { 5020 Result.setStandard(); 5021 Result.Standard.setAsIdentityConversion(); 5022 Result.Standard.setFromType(ToType); 5023 Result.Standard.setAllToTypes(ToType); 5024 } 5025 5026 Result.setStdInitializerListElement(toStdInitializerList); 5027 return Result; 5028 } 5029 5030 // C++14 [over.ics.list]p4: 5031 // C++11 [over.ics.list]p3: 5032 // Otherwise, if the parameter is a non-aggregate class X and overload 5033 // resolution chooses a single best constructor [...] the implicit 5034 // conversion sequence is a user-defined conversion sequence. If multiple 5035 // constructors are viable but none is better than the others, the 5036 // implicit conversion sequence is a user-defined conversion sequence. 5037 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5038 // This function can deal with initializer lists. 5039 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5040 AllowedExplicit::None, 5041 InOverloadResolution, /*CStyle=*/false, 5042 AllowObjCWritebackConversion, 5043 /*AllowObjCConversionOnExplicit=*/false); 5044 } 5045 5046 // C++14 [over.ics.list]p5: 5047 // C++11 [over.ics.list]p4: 5048 // Otherwise, if the parameter has an aggregate type which can be 5049 // initialized from the initializer list [...] the implicit conversion 5050 // sequence is a user-defined conversion sequence. 5051 if (ToType->isAggregateType()) { 5052 // Type is an aggregate, argument is an init list. At this point it comes 5053 // down to checking whether the initialization works. 5054 // FIXME: Find out whether this parameter is consumed or not. 5055 InitializedEntity Entity = 5056 InitializedEntity::InitializeParameter(S.Context, ToType, 5057 /*Consumed=*/false); 5058 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5059 From)) { 5060 Result.setUserDefined(); 5061 Result.UserDefined.Before.setAsIdentityConversion(); 5062 // Initializer lists don't have a type. 5063 Result.UserDefined.Before.setFromType(QualType()); 5064 Result.UserDefined.Before.setAllToTypes(QualType()); 5065 5066 Result.UserDefined.After.setAsIdentityConversion(); 5067 Result.UserDefined.After.setFromType(ToType); 5068 Result.UserDefined.After.setAllToTypes(ToType); 5069 Result.UserDefined.ConversionFunction = nullptr; 5070 } 5071 return Result; 5072 } 5073 5074 // C++14 [over.ics.list]p6: 5075 // C++11 [over.ics.list]p5: 5076 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5077 if (ToType->isReferenceType()) { 5078 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5079 // mention initializer lists in any way. So we go by what list- 5080 // initialization would do and try to extrapolate from that. 5081 5082 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5083 5084 // If the initializer list has a single element that is reference-related 5085 // to the parameter type, we initialize the reference from that. 5086 if (From->getNumInits() == 1) { 5087 Expr *Init = From->getInit(0); 5088 5089 QualType T2 = Init->getType(); 5090 5091 // If the initializer is the address of an overloaded function, try 5092 // to resolve the overloaded function. If all goes well, T2 is the 5093 // type of the resulting function. 5094 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5095 DeclAccessPair Found; 5096 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5097 Init, ToType, false, Found)) 5098 T2 = Fn->getType(); 5099 } 5100 5101 // Compute some basic properties of the types and the initializer. 5102 Sema::ReferenceCompareResult RefRelationship = 5103 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5104 5105 if (RefRelationship >= Sema::Ref_Related) { 5106 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5107 SuppressUserConversions, 5108 /*AllowExplicit=*/false); 5109 } 5110 } 5111 5112 // Otherwise, we bind the reference to a temporary created from the 5113 // initializer list. 5114 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5115 InOverloadResolution, 5116 AllowObjCWritebackConversion); 5117 if (Result.isFailure()) 5118 return Result; 5119 assert(!Result.isEllipsis() && 5120 "Sub-initialization cannot result in ellipsis conversion."); 5121 5122 // Can we even bind to a temporary? 5123 if (ToType->isRValueReferenceType() || 5124 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5125 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5126 Result.UserDefined.After; 5127 SCS.ReferenceBinding = true; 5128 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5129 SCS.BindsToRvalue = true; 5130 SCS.BindsToFunctionLvalue = false; 5131 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5132 SCS.ObjCLifetimeConversionBinding = false; 5133 } else 5134 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5135 From, ToType); 5136 return Result; 5137 } 5138 5139 // C++14 [over.ics.list]p7: 5140 // C++11 [over.ics.list]p6: 5141 // Otherwise, if the parameter type is not a class: 5142 if (!ToType->isRecordType()) { 5143 // - if the initializer list has one element that is not itself an 5144 // initializer list, the implicit conversion sequence is the one 5145 // required to convert the element to the parameter type. 5146 unsigned NumInits = From->getNumInits(); 5147 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5148 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5149 SuppressUserConversions, 5150 InOverloadResolution, 5151 AllowObjCWritebackConversion); 5152 // - if the initializer list has no elements, the implicit conversion 5153 // sequence is the identity conversion. 5154 else if (NumInits == 0) { 5155 Result.setStandard(); 5156 Result.Standard.setAsIdentityConversion(); 5157 Result.Standard.setFromType(ToType); 5158 Result.Standard.setAllToTypes(ToType); 5159 } 5160 return Result; 5161 } 5162 5163 // C++14 [over.ics.list]p8: 5164 // C++11 [over.ics.list]p7: 5165 // In all cases other than those enumerated above, no conversion is possible 5166 return Result; 5167 } 5168 5169 /// TryCopyInitialization - Try to copy-initialize a value of type 5170 /// ToType from the expression From. Return the implicit conversion 5171 /// sequence required to pass this argument, which may be a bad 5172 /// conversion sequence (meaning that the argument cannot be passed to 5173 /// a parameter of this type). If @p SuppressUserConversions, then we 5174 /// do not permit any user-defined conversion sequences. 5175 static ImplicitConversionSequence 5176 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5177 bool SuppressUserConversions, 5178 bool InOverloadResolution, 5179 bool AllowObjCWritebackConversion, 5180 bool AllowExplicit) { 5181 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5182 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5183 InOverloadResolution,AllowObjCWritebackConversion); 5184 5185 if (ToType->isReferenceType()) 5186 return TryReferenceInit(S, From, ToType, 5187 /*FIXME:*/ From->getBeginLoc(), 5188 SuppressUserConversions, AllowExplicit); 5189 5190 return TryImplicitConversion(S, From, ToType, 5191 SuppressUserConversions, 5192 AllowedExplicit::None, 5193 InOverloadResolution, 5194 /*CStyle=*/false, 5195 AllowObjCWritebackConversion, 5196 /*AllowObjCConversionOnExplicit=*/false); 5197 } 5198 5199 static bool TryCopyInitialization(const CanQualType FromQTy, 5200 const CanQualType ToQTy, 5201 Sema &S, 5202 SourceLocation Loc, 5203 ExprValueKind FromVK) { 5204 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5205 ImplicitConversionSequence ICS = 5206 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5207 5208 return !ICS.isBad(); 5209 } 5210 5211 /// TryObjectArgumentInitialization - Try to initialize the object 5212 /// parameter of the given member function (@c Method) from the 5213 /// expression @p From. 5214 static ImplicitConversionSequence 5215 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5216 Expr::Classification FromClassification, 5217 CXXMethodDecl *Method, 5218 CXXRecordDecl *ActingContext) { 5219 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5220 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5221 // const volatile object. 5222 Qualifiers Quals = Method->getMethodQualifiers(); 5223 if (isa<CXXDestructorDecl>(Method)) { 5224 Quals.addConst(); 5225 Quals.addVolatile(); 5226 } 5227 5228 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5229 5230 // Set up the conversion sequence as a "bad" conversion, to allow us 5231 // to exit early. 5232 ImplicitConversionSequence ICS; 5233 5234 // We need to have an object of class type. 5235 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5236 FromType = PT->getPointeeType(); 5237 5238 // When we had a pointer, it's implicitly dereferenced, so we 5239 // better have an lvalue. 5240 assert(FromClassification.isLValue()); 5241 } 5242 5243 assert(FromType->isRecordType()); 5244 5245 // C++0x [over.match.funcs]p4: 5246 // For non-static member functions, the type of the implicit object 5247 // parameter is 5248 // 5249 // - "lvalue reference to cv X" for functions declared without a 5250 // ref-qualifier or with the & ref-qualifier 5251 // - "rvalue reference to cv X" for functions declared with the && 5252 // ref-qualifier 5253 // 5254 // where X is the class of which the function is a member and cv is the 5255 // cv-qualification on the member function declaration. 5256 // 5257 // However, when finding an implicit conversion sequence for the argument, we 5258 // are not allowed to perform user-defined conversions 5259 // (C++ [over.match.funcs]p5). We perform a simplified version of 5260 // reference binding here, that allows class rvalues to bind to 5261 // non-constant references. 5262 5263 // First check the qualifiers. 5264 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5265 if (ImplicitParamType.getCVRQualifiers() 5266 != FromTypeCanon.getLocalCVRQualifiers() && 5267 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5268 ICS.setBad(BadConversionSequence::bad_qualifiers, 5269 FromType, ImplicitParamType); 5270 return ICS; 5271 } 5272 5273 if (FromTypeCanon.hasAddressSpace()) { 5274 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5275 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5276 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5277 ICS.setBad(BadConversionSequence::bad_qualifiers, 5278 FromType, ImplicitParamType); 5279 return ICS; 5280 } 5281 } 5282 5283 // Check that we have either the same type or a derived type. It 5284 // affects the conversion rank. 5285 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5286 ImplicitConversionKind SecondKind; 5287 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5288 SecondKind = ICK_Identity; 5289 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5290 SecondKind = ICK_Derived_To_Base; 5291 else { 5292 ICS.setBad(BadConversionSequence::unrelated_class, 5293 FromType, ImplicitParamType); 5294 return ICS; 5295 } 5296 5297 // Check the ref-qualifier. 5298 switch (Method->getRefQualifier()) { 5299 case RQ_None: 5300 // Do nothing; we don't care about lvalueness or rvalueness. 5301 break; 5302 5303 case RQ_LValue: 5304 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5305 // non-const lvalue reference cannot bind to an rvalue 5306 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5307 ImplicitParamType); 5308 return ICS; 5309 } 5310 break; 5311 5312 case RQ_RValue: 5313 if (!FromClassification.isRValue()) { 5314 // rvalue reference cannot bind to an lvalue 5315 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5316 ImplicitParamType); 5317 return ICS; 5318 } 5319 break; 5320 } 5321 5322 // Success. Mark this as a reference binding. 5323 ICS.setStandard(); 5324 ICS.Standard.setAsIdentityConversion(); 5325 ICS.Standard.Second = SecondKind; 5326 ICS.Standard.setFromType(FromType); 5327 ICS.Standard.setAllToTypes(ImplicitParamType); 5328 ICS.Standard.ReferenceBinding = true; 5329 ICS.Standard.DirectBinding = true; 5330 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5331 ICS.Standard.BindsToFunctionLvalue = false; 5332 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5333 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5334 = (Method->getRefQualifier() == RQ_None); 5335 return ICS; 5336 } 5337 5338 /// PerformObjectArgumentInitialization - Perform initialization of 5339 /// the implicit object parameter for the given Method with the given 5340 /// expression. 5341 ExprResult 5342 Sema::PerformObjectArgumentInitialization(Expr *From, 5343 NestedNameSpecifier *Qualifier, 5344 NamedDecl *FoundDecl, 5345 CXXMethodDecl *Method) { 5346 QualType FromRecordType, DestType; 5347 QualType ImplicitParamRecordType = 5348 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5349 5350 Expr::Classification FromClassification; 5351 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5352 FromRecordType = PT->getPointeeType(); 5353 DestType = Method->getThisType(); 5354 FromClassification = Expr::Classification::makeSimpleLValue(); 5355 } else { 5356 FromRecordType = From->getType(); 5357 DestType = ImplicitParamRecordType; 5358 FromClassification = From->Classify(Context); 5359 5360 // When performing member access on an rvalue, materialize a temporary. 5361 if (From->isRValue()) { 5362 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5363 Method->getRefQualifier() != 5364 RefQualifierKind::RQ_RValue); 5365 } 5366 } 5367 5368 // Note that we always use the true parent context when performing 5369 // the actual argument initialization. 5370 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5371 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5372 Method->getParent()); 5373 if (ICS.isBad()) { 5374 switch (ICS.Bad.Kind) { 5375 case BadConversionSequence::bad_qualifiers: { 5376 Qualifiers FromQs = FromRecordType.getQualifiers(); 5377 Qualifiers ToQs = DestType.getQualifiers(); 5378 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5379 if (CVR) { 5380 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5381 << Method->getDeclName() << FromRecordType << (CVR - 1) 5382 << From->getSourceRange(); 5383 Diag(Method->getLocation(), diag::note_previous_decl) 5384 << Method->getDeclName(); 5385 return ExprError(); 5386 } 5387 break; 5388 } 5389 5390 case BadConversionSequence::lvalue_ref_to_rvalue: 5391 case BadConversionSequence::rvalue_ref_to_lvalue: { 5392 bool IsRValueQualified = 5393 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5394 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5395 << Method->getDeclName() << FromClassification.isRValue() 5396 << IsRValueQualified; 5397 Diag(Method->getLocation(), diag::note_previous_decl) 5398 << Method->getDeclName(); 5399 return ExprError(); 5400 } 5401 5402 case BadConversionSequence::no_conversion: 5403 case BadConversionSequence::unrelated_class: 5404 break; 5405 } 5406 5407 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5408 << ImplicitParamRecordType << FromRecordType 5409 << From->getSourceRange(); 5410 } 5411 5412 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5413 ExprResult FromRes = 5414 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5415 if (FromRes.isInvalid()) 5416 return ExprError(); 5417 From = FromRes.get(); 5418 } 5419 5420 if (!Context.hasSameType(From->getType(), DestType)) { 5421 CastKind CK; 5422 QualType PteeTy = DestType->getPointeeType(); 5423 LangAS DestAS = 5424 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5425 if (FromRecordType.getAddressSpace() != DestAS) 5426 CK = CK_AddressSpaceConversion; 5427 else 5428 CK = CK_NoOp; 5429 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5430 } 5431 return From; 5432 } 5433 5434 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5435 /// expression From to bool (C++0x [conv]p3). 5436 static ImplicitConversionSequence 5437 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5438 // C++ [dcl.init]/17.8: 5439 // - Otherwise, if the initialization is direct-initialization, the source 5440 // type is std::nullptr_t, and the destination type is bool, the initial 5441 // value of the object being initialized is false. 5442 if (From->getType()->isNullPtrType()) 5443 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5444 S.Context.BoolTy, 5445 From->isGLValue()); 5446 5447 // All other direct-initialization of bool is equivalent to an implicit 5448 // conversion to bool in which explicit conversions are permitted. 5449 return TryImplicitConversion(S, From, S.Context.BoolTy, 5450 /*SuppressUserConversions=*/false, 5451 AllowedExplicit::Conversions, 5452 /*InOverloadResolution=*/false, 5453 /*CStyle=*/false, 5454 /*AllowObjCWritebackConversion=*/false, 5455 /*AllowObjCConversionOnExplicit=*/false); 5456 } 5457 5458 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5459 /// of the expression From to bool (C++0x [conv]p3). 5460 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5461 if (checkPlaceholderForOverload(*this, From)) 5462 return ExprError(); 5463 5464 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5465 if (!ICS.isBad()) 5466 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5467 5468 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5469 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5470 << From->getType() << From->getSourceRange(); 5471 return ExprError(); 5472 } 5473 5474 /// Check that the specified conversion is permitted in a converted constant 5475 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5476 /// is acceptable. 5477 static bool CheckConvertedConstantConversions(Sema &S, 5478 StandardConversionSequence &SCS) { 5479 // Since we know that the target type is an integral or unscoped enumeration 5480 // type, most conversion kinds are impossible. All possible First and Third 5481 // conversions are fine. 5482 switch (SCS.Second) { 5483 case ICK_Identity: 5484 case ICK_Function_Conversion: 5485 case ICK_Integral_Promotion: 5486 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5487 case ICK_Zero_Queue_Conversion: 5488 return true; 5489 5490 case ICK_Boolean_Conversion: 5491 // Conversion from an integral or unscoped enumeration type to bool is 5492 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5493 // conversion, so we allow it in a converted constant expression. 5494 // 5495 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5496 // a lot of popular code. We should at least add a warning for this 5497 // (non-conforming) extension. 5498 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5499 SCS.getToType(2)->isBooleanType(); 5500 5501 case ICK_Pointer_Conversion: 5502 case ICK_Pointer_Member: 5503 // C++1z: null pointer conversions and null member pointer conversions are 5504 // only permitted if the source type is std::nullptr_t. 5505 return SCS.getFromType()->isNullPtrType(); 5506 5507 case ICK_Floating_Promotion: 5508 case ICK_Complex_Promotion: 5509 case ICK_Floating_Conversion: 5510 case ICK_Complex_Conversion: 5511 case ICK_Floating_Integral: 5512 case ICK_Compatible_Conversion: 5513 case ICK_Derived_To_Base: 5514 case ICK_Vector_Conversion: 5515 case ICK_Vector_Splat: 5516 case ICK_Complex_Real: 5517 case ICK_Block_Pointer_Conversion: 5518 case ICK_TransparentUnionConversion: 5519 case ICK_Writeback_Conversion: 5520 case ICK_Zero_Event_Conversion: 5521 case ICK_C_Only_Conversion: 5522 case ICK_Incompatible_Pointer_Conversion: 5523 return false; 5524 5525 case ICK_Lvalue_To_Rvalue: 5526 case ICK_Array_To_Pointer: 5527 case ICK_Function_To_Pointer: 5528 llvm_unreachable("found a first conversion kind in Second"); 5529 5530 case ICK_Qualification: 5531 llvm_unreachable("found a third conversion kind in Second"); 5532 5533 case ICK_Num_Conversion_Kinds: 5534 break; 5535 } 5536 5537 llvm_unreachable("unknown conversion kind"); 5538 } 5539 5540 /// CheckConvertedConstantExpression - Check that the expression From is a 5541 /// converted constant expression of type T, perform the conversion and produce 5542 /// the converted expression, per C++11 [expr.const]p3. 5543 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5544 QualType T, APValue &Value, 5545 Sema::CCEKind CCE, 5546 bool RequireInt) { 5547 assert(S.getLangOpts().CPlusPlus11 && 5548 "converted constant expression outside C++11"); 5549 5550 if (checkPlaceholderForOverload(S, From)) 5551 return ExprError(); 5552 5553 // C++1z [expr.const]p3: 5554 // A converted constant expression of type T is an expression, 5555 // implicitly converted to type T, where the converted 5556 // expression is a constant expression and the implicit conversion 5557 // sequence contains only [... list of conversions ...]. 5558 // C++1z [stmt.if]p2: 5559 // If the if statement is of the form if constexpr, the value of the 5560 // condition shall be a contextually converted constant expression of type 5561 // bool. 5562 ImplicitConversionSequence ICS = 5563 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5564 ? TryContextuallyConvertToBool(S, From) 5565 : TryCopyInitialization(S, From, T, 5566 /*SuppressUserConversions=*/false, 5567 /*InOverloadResolution=*/false, 5568 /*AllowObjCWritebackConversion=*/false, 5569 /*AllowExplicit=*/false); 5570 StandardConversionSequence *SCS = nullptr; 5571 switch (ICS.getKind()) { 5572 case ImplicitConversionSequence::StandardConversion: 5573 SCS = &ICS.Standard; 5574 break; 5575 case ImplicitConversionSequence::UserDefinedConversion: 5576 // We are converting to a non-class type, so the Before sequence 5577 // must be trivial. 5578 SCS = &ICS.UserDefined.After; 5579 break; 5580 case ImplicitConversionSequence::AmbiguousConversion: 5581 case ImplicitConversionSequence::BadConversion: 5582 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5583 return S.Diag(From->getBeginLoc(), 5584 diag::err_typecheck_converted_constant_expression) 5585 << From->getType() << From->getSourceRange() << T; 5586 return ExprError(); 5587 5588 case ImplicitConversionSequence::EllipsisConversion: 5589 llvm_unreachable("ellipsis conversion in converted constant expression"); 5590 } 5591 5592 // Check that we would only use permitted conversions. 5593 if (!CheckConvertedConstantConversions(S, *SCS)) { 5594 return S.Diag(From->getBeginLoc(), 5595 diag::err_typecheck_converted_constant_expression_disallowed) 5596 << From->getType() << From->getSourceRange() << T; 5597 } 5598 // [...] and where the reference binding (if any) binds directly. 5599 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5600 return S.Diag(From->getBeginLoc(), 5601 diag::err_typecheck_converted_constant_expression_indirect) 5602 << From->getType() << From->getSourceRange() << T; 5603 } 5604 5605 ExprResult Result = 5606 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5607 if (Result.isInvalid()) 5608 return Result; 5609 5610 // C++2a [intro.execution]p5: 5611 // A full-expression is [...] a constant-expression [...] 5612 Result = 5613 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5614 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5615 if (Result.isInvalid()) 5616 return Result; 5617 5618 // Check for a narrowing implicit conversion. 5619 APValue PreNarrowingValue; 5620 QualType PreNarrowingType; 5621 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5622 PreNarrowingType)) { 5623 case NK_Dependent_Narrowing: 5624 // Implicit conversion to a narrower type, but the expression is 5625 // value-dependent so we can't tell whether it's actually narrowing. 5626 case NK_Variable_Narrowing: 5627 // Implicit conversion to a narrower type, and the value is not a constant 5628 // expression. We'll diagnose this in a moment. 5629 case NK_Not_Narrowing: 5630 break; 5631 5632 case NK_Constant_Narrowing: 5633 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5634 << CCE << /*Constant*/ 1 5635 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5636 break; 5637 5638 case NK_Type_Narrowing: 5639 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5640 << CCE << /*Constant*/ 0 << From->getType() << T; 5641 break; 5642 } 5643 5644 if (Result.get()->isValueDependent()) { 5645 Value = APValue(); 5646 return Result; 5647 } 5648 5649 // Check the expression is a constant expression. 5650 SmallVector<PartialDiagnosticAt, 8> Notes; 5651 Expr::EvalResult Eval; 5652 Eval.Diag = &Notes; 5653 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5654 ? Expr::EvaluateForMangling 5655 : Expr::EvaluateForCodeGen; 5656 5657 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5658 (RequireInt && !Eval.Val.isInt())) { 5659 // The expression can't be folded, so we can't keep it at this position in 5660 // the AST. 5661 Result = ExprError(); 5662 } else { 5663 Value = Eval.Val; 5664 5665 if (Notes.empty()) { 5666 // It's a constant expression. 5667 return ConstantExpr::Create(S.Context, Result.get(), Value); 5668 } 5669 } 5670 5671 // It's not a constant expression. Produce an appropriate diagnostic. 5672 if (Notes.size() == 1 && 5673 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5674 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5675 else { 5676 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5677 << CCE << From->getSourceRange(); 5678 for (unsigned I = 0; I < Notes.size(); ++I) 5679 S.Diag(Notes[I].first, Notes[I].second); 5680 } 5681 return ExprError(); 5682 } 5683 5684 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5685 APValue &Value, CCEKind CCE) { 5686 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5687 } 5688 5689 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5690 llvm::APSInt &Value, 5691 CCEKind CCE) { 5692 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5693 5694 APValue V; 5695 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5696 if (!R.isInvalid() && !R.get()->isValueDependent()) 5697 Value = V.getInt(); 5698 return R; 5699 } 5700 5701 5702 /// dropPointerConversions - If the given standard conversion sequence 5703 /// involves any pointer conversions, remove them. This may change 5704 /// the result type of the conversion sequence. 5705 static void dropPointerConversion(StandardConversionSequence &SCS) { 5706 if (SCS.Second == ICK_Pointer_Conversion) { 5707 SCS.Second = ICK_Identity; 5708 SCS.Third = ICK_Identity; 5709 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5710 } 5711 } 5712 5713 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5714 /// convert the expression From to an Objective-C pointer type. 5715 static ImplicitConversionSequence 5716 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5717 // Do an implicit conversion to 'id'. 5718 QualType Ty = S.Context.getObjCIdType(); 5719 ImplicitConversionSequence ICS 5720 = TryImplicitConversion(S, From, Ty, 5721 // FIXME: Are these flags correct? 5722 /*SuppressUserConversions=*/false, 5723 AllowedExplicit::Conversions, 5724 /*InOverloadResolution=*/false, 5725 /*CStyle=*/false, 5726 /*AllowObjCWritebackConversion=*/false, 5727 /*AllowObjCConversionOnExplicit=*/true); 5728 5729 // Strip off any final conversions to 'id'. 5730 switch (ICS.getKind()) { 5731 case ImplicitConversionSequence::BadConversion: 5732 case ImplicitConversionSequence::AmbiguousConversion: 5733 case ImplicitConversionSequence::EllipsisConversion: 5734 break; 5735 5736 case ImplicitConversionSequence::UserDefinedConversion: 5737 dropPointerConversion(ICS.UserDefined.After); 5738 break; 5739 5740 case ImplicitConversionSequence::StandardConversion: 5741 dropPointerConversion(ICS.Standard); 5742 break; 5743 } 5744 5745 return ICS; 5746 } 5747 5748 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5749 /// conversion of the expression From to an Objective-C pointer type. 5750 /// Returns a valid but null ExprResult if no conversion sequence exists. 5751 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5752 if (checkPlaceholderForOverload(*this, From)) 5753 return ExprError(); 5754 5755 QualType Ty = Context.getObjCIdType(); 5756 ImplicitConversionSequence ICS = 5757 TryContextuallyConvertToObjCPointer(*this, From); 5758 if (!ICS.isBad()) 5759 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5760 return ExprResult(); 5761 } 5762 5763 /// Determine whether the provided type is an integral type, or an enumeration 5764 /// type of a permitted flavor. 5765 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5766 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5767 : T->isIntegralOrUnscopedEnumerationType(); 5768 } 5769 5770 static ExprResult 5771 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5772 Sema::ContextualImplicitConverter &Converter, 5773 QualType T, UnresolvedSetImpl &ViableConversions) { 5774 5775 if (Converter.Suppress) 5776 return ExprError(); 5777 5778 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5779 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5780 CXXConversionDecl *Conv = 5781 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5782 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5783 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5784 } 5785 return From; 5786 } 5787 5788 static bool 5789 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5790 Sema::ContextualImplicitConverter &Converter, 5791 QualType T, bool HadMultipleCandidates, 5792 UnresolvedSetImpl &ExplicitConversions) { 5793 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5794 DeclAccessPair Found = ExplicitConversions[0]; 5795 CXXConversionDecl *Conversion = 5796 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5797 5798 // The user probably meant to invoke the given explicit 5799 // conversion; use it. 5800 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5801 std::string TypeStr; 5802 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5803 5804 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5805 << FixItHint::CreateInsertion(From->getBeginLoc(), 5806 "static_cast<" + TypeStr + ">(") 5807 << FixItHint::CreateInsertion( 5808 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5809 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5810 5811 // If we aren't in a SFINAE context, build a call to the 5812 // explicit conversion function. 5813 if (SemaRef.isSFINAEContext()) 5814 return true; 5815 5816 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5817 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5818 HadMultipleCandidates); 5819 if (Result.isInvalid()) 5820 return true; 5821 // Record usage of conversion in an implicit cast. 5822 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5823 CK_UserDefinedConversion, Result.get(), 5824 nullptr, Result.get()->getValueKind()); 5825 } 5826 return false; 5827 } 5828 5829 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5830 Sema::ContextualImplicitConverter &Converter, 5831 QualType T, bool HadMultipleCandidates, 5832 DeclAccessPair &Found) { 5833 CXXConversionDecl *Conversion = 5834 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5835 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5836 5837 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5838 if (!Converter.SuppressConversion) { 5839 if (SemaRef.isSFINAEContext()) 5840 return true; 5841 5842 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5843 << From->getSourceRange(); 5844 } 5845 5846 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5847 HadMultipleCandidates); 5848 if (Result.isInvalid()) 5849 return true; 5850 // Record usage of conversion in an implicit cast. 5851 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5852 CK_UserDefinedConversion, Result.get(), 5853 nullptr, Result.get()->getValueKind()); 5854 return false; 5855 } 5856 5857 static ExprResult finishContextualImplicitConversion( 5858 Sema &SemaRef, SourceLocation Loc, Expr *From, 5859 Sema::ContextualImplicitConverter &Converter) { 5860 if (!Converter.match(From->getType()) && !Converter.Suppress) 5861 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5862 << From->getSourceRange(); 5863 5864 return SemaRef.DefaultLvalueConversion(From); 5865 } 5866 5867 static void 5868 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5869 UnresolvedSetImpl &ViableConversions, 5870 OverloadCandidateSet &CandidateSet) { 5871 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5872 DeclAccessPair FoundDecl = ViableConversions[I]; 5873 NamedDecl *D = FoundDecl.getDecl(); 5874 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5875 if (isa<UsingShadowDecl>(D)) 5876 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5877 5878 CXXConversionDecl *Conv; 5879 FunctionTemplateDecl *ConvTemplate; 5880 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5881 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5882 else 5883 Conv = cast<CXXConversionDecl>(D); 5884 5885 if (ConvTemplate) 5886 SemaRef.AddTemplateConversionCandidate( 5887 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5888 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5889 else 5890 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5891 ToType, CandidateSet, 5892 /*AllowObjCConversionOnExplicit=*/false, 5893 /*AllowExplicit*/ true); 5894 } 5895 } 5896 5897 /// Attempt to convert the given expression to a type which is accepted 5898 /// by the given converter. 5899 /// 5900 /// This routine will attempt to convert an expression of class type to a 5901 /// type accepted by the specified converter. In C++11 and before, the class 5902 /// must have a single non-explicit conversion function converting to a matching 5903 /// type. In C++1y, there can be multiple such conversion functions, but only 5904 /// one target type. 5905 /// 5906 /// \param Loc The source location of the construct that requires the 5907 /// conversion. 5908 /// 5909 /// \param From The expression we're converting from. 5910 /// 5911 /// \param Converter Used to control and diagnose the conversion process. 5912 /// 5913 /// \returns The expression, converted to an integral or enumeration type if 5914 /// successful. 5915 ExprResult Sema::PerformContextualImplicitConversion( 5916 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5917 // We can't perform any more checking for type-dependent expressions. 5918 if (From->isTypeDependent()) 5919 return From; 5920 5921 // Process placeholders immediately. 5922 if (From->hasPlaceholderType()) { 5923 ExprResult result = CheckPlaceholderExpr(From); 5924 if (result.isInvalid()) 5925 return result; 5926 From = result.get(); 5927 } 5928 5929 // If the expression already has a matching type, we're golden. 5930 QualType T = From->getType(); 5931 if (Converter.match(T)) 5932 return DefaultLvalueConversion(From); 5933 5934 // FIXME: Check for missing '()' if T is a function type? 5935 5936 // We can only perform contextual implicit conversions on objects of class 5937 // type. 5938 const RecordType *RecordTy = T->getAs<RecordType>(); 5939 if (!RecordTy || !getLangOpts().CPlusPlus) { 5940 if (!Converter.Suppress) 5941 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5942 return From; 5943 } 5944 5945 // We must have a complete class type. 5946 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5947 ContextualImplicitConverter &Converter; 5948 Expr *From; 5949 5950 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5951 : Converter(Converter), From(From) {} 5952 5953 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5954 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5955 } 5956 } IncompleteDiagnoser(Converter, From); 5957 5958 if (Converter.Suppress ? !isCompleteType(Loc, T) 5959 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5960 return From; 5961 5962 // Look for a conversion to an integral or enumeration type. 5963 UnresolvedSet<4> 5964 ViableConversions; // These are *potentially* viable in C++1y. 5965 UnresolvedSet<4> ExplicitConversions; 5966 const auto &Conversions = 5967 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5968 5969 bool HadMultipleCandidates = 5970 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5971 5972 // To check that there is only one target type, in C++1y: 5973 QualType ToType; 5974 bool HasUniqueTargetType = true; 5975 5976 // Collect explicit or viable (potentially in C++1y) conversions. 5977 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5978 NamedDecl *D = (*I)->getUnderlyingDecl(); 5979 CXXConversionDecl *Conversion; 5980 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5981 if (ConvTemplate) { 5982 if (getLangOpts().CPlusPlus14) 5983 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5984 else 5985 continue; // C++11 does not consider conversion operator templates(?). 5986 } else 5987 Conversion = cast<CXXConversionDecl>(D); 5988 5989 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5990 "Conversion operator templates are considered potentially " 5991 "viable in C++1y"); 5992 5993 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5994 if (Converter.match(CurToType) || ConvTemplate) { 5995 5996 if (Conversion->isExplicit()) { 5997 // FIXME: For C++1y, do we need this restriction? 5998 // cf. diagnoseNoViableConversion() 5999 if (!ConvTemplate) 6000 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6001 } else { 6002 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6003 if (ToType.isNull()) 6004 ToType = CurToType.getUnqualifiedType(); 6005 else if (HasUniqueTargetType && 6006 (CurToType.getUnqualifiedType() != ToType)) 6007 HasUniqueTargetType = false; 6008 } 6009 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6010 } 6011 } 6012 } 6013 6014 if (getLangOpts().CPlusPlus14) { 6015 // C++1y [conv]p6: 6016 // ... An expression e of class type E appearing in such a context 6017 // is said to be contextually implicitly converted to a specified 6018 // type T and is well-formed if and only if e can be implicitly 6019 // converted to a type T that is determined as follows: E is searched 6020 // for conversion functions whose return type is cv T or reference to 6021 // cv T such that T is allowed by the context. There shall be 6022 // exactly one such T. 6023 6024 // If no unique T is found: 6025 if (ToType.isNull()) { 6026 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6027 HadMultipleCandidates, 6028 ExplicitConversions)) 6029 return ExprError(); 6030 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6031 } 6032 6033 // If more than one unique Ts are found: 6034 if (!HasUniqueTargetType) 6035 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6036 ViableConversions); 6037 6038 // If one unique T is found: 6039 // First, build a candidate set from the previously recorded 6040 // potentially viable conversions. 6041 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6042 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6043 CandidateSet); 6044 6045 // Then, perform overload resolution over the candidate set. 6046 OverloadCandidateSet::iterator Best; 6047 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6048 case OR_Success: { 6049 // Apply this conversion. 6050 DeclAccessPair Found = 6051 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6052 if (recordConversion(*this, Loc, From, Converter, T, 6053 HadMultipleCandidates, Found)) 6054 return ExprError(); 6055 break; 6056 } 6057 case OR_Ambiguous: 6058 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6059 ViableConversions); 6060 case OR_No_Viable_Function: 6061 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6062 HadMultipleCandidates, 6063 ExplicitConversions)) 6064 return ExprError(); 6065 LLVM_FALLTHROUGH; 6066 case OR_Deleted: 6067 // We'll complain below about a non-integral condition type. 6068 break; 6069 } 6070 } else { 6071 switch (ViableConversions.size()) { 6072 case 0: { 6073 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6074 HadMultipleCandidates, 6075 ExplicitConversions)) 6076 return ExprError(); 6077 6078 // We'll complain below about a non-integral condition type. 6079 break; 6080 } 6081 case 1: { 6082 // Apply this conversion. 6083 DeclAccessPair Found = ViableConversions[0]; 6084 if (recordConversion(*this, Loc, From, Converter, T, 6085 HadMultipleCandidates, Found)) 6086 return ExprError(); 6087 break; 6088 } 6089 default: 6090 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6091 ViableConversions); 6092 } 6093 } 6094 6095 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6096 } 6097 6098 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6099 /// an acceptable non-member overloaded operator for a call whose 6100 /// arguments have types T1 (and, if non-empty, T2). This routine 6101 /// implements the check in C++ [over.match.oper]p3b2 concerning 6102 /// enumeration types. 6103 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6104 FunctionDecl *Fn, 6105 ArrayRef<Expr *> Args) { 6106 QualType T1 = Args[0]->getType(); 6107 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6108 6109 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6110 return true; 6111 6112 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6113 return true; 6114 6115 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6116 if (Proto->getNumParams() < 1) 6117 return false; 6118 6119 if (T1->isEnumeralType()) { 6120 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6121 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6122 return true; 6123 } 6124 6125 if (Proto->getNumParams() < 2) 6126 return false; 6127 6128 if (!T2.isNull() && T2->isEnumeralType()) { 6129 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6130 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6131 return true; 6132 } 6133 6134 return false; 6135 } 6136 6137 /// AddOverloadCandidate - Adds the given function to the set of 6138 /// candidate functions, using the given function call arguments. If 6139 /// @p SuppressUserConversions, then don't allow user-defined 6140 /// conversions via constructors or conversion operators. 6141 /// 6142 /// \param PartialOverloading true if we are performing "partial" overloading 6143 /// based on an incomplete set of function arguments. This feature is used by 6144 /// code completion. 6145 void Sema::AddOverloadCandidate( 6146 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6147 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6148 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6149 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6150 OverloadCandidateParamOrder PO) { 6151 const FunctionProtoType *Proto 6152 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6153 assert(Proto && "Functions without a prototype cannot be overloaded"); 6154 assert(!Function->getDescribedFunctionTemplate() && 6155 "Use AddTemplateOverloadCandidate for function templates"); 6156 6157 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6158 if (!isa<CXXConstructorDecl>(Method)) { 6159 // If we get here, it's because we're calling a member function 6160 // that is named without a member access expression (e.g., 6161 // "this->f") that was either written explicitly or created 6162 // implicitly. This can happen with a qualified call to a member 6163 // function, e.g., X::f(). We use an empty type for the implied 6164 // object argument (C++ [over.call.func]p3), and the acting context 6165 // is irrelevant. 6166 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6167 Expr::Classification::makeSimpleLValue(), Args, 6168 CandidateSet, SuppressUserConversions, 6169 PartialOverloading, EarlyConversions, PO); 6170 return; 6171 } 6172 // We treat a constructor like a non-member function, since its object 6173 // argument doesn't participate in overload resolution. 6174 } 6175 6176 if (!CandidateSet.isNewCandidate(Function, PO)) 6177 return; 6178 6179 // C++11 [class.copy]p11: [DR1402] 6180 // A defaulted move constructor that is defined as deleted is ignored by 6181 // overload resolution. 6182 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6183 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6184 Constructor->isMoveConstructor()) 6185 return; 6186 6187 // Overload resolution is always an unevaluated context. 6188 EnterExpressionEvaluationContext Unevaluated( 6189 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6190 6191 // C++ [over.match.oper]p3: 6192 // if no operand has a class type, only those non-member functions in the 6193 // lookup set that have a first parameter of type T1 or "reference to 6194 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6195 // is a right operand) a second parameter of type T2 or "reference to 6196 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6197 // candidate functions. 6198 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6199 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6200 return; 6201 6202 // Add this candidate 6203 OverloadCandidate &Candidate = 6204 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6205 Candidate.FoundDecl = FoundDecl; 6206 Candidate.Function = Function; 6207 Candidate.Viable = true; 6208 Candidate.RewriteKind = 6209 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6210 Candidate.IsSurrogate = false; 6211 Candidate.IsADLCandidate = IsADLCandidate; 6212 Candidate.IgnoreObjectArgument = false; 6213 Candidate.ExplicitCallArguments = Args.size(); 6214 6215 // Explicit functions are not actually candidates at all if we're not 6216 // allowing them in this context, but keep them around so we can point 6217 // to them in diagnostics. 6218 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6219 Candidate.Viable = false; 6220 Candidate.FailureKind = ovl_fail_explicit; 6221 return; 6222 } 6223 6224 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6225 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6226 Candidate.Viable = false; 6227 Candidate.FailureKind = ovl_non_default_multiversion_function; 6228 return; 6229 } 6230 6231 if (Constructor) { 6232 // C++ [class.copy]p3: 6233 // A member function template is never instantiated to perform the copy 6234 // of a class object to an object of its class type. 6235 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6236 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6237 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6238 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6239 ClassType))) { 6240 Candidate.Viable = false; 6241 Candidate.FailureKind = ovl_fail_illegal_constructor; 6242 return; 6243 } 6244 6245 // C++ [over.match.funcs]p8: (proposed DR resolution) 6246 // A constructor inherited from class type C that has a first parameter 6247 // of type "reference to P" (including such a constructor instantiated 6248 // from a template) is excluded from the set of candidate functions when 6249 // constructing an object of type cv D if the argument list has exactly 6250 // one argument and D is reference-related to P and P is reference-related 6251 // to C. 6252 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6253 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6254 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6255 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6256 QualType C = Context.getRecordType(Constructor->getParent()); 6257 QualType D = Context.getRecordType(Shadow->getParent()); 6258 SourceLocation Loc = Args.front()->getExprLoc(); 6259 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6260 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6261 Candidate.Viable = false; 6262 Candidate.FailureKind = ovl_fail_inhctor_slice; 6263 return; 6264 } 6265 } 6266 6267 // Check that the constructor is capable of constructing an object in the 6268 // destination address space. 6269 if (!Qualifiers::isAddressSpaceSupersetOf( 6270 Constructor->getMethodQualifiers().getAddressSpace(), 6271 CandidateSet.getDestAS())) { 6272 Candidate.Viable = false; 6273 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6274 } 6275 } 6276 6277 unsigned NumParams = Proto->getNumParams(); 6278 6279 // (C++ 13.3.2p2): A candidate function having fewer than m 6280 // parameters is viable only if it has an ellipsis in its parameter 6281 // list (8.3.5). 6282 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6283 !Proto->isVariadic()) { 6284 Candidate.Viable = false; 6285 Candidate.FailureKind = ovl_fail_too_many_arguments; 6286 return; 6287 } 6288 6289 // (C++ 13.3.2p2): A candidate function having more than m parameters 6290 // is viable only if the (m+1)st parameter has a default argument 6291 // (8.3.6). For the purposes of overload resolution, the 6292 // parameter list is truncated on the right, so that there are 6293 // exactly m parameters. 6294 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6295 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6296 // Not enough arguments. 6297 Candidate.Viable = false; 6298 Candidate.FailureKind = ovl_fail_too_few_arguments; 6299 return; 6300 } 6301 6302 // (CUDA B.1): Check for invalid calls between targets. 6303 if (getLangOpts().CUDA) 6304 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6305 // Skip the check for callers that are implicit members, because in this 6306 // case we may not yet know what the member's target is; the target is 6307 // inferred for the member automatically, based on the bases and fields of 6308 // the class. 6309 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6310 Candidate.Viable = false; 6311 Candidate.FailureKind = ovl_fail_bad_target; 6312 return; 6313 } 6314 6315 if (Function->getTrailingRequiresClause()) { 6316 ConstraintSatisfaction Satisfaction; 6317 if (CheckFunctionConstraints(Function, Satisfaction) || 6318 !Satisfaction.IsSatisfied) { 6319 Candidate.Viable = false; 6320 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6321 return; 6322 } 6323 } 6324 6325 // Determine the implicit conversion sequences for each of the 6326 // arguments. 6327 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6328 unsigned ConvIdx = 6329 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6330 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6331 // We already formed a conversion sequence for this parameter during 6332 // template argument deduction. 6333 } else if (ArgIdx < NumParams) { 6334 // (C++ 13.3.2p3): for F to be a viable function, there shall 6335 // exist for each argument an implicit conversion sequence 6336 // (13.3.3.1) that converts that argument to the corresponding 6337 // parameter of F. 6338 QualType ParamType = Proto->getParamType(ArgIdx); 6339 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6340 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6341 /*InOverloadResolution=*/true, 6342 /*AllowObjCWritebackConversion=*/ 6343 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6344 if (Candidate.Conversions[ConvIdx].isBad()) { 6345 Candidate.Viable = false; 6346 Candidate.FailureKind = ovl_fail_bad_conversion; 6347 return; 6348 } 6349 } else { 6350 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6351 // argument for which there is no corresponding parameter is 6352 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6353 Candidate.Conversions[ConvIdx].setEllipsis(); 6354 } 6355 } 6356 6357 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6358 Candidate.Viable = false; 6359 Candidate.FailureKind = ovl_fail_enable_if; 6360 Candidate.DeductionFailure.Data = FailedAttr; 6361 return; 6362 } 6363 6364 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6365 Candidate.Viable = false; 6366 Candidate.FailureKind = ovl_fail_ext_disabled; 6367 return; 6368 } 6369 } 6370 6371 ObjCMethodDecl * 6372 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6373 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6374 if (Methods.size() <= 1) 6375 return nullptr; 6376 6377 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6378 bool Match = true; 6379 ObjCMethodDecl *Method = Methods[b]; 6380 unsigned NumNamedArgs = Sel.getNumArgs(); 6381 // Method might have more arguments than selector indicates. This is due 6382 // to addition of c-style arguments in method. 6383 if (Method->param_size() > NumNamedArgs) 6384 NumNamedArgs = Method->param_size(); 6385 if (Args.size() < NumNamedArgs) 6386 continue; 6387 6388 for (unsigned i = 0; i < NumNamedArgs; i++) { 6389 // We can't do any type-checking on a type-dependent argument. 6390 if (Args[i]->isTypeDependent()) { 6391 Match = false; 6392 break; 6393 } 6394 6395 ParmVarDecl *param = Method->parameters()[i]; 6396 Expr *argExpr = Args[i]; 6397 assert(argExpr && "SelectBestMethod(): missing expression"); 6398 6399 // Strip the unbridged-cast placeholder expression off unless it's 6400 // a consumed argument. 6401 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6402 !param->hasAttr<CFConsumedAttr>()) 6403 argExpr = stripARCUnbridgedCast(argExpr); 6404 6405 // If the parameter is __unknown_anytype, move on to the next method. 6406 if (param->getType() == Context.UnknownAnyTy) { 6407 Match = false; 6408 break; 6409 } 6410 6411 ImplicitConversionSequence ConversionState 6412 = TryCopyInitialization(*this, argExpr, param->getType(), 6413 /*SuppressUserConversions*/false, 6414 /*InOverloadResolution=*/true, 6415 /*AllowObjCWritebackConversion=*/ 6416 getLangOpts().ObjCAutoRefCount, 6417 /*AllowExplicit*/false); 6418 // This function looks for a reasonably-exact match, so we consider 6419 // incompatible pointer conversions to be a failure here. 6420 if (ConversionState.isBad() || 6421 (ConversionState.isStandard() && 6422 ConversionState.Standard.Second == 6423 ICK_Incompatible_Pointer_Conversion)) { 6424 Match = false; 6425 break; 6426 } 6427 } 6428 // Promote additional arguments to variadic methods. 6429 if (Match && Method->isVariadic()) { 6430 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6431 if (Args[i]->isTypeDependent()) { 6432 Match = false; 6433 break; 6434 } 6435 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6436 nullptr); 6437 if (Arg.isInvalid()) { 6438 Match = false; 6439 break; 6440 } 6441 } 6442 } else { 6443 // Check for extra arguments to non-variadic methods. 6444 if (Args.size() != NumNamedArgs) 6445 Match = false; 6446 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6447 // Special case when selectors have no argument. In this case, select 6448 // one with the most general result type of 'id'. 6449 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6450 QualType ReturnT = Methods[b]->getReturnType(); 6451 if (ReturnT->isObjCIdType()) 6452 return Methods[b]; 6453 } 6454 } 6455 } 6456 6457 if (Match) 6458 return Method; 6459 } 6460 return nullptr; 6461 } 6462 6463 static bool 6464 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6465 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6466 bool MissingImplicitThis, Expr *&ConvertedThis, 6467 SmallVectorImpl<Expr *> &ConvertedArgs) { 6468 if (ThisArg) { 6469 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6470 assert(!isa<CXXConstructorDecl>(Method) && 6471 "Shouldn't have `this` for ctors!"); 6472 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6473 ExprResult R = S.PerformObjectArgumentInitialization( 6474 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6475 if (R.isInvalid()) 6476 return false; 6477 ConvertedThis = R.get(); 6478 } else { 6479 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6480 (void)MD; 6481 assert((MissingImplicitThis || MD->isStatic() || 6482 isa<CXXConstructorDecl>(MD)) && 6483 "Expected `this` for non-ctor instance methods"); 6484 } 6485 ConvertedThis = nullptr; 6486 } 6487 6488 // Ignore any variadic arguments. Converting them is pointless, since the 6489 // user can't refer to them in the function condition. 6490 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6491 6492 // Convert the arguments. 6493 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6494 ExprResult R; 6495 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6496 S.Context, Function->getParamDecl(I)), 6497 SourceLocation(), Args[I]); 6498 6499 if (R.isInvalid()) 6500 return false; 6501 6502 ConvertedArgs.push_back(R.get()); 6503 } 6504 6505 if (Trap.hasErrorOccurred()) 6506 return false; 6507 6508 // Push default arguments if needed. 6509 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6510 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6511 ParmVarDecl *P = Function->getParamDecl(i); 6512 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6513 ? P->getUninstantiatedDefaultArg() 6514 : P->getDefaultArg(); 6515 // This can only happen in code completion, i.e. when PartialOverloading 6516 // is true. 6517 if (!DefArg) 6518 return false; 6519 ExprResult R = 6520 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6521 S.Context, Function->getParamDecl(i)), 6522 SourceLocation(), DefArg); 6523 if (R.isInvalid()) 6524 return false; 6525 ConvertedArgs.push_back(R.get()); 6526 } 6527 6528 if (Trap.hasErrorOccurred()) 6529 return false; 6530 } 6531 return true; 6532 } 6533 6534 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6535 bool MissingImplicitThis) { 6536 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6537 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6538 return nullptr; 6539 6540 SFINAETrap Trap(*this); 6541 SmallVector<Expr *, 16> ConvertedArgs; 6542 // FIXME: We should look into making enable_if late-parsed. 6543 Expr *DiscardedThis; 6544 if (!convertArgsForAvailabilityChecks( 6545 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6546 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6547 return *EnableIfAttrs.begin(); 6548 6549 for (auto *EIA : EnableIfAttrs) { 6550 APValue Result; 6551 // FIXME: This doesn't consider value-dependent cases, because doing so is 6552 // very difficult. Ideally, we should handle them more gracefully. 6553 if (EIA->getCond()->isValueDependent() || 6554 !EIA->getCond()->EvaluateWithSubstitution( 6555 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6556 return EIA; 6557 6558 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6559 return EIA; 6560 } 6561 return nullptr; 6562 } 6563 6564 template <typename CheckFn> 6565 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6566 bool ArgDependent, SourceLocation Loc, 6567 CheckFn &&IsSuccessful) { 6568 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6569 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6570 if (ArgDependent == DIA->getArgDependent()) 6571 Attrs.push_back(DIA); 6572 } 6573 6574 // Common case: No diagnose_if attributes, so we can quit early. 6575 if (Attrs.empty()) 6576 return false; 6577 6578 auto WarningBegin = std::stable_partition( 6579 Attrs.begin(), Attrs.end(), 6580 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6581 6582 // Note that diagnose_if attributes are late-parsed, so they appear in the 6583 // correct order (unlike enable_if attributes). 6584 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6585 IsSuccessful); 6586 if (ErrAttr != WarningBegin) { 6587 const DiagnoseIfAttr *DIA = *ErrAttr; 6588 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6589 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6590 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6591 return true; 6592 } 6593 6594 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6595 if (IsSuccessful(DIA)) { 6596 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6597 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6598 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6599 } 6600 6601 return false; 6602 } 6603 6604 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6605 const Expr *ThisArg, 6606 ArrayRef<const Expr *> Args, 6607 SourceLocation Loc) { 6608 return diagnoseDiagnoseIfAttrsWith( 6609 *this, Function, /*ArgDependent=*/true, Loc, 6610 [&](const DiagnoseIfAttr *DIA) { 6611 APValue Result; 6612 // It's sane to use the same Args for any redecl of this function, since 6613 // EvaluateWithSubstitution only cares about the position of each 6614 // argument in the arg list, not the ParmVarDecl* it maps to. 6615 if (!DIA->getCond()->EvaluateWithSubstitution( 6616 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6617 return false; 6618 return Result.isInt() && Result.getInt().getBoolValue(); 6619 }); 6620 } 6621 6622 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6623 SourceLocation Loc) { 6624 return diagnoseDiagnoseIfAttrsWith( 6625 *this, ND, /*ArgDependent=*/false, Loc, 6626 [&](const DiagnoseIfAttr *DIA) { 6627 bool Result; 6628 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6629 Result; 6630 }); 6631 } 6632 6633 /// Add all of the function declarations in the given function set to 6634 /// the overload candidate set. 6635 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6636 ArrayRef<Expr *> Args, 6637 OverloadCandidateSet &CandidateSet, 6638 TemplateArgumentListInfo *ExplicitTemplateArgs, 6639 bool SuppressUserConversions, 6640 bool PartialOverloading, 6641 bool FirstArgumentIsBase) { 6642 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6643 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6644 ArrayRef<Expr *> FunctionArgs = Args; 6645 6646 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6647 FunctionDecl *FD = 6648 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6649 6650 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6651 QualType ObjectType; 6652 Expr::Classification ObjectClassification; 6653 if (Args.size() > 0) { 6654 if (Expr *E = Args[0]) { 6655 // Use the explicit base to restrict the lookup: 6656 ObjectType = E->getType(); 6657 // Pointers in the object arguments are implicitly dereferenced, so we 6658 // always classify them as l-values. 6659 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6660 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6661 else 6662 ObjectClassification = E->Classify(Context); 6663 } // .. else there is an implicit base. 6664 FunctionArgs = Args.slice(1); 6665 } 6666 if (FunTmpl) { 6667 AddMethodTemplateCandidate( 6668 FunTmpl, F.getPair(), 6669 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6670 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6671 FunctionArgs, CandidateSet, SuppressUserConversions, 6672 PartialOverloading); 6673 } else { 6674 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6675 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6676 ObjectClassification, FunctionArgs, CandidateSet, 6677 SuppressUserConversions, PartialOverloading); 6678 } 6679 } else { 6680 // This branch handles both standalone functions and static methods. 6681 6682 // Slice the first argument (which is the base) when we access 6683 // static method as non-static. 6684 if (Args.size() > 0 && 6685 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6686 !isa<CXXConstructorDecl>(FD)))) { 6687 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6688 FunctionArgs = Args.slice(1); 6689 } 6690 if (FunTmpl) { 6691 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6692 ExplicitTemplateArgs, FunctionArgs, 6693 CandidateSet, SuppressUserConversions, 6694 PartialOverloading); 6695 } else { 6696 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6697 SuppressUserConversions, PartialOverloading); 6698 } 6699 } 6700 } 6701 } 6702 6703 /// AddMethodCandidate - Adds a named decl (which is some kind of 6704 /// method) as a method candidate to the given overload set. 6705 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6706 Expr::Classification ObjectClassification, 6707 ArrayRef<Expr *> Args, 6708 OverloadCandidateSet &CandidateSet, 6709 bool SuppressUserConversions, 6710 OverloadCandidateParamOrder PO) { 6711 NamedDecl *Decl = FoundDecl.getDecl(); 6712 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6713 6714 if (isa<UsingShadowDecl>(Decl)) 6715 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6716 6717 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6718 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6719 "Expected a member function template"); 6720 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6721 /*ExplicitArgs*/ nullptr, ObjectType, 6722 ObjectClassification, Args, CandidateSet, 6723 SuppressUserConversions, false, PO); 6724 } else { 6725 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6726 ObjectType, ObjectClassification, Args, CandidateSet, 6727 SuppressUserConversions, false, None, PO); 6728 } 6729 } 6730 6731 /// AddMethodCandidate - Adds the given C++ member function to the set 6732 /// of candidate functions, using the given function call arguments 6733 /// and the object argument (@c Object). For example, in a call 6734 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6735 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6736 /// allow user-defined conversions via constructors or conversion 6737 /// operators. 6738 void 6739 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6740 CXXRecordDecl *ActingContext, QualType ObjectType, 6741 Expr::Classification ObjectClassification, 6742 ArrayRef<Expr *> Args, 6743 OverloadCandidateSet &CandidateSet, 6744 bool SuppressUserConversions, 6745 bool PartialOverloading, 6746 ConversionSequenceList EarlyConversions, 6747 OverloadCandidateParamOrder PO) { 6748 const FunctionProtoType *Proto 6749 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6750 assert(Proto && "Methods without a prototype cannot be overloaded"); 6751 assert(!isa<CXXConstructorDecl>(Method) && 6752 "Use AddOverloadCandidate for constructors"); 6753 6754 if (!CandidateSet.isNewCandidate(Method, PO)) 6755 return; 6756 6757 // C++11 [class.copy]p23: [DR1402] 6758 // A defaulted move assignment operator that is defined as deleted is 6759 // ignored by overload resolution. 6760 if (Method->isDefaulted() && Method->isDeleted() && 6761 Method->isMoveAssignmentOperator()) 6762 return; 6763 6764 // Overload resolution is always an unevaluated context. 6765 EnterExpressionEvaluationContext Unevaluated( 6766 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6767 6768 // Add this candidate 6769 OverloadCandidate &Candidate = 6770 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6771 Candidate.FoundDecl = FoundDecl; 6772 Candidate.Function = Method; 6773 Candidate.RewriteKind = 6774 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6775 Candidate.IsSurrogate = false; 6776 Candidate.IgnoreObjectArgument = false; 6777 Candidate.ExplicitCallArguments = Args.size(); 6778 6779 unsigned NumParams = Proto->getNumParams(); 6780 6781 // (C++ 13.3.2p2): A candidate function having fewer than m 6782 // parameters is viable only if it has an ellipsis in its parameter 6783 // list (8.3.5). 6784 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6785 !Proto->isVariadic()) { 6786 Candidate.Viable = false; 6787 Candidate.FailureKind = ovl_fail_too_many_arguments; 6788 return; 6789 } 6790 6791 // (C++ 13.3.2p2): A candidate function having more than m parameters 6792 // is viable only if the (m+1)st parameter has a default argument 6793 // (8.3.6). For the purposes of overload resolution, the 6794 // parameter list is truncated on the right, so that there are 6795 // exactly m parameters. 6796 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6797 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6798 // Not enough arguments. 6799 Candidate.Viable = false; 6800 Candidate.FailureKind = ovl_fail_too_few_arguments; 6801 return; 6802 } 6803 6804 Candidate.Viable = true; 6805 6806 if (Method->isStatic() || ObjectType.isNull()) 6807 // The implicit object argument is ignored. 6808 Candidate.IgnoreObjectArgument = true; 6809 else { 6810 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6811 // Determine the implicit conversion sequence for the object 6812 // parameter. 6813 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6814 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6815 Method, ActingContext); 6816 if (Candidate.Conversions[ConvIdx].isBad()) { 6817 Candidate.Viable = false; 6818 Candidate.FailureKind = ovl_fail_bad_conversion; 6819 return; 6820 } 6821 } 6822 6823 // (CUDA B.1): Check for invalid calls between targets. 6824 if (getLangOpts().CUDA) 6825 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6826 if (!IsAllowedCUDACall(Caller, Method)) { 6827 Candidate.Viable = false; 6828 Candidate.FailureKind = ovl_fail_bad_target; 6829 return; 6830 } 6831 6832 if (Method->getTrailingRequiresClause()) { 6833 ConstraintSatisfaction Satisfaction; 6834 if (CheckFunctionConstraints(Method, Satisfaction) || 6835 !Satisfaction.IsSatisfied) { 6836 Candidate.Viable = false; 6837 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6838 return; 6839 } 6840 } 6841 6842 // Determine the implicit conversion sequences for each of the 6843 // arguments. 6844 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6845 unsigned ConvIdx = 6846 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6847 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6848 // We already formed a conversion sequence for this parameter during 6849 // template argument deduction. 6850 } else if (ArgIdx < NumParams) { 6851 // (C++ 13.3.2p3): for F to be a viable function, there shall 6852 // exist for each argument an implicit conversion sequence 6853 // (13.3.3.1) that converts that argument to the corresponding 6854 // parameter of F. 6855 QualType ParamType = Proto->getParamType(ArgIdx); 6856 Candidate.Conversions[ConvIdx] 6857 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6858 SuppressUserConversions, 6859 /*InOverloadResolution=*/true, 6860 /*AllowObjCWritebackConversion=*/ 6861 getLangOpts().ObjCAutoRefCount); 6862 if (Candidate.Conversions[ConvIdx].isBad()) { 6863 Candidate.Viable = false; 6864 Candidate.FailureKind = ovl_fail_bad_conversion; 6865 return; 6866 } 6867 } else { 6868 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6869 // argument for which there is no corresponding parameter is 6870 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6871 Candidate.Conversions[ConvIdx].setEllipsis(); 6872 } 6873 } 6874 6875 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6876 Candidate.Viable = false; 6877 Candidate.FailureKind = ovl_fail_enable_if; 6878 Candidate.DeductionFailure.Data = FailedAttr; 6879 return; 6880 } 6881 6882 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6883 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6884 Candidate.Viable = false; 6885 Candidate.FailureKind = ovl_non_default_multiversion_function; 6886 } 6887 } 6888 6889 /// Add a C++ member function template as a candidate to the candidate 6890 /// set, using template argument deduction to produce an appropriate member 6891 /// function template specialization. 6892 void Sema::AddMethodTemplateCandidate( 6893 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 6894 CXXRecordDecl *ActingContext, 6895 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 6896 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 6897 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6898 bool PartialOverloading, OverloadCandidateParamOrder PO) { 6899 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 6900 return; 6901 6902 // C++ [over.match.funcs]p7: 6903 // In each case where a candidate is a function template, candidate 6904 // function template specializations are generated using template argument 6905 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6906 // candidate functions in the usual way.113) A given name can refer to one 6907 // or more function templates and also to a set of overloaded non-template 6908 // functions. In such a case, the candidate functions generated from each 6909 // function template are combined with the set of non-template candidate 6910 // functions. 6911 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6912 FunctionDecl *Specialization = nullptr; 6913 ConversionSequenceList Conversions; 6914 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6915 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6916 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6917 return CheckNonDependentConversions( 6918 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6919 SuppressUserConversions, ActingContext, ObjectType, 6920 ObjectClassification, PO); 6921 })) { 6922 OverloadCandidate &Candidate = 6923 CandidateSet.addCandidate(Conversions.size(), Conversions); 6924 Candidate.FoundDecl = FoundDecl; 6925 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6926 Candidate.Viable = false; 6927 Candidate.RewriteKind = 6928 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6929 Candidate.IsSurrogate = false; 6930 Candidate.IgnoreObjectArgument = 6931 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6932 ObjectType.isNull(); 6933 Candidate.ExplicitCallArguments = Args.size(); 6934 if (Result == TDK_NonDependentConversionFailure) 6935 Candidate.FailureKind = ovl_fail_bad_conversion; 6936 else { 6937 Candidate.FailureKind = ovl_fail_bad_deduction; 6938 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6939 Info); 6940 } 6941 return; 6942 } 6943 6944 // Add the function template specialization produced by template argument 6945 // deduction as a candidate. 6946 assert(Specialization && "Missing member function template specialization?"); 6947 assert(isa<CXXMethodDecl>(Specialization) && 6948 "Specialization is not a member function?"); 6949 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6950 ActingContext, ObjectType, ObjectClassification, Args, 6951 CandidateSet, SuppressUserConversions, PartialOverloading, 6952 Conversions, PO); 6953 } 6954 6955 /// Determine whether a given function template has a simple explicit specifier 6956 /// or a non-value-dependent explicit-specification that evaluates to true. 6957 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 6958 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 6959 } 6960 6961 /// Add a C++ function template specialization as a candidate 6962 /// in the candidate set, using template argument deduction to produce 6963 /// an appropriate function template specialization. 6964 void Sema::AddTemplateOverloadCandidate( 6965 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6966 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6967 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6968 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 6969 OverloadCandidateParamOrder PO) { 6970 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 6971 return; 6972 6973 // If the function template has a non-dependent explicit specification, 6974 // exclude it now if appropriate; we are not permitted to perform deduction 6975 // and substitution in this case. 6976 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 6977 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6978 Candidate.FoundDecl = FoundDecl; 6979 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6980 Candidate.Viable = false; 6981 Candidate.FailureKind = ovl_fail_explicit; 6982 return; 6983 } 6984 6985 // C++ [over.match.funcs]p7: 6986 // In each case where a candidate is a function template, candidate 6987 // function template specializations are generated using template argument 6988 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6989 // candidate functions in the usual way.113) A given name can refer to one 6990 // or more function templates and also to a set of overloaded non-template 6991 // functions. In such a case, the candidate functions generated from each 6992 // function template are combined with the set of non-template candidate 6993 // functions. 6994 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6995 FunctionDecl *Specialization = nullptr; 6996 ConversionSequenceList Conversions; 6997 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6998 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6999 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7000 return CheckNonDependentConversions( 7001 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7002 SuppressUserConversions, nullptr, QualType(), {}, PO); 7003 })) { 7004 OverloadCandidate &Candidate = 7005 CandidateSet.addCandidate(Conversions.size(), Conversions); 7006 Candidate.FoundDecl = FoundDecl; 7007 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7008 Candidate.Viable = false; 7009 Candidate.RewriteKind = 7010 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7011 Candidate.IsSurrogate = false; 7012 Candidate.IsADLCandidate = IsADLCandidate; 7013 // Ignore the object argument if there is one, since we don't have an object 7014 // type. 7015 Candidate.IgnoreObjectArgument = 7016 isa<CXXMethodDecl>(Candidate.Function) && 7017 !isa<CXXConstructorDecl>(Candidate.Function); 7018 Candidate.ExplicitCallArguments = Args.size(); 7019 if (Result == TDK_NonDependentConversionFailure) 7020 Candidate.FailureKind = ovl_fail_bad_conversion; 7021 else { 7022 Candidate.FailureKind = ovl_fail_bad_deduction; 7023 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7024 Info); 7025 } 7026 return; 7027 } 7028 7029 // Add the function template specialization produced by template argument 7030 // deduction as a candidate. 7031 assert(Specialization && "Missing function template specialization?"); 7032 AddOverloadCandidate( 7033 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7034 PartialOverloading, AllowExplicit, 7035 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7036 } 7037 7038 /// Check that implicit conversion sequences can be formed for each argument 7039 /// whose corresponding parameter has a non-dependent type, per DR1391's 7040 /// [temp.deduct.call]p10. 7041 bool Sema::CheckNonDependentConversions( 7042 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7043 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7044 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7045 CXXRecordDecl *ActingContext, QualType ObjectType, 7046 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7047 // FIXME: The cases in which we allow explicit conversions for constructor 7048 // arguments never consider calling a constructor template. It's not clear 7049 // that is correct. 7050 const bool AllowExplicit = false; 7051 7052 auto *FD = FunctionTemplate->getTemplatedDecl(); 7053 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7054 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7055 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7056 7057 Conversions = 7058 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7059 7060 // Overload resolution is always an unevaluated context. 7061 EnterExpressionEvaluationContext Unevaluated( 7062 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7063 7064 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7065 // require that, but this check should never result in a hard error, and 7066 // overload resolution is permitted to sidestep instantiations. 7067 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7068 !ObjectType.isNull()) { 7069 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7070 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7071 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7072 Method, ActingContext); 7073 if (Conversions[ConvIdx].isBad()) 7074 return true; 7075 } 7076 7077 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7078 ++I) { 7079 QualType ParamType = ParamTypes[I]; 7080 if (!ParamType->isDependentType()) { 7081 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7082 ? 0 7083 : (ThisConversions + I); 7084 Conversions[ConvIdx] 7085 = TryCopyInitialization(*this, Args[I], ParamType, 7086 SuppressUserConversions, 7087 /*InOverloadResolution=*/true, 7088 /*AllowObjCWritebackConversion=*/ 7089 getLangOpts().ObjCAutoRefCount, 7090 AllowExplicit); 7091 if (Conversions[ConvIdx].isBad()) 7092 return true; 7093 } 7094 } 7095 7096 return false; 7097 } 7098 7099 /// Determine whether this is an allowable conversion from the result 7100 /// of an explicit conversion operator to the expected type, per C++ 7101 /// [over.match.conv]p1 and [over.match.ref]p1. 7102 /// 7103 /// \param ConvType The return type of the conversion function. 7104 /// 7105 /// \param ToType The type we are converting to. 7106 /// 7107 /// \param AllowObjCPointerConversion Allow a conversion from one 7108 /// Objective-C pointer to another. 7109 /// 7110 /// \returns true if the conversion is allowable, false otherwise. 7111 static bool isAllowableExplicitConversion(Sema &S, 7112 QualType ConvType, QualType ToType, 7113 bool AllowObjCPointerConversion) { 7114 QualType ToNonRefType = ToType.getNonReferenceType(); 7115 7116 // Easy case: the types are the same. 7117 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7118 return true; 7119 7120 // Allow qualification conversions. 7121 bool ObjCLifetimeConversion; 7122 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7123 ObjCLifetimeConversion)) 7124 return true; 7125 7126 // If we're not allowed to consider Objective-C pointer conversions, 7127 // we're done. 7128 if (!AllowObjCPointerConversion) 7129 return false; 7130 7131 // Is this an Objective-C pointer conversion? 7132 bool IncompatibleObjC = false; 7133 QualType ConvertedType; 7134 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7135 IncompatibleObjC); 7136 } 7137 7138 /// AddConversionCandidate - Add a C++ conversion function as a 7139 /// candidate in the candidate set (C++ [over.match.conv], 7140 /// C++ [over.match.copy]). From is the expression we're converting from, 7141 /// and ToType is the type that we're eventually trying to convert to 7142 /// (which may or may not be the same type as the type that the 7143 /// conversion function produces). 7144 void Sema::AddConversionCandidate( 7145 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7146 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7147 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7148 bool AllowExplicit, bool AllowResultConversion) { 7149 assert(!Conversion->getDescribedFunctionTemplate() && 7150 "Conversion function templates use AddTemplateConversionCandidate"); 7151 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7152 if (!CandidateSet.isNewCandidate(Conversion)) 7153 return; 7154 7155 // If the conversion function has an undeduced return type, trigger its 7156 // deduction now. 7157 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7158 if (DeduceReturnType(Conversion, From->getExprLoc())) 7159 return; 7160 ConvType = Conversion->getConversionType().getNonReferenceType(); 7161 } 7162 7163 // If we don't allow any conversion of the result type, ignore conversion 7164 // functions that don't convert to exactly (possibly cv-qualified) T. 7165 if (!AllowResultConversion && 7166 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7167 return; 7168 7169 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7170 // operator is only a candidate if its return type is the target type or 7171 // can be converted to the target type with a qualification conversion. 7172 // 7173 // FIXME: Include such functions in the candidate list and explain why we 7174 // can't select them. 7175 if (Conversion->isExplicit() && 7176 !isAllowableExplicitConversion(*this, ConvType, ToType, 7177 AllowObjCConversionOnExplicit)) 7178 return; 7179 7180 // Overload resolution is always an unevaluated context. 7181 EnterExpressionEvaluationContext Unevaluated( 7182 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7183 7184 // Add this candidate 7185 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7186 Candidate.FoundDecl = FoundDecl; 7187 Candidate.Function = Conversion; 7188 Candidate.IsSurrogate = false; 7189 Candidate.IgnoreObjectArgument = false; 7190 Candidate.FinalConversion.setAsIdentityConversion(); 7191 Candidate.FinalConversion.setFromType(ConvType); 7192 Candidate.FinalConversion.setAllToTypes(ToType); 7193 Candidate.Viable = true; 7194 Candidate.ExplicitCallArguments = 1; 7195 7196 // Explicit functions are not actually candidates at all if we're not 7197 // allowing them in this context, but keep them around so we can point 7198 // to them in diagnostics. 7199 if (!AllowExplicit && Conversion->isExplicit()) { 7200 Candidate.Viable = false; 7201 Candidate.FailureKind = ovl_fail_explicit; 7202 return; 7203 } 7204 7205 // C++ [over.match.funcs]p4: 7206 // For conversion functions, the function is considered to be a member of 7207 // the class of the implicit implied object argument for the purpose of 7208 // defining the type of the implicit object parameter. 7209 // 7210 // Determine the implicit conversion sequence for the implicit 7211 // object parameter. 7212 QualType ImplicitParamType = From->getType(); 7213 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7214 ImplicitParamType = FromPtrType->getPointeeType(); 7215 CXXRecordDecl *ConversionContext 7216 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7217 7218 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7219 *this, CandidateSet.getLocation(), From->getType(), 7220 From->Classify(Context), Conversion, ConversionContext); 7221 7222 if (Candidate.Conversions[0].isBad()) { 7223 Candidate.Viable = false; 7224 Candidate.FailureKind = ovl_fail_bad_conversion; 7225 return; 7226 } 7227 7228 if (Conversion->getTrailingRequiresClause()) { 7229 ConstraintSatisfaction Satisfaction; 7230 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7231 !Satisfaction.IsSatisfied) { 7232 Candidate.Viable = false; 7233 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7234 return; 7235 } 7236 } 7237 7238 // We won't go through a user-defined type conversion function to convert a 7239 // derived to base as such conversions are given Conversion Rank. They only 7240 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7241 QualType FromCanon 7242 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7243 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7244 if (FromCanon == ToCanon || 7245 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7246 Candidate.Viable = false; 7247 Candidate.FailureKind = ovl_fail_trivial_conversion; 7248 return; 7249 } 7250 7251 // To determine what the conversion from the result of calling the 7252 // conversion function to the type we're eventually trying to 7253 // convert to (ToType), we need to synthesize a call to the 7254 // conversion function and attempt copy initialization from it. This 7255 // makes sure that we get the right semantics with respect to 7256 // lvalues/rvalues and the type. Fortunately, we can allocate this 7257 // call on the stack and we don't need its arguments to be 7258 // well-formed. 7259 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7260 VK_LValue, From->getBeginLoc()); 7261 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7262 Context.getPointerType(Conversion->getType()), 7263 CK_FunctionToPointerDecay, 7264 &ConversionRef, VK_RValue); 7265 7266 QualType ConversionType = Conversion->getConversionType(); 7267 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7268 Candidate.Viable = false; 7269 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7270 return; 7271 } 7272 7273 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7274 7275 // Note that it is safe to allocate CallExpr on the stack here because 7276 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7277 // allocator). 7278 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7279 7280 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7281 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7282 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7283 7284 ImplicitConversionSequence ICS = 7285 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7286 /*SuppressUserConversions=*/true, 7287 /*InOverloadResolution=*/false, 7288 /*AllowObjCWritebackConversion=*/false); 7289 7290 switch (ICS.getKind()) { 7291 case ImplicitConversionSequence::StandardConversion: 7292 Candidate.FinalConversion = ICS.Standard; 7293 7294 // C++ [over.ics.user]p3: 7295 // If the user-defined conversion is specified by a specialization of a 7296 // conversion function template, the second standard conversion sequence 7297 // shall have exact match rank. 7298 if (Conversion->getPrimaryTemplate() && 7299 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7300 Candidate.Viable = false; 7301 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7302 return; 7303 } 7304 7305 // C++0x [dcl.init.ref]p5: 7306 // In the second case, if the reference is an rvalue reference and 7307 // the second standard conversion sequence of the user-defined 7308 // conversion sequence includes an lvalue-to-rvalue conversion, the 7309 // program is ill-formed. 7310 if (ToType->isRValueReferenceType() && 7311 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7312 Candidate.Viable = false; 7313 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7314 return; 7315 } 7316 break; 7317 7318 case ImplicitConversionSequence::BadConversion: 7319 Candidate.Viable = false; 7320 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7321 return; 7322 7323 default: 7324 llvm_unreachable( 7325 "Can only end up with a standard conversion sequence or failure"); 7326 } 7327 7328 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7329 Candidate.Viable = false; 7330 Candidate.FailureKind = ovl_fail_enable_if; 7331 Candidate.DeductionFailure.Data = FailedAttr; 7332 return; 7333 } 7334 7335 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7336 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7337 Candidate.Viable = false; 7338 Candidate.FailureKind = ovl_non_default_multiversion_function; 7339 } 7340 } 7341 7342 /// Adds a conversion function template specialization 7343 /// candidate to the overload set, using template argument deduction 7344 /// to deduce the template arguments of the conversion function 7345 /// template from the type that we are converting to (C++ 7346 /// [temp.deduct.conv]). 7347 void Sema::AddTemplateConversionCandidate( 7348 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7349 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7350 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7351 bool AllowExplicit, bool AllowResultConversion) { 7352 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7353 "Only conversion function templates permitted here"); 7354 7355 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7356 return; 7357 7358 // If the function template has a non-dependent explicit specification, 7359 // exclude it now if appropriate; we are not permitted to perform deduction 7360 // and substitution in this case. 7361 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7362 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7363 Candidate.FoundDecl = FoundDecl; 7364 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7365 Candidate.Viable = false; 7366 Candidate.FailureKind = ovl_fail_explicit; 7367 return; 7368 } 7369 7370 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7371 CXXConversionDecl *Specialization = nullptr; 7372 if (TemplateDeductionResult Result 7373 = DeduceTemplateArguments(FunctionTemplate, ToType, 7374 Specialization, Info)) { 7375 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7376 Candidate.FoundDecl = FoundDecl; 7377 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7378 Candidate.Viable = false; 7379 Candidate.FailureKind = ovl_fail_bad_deduction; 7380 Candidate.IsSurrogate = false; 7381 Candidate.IgnoreObjectArgument = false; 7382 Candidate.ExplicitCallArguments = 1; 7383 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7384 Info); 7385 return; 7386 } 7387 7388 // Add the conversion function template specialization produced by 7389 // template argument deduction as a candidate. 7390 assert(Specialization && "Missing function template specialization?"); 7391 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7392 CandidateSet, AllowObjCConversionOnExplicit, 7393 AllowExplicit, AllowResultConversion); 7394 } 7395 7396 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7397 /// converts the given @c Object to a function pointer via the 7398 /// conversion function @c Conversion, and then attempts to call it 7399 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7400 /// the type of function that we'll eventually be calling. 7401 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7402 DeclAccessPair FoundDecl, 7403 CXXRecordDecl *ActingContext, 7404 const FunctionProtoType *Proto, 7405 Expr *Object, 7406 ArrayRef<Expr *> Args, 7407 OverloadCandidateSet& CandidateSet) { 7408 if (!CandidateSet.isNewCandidate(Conversion)) 7409 return; 7410 7411 // Overload resolution is always an unevaluated context. 7412 EnterExpressionEvaluationContext Unevaluated( 7413 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7414 7415 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7416 Candidate.FoundDecl = FoundDecl; 7417 Candidate.Function = nullptr; 7418 Candidate.Surrogate = Conversion; 7419 Candidate.Viable = true; 7420 Candidate.IsSurrogate = true; 7421 Candidate.IgnoreObjectArgument = false; 7422 Candidate.ExplicitCallArguments = Args.size(); 7423 7424 // Determine the implicit conversion sequence for the implicit 7425 // object parameter. 7426 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7427 *this, CandidateSet.getLocation(), Object->getType(), 7428 Object->Classify(Context), Conversion, ActingContext); 7429 if (ObjectInit.isBad()) { 7430 Candidate.Viable = false; 7431 Candidate.FailureKind = ovl_fail_bad_conversion; 7432 Candidate.Conversions[0] = ObjectInit; 7433 return; 7434 } 7435 7436 // The first conversion is actually a user-defined conversion whose 7437 // first conversion is ObjectInit's standard conversion (which is 7438 // effectively a reference binding). Record it as such. 7439 Candidate.Conversions[0].setUserDefined(); 7440 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7441 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7442 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7443 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7444 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7445 Candidate.Conversions[0].UserDefined.After 7446 = Candidate.Conversions[0].UserDefined.Before; 7447 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7448 7449 // Find the 7450 unsigned NumParams = Proto->getNumParams(); 7451 7452 // (C++ 13.3.2p2): A candidate function having fewer than m 7453 // parameters is viable only if it has an ellipsis in its parameter 7454 // list (8.3.5). 7455 if (Args.size() > NumParams && !Proto->isVariadic()) { 7456 Candidate.Viable = false; 7457 Candidate.FailureKind = ovl_fail_too_many_arguments; 7458 return; 7459 } 7460 7461 // Function types don't have any default arguments, so just check if 7462 // we have enough arguments. 7463 if (Args.size() < NumParams) { 7464 // Not enough arguments. 7465 Candidate.Viable = false; 7466 Candidate.FailureKind = ovl_fail_too_few_arguments; 7467 return; 7468 } 7469 7470 // Determine the implicit conversion sequences for each of the 7471 // arguments. 7472 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7473 if (ArgIdx < NumParams) { 7474 // (C++ 13.3.2p3): for F to be a viable function, there shall 7475 // exist for each argument an implicit conversion sequence 7476 // (13.3.3.1) that converts that argument to the corresponding 7477 // parameter of F. 7478 QualType ParamType = Proto->getParamType(ArgIdx); 7479 Candidate.Conversions[ArgIdx + 1] 7480 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7481 /*SuppressUserConversions=*/false, 7482 /*InOverloadResolution=*/false, 7483 /*AllowObjCWritebackConversion=*/ 7484 getLangOpts().ObjCAutoRefCount); 7485 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7486 Candidate.Viable = false; 7487 Candidate.FailureKind = ovl_fail_bad_conversion; 7488 return; 7489 } 7490 } else { 7491 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7492 // argument for which there is no corresponding parameter is 7493 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7494 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7495 } 7496 } 7497 7498 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7499 Candidate.Viable = false; 7500 Candidate.FailureKind = ovl_fail_enable_if; 7501 Candidate.DeductionFailure.Data = FailedAttr; 7502 return; 7503 } 7504 } 7505 7506 /// Add all of the non-member operator function declarations in the given 7507 /// function set to the overload candidate set. 7508 void Sema::AddNonMemberOperatorCandidates( 7509 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7510 OverloadCandidateSet &CandidateSet, 7511 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7512 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7513 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7514 ArrayRef<Expr *> FunctionArgs = Args; 7515 7516 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7517 FunctionDecl *FD = 7518 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7519 7520 // Don't consider rewritten functions if we're not rewriting. 7521 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7522 continue; 7523 7524 assert(!isa<CXXMethodDecl>(FD) && 7525 "unqualified operator lookup found a member function"); 7526 7527 if (FunTmpl) { 7528 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7529 FunctionArgs, CandidateSet); 7530 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7531 AddTemplateOverloadCandidate( 7532 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7533 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7534 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7535 } else { 7536 if (ExplicitTemplateArgs) 7537 continue; 7538 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7539 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7540 AddOverloadCandidate(FD, F.getPair(), 7541 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7542 false, false, true, false, ADLCallKind::NotADL, 7543 None, OverloadCandidateParamOrder::Reversed); 7544 } 7545 } 7546 } 7547 7548 /// Add overload candidates for overloaded operators that are 7549 /// member functions. 7550 /// 7551 /// Add the overloaded operator candidates that are member functions 7552 /// for the operator Op that was used in an operator expression such 7553 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7554 /// CandidateSet will store the added overload candidates. (C++ 7555 /// [over.match.oper]). 7556 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7557 SourceLocation OpLoc, 7558 ArrayRef<Expr *> Args, 7559 OverloadCandidateSet &CandidateSet, 7560 OverloadCandidateParamOrder PO) { 7561 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7562 7563 // C++ [over.match.oper]p3: 7564 // For a unary operator @ with an operand of a type whose 7565 // cv-unqualified version is T1, and for a binary operator @ with 7566 // a left operand of a type whose cv-unqualified version is T1 and 7567 // a right operand of a type whose cv-unqualified version is T2, 7568 // three sets of candidate functions, designated member 7569 // candidates, non-member candidates and built-in candidates, are 7570 // constructed as follows: 7571 QualType T1 = Args[0]->getType(); 7572 7573 // -- If T1 is a complete class type or a class currently being 7574 // defined, the set of member candidates is the result of the 7575 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7576 // the set of member candidates is empty. 7577 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7578 // Complete the type if it can be completed. 7579 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7580 return; 7581 // If the type is neither complete nor being defined, bail out now. 7582 if (!T1Rec->getDecl()->getDefinition()) 7583 return; 7584 7585 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7586 LookupQualifiedName(Operators, T1Rec->getDecl()); 7587 Operators.suppressDiagnostics(); 7588 7589 for (LookupResult::iterator Oper = Operators.begin(), 7590 OperEnd = Operators.end(); 7591 Oper != OperEnd; 7592 ++Oper) 7593 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7594 Args[0]->Classify(Context), Args.slice(1), 7595 CandidateSet, /*SuppressUserConversion=*/false, PO); 7596 } 7597 } 7598 7599 /// AddBuiltinCandidate - Add a candidate for a built-in 7600 /// operator. ResultTy and ParamTys are the result and parameter types 7601 /// of the built-in candidate, respectively. Args and NumArgs are the 7602 /// arguments being passed to the candidate. IsAssignmentOperator 7603 /// should be true when this built-in candidate is an assignment 7604 /// operator. NumContextualBoolArguments is the number of arguments 7605 /// (at the beginning of the argument list) that will be contextually 7606 /// converted to bool. 7607 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7608 OverloadCandidateSet& CandidateSet, 7609 bool IsAssignmentOperator, 7610 unsigned NumContextualBoolArguments) { 7611 // Overload resolution is always an unevaluated context. 7612 EnterExpressionEvaluationContext Unevaluated( 7613 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7614 7615 // Add this candidate 7616 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7617 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7618 Candidate.Function = nullptr; 7619 Candidate.IsSurrogate = false; 7620 Candidate.IgnoreObjectArgument = false; 7621 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7622 7623 // Determine the implicit conversion sequences for each of the 7624 // arguments. 7625 Candidate.Viable = true; 7626 Candidate.ExplicitCallArguments = Args.size(); 7627 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7628 // C++ [over.match.oper]p4: 7629 // For the built-in assignment operators, conversions of the 7630 // left operand are restricted as follows: 7631 // -- no temporaries are introduced to hold the left operand, and 7632 // -- no user-defined conversions are applied to the left 7633 // operand to achieve a type match with the left-most 7634 // parameter of a built-in candidate. 7635 // 7636 // We block these conversions by turning off user-defined 7637 // conversions, since that is the only way that initialization of 7638 // a reference to a non-class type can occur from something that 7639 // is not of the same type. 7640 if (ArgIdx < NumContextualBoolArguments) { 7641 assert(ParamTys[ArgIdx] == Context.BoolTy && 7642 "Contextual conversion to bool requires bool type"); 7643 Candidate.Conversions[ArgIdx] 7644 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7645 } else { 7646 Candidate.Conversions[ArgIdx] 7647 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7648 ArgIdx == 0 && IsAssignmentOperator, 7649 /*InOverloadResolution=*/false, 7650 /*AllowObjCWritebackConversion=*/ 7651 getLangOpts().ObjCAutoRefCount); 7652 } 7653 if (Candidate.Conversions[ArgIdx].isBad()) { 7654 Candidate.Viable = false; 7655 Candidate.FailureKind = ovl_fail_bad_conversion; 7656 break; 7657 } 7658 } 7659 } 7660 7661 namespace { 7662 7663 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7664 /// candidate operator functions for built-in operators (C++ 7665 /// [over.built]). The types are separated into pointer types and 7666 /// enumeration types. 7667 class BuiltinCandidateTypeSet { 7668 /// TypeSet - A set of types. 7669 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7670 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7671 7672 /// PointerTypes - The set of pointer types that will be used in the 7673 /// built-in candidates. 7674 TypeSet PointerTypes; 7675 7676 /// MemberPointerTypes - The set of member pointer types that will be 7677 /// used in the built-in candidates. 7678 TypeSet MemberPointerTypes; 7679 7680 /// EnumerationTypes - The set of enumeration types that will be 7681 /// used in the built-in candidates. 7682 TypeSet EnumerationTypes; 7683 7684 /// The set of vector types that will be used in the built-in 7685 /// candidates. 7686 TypeSet VectorTypes; 7687 7688 /// A flag indicating non-record types are viable candidates 7689 bool HasNonRecordTypes; 7690 7691 /// A flag indicating whether either arithmetic or enumeration types 7692 /// were present in the candidate set. 7693 bool HasArithmeticOrEnumeralTypes; 7694 7695 /// A flag indicating whether the nullptr type was present in the 7696 /// candidate set. 7697 bool HasNullPtrType; 7698 7699 /// Sema - The semantic analysis instance where we are building the 7700 /// candidate type set. 7701 Sema &SemaRef; 7702 7703 /// Context - The AST context in which we will build the type sets. 7704 ASTContext &Context; 7705 7706 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7707 const Qualifiers &VisibleQuals); 7708 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7709 7710 public: 7711 /// iterator - Iterates through the types that are part of the set. 7712 typedef TypeSet::iterator iterator; 7713 7714 BuiltinCandidateTypeSet(Sema &SemaRef) 7715 : HasNonRecordTypes(false), 7716 HasArithmeticOrEnumeralTypes(false), 7717 HasNullPtrType(false), 7718 SemaRef(SemaRef), 7719 Context(SemaRef.Context) { } 7720 7721 void AddTypesConvertedFrom(QualType Ty, 7722 SourceLocation Loc, 7723 bool AllowUserConversions, 7724 bool AllowExplicitConversions, 7725 const Qualifiers &VisibleTypeConversionsQuals); 7726 7727 /// pointer_begin - First pointer type found; 7728 iterator pointer_begin() { return PointerTypes.begin(); } 7729 7730 /// pointer_end - Past the last pointer type found; 7731 iterator pointer_end() { return PointerTypes.end(); } 7732 7733 /// member_pointer_begin - First member pointer type found; 7734 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7735 7736 /// member_pointer_end - Past the last member pointer type found; 7737 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7738 7739 /// enumeration_begin - First enumeration type found; 7740 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7741 7742 /// enumeration_end - Past the last enumeration type found; 7743 iterator enumeration_end() { return EnumerationTypes.end(); } 7744 7745 iterator vector_begin() { return VectorTypes.begin(); } 7746 iterator vector_end() { return VectorTypes.end(); } 7747 7748 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7749 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7750 bool hasNullPtrType() const { return HasNullPtrType; } 7751 }; 7752 7753 } // end anonymous namespace 7754 7755 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7756 /// the set of pointer types along with any more-qualified variants of 7757 /// that type. For example, if @p Ty is "int const *", this routine 7758 /// will add "int const *", "int const volatile *", "int const 7759 /// restrict *", and "int const volatile restrict *" to the set of 7760 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7761 /// false otherwise. 7762 /// 7763 /// FIXME: what to do about extended qualifiers? 7764 bool 7765 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7766 const Qualifiers &VisibleQuals) { 7767 7768 // Insert this type. 7769 if (!PointerTypes.insert(Ty)) 7770 return false; 7771 7772 QualType PointeeTy; 7773 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7774 bool buildObjCPtr = false; 7775 if (!PointerTy) { 7776 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7777 PointeeTy = PTy->getPointeeType(); 7778 buildObjCPtr = true; 7779 } else { 7780 PointeeTy = PointerTy->getPointeeType(); 7781 } 7782 7783 // Don't add qualified variants of arrays. For one, they're not allowed 7784 // (the qualifier would sink to the element type), and for another, the 7785 // only overload situation where it matters is subscript or pointer +- int, 7786 // and those shouldn't have qualifier variants anyway. 7787 if (PointeeTy->isArrayType()) 7788 return true; 7789 7790 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7791 bool hasVolatile = VisibleQuals.hasVolatile(); 7792 bool hasRestrict = VisibleQuals.hasRestrict(); 7793 7794 // Iterate through all strict supersets of BaseCVR. 7795 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7796 if ((CVR | BaseCVR) != CVR) continue; 7797 // Skip over volatile if no volatile found anywhere in the types. 7798 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7799 7800 // Skip over restrict if no restrict found anywhere in the types, or if 7801 // the type cannot be restrict-qualified. 7802 if ((CVR & Qualifiers::Restrict) && 7803 (!hasRestrict || 7804 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7805 continue; 7806 7807 // Build qualified pointee type. 7808 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7809 7810 // Build qualified pointer type. 7811 QualType QPointerTy; 7812 if (!buildObjCPtr) 7813 QPointerTy = Context.getPointerType(QPointeeTy); 7814 else 7815 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7816 7817 // Insert qualified pointer type. 7818 PointerTypes.insert(QPointerTy); 7819 } 7820 7821 return true; 7822 } 7823 7824 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7825 /// to the set of pointer types along with any more-qualified variants of 7826 /// that type. For example, if @p Ty is "int const *", this routine 7827 /// will add "int const *", "int const volatile *", "int const 7828 /// restrict *", and "int const volatile restrict *" to the set of 7829 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7830 /// false otherwise. 7831 /// 7832 /// FIXME: what to do about extended qualifiers? 7833 bool 7834 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7835 QualType Ty) { 7836 // Insert this type. 7837 if (!MemberPointerTypes.insert(Ty)) 7838 return false; 7839 7840 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7841 assert(PointerTy && "type was not a member pointer type!"); 7842 7843 QualType PointeeTy = PointerTy->getPointeeType(); 7844 // Don't add qualified variants of arrays. For one, they're not allowed 7845 // (the qualifier would sink to the element type), and for another, the 7846 // only overload situation where it matters is subscript or pointer +- int, 7847 // and those shouldn't have qualifier variants anyway. 7848 if (PointeeTy->isArrayType()) 7849 return true; 7850 const Type *ClassTy = PointerTy->getClass(); 7851 7852 // Iterate through all strict supersets of the pointee type's CVR 7853 // qualifiers. 7854 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7855 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7856 if ((CVR | BaseCVR) != CVR) continue; 7857 7858 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7859 MemberPointerTypes.insert( 7860 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7861 } 7862 7863 return true; 7864 } 7865 7866 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7867 /// Ty can be implicit converted to the given set of @p Types. We're 7868 /// primarily interested in pointer types and enumeration types. We also 7869 /// take member pointer types, for the conditional operator. 7870 /// AllowUserConversions is true if we should look at the conversion 7871 /// functions of a class type, and AllowExplicitConversions if we 7872 /// should also include the explicit conversion functions of a class 7873 /// type. 7874 void 7875 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7876 SourceLocation Loc, 7877 bool AllowUserConversions, 7878 bool AllowExplicitConversions, 7879 const Qualifiers &VisibleQuals) { 7880 // Only deal with canonical types. 7881 Ty = Context.getCanonicalType(Ty); 7882 7883 // Look through reference types; they aren't part of the type of an 7884 // expression for the purposes of conversions. 7885 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7886 Ty = RefTy->getPointeeType(); 7887 7888 // If we're dealing with an array type, decay to the pointer. 7889 if (Ty->isArrayType()) 7890 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7891 7892 // Otherwise, we don't care about qualifiers on the type. 7893 Ty = Ty.getLocalUnqualifiedType(); 7894 7895 // Flag if we ever add a non-record type. 7896 const RecordType *TyRec = Ty->getAs<RecordType>(); 7897 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7898 7899 // Flag if we encounter an arithmetic type. 7900 HasArithmeticOrEnumeralTypes = 7901 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7902 7903 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7904 PointerTypes.insert(Ty); 7905 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7906 // Insert our type, and its more-qualified variants, into the set 7907 // of types. 7908 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7909 return; 7910 } else if (Ty->isMemberPointerType()) { 7911 // Member pointers are far easier, since the pointee can't be converted. 7912 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7913 return; 7914 } else if (Ty->isEnumeralType()) { 7915 HasArithmeticOrEnumeralTypes = true; 7916 EnumerationTypes.insert(Ty); 7917 } else if (Ty->isVectorType()) { 7918 // We treat vector types as arithmetic types in many contexts as an 7919 // extension. 7920 HasArithmeticOrEnumeralTypes = true; 7921 VectorTypes.insert(Ty); 7922 } else if (Ty->isNullPtrType()) { 7923 HasNullPtrType = true; 7924 } else if (AllowUserConversions && TyRec) { 7925 // No conversion functions in incomplete types. 7926 if (!SemaRef.isCompleteType(Loc, Ty)) 7927 return; 7928 7929 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7930 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7931 if (isa<UsingShadowDecl>(D)) 7932 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7933 7934 // Skip conversion function templates; they don't tell us anything 7935 // about which builtin types we can convert to. 7936 if (isa<FunctionTemplateDecl>(D)) 7937 continue; 7938 7939 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7940 if (AllowExplicitConversions || !Conv->isExplicit()) { 7941 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7942 VisibleQuals); 7943 } 7944 } 7945 } 7946 } 7947 /// Helper function for adjusting address spaces for the pointer or reference 7948 /// operands of builtin operators depending on the argument. 7949 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7950 Expr *Arg) { 7951 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7952 } 7953 7954 /// Helper function for AddBuiltinOperatorCandidates() that adds 7955 /// the volatile- and non-volatile-qualified assignment operators for the 7956 /// given type to the candidate set. 7957 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7958 QualType T, 7959 ArrayRef<Expr *> Args, 7960 OverloadCandidateSet &CandidateSet) { 7961 QualType ParamTypes[2]; 7962 7963 // T& operator=(T&, T) 7964 ParamTypes[0] = S.Context.getLValueReferenceType( 7965 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7966 ParamTypes[1] = T; 7967 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7968 /*IsAssignmentOperator=*/true); 7969 7970 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7971 // volatile T& operator=(volatile T&, T) 7972 ParamTypes[0] = S.Context.getLValueReferenceType( 7973 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7974 Args[0])); 7975 ParamTypes[1] = T; 7976 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7977 /*IsAssignmentOperator=*/true); 7978 } 7979 } 7980 7981 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7982 /// if any, found in visible type conversion functions found in ArgExpr's type. 7983 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7984 Qualifiers VRQuals; 7985 const RecordType *TyRec; 7986 if (const MemberPointerType *RHSMPType = 7987 ArgExpr->getType()->getAs<MemberPointerType>()) 7988 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7989 else 7990 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7991 if (!TyRec) { 7992 // Just to be safe, assume the worst case. 7993 VRQuals.addVolatile(); 7994 VRQuals.addRestrict(); 7995 return VRQuals; 7996 } 7997 7998 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7999 if (!ClassDecl->hasDefinition()) 8000 return VRQuals; 8001 8002 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8003 if (isa<UsingShadowDecl>(D)) 8004 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8005 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8006 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8007 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8008 CanTy = ResTypeRef->getPointeeType(); 8009 // Need to go down the pointer/mempointer chain and add qualifiers 8010 // as see them. 8011 bool done = false; 8012 while (!done) { 8013 if (CanTy.isRestrictQualified()) 8014 VRQuals.addRestrict(); 8015 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8016 CanTy = ResTypePtr->getPointeeType(); 8017 else if (const MemberPointerType *ResTypeMPtr = 8018 CanTy->getAs<MemberPointerType>()) 8019 CanTy = ResTypeMPtr->getPointeeType(); 8020 else 8021 done = true; 8022 if (CanTy.isVolatileQualified()) 8023 VRQuals.addVolatile(); 8024 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8025 return VRQuals; 8026 } 8027 } 8028 } 8029 return VRQuals; 8030 } 8031 8032 namespace { 8033 8034 /// Helper class to manage the addition of builtin operator overload 8035 /// candidates. It provides shared state and utility methods used throughout 8036 /// the process, as well as a helper method to add each group of builtin 8037 /// operator overloads from the standard to a candidate set. 8038 class BuiltinOperatorOverloadBuilder { 8039 // Common instance state available to all overload candidate addition methods. 8040 Sema &S; 8041 ArrayRef<Expr *> Args; 8042 Qualifiers VisibleTypeConversionsQuals; 8043 bool HasArithmeticOrEnumeralCandidateType; 8044 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8045 OverloadCandidateSet &CandidateSet; 8046 8047 static constexpr int ArithmeticTypesCap = 24; 8048 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8049 8050 // Define some indices used to iterate over the arithmetic types in 8051 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8052 // types are that preserved by promotion (C++ [over.built]p2). 8053 unsigned FirstIntegralType, 8054 LastIntegralType; 8055 unsigned FirstPromotedIntegralType, 8056 LastPromotedIntegralType; 8057 unsigned FirstPromotedArithmeticType, 8058 LastPromotedArithmeticType; 8059 unsigned NumArithmeticTypes; 8060 8061 void InitArithmeticTypes() { 8062 // Start of promoted types. 8063 FirstPromotedArithmeticType = 0; 8064 ArithmeticTypes.push_back(S.Context.FloatTy); 8065 ArithmeticTypes.push_back(S.Context.DoubleTy); 8066 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8067 if (S.Context.getTargetInfo().hasFloat128Type()) 8068 ArithmeticTypes.push_back(S.Context.Float128Ty); 8069 8070 // Start of integral types. 8071 FirstIntegralType = ArithmeticTypes.size(); 8072 FirstPromotedIntegralType = ArithmeticTypes.size(); 8073 ArithmeticTypes.push_back(S.Context.IntTy); 8074 ArithmeticTypes.push_back(S.Context.LongTy); 8075 ArithmeticTypes.push_back(S.Context.LongLongTy); 8076 if (S.Context.getTargetInfo().hasInt128Type()) 8077 ArithmeticTypes.push_back(S.Context.Int128Ty); 8078 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8079 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8080 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8081 if (S.Context.getTargetInfo().hasInt128Type()) 8082 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8083 LastPromotedIntegralType = ArithmeticTypes.size(); 8084 LastPromotedArithmeticType = ArithmeticTypes.size(); 8085 // End of promoted types. 8086 8087 ArithmeticTypes.push_back(S.Context.BoolTy); 8088 ArithmeticTypes.push_back(S.Context.CharTy); 8089 ArithmeticTypes.push_back(S.Context.WCharTy); 8090 if (S.Context.getLangOpts().Char8) 8091 ArithmeticTypes.push_back(S.Context.Char8Ty); 8092 ArithmeticTypes.push_back(S.Context.Char16Ty); 8093 ArithmeticTypes.push_back(S.Context.Char32Ty); 8094 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8095 ArithmeticTypes.push_back(S.Context.ShortTy); 8096 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8097 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8098 LastIntegralType = ArithmeticTypes.size(); 8099 NumArithmeticTypes = ArithmeticTypes.size(); 8100 // End of integral types. 8101 // FIXME: What about complex? What about half? 8102 8103 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8104 "Enough inline storage for all arithmetic types."); 8105 } 8106 8107 /// Helper method to factor out the common pattern of adding overloads 8108 /// for '++' and '--' builtin operators. 8109 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8110 bool HasVolatile, 8111 bool HasRestrict) { 8112 QualType ParamTypes[2] = { 8113 S.Context.getLValueReferenceType(CandidateTy), 8114 S.Context.IntTy 8115 }; 8116 8117 // Non-volatile version. 8118 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8119 8120 // Use a heuristic to reduce number of builtin candidates in the set: 8121 // add volatile version only if there are conversions to a volatile type. 8122 if (HasVolatile) { 8123 ParamTypes[0] = 8124 S.Context.getLValueReferenceType( 8125 S.Context.getVolatileType(CandidateTy)); 8126 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8127 } 8128 8129 // Add restrict version only if there are conversions to a restrict type 8130 // and our candidate type is a non-restrict-qualified pointer. 8131 if (HasRestrict && CandidateTy->isAnyPointerType() && 8132 !CandidateTy.isRestrictQualified()) { 8133 ParamTypes[0] 8134 = S.Context.getLValueReferenceType( 8135 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8136 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8137 8138 if (HasVolatile) { 8139 ParamTypes[0] 8140 = S.Context.getLValueReferenceType( 8141 S.Context.getCVRQualifiedType(CandidateTy, 8142 (Qualifiers::Volatile | 8143 Qualifiers::Restrict))); 8144 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8145 } 8146 } 8147 8148 } 8149 8150 public: 8151 BuiltinOperatorOverloadBuilder( 8152 Sema &S, ArrayRef<Expr *> Args, 8153 Qualifiers VisibleTypeConversionsQuals, 8154 bool HasArithmeticOrEnumeralCandidateType, 8155 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8156 OverloadCandidateSet &CandidateSet) 8157 : S(S), Args(Args), 8158 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8159 HasArithmeticOrEnumeralCandidateType( 8160 HasArithmeticOrEnumeralCandidateType), 8161 CandidateTypes(CandidateTypes), 8162 CandidateSet(CandidateSet) { 8163 8164 InitArithmeticTypes(); 8165 } 8166 8167 // Increment is deprecated for bool since C++17. 8168 // 8169 // C++ [over.built]p3: 8170 // 8171 // For every pair (T, VQ), where T is an arithmetic type other 8172 // than bool, and VQ is either volatile or empty, there exist 8173 // candidate operator functions of the form 8174 // 8175 // VQ T& operator++(VQ T&); 8176 // T operator++(VQ T&, int); 8177 // 8178 // C++ [over.built]p4: 8179 // 8180 // For every pair (T, VQ), where T is an arithmetic type other 8181 // than bool, and VQ is either volatile or empty, there exist 8182 // candidate operator functions of the form 8183 // 8184 // VQ T& operator--(VQ T&); 8185 // T operator--(VQ T&, int); 8186 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8187 if (!HasArithmeticOrEnumeralCandidateType) 8188 return; 8189 8190 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8191 const auto TypeOfT = ArithmeticTypes[Arith]; 8192 if (TypeOfT == S.Context.BoolTy) { 8193 if (Op == OO_MinusMinus) 8194 continue; 8195 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8196 continue; 8197 } 8198 addPlusPlusMinusMinusStyleOverloads( 8199 TypeOfT, 8200 VisibleTypeConversionsQuals.hasVolatile(), 8201 VisibleTypeConversionsQuals.hasRestrict()); 8202 } 8203 } 8204 8205 // C++ [over.built]p5: 8206 // 8207 // For every pair (T, VQ), where T is a cv-qualified or 8208 // cv-unqualified object type, and VQ is either volatile or 8209 // empty, there exist candidate operator functions of the form 8210 // 8211 // T*VQ& operator++(T*VQ&); 8212 // T*VQ& operator--(T*VQ&); 8213 // T* operator++(T*VQ&, int); 8214 // T* operator--(T*VQ&, int); 8215 void addPlusPlusMinusMinusPointerOverloads() { 8216 for (BuiltinCandidateTypeSet::iterator 8217 Ptr = CandidateTypes[0].pointer_begin(), 8218 PtrEnd = CandidateTypes[0].pointer_end(); 8219 Ptr != PtrEnd; ++Ptr) { 8220 // Skip pointer types that aren't pointers to object types. 8221 if (!(*Ptr)->getPointeeType()->isObjectType()) 8222 continue; 8223 8224 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8225 (!(*Ptr).isVolatileQualified() && 8226 VisibleTypeConversionsQuals.hasVolatile()), 8227 (!(*Ptr).isRestrictQualified() && 8228 VisibleTypeConversionsQuals.hasRestrict())); 8229 } 8230 } 8231 8232 // C++ [over.built]p6: 8233 // For every cv-qualified or cv-unqualified object type T, there 8234 // exist candidate operator functions of the form 8235 // 8236 // T& operator*(T*); 8237 // 8238 // C++ [over.built]p7: 8239 // For every function type T that does not have cv-qualifiers or a 8240 // ref-qualifier, there exist candidate operator functions of the form 8241 // T& operator*(T*); 8242 void addUnaryStarPointerOverloads() { 8243 for (BuiltinCandidateTypeSet::iterator 8244 Ptr = CandidateTypes[0].pointer_begin(), 8245 PtrEnd = CandidateTypes[0].pointer_end(); 8246 Ptr != PtrEnd; ++Ptr) { 8247 QualType ParamTy = *Ptr; 8248 QualType PointeeTy = ParamTy->getPointeeType(); 8249 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8250 continue; 8251 8252 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8253 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8254 continue; 8255 8256 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8257 } 8258 } 8259 8260 // C++ [over.built]p9: 8261 // For every promoted arithmetic type T, there exist candidate 8262 // operator functions of the form 8263 // 8264 // T operator+(T); 8265 // T operator-(T); 8266 void addUnaryPlusOrMinusArithmeticOverloads() { 8267 if (!HasArithmeticOrEnumeralCandidateType) 8268 return; 8269 8270 for (unsigned Arith = FirstPromotedArithmeticType; 8271 Arith < LastPromotedArithmeticType; ++Arith) { 8272 QualType ArithTy = ArithmeticTypes[Arith]; 8273 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8274 } 8275 8276 // Extension: We also add these operators for vector types. 8277 for (BuiltinCandidateTypeSet::iterator 8278 Vec = CandidateTypes[0].vector_begin(), 8279 VecEnd = CandidateTypes[0].vector_end(); 8280 Vec != VecEnd; ++Vec) { 8281 QualType VecTy = *Vec; 8282 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8283 } 8284 } 8285 8286 // C++ [over.built]p8: 8287 // For every type T, there exist candidate operator functions of 8288 // the form 8289 // 8290 // T* operator+(T*); 8291 void addUnaryPlusPointerOverloads() { 8292 for (BuiltinCandidateTypeSet::iterator 8293 Ptr = CandidateTypes[0].pointer_begin(), 8294 PtrEnd = CandidateTypes[0].pointer_end(); 8295 Ptr != PtrEnd; ++Ptr) { 8296 QualType ParamTy = *Ptr; 8297 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8298 } 8299 } 8300 8301 // C++ [over.built]p10: 8302 // For every promoted integral type T, there exist candidate 8303 // operator functions of the form 8304 // 8305 // T operator~(T); 8306 void addUnaryTildePromotedIntegralOverloads() { 8307 if (!HasArithmeticOrEnumeralCandidateType) 8308 return; 8309 8310 for (unsigned Int = FirstPromotedIntegralType; 8311 Int < LastPromotedIntegralType; ++Int) { 8312 QualType IntTy = ArithmeticTypes[Int]; 8313 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8314 } 8315 8316 // Extension: We also add this operator for vector types. 8317 for (BuiltinCandidateTypeSet::iterator 8318 Vec = CandidateTypes[0].vector_begin(), 8319 VecEnd = CandidateTypes[0].vector_end(); 8320 Vec != VecEnd; ++Vec) { 8321 QualType VecTy = *Vec; 8322 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8323 } 8324 } 8325 8326 // C++ [over.match.oper]p16: 8327 // For every pointer to member type T or type std::nullptr_t, there 8328 // exist candidate operator functions of the form 8329 // 8330 // bool operator==(T,T); 8331 // bool operator!=(T,T); 8332 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8333 /// Set of (canonical) types that we've already handled. 8334 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8335 8336 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8337 for (BuiltinCandidateTypeSet::iterator 8338 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8339 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8340 MemPtr != MemPtrEnd; 8341 ++MemPtr) { 8342 // Don't add the same builtin candidate twice. 8343 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8344 continue; 8345 8346 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8347 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8348 } 8349 8350 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8351 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8352 if (AddedTypes.insert(NullPtrTy).second) { 8353 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8354 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8355 } 8356 } 8357 } 8358 } 8359 8360 // C++ [over.built]p15: 8361 // 8362 // For every T, where T is an enumeration type or a pointer type, 8363 // there exist candidate operator functions of the form 8364 // 8365 // bool operator<(T, T); 8366 // bool operator>(T, T); 8367 // bool operator<=(T, T); 8368 // bool operator>=(T, T); 8369 // bool operator==(T, T); 8370 // bool operator!=(T, T); 8371 // R operator<=>(T, T) 8372 void addGenericBinaryPointerOrEnumeralOverloads() { 8373 // C++ [over.match.oper]p3: 8374 // [...]the built-in candidates include all of the candidate operator 8375 // functions defined in 13.6 that, compared to the given operator, [...] 8376 // do not have the same parameter-type-list as any non-template non-member 8377 // candidate. 8378 // 8379 // Note that in practice, this only affects enumeration types because there 8380 // aren't any built-in candidates of record type, and a user-defined operator 8381 // must have an operand of record or enumeration type. Also, the only other 8382 // overloaded operator with enumeration arguments, operator=, 8383 // cannot be overloaded for enumeration types, so this is the only place 8384 // where we must suppress candidates like this. 8385 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8386 UserDefinedBinaryOperators; 8387 8388 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8389 if (CandidateTypes[ArgIdx].enumeration_begin() != 8390 CandidateTypes[ArgIdx].enumeration_end()) { 8391 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8392 CEnd = CandidateSet.end(); 8393 C != CEnd; ++C) { 8394 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8395 continue; 8396 8397 if (C->Function->isFunctionTemplateSpecialization()) 8398 continue; 8399 8400 // We interpret "same parameter-type-list" as applying to the 8401 // "synthesized candidate, with the order of the two parameters 8402 // reversed", not to the original function. 8403 bool Reversed = C->isReversed(); 8404 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8405 ->getType() 8406 .getUnqualifiedType(); 8407 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8408 ->getType() 8409 .getUnqualifiedType(); 8410 8411 // Skip if either parameter isn't of enumeral type. 8412 if (!FirstParamType->isEnumeralType() || 8413 !SecondParamType->isEnumeralType()) 8414 continue; 8415 8416 // Add this operator to the set of known user-defined operators. 8417 UserDefinedBinaryOperators.insert( 8418 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8419 S.Context.getCanonicalType(SecondParamType))); 8420 } 8421 } 8422 } 8423 8424 /// Set of (canonical) types that we've already handled. 8425 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8426 8427 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8428 for (BuiltinCandidateTypeSet::iterator 8429 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8430 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8431 Ptr != PtrEnd; ++Ptr) { 8432 // Don't add the same builtin candidate twice. 8433 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8434 continue; 8435 8436 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8437 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8438 } 8439 for (BuiltinCandidateTypeSet::iterator 8440 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8441 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8442 Enum != EnumEnd; ++Enum) { 8443 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8444 8445 // Don't add the same builtin candidate twice, or if a user defined 8446 // candidate exists. 8447 if (!AddedTypes.insert(CanonType).second || 8448 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8449 CanonType))) 8450 continue; 8451 QualType ParamTypes[2] = { *Enum, *Enum }; 8452 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8453 } 8454 } 8455 } 8456 8457 // C++ [over.built]p13: 8458 // 8459 // For every cv-qualified or cv-unqualified object type T 8460 // there exist candidate operator functions of the form 8461 // 8462 // T* operator+(T*, ptrdiff_t); 8463 // T& operator[](T*, ptrdiff_t); [BELOW] 8464 // T* operator-(T*, ptrdiff_t); 8465 // T* operator+(ptrdiff_t, T*); 8466 // T& operator[](ptrdiff_t, T*); [BELOW] 8467 // 8468 // C++ [over.built]p14: 8469 // 8470 // For every T, where T is a pointer to object type, there 8471 // exist candidate operator functions of the form 8472 // 8473 // ptrdiff_t operator-(T, T); 8474 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8475 /// Set of (canonical) types that we've already handled. 8476 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8477 8478 for (int Arg = 0; Arg < 2; ++Arg) { 8479 QualType AsymmetricParamTypes[2] = { 8480 S.Context.getPointerDiffType(), 8481 S.Context.getPointerDiffType(), 8482 }; 8483 for (BuiltinCandidateTypeSet::iterator 8484 Ptr = CandidateTypes[Arg].pointer_begin(), 8485 PtrEnd = CandidateTypes[Arg].pointer_end(); 8486 Ptr != PtrEnd; ++Ptr) { 8487 QualType PointeeTy = (*Ptr)->getPointeeType(); 8488 if (!PointeeTy->isObjectType()) 8489 continue; 8490 8491 AsymmetricParamTypes[Arg] = *Ptr; 8492 if (Arg == 0 || Op == OO_Plus) { 8493 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8494 // T* operator+(ptrdiff_t, T*); 8495 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8496 } 8497 if (Op == OO_Minus) { 8498 // ptrdiff_t operator-(T, T); 8499 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8500 continue; 8501 8502 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8503 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8504 } 8505 } 8506 } 8507 } 8508 8509 // C++ [over.built]p12: 8510 // 8511 // For every pair of promoted arithmetic types L and R, there 8512 // exist candidate operator functions of the form 8513 // 8514 // LR operator*(L, R); 8515 // LR operator/(L, R); 8516 // LR operator+(L, R); 8517 // LR operator-(L, R); 8518 // bool operator<(L, R); 8519 // bool operator>(L, R); 8520 // bool operator<=(L, R); 8521 // bool operator>=(L, R); 8522 // bool operator==(L, R); 8523 // bool operator!=(L, R); 8524 // 8525 // where LR is the result of the usual arithmetic conversions 8526 // between types L and R. 8527 // 8528 // C++ [over.built]p24: 8529 // 8530 // For every pair of promoted arithmetic types L and R, there exist 8531 // candidate operator functions of the form 8532 // 8533 // LR operator?(bool, L, R); 8534 // 8535 // where LR is the result of the usual arithmetic conversions 8536 // between types L and R. 8537 // Our candidates ignore the first parameter. 8538 void addGenericBinaryArithmeticOverloads() { 8539 if (!HasArithmeticOrEnumeralCandidateType) 8540 return; 8541 8542 for (unsigned Left = FirstPromotedArithmeticType; 8543 Left < LastPromotedArithmeticType; ++Left) { 8544 for (unsigned Right = FirstPromotedArithmeticType; 8545 Right < LastPromotedArithmeticType; ++Right) { 8546 QualType LandR[2] = { ArithmeticTypes[Left], 8547 ArithmeticTypes[Right] }; 8548 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8549 } 8550 } 8551 8552 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8553 // conditional operator for vector types. 8554 for (BuiltinCandidateTypeSet::iterator 8555 Vec1 = CandidateTypes[0].vector_begin(), 8556 Vec1End = CandidateTypes[0].vector_end(); 8557 Vec1 != Vec1End; ++Vec1) { 8558 for (BuiltinCandidateTypeSet::iterator 8559 Vec2 = CandidateTypes[1].vector_begin(), 8560 Vec2End = CandidateTypes[1].vector_end(); 8561 Vec2 != Vec2End; ++Vec2) { 8562 QualType LandR[2] = { *Vec1, *Vec2 }; 8563 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8564 } 8565 } 8566 } 8567 8568 // C++2a [over.built]p14: 8569 // 8570 // For every integral type T there exists a candidate operator function 8571 // of the form 8572 // 8573 // std::strong_ordering operator<=>(T, T) 8574 // 8575 // C++2a [over.built]p15: 8576 // 8577 // For every pair of floating-point types L and R, there exists a candidate 8578 // operator function of the form 8579 // 8580 // std::partial_ordering operator<=>(L, R); 8581 // 8582 // FIXME: The current specification for integral types doesn't play nice with 8583 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8584 // comparisons. Under the current spec this can lead to ambiguity during 8585 // overload resolution. For example: 8586 // 8587 // enum A : int {a}; 8588 // auto x = (a <=> (long)42); 8589 // 8590 // error: call is ambiguous for arguments 'A' and 'long'. 8591 // note: candidate operator<=>(int, int) 8592 // note: candidate operator<=>(long, long) 8593 // 8594 // To avoid this error, this function deviates from the specification and adds 8595 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8596 // arithmetic types (the same as the generic relational overloads). 8597 // 8598 // For now this function acts as a placeholder. 8599 void addThreeWayArithmeticOverloads() { 8600 addGenericBinaryArithmeticOverloads(); 8601 } 8602 8603 // C++ [over.built]p17: 8604 // 8605 // For every pair of promoted integral types L and R, there 8606 // exist candidate operator functions of the form 8607 // 8608 // LR operator%(L, R); 8609 // LR operator&(L, R); 8610 // LR operator^(L, R); 8611 // LR operator|(L, R); 8612 // L operator<<(L, R); 8613 // L operator>>(L, R); 8614 // 8615 // where LR is the result of the usual arithmetic conversions 8616 // between types L and R. 8617 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8618 if (!HasArithmeticOrEnumeralCandidateType) 8619 return; 8620 8621 for (unsigned Left = FirstPromotedIntegralType; 8622 Left < LastPromotedIntegralType; ++Left) { 8623 for (unsigned Right = FirstPromotedIntegralType; 8624 Right < LastPromotedIntegralType; ++Right) { 8625 QualType LandR[2] = { ArithmeticTypes[Left], 8626 ArithmeticTypes[Right] }; 8627 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8628 } 8629 } 8630 } 8631 8632 // C++ [over.built]p20: 8633 // 8634 // For every pair (T, VQ), where T is an enumeration or 8635 // pointer to member type and VQ is either volatile or 8636 // empty, there exist candidate operator functions of the form 8637 // 8638 // VQ T& operator=(VQ T&, T); 8639 void addAssignmentMemberPointerOrEnumeralOverloads() { 8640 /// Set of (canonical) types that we've already handled. 8641 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8642 8643 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8644 for (BuiltinCandidateTypeSet::iterator 8645 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8646 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8647 Enum != EnumEnd; ++Enum) { 8648 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8649 continue; 8650 8651 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8652 } 8653 8654 for (BuiltinCandidateTypeSet::iterator 8655 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8656 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8657 MemPtr != MemPtrEnd; ++MemPtr) { 8658 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8659 continue; 8660 8661 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8662 } 8663 } 8664 } 8665 8666 // C++ [over.built]p19: 8667 // 8668 // For every pair (T, VQ), where T is any type and VQ is either 8669 // volatile or empty, there exist candidate operator functions 8670 // of the form 8671 // 8672 // T*VQ& operator=(T*VQ&, T*); 8673 // 8674 // C++ [over.built]p21: 8675 // 8676 // For every pair (T, VQ), where T is a cv-qualified or 8677 // cv-unqualified object type and VQ is either volatile or 8678 // empty, there exist candidate operator functions of the form 8679 // 8680 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8681 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8682 void addAssignmentPointerOverloads(bool isEqualOp) { 8683 /// Set of (canonical) types that we've already handled. 8684 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8685 8686 for (BuiltinCandidateTypeSet::iterator 8687 Ptr = CandidateTypes[0].pointer_begin(), 8688 PtrEnd = CandidateTypes[0].pointer_end(); 8689 Ptr != PtrEnd; ++Ptr) { 8690 // If this is operator=, keep track of the builtin candidates we added. 8691 if (isEqualOp) 8692 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8693 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8694 continue; 8695 8696 // non-volatile version 8697 QualType ParamTypes[2] = { 8698 S.Context.getLValueReferenceType(*Ptr), 8699 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8700 }; 8701 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8702 /*IsAssignmentOperator=*/ isEqualOp); 8703 8704 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8705 VisibleTypeConversionsQuals.hasVolatile(); 8706 if (NeedVolatile) { 8707 // volatile version 8708 ParamTypes[0] = 8709 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8710 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8711 /*IsAssignmentOperator=*/isEqualOp); 8712 } 8713 8714 if (!(*Ptr).isRestrictQualified() && 8715 VisibleTypeConversionsQuals.hasRestrict()) { 8716 // restrict version 8717 ParamTypes[0] 8718 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8719 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8720 /*IsAssignmentOperator=*/isEqualOp); 8721 8722 if (NeedVolatile) { 8723 // volatile restrict version 8724 ParamTypes[0] 8725 = S.Context.getLValueReferenceType( 8726 S.Context.getCVRQualifiedType(*Ptr, 8727 (Qualifiers::Volatile | 8728 Qualifiers::Restrict))); 8729 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8730 /*IsAssignmentOperator=*/isEqualOp); 8731 } 8732 } 8733 } 8734 8735 if (isEqualOp) { 8736 for (BuiltinCandidateTypeSet::iterator 8737 Ptr = CandidateTypes[1].pointer_begin(), 8738 PtrEnd = CandidateTypes[1].pointer_end(); 8739 Ptr != PtrEnd; ++Ptr) { 8740 // Make sure we don't add the same candidate twice. 8741 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8742 continue; 8743 8744 QualType ParamTypes[2] = { 8745 S.Context.getLValueReferenceType(*Ptr), 8746 *Ptr, 8747 }; 8748 8749 // non-volatile version 8750 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8751 /*IsAssignmentOperator=*/true); 8752 8753 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8754 VisibleTypeConversionsQuals.hasVolatile(); 8755 if (NeedVolatile) { 8756 // volatile version 8757 ParamTypes[0] = 8758 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8759 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8760 /*IsAssignmentOperator=*/true); 8761 } 8762 8763 if (!(*Ptr).isRestrictQualified() && 8764 VisibleTypeConversionsQuals.hasRestrict()) { 8765 // restrict version 8766 ParamTypes[0] 8767 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8768 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8769 /*IsAssignmentOperator=*/true); 8770 8771 if (NeedVolatile) { 8772 // volatile restrict version 8773 ParamTypes[0] 8774 = S.Context.getLValueReferenceType( 8775 S.Context.getCVRQualifiedType(*Ptr, 8776 (Qualifiers::Volatile | 8777 Qualifiers::Restrict))); 8778 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8779 /*IsAssignmentOperator=*/true); 8780 } 8781 } 8782 } 8783 } 8784 } 8785 8786 // C++ [over.built]p18: 8787 // 8788 // For every triple (L, VQ, R), where L is an arithmetic type, 8789 // VQ is either volatile or empty, and R is a promoted 8790 // arithmetic type, there exist candidate operator functions of 8791 // the form 8792 // 8793 // VQ L& operator=(VQ L&, R); 8794 // VQ L& operator*=(VQ L&, R); 8795 // VQ L& operator/=(VQ L&, R); 8796 // VQ L& operator+=(VQ L&, R); 8797 // VQ L& operator-=(VQ L&, R); 8798 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8799 if (!HasArithmeticOrEnumeralCandidateType) 8800 return; 8801 8802 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8803 for (unsigned Right = FirstPromotedArithmeticType; 8804 Right < LastPromotedArithmeticType; ++Right) { 8805 QualType ParamTypes[2]; 8806 ParamTypes[1] = ArithmeticTypes[Right]; 8807 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8808 S, ArithmeticTypes[Left], Args[0]); 8809 // Add this built-in operator as a candidate (VQ is empty). 8810 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8811 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8812 /*IsAssignmentOperator=*/isEqualOp); 8813 8814 // Add this built-in operator as a candidate (VQ is 'volatile'). 8815 if (VisibleTypeConversionsQuals.hasVolatile()) { 8816 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8817 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8818 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8819 /*IsAssignmentOperator=*/isEqualOp); 8820 } 8821 } 8822 } 8823 8824 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8825 for (BuiltinCandidateTypeSet::iterator 8826 Vec1 = CandidateTypes[0].vector_begin(), 8827 Vec1End = CandidateTypes[0].vector_end(); 8828 Vec1 != Vec1End; ++Vec1) { 8829 for (BuiltinCandidateTypeSet::iterator 8830 Vec2 = CandidateTypes[1].vector_begin(), 8831 Vec2End = CandidateTypes[1].vector_end(); 8832 Vec2 != Vec2End; ++Vec2) { 8833 QualType ParamTypes[2]; 8834 ParamTypes[1] = *Vec2; 8835 // Add this built-in operator as a candidate (VQ is empty). 8836 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8837 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8838 /*IsAssignmentOperator=*/isEqualOp); 8839 8840 // Add this built-in operator as a candidate (VQ is 'volatile'). 8841 if (VisibleTypeConversionsQuals.hasVolatile()) { 8842 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8843 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8844 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8845 /*IsAssignmentOperator=*/isEqualOp); 8846 } 8847 } 8848 } 8849 } 8850 8851 // C++ [over.built]p22: 8852 // 8853 // For every triple (L, VQ, R), where L is an integral type, VQ 8854 // is either volatile or empty, and R is a promoted integral 8855 // type, there exist candidate operator functions of the form 8856 // 8857 // VQ L& operator%=(VQ L&, R); 8858 // VQ L& operator<<=(VQ L&, R); 8859 // VQ L& operator>>=(VQ L&, R); 8860 // VQ L& operator&=(VQ L&, R); 8861 // VQ L& operator^=(VQ L&, R); 8862 // VQ L& operator|=(VQ L&, R); 8863 void addAssignmentIntegralOverloads() { 8864 if (!HasArithmeticOrEnumeralCandidateType) 8865 return; 8866 8867 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8868 for (unsigned Right = FirstPromotedIntegralType; 8869 Right < LastPromotedIntegralType; ++Right) { 8870 QualType ParamTypes[2]; 8871 ParamTypes[1] = ArithmeticTypes[Right]; 8872 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8873 S, ArithmeticTypes[Left], Args[0]); 8874 // Add this built-in operator as a candidate (VQ is empty). 8875 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8876 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8877 if (VisibleTypeConversionsQuals.hasVolatile()) { 8878 // Add this built-in operator as a candidate (VQ is 'volatile'). 8879 ParamTypes[0] = LeftBaseTy; 8880 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8881 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8882 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8883 } 8884 } 8885 } 8886 } 8887 8888 // C++ [over.operator]p23: 8889 // 8890 // There also exist candidate operator functions of the form 8891 // 8892 // bool operator!(bool); 8893 // bool operator&&(bool, bool); 8894 // bool operator||(bool, bool); 8895 void addExclaimOverload() { 8896 QualType ParamTy = S.Context.BoolTy; 8897 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8898 /*IsAssignmentOperator=*/false, 8899 /*NumContextualBoolArguments=*/1); 8900 } 8901 void addAmpAmpOrPipePipeOverload() { 8902 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8903 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8904 /*IsAssignmentOperator=*/false, 8905 /*NumContextualBoolArguments=*/2); 8906 } 8907 8908 // C++ [over.built]p13: 8909 // 8910 // For every cv-qualified or cv-unqualified object type T there 8911 // exist candidate operator functions of the form 8912 // 8913 // T* operator+(T*, ptrdiff_t); [ABOVE] 8914 // T& operator[](T*, ptrdiff_t); 8915 // T* operator-(T*, ptrdiff_t); [ABOVE] 8916 // T* operator+(ptrdiff_t, T*); [ABOVE] 8917 // T& operator[](ptrdiff_t, T*); 8918 void addSubscriptOverloads() { 8919 for (BuiltinCandidateTypeSet::iterator 8920 Ptr = CandidateTypes[0].pointer_begin(), 8921 PtrEnd = CandidateTypes[0].pointer_end(); 8922 Ptr != PtrEnd; ++Ptr) { 8923 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8924 QualType PointeeType = (*Ptr)->getPointeeType(); 8925 if (!PointeeType->isObjectType()) 8926 continue; 8927 8928 // T& operator[](T*, ptrdiff_t) 8929 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8930 } 8931 8932 for (BuiltinCandidateTypeSet::iterator 8933 Ptr = CandidateTypes[1].pointer_begin(), 8934 PtrEnd = CandidateTypes[1].pointer_end(); 8935 Ptr != PtrEnd; ++Ptr) { 8936 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8937 QualType PointeeType = (*Ptr)->getPointeeType(); 8938 if (!PointeeType->isObjectType()) 8939 continue; 8940 8941 // T& operator[](ptrdiff_t, T*) 8942 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8943 } 8944 } 8945 8946 // C++ [over.built]p11: 8947 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8948 // C1 is the same type as C2 or is a derived class of C2, T is an object 8949 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8950 // there exist candidate operator functions of the form 8951 // 8952 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8953 // 8954 // where CV12 is the union of CV1 and CV2. 8955 void addArrowStarOverloads() { 8956 for (BuiltinCandidateTypeSet::iterator 8957 Ptr = CandidateTypes[0].pointer_begin(), 8958 PtrEnd = CandidateTypes[0].pointer_end(); 8959 Ptr != PtrEnd; ++Ptr) { 8960 QualType C1Ty = (*Ptr); 8961 QualType C1; 8962 QualifierCollector Q1; 8963 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8964 if (!isa<RecordType>(C1)) 8965 continue; 8966 // heuristic to reduce number of builtin candidates in the set. 8967 // Add volatile/restrict version only if there are conversions to a 8968 // volatile/restrict type. 8969 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8970 continue; 8971 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8972 continue; 8973 for (BuiltinCandidateTypeSet::iterator 8974 MemPtr = CandidateTypes[1].member_pointer_begin(), 8975 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8976 MemPtr != MemPtrEnd; ++MemPtr) { 8977 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8978 QualType C2 = QualType(mptr->getClass(), 0); 8979 C2 = C2.getUnqualifiedType(); 8980 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8981 break; 8982 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8983 // build CV12 T& 8984 QualType T = mptr->getPointeeType(); 8985 if (!VisibleTypeConversionsQuals.hasVolatile() && 8986 T.isVolatileQualified()) 8987 continue; 8988 if (!VisibleTypeConversionsQuals.hasRestrict() && 8989 T.isRestrictQualified()) 8990 continue; 8991 T = Q1.apply(S.Context, T); 8992 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8993 } 8994 } 8995 } 8996 8997 // Note that we don't consider the first argument, since it has been 8998 // contextually converted to bool long ago. The candidates below are 8999 // therefore added as binary. 9000 // 9001 // C++ [over.built]p25: 9002 // For every type T, where T is a pointer, pointer-to-member, or scoped 9003 // enumeration type, there exist candidate operator functions of the form 9004 // 9005 // T operator?(bool, T, T); 9006 // 9007 void addConditionalOperatorOverloads() { 9008 /// Set of (canonical) types that we've already handled. 9009 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9010 9011 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9012 for (BuiltinCandidateTypeSet::iterator 9013 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 9014 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 9015 Ptr != PtrEnd; ++Ptr) { 9016 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 9017 continue; 9018 9019 QualType ParamTypes[2] = { *Ptr, *Ptr }; 9020 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9021 } 9022 9023 for (BuiltinCandidateTypeSet::iterator 9024 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 9025 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 9026 MemPtr != MemPtrEnd; ++MemPtr) { 9027 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 9028 continue; 9029 9030 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 9031 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9032 } 9033 9034 if (S.getLangOpts().CPlusPlus11) { 9035 for (BuiltinCandidateTypeSet::iterator 9036 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 9037 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 9038 Enum != EnumEnd; ++Enum) { 9039 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 9040 continue; 9041 9042 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 9043 continue; 9044 9045 QualType ParamTypes[2] = { *Enum, *Enum }; 9046 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9047 } 9048 } 9049 } 9050 } 9051 }; 9052 9053 } // end anonymous namespace 9054 9055 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9056 /// operator overloads to the candidate set (C++ [over.built]), based 9057 /// on the operator @p Op and the arguments given. For example, if the 9058 /// operator is a binary '+', this routine might add "int 9059 /// operator+(int, int)" to cover integer addition. 9060 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9061 SourceLocation OpLoc, 9062 ArrayRef<Expr *> Args, 9063 OverloadCandidateSet &CandidateSet) { 9064 // Find all of the types that the arguments can convert to, but only 9065 // if the operator we're looking at has built-in operator candidates 9066 // that make use of these types. Also record whether we encounter non-record 9067 // candidate types or either arithmetic or enumeral candidate types. 9068 Qualifiers VisibleTypeConversionsQuals; 9069 VisibleTypeConversionsQuals.addConst(); 9070 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9071 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9072 9073 bool HasNonRecordCandidateType = false; 9074 bool HasArithmeticOrEnumeralCandidateType = false; 9075 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9076 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9077 CandidateTypes.emplace_back(*this); 9078 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9079 OpLoc, 9080 true, 9081 (Op == OO_Exclaim || 9082 Op == OO_AmpAmp || 9083 Op == OO_PipePipe), 9084 VisibleTypeConversionsQuals); 9085 HasNonRecordCandidateType = HasNonRecordCandidateType || 9086 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9087 HasArithmeticOrEnumeralCandidateType = 9088 HasArithmeticOrEnumeralCandidateType || 9089 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9090 } 9091 9092 // Exit early when no non-record types have been added to the candidate set 9093 // for any of the arguments to the operator. 9094 // 9095 // We can't exit early for !, ||, or &&, since there we have always have 9096 // 'bool' overloads. 9097 if (!HasNonRecordCandidateType && 9098 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9099 return; 9100 9101 // Setup an object to manage the common state for building overloads. 9102 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9103 VisibleTypeConversionsQuals, 9104 HasArithmeticOrEnumeralCandidateType, 9105 CandidateTypes, CandidateSet); 9106 9107 // Dispatch over the operation to add in only those overloads which apply. 9108 switch (Op) { 9109 case OO_None: 9110 case NUM_OVERLOADED_OPERATORS: 9111 llvm_unreachable("Expected an overloaded operator"); 9112 9113 case OO_New: 9114 case OO_Delete: 9115 case OO_Array_New: 9116 case OO_Array_Delete: 9117 case OO_Call: 9118 llvm_unreachable( 9119 "Special operators don't use AddBuiltinOperatorCandidates"); 9120 9121 case OO_Comma: 9122 case OO_Arrow: 9123 case OO_Coawait: 9124 // C++ [over.match.oper]p3: 9125 // -- For the operator ',', the unary operator '&', the 9126 // operator '->', or the operator 'co_await', the 9127 // built-in candidates set is empty. 9128 break; 9129 9130 case OO_Plus: // '+' is either unary or binary 9131 if (Args.size() == 1) 9132 OpBuilder.addUnaryPlusPointerOverloads(); 9133 LLVM_FALLTHROUGH; 9134 9135 case OO_Minus: // '-' is either unary or binary 9136 if (Args.size() == 1) { 9137 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9138 } else { 9139 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9140 OpBuilder.addGenericBinaryArithmeticOverloads(); 9141 } 9142 break; 9143 9144 case OO_Star: // '*' is either unary or binary 9145 if (Args.size() == 1) 9146 OpBuilder.addUnaryStarPointerOverloads(); 9147 else 9148 OpBuilder.addGenericBinaryArithmeticOverloads(); 9149 break; 9150 9151 case OO_Slash: 9152 OpBuilder.addGenericBinaryArithmeticOverloads(); 9153 break; 9154 9155 case OO_PlusPlus: 9156 case OO_MinusMinus: 9157 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9158 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9159 break; 9160 9161 case OO_EqualEqual: 9162 case OO_ExclaimEqual: 9163 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9164 LLVM_FALLTHROUGH; 9165 9166 case OO_Less: 9167 case OO_Greater: 9168 case OO_LessEqual: 9169 case OO_GreaterEqual: 9170 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9171 OpBuilder.addGenericBinaryArithmeticOverloads(); 9172 break; 9173 9174 case OO_Spaceship: 9175 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9176 OpBuilder.addThreeWayArithmeticOverloads(); 9177 break; 9178 9179 case OO_Percent: 9180 case OO_Caret: 9181 case OO_Pipe: 9182 case OO_LessLess: 9183 case OO_GreaterGreater: 9184 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9185 break; 9186 9187 case OO_Amp: // '&' is either unary or binary 9188 if (Args.size() == 1) 9189 // C++ [over.match.oper]p3: 9190 // -- For the operator ',', the unary operator '&', or the 9191 // operator '->', the built-in candidates set is empty. 9192 break; 9193 9194 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9195 break; 9196 9197 case OO_Tilde: 9198 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9199 break; 9200 9201 case OO_Equal: 9202 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9203 LLVM_FALLTHROUGH; 9204 9205 case OO_PlusEqual: 9206 case OO_MinusEqual: 9207 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9208 LLVM_FALLTHROUGH; 9209 9210 case OO_StarEqual: 9211 case OO_SlashEqual: 9212 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9213 break; 9214 9215 case OO_PercentEqual: 9216 case OO_LessLessEqual: 9217 case OO_GreaterGreaterEqual: 9218 case OO_AmpEqual: 9219 case OO_CaretEqual: 9220 case OO_PipeEqual: 9221 OpBuilder.addAssignmentIntegralOverloads(); 9222 break; 9223 9224 case OO_Exclaim: 9225 OpBuilder.addExclaimOverload(); 9226 break; 9227 9228 case OO_AmpAmp: 9229 case OO_PipePipe: 9230 OpBuilder.addAmpAmpOrPipePipeOverload(); 9231 break; 9232 9233 case OO_Subscript: 9234 OpBuilder.addSubscriptOverloads(); 9235 break; 9236 9237 case OO_ArrowStar: 9238 OpBuilder.addArrowStarOverloads(); 9239 break; 9240 9241 case OO_Conditional: 9242 OpBuilder.addConditionalOperatorOverloads(); 9243 OpBuilder.addGenericBinaryArithmeticOverloads(); 9244 break; 9245 } 9246 } 9247 9248 /// Add function candidates found via argument-dependent lookup 9249 /// to the set of overloading candidates. 9250 /// 9251 /// This routine performs argument-dependent name lookup based on the 9252 /// given function name (which may also be an operator name) and adds 9253 /// all of the overload candidates found by ADL to the overload 9254 /// candidate set (C++ [basic.lookup.argdep]). 9255 void 9256 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9257 SourceLocation Loc, 9258 ArrayRef<Expr *> Args, 9259 TemplateArgumentListInfo *ExplicitTemplateArgs, 9260 OverloadCandidateSet& CandidateSet, 9261 bool PartialOverloading) { 9262 ADLResult Fns; 9263 9264 // FIXME: This approach for uniquing ADL results (and removing 9265 // redundant candidates from the set) relies on pointer-equality, 9266 // which means we need to key off the canonical decl. However, 9267 // always going back to the canonical decl might not get us the 9268 // right set of default arguments. What default arguments are 9269 // we supposed to consider on ADL candidates, anyway? 9270 9271 // FIXME: Pass in the explicit template arguments? 9272 ArgumentDependentLookup(Name, Loc, Args, Fns); 9273 9274 // Erase all of the candidates we already knew about. 9275 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9276 CandEnd = CandidateSet.end(); 9277 Cand != CandEnd; ++Cand) 9278 if (Cand->Function) { 9279 Fns.erase(Cand->Function); 9280 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9281 Fns.erase(FunTmpl); 9282 } 9283 9284 // For each of the ADL candidates we found, add it to the overload 9285 // set. 9286 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9287 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9288 9289 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9290 if (ExplicitTemplateArgs) 9291 continue; 9292 9293 AddOverloadCandidate( 9294 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9295 PartialOverloading, /*AllowExplicit=*/true, 9296 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL); 9297 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9298 AddOverloadCandidate( 9299 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9300 /*SuppressUserConversions=*/false, PartialOverloading, 9301 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false, 9302 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9303 } 9304 } else { 9305 auto *FTD = cast<FunctionTemplateDecl>(*I); 9306 AddTemplateOverloadCandidate( 9307 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9308 /*SuppressUserConversions=*/false, PartialOverloading, 9309 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9310 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9311 Context, FTD->getTemplatedDecl())) { 9312 AddTemplateOverloadCandidate( 9313 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9314 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9315 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9316 OverloadCandidateParamOrder::Reversed); 9317 } 9318 } 9319 } 9320 } 9321 9322 namespace { 9323 enum class Comparison { Equal, Better, Worse }; 9324 } 9325 9326 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9327 /// overload resolution. 9328 /// 9329 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9330 /// Cand1's first N enable_if attributes have precisely the same conditions as 9331 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9332 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9333 /// 9334 /// Note that you can have a pair of candidates such that Cand1's enable_if 9335 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9336 /// worse than Cand1's. 9337 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9338 const FunctionDecl *Cand2) { 9339 // Common case: One (or both) decls don't have enable_if attrs. 9340 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9341 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9342 if (!Cand1Attr || !Cand2Attr) { 9343 if (Cand1Attr == Cand2Attr) 9344 return Comparison::Equal; 9345 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9346 } 9347 9348 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9349 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9350 9351 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9352 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9353 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9354 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9355 9356 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9357 // has fewer enable_if attributes than Cand2, and vice versa. 9358 if (!Cand1A) 9359 return Comparison::Worse; 9360 if (!Cand2A) 9361 return Comparison::Better; 9362 9363 Cand1ID.clear(); 9364 Cand2ID.clear(); 9365 9366 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9367 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9368 if (Cand1ID != Cand2ID) 9369 return Comparison::Worse; 9370 } 9371 9372 return Comparison::Equal; 9373 } 9374 9375 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9376 const OverloadCandidate &Cand2) { 9377 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9378 !Cand2.Function->isMultiVersion()) 9379 return false; 9380 9381 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9382 // is obviously better. 9383 if (Cand1.Function->isInvalidDecl()) return false; 9384 if (Cand2.Function->isInvalidDecl()) return true; 9385 9386 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9387 // cpu_dispatch, else arbitrarily based on the identifiers. 9388 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9389 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9390 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9391 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9392 9393 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9394 return false; 9395 9396 if (Cand1CPUDisp && !Cand2CPUDisp) 9397 return true; 9398 if (Cand2CPUDisp && !Cand1CPUDisp) 9399 return false; 9400 9401 if (Cand1CPUSpec && Cand2CPUSpec) { 9402 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9403 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9404 9405 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9406 FirstDiff = std::mismatch( 9407 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9408 Cand2CPUSpec->cpus_begin(), 9409 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9410 return LHS->getName() == RHS->getName(); 9411 }); 9412 9413 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9414 "Two different cpu-specific versions should not have the same " 9415 "identifier list, otherwise they'd be the same decl!"); 9416 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9417 } 9418 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9419 } 9420 9421 /// isBetterOverloadCandidate - Determines whether the first overload 9422 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9423 bool clang::isBetterOverloadCandidate( 9424 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9425 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9426 // Define viable functions to be better candidates than non-viable 9427 // functions. 9428 if (!Cand2.Viable) 9429 return Cand1.Viable; 9430 else if (!Cand1.Viable) 9431 return false; 9432 9433 // C++ [over.match.best]p1: 9434 // 9435 // -- if F is a static member function, ICS1(F) is defined such 9436 // that ICS1(F) is neither better nor worse than ICS1(G) for 9437 // any function G, and, symmetrically, ICS1(G) is neither 9438 // better nor worse than ICS1(F). 9439 unsigned StartArg = 0; 9440 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9441 StartArg = 1; 9442 9443 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9444 // We don't allow incompatible pointer conversions in C++. 9445 if (!S.getLangOpts().CPlusPlus) 9446 return ICS.isStandard() && 9447 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9448 9449 // The only ill-formed conversion we allow in C++ is the string literal to 9450 // char* conversion, which is only considered ill-formed after C++11. 9451 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9452 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9453 }; 9454 9455 // Define functions that don't require ill-formed conversions for a given 9456 // argument to be better candidates than functions that do. 9457 unsigned NumArgs = Cand1.Conversions.size(); 9458 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9459 bool HasBetterConversion = false; 9460 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9461 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9462 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9463 if (Cand1Bad != Cand2Bad) { 9464 if (Cand1Bad) 9465 return false; 9466 HasBetterConversion = true; 9467 } 9468 } 9469 9470 if (HasBetterConversion) 9471 return true; 9472 9473 // C++ [over.match.best]p1: 9474 // A viable function F1 is defined to be a better function than another 9475 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9476 // conversion sequence than ICSi(F2), and then... 9477 bool HasWorseConversion = false; 9478 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9479 switch (CompareImplicitConversionSequences(S, Loc, 9480 Cand1.Conversions[ArgIdx], 9481 Cand2.Conversions[ArgIdx])) { 9482 case ImplicitConversionSequence::Better: 9483 // Cand1 has a better conversion sequence. 9484 HasBetterConversion = true; 9485 break; 9486 9487 case ImplicitConversionSequence::Worse: 9488 if (Cand1.Function && Cand1.Function == Cand2.Function && 9489 Cand2.isReversed()) { 9490 // Work around large-scale breakage caused by considering reversed 9491 // forms of operator== in C++20: 9492 // 9493 // When comparing a function against its reversed form, if we have a 9494 // better conversion for one argument and a worse conversion for the 9495 // other, we prefer the non-reversed form. 9496 // 9497 // This prevents a conversion function from being considered ambiguous 9498 // with its own reversed form in various where it's only incidentally 9499 // heterogeneous. 9500 // 9501 // We diagnose this as an extension from CreateOverloadedBinOp. 9502 HasWorseConversion = true; 9503 break; 9504 } 9505 9506 // Cand1 can't be better than Cand2. 9507 return false; 9508 9509 case ImplicitConversionSequence::Indistinguishable: 9510 // Do nothing. 9511 break; 9512 } 9513 } 9514 9515 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9516 // ICSj(F2), or, if not that, 9517 if (HasBetterConversion) 9518 return true; 9519 if (HasWorseConversion) 9520 return false; 9521 9522 // -- the context is an initialization by user-defined conversion 9523 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9524 // from the return type of F1 to the destination type (i.e., 9525 // the type of the entity being initialized) is a better 9526 // conversion sequence than the standard conversion sequence 9527 // from the return type of F2 to the destination type. 9528 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9529 Cand1.Function && Cand2.Function && 9530 isa<CXXConversionDecl>(Cand1.Function) && 9531 isa<CXXConversionDecl>(Cand2.Function)) { 9532 // First check whether we prefer one of the conversion functions over the 9533 // other. This only distinguishes the results in non-standard, extension 9534 // cases such as the conversion from a lambda closure type to a function 9535 // pointer or block. 9536 ImplicitConversionSequence::CompareKind Result = 9537 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9538 if (Result == ImplicitConversionSequence::Indistinguishable) 9539 Result = CompareStandardConversionSequences(S, Loc, 9540 Cand1.FinalConversion, 9541 Cand2.FinalConversion); 9542 9543 if (Result != ImplicitConversionSequence::Indistinguishable) 9544 return Result == ImplicitConversionSequence::Better; 9545 9546 // FIXME: Compare kind of reference binding if conversion functions 9547 // convert to a reference type used in direct reference binding, per 9548 // C++14 [over.match.best]p1 section 2 bullet 3. 9549 } 9550 9551 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9552 // as combined with the resolution to CWG issue 243. 9553 // 9554 // When the context is initialization by constructor ([over.match.ctor] or 9555 // either phase of [over.match.list]), a constructor is preferred over 9556 // a conversion function. 9557 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9558 Cand1.Function && Cand2.Function && 9559 isa<CXXConstructorDecl>(Cand1.Function) != 9560 isa<CXXConstructorDecl>(Cand2.Function)) 9561 return isa<CXXConstructorDecl>(Cand1.Function); 9562 9563 // -- F1 is a non-template function and F2 is a function template 9564 // specialization, or, if not that, 9565 bool Cand1IsSpecialization = Cand1.Function && 9566 Cand1.Function->getPrimaryTemplate(); 9567 bool Cand2IsSpecialization = Cand2.Function && 9568 Cand2.Function->getPrimaryTemplate(); 9569 if (Cand1IsSpecialization != Cand2IsSpecialization) 9570 return Cand2IsSpecialization; 9571 9572 // -- F1 and F2 are function template specializations, and the function 9573 // template for F1 is more specialized than the template for F2 9574 // according to the partial ordering rules described in 14.5.5.2, or, 9575 // if not that, 9576 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9577 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9578 Cand1.Function->getPrimaryTemplate(), 9579 Cand2.Function->getPrimaryTemplate(), Loc, 9580 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9581 : TPOC_Call, 9582 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9583 Cand1.isReversed() ^ Cand2.isReversed())) 9584 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9585 } 9586 9587 // -— F1 and F2 are non-template functions with the same 9588 // parameter-type-lists, and F1 is more constrained than F2 [...], 9589 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9590 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9591 Cand2.Function->hasPrototype()) { 9592 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9593 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9594 if (PT1->getNumParams() == PT2->getNumParams() && 9595 PT1->isVariadic() == PT2->isVariadic() && 9596 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9597 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9598 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9599 if (RC1 && RC2) { 9600 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9601 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9602 {RC2}, AtLeastAsConstrained1) || 9603 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9604 {RC1}, AtLeastAsConstrained2)) 9605 return false; 9606 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9607 return AtLeastAsConstrained1; 9608 } else if (RC1 || RC2) { 9609 return RC1 != nullptr; 9610 } 9611 } 9612 } 9613 9614 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9615 // class B of D, and for all arguments the corresponding parameters of 9616 // F1 and F2 have the same type. 9617 // FIXME: Implement the "all parameters have the same type" check. 9618 bool Cand1IsInherited = 9619 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9620 bool Cand2IsInherited = 9621 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9622 if (Cand1IsInherited != Cand2IsInherited) 9623 return Cand2IsInherited; 9624 else if (Cand1IsInherited) { 9625 assert(Cand2IsInherited); 9626 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9627 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9628 if (Cand1Class->isDerivedFrom(Cand2Class)) 9629 return true; 9630 if (Cand2Class->isDerivedFrom(Cand1Class)) 9631 return false; 9632 // Inherited from sibling base classes: still ambiguous. 9633 } 9634 9635 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9636 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9637 // with reversed order of parameters and F1 is not 9638 // 9639 // We rank reversed + different operator as worse than just reversed, but 9640 // that comparison can never happen, because we only consider reversing for 9641 // the maximally-rewritten operator (== or <=>). 9642 if (Cand1.RewriteKind != Cand2.RewriteKind) 9643 return Cand1.RewriteKind < Cand2.RewriteKind; 9644 9645 // Check C++17 tie-breakers for deduction guides. 9646 { 9647 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9648 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9649 if (Guide1 && Guide2) { 9650 // -- F1 is generated from a deduction-guide and F2 is not 9651 if (Guide1->isImplicit() != Guide2->isImplicit()) 9652 return Guide2->isImplicit(); 9653 9654 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9655 if (Guide1->isCopyDeductionCandidate()) 9656 return true; 9657 } 9658 } 9659 9660 // Check for enable_if value-based overload resolution. 9661 if (Cand1.Function && Cand2.Function) { 9662 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9663 if (Cmp != Comparison::Equal) 9664 return Cmp == Comparison::Better; 9665 } 9666 9667 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9668 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9669 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9670 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9671 } 9672 9673 bool HasPS1 = Cand1.Function != nullptr && 9674 functionHasPassObjectSizeParams(Cand1.Function); 9675 bool HasPS2 = Cand2.Function != nullptr && 9676 functionHasPassObjectSizeParams(Cand2.Function); 9677 if (HasPS1 != HasPS2 && HasPS1) 9678 return true; 9679 9680 return isBetterMultiversionCandidate(Cand1, Cand2); 9681 } 9682 9683 /// Determine whether two declarations are "equivalent" for the purposes of 9684 /// name lookup and overload resolution. This applies when the same internal/no 9685 /// linkage entity is defined by two modules (probably by textually including 9686 /// the same header). In such a case, we don't consider the declarations to 9687 /// declare the same entity, but we also don't want lookups with both 9688 /// declarations visible to be ambiguous in some cases (this happens when using 9689 /// a modularized libstdc++). 9690 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9691 const NamedDecl *B) { 9692 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9693 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9694 if (!VA || !VB) 9695 return false; 9696 9697 // The declarations must be declaring the same name as an internal linkage 9698 // entity in different modules. 9699 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9700 VB->getDeclContext()->getRedeclContext()) || 9701 getOwningModule(VA) == getOwningModule(VB) || 9702 VA->isExternallyVisible() || VB->isExternallyVisible()) 9703 return false; 9704 9705 // Check that the declarations appear to be equivalent. 9706 // 9707 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9708 // For constants and functions, we should check the initializer or body is 9709 // the same. For non-constant variables, we shouldn't allow it at all. 9710 if (Context.hasSameType(VA->getType(), VB->getType())) 9711 return true; 9712 9713 // Enum constants within unnamed enumerations will have different types, but 9714 // may still be similar enough to be interchangeable for our purposes. 9715 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9716 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9717 // Only handle anonymous enums. If the enumerations were named and 9718 // equivalent, they would have been merged to the same type. 9719 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9720 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9721 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9722 !Context.hasSameType(EnumA->getIntegerType(), 9723 EnumB->getIntegerType())) 9724 return false; 9725 // Allow this only if the value is the same for both enumerators. 9726 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9727 } 9728 } 9729 9730 // Nothing else is sufficiently similar. 9731 return false; 9732 } 9733 9734 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9735 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9736 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9737 9738 Module *M = getOwningModule(D); 9739 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9740 << !M << (M ? M->getFullModuleName() : ""); 9741 9742 for (auto *E : Equiv) { 9743 Module *M = getOwningModule(E); 9744 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9745 << !M << (M ? M->getFullModuleName() : ""); 9746 } 9747 } 9748 9749 /// Computes the best viable function (C++ 13.3.3) 9750 /// within an overload candidate set. 9751 /// 9752 /// \param Loc The location of the function name (or operator symbol) for 9753 /// which overload resolution occurs. 9754 /// 9755 /// \param Best If overload resolution was successful or found a deleted 9756 /// function, \p Best points to the candidate function found. 9757 /// 9758 /// \returns The result of overload resolution. 9759 OverloadingResult 9760 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9761 iterator &Best) { 9762 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9763 std::transform(begin(), end(), std::back_inserter(Candidates), 9764 [](OverloadCandidate &Cand) { return &Cand; }); 9765 9766 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9767 // are accepted by both clang and NVCC. However, during a particular 9768 // compilation mode only one call variant is viable. We need to 9769 // exclude non-viable overload candidates from consideration based 9770 // only on their host/device attributes. Specifically, if one 9771 // candidate call is WrongSide and the other is SameSide, we ignore 9772 // the WrongSide candidate. 9773 if (S.getLangOpts().CUDA) { 9774 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9775 bool ContainsSameSideCandidate = 9776 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9777 // Check viable function only. 9778 return Cand->Viable && Cand->Function && 9779 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9780 Sema::CFP_SameSide; 9781 }); 9782 if (ContainsSameSideCandidate) { 9783 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9784 // Check viable function only to avoid unnecessary data copying/moving. 9785 return Cand->Viable && Cand->Function && 9786 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9787 Sema::CFP_WrongSide; 9788 }; 9789 llvm::erase_if(Candidates, IsWrongSideCandidate); 9790 } 9791 } 9792 9793 // Find the best viable function. 9794 Best = end(); 9795 for (auto *Cand : Candidates) { 9796 Cand->Best = false; 9797 if (Cand->Viable) 9798 if (Best == end() || 9799 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9800 Best = Cand; 9801 } 9802 9803 // If we didn't find any viable functions, abort. 9804 if (Best == end()) 9805 return OR_No_Viable_Function; 9806 9807 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9808 9809 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 9810 PendingBest.push_back(&*Best); 9811 Best->Best = true; 9812 9813 // Make sure that this function is better than every other viable 9814 // function. If not, we have an ambiguity. 9815 while (!PendingBest.empty()) { 9816 auto *Curr = PendingBest.pop_back_val(); 9817 for (auto *Cand : Candidates) { 9818 if (Cand->Viable && !Cand->Best && 9819 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 9820 PendingBest.push_back(Cand); 9821 Cand->Best = true; 9822 9823 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 9824 Curr->Function)) 9825 EquivalentCands.push_back(Cand->Function); 9826 else 9827 Best = end(); 9828 } 9829 } 9830 } 9831 9832 // If we found more than one best candidate, this is ambiguous. 9833 if (Best == end()) 9834 return OR_Ambiguous; 9835 9836 // Best is the best viable function. 9837 if (Best->Function && Best->Function->isDeleted()) 9838 return OR_Deleted; 9839 9840 if (!EquivalentCands.empty()) 9841 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9842 EquivalentCands); 9843 9844 return OR_Success; 9845 } 9846 9847 namespace { 9848 9849 enum OverloadCandidateKind { 9850 oc_function, 9851 oc_method, 9852 oc_reversed_binary_operator, 9853 oc_constructor, 9854 oc_implicit_default_constructor, 9855 oc_implicit_copy_constructor, 9856 oc_implicit_move_constructor, 9857 oc_implicit_copy_assignment, 9858 oc_implicit_move_assignment, 9859 oc_implicit_equality_comparison, 9860 oc_inherited_constructor 9861 }; 9862 9863 enum OverloadCandidateSelect { 9864 ocs_non_template, 9865 ocs_template, 9866 ocs_described_template, 9867 }; 9868 9869 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9870 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9871 OverloadCandidateRewriteKind CRK, 9872 std::string &Description) { 9873 9874 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9875 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9876 isTemplate = true; 9877 Description = S.getTemplateArgumentBindingsText( 9878 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9879 } 9880 9881 OverloadCandidateSelect Select = [&]() { 9882 if (!Description.empty()) 9883 return ocs_described_template; 9884 return isTemplate ? ocs_template : ocs_non_template; 9885 }(); 9886 9887 OverloadCandidateKind Kind = [&]() { 9888 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 9889 return oc_implicit_equality_comparison; 9890 9891 if (CRK & CRK_Reversed) 9892 return oc_reversed_binary_operator; 9893 9894 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9895 if (!Ctor->isImplicit()) { 9896 if (isa<ConstructorUsingShadowDecl>(Found)) 9897 return oc_inherited_constructor; 9898 else 9899 return oc_constructor; 9900 } 9901 9902 if (Ctor->isDefaultConstructor()) 9903 return oc_implicit_default_constructor; 9904 9905 if (Ctor->isMoveConstructor()) 9906 return oc_implicit_move_constructor; 9907 9908 assert(Ctor->isCopyConstructor() && 9909 "unexpected sort of implicit constructor"); 9910 return oc_implicit_copy_constructor; 9911 } 9912 9913 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9914 // This actually gets spelled 'candidate function' for now, but 9915 // it doesn't hurt to split it out. 9916 if (!Meth->isImplicit()) 9917 return oc_method; 9918 9919 if (Meth->isMoveAssignmentOperator()) 9920 return oc_implicit_move_assignment; 9921 9922 if (Meth->isCopyAssignmentOperator()) 9923 return oc_implicit_copy_assignment; 9924 9925 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9926 return oc_method; 9927 } 9928 9929 return oc_function; 9930 }(); 9931 9932 return std::make_pair(Kind, Select); 9933 } 9934 9935 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9936 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9937 // set. 9938 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9939 S.Diag(FoundDecl->getLocation(), 9940 diag::note_ovl_candidate_inherited_constructor) 9941 << Shadow->getNominatedBaseClass(); 9942 } 9943 9944 } // end anonymous namespace 9945 9946 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9947 const FunctionDecl *FD) { 9948 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9949 bool AlwaysTrue; 9950 if (EnableIf->getCond()->isValueDependent() || 9951 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9952 return false; 9953 if (!AlwaysTrue) 9954 return false; 9955 } 9956 return true; 9957 } 9958 9959 /// Returns true if we can take the address of the function. 9960 /// 9961 /// \param Complain - If true, we'll emit a diagnostic 9962 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9963 /// we in overload resolution? 9964 /// \param Loc - The location of the statement we're complaining about. Ignored 9965 /// if we're not complaining, or if we're in overload resolution. 9966 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9967 bool Complain, 9968 bool InOverloadResolution, 9969 SourceLocation Loc) { 9970 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9971 if (Complain) { 9972 if (InOverloadResolution) 9973 S.Diag(FD->getBeginLoc(), 9974 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9975 else 9976 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9977 } 9978 return false; 9979 } 9980 9981 if (FD->getTrailingRequiresClause()) { 9982 ConstraintSatisfaction Satisfaction; 9983 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 9984 return false; 9985 if (!Satisfaction.IsSatisfied) { 9986 if (Complain) { 9987 if (InOverloadResolution) 9988 S.Diag(FD->getBeginLoc(), 9989 diag::note_ovl_candidate_unsatisfied_constraints); 9990 else 9991 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 9992 << FD; 9993 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 9994 } 9995 return false; 9996 } 9997 } 9998 9999 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10000 return P->hasAttr<PassObjectSizeAttr>(); 10001 }); 10002 if (I == FD->param_end()) 10003 return true; 10004 10005 if (Complain) { 10006 // Add one to ParamNo because it's user-facing 10007 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10008 if (InOverloadResolution) 10009 S.Diag(FD->getLocation(), 10010 diag::note_ovl_candidate_has_pass_object_size_params) 10011 << ParamNo; 10012 else 10013 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10014 << FD << ParamNo; 10015 } 10016 return false; 10017 } 10018 10019 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10020 const FunctionDecl *FD) { 10021 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10022 /*InOverloadResolution=*/true, 10023 /*Loc=*/SourceLocation()); 10024 } 10025 10026 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10027 bool Complain, 10028 SourceLocation Loc) { 10029 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10030 /*InOverloadResolution=*/false, 10031 Loc); 10032 } 10033 10034 // Notes the location of an overload candidate. 10035 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10036 OverloadCandidateRewriteKind RewriteKind, 10037 QualType DestType, bool TakingAddress) { 10038 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10039 return; 10040 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10041 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10042 return; 10043 10044 std::string FnDesc; 10045 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10046 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10047 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10048 << (unsigned)KSPair.first << (unsigned)KSPair.second 10049 << Fn << FnDesc; 10050 10051 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10052 Diag(Fn->getLocation(), PD); 10053 MaybeEmitInheritedConstructorNote(*this, Found); 10054 } 10055 10056 static void 10057 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10058 // Perhaps the ambiguity was caused by two atomic constraints that are 10059 // 'identical' but not equivalent: 10060 // 10061 // void foo() requires (sizeof(T) > 4) { } // #1 10062 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10063 // 10064 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10065 // #2 to subsume #1, but these constraint are not considered equivalent 10066 // according to the subsumption rules because they are not the same 10067 // source-level construct. This behavior is quite confusing and we should try 10068 // to help the user figure out what happened. 10069 10070 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10071 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10072 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10073 if (!I->Function) 10074 continue; 10075 SmallVector<const Expr *, 3> AC; 10076 if (auto *Template = I->Function->getPrimaryTemplate()) 10077 Template->getAssociatedConstraints(AC); 10078 else 10079 I->Function->getAssociatedConstraints(AC); 10080 if (AC.empty()) 10081 continue; 10082 if (FirstCand == nullptr) { 10083 FirstCand = I->Function; 10084 FirstAC = AC; 10085 } else if (SecondCand == nullptr) { 10086 SecondCand = I->Function; 10087 SecondAC = AC; 10088 } else { 10089 // We have more than one pair of constrained functions - this check is 10090 // expensive and we'd rather not try to diagnose it. 10091 return; 10092 } 10093 } 10094 if (!SecondCand) 10095 return; 10096 // The diagnostic can only happen if there are associated constraints on 10097 // both sides (there needs to be some identical atomic constraint). 10098 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10099 SecondCand, SecondAC)) 10100 // Just show the user one diagnostic, they'll probably figure it out 10101 // from here. 10102 return; 10103 } 10104 10105 // Notes the location of all overload candidates designated through 10106 // OverloadedExpr 10107 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10108 bool TakingAddress) { 10109 assert(OverloadedExpr->getType() == Context.OverloadTy); 10110 10111 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10112 OverloadExpr *OvlExpr = Ovl.Expression; 10113 10114 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10115 IEnd = OvlExpr->decls_end(); 10116 I != IEnd; ++I) { 10117 if (FunctionTemplateDecl *FunTmpl = 10118 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10119 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10120 TakingAddress); 10121 } else if (FunctionDecl *Fun 10122 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10123 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10124 } 10125 } 10126 } 10127 10128 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10129 /// "lead" diagnostic; it will be given two arguments, the source and 10130 /// target types of the conversion. 10131 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10132 Sema &S, 10133 SourceLocation CaretLoc, 10134 const PartialDiagnostic &PDiag) const { 10135 S.Diag(CaretLoc, PDiag) 10136 << Ambiguous.getFromType() << Ambiguous.getToType(); 10137 // FIXME: The note limiting machinery is borrowed from 10138 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 10139 // refactoring here. 10140 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10141 unsigned CandsShown = 0; 10142 AmbiguousConversionSequence::const_iterator I, E; 10143 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10144 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10145 break; 10146 ++CandsShown; 10147 S.NoteOverloadCandidate(I->first, I->second); 10148 } 10149 if (I != E) 10150 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10151 } 10152 10153 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10154 unsigned I, bool TakingCandidateAddress) { 10155 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10156 assert(Conv.isBad()); 10157 assert(Cand->Function && "for now, candidate must be a function"); 10158 FunctionDecl *Fn = Cand->Function; 10159 10160 // There's a conversion slot for the object argument if this is a 10161 // non-constructor method. Note that 'I' corresponds the 10162 // conversion-slot index. 10163 bool isObjectArgument = false; 10164 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10165 if (I == 0) 10166 isObjectArgument = true; 10167 else 10168 I--; 10169 } 10170 10171 std::string FnDesc; 10172 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10173 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10174 FnDesc); 10175 10176 Expr *FromExpr = Conv.Bad.FromExpr; 10177 QualType FromTy = Conv.Bad.getFromType(); 10178 QualType ToTy = Conv.Bad.getToType(); 10179 10180 if (FromTy == S.Context.OverloadTy) { 10181 assert(FromExpr && "overload set argument came from implicit argument?"); 10182 Expr *E = FromExpr->IgnoreParens(); 10183 if (isa<UnaryOperator>(E)) 10184 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10185 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10186 10187 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10188 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10189 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10190 << Name << I + 1; 10191 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10192 return; 10193 } 10194 10195 // Do some hand-waving analysis to see if the non-viability is due 10196 // to a qualifier mismatch. 10197 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10198 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10199 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10200 CToTy = RT->getPointeeType(); 10201 else { 10202 // TODO: detect and diagnose the full richness of const mismatches. 10203 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10204 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10205 CFromTy = FromPT->getPointeeType(); 10206 CToTy = ToPT->getPointeeType(); 10207 } 10208 } 10209 10210 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10211 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10212 Qualifiers FromQs = CFromTy.getQualifiers(); 10213 Qualifiers ToQs = CToTy.getQualifiers(); 10214 10215 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10216 if (isObjectArgument) 10217 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10218 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10219 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10220 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10221 else 10222 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10223 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10224 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10225 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10226 << ToTy->isReferenceType() << I + 1; 10227 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10228 return; 10229 } 10230 10231 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10232 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10233 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10234 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10235 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10236 << (unsigned)isObjectArgument << I + 1; 10237 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10238 return; 10239 } 10240 10241 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10242 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10243 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10244 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10245 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10246 << (unsigned)isObjectArgument << I + 1; 10247 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10248 return; 10249 } 10250 10251 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10252 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10253 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10254 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10255 << FromQs.hasUnaligned() << I + 1; 10256 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10257 return; 10258 } 10259 10260 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10261 assert(CVR && "unexpected qualifiers mismatch"); 10262 10263 if (isObjectArgument) { 10264 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10265 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10266 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10267 << (CVR - 1); 10268 } else { 10269 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10270 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10271 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10272 << (CVR - 1) << I + 1; 10273 } 10274 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10275 return; 10276 } 10277 10278 // Special diagnostic for failure to convert an initializer list, since 10279 // telling the user that it has type void is not useful. 10280 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10281 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10282 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10283 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10284 << ToTy << (unsigned)isObjectArgument << I + 1; 10285 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10286 return; 10287 } 10288 10289 // Diagnose references or pointers to incomplete types differently, 10290 // since it's far from impossible that the incompleteness triggered 10291 // the failure. 10292 QualType TempFromTy = FromTy.getNonReferenceType(); 10293 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10294 TempFromTy = PTy->getPointeeType(); 10295 if (TempFromTy->isIncompleteType()) { 10296 // Emit the generic diagnostic and, optionally, add the hints to it. 10297 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10298 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10299 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10300 << ToTy << (unsigned)isObjectArgument << I + 1 10301 << (unsigned)(Cand->Fix.Kind); 10302 10303 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10304 return; 10305 } 10306 10307 // Diagnose base -> derived pointer conversions. 10308 unsigned BaseToDerivedConversion = 0; 10309 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10310 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10311 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10312 FromPtrTy->getPointeeType()) && 10313 !FromPtrTy->getPointeeType()->isIncompleteType() && 10314 !ToPtrTy->getPointeeType()->isIncompleteType() && 10315 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10316 FromPtrTy->getPointeeType())) 10317 BaseToDerivedConversion = 1; 10318 } 10319 } else if (const ObjCObjectPointerType *FromPtrTy 10320 = FromTy->getAs<ObjCObjectPointerType>()) { 10321 if (const ObjCObjectPointerType *ToPtrTy 10322 = ToTy->getAs<ObjCObjectPointerType>()) 10323 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10324 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10325 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10326 FromPtrTy->getPointeeType()) && 10327 FromIface->isSuperClassOf(ToIface)) 10328 BaseToDerivedConversion = 2; 10329 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10330 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10331 !FromTy->isIncompleteType() && 10332 !ToRefTy->getPointeeType()->isIncompleteType() && 10333 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10334 BaseToDerivedConversion = 3; 10335 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 10336 ToTy.getNonReferenceType().getCanonicalType() == 10337 FromTy.getNonReferenceType().getCanonicalType()) { 10338 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10339 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10340 << (unsigned)isObjectArgument << I + 1 10341 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10342 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10343 return; 10344 } 10345 } 10346 10347 if (BaseToDerivedConversion) { 10348 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10349 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10350 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10351 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10352 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10353 return; 10354 } 10355 10356 if (isa<ObjCObjectPointerType>(CFromTy) && 10357 isa<PointerType>(CToTy)) { 10358 Qualifiers FromQs = CFromTy.getQualifiers(); 10359 Qualifiers ToQs = CToTy.getQualifiers(); 10360 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10361 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10362 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10363 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10364 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10365 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10366 return; 10367 } 10368 } 10369 10370 if (TakingCandidateAddress && 10371 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10372 return; 10373 10374 // Emit the generic diagnostic and, optionally, add the hints to it. 10375 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10376 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10377 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10378 << ToTy << (unsigned)isObjectArgument << I + 1 10379 << (unsigned)(Cand->Fix.Kind); 10380 10381 // If we can fix the conversion, suggest the FixIts. 10382 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10383 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10384 FDiag << *HI; 10385 S.Diag(Fn->getLocation(), FDiag); 10386 10387 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10388 } 10389 10390 /// Additional arity mismatch diagnosis specific to a function overload 10391 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10392 /// over a candidate in any candidate set. 10393 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10394 unsigned NumArgs) { 10395 FunctionDecl *Fn = Cand->Function; 10396 unsigned MinParams = Fn->getMinRequiredArguments(); 10397 10398 // With invalid overloaded operators, it's possible that we think we 10399 // have an arity mismatch when in fact it looks like we have the 10400 // right number of arguments, because only overloaded operators have 10401 // the weird behavior of overloading member and non-member functions. 10402 // Just don't report anything. 10403 if (Fn->isInvalidDecl() && 10404 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10405 return true; 10406 10407 if (NumArgs < MinParams) { 10408 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10409 (Cand->FailureKind == ovl_fail_bad_deduction && 10410 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10411 } else { 10412 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10413 (Cand->FailureKind == ovl_fail_bad_deduction && 10414 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10415 } 10416 10417 return false; 10418 } 10419 10420 /// General arity mismatch diagnosis over a candidate in a candidate set. 10421 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10422 unsigned NumFormalArgs) { 10423 assert(isa<FunctionDecl>(D) && 10424 "The templated declaration should at least be a function" 10425 " when diagnosing bad template argument deduction due to too many" 10426 " or too few arguments"); 10427 10428 FunctionDecl *Fn = cast<FunctionDecl>(D); 10429 10430 // TODO: treat calls to a missing default constructor as a special case 10431 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10432 unsigned MinParams = Fn->getMinRequiredArguments(); 10433 10434 // at least / at most / exactly 10435 unsigned mode, modeCount; 10436 if (NumFormalArgs < MinParams) { 10437 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10438 FnTy->isTemplateVariadic()) 10439 mode = 0; // "at least" 10440 else 10441 mode = 2; // "exactly" 10442 modeCount = MinParams; 10443 } else { 10444 if (MinParams != FnTy->getNumParams()) 10445 mode = 1; // "at most" 10446 else 10447 mode = 2; // "exactly" 10448 modeCount = FnTy->getNumParams(); 10449 } 10450 10451 std::string Description; 10452 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10453 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10454 10455 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10456 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10457 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10458 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10459 else 10460 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10461 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10462 << Description << mode << modeCount << NumFormalArgs; 10463 10464 MaybeEmitInheritedConstructorNote(S, Found); 10465 } 10466 10467 /// Arity mismatch diagnosis specific to a function overload candidate. 10468 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10469 unsigned NumFormalArgs) { 10470 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10471 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10472 } 10473 10474 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10475 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10476 return TD; 10477 llvm_unreachable("Unsupported: Getting the described template declaration" 10478 " for bad deduction diagnosis"); 10479 } 10480 10481 /// Diagnose a failed template-argument deduction. 10482 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10483 DeductionFailureInfo &DeductionFailure, 10484 unsigned NumArgs, 10485 bool TakingCandidateAddress) { 10486 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10487 NamedDecl *ParamD; 10488 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10489 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10490 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10491 switch (DeductionFailure.Result) { 10492 case Sema::TDK_Success: 10493 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10494 10495 case Sema::TDK_Incomplete: { 10496 assert(ParamD && "no parameter found for incomplete deduction result"); 10497 S.Diag(Templated->getLocation(), 10498 diag::note_ovl_candidate_incomplete_deduction) 10499 << ParamD->getDeclName(); 10500 MaybeEmitInheritedConstructorNote(S, Found); 10501 return; 10502 } 10503 10504 case Sema::TDK_IncompletePack: { 10505 assert(ParamD && "no parameter found for incomplete deduction result"); 10506 S.Diag(Templated->getLocation(), 10507 diag::note_ovl_candidate_incomplete_deduction_pack) 10508 << ParamD->getDeclName() 10509 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10510 << *DeductionFailure.getFirstArg(); 10511 MaybeEmitInheritedConstructorNote(S, Found); 10512 return; 10513 } 10514 10515 case Sema::TDK_Underqualified: { 10516 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10517 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10518 10519 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10520 10521 // Param will have been canonicalized, but it should just be a 10522 // qualified version of ParamD, so move the qualifiers to that. 10523 QualifierCollector Qs; 10524 Qs.strip(Param); 10525 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10526 assert(S.Context.hasSameType(Param, NonCanonParam)); 10527 10528 // Arg has also been canonicalized, but there's nothing we can do 10529 // about that. It also doesn't matter as much, because it won't 10530 // have any template parameters in it (because deduction isn't 10531 // done on dependent types). 10532 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10533 10534 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10535 << ParamD->getDeclName() << Arg << NonCanonParam; 10536 MaybeEmitInheritedConstructorNote(S, Found); 10537 return; 10538 } 10539 10540 case Sema::TDK_Inconsistent: { 10541 assert(ParamD && "no parameter found for inconsistent deduction result"); 10542 int which = 0; 10543 if (isa<TemplateTypeParmDecl>(ParamD)) 10544 which = 0; 10545 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10546 // Deduction might have failed because we deduced arguments of two 10547 // different types for a non-type template parameter. 10548 // FIXME: Use a different TDK value for this. 10549 QualType T1 = 10550 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10551 QualType T2 = 10552 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10553 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10554 S.Diag(Templated->getLocation(), 10555 diag::note_ovl_candidate_inconsistent_deduction_types) 10556 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10557 << *DeductionFailure.getSecondArg() << T2; 10558 MaybeEmitInheritedConstructorNote(S, Found); 10559 return; 10560 } 10561 10562 which = 1; 10563 } else { 10564 which = 2; 10565 } 10566 10567 // Tweak the diagnostic if the problem is that we deduced packs of 10568 // different arities. We'll print the actual packs anyway in case that 10569 // includes additional useful information. 10570 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10571 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10572 DeductionFailure.getFirstArg()->pack_size() != 10573 DeductionFailure.getSecondArg()->pack_size()) { 10574 which = 3; 10575 } 10576 10577 S.Diag(Templated->getLocation(), 10578 diag::note_ovl_candidate_inconsistent_deduction) 10579 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10580 << *DeductionFailure.getSecondArg(); 10581 MaybeEmitInheritedConstructorNote(S, Found); 10582 return; 10583 } 10584 10585 case Sema::TDK_InvalidExplicitArguments: 10586 assert(ParamD && "no parameter found for invalid explicit arguments"); 10587 if (ParamD->getDeclName()) 10588 S.Diag(Templated->getLocation(), 10589 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10590 << ParamD->getDeclName(); 10591 else { 10592 int index = 0; 10593 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10594 index = TTP->getIndex(); 10595 else if (NonTypeTemplateParmDecl *NTTP 10596 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10597 index = NTTP->getIndex(); 10598 else 10599 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10600 S.Diag(Templated->getLocation(), 10601 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10602 << (index + 1); 10603 } 10604 MaybeEmitInheritedConstructorNote(S, Found); 10605 return; 10606 10607 case Sema::TDK_ConstraintsNotSatisfied: { 10608 // Format the template argument list into the argument string. 10609 SmallString<128> TemplateArgString; 10610 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10611 TemplateArgString = " "; 10612 TemplateArgString += S.getTemplateArgumentBindingsText( 10613 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10614 if (TemplateArgString.size() == 1) 10615 TemplateArgString.clear(); 10616 S.Diag(Templated->getLocation(), 10617 diag::note_ovl_candidate_unsatisfied_constraints) 10618 << TemplateArgString; 10619 10620 S.DiagnoseUnsatisfiedConstraint( 10621 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10622 return; 10623 } 10624 case Sema::TDK_TooManyArguments: 10625 case Sema::TDK_TooFewArguments: 10626 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10627 return; 10628 10629 case Sema::TDK_InstantiationDepth: 10630 S.Diag(Templated->getLocation(), 10631 diag::note_ovl_candidate_instantiation_depth); 10632 MaybeEmitInheritedConstructorNote(S, Found); 10633 return; 10634 10635 case Sema::TDK_SubstitutionFailure: { 10636 // Format the template argument list into the argument string. 10637 SmallString<128> TemplateArgString; 10638 if (TemplateArgumentList *Args = 10639 DeductionFailure.getTemplateArgumentList()) { 10640 TemplateArgString = " "; 10641 TemplateArgString += S.getTemplateArgumentBindingsText( 10642 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10643 if (TemplateArgString.size() == 1) 10644 TemplateArgString.clear(); 10645 } 10646 10647 // If this candidate was disabled by enable_if, say so. 10648 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10649 if (PDiag && PDiag->second.getDiagID() == 10650 diag::err_typename_nested_not_found_enable_if) { 10651 // FIXME: Use the source range of the condition, and the fully-qualified 10652 // name of the enable_if template. These are both present in PDiag. 10653 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10654 << "'enable_if'" << TemplateArgString; 10655 return; 10656 } 10657 10658 // We found a specific requirement that disabled the enable_if. 10659 if (PDiag && PDiag->second.getDiagID() == 10660 diag::err_typename_nested_not_found_requirement) { 10661 S.Diag(Templated->getLocation(), 10662 diag::note_ovl_candidate_disabled_by_requirement) 10663 << PDiag->second.getStringArg(0) << TemplateArgString; 10664 return; 10665 } 10666 10667 // Format the SFINAE diagnostic into the argument string. 10668 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10669 // formatted message in another diagnostic. 10670 SmallString<128> SFINAEArgString; 10671 SourceRange R; 10672 if (PDiag) { 10673 SFINAEArgString = ": "; 10674 R = SourceRange(PDiag->first, PDiag->first); 10675 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10676 } 10677 10678 S.Diag(Templated->getLocation(), 10679 diag::note_ovl_candidate_substitution_failure) 10680 << TemplateArgString << SFINAEArgString << R; 10681 MaybeEmitInheritedConstructorNote(S, Found); 10682 return; 10683 } 10684 10685 case Sema::TDK_DeducedMismatch: 10686 case Sema::TDK_DeducedMismatchNested: { 10687 // Format the template argument list into the argument string. 10688 SmallString<128> TemplateArgString; 10689 if (TemplateArgumentList *Args = 10690 DeductionFailure.getTemplateArgumentList()) { 10691 TemplateArgString = " "; 10692 TemplateArgString += S.getTemplateArgumentBindingsText( 10693 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10694 if (TemplateArgString.size() == 1) 10695 TemplateArgString.clear(); 10696 } 10697 10698 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10699 << (*DeductionFailure.getCallArgIndex() + 1) 10700 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10701 << TemplateArgString 10702 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10703 break; 10704 } 10705 10706 case Sema::TDK_NonDeducedMismatch: { 10707 // FIXME: Provide a source location to indicate what we couldn't match. 10708 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10709 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10710 if (FirstTA.getKind() == TemplateArgument::Template && 10711 SecondTA.getKind() == TemplateArgument::Template) { 10712 TemplateName FirstTN = FirstTA.getAsTemplate(); 10713 TemplateName SecondTN = SecondTA.getAsTemplate(); 10714 if (FirstTN.getKind() == TemplateName::Template && 10715 SecondTN.getKind() == TemplateName::Template) { 10716 if (FirstTN.getAsTemplateDecl()->getName() == 10717 SecondTN.getAsTemplateDecl()->getName()) { 10718 // FIXME: This fixes a bad diagnostic where both templates are named 10719 // the same. This particular case is a bit difficult since: 10720 // 1) It is passed as a string to the diagnostic printer. 10721 // 2) The diagnostic printer only attempts to find a better 10722 // name for types, not decls. 10723 // Ideally, this should folded into the diagnostic printer. 10724 S.Diag(Templated->getLocation(), 10725 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10726 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10727 return; 10728 } 10729 } 10730 } 10731 10732 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10733 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10734 return; 10735 10736 // FIXME: For generic lambda parameters, check if the function is a lambda 10737 // call operator, and if so, emit a prettier and more informative 10738 // diagnostic that mentions 'auto' and lambda in addition to 10739 // (or instead of?) the canonical template type parameters. 10740 S.Diag(Templated->getLocation(), 10741 diag::note_ovl_candidate_non_deduced_mismatch) 10742 << FirstTA << SecondTA; 10743 return; 10744 } 10745 // TODO: diagnose these individually, then kill off 10746 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10747 case Sema::TDK_MiscellaneousDeductionFailure: 10748 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10749 MaybeEmitInheritedConstructorNote(S, Found); 10750 return; 10751 case Sema::TDK_CUDATargetMismatch: 10752 S.Diag(Templated->getLocation(), 10753 diag::note_cuda_ovl_candidate_target_mismatch); 10754 return; 10755 } 10756 } 10757 10758 /// Diagnose a failed template-argument deduction, for function calls. 10759 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10760 unsigned NumArgs, 10761 bool TakingCandidateAddress) { 10762 unsigned TDK = Cand->DeductionFailure.Result; 10763 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10764 if (CheckArityMismatch(S, Cand, NumArgs)) 10765 return; 10766 } 10767 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10768 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10769 } 10770 10771 /// CUDA: diagnose an invalid call across targets. 10772 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10773 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10774 FunctionDecl *Callee = Cand->Function; 10775 10776 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10777 CalleeTarget = S.IdentifyCUDATarget(Callee); 10778 10779 std::string FnDesc; 10780 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10781 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 10782 Cand->getRewriteKind(), FnDesc); 10783 10784 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10785 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10786 << FnDesc /* Ignored */ 10787 << CalleeTarget << CallerTarget; 10788 10789 // This could be an implicit constructor for which we could not infer the 10790 // target due to a collsion. Diagnose that case. 10791 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10792 if (Meth != nullptr && Meth->isImplicit()) { 10793 CXXRecordDecl *ParentClass = Meth->getParent(); 10794 Sema::CXXSpecialMember CSM; 10795 10796 switch (FnKindPair.first) { 10797 default: 10798 return; 10799 case oc_implicit_default_constructor: 10800 CSM = Sema::CXXDefaultConstructor; 10801 break; 10802 case oc_implicit_copy_constructor: 10803 CSM = Sema::CXXCopyConstructor; 10804 break; 10805 case oc_implicit_move_constructor: 10806 CSM = Sema::CXXMoveConstructor; 10807 break; 10808 case oc_implicit_copy_assignment: 10809 CSM = Sema::CXXCopyAssignment; 10810 break; 10811 case oc_implicit_move_assignment: 10812 CSM = Sema::CXXMoveAssignment; 10813 break; 10814 }; 10815 10816 bool ConstRHS = false; 10817 if (Meth->getNumParams()) { 10818 if (const ReferenceType *RT = 10819 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10820 ConstRHS = RT->getPointeeType().isConstQualified(); 10821 } 10822 } 10823 10824 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10825 /* ConstRHS */ ConstRHS, 10826 /* Diagnose */ true); 10827 } 10828 } 10829 10830 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10831 FunctionDecl *Callee = Cand->Function; 10832 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10833 10834 S.Diag(Callee->getLocation(), 10835 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10836 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10837 } 10838 10839 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10840 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 10841 assert(ES.isExplicit() && "not an explicit candidate"); 10842 10843 unsigned Kind; 10844 switch (Cand->Function->getDeclKind()) { 10845 case Decl::Kind::CXXConstructor: 10846 Kind = 0; 10847 break; 10848 case Decl::Kind::CXXConversion: 10849 Kind = 1; 10850 break; 10851 case Decl::Kind::CXXDeductionGuide: 10852 Kind = Cand->Function->isImplicit() ? 0 : 2; 10853 break; 10854 default: 10855 llvm_unreachable("invalid Decl"); 10856 } 10857 10858 // Note the location of the first (in-class) declaration; a redeclaration 10859 // (particularly an out-of-class definition) will typically lack the 10860 // 'explicit' specifier. 10861 // FIXME: This is probably a good thing to do for all 'candidate' notes. 10862 FunctionDecl *First = Cand->Function->getFirstDecl(); 10863 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 10864 First = Pattern->getFirstDecl(); 10865 10866 S.Diag(First->getLocation(), 10867 diag::note_ovl_candidate_explicit) 10868 << Kind << (ES.getExpr() ? 1 : 0) 10869 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 10870 } 10871 10872 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10873 FunctionDecl *Callee = Cand->Function; 10874 10875 S.Diag(Callee->getLocation(), 10876 diag::note_ovl_candidate_disabled_by_extension) 10877 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10878 } 10879 10880 /// Generates a 'note' diagnostic for an overload candidate. We've 10881 /// already generated a primary error at the call site. 10882 /// 10883 /// It really does need to be a single diagnostic with its caret 10884 /// pointed at the candidate declaration. Yes, this creates some 10885 /// major challenges of technical writing. Yes, this makes pointing 10886 /// out problems with specific arguments quite awkward. It's still 10887 /// better than generating twenty screens of text for every failed 10888 /// overload. 10889 /// 10890 /// It would be great to be able to express per-candidate problems 10891 /// more richly for those diagnostic clients that cared, but we'd 10892 /// still have to be just as careful with the default diagnostics. 10893 /// \param CtorDestAS Addr space of object being constructed (for ctor 10894 /// candidates only). 10895 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10896 unsigned NumArgs, 10897 bool TakingCandidateAddress, 10898 LangAS CtorDestAS = LangAS::Default) { 10899 FunctionDecl *Fn = Cand->Function; 10900 10901 // Note deleted candidates, but only if they're viable. 10902 if (Cand->Viable) { 10903 if (Fn->isDeleted()) { 10904 std::string FnDesc; 10905 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10906 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 10907 Cand->getRewriteKind(), FnDesc); 10908 10909 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10910 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10911 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10912 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10913 return; 10914 } 10915 10916 // We don't really have anything else to say about viable candidates. 10917 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10918 return; 10919 } 10920 10921 switch (Cand->FailureKind) { 10922 case ovl_fail_too_many_arguments: 10923 case ovl_fail_too_few_arguments: 10924 return DiagnoseArityMismatch(S, Cand, NumArgs); 10925 10926 case ovl_fail_bad_deduction: 10927 return DiagnoseBadDeduction(S, Cand, NumArgs, 10928 TakingCandidateAddress); 10929 10930 case ovl_fail_illegal_constructor: { 10931 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10932 << (Fn->getPrimaryTemplate() ? 1 : 0); 10933 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10934 return; 10935 } 10936 10937 case ovl_fail_object_addrspace_mismatch: { 10938 Qualifiers QualsForPrinting; 10939 QualsForPrinting.setAddressSpace(CtorDestAS); 10940 S.Diag(Fn->getLocation(), 10941 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 10942 << QualsForPrinting; 10943 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10944 return; 10945 } 10946 10947 case ovl_fail_trivial_conversion: 10948 case ovl_fail_bad_final_conversion: 10949 case ovl_fail_final_conversion_not_exact: 10950 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10951 10952 case ovl_fail_bad_conversion: { 10953 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10954 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10955 if (Cand->Conversions[I].isBad()) 10956 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10957 10958 // FIXME: this currently happens when we're called from SemaInit 10959 // when user-conversion overload fails. Figure out how to handle 10960 // those conditions and diagnose them well. 10961 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10962 } 10963 10964 case ovl_fail_bad_target: 10965 return DiagnoseBadTarget(S, Cand); 10966 10967 case ovl_fail_enable_if: 10968 return DiagnoseFailedEnableIfAttr(S, Cand); 10969 10970 case ovl_fail_explicit: 10971 return DiagnoseFailedExplicitSpec(S, Cand); 10972 10973 case ovl_fail_ext_disabled: 10974 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10975 10976 case ovl_fail_inhctor_slice: 10977 // It's generally not interesting to note copy/move constructors here. 10978 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10979 return; 10980 S.Diag(Fn->getLocation(), 10981 diag::note_ovl_candidate_inherited_constructor_slice) 10982 << (Fn->getPrimaryTemplate() ? 1 : 0) 10983 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10984 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10985 return; 10986 10987 case ovl_fail_addr_not_available: { 10988 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10989 (void)Available; 10990 assert(!Available); 10991 break; 10992 } 10993 case ovl_non_default_multiversion_function: 10994 // Do nothing, these should simply be ignored. 10995 break; 10996 10997 case ovl_fail_constraints_not_satisfied: { 10998 std::string FnDesc; 10999 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11000 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11001 Cand->getRewriteKind(), FnDesc); 11002 11003 S.Diag(Fn->getLocation(), 11004 diag::note_ovl_candidate_constraints_not_satisfied) 11005 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11006 << FnDesc /* Ignored */; 11007 ConstraintSatisfaction Satisfaction; 11008 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11009 break; 11010 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11011 } 11012 } 11013 } 11014 11015 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11016 // Desugar the type of the surrogate down to a function type, 11017 // retaining as many typedefs as possible while still showing 11018 // the function type (and, therefore, its parameter types). 11019 QualType FnType = Cand->Surrogate->getConversionType(); 11020 bool isLValueReference = false; 11021 bool isRValueReference = false; 11022 bool isPointer = false; 11023 if (const LValueReferenceType *FnTypeRef = 11024 FnType->getAs<LValueReferenceType>()) { 11025 FnType = FnTypeRef->getPointeeType(); 11026 isLValueReference = true; 11027 } else if (const RValueReferenceType *FnTypeRef = 11028 FnType->getAs<RValueReferenceType>()) { 11029 FnType = FnTypeRef->getPointeeType(); 11030 isRValueReference = true; 11031 } 11032 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11033 FnType = FnTypePtr->getPointeeType(); 11034 isPointer = true; 11035 } 11036 // Desugar down to a function type. 11037 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11038 // Reconstruct the pointer/reference as appropriate. 11039 if (isPointer) FnType = S.Context.getPointerType(FnType); 11040 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11041 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11042 11043 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11044 << FnType; 11045 } 11046 11047 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11048 SourceLocation OpLoc, 11049 OverloadCandidate *Cand) { 11050 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11051 std::string TypeStr("operator"); 11052 TypeStr += Opc; 11053 TypeStr += "("; 11054 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11055 if (Cand->Conversions.size() == 1) { 11056 TypeStr += ")"; 11057 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11058 } else { 11059 TypeStr += ", "; 11060 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11061 TypeStr += ")"; 11062 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11063 } 11064 } 11065 11066 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11067 OverloadCandidate *Cand) { 11068 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11069 if (ICS.isBad()) break; // all meaningless after first invalid 11070 if (!ICS.isAmbiguous()) continue; 11071 11072 ICS.DiagnoseAmbiguousConversion( 11073 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11074 } 11075 } 11076 11077 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11078 if (Cand->Function) 11079 return Cand->Function->getLocation(); 11080 if (Cand->IsSurrogate) 11081 return Cand->Surrogate->getLocation(); 11082 return SourceLocation(); 11083 } 11084 11085 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11086 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11087 case Sema::TDK_Success: 11088 case Sema::TDK_NonDependentConversionFailure: 11089 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11090 11091 case Sema::TDK_Invalid: 11092 case Sema::TDK_Incomplete: 11093 case Sema::TDK_IncompletePack: 11094 return 1; 11095 11096 case Sema::TDK_Underqualified: 11097 case Sema::TDK_Inconsistent: 11098 return 2; 11099 11100 case Sema::TDK_SubstitutionFailure: 11101 case Sema::TDK_DeducedMismatch: 11102 case Sema::TDK_ConstraintsNotSatisfied: 11103 case Sema::TDK_DeducedMismatchNested: 11104 case Sema::TDK_NonDeducedMismatch: 11105 case Sema::TDK_MiscellaneousDeductionFailure: 11106 case Sema::TDK_CUDATargetMismatch: 11107 return 3; 11108 11109 case Sema::TDK_InstantiationDepth: 11110 return 4; 11111 11112 case Sema::TDK_InvalidExplicitArguments: 11113 return 5; 11114 11115 case Sema::TDK_TooManyArguments: 11116 case Sema::TDK_TooFewArguments: 11117 return 6; 11118 } 11119 llvm_unreachable("Unhandled deduction result"); 11120 } 11121 11122 namespace { 11123 struct CompareOverloadCandidatesForDisplay { 11124 Sema &S; 11125 SourceLocation Loc; 11126 size_t NumArgs; 11127 OverloadCandidateSet::CandidateSetKind CSK; 11128 11129 CompareOverloadCandidatesForDisplay( 11130 Sema &S, SourceLocation Loc, size_t NArgs, 11131 OverloadCandidateSet::CandidateSetKind CSK) 11132 : S(S), NumArgs(NArgs), CSK(CSK) {} 11133 11134 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11135 // If there are too many or too few arguments, that's the high-order bit we 11136 // want to sort by, even if the immediate failure kind was something else. 11137 if (C->FailureKind == ovl_fail_too_many_arguments || 11138 C->FailureKind == ovl_fail_too_few_arguments) 11139 return static_cast<OverloadFailureKind>(C->FailureKind); 11140 11141 if (C->Function) { 11142 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11143 return ovl_fail_too_many_arguments; 11144 if (NumArgs < C->Function->getMinRequiredArguments()) 11145 return ovl_fail_too_few_arguments; 11146 } 11147 11148 return static_cast<OverloadFailureKind>(C->FailureKind); 11149 } 11150 11151 bool operator()(const OverloadCandidate *L, 11152 const OverloadCandidate *R) { 11153 // Fast-path this check. 11154 if (L == R) return false; 11155 11156 // Order first by viability. 11157 if (L->Viable) { 11158 if (!R->Viable) return true; 11159 11160 // TODO: introduce a tri-valued comparison for overload 11161 // candidates. Would be more worthwhile if we had a sort 11162 // that could exploit it. 11163 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11164 return true; 11165 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11166 return false; 11167 } else if (R->Viable) 11168 return false; 11169 11170 assert(L->Viable == R->Viable); 11171 11172 // Criteria by which we can sort non-viable candidates: 11173 if (!L->Viable) { 11174 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11175 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11176 11177 // 1. Arity mismatches come after other candidates. 11178 if (LFailureKind == ovl_fail_too_many_arguments || 11179 LFailureKind == ovl_fail_too_few_arguments) { 11180 if (RFailureKind == ovl_fail_too_many_arguments || 11181 RFailureKind == ovl_fail_too_few_arguments) { 11182 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11183 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11184 if (LDist == RDist) { 11185 if (LFailureKind == RFailureKind) 11186 // Sort non-surrogates before surrogates. 11187 return !L->IsSurrogate && R->IsSurrogate; 11188 // Sort candidates requiring fewer parameters than there were 11189 // arguments given after candidates requiring more parameters 11190 // than there were arguments given. 11191 return LFailureKind == ovl_fail_too_many_arguments; 11192 } 11193 return LDist < RDist; 11194 } 11195 return false; 11196 } 11197 if (RFailureKind == ovl_fail_too_many_arguments || 11198 RFailureKind == ovl_fail_too_few_arguments) 11199 return true; 11200 11201 // 2. Bad conversions come first and are ordered by the number 11202 // of bad conversions and quality of good conversions. 11203 if (LFailureKind == ovl_fail_bad_conversion) { 11204 if (RFailureKind != ovl_fail_bad_conversion) 11205 return true; 11206 11207 // The conversion that can be fixed with a smaller number of changes, 11208 // comes first. 11209 unsigned numLFixes = L->Fix.NumConversionsFixed; 11210 unsigned numRFixes = R->Fix.NumConversionsFixed; 11211 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11212 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11213 if (numLFixes != numRFixes) { 11214 return numLFixes < numRFixes; 11215 } 11216 11217 // If there's any ordering between the defined conversions... 11218 // FIXME: this might not be transitive. 11219 assert(L->Conversions.size() == R->Conversions.size()); 11220 11221 int leftBetter = 0; 11222 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11223 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11224 switch (CompareImplicitConversionSequences(S, Loc, 11225 L->Conversions[I], 11226 R->Conversions[I])) { 11227 case ImplicitConversionSequence::Better: 11228 leftBetter++; 11229 break; 11230 11231 case ImplicitConversionSequence::Worse: 11232 leftBetter--; 11233 break; 11234 11235 case ImplicitConversionSequence::Indistinguishable: 11236 break; 11237 } 11238 } 11239 if (leftBetter > 0) return true; 11240 if (leftBetter < 0) return false; 11241 11242 } else if (RFailureKind == ovl_fail_bad_conversion) 11243 return false; 11244 11245 if (LFailureKind == ovl_fail_bad_deduction) { 11246 if (RFailureKind != ovl_fail_bad_deduction) 11247 return true; 11248 11249 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11250 return RankDeductionFailure(L->DeductionFailure) 11251 < RankDeductionFailure(R->DeductionFailure); 11252 } else if (RFailureKind == ovl_fail_bad_deduction) 11253 return false; 11254 11255 // TODO: others? 11256 } 11257 11258 // Sort everything else by location. 11259 SourceLocation LLoc = GetLocationForCandidate(L); 11260 SourceLocation RLoc = GetLocationForCandidate(R); 11261 11262 // Put candidates without locations (e.g. builtins) at the end. 11263 if (LLoc.isInvalid()) return false; 11264 if (RLoc.isInvalid()) return true; 11265 11266 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11267 } 11268 }; 11269 } 11270 11271 /// CompleteNonViableCandidate - Normally, overload resolution only 11272 /// computes up to the first bad conversion. Produces the FixIt set if 11273 /// possible. 11274 static void 11275 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11276 ArrayRef<Expr *> Args, 11277 OverloadCandidateSet::CandidateSetKind CSK) { 11278 assert(!Cand->Viable); 11279 11280 // Don't do anything on failures other than bad conversion. 11281 if (Cand->FailureKind != ovl_fail_bad_conversion) 11282 return; 11283 11284 // We only want the FixIts if all the arguments can be corrected. 11285 bool Unfixable = false; 11286 // Use a implicit copy initialization to check conversion fixes. 11287 Cand->Fix.setConversionChecker(TryCopyInitialization); 11288 11289 // Attempt to fix the bad conversion. 11290 unsigned ConvCount = Cand->Conversions.size(); 11291 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11292 ++ConvIdx) { 11293 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11294 if (Cand->Conversions[ConvIdx].isInitialized() && 11295 Cand->Conversions[ConvIdx].isBad()) { 11296 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11297 break; 11298 } 11299 } 11300 11301 // FIXME: this should probably be preserved from the overload 11302 // operation somehow. 11303 bool SuppressUserConversions = false; 11304 11305 unsigned ConvIdx = 0; 11306 unsigned ArgIdx = 0; 11307 ArrayRef<QualType> ParamTypes; 11308 bool Reversed = Cand->isReversed(); 11309 11310 if (Cand->IsSurrogate) { 11311 QualType ConvType 11312 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11313 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11314 ConvType = ConvPtrType->getPointeeType(); 11315 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11316 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11317 ConvIdx = 1; 11318 } else if (Cand->Function) { 11319 ParamTypes = 11320 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11321 if (isa<CXXMethodDecl>(Cand->Function) && 11322 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11323 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11324 ConvIdx = 1; 11325 if (CSK == OverloadCandidateSet::CSK_Operator && 11326 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11327 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11328 ArgIdx = 1; 11329 } 11330 } else { 11331 // Builtin operator. 11332 assert(ConvCount <= 3); 11333 ParamTypes = Cand->BuiltinParamTypes; 11334 } 11335 11336 // Fill in the rest of the conversions. 11337 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11338 ConvIdx != ConvCount; 11339 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11340 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11341 if (Cand->Conversions[ConvIdx].isInitialized()) { 11342 // We've already checked this conversion. 11343 } else if (ParamIdx < ParamTypes.size()) { 11344 if (ParamTypes[ParamIdx]->isDependentType()) 11345 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11346 Args[ArgIdx]->getType()); 11347 else { 11348 Cand->Conversions[ConvIdx] = 11349 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11350 SuppressUserConversions, 11351 /*InOverloadResolution=*/true, 11352 /*AllowObjCWritebackConversion=*/ 11353 S.getLangOpts().ObjCAutoRefCount); 11354 // Store the FixIt in the candidate if it exists. 11355 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11356 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11357 } 11358 } else 11359 Cand->Conversions[ConvIdx].setEllipsis(); 11360 } 11361 } 11362 11363 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11364 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11365 SourceLocation OpLoc, 11366 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11367 // Sort the candidates by viability and position. Sorting directly would 11368 // be prohibitive, so we make a set of pointers and sort those. 11369 SmallVector<OverloadCandidate*, 32> Cands; 11370 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11371 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11372 if (!Filter(*Cand)) 11373 continue; 11374 switch (OCD) { 11375 case OCD_AllCandidates: 11376 if (!Cand->Viable) { 11377 if (!Cand->Function && !Cand->IsSurrogate) { 11378 // This a non-viable builtin candidate. We do not, in general, 11379 // want to list every possible builtin candidate. 11380 continue; 11381 } 11382 CompleteNonViableCandidate(S, Cand, Args, Kind); 11383 } 11384 break; 11385 11386 case OCD_ViableCandidates: 11387 if (!Cand->Viable) 11388 continue; 11389 break; 11390 11391 case OCD_AmbiguousCandidates: 11392 if (!Cand->Best) 11393 continue; 11394 break; 11395 } 11396 11397 Cands.push_back(Cand); 11398 } 11399 11400 llvm::stable_sort( 11401 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11402 11403 return Cands; 11404 } 11405 11406 /// When overload resolution fails, prints diagnostic messages containing the 11407 /// candidates in the candidate set. 11408 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11409 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11410 StringRef Opc, SourceLocation OpLoc, 11411 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11412 11413 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11414 11415 S.Diag(PD.first, PD.second); 11416 11417 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11418 11419 if (OCD == OCD_AmbiguousCandidates) 11420 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11421 } 11422 11423 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11424 ArrayRef<OverloadCandidate *> Cands, 11425 StringRef Opc, SourceLocation OpLoc) { 11426 bool ReportedAmbiguousConversions = false; 11427 11428 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11429 unsigned CandsShown = 0; 11430 auto I = Cands.begin(), E = Cands.end(); 11431 for (; I != E; ++I) { 11432 OverloadCandidate *Cand = *I; 11433 11434 // Set an arbitrary limit on the number of candidate functions we'll spam 11435 // the user with. FIXME: This limit should depend on details of the 11436 // candidate list. 11437 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11438 break; 11439 } 11440 ++CandsShown; 11441 11442 if (Cand->Function) 11443 NoteFunctionCandidate(S, Cand, Args.size(), 11444 /*TakingCandidateAddress=*/false, DestAS); 11445 else if (Cand->IsSurrogate) 11446 NoteSurrogateCandidate(S, Cand); 11447 else { 11448 assert(Cand->Viable && 11449 "Non-viable built-in candidates are not added to Cands."); 11450 // Generally we only see ambiguities including viable builtin 11451 // operators if overload resolution got screwed up by an 11452 // ambiguous user-defined conversion. 11453 // 11454 // FIXME: It's quite possible for different conversions to see 11455 // different ambiguities, though. 11456 if (!ReportedAmbiguousConversions) { 11457 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11458 ReportedAmbiguousConversions = true; 11459 } 11460 11461 // If this is a viable builtin, print it. 11462 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11463 } 11464 } 11465 11466 if (I != E) 11467 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11468 } 11469 11470 static SourceLocation 11471 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11472 return Cand->Specialization ? Cand->Specialization->getLocation() 11473 : SourceLocation(); 11474 } 11475 11476 namespace { 11477 struct CompareTemplateSpecCandidatesForDisplay { 11478 Sema &S; 11479 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11480 11481 bool operator()(const TemplateSpecCandidate *L, 11482 const TemplateSpecCandidate *R) { 11483 // Fast-path this check. 11484 if (L == R) 11485 return false; 11486 11487 // Assuming that both candidates are not matches... 11488 11489 // Sort by the ranking of deduction failures. 11490 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11491 return RankDeductionFailure(L->DeductionFailure) < 11492 RankDeductionFailure(R->DeductionFailure); 11493 11494 // Sort everything else by location. 11495 SourceLocation LLoc = GetLocationForCandidate(L); 11496 SourceLocation RLoc = GetLocationForCandidate(R); 11497 11498 // Put candidates without locations (e.g. builtins) at the end. 11499 if (LLoc.isInvalid()) 11500 return false; 11501 if (RLoc.isInvalid()) 11502 return true; 11503 11504 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11505 } 11506 }; 11507 } 11508 11509 /// Diagnose a template argument deduction failure. 11510 /// We are treating these failures as overload failures due to bad 11511 /// deductions. 11512 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11513 bool ForTakingAddress) { 11514 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11515 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11516 } 11517 11518 void TemplateSpecCandidateSet::destroyCandidates() { 11519 for (iterator i = begin(), e = end(); i != e; ++i) { 11520 i->DeductionFailure.Destroy(); 11521 } 11522 } 11523 11524 void TemplateSpecCandidateSet::clear() { 11525 destroyCandidates(); 11526 Candidates.clear(); 11527 } 11528 11529 /// NoteCandidates - When no template specialization match is found, prints 11530 /// diagnostic messages containing the non-matching specializations that form 11531 /// the candidate set. 11532 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11533 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11534 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11535 // Sort the candidates by position (assuming no candidate is a match). 11536 // Sorting directly would be prohibitive, so we make a set of pointers 11537 // and sort those. 11538 SmallVector<TemplateSpecCandidate *, 32> Cands; 11539 Cands.reserve(size()); 11540 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11541 if (Cand->Specialization) 11542 Cands.push_back(Cand); 11543 // Otherwise, this is a non-matching builtin candidate. We do not, 11544 // in general, want to list every possible builtin candidate. 11545 } 11546 11547 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11548 11549 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11550 // for generalization purposes (?). 11551 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11552 11553 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11554 unsigned CandsShown = 0; 11555 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11556 TemplateSpecCandidate *Cand = *I; 11557 11558 // Set an arbitrary limit on the number of candidates we'll spam 11559 // the user with. FIXME: This limit should depend on details of the 11560 // candidate list. 11561 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11562 break; 11563 ++CandsShown; 11564 11565 assert(Cand->Specialization && 11566 "Non-matching built-in candidates are not added to Cands."); 11567 Cand->NoteDeductionFailure(S, ForTakingAddress); 11568 } 11569 11570 if (I != E) 11571 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11572 } 11573 11574 // [PossiblyAFunctionType] --> [Return] 11575 // NonFunctionType --> NonFunctionType 11576 // R (A) --> R(A) 11577 // R (*)(A) --> R (A) 11578 // R (&)(A) --> R (A) 11579 // R (S::*)(A) --> R (A) 11580 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11581 QualType Ret = PossiblyAFunctionType; 11582 if (const PointerType *ToTypePtr = 11583 PossiblyAFunctionType->getAs<PointerType>()) 11584 Ret = ToTypePtr->getPointeeType(); 11585 else if (const ReferenceType *ToTypeRef = 11586 PossiblyAFunctionType->getAs<ReferenceType>()) 11587 Ret = ToTypeRef->getPointeeType(); 11588 else if (const MemberPointerType *MemTypePtr = 11589 PossiblyAFunctionType->getAs<MemberPointerType>()) 11590 Ret = MemTypePtr->getPointeeType(); 11591 Ret = 11592 Context.getCanonicalType(Ret).getUnqualifiedType(); 11593 return Ret; 11594 } 11595 11596 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11597 bool Complain = true) { 11598 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11599 S.DeduceReturnType(FD, Loc, Complain)) 11600 return true; 11601 11602 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11603 if (S.getLangOpts().CPlusPlus17 && 11604 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11605 !S.ResolveExceptionSpec(Loc, FPT)) 11606 return true; 11607 11608 return false; 11609 } 11610 11611 namespace { 11612 // A helper class to help with address of function resolution 11613 // - allows us to avoid passing around all those ugly parameters 11614 class AddressOfFunctionResolver { 11615 Sema& S; 11616 Expr* SourceExpr; 11617 const QualType& TargetType; 11618 QualType TargetFunctionType; // Extracted function type from target type 11619 11620 bool Complain; 11621 //DeclAccessPair& ResultFunctionAccessPair; 11622 ASTContext& Context; 11623 11624 bool TargetTypeIsNonStaticMemberFunction; 11625 bool FoundNonTemplateFunction; 11626 bool StaticMemberFunctionFromBoundPointer; 11627 bool HasComplained; 11628 11629 OverloadExpr::FindResult OvlExprInfo; 11630 OverloadExpr *OvlExpr; 11631 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11632 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11633 TemplateSpecCandidateSet FailedCandidates; 11634 11635 public: 11636 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11637 const QualType &TargetType, bool Complain) 11638 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11639 Complain(Complain), Context(S.getASTContext()), 11640 TargetTypeIsNonStaticMemberFunction( 11641 !!TargetType->getAs<MemberPointerType>()), 11642 FoundNonTemplateFunction(false), 11643 StaticMemberFunctionFromBoundPointer(false), 11644 HasComplained(false), 11645 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11646 OvlExpr(OvlExprInfo.Expression), 11647 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11648 ExtractUnqualifiedFunctionTypeFromTargetType(); 11649 11650 if (TargetFunctionType->isFunctionType()) { 11651 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11652 if (!UME->isImplicitAccess() && 11653 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11654 StaticMemberFunctionFromBoundPointer = true; 11655 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11656 DeclAccessPair dap; 11657 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11658 OvlExpr, false, &dap)) { 11659 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11660 if (!Method->isStatic()) { 11661 // If the target type is a non-function type and the function found 11662 // is a non-static member function, pretend as if that was the 11663 // target, it's the only possible type to end up with. 11664 TargetTypeIsNonStaticMemberFunction = true; 11665 11666 // And skip adding the function if its not in the proper form. 11667 // We'll diagnose this due to an empty set of functions. 11668 if (!OvlExprInfo.HasFormOfMemberPointer) 11669 return; 11670 } 11671 11672 Matches.push_back(std::make_pair(dap, Fn)); 11673 } 11674 return; 11675 } 11676 11677 if (OvlExpr->hasExplicitTemplateArgs()) 11678 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11679 11680 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11681 // C++ [over.over]p4: 11682 // If more than one function is selected, [...] 11683 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11684 if (FoundNonTemplateFunction) 11685 EliminateAllTemplateMatches(); 11686 else 11687 EliminateAllExceptMostSpecializedTemplate(); 11688 } 11689 } 11690 11691 if (S.getLangOpts().CUDA && Matches.size() > 1) 11692 EliminateSuboptimalCudaMatches(); 11693 } 11694 11695 bool hasComplained() const { return HasComplained; } 11696 11697 private: 11698 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11699 QualType Discard; 11700 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11701 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11702 } 11703 11704 /// \return true if A is considered a better overload candidate for the 11705 /// desired type than B. 11706 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11707 // If A doesn't have exactly the correct type, we don't want to classify it 11708 // as "better" than anything else. This way, the user is required to 11709 // disambiguate for us if there are multiple candidates and no exact match. 11710 return candidateHasExactlyCorrectType(A) && 11711 (!candidateHasExactlyCorrectType(B) || 11712 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11713 } 11714 11715 /// \return true if we were able to eliminate all but one overload candidate, 11716 /// false otherwise. 11717 bool eliminiateSuboptimalOverloadCandidates() { 11718 // Same algorithm as overload resolution -- one pass to pick the "best", 11719 // another pass to be sure that nothing is better than the best. 11720 auto Best = Matches.begin(); 11721 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11722 if (isBetterCandidate(I->second, Best->second)) 11723 Best = I; 11724 11725 const FunctionDecl *BestFn = Best->second; 11726 auto IsBestOrInferiorToBest = [this, BestFn]( 11727 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11728 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11729 }; 11730 11731 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11732 // option, so we can potentially give the user a better error 11733 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11734 return false; 11735 Matches[0] = *Best; 11736 Matches.resize(1); 11737 return true; 11738 } 11739 11740 bool isTargetTypeAFunction() const { 11741 return TargetFunctionType->isFunctionType(); 11742 } 11743 11744 // [ToType] [Return] 11745 11746 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11747 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11748 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11749 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11750 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11751 } 11752 11753 // return true if any matching specializations were found 11754 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11755 const DeclAccessPair& CurAccessFunPair) { 11756 if (CXXMethodDecl *Method 11757 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11758 // Skip non-static function templates when converting to pointer, and 11759 // static when converting to member pointer. 11760 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11761 return false; 11762 } 11763 else if (TargetTypeIsNonStaticMemberFunction) 11764 return false; 11765 11766 // C++ [over.over]p2: 11767 // If the name is a function template, template argument deduction is 11768 // done (14.8.2.2), and if the argument deduction succeeds, the 11769 // resulting template argument list is used to generate a single 11770 // function template specialization, which is added to the set of 11771 // overloaded functions considered. 11772 FunctionDecl *Specialization = nullptr; 11773 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11774 if (Sema::TemplateDeductionResult Result 11775 = S.DeduceTemplateArguments(FunctionTemplate, 11776 &OvlExplicitTemplateArgs, 11777 TargetFunctionType, Specialization, 11778 Info, /*IsAddressOfFunction*/true)) { 11779 // Make a note of the failed deduction for diagnostics. 11780 FailedCandidates.addCandidate() 11781 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11782 MakeDeductionFailureInfo(Context, Result, Info)); 11783 return false; 11784 } 11785 11786 // Template argument deduction ensures that we have an exact match or 11787 // compatible pointer-to-function arguments that would be adjusted by ICS. 11788 // This function template specicalization works. 11789 assert(S.isSameOrCompatibleFunctionType( 11790 Context.getCanonicalType(Specialization->getType()), 11791 Context.getCanonicalType(TargetFunctionType))); 11792 11793 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11794 return false; 11795 11796 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11797 return true; 11798 } 11799 11800 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11801 const DeclAccessPair& CurAccessFunPair) { 11802 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11803 // Skip non-static functions when converting to pointer, and static 11804 // when converting to member pointer. 11805 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11806 return false; 11807 } 11808 else if (TargetTypeIsNonStaticMemberFunction) 11809 return false; 11810 11811 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11812 if (S.getLangOpts().CUDA) 11813 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11814 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11815 return false; 11816 if (FunDecl->isMultiVersion()) { 11817 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11818 if (TA && !TA->isDefaultVersion()) 11819 return false; 11820 } 11821 11822 // If any candidate has a placeholder return type, trigger its deduction 11823 // now. 11824 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11825 Complain)) { 11826 HasComplained |= Complain; 11827 return false; 11828 } 11829 11830 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11831 return false; 11832 11833 // If we're in C, we need to support types that aren't exactly identical. 11834 if (!S.getLangOpts().CPlusPlus || 11835 candidateHasExactlyCorrectType(FunDecl)) { 11836 Matches.push_back(std::make_pair( 11837 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11838 FoundNonTemplateFunction = true; 11839 return true; 11840 } 11841 } 11842 11843 return false; 11844 } 11845 11846 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11847 bool Ret = false; 11848 11849 // If the overload expression doesn't have the form of a pointer to 11850 // member, don't try to convert it to a pointer-to-member type. 11851 if (IsInvalidFormOfPointerToMemberFunction()) 11852 return false; 11853 11854 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11855 E = OvlExpr->decls_end(); 11856 I != E; ++I) { 11857 // Look through any using declarations to find the underlying function. 11858 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11859 11860 // C++ [over.over]p3: 11861 // Non-member functions and static member functions match 11862 // targets of type "pointer-to-function" or "reference-to-function." 11863 // Nonstatic member functions match targets of 11864 // type "pointer-to-member-function." 11865 // Note that according to DR 247, the containing class does not matter. 11866 if (FunctionTemplateDecl *FunctionTemplate 11867 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11868 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11869 Ret = true; 11870 } 11871 // If we have explicit template arguments supplied, skip non-templates. 11872 else if (!OvlExpr->hasExplicitTemplateArgs() && 11873 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11874 Ret = true; 11875 } 11876 assert(Ret || Matches.empty()); 11877 return Ret; 11878 } 11879 11880 void EliminateAllExceptMostSpecializedTemplate() { 11881 // [...] and any given function template specialization F1 is 11882 // eliminated if the set contains a second function template 11883 // specialization whose function template is more specialized 11884 // than the function template of F1 according to the partial 11885 // ordering rules of 14.5.5.2. 11886 11887 // The algorithm specified above is quadratic. We instead use a 11888 // two-pass algorithm (similar to the one used to identify the 11889 // best viable function in an overload set) that identifies the 11890 // best function template (if it exists). 11891 11892 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11893 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11894 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11895 11896 // TODO: It looks like FailedCandidates does not serve much purpose 11897 // here, since the no_viable diagnostic has index 0. 11898 UnresolvedSetIterator Result = S.getMostSpecialized( 11899 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11900 SourceExpr->getBeginLoc(), S.PDiag(), 11901 S.PDiag(diag::err_addr_ovl_ambiguous) 11902 << Matches[0].second->getDeclName(), 11903 S.PDiag(diag::note_ovl_candidate) 11904 << (unsigned)oc_function << (unsigned)ocs_described_template, 11905 Complain, TargetFunctionType); 11906 11907 if (Result != MatchesCopy.end()) { 11908 // Make it the first and only element 11909 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11910 Matches[0].second = cast<FunctionDecl>(*Result); 11911 Matches.resize(1); 11912 } else 11913 HasComplained |= Complain; 11914 } 11915 11916 void EliminateAllTemplateMatches() { 11917 // [...] any function template specializations in the set are 11918 // eliminated if the set also contains a non-template function, [...] 11919 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11920 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11921 ++I; 11922 else { 11923 Matches[I] = Matches[--N]; 11924 Matches.resize(N); 11925 } 11926 } 11927 } 11928 11929 void EliminateSuboptimalCudaMatches() { 11930 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11931 } 11932 11933 public: 11934 void ComplainNoMatchesFound() const { 11935 assert(Matches.empty()); 11936 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11937 << OvlExpr->getName() << TargetFunctionType 11938 << OvlExpr->getSourceRange(); 11939 if (FailedCandidates.empty()) 11940 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11941 /*TakingAddress=*/true); 11942 else { 11943 // We have some deduction failure messages. Use them to diagnose 11944 // the function templates, and diagnose the non-template candidates 11945 // normally. 11946 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11947 IEnd = OvlExpr->decls_end(); 11948 I != IEnd; ++I) 11949 if (FunctionDecl *Fun = 11950 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11951 if (!functionHasPassObjectSizeParams(Fun)) 11952 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 11953 /*TakingAddress=*/true); 11954 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11955 } 11956 } 11957 11958 bool IsInvalidFormOfPointerToMemberFunction() const { 11959 return TargetTypeIsNonStaticMemberFunction && 11960 !OvlExprInfo.HasFormOfMemberPointer; 11961 } 11962 11963 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11964 // TODO: Should we condition this on whether any functions might 11965 // have matched, or is it more appropriate to do that in callers? 11966 // TODO: a fixit wouldn't hurt. 11967 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11968 << TargetType << OvlExpr->getSourceRange(); 11969 } 11970 11971 bool IsStaticMemberFunctionFromBoundPointer() const { 11972 return StaticMemberFunctionFromBoundPointer; 11973 } 11974 11975 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11976 S.Diag(OvlExpr->getBeginLoc(), 11977 diag::err_invalid_form_pointer_member_function) 11978 << OvlExpr->getSourceRange(); 11979 } 11980 11981 void ComplainOfInvalidConversion() const { 11982 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11983 << OvlExpr->getName() << TargetType; 11984 } 11985 11986 void ComplainMultipleMatchesFound() const { 11987 assert(Matches.size() > 1); 11988 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11989 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11990 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11991 /*TakingAddress=*/true); 11992 } 11993 11994 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11995 11996 int getNumMatches() const { return Matches.size(); } 11997 11998 FunctionDecl* getMatchingFunctionDecl() const { 11999 if (Matches.size() != 1) return nullptr; 12000 return Matches[0].second; 12001 } 12002 12003 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12004 if (Matches.size() != 1) return nullptr; 12005 return &Matches[0].first; 12006 } 12007 }; 12008 } 12009 12010 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12011 /// an overloaded function (C++ [over.over]), where @p From is an 12012 /// expression with overloaded function type and @p ToType is the type 12013 /// we're trying to resolve to. For example: 12014 /// 12015 /// @code 12016 /// int f(double); 12017 /// int f(int); 12018 /// 12019 /// int (*pfd)(double) = f; // selects f(double) 12020 /// @endcode 12021 /// 12022 /// This routine returns the resulting FunctionDecl if it could be 12023 /// resolved, and NULL otherwise. When @p Complain is true, this 12024 /// routine will emit diagnostics if there is an error. 12025 FunctionDecl * 12026 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12027 QualType TargetType, 12028 bool Complain, 12029 DeclAccessPair &FoundResult, 12030 bool *pHadMultipleCandidates) { 12031 assert(AddressOfExpr->getType() == Context.OverloadTy); 12032 12033 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12034 Complain); 12035 int NumMatches = Resolver.getNumMatches(); 12036 FunctionDecl *Fn = nullptr; 12037 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12038 if (NumMatches == 0 && ShouldComplain) { 12039 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12040 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12041 else 12042 Resolver.ComplainNoMatchesFound(); 12043 } 12044 else if (NumMatches > 1 && ShouldComplain) 12045 Resolver.ComplainMultipleMatchesFound(); 12046 else if (NumMatches == 1) { 12047 Fn = Resolver.getMatchingFunctionDecl(); 12048 assert(Fn); 12049 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12050 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12051 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12052 if (Complain) { 12053 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12054 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12055 else 12056 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12057 } 12058 } 12059 12060 if (pHadMultipleCandidates) 12061 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12062 return Fn; 12063 } 12064 12065 /// Given an expression that refers to an overloaded function, try to 12066 /// resolve that function to a single function that can have its address taken. 12067 /// This will modify `Pair` iff it returns non-null. 12068 /// 12069 /// This routine can only succeed if from all of the candidates in the overload 12070 /// set for SrcExpr that can have their addresses taken, there is one candidate 12071 /// that is more constrained than the rest. 12072 FunctionDecl * 12073 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12074 OverloadExpr::FindResult R = OverloadExpr::find(E); 12075 OverloadExpr *Ovl = R.Expression; 12076 bool IsResultAmbiguous = false; 12077 FunctionDecl *Result = nullptr; 12078 DeclAccessPair DAP; 12079 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12080 12081 auto CheckMoreConstrained = 12082 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12083 SmallVector<const Expr *, 1> AC1, AC2; 12084 FD1->getAssociatedConstraints(AC1); 12085 FD2->getAssociatedConstraints(AC2); 12086 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12087 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12088 return None; 12089 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12090 return None; 12091 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12092 return None; 12093 return AtLeastAsConstrained1; 12094 }; 12095 12096 // Don't use the AddressOfResolver because we're specifically looking for 12097 // cases where we have one overload candidate that lacks 12098 // enable_if/pass_object_size/... 12099 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12100 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12101 if (!FD) 12102 return nullptr; 12103 12104 if (!checkAddressOfFunctionIsAvailable(FD)) 12105 continue; 12106 12107 // We have more than one result - see if it is more constrained than the 12108 // previous one. 12109 if (Result) { 12110 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12111 Result); 12112 if (!MoreConstrainedThanPrevious) { 12113 IsResultAmbiguous = true; 12114 AmbiguousDecls.push_back(FD); 12115 continue; 12116 } 12117 if (!*MoreConstrainedThanPrevious) 12118 continue; 12119 // FD is more constrained - replace Result with it. 12120 } 12121 IsResultAmbiguous = false; 12122 DAP = I.getPair(); 12123 Result = FD; 12124 } 12125 12126 if (IsResultAmbiguous) 12127 return nullptr; 12128 12129 if (Result) { 12130 SmallVector<const Expr *, 1> ResultAC; 12131 // We skipped over some ambiguous declarations which might be ambiguous with 12132 // the selected result. 12133 for (FunctionDecl *Skipped : AmbiguousDecls) 12134 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12135 return nullptr; 12136 Pair = DAP; 12137 } 12138 return Result; 12139 } 12140 12141 /// Given an overloaded function, tries to turn it into a non-overloaded 12142 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12143 /// will perform access checks, diagnose the use of the resultant decl, and, if 12144 /// requested, potentially perform a function-to-pointer decay. 12145 /// 12146 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12147 /// Otherwise, returns true. This may emit diagnostics and return true. 12148 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12149 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12150 Expr *E = SrcExpr.get(); 12151 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12152 12153 DeclAccessPair DAP; 12154 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12155 if (!Found || Found->isCPUDispatchMultiVersion() || 12156 Found->isCPUSpecificMultiVersion()) 12157 return false; 12158 12159 // Emitting multiple diagnostics for a function that is both inaccessible and 12160 // unavailable is consistent with our behavior elsewhere. So, always check 12161 // for both. 12162 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12163 CheckAddressOfMemberAccess(E, DAP); 12164 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12165 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12166 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12167 else 12168 SrcExpr = Fixed; 12169 return true; 12170 } 12171 12172 /// Given an expression that refers to an overloaded function, try to 12173 /// resolve that overloaded function expression down to a single function. 12174 /// 12175 /// This routine can only resolve template-ids that refer to a single function 12176 /// template, where that template-id refers to a single template whose template 12177 /// arguments are either provided by the template-id or have defaults, 12178 /// as described in C++0x [temp.arg.explicit]p3. 12179 /// 12180 /// If no template-ids are found, no diagnostics are emitted and NULL is 12181 /// returned. 12182 FunctionDecl * 12183 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12184 bool Complain, 12185 DeclAccessPair *FoundResult) { 12186 // C++ [over.over]p1: 12187 // [...] [Note: any redundant set of parentheses surrounding the 12188 // overloaded function name is ignored (5.1). ] 12189 // C++ [over.over]p1: 12190 // [...] The overloaded function name can be preceded by the & 12191 // operator. 12192 12193 // If we didn't actually find any template-ids, we're done. 12194 if (!ovl->hasExplicitTemplateArgs()) 12195 return nullptr; 12196 12197 TemplateArgumentListInfo ExplicitTemplateArgs; 12198 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12199 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12200 12201 // Look through all of the overloaded functions, searching for one 12202 // whose type matches exactly. 12203 FunctionDecl *Matched = nullptr; 12204 for (UnresolvedSetIterator I = ovl->decls_begin(), 12205 E = ovl->decls_end(); I != E; ++I) { 12206 // C++0x [temp.arg.explicit]p3: 12207 // [...] In contexts where deduction is done and fails, or in contexts 12208 // where deduction is not done, if a template argument list is 12209 // specified and it, along with any default template arguments, 12210 // identifies a single function template specialization, then the 12211 // template-id is an lvalue for the function template specialization. 12212 FunctionTemplateDecl *FunctionTemplate 12213 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12214 12215 // C++ [over.over]p2: 12216 // If the name is a function template, template argument deduction is 12217 // done (14.8.2.2), and if the argument deduction succeeds, the 12218 // resulting template argument list is used to generate a single 12219 // function template specialization, which is added to the set of 12220 // overloaded functions considered. 12221 FunctionDecl *Specialization = nullptr; 12222 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12223 if (TemplateDeductionResult Result 12224 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12225 Specialization, Info, 12226 /*IsAddressOfFunction*/true)) { 12227 // Make a note of the failed deduction for diagnostics. 12228 // TODO: Actually use the failed-deduction info? 12229 FailedCandidates.addCandidate() 12230 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12231 MakeDeductionFailureInfo(Context, Result, Info)); 12232 continue; 12233 } 12234 12235 assert(Specialization && "no specialization and no error?"); 12236 12237 // Multiple matches; we can't resolve to a single declaration. 12238 if (Matched) { 12239 if (Complain) { 12240 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12241 << ovl->getName(); 12242 NoteAllOverloadCandidates(ovl); 12243 } 12244 return nullptr; 12245 } 12246 12247 Matched = Specialization; 12248 if (FoundResult) *FoundResult = I.getPair(); 12249 } 12250 12251 if (Matched && 12252 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12253 return nullptr; 12254 12255 return Matched; 12256 } 12257 12258 // Resolve and fix an overloaded expression that can be resolved 12259 // because it identifies a single function template specialization. 12260 // 12261 // Last three arguments should only be supplied if Complain = true 12262 // 12263 // Return true if it was logically possible to so resolve the 12264 // expression, regardless of whether or not it succeeded. Always 12265 // returns true if 'complain' is set. 12266 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12267 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12268 bool complain, SourceRange OpRangeForComplaining, 12269 QualType DestTypeForComplaining, 12270 unsigned DiagIDForComplaining) { 12271 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12272 12273 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12274 12275 DeclAccessPair found; 12276 ExprResult SingleFunctionExpression; 12277 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12278 ovl.Expression, /*complain*/ false, &found)) { 12279 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12280 SrcExpr = ExprError(); 12281 return true; 12282 } 12283 12284 // It is only correct to resolve to an instance method if we're 12285 // resolving a form that's permitted to be a pointer to member. 12286 // Otherwise we'll end up making a bound member expression, which 12287 // is illegal in all the contexts we resolve like this. 12288 if (!ovl.HasFormOfMemberPointer && 12289 isa<CXXMethodDecl>(fn) && 12290 cast<CXXMethodDecl>(fn)->isInstance()) { 12291 if (!complain) return false; 12292 12293 Diag(ovl.Expression->getExprLoc(), 12294 diag::err_bound_member_function) 12295 << 0 << ovl.Expression->getSourceRange(); 12296 12297 // TODO: I believe we only end up here if there's a mix of 12298 // static and non-static candidates (otherwise the expression 12299 // would have 'bound member' type, not 'overload' type). 12300 // Ideally we would note which candidate was chosen and why 12301 // the static candidates were rejected. 12302 SrcExpr = ExprError(); 12303 return true; 12304 } 12305 12306 // Fix the expression to refer to 'fn'. 12307 SingleFunctionExpression = 12308 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12309 12310 // If desired, do function-to-pointer decay. 12311 if (doFunctionPointerConverion) { 12312 SingleFunctionExpression = 12313 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12314 if (SingleFunctionExpression.isInvalid()) { 12315 SrcExpr = ExprError(); 12316 return true; 12317 } 12318 } 12319 } 12320 12321 if (!SingleFunctionExpression.isUsable()) { 12322 if (complain) { 12323 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12324 << ovl.Expression->getName() 12325 << DestTypeForComplaining 12326 << OpRangeForComplaining 12327 << ovl.Expression->getQualifierLoc().getSourceRange(); 12328 NoteAllOverloadCandidates(SrcExpr.get()); 12329 12330 SrcExpr = ExprError(); 12331 return true; 12332 } 12333 12334 return false; 12335 } 12336 12337 SrcExpr = SingleFunctionExpression; 12338 return true; 12339 } 12340 12341 /// Add a single candidate to the overload set. 12342 static void AddOverloadedCallCandidate(Sema &S, 12343 DeclAccessPair FoundDecl, 12344 TemplateArgumentListInfo *ExplicitTemplateArgs, 12345 ArrayRef<Expr *> Args, 12346 OverloadCandidateSet &CandidateSet, 12347 bool PartialOverloading, 12348 bool KnownValid) { 12349 NamedDecl *Callee = FoundDecl.getDecl(); 12350 if (isa<UsingShadowDecl>(Callee)) 12351 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12352 12353 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12354 if (ExplicitTemplateArgs) { 12355 assert(!KnownValid && "Explicit template arguments?"); 12356 return; 12357 } 12358 // Prevent ill-formed function decls to be added as overload candidates. 12359 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12360 return; 12361 12362 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12363 /*SuppressUserConversions=*/false, 12364 PartialOverloading); 12365 return; 12366 } 12367 12368 if (FunctionTemplateDecl *FuncTemplate 12369 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12370 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12371 ExplicitTemplateArgs, Args, CandidateSet, 12372 /*SuppressUserConversions=*/false, 12373 PartialOverloading); 12374 return; 12375 } 12376 12377 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12378 } 12379 12380 /// Add the overload candidates named by callee and/or found by argument 12381 /// dependent lookup to the given overload set. 12382 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12383 ArrayRef<Expr *> Args, 12384 OverloadCandidateSet &CandidateSet, 12385 bool PartialOverloading) { 12386 12387 #ifndef NDEBUG 12388 // Verify that ArgumentDependentLookup is consistent with the rules 12389 // in C++0x [basic.lookup.argdep]p3: 12390 // 12391 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12392 // and let Y be the lookup set produced by argument dependent 12393 // lookup (defined as follows). If X contains 12394 // 12395 // -- a declaration of a class member, or 12396 // 12397 // -- a block-scope function declaration that is not a 12398 // using-declaration, or 12399 // 12400 // -- a declaration that is neither a function or a function 12401 // template 12402 // 12403 // then Y is empty. 12404 12405 if (ULE->requiresADL()) { 12406 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12407 E = ULE->decls_end(); I != E; ++I) { 12408 assert(!(*I)->getDeclContext()->isRecord()); 12409 assert(isa<UsingShadowDecl>(*I) || 12410 !(*I)->getDeclContext()->isFunctionOrMethod()); 12411 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12412 } 12413 } 12414 #endif 12415 12416 // It would be nice to avoid this copy. 12417 TemplateArgumentListInfo TABuffer; 12418 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12419 if (ULE->hasExplicitTemplateArgs()) { 12420 ULE->copyTemplateArgumentsInto(TABuffer); 12421 ExplicitTemplateArgs = &TABuffer; 12422 } 12423 12424 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12425 E = ULE->decls_end(); I != E; ++I) 12426 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12427 CandidateSet, PartialOverloading, 12428 /*KnownValid*/ true); 12429 12430 if (ULE->requiresADL()) 12431 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12432 Args, ExplicitTemplateArgs, 12433 CandidateSet, PartialOverloading); 12434 } 12435 12436 /// Determine whether a declaration with the specified name could be moved into 12437 /// a different namespace. 12438 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12439 switch (Name.getCXXOverloadedOperator()) { 12440 case OO_New: case OO_Array_New: 12441 case OO_Delete: case OO_Array_Delete: 12442 return false; 12443 12444 default: 12445 return true; 12446 } 12447 } 12448 12449 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12450 /// template, where the non-dependent name was declared after the template 12451 /// was defined. This is common in code written for a compilers which do not 12452 /// correctly implement two-stage name lookup. 12453 /// 12454 /// Returns true if a viable candidate was found and a diagnostic was issued. 12455 static bool 12456 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12457 const CXXScopeSpec &SS, LookupResult &R, 12458 OverloadCandidateSet::CandidateSetKind CSK, 12459 TemplateArgumentListInfo *ExplicitTemplateArgs, 12460 ArrayRef<Expr *> Args, 12461 bool *DoDiagnoseEmptyLookup = nullptr) { 12462 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12463 return false; 12464 12465 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12466 if (DC->isTransparentContext()) 12467 continue; 12468 12469 SemaRef.LookupQualifiedName(R, DC); 12470 12471 if (!R.empty()) { 12472 R.suppressDiagnostics(); 12473 12474 if (isa<CXXRecordDecl>(DC)) { 12475 // Don't diagnose names we find in classes; we get much better 12476 // diagnostics for these from DiagnoseEmptyLookup. 12477 R.clear(); 12478 if (DoDiagnoseEmptyLookup) 12479 *DoDiagnoseEmptyLookup = true; 12480 return false; 12481 } 12482 12483 OverloadCandidateSet Candidates(FnLoc, CSK); 12484 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12485 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12486 ExplicitTemplateArgs, Args, 12487 Candidates, false, /*KnownValid*/ false); 12488 12489 OverloadCandidateSet::iterator Best; 12490 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12491 // No viable functions. Don't bother the user with notes for functions 12492 // which don't work and shouldn't be found anyway. 12493 R.clear(); 12494 return false; 12495 } 12496 12497 // Find the namespaces where ADL would have looked, and suggest 12498 // declaring the function there instead. 12499 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12500 Sema::AssociatedClassSet AssociatedClasses; 12501 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12502 AssociatedNamespaces, 12503 AssociatedClasses); 12504 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12505 if (canBeDeclaredInNamespace(R.getLookupName())) { 12506 DeclContext *Std = SemaRef.getStdNamespace(); 12507 for (Sema::AssociatedNamespaceSet::iterator 12508 it = AssociatedNamespaces.begin(), 12509 end = AssociatedNamespaces.end(); it != end; ++it) { 12510 // Never suggest declaring a function within namespace 'std'. 12511 if (Std && Std->Encloses(*it)) 12512 continue; 12513 12514 // Never suggest declaring a function within a namespace with a 12515 // reserved name, like __gnu_cxx. 12516 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12517 if (NS && 12518 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12519 continue; 12520 12521 SuggestedNamespaces.insert(*it); 12522 } 12523 } 12524 12525 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12526 << R.getLookupName(); 12527 if (SuggestedNamespaces.empty()) { 12528 SemaRef.Diag(Best->Function->getLocation(), 12529 diag::note_not_found_by_two_phase_lookup) 12530 << R.getLookupName() << 0; 12531 } else if (SuggestedNamespaces.size() == 1) { 12532 SemaRef.Diag(Best->Function->getLocation(), 12533 diag::note_not_found_by_two_phase_lookup) 12534 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12535 } else { 12536 // FIXME: It would be useful to list the associated namespaces here, 12537 // but the diagnostics infrastructure doesn't provide a way to produce 12538 // a localized representation of a list of items. 12539 SemaRef.Diag(Best->Function->getLocation(), 12540 diag::note_not_found_by_two_phase_lookup) 12541 << R.getLookupName() << 2; 12542 } 12543 12544 // Try to recover by calling this function. 12545 return true; 12546 } 12547 12548 R.clear(); 12549 } 12550 12551 return false; 12552 } 12553 12554 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12555 /// template, where the non-dependent operator was declared after the template 12556 /// was defined. 12557 /// 12558 /// Returns true if a viable candidate was found and a diagnostic was issued. 12559 static bool 12560 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12561 SourceLocation OpLoc, 12562 ArrayRef<Expr *> Args) { 12563 DeclarationName OpName = 12564 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12565 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12566 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12567 OverloadCandidateSet::CSK_Operator, 12568 /*ExplicitTemplateArgs=*/nullptr, Args); 12569 } 12570 12571 namespace { 12572 class BuildRecoveryCallExprRAII { 12573 Sema &SemaRef; 12574 public: 12575 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12576 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12577 SemaRef.IsBuildingRecoveryCallExpr = true; 12578 } 12579 12580 ~BuildRecoveryCallExprRAII() { 12581 SemaRef.IsBuildingRecoveryCallExpr = false; 12582 } 12583 }; 12584 12585 } 12586 12587 /// Attempts to recover from a call where no functions were found. 12588 /// 12589 /// Returns true if new candidates were found. 12590 static ExprResult 12591 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12592 UnresolvedLookupExpr *ULE, 12593 SourceLocation LParenLoc, 12594 MutableArrayRef<Expr *> Args, 12595 SourceLocation RParenLoc, 12596 bool EmptyLookup, bool AllowTypoCorrection) { 12597 // Do not try to recover if it is already building a recovery call. 12598 // This stops infinite loops for template instantiations like 12599 // 12600 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12601 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12602 // 12603 if (SemaRef.IsBuildingRecoveryCallExpr) 12604 return ExprError(); 12605 BuildRecoveryCallExprRAII RCE(SemaRef); 12606 12607 CXXScopeSpec SS; 12608 SS.Adopt(ULE->getQualifierLoc()); 12609 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12610 12611 TemplateArgumentListInfo TABuffer; 12612 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12613 if (ULE->hasExplicitTemplateArgs()) { 12614 ULE->copyTemplateArgumentsInto(TABuffer); 12615 ExplicitTemplateArgs = &TABuffer; 12616 } 12617 12618 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12619 Sema::LookupOrdinaryName); 12620 bool DoDiagnoseEmptyLookup = EmptyLookup; 12621 if (!DiagnoseTwoPhaseLookup( 12622 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12623 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12624 NoTypoCorrectionCCC NoTypoValidator{}; 12625 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12626 ExplicitTemplateArgs != nullptr, 12627 dyn_cast<MemberExpr>(Fn)); 12628 CorrectionCandidateCallback &Validator = 12629 AllowTypoCorrection 12630 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12631 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12632 if (!DoDiagnoseEmptyLookup || 12633 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12634 Args)) 12635 return ExprError(); 12636 } 12637 12638 assert(!R.empty() && "lookup results empty despite recovery"); 12639 12640 // If recovery created an ambiguity, just bail out. 12641 if (R.isAmbiguous()) { 12642 R.suppressDiagnostics(); 12643 return ExprError(); 12644 } 12645 12646 // Build an implicit member call if appropriate. Just drop the 12647 // casts and such from the call, we don't really care. 12648 ExprResult NewFn = ExprError(); 12649 if ((*R.begin())->isCXXClassMember()) 12650 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12651 ExplicitTemplateArgs, S); 12652 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12653 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12654 ExplicitTemplateArgs); 12655 else 12656 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12657 12658 if (NewFn.isInvalid()) 12659 return ExprError(); 12660 12661 // This shouldn't cause an infinite loop because we're giving it 12662 // an expression with viable lookup results, which should never 12663 // end up here. 12664 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12665 MultiExprArg(Args.data(), Args.size()), 12666 RParenLoc); 12667 } 12668 12669 /// Constructs and populates an OverloadedCandidateSet from 12670 /// the given function. 12671 /// \returns true when an the ExprResult output parameter has been set. 12672 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12673 UnresolvedLookupExpr *ULE, 12674 MultiExprArg Args, 12675 SourceLocation RParenLoc, 12676 OverloadCandidateSet *CandidateSet, 12677 ExprResult *Result) { 12678 #ifndef NDEBUG 12679 if (ULE->requiresADL()) { 12680 // To do ADL, we must have found an unqualified name. 12681 assert(!ULE->getQualifier() && "qualified name with ADL"); 12682 12683 // We don't perform ADL for implicit declarations of builtins. 12684 // Verify that this was correctly set up. 12685 FunctionDecl *F; 12686 if (ULE->decls_begin() != ULE->decls_end() && 12687 ULE->decls_begin() + 1 == ULE->decls_end() && 12688 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12689 F->getBuiltinID() && F->isImplicit()) 12690 llvm_unreachable("performing ADL for builtin"); 12691 12692 // We don't perform ADL in C. 12693 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12694 } 12695 #endif 12696 12697 UnbridgedCastsSet UnbridgedCasts; 12698 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12699 *Result = ExprError(); 12700 return true; 12701 } 12702 12703 // Add the functions denoted by the callee to the set of candidate 12704 // functions, including those from argument-dependent lookup. 12705 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12706 12707 if (getLangOpts().MSVCCompat && 12708 CurContext->isDependentContext() && !isSFINAEContext() && 12709 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12710 12711 OverloadCandidateSet::iterator Best; 12712 if (CandidateSet->empty() || 12713 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12714 OR_No_Viable_Function) { 12715 // In Microsoft mode, if we are inside a template class member function 12716 // then create a type dependent CallExpr. The goal is to postpone name 12717 // lookup to instantiation time to be able to search into type dependent 12718 // base classes. 12719 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12720 VK_RValue, RParenLoc); 12721 CE->setTypeDependent(true); 12722 CE->setValueDependent(true); 12723 CE->setInstantiationDependent(true); 12724 *Result = CE; 12725 return true; 12726 } 12727 } 12728 12729 if (CandidateSet->empty()) 12730 return false; 12731 12732 UnbridgedCasts.restore(); 12733 return false; 12734 } 12735 12736 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12737 /// the completed call expression. If overload resolution fails, emits 12738 /// diagnostics and returns ExprError() 12739 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12740 UnresolvedLookupExpr *ULE, 12741 SourceLocation LParenLoc, 12742 MultiExprArg Args, 12743 SourceLocation RParenLoc, 12744 Expr *ExecConfig, 12745 OverloadCandidateSet *CandidateSet, 12746 OverloadCandidateSet::iterator *Best, 12747 OverloadingResult OverloadResult, 12748 bool AllowTypoCorrection) { 12749 if (CandidateSet->empty()) 12750 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12751 RParenLoc, /*EmptyLookup=*/true, 12752 AllowTypoCorrection); 12753 12754 switch (OverloadResult) { 12755 case OR_Success: { 12756 FunctionDecl *FDecl = (*Best)->Function; 12757 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12758 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12759 return ExprError(); 12760 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12761 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12762 ExecConfig, /*IsExecConfig=*/false, 12763 (*Best)->IsADLCandidate); 12764 } 12765 12766 case OR_No_Viable_Function: { 12767 // Try to recover by looking for viable functions which the user might 12768 // have meant to call. 12769 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12770 Args, RParenLoc, 12771 /*EmptyLookup=*/false, 12772 AllowTypoCorrection); 12773 if (!Recovery.isInvalid()) 12774 return Recovery; 12775 12776 // If the user passes in a function that we can't take the address of, we 12777 // generally end up emitting really bad error messages. Here, we attempt to 12778 // emit better ones. 12779 for (const Expr *Arg : Args) { 12780 if (!Arg->getType()->isFunctionType()) 12781 continue; 12782 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12783 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12784 if (FD && 12785 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12786 Arg->getExprLoc())) 12787 return ExprError(); 12788 } 12789 } 12790 12791 CandidateSet->NoteCandidates( 12792 PartialDiagnosticAt( 12793 Fn->getBeginLoc(), 12794 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12795 << ULE->getName() << Fn->getSourceRange()), 12796 SemaRef, OCD_AllCandidates, Args); 12797 break; 12798 } 12799 12800 case OR_Ambiguous: 12801 CandidateSet->NoteCandidates( 12802 PartialDiagnosticAt(Fn->getBeginLoc(), 12803 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12804 << ULE->getName() << Fn->getSourceRange()), 12805 SemaRef, OCD_AmbiguousCandidates, Args); 12806 break; 12807 12808 case OR_Deleted: { 12809 CandidateSet->NoteCandidates( 12810 PartialDiagnosticAt(Fn->getBeginLoc(), 12811 SemaRef.PDiag(diag::err_ovl_deleted_call) 12812 << ULE->getName() << Fn->getSourceRange()), 12813 SemaRef, OCD_AllCandidates, Args); 12814 12815 // We emitted an error for the unavailable/deleted function call but keep 12816 // the call in the AST. 12817 FunctionDecl *FDecl = (*Best)->Function; 12818 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12819 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12820 ExecConfig, /*IsExecConfig=*/false, 12821 (*Best)->IsADLCandidate); 12822 } 12823 } 12824 12825 // Overload resolution failed. 12826 return ExprError(); 12827 } 12828 12829 static void markUnaddressableCandidatesUnviable(Sema &S, 12830 OverloadCandidateSet &CS) { 12831 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12832 if (I->Viable && 12833 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12834 I->Viable = false; 12835 I->FailureKind = ovl_fail_addr_not_available; 12836 } 12837 } 12838 } 12839 12840 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12841 /// (which eventually refers to the declaration Func) and the call 12842 /// arguments Args/NumArgs, attempt to resolve the function call down 12843 /// to a specific function. If overload resolution succeeds, returns 12844 /// the call expression produced by overload resolution. 12845 /// Otherwise, emits diagnostics and returns ExprError. 12846 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12847 UnresolvedLookupExpr *ULE, 12848 SourceLocation LParenLoc, 12849 MultiExprArg Args, 12850 SourceLocation RParenLoc, 12851 Expr *ExecConfig, 12852 bool AllowTypoCorrection, 12853 bool CalleesAddressIsTaken) { 12854 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12855 OverloadCandidateSet::CSK_Normal); 12856 ExprResult result; 12857 12858 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12859 &result)) 12860 return result; 12861 12862 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12863 // functions that aren't addressible are considered unviable. 12864 if (CalleesAddressIsTaken) 12865 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12866 12867 OverloadCandidateSet::iterator Best; 12868 OverloadingResult OverloadResult = 12869 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12870 12871 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 12872 ExecConfig, &CandidateSet, &Best, 12873 OverloadResult, AllowTypoCorrection); 12874 } 12875 12876 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12877 return Functions.size() > 1 || 12878 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12879 } 12880 12881 /// Create a unary operation that may resolve to an overloaded 12882 /// operator. 12883 /// 12884 /// \param OpLoc The location of the operator itself (e.g., '*'). 12885 /// 12886 /// \param Opc The UnaryOperatorKind that describes this operator. 12887 /// 12888 /// \param Fns The set of non-member functions that will be 12889 /// considered by overload resolution. The caller needs to build this 12890 /// set based on the context using, e.g., 12891 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12892 /// set should not contain any member functions; those will be added 12893 /// by CreateOverloadedUnaryOp(). 12894 /// 12895 /// \param Input The input argument. 12896 ExprResult 12897 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12898 const UnresolvedSetImpl &Fns, 12899 Expr *Input, bool PerformADL) { 12900 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12901 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12902 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12903 // TODO: provide better source location info. 12904 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12905 12906 if (checkPlaceholderForOverload(*this, Input)) 12907 return ExprError(); 12908 12909 Expr *Args[2] = { Input, nullptr }; 12910 unsigned NumArgs = 1; 12911 12912 // For post-increment and post-decrement, add the implicit '0' as 12913 // the second argument, so that we know this is a post-increment or 12914 // post-decrement. 12915 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12916 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12917 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12918 SourceLocation()); 12919 NumArgs = 2; 12920 } 12921 12922 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12923 12924 if (Input->isTypeDependent()) { 12925 if (Fns.empty()) 12926 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12927 VK_RValue, OK_Ordinary, OpLoc, false); 12928 12929 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12930 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12931 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12932 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12933 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12934 Context.DependentTy, VK_RValue, OpLoc, 12935 FPOptions()); 12936 } 12937 12938 // Build an empty overload set. 12939 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12940 12941 // Add the candidates from the given function set. 12942 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 12943 12944 // Add operator candidates that are member functions. 12945 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12946 12947 // Add candidates from ADL. 12948 if (PerformADL) { 12949 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12950 /*ExplicitTemplateArgs*/nullptr, 12951 CandidateSet); 12952 } 12953 12954 // Add builtin operator candidates. 12955 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12956 12957 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12958 12959 // Perform overload resolution. 12960 OverloadCandidateSet::iterator Best; 12961 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12962 case OR_Success: { 12963 // We found a built-in operator or an overloaded operator. 12964 FunctionDecl *FnDecl = Best->Function; 12965 12966 if (FnDecl) { 12967 Expr *Base = nullptr; 12968 // We matched an overloaded operator. Build a call to that 12969 // operator. 12970 12971 // Convert the arguments. 12972 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12973 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12974 12975 ExprResult InputRes = 12976 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12977 Best->FoundDecl, Method); 12978 if (InputRes.isInvalid()) 12979 return ExprError(); 12980 Base = Input = InputRes.get(); 12981 } else { 12982 // Convert the arguments. 12983 ExprResult InputInit 12984 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12985 Context, 12986 FnDecl->getParamDecl(0)), 12987 SourceLocation(), 12988 Input); 12989 if (InputInit.isInvalid()) 12990 return ExprError(); 12991 Input = InputInit.get(); 12992 } 12993 12994 // Build the actual expression node. 12995 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12996 Base, HadMultipleCandidates, 12997 OpLoc); 12998 if (FnExpr.isInvalid()) 12999 return ExprError(); 13000 13001 // Determine the result type. 13002 QualType ResultTy = FnDecl->getReturnType(); 13003 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13004 ResultTy = ResultTy.getNonLValueExprType(Context); 13005 13006 Args[0] = Input; 13007 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13008 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13009 FPOptions(), Best->IsADLCandidate); 13010 13011 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13012 return ExprError(); 13013 13014 if (CheckFunctionCall(FnDecl, TheCall, 13015 FnDecl->getType()->castAs<FunctionProtoType>())) 13016 return ExprError(); 13017 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13018 } else { 13019 // We matched a built-in operator. Convert the arguments, then 13020 // break out so that we will build the appropriate built-in 13021 // operator node. 13022 ExprResult InputRes = PerformImplicitConversion( 13023 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13024 CCK_ForBuiltinOverloadedOp); 13025 if (InputRes.isInvalid()) 13026 return ExprError(); 13027 Input = InputRes.get(); 13028 break; 13029 } 13030 } 13031 13032 case OR_No_Viable_Function: 13033 // This is an erroneous use of an operator which can be overloaded by 13034 // a non-member function. Check for non-member operators which were 13035 // defined too late to be candidates. 13036 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13037 // FIXME: Recover by calling the found function. 13038 return ExprError(); 13039 13040 // No viable function; fall through to handling this as a 13041 // built-in operator, which will produce an error message for us. 13042 break; 13043 13044 case OR_Ambiguous: 13045 CandidateSet.NoteCandidates( 13046 PartialDiagnosticAt(OpLoc, 13047 PDiag(diag::err_ovl_ambiguous_oper_unary) 13048 << UnaryOperator::getOpcodeStr(Opc) 13049 << Input->getType() << Input->getSourceRange()), 13050 *this, OCD_AmbiguousCandidates, ArgsArray, 13051 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13052 return ExprError(); 13053 13054 case OR_Deleted: 13055 CandidateSet.NoteCandidates( 13056 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13057 << UnaryOperator::getOpcodeStr(Opc) 13058 << Input->getSourceRange()), 13059 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13060 OpLoc); 13061 return ExprError(); 13062 } 13063 13064 // Either we found no viable overloaded operator or we matched a 13065 // built-in operator. In either case, fall through to trying to 13066 // build a built-in operation. 13067 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13068 } 13069 13070 /// Perform lookup for an overloaded binary operator. 13071 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13072 OverloadedOperatorKind Op, 13073 const UnresolvedSetImpl &Fns, 13074 ArrayRef<Expr *> Args, bool PerformADL) { 13075 SourceLocation OpLoc = CandidateSet.getLocation(); 13076 13077 OverloadedOperatorKind ExtraOp = 13078 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13079 ? getRewrittenOverloadedOperator(Op) 13080 : OO_None; 13081 13082 // Add the candidates from the given function set. This also adds the 13083 // rewritten candidates using these functions if necessary. 13084 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13085 13086 // Add operator candidates that are member functions. 13087 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13088 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13089 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13090 OverloadCandidateParamOrder::Reversed); 13091 13092 // In C++20, also add any rewritten member candidates. 13093 if (ExtraOp) { 13094 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13095 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13096 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13097 CandidateSet, 13098 OverloadCandidateParamOrder::Reversed); 13099 } 13100 13101 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13102 // performed for an assignment operator (nor for operator[] nor operator->, 13103 // which don't get here). 13104 if (Op != OO_Equal && PerformADL) { 13105 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13106 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13107 /*ExplicitTemplateArgs*/ nullptr, 13108 CandidateSet); 13109 if (ExtraOp) { 13110 DeclarationName ExtraOpName = 13111 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13112 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13113 /*ExplicitTemplateArgs*/ nullptr, 13114 CandidateSet); 13115 } 13116 } 13117 13118 // Add builtin operator candidates. 13119 // 13120 // FIXME: We don't add any rewritten candidates here. This is strictly 13121 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13122 // resulting in our selecting a rewritten builtin candidate. For example: 13123 // 13124 // enum class E { e }; 13125 // bool operator!=(E, E) requires false; 13126 // bool k = E::e != E::e; 13127 // 13128 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13129 // it seems unreasonable to consider rewritten builtin candidates. A core 13130 // issue has been filed proposing to removed this requirement. 13131 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13132 } 13133 13134 /// Create a binary operation that may resolve to an overloaded 13135 /// operator. 13136 /// 13137 /// \param OpLoc The location of the operator itself (e.g., '+'). 13138 /// 13139 /// \param Opc The BinaryOperatorKind that describes this operator. 13140 /// 13141 /// \param Fns The set of non-member functions that will be 13142 /// considered by overload resolution. The caller needs to build this 13143 /// set based on the context using, e.g., 13144 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13145 /// set should not contain any member functions; those will be added 13146 /// by CreateOverloadedBinOp(). 13147 /// 13148 /// \param LHS Left-hand argument. 13149 /// \param RHS Right-hand argument. 13150 /// \param PerformADL Whether to consider operator candidates found by ADL. 13151 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13152 /// C++20 operator rewrites. 13153 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13154 /// the function in question. Such a function is never a candidate in 13155 /// our overload resolution. This also enables synthesizing a three-way 13156 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13157 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13158 BinaryOperatorKind Opc, 13159 const UnresolvedSetImpl &Fns, Expr *LHS, 13160 Expr *RHS, bool PerformADL, 13161 bool AllowRewrittenCandidates, 13162 FunctionDecl *DefaultedFn) { 13163 Expr *Args[2] = { LHS, RHS }; 13164 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13165 13166 if (!getLangOpts().CPlusPlus2a) 13167 AllowRewrittenCandidates = false; 13168 13169 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13170 13171 // If either side is type-dependent, create an appropriate dependent 13172 // expression. 13173 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13174 if (Fns.empty()) { 13175 // If there are no functions to store, just build a dependent 13176 // BinaryOperator or CompoundAssignment. 13177 if (Opc <= BO_Assign || Opc > BO_OrAssign) 13178 return new (Context) BinaryOperator( 13179 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 13180 OpLoc, FPFeatures); 13181 13182 return new (Context) CompoundAssignOperator( 13183 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 13184 Context.DependentTy, Context.DependentTy, OpLoc, 13185 FPFeatures); 13186 } 13187 13188 // FIXME: save results of ADL from here? 13189 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13190 // TODO: provide better source location info in DNLoc component. 13191 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13192 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13193 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 13194 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 13195 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 13196 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 13197 Context.DependentTy, VK_RValue, OpLoc, 13198 FPFeatures); 13199 } 13200 13201 // Always do placeholder-like conversions on the RHS. 13202 if (checkPlaceholderForOverload(*this, Args[1])) 13203 return ExprError(); 13204 13205 // Do placeholder-like conversion on the LHS; note that we should 13206 // not get here with a PseudoObject LHS. 13207 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13208 if (checkPlaceholderForOverload(*this, Args[0])) 13209 return ExprError(); 13210 13211 // If this is the assignment operator, we only perform overload resolution 13212 // if the left-hand side is a class or enumeration type. This is actually 13213 // a hack. The standard requires that we do overload resolution between the 13214 // various built-in candidates, but as DR507 points out, this can lead to 13215 // problems. So we do it this way, which pretty much follows what GCC does. 13216 // Note that we go the traditional code path for compound assignment forms. 13217 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13218 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13219 13220 // If this is the .* operator, which is not overloadable, just 13221 // create a built-in binary operator. 13222 if (Opc == BO_PtrMemD) 13223 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13224 13225 // Build the overload set. 13226 OverloadCandidateSet CandidateSet( 13227 OpLoc, OverloadCandidateSet::CSK_Operator, 13228 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13229 if (DefaultedFn) 13230 CandidateSet.exclude(DefaultedFn); 13231 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13232 13233 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13234 13235 // Perform overload resolution. 13236 OverloadCandidateSet::iterator Best; 13237 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13238 case OR_Success: { 13239 // We found a built-in operator or an overloaded operator. 13240 FunctionDecl *FnDecl = Best->Function; 13241 13242 bool IsReversed = Best->isReversed(); 13243 if (IsReversed) 13244 std::swap(Args[0], Args[1]); 13245 13246 if (FnDecl) { 13247 Expr *Base = nullptr; 13248 // We matched an overloaded operator. Build a call to that 13249 // operator. 13250 13251 OverloadedOperatorKind ChosenOp = 13252 FnDecl->getDeclName().getCXXOverloadedOperator(); 13253 13254 // C++2a [over.match.oper]p9: 13255 // If a rewritten operator== candidate is selected by overload 13256 // resolution for an operator@, its return type shall be cv bool 13257 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13258 !FnDecl->getReturnType()->isBooleanType()) { 13259 Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool) 13260 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13261 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13262 Diag(FnDecl->getLocation(), diag::note_declared_at); 13263 return ExprError(); 13264 } 13265 13266 if (AllowRewrittenCandidates && !IsReversed && 13267 CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) { 13268 // We could have reversed this operator, but didn't. Check if the 13269 // reversed form was a viable candidate, and if so, if it had a 13270 // better conversion for either parameter. If so, this call is 13271 // formally ambiguous, and allowing it is an extension. 13272 for (OverloadCandidate &Cand : CandidateSet) { 13273 if (Cand.Viable && Cand.Function == FnDecl && 13274 Cand.isReversed()) { 13275 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13276 if (CompareImplicitConversionSequences( 13277 *this, OpLoc, Cand.Conversions[ArgIdx], 13278 Best->Conversions[ArgIdx]) == 13279 ImplicitConversionSequence::Better) { 13280 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13281 << BinaryOperator::getOpcodeStr(Opc) 13282 << Args[0]->getType() << Args[1]->getType() 13283 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13284 Diag(FnDecl->getLocation(), 13285 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13286 } 13287 } 13288 break; 13289 } 13290 } 13291 } 13292 13293 // Convert the arguments. 13294 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13295 // Best->Access is only meaningful for class members. 13296 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13297 13298 ExprResult Arg1 = 13299 PerformCopyInitialization( 13300 InitializedEntity::InitializeParameter(Context, 13301 FnDecl->getParamDecl(0)), 13302 SourceLocation(), Args[1]); 13303 if (Arg1.isInvalid()) 13304 return ExprError(); 13305 13306 ExprResult Arg0 = 13307 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13308 Best->FoundDecl, Method); 13309 if (Arg0.isInvalid()) 13310 return ExprError(); 13311 Base = Args[0] = Arg0.getAs<Expr>(); 13312 Args[1] = RHS = Arg1.getAs<Expr>(); 13313 } else { 13314 // Convert the arguments. 13315 ExprResult Arg0 = PerformCopyInitialization( 13316 InitializedEntity::InitializeParameter(Context, 13317 FnDecl->getParamDecl(0)), 13318 SourceLocation(), Args[0]); 13319 if (Arg0.isInvalid()) 13320 return ExprError(); 13321 13322 ExprResult Arg1 = 13323 PerformCopyInitialization( 13324 InitializedEntity::InitializeParameter(Context, 13325 FnDecl->getParamDecl(1)), 13326 SourceLocation(), Args[1]); 13327 if (Arg1.isInvalid()) 13328 return ExprError(); 13329 Args[0] = LHS = Arg0.getAs<Expr>(); 13330 Args[1] = RHS = Arg1.getAs<Expr>(); 13331 } 13332 13333 // Build the actual expression node. 13334 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13335 Best->FoundDecl, Base, 13336 HadMultipleCandidates, OpLoc); 13337 if (FnExpr.isInvalid()) 13338 return ExprError(); 13339 13340 // Determine the result type. 13341 QualType ResultTy = FnDecl->getReturnType(); 13342 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13343 ResultTy = ResultTy.getNonLValueExprType(Context); 13344 13345 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13346 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13347 FPFeatures, Best->IsADLCandidate); 13348 13349 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13350 FnDecl)) 13351 return ExprError(); 13352 13353 ArrayRef<const Expr *> ArgsArray(Args, 2); 13354 const Expr *ImplicitThis = nullptr; 13355 // Cut off the implicit 'this'. 13356 if (isa<CXXMethodDecl>(FnDecl)) { 13357 ImplicitThis = ArgsArray[0]; 13358 ArgsArray = ArgsArray.slice(1); 13359 } 13360 13361 // Check for a self move. 13362 if (Op == OO_Equal) 13363 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13364 13365 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13366 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13367 VariadicDoesNotApply); 13368 13369 ExprResult R = MaybeBindToTemporary(TheCall); 13370 if (R.isInvalid()) 13371 return ExprError(); 13372 13373 // For a rewritten candidate, we've already reversed the arguments 13374 // if needed. Perform the rest of the rewrite now. 13375 if ((Best->RewriteKind & CRK_DifferentOperator) || 13376 (Op == OO_Spaceship && IsReversed)) { 13377 if (Op == OO_ExclaimEqual) { 13378 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13379 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13380 } else { 13381 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13382 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13383 Expr *ZeroLiteral = 13384 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13385 13386 Sema::CodeSynthesisContext Ctx; 13387 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13388 Ctx.Entity = FnDecl; 13389 pushCodeSynthesisContext(Ctx); 13390 13391 R = CreateOverloadedBinOp( 13392 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13393 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13394 /*AllowRewrittenCandidates=*/false); 13395 13396 popCodeSynthesisContext(); 13397 } 13398 if (R.isInvalid()) 13399 return ExprError(); 13400 } else { 13401 assert(ChosenOp == Op && "unexpected operator name"); 13402 } 13403 13404 // Make a note in the AST if we did any rewriting. 13405 if (Best->RewriteKind != CRK_None) 13406 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13407 13408 return CheckForImmediateInvocation(R, FnDecl); 13409 } else { 13410 // We matched a built-in operator. Convert the arguments, then 13411 // break out so that we will build the appropriate built-in 13412 // operator node. 13413 ExprResult ArgsRes0 = PerformImplicitConversion( 13414 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13415 AA_Passing, CCK_ForBuiltinOverloadedOp); 13416 if (ArgsRes0.isInvalid()) 13417 return ExprError(); 13418 Args[0] = ArgsRes0.get(); 13419 13420 ExprResult ArgsRes1 = PerformImplicitConversion( 13421 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13422 AA_Passing, CCK_ForBuiltinOverloadedOp); 13423 if (ArgsRes1.isInvalid()) 13424 return ExprError(); 13425 Args[1] = ArgsRes1.get(); 13426 break; 13427 } 13428 } 13429 13430 case OR_No_Viable_Function: { 13431 // C++ [over.match.oper]p9: 13432 // If the operator is the operator , [...] and there are no 13433 // viable functions, then the operator is assumed to be the 13434 // built-in operator and interpreted according to clause 5. 13435 if (Opc == BO_Comma) 13436 break; 13437 13438 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13439 // compare result using '==' and '<'. 13440 if (DefaultedFn && Opc == BO_Cmp) { 13441 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13442 Args[1], DefaultedFn); 13443 if (E.isInvalid() || E.isUsable()) 13444 return E; 13445 } 13446 13447 // For class as left operand for assignment or compound assignment 13448 // operator do not fall through to handling in built-in, but report that 13449 // no overloaded assignment operator found 13450 ExprResult Result = ExprError(); 13451 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13452 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13453 Args, OpLoc); 13454 if (Args[0]->getType()->isRecordType() && 13455 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13456 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13457 << BinaryOperator::getOpcodeStr(Opc) 13458 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13459 if (Args[0]->getType()->isIncompleteType()) { 13460 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13461 << Args[0]->getType() 13462 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13463 } 13464 } else { 13465 // This is an erroneous use of an operator which can be overloaded by 13466 // a non-member function. Check for non-member operators which were 13467 // defined too late to be candidates. 13468 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13469 // FIXME: Recover by calling the found function. 13470 return ExprError(); 13471 13472 // No viable function; try to create a built-in operation, which will 13473 // produce an error. Then, show the non-viable candidates. 13474 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13475 } 13476 assert(Result.isInvalid() && 13477 "C++ binary operator overloading is missing candidates!"); 13478 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13479 return Result; 13480 } 13481 13482 case OR_Ambiguous: 13483 CandidateSet.NoteCandidates( 13484 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13485 << BinaryOperator::getOpcodeStr(Opc) 13486 << Args[0]->getType() 13487 << Args[1]->getType() 13488 << Args[0]->getSourceRange() 13489 << Args[1]->getSourceRange()), 13490 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13491 OpLoc); 13492 return ExprError(); 13493 13494 case OR_Deleted: 13495 if (isImplicitlyDeleted(Best->Function)) { 13496 FunctionDecl *DeletedFD = Best->Function; 13497 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13498 if (DFK.isSpecialMember()) { 13499 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13500 << Args[0]->getType() << DFK.asSpecialMember(); 13501 } else { 13502 assert(DFK.isComparison()); 13503 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13504 << Args[0]->getType() << DeletedFD; 13505 } 13506 13507 // The user probably meant to call this special member. Just 13508 // explain why it's deleted. 13509 NoteDeletedFunction(DeletedFD); 13510 return ExprError(); 13511 } 13512 CandidateSet.NoteCandidates( 13513 PartialDiagnosticAt( 13514 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13515 << getOperatorSpelling(Best->Function->getDeclName() 13516 .getCXXOverloadedOperator()) 13517 << Args[0]->getSourceRange() 13518 << Args[1]->getSourceRange()), 13519 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13520 OpLoc); 13521 return ExprError(); 13522 } 13523 13524 // We matched a built-in operator; build it. 13525 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13526 } 13527 13528 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13529 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13530 FunctionDecl *DefaultedFn) { 13531 const ComparisonCategoryInfo *Info = 13532 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13533 // If we're not producing a known comparison category type, we can't 13534 // synthesize a three-way comparison. Let the caller diagnose this. 13535 if (!Info) 13536 return ExprResult((Expr*)nullptr); 13537 13538 // If we ever want to perform this synthesis more generally, we will need to 13539 // apply the temporary materialization conversion to the operands. 13540 assert(LHS->isGLValue() && RHS->isGLValue() && 13541 "cannot use prvalue expressions more than once"); 13542 Expr *OrigLHS = LHS; 13543 Expr *OrigRHS = RHS; 13544 13545 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13546 // each of them multiple times below. 13547 LHS = new (Context) 13548 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13549 LHS->getObjectKind(), LHS); 13550 RHS = new (Context) 13551 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13552 RHS->getObjectKind(), RHS); 13553 13554 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13555 DefaultedFn); 13556 if (Eq.isInvalid()) 13557 return ExprError(); 13558 13559 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13560 true, DefaultedFn); 13561 if (Less.isInvalid()) 13562 return ExprError(); 13563 13564 ExprResult Greater; 13565 if (Info->isPartial()) { 13566 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13567 DefaultedFn); 13568 if (Greater.isInvalid()) 13569 return ExprError(); 13570 } 13571 13572 // Form the list of comparisons we're going to perform. 13573 struct Comparison { 13574 ExprResult Cmp; 13575 ComparisonCategoryResult Result; 13576 } Comparisons[4] = 13577 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13578 : ComparisonCategoryResult::Equivalent}, 13579 {Less, ComparisonCategoryResult::Less}, 13580 {Greater, ComparisonCategoryResult::Greater}, 13581 {ExprResult(), ComparisonCategoryResult::Unordered}, 13582 }; 13583 13584 int I = Info->isPartial() ? 3 : 2; 13585 13586 // Combine the comparisons with suitable conditional expressions. 13587 ExprResult Result; 13588 for (; I >= 0; --I) { 13589 // Build a reference to the comparison category constant. 13590 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13591 // FIXME: Missing a constant for a comparison category. Diagnose this? 13592 if (!VI) 13593 return ExprResult((Expr*)nullptr); 13594 ExprResult ThisResult = 13595 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13596 if (ThisResult.isInvalid()) 13597 return ExprError(); 13598 13599 // Build a conditional unless this is the final case. 13600 if (Result.get()) { 13601 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13602 ThisResult.get(), Result.get()); 13603 if (Result.isInvalid()) 13604 return ExprError(); 13605 } else { 13606 Result = ThisResult; 13607 } 13608 } 13609 13610 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13611 // bind the OpaqueValueExprs before they're (repeatedly) used. 13612 Expr *SyntacticForm = new (Context) 13613 BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13614 Result.get()->getValueKind(), 13615 Result.get()->getObjectKind(), OpLoc, FPFeatures); 13616 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13617 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13618 } 13619 13620 ExprResult 13621 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13622 SourceLocation RLoc, 13623 Expr *Base, Expr *Idx) { 13624 Expr *Args[2] = { Base, Idx }; 13625 DeclarationName OpName = 13626 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13627 13628 // If either side is type-dependent, create an appropriate dependent 13629 // expression. 13630 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13631 13632 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13633 // CHECKME: no 'operator' keyword? 13634 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13635 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13636 UnresolvedLookupExpr *Fn 13637 = UnresolvedLookupExpr::Create(Context, NamingClass, 13638 NestedNameSpecifierLoc(), OpNameInfo, 13639 /*ADL*/ true, /*Overloaded*/ false, 13640 UnresolvedSetIterator(), 13641 UnresolvedSetIterator()); 13642 // Can't add any actual overloads yet 13643 13644 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 13645 Context.DependentTy, VK_RValue, RLoc, 13646 FPOptions()); 13647 } 13648 13649 // Handle placeholders on both operands. 13650 if (checkPlaceholderForOverload(*this, Args[0])) 13651 return ExprError(); 13652 if (checkPlaceholderForOverload(*this, Args[1])) 13653 return ExprError(); 13654 13655 // Build an empty overload set. 13656 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13657 13658 // Subscript can only be overloaded as a member function. 13659 13660 // Add operator candidates that are member functions. 13661 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13662 13663 // Add builtin operator candidates. 13664 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13665 13666 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13667 13668 // Perform overload resolution. 13669 OverloadCandidateSet::iterator Best; 13670 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13671 case OR_Success: { 13672 // We found a built-in operator or an overloaded operator. 13673 FunctionDecl *FnDecl = Best->Function; 13674 13675 if (FnDecl) { 13676 // We matched an overloaded operator. Build a call to that 13677 // operator. 13678 13679 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13680 13681 // Convert the arguments. 13682 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13683 ExprResult Arg0 = 13684 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13685 Best->FoundDecl, Method); 13686 if (Arg0.isInvalid()) 13687 return ExprError(); 13688 Args[0] = Arg0.get(); 13689 13690 // Convert the arguments. 13691 ExprResult InputInit 13692 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13693 Context, 13694 FnDecl->getParamDecl(0)), 13695 SourceLocation(), 13696 Args[1]); 13697 if (InputInit.isInvalid()) 13698 return ExprError(); 13699 13700 Args[1] = InputInit.getAs<Expr>(); 13701 13702 // Build the actual expression node. 13703 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13704 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13705 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13706 Best->FoundDecl, 13707 Base, 13708 HadMultipleCandidates, 13709 OpLocInfo.getLoc(), 13710 OpLocInfo.getInfo()); 13711 if (FnExpr.isInvalid()) 13712 return ExprError(); 13713 13714 // Determine the result type 13715 QualType ResultTy = FnDecl->getReturnType(); 13716 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13717 ResultTy = ResultTy.getNonLValueExprType(Context); 13718 13719 CXXOperatorCallExpr *TheCall = 13720 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 13721 Args, ResultTy, VK, RLoc, FPOptions()); 13722 13723 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 13724 return ExprError(); 13725 13726 if (CheckFunctionCall(Method, TheCall, 13727 Method->getType()->castAs<FunctionProtoType>())) 13728 return ExprError(); 13729 13730 return MaybeBindToTemporary(TheCall); 13731 } else { 13732 // We matched a built-in operator. Convert the arguments, then 13733 // break out so that we will build the appropriate built-in 13734 // operator node. 13735 ExprResult ArgsRes0 = PerformImplicitConversion( 13736 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13737 AA_Passing, CCK_ForBuiltinOverloadedOp); 13738 if (ArgsRes0.isInvalid()) 13739 return ExprError(); 13740 Args[0] = ArgsRes0.get(); 13741 13742 ExprResult ArgsRes1 = PerformImplicitConversion( 13743 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13744 AA_Passing, CCK_ForBuiltinOverloadedOp); 13745 if (ArgsRes1.isInvalid()) 13746 return ExprError(); 13747 Args[1] = ArgsRes1.get(); 13748 13749 break; 13750 } 13751 } 13752 13753 case OR_No_Viable_Function: { 13754 PartialDiagnostic PD = CandidateSet.empty() 13755 ? (PDiag(diag::err_ovl_no_oper) 13756 << Args[0]->getType() << /*subscript*/ 0 13757 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 13758 : (PDiag(diag::err_ovl_no_viable_subscript) 13759 << Args[0]->getType() << Args[0]->getSourceRange() 13760 << Args[1]->getSourceRange()); 13761 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 13762 OCD_AllCandidates, Args, "[]", LLoc); 13763 return ExprError(); 13764 } 13765 13766 case OR_Ambiguous: 13767 CandidateSet.NoteCandidates( 13768 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13769 << "[]" << Args[0]->getType() 13770 << Args[1]->getType() 13771 << Args[0]->getSourceRange() 13772 << Args[1]->getSourceRange()), 13773 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 13774 return ExprError(); 13775 13776 case OR_Deleted: 13777 CandidateSet.NoteCandidates( 13778 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 13779 << "[]" << Args[0]->getSourceRange() 13780 << Args[1]->getSourceRange()), 13781 *this, OCD_AllCandidates, Args, "[]", LLoc); 13782 return ExprError(); 13783 } 13784 13785 // We matched a built-in operator; build it. 13786 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 13787 } 13788 13789 /// BuildCallToMemberFunction - Build a call to a member 13790 /// function. MemExpr is the expression that refers to the member 13791 /// function (and includes the object parameter), Args/NumArgs are the 13792 /// arguments to the function call (not including the object 13793 /// parameter). The caller needs to validate that the member 13794 /// expression refers to a non-static member function or an overloaded 13795 /// member function. 13796 ExprResult 13797 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 13798 SourceLocation LParenLoc, 13799 MultiExprArg Args, 13800 SourceLocation RParenLoc) { 13801 assert(MemExprE->getType() == Context.BoundMemberTy || 13802 MemExprE->getType() == Context.OverloadTy); 13803 13804 // Dig out the member expression. This holds both the object 13805 // argument and the member function we're referring to. 13806 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 13807 13808 // Determine whether this is a call to a pointer-to-member function. 13809 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 13810 assert(op->getType() == Context.BoundMemberTy); 13811 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 13812 13813 QualType fnType = 13814 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 13815 13816 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 13817 QualType resultType = proto->getCallResultType(Context); 13818 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 13819 13820 // Check that the object type isn't more qualified than the 13821 // member function we're calling. 13822 Qualifiers funcQuals = proto->getMethodQuals(); 13823 13824 QualType objectType = op->getLHS()->getType(); 13825 if (op->getOpcode() == BO_PtrMemI) 13826 objectType = objectType->castAs<PointerType>()->getPointeeType(); 13827 Qualifiers objectQuals = objectType.getQualifiers(); 13828 13829 Qualifiers difference = objectQuals - funcQuals; 13830 difference.removeObjCGCAttr(); 13831 difference.removeAddressSpace(); 13832 if (difference) { 13833 std::string qualsString = difference.getAsString(); 13834 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 13835 << fnType.getUnqualifiedType() 13836 << qualsString 13837 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 13838 } 13839 13840 CXXMemberCallExpr *call = 13841 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 13842 valueKind, RParenLoc, proto->getNumParams()); 13843 13844 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 13845 call, nullptr)) 13846 return ExprError(); 13847 13848 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 13849 return ExprError(); 13850 13851 if (CheckOtherCall(call, proto)) 13852 return ExprError(); 13853 13854 return MaybeBindToTemporary(call); 13855 } 13856 13857 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 13858 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 13859 RParenLoc); 13860 13861 UnbridgedCastsSet UnbridgedCasts; 13862 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13863 return ExprError(); 13864 13865 MemberExpr *MemExpr; 13866 CXXMethodDecl *Method = nullptr; 13867 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 13868 NestedNameSpecifier *Qualifier = nullptr; 13869 if (isa<MemberExpr>(NakedMemExpr)) { 13870 MemExpr = cast<MemberExpr>(NakedMemExpr); 13871 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 13872 FoundDecl = MemExpr->getFoundDecl(); 13873 Qualifier = MemExpr->getQualifier(); 13874 UnbridgedCasts.restore(); 13875 } else { 13876 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 13877 Qualifier = UnresExpr->getQualifier(); 13878 13879 QualType ObjectType = UnresExpr->getBaseType(); 13880 Expr::Classification ObjectClassification 13881 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 13882 : UnresExpr->getBase()->Classify(Context); 13883 13884 // Add overload candidates 13885 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 13886 OverloadCandidateSet::CSK_Normal); 13887 13888 // FIXME: avoid copy. 13889 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13890 if (UnresExpr->hasExplicitTemplateArgs()) { 13891 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13892 TemplateArgs = &TemplateArgsBuffer; 13893 } 13894 13895 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 13896 E = UnresExpr->decls_end(); I != E; ++I) { 13897 13898 NamedDecl *Func = *I; 13899 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 13900 if (isa<UsingShadowDecl>(Func)) 13901 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 13902 13903 13904 // Microsoft supports direct constructor calls. 13905 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 13906 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 13907 CandidateSet, 13908 /*SuppressUserConversions*/ false); 13909 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 13910 // If explicit template arguments were provided, we can't call a 13911 // non-template member function. 13912 if (TemplateArgs) 13913 continue; 13914 13915 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 13916 ObjectClassification, Args, CandidateSet, 13917 /*SuppressUserConversions=*/false); 13918 } else { 13919 AddMethodTemplateCandidate( 13920 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 13921 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 13922 /*SuppressUserConversions=*/false); 13923 } 13924 } 13925 13926 DeclarationName DeclName = UnresExpr->getMemberName(); 13927 13928 UnbridgedCasts.restore(); 13929 13930 OverloadCandidateSet::iterator Best; 13931 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 13932 Best)) { 13933 case OR_Success: 13934 Method = cast<CXXMethodDecl>(Best->Function); 13935 FoundDecl = Best->FoundDecl; 13936 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13937 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13938 return ExprError(); 13939 // If FoundDecl is different from Method (such as if one is a template 13940 // and the other a specialization), make sure DiagnoseUseOfDecl is 13941 // called on both. 13942 // FIXME: This would be more comprehensively addressed by modifying 13943 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13944 // being used. 13945 if (Method != FoundDecl.getDecl() && 13946 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13947 return ExprError(); 13948 break; 13949 13950 case OR_No_Viable_Function: 13951 CandidateSet.NoteCandidates( 13952 PartialDiagnosticAt( 13953 UnresExpr->getMemberLoc(), 13954 PDiag(diag::err_ovl_no_viable_member_function_in_call) 13955 << DeclName << MemExprE->getSourceRange()), 13956 *this, OCD_AllCandidates, Args); 13957 // FIXME: Leaking incoming expressions! 13958 return ExprError(); 13959 13960 case OR_Ambiguous: 13961 CandidateSet.NoteCandidates( 13962 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13963 PDiag(diag::err_ovl_ambiguous_member_call) 13964 << DeclName << MemExprE->getSourceRange()), 13965 *this, OCD_AmbiguousCandidates, Args); 13966 // FIXME: Leaking incoming expressions! 13967 return ExprError(); 13968 13969 case OR_Deleted: 13970 CandidateSet.NoteCandidates( 13971 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13972 PDiag(diag::err_ovl_deleted_member_call) 13973 << DeclName << MemExprE->getSourceRange()), 13974 *this, OCD_AllCandidates, Args); 13975 // FIXME: Leaking incoming expressions! 13976 return ExprError(); 13977 } 13978 13979 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13980 13981 // If overload resolution picked a static member, build a 13982 // non-member call based on that function. 13983 if (Method->isStatic()) { 13984 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13985 RParenLoc); 13986 } 13987 13988 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13989 } 13990 13991 QualType ResultType = Method->getReturnType(); 13992 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13993 ResultType = ResultType.getNonLValueExprType(Context); 13994 13995 assert(Method && "Member call to something that isn't a method?"); 13996 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 13997 CXXMemberCallExpr *TheCall = 13998 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13999 RParenLoc, Proto->getNumParams()); 14000 14001 // Check for a valid return type. 14002 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14003 TheCall, Method)) 14004 return ExprError(); 14005 14006 // Convert the object argument (for a non-static member function call). 14007 // We only need to do this if there was actually an overload; otherwise 14008 // it was done at lookup. 14009 if (!Method->isStatic()) { 14010 ExprResult ObjectArg = 14011 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14012 FoundDecl, Method); 14013 if (ObjectArg.isInvalid()) 14014 return ExprError(); 14015 MemExpr->setBase(ObjectArg.get()); 14016 } 14017 14018 // Convert the rest of the arguments 14019 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14020 RParenLoc)) 14021 return ExprError(); 14022 14023 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14024 14025 if (CheckFunctionCall(Method, TheCall, Proto)) 14026 return ExprError(); 14027 14028 // In the case the method to call was not selected by the overloading 14029 // resolution process, we still need to handle the enable_if attribute. Do 14030 // that here, so it will not hide previous -- and more relevant -- errors. 14031 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14032 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 14033 Diag(MemE->getMemberLoc(), 14034 diag::err_ovl_no_viable_member_function_in_call) 14035 << Method << Method->getSourceRange(); 14036 Diag(Method->getLocation(), 14037 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14038 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14039 return ExprError(); 14040 } 14041 } 14042 14043 if ((isa<CXXConstructorDecl>(CurContext) || 14044 isa<CXXDestructorDecl>(CurContext)) && 14045 TheCall->getMethodDecl()->isPure()) { 14046 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14047 14048 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14049 MemExpr->performsVirtualDispatch(getLangOpts())) { 14050 Diag(MemExpr->getBeginLoc(), 14051 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14052 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14053 << MD->getParent()->getDeclName(); 14054 14055 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14056 if (getLangOpts().AppleKext) 14057 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14058 << MD->getParent()->getDeclName() << MD->getDeclName(); 14059 } 14060 } 14061 14062 if (CXXDestructorDecl *DD = 14063 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14064 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14065 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14066 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14067 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14068 MemExpr->getMemberLoc()); 14069 } 14070 14071 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14072 TheCall->getMethodDecl()); 14073 } 14074 14075 /// BuildCallToObjectOfClassType - Build a call to an object of class 14076 /// type (C++ [over.call.object]), which can end up invoking an 14077 /// overloaded function call operator (@c operator()) or performing a 14078 /// user-defined conversion on the object argument. 14079 ExprResult 14080 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14081 SourceLocation LParenLoc, 14082 MultiExprArg Args, 14083 SourceLocation RParenLoc) { 14084 if (checkPlaceholderForOverload(*this, Obj)) 14085 return ExprError(); 14086 ExprResult Object = Obj; 14087 14088 UnbridgedCastsSet UnbridgedCasts; 14089 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14090 return ExprError(); 14091 14092 assert(Object.get()->getType()->isRecordType() && 14093 "Requires object type argument"); 14094 14095 // C++ [over.call.object]p1: 14096 // If the primary-expression E in the function call syntax 14097 // evaluates to a class object of type "cv T", then the set of 14098 // candidate functions includes at least the function call 14099 // operators of T. The function call operators of T are obtained by 14100 // ordinary lookup of the name operator() in the context of 14101 // (E).operator(). 14102 OverloadCandidateSet CandidateSet(LParenLoc, 14103 OverloadCandidateSet::CSK_Operator); 14104 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14105 14106 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14107 diag::err_incomplete_object_call, Object.get())) 14108 return true; 14109 14110 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14111 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14112 LookupQualifiedName(R, Record->getDecl()); 14113 R.suppressDiagnostics(); 14114 14115 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14116 Oper != OperEnd; ++Oper) { 14117 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14118 Object.get()->Classify(Context), Args, CandidateSet, 14119 /*SuppressUserConversion=*/false); 14120 } 14121 14122 // C++ [over.call.object]p2: 14123 // In addition, for each (non-explicit in C++0x) conversion function 14124 // declared in T of the form 14125 // 14126 // operator conversion-type-id () cv-qualifier; 14127 // 14128 // where cv-qualifier is the same cv-qualification as, or a 14129 // greater cv-qualification than, cv, and where conversion-type-id 14130 // denotes the type "pointer to function of (P1,...,Pn) returning 14131 // R", or the type "reference to pointer to function of 14132 // (P1,...,Pn) returning R", or the type "reference to function 14133 // of (P1,...,Pn) returning R", a surrogate call function [...] 14134 // is also considered as a candidate function. Similarly, 14135 // surrogate call functions are added to the set of candidate 14136 // functions for each conversion function declared in an 14137 // accessible base class provided the function is not hidden 14138 // within T by another intervening declaration. 14139 const auto &Conversions = 14140 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14141 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14142 NamedDecl *D = *I; 14143 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14144 if (isa<UsingShadowDecl>(D)) 14145 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14146 14147 // Skip over templated conversion functions; they aren't 14148 // surrogates. 14149 if (isa<FunctionTemplateDecl>(D)) 14150 continue; 14151 14152 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14153 if (!Conv->isExplicit()) { 14154 // Strip the reference type (if any) and then the pointer type (if 14155 // any) to get down to what might be a function type. 14156 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14157 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14158 ConvType = ConvPtrType->getPointeeType(); 14159 14160 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14161 { 14162 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14163 Object.get(), Args, CandidateSet); 14164 } 14165 } 14166 } 14167 14168 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14169 14170 // Perform overload resolution. 14171 OverloadCandidateSet::iterator Best; 14172 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14173 Best)) { 14174 case OR_Success: 14175 // Overload resolution succeeded; we'll build the appropriate call 14176 // below. 14177 break; 14178 14179 case OR_No_Viable_Function: { 14180 PartialDiagnostic PD = 14181 CandidateSet.empty() 14182 ? (PDiag(diag::err_ovl_no_oper) 14183 << Object.get()->getType() << /*call*/ 1 14184 << Object.get()->getSourceRange()) 14185 : (PDiag(diag::err_ovl_no_viable_object_call) 14186 << Object.get()->getType() << Object.get()->getSourceRange()); 14187 CandidateSet.NoteCandidates( 14188 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14189 OCD_AllCandidates, Args); 14190 break; 14191 } 14192 case OR_Ambiguous: 14193 CandidateSet.NoteCandidates( 14194 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14195 PDiag(diag::err_ovl_ambiguous_object_call) 14196 << Object.get()->getType() 14197 << Object.get()->getSourceRange()), 14198 *this, OCD_AmbiguousCandidates, Args); 14199 break; 14200 14201 case OR_Deleted: 14202 CandidateSet.NoteCandidates( 14203 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14204 PDiag(diag::err_ovl_deleted_object_call) 14205 << Object.get()->getType() 14206 << Object.get()->getSourceRange()), 14207 *this, OCD_AllCandidates, Args); 14208 break; 14209 } 14210 14211 if (Best == CandidateSet.end()) 14212 return true; 14213 14214 UnbridgedCasts.restore(); 14215 14216 if (Best->Function == nullptr) { 14217 // Since there is no function declaration, this is one of the 14218 // surrogate candidates. Dig out the conversion function. 14219 CXXConversionDecl *Conv 14220 = cast<CXXConversionDecl>( 14221 Best->Conversions[0].UserDefined.ConversionFunction); 14222 14223 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14224 Best->FoundDecl); 14225 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14226 return ExprError(); 14227 assert(Conv == Best->FoundDecl.getDecl() && 14228 "Found Decl & conversion-to-functionptr should be same, right?!"); 14229 // We selected one of the surrogate functions that converts the 14230 // object parameter to a function pointer. Perform the conversion 14231 // on the object argument, then let BuildCallExpr finish the job. 14232 14233 // Create an implicit member expr to refer to the conversion operator. 14234 // and then call it. 14235 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14236 Conv, HadMultipleCandidates); 14237 if (Call.isInvalid()) 14238 return ExprError(); 14239 // Record usage of conversion in an implicit cast. 14240 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 14241 CK_UserDefinedConversion, Call.get(), 14242 nullptr, VK_RValue); 14243 14244 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14245 } 14246 14247 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14248 14249 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14250 // that calls this method, using Object for the implicit object 14251 // parameter and passing along the remaining arguments. 14252 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14253 14254 // An error diagnostic has already been printed when parsing the declaration. 14255 if (Method->isInvalidDecl()) 14256 return ExprError(); 14257 14258 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14259 unsigned NumParams = Proto->getNumParams(); 14260 14261 DeclarationNameInfo OpLocInfo( 14262 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14263 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14264 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14265 Obj, HadMultipleCandidates, 14266 OpLocInfo.getLoc(), 14267 OpLocInfo.getInfo()); 14268 if (NewFn.isInvalid()) 14269 return true; 14270 14271 // The number of argument slots to allocate in the call. If we have default 14272 // arguments we need to allocate space for them as well. We additionally 14273 // need one more slot for the object parameter. 14274 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14275 14276 // Build the full argument list for the method call (the implicit object 14277 // parameter is placed at the beginning of the list). 14278 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14279 14280 bool IsError = false; 14281 14282 // Initialize the implicit object parameter. 14283 ExprResult ObjRes = 14284 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14285 Best->FoundDecl, Method); 14286 if (ObjRes.isInvalid()) 14287 IsError = true; 14288 else 14289 Object = ObjRes; 14290 MethodArgs[0] = Object.get(); 14291 14292 // Check the argument types. 14293 for (unsigned i = 0; i != NumParams; i++) { 14294 Expr *Arg; 14295 if (i < Args.size()) { 14296 Arg = Args[i]; 14297 14298 // Pass the argument. 14299 14300 ExprResult InputInit 14301 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14302 Context, 14303 Method->getParamDecl(i)), 14304 SourceLocation(), Arg); 14305 14306 IsError |= InputInit.isInvalid(); 14307 Arg = InputInit.getAs<Expr>(); 14308 } else { 14309 ExprResult DefArg 14310 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14311 if (DefArg.isInvalid()) { 14312 IsError = true; 14313 break; 14314 } 14315 14316 Arg = DefArg.getAs<Expr>(); 14317 } 14318 14319 MethodArgs[i + 1] = Arg; 14320 } 14321 14322 // If this is a variadic call, handle args passed through "...". 14323 if (Proto->isVariadic()) { 14324 // Promote the arguments (C99 6.5.2.2p7). 14325 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14326 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14327 nullptr); 14328 IsError |= Arg.isInvalid(); 14329 MethodArgs[i + 1] = Arg.get(); 14330 } 14331 } 14332 14333 if (IsError) 14334 return true; 14335 14336 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14337 14338 // Once we've built TheCall, all of the expressions are properly owned. 14339 QualType ResultTy = Method->getReturnType(); 14340 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14341 ResultTy = ResultTy.getNonLValueExprType(Context); 14342 14343 CXXOperatorCallExpr *TheCall = 14344 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 14345 ResultTy, VK, RParenLoc, FPOptions()); 14346 14347 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14348 return true; 14349 14350 if (CheckFunctionCall(Method, TheCall, Proto)) 14351 return true; 14352 14353 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14354 } 14355 14356 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14357 /// (if one exists), where @c Base is an expression of class type and 14358 /// @c Member is the name of the member we're trying to find. 14359 ExprResult 14360 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14361 bool *NoArrowOperatorFound) { 14362 assert(Base->getType()->isRecordType() && 14363 "left-hand side must have class type"); 14364 14365 if (checkPlaceholderForOverload(*this, Base)) 14366 return ExprError(); 14367 14368 SourceLocation Loc = Base->getExprLoc(); 14369 14370 // C++ [over.ref]p1: 14371 // 14372 // [...] An expression x->m is interpreted as (x.operator->())->m 14373 // for a class object x of type T if T::operator->() exists and if 14374 // the operator is selected as the best match function by the 14375 // overload resolution mechanism (13.3). 14376 DeclarationName OpName = 14377 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14378 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14379 14380 if (RequireCompleteType(Loc, Base->getType(), 14381 diag::err_typecheck_incomplete_tag, Base)) 14382 return ExprError(); 14383 14384 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14385 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14386 R.suppressDiagnostics(); 14387 14388 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14389 Oper != OperEnd; ++Oper) { 14390 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14391 None, CandidateSet, /*SuppressUserConversion=*/false); 14392 } 14393 14394 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14395 14396 // Perform overload resolution. 14397 OverloadCandidateSet::iterator Best; 14398 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14399 case OR_Success: 14400 // Overload resolution succeeded; we'll build the call below. 14401 break; 14402 14403 case OR_No_Viable_Function: { 14404 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14405 if (CandidateSet.empty()) { 14406 QualType BaseType = Base->getType(); 14407 if (NoArrowOperatorFound) { 14408 // Report this specific error to the caller instead of emitting a 14409 // diagnostic, as requested. 14410 *NoArrowOperatorFound = true; 14411 return ExprError(); 14412 } 14413 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14414 << BaseType << Base->getSourceRange(); 14415 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14416 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14417 << FixItHint::CreateReplacement(OpLoc, "."); 14418 } 14419 } else 14420 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14421 << "operator->" << Base->getSourceRange(); 14422 CandidateSet.NoteCandidates(*this, Base, Cands); 14423 return ExprError(); 14424 } 14425 case OR_Ambiguous: 14426 CandidateSet.NoteCandidates( 14427 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14428 << "->" << Base->getType() 14429 << Base->getSourceRange()), 14430 *this, OCD_AmbiguousCandidates, Base); 14431 return ExprError(); 14432 14433 case OR_Deleted: 14434 CandidateSet.NoteCandidates( 14435 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14436 << "->" << Base->getSourceRange()), 14437 *this, OCD_AllCandidates, Base); 14438 return ExprError(); 14439 } 14440 14441 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14442 14443 // Convert the object parameter. 14444 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14445 ExprResult BaseResult = 14446 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14447 Best->FoundDecl, Method); 14448 if (BaseResult.isInvalid()) 14449 return ExprError(); 14450 Base = BaseResult.get(); 14451 14452 // Build the operator call. 14453 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14454 Base, HadMultipleCandidates, OpLoc); 14455 if (FnExpr.isInvalid()) 14456 return ExprError(); 14457 14458 QualType ResultTy = Method->getReturnType(); 14459 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14460 ResultTy = ResultTy.getNonLValueExprType(Context); 14461 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14462 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 14463 14464 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14465 return ExprError(); 14466 14467 if (CheckFunctionCall(Method, TheCall, 14468 Method->getType()->castAs<FunctionProtoType>())) 14469 return ExprError(); 14470 14471 return MaybeBindToTemporary(TheCall); 14472 } 14473 14474 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14475 /// a literal operator described by the provided lookup results. 14476 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14477 DeclarationNameInfo &SuffixInfo, 14478 ArrayRef<Expr*> Args, 14479 SourceLocation LitEndLoc, 14480 TemplateArgumentListInfo *TemplateArgs) { 14481 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14482 14483 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14484 OverloadCandidateSet::CSK_Normal); 14485 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14486 TemplateArgs); 14487 14488 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14489 14490 // Perform overload resolution. This will usually be trivial, but might need 14491 // to perform substitutions for a literal operator template. 14492 OverloadCandidateSet::iterator Best; 14493 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14494 case OR_Success: 14495 case OR_Deleted: 14496 break; 14497 14498 case OR_No_Viable_Function: 14499 CandidateSet.NoteCandidates( 14500 PartialDiagnosticAt(UDSuffixLoc, 14501 PDiag(diag::err_ovl_no_viable_function_in_call) 14502 << R.getLookupName()), 14503 *this, OCD_AllCandidates, Args); 14504 return ExprError(); 14505 14506 case OR_Ambiguous: 14507 CandidateSet.NoteCandidates( 14508 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14509 << R.getLookupName()), 14510 *this, OCD_AmbiguousCandidates, Args); 14511 return ExprError(); 14512 } 14513 14514 FunctionDecl *FD = Best->Function; 14515 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14516 nullptr, HadMultipleCandidates, 14517 SuffixInfo.getLoc(), 14518 SuffixInfo.getInfo()); 14519 if (Fn.isInvalid()) 14520 return true; 14521 14522 // Check the argument types. This should almost always be a no-op, except 14523 // that array-to-pointer decay is applied to string literals. 14524 Expr *ConvArgs[2]; 14525 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14526 ExprResult InputInit = PerformCopyInitialization( 14527 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14528 SourceLocation(), Args[ArgIdx]); 14529 if (InputInit.isInvalid()) 14530 return true; 14531 ConvArgs[ArgIdx] = InputInit.get(); 14532 } 14533 14534 QualType ResultTy = FD->getReturnType(); 14535 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14536 ResultTy = ResultTy.getNonLValueExprType(Context); 14537 14538 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14539 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14540 VK, LitEndLoc, UDSuffixLoc); 14541 14542 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14543 return ExprError(); 14544 14545 if (CheckFunctionCall(FD, UDL, nullptr)) 14546 return ExprError(); 14547 14548 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 14549 } 14550 14551 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14552 /// given LookupResult is non-empty, it is assumed to describe a member which 14553 /// will be invoked. Otherwise, the function will be found via argument 14554 /// dependent lookup. 14555 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14556 /// otherwise CallExpr is set to ExprError() and some non-success value 14557 /// is returned. 14558 Sema::ForRangeStatus 14559 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14560 SourceLocation RangeLoc, 14561 const DeclarationNameInfo &NameInfo, 14562 LookupResult &MemberLookup, 14563 OverloadCandidateSet *CandidateSet, 14564 Expr *Range, ExprResult *CallExpr) { 14565 Scope *S = nullptr; 14566 14567 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14568 if (!MemberLookup.empty()) { 14569 ExprResult MemberRef = 14570 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14571 /*IsPtr=*/false, CXXScopeSpec(), 14572 /*TemplateKWLoc=*/SourceLocation(), 14573 /*FirstQualifierInScope=*/nullptr, 14574 MemberLookup, 14575 /*TemplateArgs=*/nullptr, S); 14576 if (MemberRef.isInvalid()) { 14577 *CallExpr = ExprError(); 14578 return FRS_DiagnosticIssued; 14579 } 14580 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14581 if (CallExpr->isInvalid()) { 14582 *CallExpr = ExprError(); 14583 return FRS_DiagnosticIssued; 14584 } 14585 } else { 14586 UnresolvedSet<0> FoundNames; 14587 UnresolvedLookupExpr *Fn = 14588 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 14589 NestedNameSpecifierLoc(), NameInfo, 14590 /*NeedsADL=*/true, /*Overloaded=*/false, 14591 FoundNames.begin(), FoundNames.end()); 14592 14593 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14594 CandidateSet, CallExpr); 14595 if (CandidateSet->empty() || CandidateSetError) { 14596 *CallExpr = ExprError(); 14597 return FRS_NoViableFunction; 14598 } 14599 OverloadCandidateSet::iterator Best; 14600 OverloadingResult OverloadResult = 14601 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14602 14603 if (OverloadResult == OR_No_Viable_Function) { 14604 *CallExpr = ExprError(); 14605 return FRS_NoViableFunction; 14606 } 14607 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14608 Loc, nullptr, CandidateSet, &Best, 14609 OverloadResult, 14610 /*AllowTypoCorrection=*/false); 14611 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14612 *CallExpr = ExprError(); 14613 return FRS_DiagnosticIssued; 14614 } 14615 } 14616 return FRS_Success; 14617 } 14618 14619 14620 /// FixOverloadedFunctionReference - E is an expression that refers to 14621 /// a C++ overloaded function (possibly with some parentheses and 14622 /// perhaps a '&' around it). We have resolved the overloaded function 14623 /// to the function declaration Fn, so patch up the expression E to 14624 /// refer (possibly indirectly) to Fn. Returns the new expr. 14625 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14626 FunctionDecl *Fn) { 14627 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14628 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14629 Found, Fn); 14630 if (SubExpr == PE->getSubExpr()) 14631 return PE; 14632 14633 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14634 } 14635 14636 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14637 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14638 Found, Fn); 14639 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 14640 SubExpr->getType()) && 14641 "Implicit cast type cannot be determined from overload"); 14642 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 14643 if (SubExpr == ICE->getSubExpr()) 14644 return ICE; 14645 14646 return ImplicitCastExpr::Create(Context, ICE->getType(), 14647 ICE->getCastKind(), 14648 SubExpr, nullptr, 14649 ICE->getValueKind()); 14650 } 14651 14652 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14653 if (!GSE->isResultDependent()) { 14654 Expr *SubExpr = 14655 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14656 if (SubExpr == GSE->getResultExpr()) 14657 return GSE; 14658 14659 // Replace the resulting type information before rebuilding the generic 14660 // selection expression. 14661 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14662 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14663 unsigned ResultIdx = GSE->getResultIndex(); 14664 AssocExprs[ResultIdx] = SubExpr; 14665 14666 return GenericSelectionExpr::Create( 14667 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14668 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14669 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14670 ResultIdx); 14671 } 14672 // Rather than fall through to the unreachable, return the original generic 14673 // selection expression. 14674 return GSE; 14675 } 14676 14677 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14678 assert(UnOp->getOpcode() == UO_AddrOf && 14679 "Can only take the address of an overloaded function"); 14680 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14681 if (Method->isStatic()) { 14682 // Do nothing: static member functions aren't any different 14683 // from non-member functions. 14684 } else { 14685 // Fix the subexpression, which really has to be an 14686 // UnresolvedLookupExpr holding an overloaded member function 14687 // or template. 14688 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14689 Found, Fn); 14690 if (SubExpr == UnOp->getSubExpr()) 14691 return UnOp; 14692 14693 assert(isa<DeclRefExpr>(SubExpr) 14694 && "fixed to something other than a decl ref"); 14695 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 14696 && "fixed to a member ref with no nested name qualifier"); 14697 14698 // We have taken the address of a pointer to member 14699 // function. Perform the computation here so that we get the 14700 // appropriate pointer to member type. 14701 QualType ClassType 14702 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14703 QualType MemPtrType 14704 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 14705 // Under the MS ABI, lock down the inheritance model now. 14706 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14707 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 14708 14709 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 14710 VK_RValue, OK_Ordinary, 14711 UnOp->getOperatorLoc(), false); 14712 } 14713 } 14714 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14715 Found, Fn); 14716 if (SubExpr == UnOp->getSubExpr()) 14717 return UnOp; 14718 14719 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 14720 Context.getPointerType(SubExpr->getType()), 14721 VK_RValue, OK_Ordinary, 14722 UnOp->getOperatorLoc(), false); 14723 } 14724 14725 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14726 // FIXME: avoid copy. 14727 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14728 if (ULE->hasExplicitTemplateArgs()) { 14729 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 14730 TemplateArgs = &TemplateArgsBuffer; 14731 } 14732 14733 DeclRefExpr *DRE = 14734 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 14735 ULE->getQualifierLoc(), Found.getDecl(), 14736 ULE->getTemplateKeywordLoc(), TemplateArgs); 14737 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 14738 return DRE; 14739 } 14740 14741 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 14742 // FIXME: avoid copy. 14743 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14744 if (MemExpr->hasExplicitTemplateArgs()) { 14745 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14746 TemplateArgs = &TemplateArgsBuffer; 14747 } 14748 14749 Expr *Base; 14750 14751 // If we're filling in a static method where we used to have an 14752 // implicit member access, rewrite to a simple decl ref. 14753 if (MemExpr->isImplicitAccess()) { 14754 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14755 DeclRefExpr *DRE = BuildDeclRefExpr( 14756 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 14757 MemExpr->getQualifierLoc(), Found.getDecl(), 14758 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 14759 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 14760 return DRE; 14761 } else { 14762 SourceLocation Loc = MemExpr->getMemberLoc(); 14763 if (MemExpr->getQualifier()) 14764 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 14765 Base = 14766 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 14767 } 14768 } else 14769 Base = MemExpr->getBase(); 14770 14771 ExprValueKind valueKind; 14772 QualType type; 14773 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14774 valueKind = VK_LValue; 14775 type = Fn->getType(); 14776 } else { 14777 valueKind = VK_RValue; 14778 type = Context.BoundMemberTy; 14779 } 14780 14781 return BuildMemberExpr( 14782 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 14783 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 14784 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 14785 type, valueKind, OK_Ordinary, TemplateArgs); 14786 } 14787 14788 llvm_unreachable("Invalid reference to overloaded function"); 14789 } 14790 14791 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 14792 DeclAccessPair Found, 14793 FunctionDecl *Fn) { 14794 return FixOverloadedFunctionReference(E.get(), Found, Fn); 14795 } 14796