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 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 42 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 43 return P->hasAttr<PassObjectSizeAttr>(); 44 }); 45 } 46 47 /// A convenience routine for creating a decayed reference to a function. 48 static ExprResult 49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 50 const Expr *Base, bool HadMultipleCandidates, 51 SourceLocation Loc = SourceLocation(), 52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 54 return ExprError(); 55 // If FoundDecl is different from Fn (such as if one is a template 56 // and the other a specialization), make sure DiagnoseUseOfDecl is 57 // called on both. 58 // FIXME: This would be more comprehensively addressed by modifying 59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 60 // being used. 61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 62 return ExprError(); 63 DeclRefExpr *DRE = new (S.Context) 64 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 65 if (HadMultipleCandidates) 66 DRE->setHadMultipleCandidates(true); 67 68 S.MarkDeclRefReferenced(DRE, Base); 69 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 70 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 71 S.ResolveExceptionSpec(Loc, FPT); 72 DRE->setType(Fn->getType()); 73 } 74 } 75 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 76 CK_FunctionToPointerDecay); 77 } 78 79 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 80 bool InOverloadResolution, 81 StandardConversionSequence &SCS, 82 bool CStyle, 83 bool AllowObjCWritebackConversion); 84 85 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 86 QualType &ToType, 87 bool InOverloadResolution, 88 StandardConversionSequence &SCS, 89 bool CStyle); 90 static OverloadingResult 91 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 92 UserDefinedConversionSequence& User, 93 OverloadCandidateSet& Conversions, 94 bool AllowExplicit, 95 bool AllowObjCConversionOnExplicit); 96 97 98 static ImplicitConversionSequence::CompareKind 99 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 100 const StandardConversionSequence& SCS1, 101 const StandardConversionSequence& SCS2); 102 103 static ImplicitConversionSequence::CompareKind 104 CompareQualificationConversions(Sema &S, 105 const StandardConversionSequence& SCS1, 106 const StandardConversionSequence& SCS2); 107 108 static ImplicitConversionSequence::CompareKind 109 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 110 const StandardConversionSequence& SCS1, 111 const StandardConversionSequence& SCS2); 112 113 /// GetConversionRank - Retrieve the implicit conversion rank 114 /// corresponding to the given implicit conversion kind. 115 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 116 static const ImplicitConversionRank 117 Rank[(int)ICK_Num_Conversion_Kinds] = { 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Exact_Match, 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Promotion, 125 ICR_Promotion, 126 ICR_Promotion, 127 ICR_Conversion, 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_OCL_Scalar_Widening, 138 ICR_Complex_Real_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_Writeback_Conversion, 142 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 143 // it was omitted by the patch that added 144 // ICK_Zero_Event_Conversion 145 ICR_C_Conversion, 146 ICR_C_Conversion_Extension 147 }; 148 return Rank[(int)Kind]; 149 } 150 151 /// GetImplicitConversionName - Return the name of this kind of 152 /// implicit conversion. 153 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 154 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 155 "No conversion", 156 "Lvalue-to-rvalue", 157 "Array-to-pointer", 158 "Function-to-pointer", 159 "Function pointer conversion", 160 "Qualification", 161 "Integral promotion", 162 "Floating point promotion", 163 "Complex promotion", 164 "Integral conversion", 165 "Floating conversion", 166 "Complex conversion", 167 "Floating-integral conversion", 168 "Pointer conversion", 169 "Pointer-to-member conversion", 170 "Boolean conversion", 171 "Compatible-types conversion", 172 "Derived-to-base conversion", 173 "Vector conversion", 174 "Vector splat", 175 "Complex-real conversion", 176 "Block Pointer conversion", 177 "Transparent Union Conversion", 178 "Writeback conversion", 179 "OpenCL Zero Event Conversion", 180 "C specific type conversion", 181 "Incompatible pointer conversion" 182 }; 183 return Name[Kind]; 184 } 185 186 /// StandardConversionSequence - Set the standard conversion 187 /// sequence to the identity conversion. 188 void StandardConversionSequence::setAsIdentityConversion() { 189 First = ICK_Identity; 190 Second = ICK_Identity; 191 Third = ICK_Identity; 192 DeprecatedStringLiteralToCharPtr = false; 193 QualificationIncludesObjCLifetime = false; 194 ReferenceBinding = false; 195 DirectBinding = false; 196 IsLvalueReference = true; 197 BindsToFunctionLvalue = false; 198 BindsToRvalue = false; 199 BindsImplicitObjectArgumentWithoutRefQualifier = false; 200 ObjCLifetimeConversionBinding = false; 201 CopyConstructor = nullptr; 202 } 203 204 /// getRank - Retrieve the rank of this standard conversion sequence 205 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 206 /// implicit conversions. 207 ImplicitConversionRank StandardConversionSequence::getRank() const { 208 ImplicitConversionRank Rank = ICR_Exact_Match; 209 if (GetConversionRank(First) > Rank) 210 Rank = GetConversionRank(First); 211 if (GetConversionRank(Second) > Rank) 212 Rank = GetConversionRank(Second); 213 if (GetConversionRank(Third) > Rank) 214 Rank = GetConversionRank(Third); 215 return Rank; 216 } 217 218 /// isPointerConversionToBool - Determines whether this conversion is 219 /// a conversion of a pointer or pointer-to-member to bool. This is 220 /// used as part of the ranking of standard conversion sequences 221 /// (C++ 13.3.3.2p4). 222 bool StandardConversionSequence::isPointerConversionToBool() const { 223 // Note that FromType has not necessarily been transformed by the 224 // array-to-pointer or function-to-pointer implicit conversions, so 225 // check for their presence as well as checking whether FromType is 226 // a pointer. 227 if (getToType(1)->isBooleanType() && 228 (getFromType()->isPointerType() || 229 getFromType()->isMemberPointerType() || 230 getFromType()->isObjCObjectPointerType() || 231 getFromType()->isBlockPointerType() || 232 getFromType()->isNullPtrType() || 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 // Boolean conversions can be from pointers and pointers to members 331 // [conv.bool], and those aren't considered narrowing conversions. 332 return NK_Not_Narrowing; 333 334 // -- from a floating-point type to an integer type, or 335 // 336 // -- from an integer type or unscoped enumeration type to a floating-point 337 // type, except where the source is a constant expression and the actual 338 // value after conversion will fit into the target type and will produce 339 // the original value when converted back to the original type, or 340 case ICK_Floating_Integral: 341 FloatingIntegralConversion: 342 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 343 return NK_Type_Narrowing; 344 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 345 ToType->isRealFloatingType()) { 346 if (IgnoreFloatToIntegralConversion) 347 return NK_Not_Narrowing; 348 llvm::APSInt IntConstantValue; 349 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 350 assert(Initializer && "Unknown conversion expression"); 351 352 // If it's value-dependent, we can't tell whether it's narrowing. 353 if (Initializer->isValueDependent()) 354 return NK_Dependent_Narrowing; 355 356 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 357 // Convert the integer to the floating type. 358 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 359 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 360 llvm::APFloat::rmNearestTiesToEven); 361 // And back. 362 llvm::APSInt ConvertedValue = IntConstantValue; 363 bool ignored; 364 Result.convertToInteger(ConvertedValue, 365 llvm::APFloat::rmTowardZero, &ignored); 366 // If the resulting value is different, this was a narrowing conversion. 367 if (IntConstantValue != ConvertedValue) { 368 ConstantValue = APValue(IntConstantValue); 369 ConstantType = Initializer->getType(); 370 return NK_Constant_Narrowing; 371 } 372 } else { 373 // Variables are always narrowings. 374 return NK_Variable_Narrowing; 375 } 376 } 377 return NK_Not_Narrowing; 378 379 // -- from long double to double or float, or from double to float, except 380 // where the source is a constant expression and the actual value after 381 // conversion is within the range of values that can be represented (even 382 // if it cannot be represented exactly), or 383 case ICK_Floating_Conversion: 384 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 385 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 386 // FromType is larger than ToType. 387 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 388 389 // If it's value-dependent, we can't tell whether it's narrowing. 390 if (Initializer->isValueDependent()) 391 return NK_Dependent_Narrowing; 392 393 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 394 // Constant! 395 assert(ConstantValue.isFloat()); 396 llvm::APFloat FloatVal = ConstantValue.getFloat(); 397 // Convert the source value into the target type. 398 bool ignored; 399 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 400 Ctx.getFloatTypeSemantics(ToType), 401 llvm::APFloat::rmNearestTiesToEven, &ignored); 402 // If there was no overflow, the source value is within the range of 403 // values that can be represented. 404 if (ConvertStatus & llvm::APFloat::opOverflow) { 405 ConstantType = Initializer->getType(); 406 return NK_Constant_Narrowing; 407 } 408 } else { 409 return NK_Variable_Narrowing; 410 } 411 } 412 return NK_Not_Narrowing; 413 414 // -- from an integer type or unscoped enumeration type to an integer type 415 // that cannot represent all the values of the original type, except where 416 // the source is a constant expression and the actual value after 417 // conversion will fit into the target type and will produce the original 418 // value when converted back to the original type. 419 case ICK_Integral_Conversion: 420 IntegralConversion: { 421 assert(FromType->isIntegralOrUnscopedEnumerationType()); 422 assert(ToType->isIntegralOrUnscopedEnumerationType()); 423 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 424 const unsigned FromWidth = Ctx.getIntWidth(FromType); 425 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 426 const unsigned ToWidth = Ctx.getIntWidth(ToType); 427 428 if (FromWidth > ToWidth || 429 (FromWidth == ToWidth && FromSigned != ToSigned) || 430 (FromSigned && !ToSigned)) { 431 // Not all values of FromType can be represented in ToType. 432 llvm::APSInt InitializerValue; 433 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 434 435 // If it's value-dependent, we can't tell whether it's narrowing. 436 if (Initializer->isValueDependent()) 437 return NK_Dependent_Narrowing; 438 439 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 440 // Such conversions on variables are always narrowing. 441 return NK_Variable_Narrowing; 442 } 443 bool Narrowing = false; 444 if (FromWidth < ToWidth) { 445 // Negative -> unsigned is narrowing. Otherwise, more bits is never 446 // narrowing. 447 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 448 Narrowing = true; 449 } else { 450 // Add a bit to the InitializerValue so we don't have to worry about 451 // signed vs. unsigned comparisons. 452 InitializerValue = InitializerValue.extend( 453 InitializerValue.getBitWidth() + 1); 454 // Convert the initializer to and from the target width and signed-ness. 455 llvm::APSInt ConvertedValue = InitializerValue; 456 ConvertedValue = ConvertedValue.trunc(ToWidth); 457 ConvertedValue.setIsSigned(ToSigned); 458 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 459 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 460 // If the result is different, this was a narrowing conversion. 461 if (ConvertedValue != InitializerValue) 462 Narrowing = true; 463 } 464 if (Narrowing) { 465 ConstantType = Initializer->getType(); 466 ConstantValue = APValue(InitializerValue); 467 return NK_Constant_Narrowing; 468 } 469 } 470 return NK_Not_Narrowing; 471 } 472 473 default: 474 // Other kinds of conversions are not narrowings. 475 return NK_Not_Narrowing; 476 } 477 } 478 479 /// dump - Print this standard conversion sequence to standard 480 /// error. Useful for debugging overloading issues. 481 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 482 raw_ostream &OS = llvm::errs(); 483 bool PrintedSomething = false; 484 if (First != ICK_Identity) { 485 OS << GetImplicitConversionName(First); 486 PrintedSomething = true; 487 } 488 489 if (Second != ICK_Identity) { 490 if (PrintedSomething) { 491 OS << " -> "; 492 } 493 OS << GetImplicitConversionName(Second); 494 495 if (CopyConstructor) { 496 OS << " (by copy constructor)"; 497 } else if (DirectBinding) { 498 OS << " (direct reference binding)"; 499 } else if (ReferenceBinding) { 500 OS << " (reference binding)"; 501 } 502 PrintedSomething = true; 503 } 504 505 if (Third != ICK_Identity) { 506 if (PrintedSomething) { 507 OS << " -> "; 508 } 509 OS << GetImplicitConversionName(Third); 510 PrintedSomething = true; 511 } 512 513 if (!PrintedSomething) { 514 OS << "No conversions required"; 515 } 516 } 517 518 /// dump - Print this user-defined conversion sequence to standard 519 /// error. Useful for debugging overloading issues. 520 void UserDefinedConversionSequence::dump() const { 521 raw_ostream &OS = llvm::errs(); 522 if (Before.First || Before.Second || Before.Third) { 523 Before.dump(); 524 OS << " -> "; 525 } 526 if (ConversionFunction) 527 OS << '\'' << *ConversionFunction << '\''; 528 else 529 OS << "aggregate initialization"; 530 if (After.First || After.Second || After.Third) { 531 OS << " -> "; 532 After.dump(); 533 } 534 } 535 536 /// dump - Print this implicit conversion sequence to standard 537 /// error. Useful for debugging overloading issues. 538 void ImplicitConversionSequence::dump() const { 539 raw_ostream &OS = llvm::errs(); 540 if (isStdInitializerListElement()) 541 OS << "Worst std::initializer_list element conversion: "; 542 switch (ConversionKind) { 543 case StandardConversion: 544 OS << "Standard conversion: "; 545 Standard.dump(); 546 break; 547 case UserDefinedConversion: 548 OS << "User-defined conversion: "; 549 UserDefined.dump(); 550 break; 551 case EllipsisConversion: 552 OS << "Ellipsis conversion"; 553 break; 554 case AmbiguousConversion: 555 OS << "Ambiguous conversion"; 556 break; 557 case BadConversion: 558 OS << "Bad conversion"; 559 break; 560 } 561 562 OS << "\n"; 563 } 564 565 void AmbiguousConversionSequence::construct() { 566 new (&conversions()) ConversionSet(); 567 } 568 569 void AmbiguousConversionSequence::destruct() { 570 conversions().~ConversionSet(); 571 } 572 573 void 574 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 575 FromTypePtr = O.FromTypePtr; 576 ToTypePtr = O.ToTypePtr; 577 new (&conversions()) ConversionSet(O.conversions()); 578 } 579 580 namespace { 581 // Structure used by DeductionFailureInfo to store 582 // template argument information. 583 struct DFIArguments { 584 TemplateArgument FirstArg; 585 TemplateArgument SecondArg; 586 }; 587 // Structure used by DeductionFailureInfo to store 588 // template parameter and template argument information. 589 struct DFIParamWithArguments : DFIArguments { 590 TemplateParameter Param; 591 }; 592 // Structure used by DeductionFailureInfo to store template argument 593 // information and the index of the problematic call argument. 594 struct DFIDeducedMismatchArgs : DFIArguments { 595 TemplateArgumentList *TemplateArgs; 596 unsigned CallArgIndex; 597 }; 598 // Structure used by DeductionFailureInfo to store information about 599 // unsatisfied constraints. 600 struct CNSInfo { 601 TemplateArgumentList *TemplateArgs; 602 ConstraintSatisfaction Satisfaction; 603 }; 604 } 605 606 /// Convert from Sema's representation of template deduction information 607 /// to the form used in overload-candidate information. 608 DeductionFailureInfo 609 clang::MakeDeductionFailureInfo(ASTContext &Context, 610 Sema::TemplateDeductionResult TDK, 611 TemplateDeductionInfo &Info) { 612 DeductionFailureInfo Result; 613 Result.Result = static_cast<unsigned>(TDK); 614 Result.HasDiagnostic = false; 615 switch (TDK) { 616 case Sema::TDK_Invalid: 617 case Sema::TDK_InstantiationDepth: 618 case Sema::TDK_TooManyArguments: 619 case Sema::TDK_TooFewArguments: 620 case Sema::TDK_MiscellaneousDeductionFailure: 621 case Sema::TDK_CUDATargetMismatch: 622 Result.Data = nullptr; 623 break; 624 625 case Sema::TDK_Incomplete: 626 case Sema::TDK_InvalidExplicitArguments: 627 Result.Data = Info.Param.getOpaqueValue(); 628 break; 629 630 case Sema::TDK_DeducedMismatch: 631 case Sema::TDK_DeducedMismatchNested: { 632 // FIXME: Should allocate from normal heap so that we can free this later. 633 auto *Saved = new (Context) DFIDeducedMismatchArgs; 634 Saved->FirstArg = Info.FirstArg; 635 Saved->SecondArg = Info.SecondArg; 636 Saved->TemplateArgs = Info.take(); 637 Saved->CallArgIndex = Info.CallArgIndex; 638 Result.Data = Saved; 639 break; 640 } 641 642 case Sema::TDK_NonDeducedMismatch: { 643 // FIXME: Should allocate from normal heap so that we can free this later. 644 DFIArguments *Saved = new (Context) DFIArguments; 645 Saved->FirstArg = Info.FirstArg; 646 Saved->SecondArg = Info.SecondArg; 647 Result.Data = Saved; 648 break; 649 } 650 651 case Sema::TDK_IncompletePack: 652 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 653 case Sema::TDK_Inconsistent: 654 case Sema::TDK_Underqualified: { 655 // FIXME: Should allocate from normal heap so that we can free this later. 656 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 657 Saved->Param = Info.Param; 658 Saved->FirstArg = Info.FirstArg; 659 Saved->SecondArg = Info.SecondArg; 660 Result.Data = Saved; 661 break; 662 } 663 664 case Sema::TDK_SubstitutionFailure: 665 Result.Data = Info.take(); 666 if (Info.hasSFINAEDiagnostic()) { 667 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 668 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 669 Info.takeSFINAEDiagnostic(*Diag); 670 Result.HasDiagnostic = true; 671 } 672 break; 673 674 case Sema::TDK_ConstraintsNotSatisfied: { 675 CNSInfo *Saved = new (Context) CNSInfo; 676 Saved->TemplateArgs = Info.take(); 677 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 678 Result.Data = Saved; 679 break; 680 } 681 682 case Sema::TDK_Success: 683 case Sema::TDK_NonDependentConversionFailure: 684 llvm_unreachable("not a deduction failure"); 685 } 686 687 return Result; 688 } 689 690 void DeductionFailureInfo::Destroy() { 691 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 692 case Sema::TDK_Success: 693 case Sema::TDK_Invalid: 694 case Sema::TDK_InstantiationDepth: 695 case Sema::TDK_Incomplete: 696 case Sema::TDK_TooManyArguments: 697 case Sema::TDK_TooFewArguments: 698 case Sema::TDK_InvalidExplicitArguments: 699 case Sema::TDK_CUDATargetMismatch: 700 case Sema::TDK_NonDependentConversionFailure: 701 break; 702 703 case Sema::TDK_IncompletePack: 704 case Sema::TDK_Inconsistent: 705 case Sema::TDK_Underqualified: 706 case Sema::TDK_DeducedMismatch: 707 case Sema::TDK_DeducedMismatchNested: 708 case Sema::TDK_NonDeducedMismatch: 709 // FIXME: Destroy the data? 710 Data = nullptr; 711 break; 712 713 case Sema::TDK_SubstitutionFailure: 714 // FIXME: Destroy the template argument list? 715 Data = nullptr; 716 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 717 Diag->~PartialDiagnosticAt(); 718 HasDiagnostic = false; 719 } 720 break; 721 722 case Sema::TDK_ConstraintsNotSatisfied: 723 // FIXME: Destroy the template argument list? 724 Data = nullptr; 725 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 726 Diag->~PartialDiagnosticAt(); 727 HasDiagnostic = false; 728 } 729 break; 730 731 // Unhandled 732 case Sema::TDK_MiscellaneousDeductionFailure: 733 break; 734 } 735 } 736 737 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 738 if (HasDiagnostic) 739 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 740 return nullptr; 741 } 742 743 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 745 case Sema::TDK_Success: 746 case Sema::TDK_Invalid: 747 case Sema::TDK_InstantiationDepth: 748 case Sema::TDK_TooManyArguments: 749 case Sema::TDK_TooFewArguments: 750 case Sema::TDK_SubstitutionFailure: 751 case Sema::TDK_DeducedMismatch: 752 case Sema::TDK_DeducedMismatchNested: 753 case Sema::TDK_NonDeducedMismatch: 754 case Sema::TDK_CUDATargetMismatch: 755 case Sema::TDK_NonDependentConversionFailure: 756 case Sema::TDK_ConstraintsNotSatisfied: 757 return TemplateParameter(); 758 759 case Sema::TDK_Incomplete: 760 case Sema::TDK_InvalidExplicitArguments: 761 return TemplateParameter::getFromOpaqueValue(Data); 762 763 case Sema::TDK_IncompletePack: 764 case Sema::TDK_Inconsistent: 765 case Sema::TDK_Underqualified: 766 return static_cast<DFIParamWithArguments*>(Data)->Param; 767 768 // Unhandled 769 case Sema::TDK_MiscellaneousDeductionFailure: 770 break; 771 } 772 773 return TemplateParameter(); 774 } 775 776 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 777 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 778 case Sema::TDK_Success: 779 case Sema::TDK_Invalid: 780 case Sema::TDK_InstantiationDepth: 781 case Sema::TDK_TooManyArguments: 782 case Sema::TDK_TooFewArguments: 783 case Sema::TDK_Incomplete: 784 case Sema::TDK_IncompletePack: 785 case Sema::TDK_InvalidExplicitArguments: 786 case Sema::TDK_Inconsistent: 787 case Sema::TDK_Underqualified: 788 case Sema::TDK_NonDeducedMismatch: 789 case Sema::TDK_CUDATargetMismatch: 790 case Sema::TDK_NonDependentConversionFailure: 791 return nullptr; 792 793 case Sema::TDK_DeducedMismatch: 794 case Sema::TDK_DeducedMismatchNested: 795 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 796 797 case Sema::TDK_SubstitutionFailure: 798 return static_cast<TemplateArgumentList*>(Data); 799 800 case Sema::TDK_ConstraintsNotSatisfied: 801 return static_cast<CNSInfo*>(Data)->TemplateArgs; 802 803 // Unhandled 804 case Sema::TDK_MiscellaneousDeductionFailure: 805 break; 806 } 807 808 return nullptr; 809 } 810 811 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 812 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 813 case Sema::TDK_Success: 814 case Sema::TDK_Invalid: 815 case Sema::TDK_InstantiationDepth: 816 case Sema::TDK_Incomplete: 817 case Sema::TDK_TooManyArguments: 818 case Sema::TDK_TooFewArguments: 819 case Sema::TDK_InvalidExplicitArguments: 820 case Sema::TDK_SubstitutionFailure: 821 case Sema::TDK_CUDATargetMismatch: 822 case Sema::TDK_NonDependentConversionFailure: 823 case Sema::TDK_ConstraintsNotSatisfied: 824 return nullptr; 825 826 case Sema::TDK_IncompletePack: 827 case Sema::TDK_Inconsistent: 828 case Sema::TDK_Underqualified: 829 case Sema::TDK_DeducedMismatch: 830 case Sema::TDK_DeducedMismatchNested: 831 case Sema::TDK_NonDeducedMismatch: 832 return &static_cast<DFIArguments*>(Data)->FirstArg; 833 834 // Unhandled 835 case Sema::TDK_MiscellaneousDeductionFailure: 836 break; 837 } 838 839 return nullptr; 840 } 841 842 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 843 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 844 case Sema::TDK_Success: 845 case Sema::TDK_Invalid: 846 case Sema::TDK_InstantiationDepth: 847 case Sema::TDK_Incomplete: 848 case Sema::TDK_IncompletePack: 849 case Sema::TDK_TooManyArguments: 850 case Sema::TDK_TooFewArguments: 851 case Sema::TDK_InvalidExplicitArguments: 852 case Sema::TDK_SubstitutionFailure: 853 case Sema::TDK_CUDATargetMismatch: 854 case Sema::TDK_NonDependentConversionFailure: 855 case Sema::TDK_ConstraintsNotSatisfied: 856 return nullptr; 857 858 case Sema::TDK_Inconsistent: 859 case Sema::TDK_Underqualified: 860 case Sema::TDK_DeducedMismatch: 861 case Sema::TDK_DeducedMismatchNested: 862 case Sema::TDK_NonDeducedMismatch: 863 return &static_cast<DFIArguments*>(Data)->SecondArg; 864 865 // Unhandled 866 case Sema::TDK_MiscellaneousDeductionFailure: 867 break; 868 } 869 870 return nullptr; 871 } 872 873 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 874 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 875 case Sema::TDK_DeducedMismatch: 876 case Sema::TDK_DeducedMismatchNested: 877 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 878 879 default: 880 return llvm::None; 881 } 882 } 883 884 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 885 OverloadedOperatorKind Op) { 886 if (!AllowRewrittenCandidates) 887 return false; 888 return Op == OO_EqualEqual || Op == OO_Spaceship; 889 } 890 891 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 892 ASTContext &Ctx, const FunctionDecl *FD) { 893 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 894 return false; 895 // Don't bother adding a reversed candidate that can never be a better 896 // match than the non-reversed version. 897 return FD->getNumParams() != 2 || 898 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 899 FD->getParamDecl(1)->getType()) || 900 FD->hasAttr<EnableIfAttr>(); 901 } 902 903 void OverloadCandidateSet::destroyCandidates() { 904 for (iterator i = begin(), e = end(); i != e; ++i) { 905 for (auto &C : i->Conversions) 906 C.~ImplicitConversionSequence(); 907 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 908 i->DeductionFailure.Destroy(); 909 } 910 } 911 912 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 913 destroyCandidates(); 914 SlabAllocator.Reset(); 915 NumInlineBytesUsed = 0; 916 Candidates.clear(); 917 Functions.clear(); 918 Kind = CSK; 919 } 920 921 namespace { 922 class UnbridgedCastsSet { 923 struct Entry { 924 Expr **Addr; 925 Expr *Saved; 926 }; 927 SmallVector<Entry, 2> Entries; 928 929 public: 930 void save(Sema &S, Expr *&E) { 931 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 932 Entry entry = { &E, E }; 933 Entries.push_back(entry); 934 E = S.stripARCUnbridgedCast(E); 935 } 936 937 void restore() { 938 for (SmallVectorImpl<Entry>::iterator 939 i = Entries.begin(), e = Entries.end(); i != e; ++i) 940 *i->Addr = i->Saved; 941 } 942 }; 943 } 944 945 /// checkPlaceholderForOverload - Do any interesting placeholder-like 946 /// preprocessing on the given expression. 947 /// 948 /// \param unbridgedCasts a collection to which to add unbridged casts; 949 /// without this, they will be immediately diagnosed as errors 950 /// 951 /// Return true on unrecoverable error. 952 static bool 953 checkPlaceholderForOverload(Sema &S, Expr *&E, 954 UnbridgedCastsSet *unbridgedCasts = nullptr) { 955 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 956 // We can't handle overloaded expressions here because overload 957 // resolution might reasonably tweak them. 958 if (placeholder->getKind() == BuiltinType::Overload) return false; 959 960 // If the context potentially accepts unbridged ARC casts, strip 961 // the unbridged cast and add it to the collection for later restoration. 962 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 963 unbridgedCasts) { 964 unbridgedCasts->save(S, E); 965 return false; 966 } 967 968 // Go ahead and check everything else. 969 ExprResult result = S.CheckPlaceholderExpr(E); 970 if (result.isInvalid()) 971 return true; 972 973 E = result.get(); 974 return false; 975 } 976 977 // Nothing to do. 978 return false; 979 } 980 981 /// checkArgPlaceholdersForOverload - Check a set of call operands for 982 /// placeholders. 983 static bool checkArgPlaceholdersForOverload(Sema &S, 984 MultiExprArg Args, 985 UnbridgedCastsSet &unbridged) { 986 for (unsigned i = 0, e = Args.size(); i != e; ++i) 987 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 988 return true; 989 990 return false; 991 } 992 993 /// Determine whether the given New declaration is an overload of the 994 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 995 /// New and Old cannot be overloaded, e.g., if New has the same signature as 996 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 997 /// functions (or function templates) at all. When it does return Ovl_Match or 998 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 999 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1000 /// declaration. 1001 /// 1002 /// Example: Given the following input: 1003 /// 1004 /// void f(int, float); // #1 1005 /// void f(int, int); // #2 1006 /// int f(int, int); // #3 1007 /// 1008 /// When we process #1, there is no previous declaration of "f", so IsOverload 1009 /// will not be used. 1010 /// 1011 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1012 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1013 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1014 /// unchanged. 1015 /// 1016 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1017 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1018 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1019 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1020 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1021 /// 1022 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1023 /// by a using declaration. The rules for whether to hide shadow declarations 1024 /// ignore some properties which otherwise figure into a function template's 1025 /// signature. 1026 Sema::OverloadKind 1027 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1028 NamedDecl *&Match, bool NewIsUsingDecl) { 1029 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1030 I != E; ++I) { 1031 NamedDecl *OldD = *I; 1032 1033 bool OldIsUsingDecl = false; 1034 if (isa<UsingShadowDecl>(OldD)) { 1035 OldIsUsingDecl = true; 1036 1037 // We can always introduce two using declarations into the same 1038 // context, even if they have identical signatures. 1039 if (NewIsUsingDecl) continue; 1040 1041 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1042 } 1043 1044 // A using-declaration does not conflict with another declaration 1045 // if one of them is hidden. 1046 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1047 continue; 1048 1049 // If either declaration was introduced by a using declaration, 1050 // we'll need to use slightly different rules for matching. 1051 // Essentially, these rules are the normal rules, except that 1052 // function templates hide function templates with different 1053 // return types or template parameter lists. 1054 bool UseMemberUsingDeclRules = 1055 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1056 !New->getFriendObjectKind(); 1057 1058 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1059 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1060 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1061 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1062 continue; 1063 } 1064 1065 if (!isa<FunctionTemplateDecl>(OldD) && 1066 !shouldLinkPossiblyHiddenDecl(*I, New)) 1067 continue; 1068 1069 Match = *I; 1070 return Ovl_Match; 1071 } 1072 1073 // Builtins that have custom typechecking or have a reference should 1074 // not be overloadable or redeclarable. 1075 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1076 Match = *I; 1077 return Ovl_NonFunction; 1078 } 1079 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1080 // We can overload with these, which can show up when doing 1081 // redeclaration checks for UsingDecls. 1082 assert(Old.getLookupKind() == LookupUsingDeclName); 1083 } else if (isa<TagDecl>(OldD)) { 1084 // We can always overload with tags by hiding them. 1085 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1086 // Optimistically assume that an unresolved using decl will 1087 // overload; if it doesn't, we'll have to diagnose during 1088 // template instantiation. 1089 // 1090 // Exception: if the scope is dependent and this is not a class 1091 // member, the using declaration can only introduce an enumerator. 1092 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1093 Match = *I; 1094 return Ovl_NonFunction; 1095 } 1096 } else { 1097 // (C++ 13p1): 1098 // Only function declarations can be overloaded; object and type 1099 // declarations cannot be overloaded. 1100 Match = *I; 1101 return Ovl_NonFunction; 1102 } 1103 } 1104 1105 // C++ [temp.friend]p1: 1106 // For a friend function declaration that is not a template declaration: 1107 // -- if the name of the friend is a qualified or unqualified template-id, 1108 // [...], otherwise 1109 // -- if the name of the friend is a qualified-id and a matching 1110 // non-template function is found in the specified class or namespace, 1111 // the friend declaration refers to that function, otherwise, 1112 // -- if the name of the friend is a qualified-id and a matching function 1113 // template is found in the specified class or namespace, the friend 1114 // declaration refers to the deduced specialization of that function 1115 // template, otherwise 1116 // -- the name shall be an unqualified-id [...] 1117 // If we get here for a qualified friend declaration, we've just reached the 1118 // third bullet. If the type of the friend is dependent, skip this lookup 1119 // until instantiation. 1120 if (New->getFriendObjectKind() && New->getQualifier() && 1121 !New->getDescribedFunctionTemplate() && 1122 !New->getDependentSpecializationInfo() && 1123 !New->getType()->isDependentType()) { 1124 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1125 TemplateSpecResult.addAllDecls(Old); 1126 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1127 /*QualifiedFriend*/true)) { 1128 New->setInvalidDecl(); 1129 return Ovl_Overload; 1130 } 1131 1132 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1133 return Ovl_Match; 1134 } 1135 1136 return Ovl_Overload; 1137 } 1138 1139 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1140 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1141 bool ConsiderRequiresClauses) { 1142 // C++ [basic.start.main]p2: This function shall not be overloaded. 1143 if (New->isMain()) 1144 return false; 1145 1146 // MSVCRT user defined entry points cannot be overloaded. 1147 if (New->isMSVCRTEntryPoint()) 1148 return false; 1149 1150 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1151 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1152 1153 // C++ [temp.fct]p2: 1154 // A function template can be overloaded with other function templates 1155 // and with normal (non-template) functions. 1156 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1157 return true; 1158 1159 // Is the function New an overload of the function Old? 1160 QualType OldQType = Context.getCanonicalType(Old->getType()); 1161 QualType NewQType = Context.getCanonicalType(New->getType()); 1162 1163 // Compare the signatures (C++ 1.3.10) of the two functions to 1164 // determine whether they are overloads. If we find any mismatch 1165 // in the signature, they are overloads. 1166 1167 // If either of these functions is a K&R-style function (no 1168 // prototype), then we consider them to have matching signatures. 1169 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1170 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1171 return false; 1172 1173 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1174 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1175 1176 // The signature of a function includes the types of its 1177 // parameters (C++ 1.3.10), which includes the presence or absence 1178 // of the ellipsis; see C++ DR 357). 1179 if (OldQType != NewQType && 1180 (OldType->getNumParams() != NewType->getNumParams() || 1181 OldType->isVariadic() != NewType->isVariadic() || 1182 !FunctionParamTypesAreEqual(OldType, NewType))) 1183 return true; 1184 1185 // C++ [temp.over.link]p4: 1186 // The signature of a function template consists of its function 1187 // signature, its return type and its template parameter list. The names 1188 // of the template parameters are significant only for establishing the 1189 // relationship between the template parameters and the rest of the 1190 // signature. 1191 // 1192 // We check the return type and template parameter lists for function 1193 // templates first; the remaining checks follow. 1194 // 1195 // However, we don't consider either of these when deciding whether 1196 // a member introduced by a shadow declaration is hidden. 1197 if (!UseMemberUsingDeclRules && NewTemplate && 1198 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1199 OldTemplate->getTemplateParameters(), 1200 false, TPL_TemplateMatch) || 1201 !Context.hasSameType(Old->getDeclaredReturnType(), 1202 New->getDeclaredReturnType()))) 1203 return true; 1204 1205 // If the function is a class member, its signature includes the 1206 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1207 // 1208 // As part of this, also check whether one of the member functions 1209 // is static, in which case they are not overloads (C++ 1210 // 13.1p2). While not part of the definition of the signature, 1211 // this check is important to determine whether these functions 1212 // can be overloaded. 1213 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1214 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1215 if (OldMethod && NewMethod && 1216 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1217 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1218 if (!UseMemberUsingDeclRules && 1219 (OldMethod->getRefQualifier() == RQ_None || 1220 NewMethod->getRefQualifier() == RQ_None)) { 1221 // C++0x [over.load]p2: 1222 // - Member function declarations with the same name and the same 1223 // parameter-type-list as well as member function template 1224 // declarations with the same name, the same parameter-type-list, and 1225 // the same template parameter lists cannot be overloaded if any of 1226 // them, but not all, have a ref-qualifier (8.3.5). 1227 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1228 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1229 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1230 } 1231 return true; 1232 } 1233 1234 // We may not have applied the implicit const for a constexpr member 1235 // function yet (because we haven't yet resolved whether this is a static 1236 // or non-static member function). Add it now, on the assumption that this 1237 // is a redeclaration of OldMethod. 1238 auto OldQuals = OldMethod->getMethodQualifiers(); 1239 auto NewQuals = NewMethod->getMethodQualifiers(); 1240 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1241 !isa<CXXConstructorDecl>(NewMethod)) 1242 NewQuals.addConst(); 1243 // We do not allow overloading based off of '__restrict'. 1244 OldQuals.removeRestrict(); 1245 NewQuals.removeRestrict(); 1246 if (OldQuals != NewQuals) 1247 return true; 1248 } 1249 1250 // Though pass_object_size is placed on parameters and takes an argument, we 1251 // consider it to be a function-level modifier for the sake of function 1252 // identity. Either the function has one or more parameters with 1253 // pass_object_size or it doesn't. 1254 if (functionHasPassObjectSizeParams(New) != 1255 functionHasPassObjectSizeParams(Old)) 1256 return true; 1257 1258 // enable_if attributes are an order-sensitive part of the signature. 1259 for (specific_attr_iterator<EnableIfAttr> 1260 NewI = New->specific_attr_begin<EnableIfAttr>(), 1261 NewE = New->specific_attr_end<EnableIfAttr>(), 1262 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1263 OldE = Old->specific_attr_end<EnableIfAttr>(); 1264 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1265 if (NewI == NewE || OldI == OldE) 1266 return true; 1267 llvm::FoldingSetNodeID NewID, OldID; 1268 NewI->getCond()->Profile(NewID, Context, true); 1269 OldI->getCond()->Profile(OldID, Context, true); 1270 if (NewID != OldID) 1271 return true; 1272 } 1273 1274 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1275 // Don't allow overloading of destructors. (In theory we could, but it 1276 // would be a giant change to clang.) 1277 if (!isa<CXXDestructorDecl>(New)) { 1278 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1279 OldTarget = IdentifyCUDATarget(Old); 1280 if (NewTarget != CFT_InvalidTarget) { 1281 assert((OldTarget != CFT_InvalidTarget) && 1282 "Unexpected invalid target."); 1283 1284 // Allow overloading of functions with same signature and different CUDA 1285 // target attributes. 1286 if (NewTarget != OldTarget) 1287 return true; 1288 } 1289 } 1290 } 1291 1292 if (ConsiderRequiresClauses) { 1293 Expr *NewRC = New->getTrailingRequiresClause(), 1294 *OldRC = Old->getTrailingRequiresClause(); 1295 if ((NewRC != nullptr) != (OldRC != nullptr)) 1296 // RC are most certainly different - these are overloads. 1297 return true; 1298 1299 if (NewRC) { 1300 llvm::FoldingSetNodeID NewID, OldID; 1301 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1302 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1303 if (NewID != OldID) 1304 // RCs are not equivalent - these are overloads. 1305 return true; 1306 } 1307 } 1308 1309 // The signatures match; this is not an overload. 1310 return false; 1311 } 1312 1313 /// Tries a user-defined conversion from From to ToType. 1314 /// 1315 /// Produces an implicit conversion sequence for when a standard conversion 1316 /// is not an option. See TryImplicitConversion for more information. 1317 static ImplicitConversionSequence 1318 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1319 bool SuppressUserConversions, 1320 bool AllowExplicit, 1321 bool InOverloadResolution, 1322 bool CStyle, 1323 bool AllowObjCWritebackConversion, 1324 bool AllowObjCConversionOnExplicit) { 1325 ImplicitConversionSequence ICS; 1326 1327 if (SuppressUserConversions) { 1328 // We're not in the case above, so there is no conversion that 1329 // we can perform. 1330 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1331 return ICS; 1332 } 1333 1334 // Attempt user-defined conversion. 1335 OverloadCandidateSet Conversions(From->getExprLoc(), 1336 OverloadCandidateSet::CSK_Normal); 1337 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1338 Conversions, AllowExplicit, 1339 AllowObjCConversionOnExplicit)) { 1340 case OR_Success: 1341 case OR_Deleted: 1342 ICS.setUserDefined(); 1343 // C++ [over.ics.user]p4: 1344 // A conversion of an expression of class type to the same class 1345 // type is given Exact Match rank, and a conversion of an 1346 // expression of class type to a base class of that type is 1347 // given Conversion rank, in spite of the fact that a copy 1348 // constructor (i.e., a user-defined conversion function) is 1349 // called for those cases. 1350 if (CXXConstructorDecl *Constructor 1351 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1352 QualType FromCanon 1353 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1354 QualType ToCanon 1355 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1356 if (Constructor->isCopyConstructor() && 1357 (FromCanon == ToCanon || 1358 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1359 // Turn this into a "standard" conversion sequence, so that it 1360 // gets ranked with standard conversion sequences. 1361 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1362 ICS.setStandard(); 1363 ICS.Standard.setAsIdentityConversion(); 1364 ICS.Standard.setFromType(From->getType()); 1365 ICS.Standard.setAllToTypes(ToType); 1366 ICS.Standard.CopyConstructor = Constructor; 1367 ICS.Standard.FoundCopyConstructor = Found; 1368 if (ToCanon != FromCanon) 1369 ICS.Standard.Second = ICK_Derived_To_Base; 1370 } 1371 } 1372 break; 1373 1374 case OR_Ambiguous: 1375 ICS.setAmbiguous(); 1376 ICS.Ambiguous.setFromType(From->getType()); 1377 ICS.Ambiguous.setToType(ToType); 1378 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1379 Cand != Conversions.end(); ++Cand) 1380 if (Cand->Best) 1381 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1382 break; 1383 1384 // Fall through. 1385 case OR_No_Viable_Function: 1386 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1387 break; 1388 } 1389 1390 return ICS; 1391 } 1392 1393 /// TryImplicitConversion - Attempt to perform an implicit conversion 1394 /// from the given expression (Expr) to the given type (ToType). This 1395 /// function returns an implicit conversion sequence that can be used 1396 /// to perform the initialization. Given 1397 /// 1398 /// void f(float f); 1399 /// void g(int i) { f(i); } 1400 /// 1401 /// this routine would produce an implicit conversion sequence to 1402 /// describe the initialization of f from i, which will be a standard 1403 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1404 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1405 // 1406 /// Note that this routine only determines how the conversion can be 1407 /// performed; it does not actually perform the conversion. As such, 1408 /// it will not produce any diagnostics if no conversion is available, 1409 /// but will instead return an implicit conversion sequence of kind 1410 /// "BadConversion". 1411 /// 1412 /// If @p SuppressUserConversions, then user-defined conversions are 1413 /// not permitted. 1414 /// If @p AllowExplicit, then explicit user-defined conversions are 1415 /// permitted. 1416 /// 1417 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1418 /// writeback conversion, which allows __autoreleasing id* parameters to 1419 /// be initialized with __strong id* or __weak id* arguments. 1420 static ImplicitConversionSequence 1421 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1422 bool SuppressUserConversions, 1423 bool AllowExplicit, 1424 bool InOverloadResolution, 1425 bool CStyle, 1426 bool AllowObjCWritebackConversion, 1427 bool AllowObjCConversionOnExplicit) { 1428 ImplicitConversionSequence ICS; 1429 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1430 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1431 ICS.setStandard(); 1432 return ICS; 1433 } 1434 1435 if (!S.getLangOpts().CPlusPlus) { 1436 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1437 return ICS; 1438 } 1439 1440 // C++ [over.ics.user]p4: 1441 // A conversion of an expression of class type to the same class 1442 // type is given Exact Match rank, and a conversion of an 1443 // expression of class type to a base class of that type is 1444 // given Conversion rank, in spite of the fact that a copy/move 1445 // constructor (i.e., a user-defined conversion function) is 1446 // called for those cases. 1447 QualType FromType = From->getType(); 1448 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1449 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1450 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1451 ICS.setStandard(); 1452 ICS.Standard.setAsIdentityConversion(); 1453 ICS.Standard.setFromType(FromType); 1454 ICS.Standard.setAllToTypes(ToType); 1455 1456 // We don't actually check at this point whether there is a valid 1457 // copy/move constructor, since overloading just assumes that it 1458 // exists. When we actually perform initialization, we'll find the 1459 // appropriate constructor to copy the returned object, if needed. 1460 ICS.Standard.CopyConstructor = nullptr; 1461 1462 // Determine whether this is considered a derived-to-base conversion. 1463 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1464 ICS.Standard.Second = ICK_Derived_To_Base; 1465 1466 return ICS; 1467 } 1468 1469 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1470 AllowExplicit, InOverloadResolution, CStyle, 1471 AllowObjCWritebackConversion, 1472 AllowObjCConversionOnExplicit); 1473 } 1474 1475 ImplicitConversionSequence 1476 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1477 bool SuppressUserConversions, 1478 bool AllowExplicit, 1479 bool InOverloadResolution, 1480 bool CStyle, 1481 bool AllowObjCWritebackConversion) { 1482 return ::TryImplicitConversion(*this, From, ToType, 1483 SuppressUserConversions, AllowExplicit, 1484 InOverloadResolution, CStyle, 1485 AllowObjCWritebackConversion, 1486 /*AllowObjCConversionOnExplicit=*/false); 1487 } 1488 1489 /// PerformImplicitConversion - Perform an implicit conversion of the 1490 /// expression From to the type ToType. Returns the 1491 /// converted expression. Flavor is the kind of conversion we're 1492 /// performing, used in the error message. If @p AllowExplicit, 1493 /// explicit user-defined conversions are permitted. 1494 ExprResult 1495 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1496 AssignmentAction Action, bool AllowExplicit) { 1497 ImplicitConversionSequence ICS; 1498 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1499 } 1500 1501 ExprResult 1502 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1503 AssignmentAction Action, bool AllowExplicit, 1504 ImplicitConversionSequence& ICS) { 1505 if (checkPlaceholderForOverload(*this, From)) 1506 return ExprError(); 1507 1508 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1509 bool AllowObjCWritebackConversion 1510 = getLangOpts().ObjCAutoRefCount && 1511 (Action == AA_Passing || Action == AA_Sending); 1512 if (getLangOpts().ObjC) 1513 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1514 From->getType(), From); 1515 ICS = ::TryImplicitConversion(*this, From, ToType, 1516 /*SuppressUserConversions=*/false, 1517 AllowExplicit, 1518 /*InOverloadResolution=*/false, 1519 /*CStyle=*/false, 1520 AllowObjCWritebackConversion, 1521 /*AllowObjCConversionOnExplicit=*/false); 1522 return PerformImplicitConversion(From, ToType, ICS, Action); 1523 } 1524 1525 /// Determine whether the conversion from FromType to ToType is a valid 1526 /// conversion that strips "noexcept" or "noreturn" off the nested function 1527 /// type. 1528 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1529 QualType &ResultTy) { 1530 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1531 return false; 1532 1533 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1534 // or F(t noexcept) -> F(t) 1535 // where F adds one of the following at most once: 1536 // - a pointer 1537 // - a member pointer 1538 // - a block pointer 1539 // Changes here need matching changes in FindCompositePointerType. 1540 CanQualType CanTo = Context.getCanonicalType(ToType); 1541 CanQualType CanFrom = Context.getCanonicalType(FromType); 1542 Type::TypeClass TyClass = CanTo->getTypeClass(); 1543 if (TyClass != CanFrom->getTypeClass()) return false; 1544 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1545 if (TyClass == Type::Pointer) { 1546 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1547 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1548 } else if (TyClass == Type::BlockPointer) { 1549 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1550 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1551 } else if (TyClass == Type::MemberPointer) { 1552 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1553 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1554 // A function pointer conversion cannot change the class of the function. 1555 if (ToMPT->getClass() != FromMPT->getClass()) 1556 return false; 1557 CanTo = ToMPT->getPointeeType(); 1558 CanFrom = FromMPT->getPointeeType(); 1559 } else { 1560 return false; 1561 } 1562 1563 TyClass = CanTo->getTypeClass(); 1564 if (TyClass != CanFrom->getTypeClass()) return false; 1565 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1566 return false; 1567 } 1568 1569 const auto *FromFn = cast<FunctionType>(CanFrom); 1570 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1571 1572 const auto *ToFn = cast<FunctionType>(CanTo); 1573 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1574 1575 bool Changed = false; 1576 1577 // Drop 'noreturn' if not present in target type. 1578 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1579 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1580 Changed = true; 1581 } 1582 1583 // Drop 'noexcept' if not present in target type. 1584 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1585 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1586 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1587 FromFn = cast<FunctionType>( 1588 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1589 EST_None) 1590 .getTypePtr()); 1591 Changed = true; 1592 } 1593 1594 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1595 // only if the ExtParameterInfo lists of the two function prototypes can be 1596 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1597 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1598 bool CanUseToFPT, CanUseFromFPT; 1599 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1600 CanUseFromFPT, NewParamInfos) && 1601 CanUseToFPT && !CanUseFromFPT) { 1602 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1603 ExtInfo.ExtParameterInfos = 1604 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1605 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1606 FromFPT->getParamTypes(), ExtInfo); 1607 FromFn = QT->getAs<FunctionType>(); 1608 Changed = true; 1609 } 1610 } 1611 1612 if (!Changed) 1613 return false; 1614 1615 assert(QualType(FromFn, 0).isCanonical()); 1616 if (QualType(FromFn, 0) != CanTo) return false; 1617 1618 ResultTy = ToType; 1619 return true; 1620 } 1621 1622 /// Determine whether the conversion from FromType to ToType is a valid 1623 /// vector conversion. 1624 /// 1625 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1626 /// conversion. 1627 static bool IsVectorConversion(Sema &S, QualType FromType, 1628 QualType ToType, ImplicitConversionKind &ICK) { 1629 // We need at least one of these types to be a vector type to have a vector 1630 // conversion. 1631 if (!ToType->isVectorType() && !FromType->isVectorType()) 1632 return false; 1633 1634 // Identical types require no conversions. 1635 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1636 return false; 1637 1638 // There are no conversions between extended vector types, only identity. 1639 if (ToType->isExtVectorType()) { 1640 // There are no conversions between extended vector types other than the 1641 // identity conversion. 1642 if (FromType->isExtVectorType()) 1643 return false; 1644 1645 // Vector splat from any arithmetic type to a vector. 1646 if (FromType->isArithmeticType()) { 1647 ICK = ICK_Vector_Splat; 1648 return true; 1649 } 1650 } 1651 1652 // We can perform the conversion between vector types in the following cases: 1653 // 1)vector types are equivalent AltiVec and GCC vector types 1654 // 2)lax vector conversions are permitted and the vector types are of the 1655 // same size 1656 if (ToType->isVectorType() && FromType->isVectorType()) { 1657 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1658 S.isLaxVectorConversion(FromType, ToType)) { 1659 ICK = ICK_Vector_Conversion; 1660 return true; 1661 } 1662 } 1663 1664 return false; 1665 } 1666 1667 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1668 bool InOverloadResolution, 1669 StandardConversionSequence &SCS, 1670 bool CStyle); 1671 1672 /// IsStandardConversion - Determines whether there is a standard 1673 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1674 /// expression From to the type ToType. Standard conversion sequences 1675 /// only consider non-class types; for conversions that involve class 1676 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1677 /// contain the standard conversion sequence required to perform this 1678 /// conversion and this routine will return true. Otherwise, this 1679 /// routine will return false and the value of SCS is unspecified. 1680 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1681 bool InOverloadResolution, 1682 StandardConversionSequence &SCS, 1683 bool CStyle, 1684 bool AllowObjCWritebackConversion) { 1685 QualType FromType = From->getType(); 1686 1687 // Standard conversions (C++ [conv]) 1688 SCS.setAsIdentityConversion(); 1689 SCS.IncompatibleObjC = false; 1690 SCS.setFromType(FromType); 1691 SCS.CopyConstructor = nullptr; 1692 1693 // There are no standard conversions for class types in C++, so 1694 // abort early. When overloading in C, however, we do permit them. 1695 if (S.getLangOpts().CPlusPlus && 1696 (FromType->isRecordType() || ToType->isRecordType())) 1697 return false; 1698 1699 // The first conversion can be an lvalue-to-rvalue conversion, 1700 // array-to-pointer conversion, or function-to-pointer conversion 1701 // (C++ 4p1). 1702 1703 if (FromType == S.Context.OverloadTy) { 1704 DeclAccessPair AccessPair; 1705 if (FunctionDecl *Fn 1706 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1707 AccessPair)) { 1708 // We were able to resolve the address of the overloaded function, 1709 // so we can convert to the type of that function. 1710 FromType = Fn->getType(); 1711 SCS.setFromType(FromType); 1712 1713 // we can sometimes resolve &foo<int> regardless of ToType, so check 1714 // if the type matches (identity) or we are converting to bool 1715 if (!S.Context.hasSameUnqualifiedType( 1716 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1717 QualType resultTy; 1718 // if the function type matches except for [[noreturn]], it's ok 1719 if (!S.IsFunctionConversion(FromType, 1720 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1721 // otherwise, only a boolean conversion is standard 1722 if (!ToType->isBooleanType()) 1723 return false; 1724 } 1725 1726 // Check if the "from" expression is taking the address of an overloaded 1727 // function and recompute the FromType accordingly. Take advantage of the 1728 // fact that non-static member functions *must* have such an address-of 1729 // expression. 1730 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1731 if (Method && !Method->isStatic()) { 1732 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1733 "Non-unary operator on non-static member address"); 1734 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1735 == UO_AddrOf && 1736 "Non-address-of operator on non-static member address"); 1737 const Type *ClassType 1738 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1739 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1740 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1741 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1742 UO_AddrOf && 1743 "Non-address-of operator for overloaded function expression"); 1744 FromType = S.Context.getPointerType(FromType); 1745 } 1746 1747 // Check that we've computed the proper type after overload resolution. 1748 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1749 // be calling it from within an NDEBUG block. 1750 assert(S.Context.hasSameType( 1751 FromType, 1752 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1753 } else { 1754 return false; 1755 } 1756 } 1757 // Lvalue-to-rvalue conversion (C++11 4.1): 1758 // A glvalue (3.10) of a non-function, non-array type T can 1759 // be converted to a prvalue. 1760 bool argIsLValue = From->isGLValue(); 1761 if (argIsLValue && 1762 !FromType->isFunctionType() && !FromType->isArrayType() && 1763 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1764 SCS.First = ICK_Lvalue_To_Rvalue; 1765 1766 // C11 6.3.2.1p2: 1767 // ... if the lvalue has atomic type, the value has the non-atomic version 1768 // of the type of the lvalue ... 1769 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1770 FromType = Atomic->getValueType(); 1771 1772 // If T is a non-class type, the type of the rvalue is the 1773 // cv-unqualified version of T. Otherwise, the type of the rvalue 1774 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1775 // just strip the qualifiers because they don't matter. 1776 FromType = FromType.getUnqualifiedType(); 1777 } else if (FromType->isArrayType()) { 1778 // Array-to-pointer conversion (C++ 4.2) 1779 SCS.First = ICK_Array_To_Pointer; 1780 1781 // An lvalue or rvalue of type "array of N T" or "array of unknown 1782 // bound of T" can be converted to an rvalue of type "pointer to 1783 // T" (C++ 4.2p1). 1784 FromType = S.Context.getArrayDecayedType(FromType); 1785 1786 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1787 // This conversion is deprecated in C++03 (D.4) 1788 SCS.DeprecatedStringLiteralToCharPtr = true; 1789 1790 // For the purpose of ranking in overload resolution 1791 // (13.3.3.1.1), this conversion is considered an 1792 // array-to-pointer conversion followed by a qualification 1793 // conversion (4.4). (C++ 4.2p2) 1794 SCS.Second = ICK_Identity; 1795 SCS.Third = ICK_Qualification; 1796 SCS.QualificationIncludesObjCLifetime = false; 1797 SCS.setAllToTypes(FromType); 1798 return true; 1799 } 1800 } else if (FromType->isFunctionType() && argIsLValue) { 1801 // Function-to-pointer conversion (C++ 4.3). 1802 SCS.First = ICK_Function_To_Pointer; 1803 1804 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1805 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1806 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1807 return false; 1808 1809 // An lvalue of function type T can be converted to an rvalue of 1810 // type "pointer to T." The result is a pointer to the 1811 // function. (C++ 4.3p1). 1812 FromType = S.Context.getPointerType(FromType); 1813 } else { 1814 // We don't require any conversions for the first step. 1815 SCS.First = ICK_Identity; 1816 } 1817 SCS.setToType(0, FromType); 1818 1819 // The second conversion can be an integral promotion, floating 1820 // point promotion, integral conversion, floating point conversion, 1821 // floating-integral conversion, pointer conversion, 1822 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1823 // For overloading in C, this can also be a "compatible-type" 1824 // conversion. 1825 bool IncompatibleObjC = false; 1826 ImplicitConversionKind SecondICK = ICK_Identity; 1827 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1828 // The unqualified versions of the types are the same: there's no 1829 // conversion to do. 1830 SCS.Second = ICK_Identity; 1831 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1832 // Integral promotion (C++ 4.5). 1833 SCS.Second = ICK_Integral_Promotion; 1834 FromType = ToType.getUnqualifiedType(); 1835 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1836 // Floating point promotion (C++ 4.6). 1837 SCS.Second = ICK_Floating_Promotion; 1838 FromType = ToType.getUnqualifiedType(); 1839 } else if (S.IsComplexPromotion(FromType, ToType)) { 1840 // Complex promotion (Clang extension) 1841 SCS.Second = ICK_Complex_Promotion; 1842 FromType = ToType.getUnqualifiedType(); 1843 } else if (ToType->isBooleanType() && 1844 (FromType->isArithmeticType() || 1845 FromType->isAnyPointerType() || 1846 FromType->isBlockPointerType() || 1847 FromType->isMemberPointerType() || 1848 FromType->isNullPtrType())) { 1849 // Boolean conversions (C++ 4.12). 1850 SCS.Second = ICK_Boolean_Conversion; 1851 FromType = S.Context.BoolTy; 1852 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1853 ToType->isIntegralType(S.Context)) { 1854 // Integral conversions (C++ 4.7). 1855 SCS.Second = ICK_Integral_Conversion; 1856 FromType = ToType.getUnqualifiedType(); 1857 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1858 // Complex conversions (C99 6.3.1.6) 1859 SCS.Second = ICK_Complex_Conversion; 1860 FromType = ToType.getUnqualifiedType(); 1861 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1862 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1863 // Complex-real conversions (C99 6.3.1.7) 1864 SCS.Second = ICK_Complex_Real; 1865 FromType = ToType.getUnqualifiedType(); 1866 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1867 // FIXME: disable conversions between long double and __float128 if 1868 // their representation is different until there is back end support 1869 // We of course allow this conversion if long double is really double. 1870 if (&S.Context.getFloatTypeSemantics(FromType) != 1871 &S.Context.getFloatTypeSemantics(ToType)) { 1872 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1873 ToType == S.Context.LongDoubleTy) || 1874 (FromType == S.Context.LongDoubleTy && 1875 ToType == S.Context.Float128Ty)); 1876 if (Float128AndLongDouble && 1877 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1878 &llvm::APFloat::PPCDoubleDouble())) 1879 return false; 1880 } 1881 // Floating point conversions (C++ 4.8). 1882 SCS.Second = ICK_Floating_Conversion; 1883 FromType = ToType.getUnqualifiedType(); 1884 } else if ((FromType->isRealFloatingType() && 1885 ToType->isIntegralType(S.Context)) || 1886 (FromType->isIntegralOrUnscopedEnumerationType() && 1887 ToType->isRealFloatingType())) { 1888 // Floating-integral conversions (C++ 4.9). 1889 SCS.Second = ICK_Floating_Integral; 1890 FromType = ToType.getUnqualifiedType(); 1891 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1892 SCS.Second = ICK_Block_Pointer_Conversion; 1893 } else if (AllowObjCWritebackConversion && 1894 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1895 SCS.Second = ICK_Writeback_Conversion; 1896 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1897 FromType, IncompatibleObjC)) { 1898 // Pointer conversions (C++ 4.10). 1899 SCS.Second = ICK_Pointer_Conversion; 1900 SCS.IncompatibleObjC = IncompatibleObjC; 1901 FromType = FromType.getUnqualifiedType(); 1902 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1903 InOverloadResolution, FromType)) { 1904 // Pointer to member conversions (4.11). 1905 SCS.Second = ICK_Pointer_Member; 1906 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1907 SCS.Second = SecondICK; 1908 FromType = ToType.getUnqualifiedType(); 1909 } else if (!S.getLangOpts().CPlusPlus && 1910 S.Context.typesAreCompatible(ToType, FromType)) { 1911 // Compatible conversions (Clang extension for C function overloading) 1912 SCS.Second = ICK_Compatible_Conversion; 1913 FromType = ToType.getUnqualifiedType(); 1914 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1915 InOverloadResolution, 1916 SCS, CStyle)) { 1917 SCS.Second = ICK_TransparentUnionConversion; 1918 FromType = ToType; 1919 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1920 CStyle)) { 1921 // tryAtomicConversion has updated the standard conversion sequence 1922 // appropriately. 1923 return true; 1924 } else if (ToType->isEventT() && 1925 From->isIntegerConstantExpr(S.getASTContext()) && 1926 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1927 SCS.Second = ICK_Zero_Event_Conversion; 1928 FromType = ToType; 1929 } else if (ToType->isQueueT() && 1930 From->isIntegerConstantExpr(S.getASTContext()) && 1931 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1932 SCS.Second = ICK_Zero_Queue_Conversion; 1933 FromType = ToType; 1934 } else if (ToType->isSamplerT() && 1935 From->isIntegerConstantExpr(S.getASTContext())) { 1936 SCS.Second = ICK_Compatible_Conversion; 1937 FromType = ToType; 1938 } else { 1939 // No second conversion required. 1940 SCS.Second = ICK_Identity; 1941 } 1942 SCS.setToType(1, FromType); 1943 1944 // The third conversion can be a function pointer conversion or a 1945 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1946 bool ObjCLifetimeConversion; 1947 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1948 // Function pointer conversions (removing 'noexcept') including removal of 1949 // 'noreturn' (Clang extension). 1950 SCS.Third = ICK_Function_Conversion; 1951 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1952 ObjCLifetimeConversion)) { 1953 SCS.Third = ICK_Qualification; 1954 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1955 FromType = ToType; 1956 } else { 1957 // No conversion required 1958 SCS.Third = ICK_Identity; 1959 } 1960 1961 // C++ [over.best.ics]p6: 1962 // [...] Any difference in top-level cv-qualification is 1963 // subsumed by the initialization itself and does not constitute 1964 // a conversion. [...] 1965 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1966 QualType CanonTo = S.Context.getCanonicalType(ToType); 1967 if (CanonFrom.getLocalUnqualifiedType() 1968 == CanonTo.getLocalUnqualifiedType() && 1969 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1970 FromType = ToType; 1971 CanonFrom = CanonTo; 1972 } 1973 1974 SCS.setToType(2, FromType); 1975 1976 if (CanonFrom == CanonTo) 1977 return true; 1978 1979 // If we have not converted the argument type to the parameter type, 1980 // this is a bad conversion sequence, unless we're resolving an overload in C. 1981 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1982 return false; 1983 1984 ExprResult ER = ExprResult{From}; 1985 Sema::AssignConvertType Conv = 1986 S.CheckSingleAssignmentConstraints(ToType, ER, 1987 /*Diagnose=*/false, 1988 /*DiagnoseCFAudited=*/false, 1989 /*ConvertRHS=*/false); 1990 ImplicitConversionKind SecondConv; 1991 switch (Conv) { 1992 case Sema::Compatible: 1993 SecondConv = ICK_C_Only_Conversion; 1994 break; 1995 // For our purposes, discarding qualifiers is just as bad as using an 1996 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1997 // qualifiers, as well. 1998 case Sema::CompatiblePointerDiscardsQualifiers: 1999 case Sema::IncompatiblePointer: 2000 case Sema::IncompatiblePointerSign: 2001 SecondConv = ICK_Incompatible_Pointer_Conversion; 2002 break; 2003 default: 2004 return false; 2005 } 2006 2007 // First can only be an lvalue conversion, so we pretend that this was the 2008 // second conversion. First should already be valid from earlier in the 2009 // function. 2010 SCS.Second = SecondConv; 2011 SCS.setToType(1, ToType); 2012 2013 // Third is Identity, because Second should rank us worse than any other 2014 // conversion. This could also be ICK_Qualification, but it's simpler to just 2015 // lump everything in with the second conversion, and we don't gain anything 2016 // from making this ICK_Qualification. 2017 SCS.Third = ICK_Identity; 2018 SCS.setToType(2, ToType); 2019 return true; 2020 } 2021 2022 static bool 2023 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2024 QualType &ToType, 2025 bool InOverloadResolution, 2026 StandardConversionSequence &SCS, 2027 bool CStyle) { 2028 2029 const RecordType *UT = ToType->getAsUnionType(); 2030 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2031 return false; 2032 // The field to initialize within the transparent union. 2033 RecordDecl *UD = UT->getDecl(); 2034 // It's compatible if the expression matches any of the fields. 2035 for (const auto *it : UD->fields()) { 2036 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2037 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2038 ToType = it->getType(); 2039 return true; 2040 } 2041 } 2042 return false; 2043 } 2044 2045 /// IsIntegralPromotion - Determines whether the conversion from the 2046 /// expression From (whose potentially-adjusted type is FromType) to 2047 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2048 /// sets PromotedType to the promoted type. 2049 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2050 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2051 // All integers are built-in. 2052 if (!To) { 2053 return false; 2054 } 2055 2056 // An rvalue of type char, signed char, unsigned char, short int, or 2057 // unsigned short int can be converted to an rvalue of type int if 2058 // int can represent all the values of the source type; otherwise, 2059 // the source rvalue can be converted to an rvalue of type unsigned 2060 // int (C++ 4.5p1). 2061 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2062 !FromType->isEnumeralType()) { 2063 if (// We can promote any signed, promotable integer type to an int 2064 (FromType->isSignedIntegerType() || 2065 // We can promote any unsigned integer type whose size is 2066 // less than int to an int. 2067 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2068 return To->getKind() == BuiltinType::Int; 2069 } 2070 2071 return To->getKind() == BuiltinType::UInt; 2072 } 2073 2074 // C++11 [conv.prom]p3: 2075 // A prvalue of an unscoped enumeration type whose underlying type is not 2076 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2077 // following types that can represent all the values of the enumeration 2078 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2079 // unsigned int, long int, unsigned long int, long long int, or unsigned 2080 // long long int. If none of the types in that list can represent all the 2081 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2082 // type can be converted to an rvalue a prvalue of the extended integer type 2083 // with lowest integer conversion rank (4.13) greater than the rank of long 2084 // long in which all the values of the enumeration can be represented. If 2085 // there are two such extended types, the signed one is chosen. 2086 // C++11 [conv.prom]p4: 2087 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2088 // can be converted to a prvalue of its underlying type. Moreover, if 2089 // integral promotion can be applied to its underlying type, a prvalue of an 2090 // unscoped enumeration type whose underlying type is fixed can also be 2091 // converted to a prvalue of the promoted underlying type. 2092 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2093 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2094 // provided for a scoped enumeration. 2095 if (FromEnumType->getDecl()->isScoped()) 2096 return false; 2097 2098 // We can perform an integral promotion to the underlying type of the enum, 2099 // even if that's not the promoted type. Note that the check for promoting 2100 // the underlying type is based on the type alone, and does not consider 2101 // the bitfield-ness of the actual source expression. 2102 if (FromEnumType->getDecl()->isFixed()) { 2103 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2104 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2105 IsIntegralPromotion(nullptr, Underlying, ToType); 2106 } 2107 2108 // We have already pre-calculated the promotion type, so this is trivial. 2109 if (ToType->isIntegerType() && 2110 isCompleteType(From->getBeginLoc(), FromType)) 2111 return Context.hasSameUnqualifiedType( 2112 ToType, FromEnumType->getDecl()->getPromotionType()); 2113 2114 // C++ [conv.prom]p5: 2115 // If the bit-field has an enumerated type, it is treated as any other 2116 // value of that type for promotion purposes. 2117 // 2118 // ... so do not fall through into the bit-field checks below in C++. 2119 if (getLangOpts().CPlusPlus) 2120 return false; 2121 } 2122 2123 // C++0x [conv.prom]p2: 2124 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2125 // to an rvalue a prvalue of the first of the following types that can 2126 // represent all the values of its underlying type: int, unsigned int, 2127 // long int, unsigned long int, long long int, or unsigned long long int. 2128 // If none of the types in that list can represent all the values of its 2129 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2130 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2131 // type. 2132 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2133 ToType->isIntegerType()) { 2134 // Determine whether the type we're converting from is signed or 2135 // unsigned. 2136 bool FromIsSigned = FromType->isSignedIntegerType(); 2137 uint64_t FromSize = Context.getTypeSize(FromType); 2138 2139 // The types we'll try to promote to, in the appropriate 2140 // order. Try each of these types. 2141 QualType PromoteTypes[6] = { 2142 Context.IntTy, Context.UnsignedIntTy, 2143 Context.LongTy, Context.UnsignedLongTy , 2144 Context.LongLongTy, Context.UnsignedLongLongTy 2145 }; 2146 for (int Idx = 0; Idx < 6; ++Idx) { 2147 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2148 if (FromSize < ToSize || 2149 (FromSize == ToSize && 2150 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2151 // We found the type that we can promote to. If this is the 2152 // type we wanted, we have a promotion. Otherwise, no 2153 // promotion. 2154 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2155 } 2156 } 2157 } 2158 2159 // An rvalue for an integral bit-field (9.6) can be converted to an 2160 // rvalue of type int if int can represent all the values of the 2161 // bit-field; otherwise, it can be converted to unsigned int if 2162 // unsigned int can represent all the values of the bit-field. If 2163 // the bit-field is larger yet, no integral promotion applies to 2164 // it. If the bit-field has an enumerated type, it is treated as any 2165 // other value of that type for promotion purposes (C++ 4.5p3). 2166 // FIXME: We should delay checking of bit-fields until we actually perform the 2167 // conversion. 2168 // 2169 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2170 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2171 // bit-fields and those whose underlying type is larger than int) for GCC 2172 // compatibility. 2173 if (From) { 2174 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2175 llvm::APSInt BitWidth; 2176 if (FromType->isIntegralType(Context) && 2177 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2178 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2179 ToSize = Context.getTypeSize(ToType); 2180 2181 // Are we promoting to an int from a bitfield that fits in an int? 2182 if (BitWidth < ToSize || 2183 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2184 return To->getKind() == BuiltinType::Int; 2185 } 2186 2187 // Are we promoting to an unsigned int from an unsigned bitfield 2188 // that fits into an unsigned int? 2189 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2190 return To->getKind() == BuiltinType::UInt; 2191 } 2192 2193 return false; 2194 } 2195 } 2196 } 2197 2198 // An rvalue of type bool can be converted to an rvalue of type int, 2199 // with false becoming zero and true becoming one (C++ 4.5p4). 2200 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2201 return true; 2202 } 2203 2204 return false; 2205 } 2206 2207 /// IsFloatingPointPromotion - Determines whether the conversion from 2208 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2209 /// returns true and sets PromotedType to the promoted type. 2210 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2211 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2212 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2213 /// An rvalue of type float can be converted to an rvalue of type 2214 /// double. (C++ 4.6p1). 2215 if (FromBuiltin->getKind() == BuiltinType::Float && 2216 ToBuiltin->getKind() == BuiltinType::Double) 2217 return true; 2218 2219 // C99 6.3.1.5p1: 2220 // When a float is promoted to double or long double, or a 2221 // double is promoted to long double [...]. 2222 if (!getLangOpts().CPlusPlus && 2223 (FromBuiltin->getKind() == BuiltinType::Float || 2224 FromBuiltin->getKind() == BuiltinType::Double) && 2225 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2226 ToBuiltin->getKind() == BuiltinType::Float128)) 2227 return true; 2228 2229 // Half can be promoted to float. 2230 if (!getLangOpts().NativeHalfType && 2231 FromBuiltin->getKind() == BuiltinType::Half && 2232 ToBuiltin->getKind() == BuiltinType::Float) 2233 return true; 2234 } 2235 2236 return false; 2237 } 2238 2239 /// Determine if a conversion is a complex promotion. 2240 /// 2241 /// A complex promotion is defined as a complex -> complex conversion 2242 /// where the conversion between the underlying real types is a 2243 /// floating-point or integral promotion. 2244 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2245 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2246 if (!FromComplex) 2247 return false; 2248 2249 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2250 if (!ToComplex) 2251 return false; 2252 2253 return IsFloatingPointPromotion(FromComplex->getElementType(), 2254 ToComplex->getElementType()) || 2255 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2256 ToComplex->getElementType()); 2257 } 2258 2259 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2260 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2261 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2262 /// if non-empty, will be a pointer to ToType that may or may not have 2263 /// the right set of qualifiers on its pointee. 2264 /// 2265 static QualType 2266 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2267 QualType ToPointee, QualType ToType, 2268 ASTContext &Context, 2269 bool StripObjCLifetime = false) { 2270 assert((FromPtr->getTypeClass() == Type::Pointer || 2271 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2272 "Invalid similarly-qualified pointer type"); 2273 2274 /// Conversions to 'id' subsume cv-qualifier conversions. 2275 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2276 return ToType.getUnqualifiedType(); 2277 2278 QualType CanonFromPointee 2279 = Context.getCanonicalType(FromPtr->getPointeeType()); 2280 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2281 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2282 2283 if (StripObjCLifetime) 2284 Quals.removeObjCLifetime(); 2285 2286 // Exact qualifier match -> return the pointer type we're converting to. 2287 if (CanonToPointee.getLocalQualifiers() == Quals) { 2288 // ToType is exactly what we need. Return it. 2289 if (!ToType.isNull()) 2290 return ToType.getUnqualifiedType(); 2291 2292 // Build a pointer to ToPointee. It has the right qualifiers 2293 // already. 2294 if (isa<ObjCObjectPointerType>(ToType)) 2295 return Context.getObjCObjectPointerType(ToPointee); 2296 return Context.getPointerType(ToPointee); 2297 } 2298 2299 // Just build a canonical type that has the right qualifiers. 2300 QualType QualifiedCanonToPointee 2301 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2302 2303 if (isa<ObjCObjectPointerType>(ToType)) 2304 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2305 return Context.getPointerType(QualifiedCanonToPointee); 2306 } 2307 2308 static bool isNullPointerConstantForConversion(Expr *Expr, 2309 bool InOverloadResolution, 2310 ASTContext &Context) { 2311 // Handle value-dependent integral null pointer constants correctly. 2312 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2313 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2314 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2315 return !InOverloadResolution; 2316 2317 return Expr->isNullPointerConstant(Context, 2318 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2319 : Expr::NPC_ValueDependentIsNull); 2320 } 2321 2322 /// IsPointerConversion - Determines whether the conversion of the 2323 /// expression From, which has the (possibly adjusted) type FromType, 2324 /// can be converted to the type ToType via a pointer conversion (C++ 2325 /// 4.10). If so, returns true and places the converted type (that 2326 /// might differ from ToType in its cv-qualifiers at some level) into 2327 /// ConvertedType. 2328 /// 2329 /// This routine also supports conversions to and from block pointers 2330 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2331 /// pointers to interfaces. FIXME: Once we've determined the 2332 /// appropriate overloading rules for Objective-C, we may want to 2333 /// split the Objective-C checks into a different routine; however, 2334 /// GCC seems to consider all of these conversions to be pointer 2335 /// conversions, so for now they live here. IncompatibleObjC will be 2336 /// set if the conversion is an allowed Objective-C conversion that 2337 /// should result in a warning. 2338 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2339 bool InOverloadResolution, 2340 QualType& ConvertedType, 2341 bool &IncompatibleObjC) { 2342 IncompatibleObjC = false; 2343 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2344 IncompatibleObjC)) 2345 return true; 2346 2347 // Conversion from a null pointer constant to any Objective-C pointer type. 2348 if (ToType->isObjCObjectPointerType() && 2349 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2350 ConvertedType = ToType; 2351 return true; 2352 } 2353 2354 // Blocks: Block pointers can be converted to void*. 2355 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2356 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2357 ConvertedType = ToType; 2358 return true; 2359 } 2360 // Blocks: A null pointer constant can be converted to a block 2361 // pointer type. 2362 if (ToType->isBlockPointerType() && 2363 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2364 ConvertedType = ToType; 2365 return true; 2366 } 2367 2368 // If the left-hand-side is nullptr_t, the right side can be a null 2369 // pointer constant. 2370 if (ToType->isNullPtrType() && 2371 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2372 ConvertedType = ToType; 2373 return true; 2374 } 2375 2376 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2377 if (!ToTypePtr) 2378 return false; 2379 2380 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2381 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2382 ConvertedType = ToType; 2383 return true; 2384 } 2385 2386 // Beyond this point, both types need to be pointers 2387 // , including objective-c pointers. 2388 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2389 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2390 !getLangOpts().ObjCAutoRefCount) { 2391 ConvertedType = BuildSimilarlyQualifiedPointerType( 2392 FromType->getAs<ObjCObjectPointerType>(), 2393 ToPointeeType, 2394 ToType, Context); 2395 return true; 2396 } 2397 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2398 if (!FromTypePtr) 2399 return false; 2400 2401 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2402 2403 // If the unqualified pointee types are the same, this can't be a 2404 // pointer conversion, so don't do all of the work below. 2405 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2406 return false; 2407 2408 // An rvalue of type "pointer to cv T," where T is an object type, 2409 // can be converted to an rvalue of type "pointer to cv void" (C++ 2410 // 4.10p2). 2411 if (FromPointeeType->isIncompleteOrObjectType() && 2412 ToPointeeType->isVoidType()) { 2413 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2414 ToPointeeType, 2415 ToType, Context, 2416 /*StripObjCLifetime=*/true); 2417 return true; 2418 } 2419 2420 // MSVC allows implicit function to void* type conversion. 2421 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2422 ToPointeeType->isVoidType()) { 2423 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2424 ToPointeeType, 2425 ToType, Context); 2426 return true; 2427 } 2428 2429 // When we're overloading in C, we allow a special kind of pointer 2430 // conversion for compatible-but-not-identical pointee types. 2431 if (!getLangOpts().CPlusPlus && 2432 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2433 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2434 ToPointeeType, 2435 ToType, Context); 2436 return true; 2437 } 2438 2439 // C++ [conv.ptr]p3: 2440 // 2441 // An rvalue of type "pointer to cv D," where D is a class type, 2442 // can be converted to an rvalue of type "pointer to cv B," where 2443 // B is a base class (clause 10) of D. If B is an inaccessible 2444 // (clause 11) or ambiguous (10.2) base class of D, a program that 2445 // necessitates this conversion is ill-formed. The result of the 2446 // conversion is a pointer to the base class sub-object of the 2447 // derived class object. The null pointer value is converted to 2448 // the null pointer value of the destination type. 2449 // 2450 // Note that we do not check for ambiguity or inaccessibility 2451 // here. That is handled by CheckPointerConversion. 2452 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2453 ToPointeeType->isRecordType() && 2454 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2455 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2456 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2457 ToPointeeType, 2458 ToType, Context); 2459 return true; 2460 } 2461 2462 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2463 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2464 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2465 ToPointeeType, 2466 ToType, Context); 2467 return true; 2468 } 2469 2470 return false; 2471 } 2472 2473 /// Adopt the given qualifiers for the given type. 2474 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2475 Qualifiers TQs = T.getQualifiers(); 2476 2477 // Check whether qualifiers already match. 2478 if (TQs == Qs) 2479 return T; 2480 2481 if (Qs.compatiblyIncludes(TQs)) 2482 return Context.getQualifiedType(T, Qs); 2483 2484 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2485 } 2486 2487 /// isObjCPointerConversion - Determines whether this is an 2488 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2489 /// with the same arguments and return values. 2490 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2491 QualType& ConvertedType, 2492 bool &IncompatibleObjC) { 2493 if (!getLangOpts().ObjC) 2494 return false; 2495 2496 // The set of qualifiers on the type we're converting from. 2497 Qualifiers FromQualifiers = FromType.getQualifiers(); 2498 2499 // First, we handle all conversions on ObjC object pointer types. 2500 const ObjCObjectPointerType* ToObjCPtr = 2501 ToType->getAs<ObjCObjectPointerType>(); 2502 const ObjCObjectPointerType *FromObjCPtr = 2503 FromType->getAs<ObjCObjectPointerType>(); 2504 2505 if (ToObjCPtr && FromObjCPtr) { 2506 // If the pointee types are the same (ignoring qualifications), 2507 // then this is not a pointer conversion. 2508 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2509 FromObjCPtr->getPointeeType())) 2510 return false; 2511 2512 // Conversion between Objective-C pointers. 2513 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2514 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2515 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2516 if (getLangOpts().CPlusPlus && LHS && RHS && 2517 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2518 FromObjCPtr->getPointeeType())) 2519 return false; 2520 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2521 ToObjCPtr->getPointeeType(), 2522 ToType, Context); 2523 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2524 return true; 2525 } 2526 2527 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2528 // Okay: this is some kind of implicit downcast of Objective-C 2529 // interfaces, which is permitted. However, we're going to 2530 // complain about it. 2531 IncompatibleObjC = true; 2532 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2533 ToObjCPtr->getPointeeType(), 2534 ToType, Context); 2535 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2536 return true; 2537 } 2538 } 2539 // Beyond this point, both types need to be C pointers or block pointers. 2540 QualType ToPointeeType; 2541 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2542 ToPointeeType = ToCPtr->getPointeeType(); 2543 else if (const BlockPointerType *ToBlockPtr = 2544 ToType->getAs<BlockPointerType>()) { 2545 // Objective C++: We're able to convert from a pointer to any object 2546 // to a block pointer type. 2547 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2548 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2549 return true; 2550 } 2551 ToPointeeType = ToBlockPtr->getPointeeType(); 2552 } 2553 else if (FromType->getAs<BlockPointerType>() && 2554 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2555 // Objective C++: We're able to convert from a block pointer type to a 2556 // pointer to any object. 2557 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2558 return true; 2559 } 2560 else 2561 return false; 2562 2563 QualType FromPointeeType; 2564 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2565 FromPointeeType = FromCPtr->getPointeeType(); 2566 else if (const BlockPointerType *FromBlockPtr = 2567 FromType->getAs<BlockPointerType>()) 2568 FromPointeeType = FromBlockPtr->getPointeeType(); 2569 else 2570 return false; 2571 2572 // If we have pointers to pointers, recursively check whether this 2573 // is an Objective-C conversion. 2574 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2575 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2576 IncompatibleObjC)) { 2577 // We always complain about this conversion. 2578 IncompatibleObjC = true; 2579 ConvertedType = Context.getPointerType(ConvertedType); 2580 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2581 return true; 2582 } 2583 // Allow conversion of pointee being objective-c pointer to another one; 2584 // as in I* to id. 2585 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2586 ToPointeeType->getAs<ObjCObjectPointerType>() && 2587 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2588 IncompatibleObjC)) { 2589 2590 ConvertedType = Context.getPointerType(ConvertedType); 2591 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2592 return true; 2593 } 2594 2595 // If we have pointers to functions or blocks, check whether the only 2596 // differences in the argument and result types are in Objective-C 2597 // pointer conversions. If so, we permit the conversion (but 2598 // complain about it). 2599 const FunctionProtoType *FromFunctionType 2600 = FromPointeeType->getAs<FunctionProtoType>(); 2601 const FunctionProtoType *ToFunctionType 2602 = ToPointeeType->getAs<FunctionProtoType>(); 2603 if (FromFunctionType && ToFunctionType) { 2604 // If the function types are exactly the same, this isn't an 2605 // Objective-C pointer conversion. 2606 if (Context.getCanonicalType(FromPointeeType) 2607 == Context.getCanonicalType(ToPointeeType)) 2608 return false; 2609 2610 // Perform the quick checks that will tell us whether these 2611 // function types are obviously different. 2612 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2613 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2614 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2615 return false; 2616 2617 bool HasObjCConversion = false; 2618 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2619 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2620 // Okay, the types match exactly. Nothing to do. 2621 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2622 ToFunctionType->getReturnType(), 2623 ConvertedType, IncompatibleObjC)) { 2624 // Okay, we have an Objective-C pointer conversion. 2625 HasObjCConversion = true; 2626 } else { 2627 // Function types are too different. Abort. 2628 return false; 2629 } 2630 2631 // Check argument types. 2632 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2633 ArgIdx != NumArgs; ++ArgIdx) { 2634 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2635 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2636 if (Context.getCanonicalType(FromArgType) 2637 == Context.getCanonicalType(ToArgType)) { 2638 // Okay, the types match exactly. Nothing to do. 2639 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2640 ConvertedType, IncompatibleObjC)) { 2641 // Okay, we have an Objective-C pointer conversion. 2642 HasObjCConversion = true; 2643 } else { 2644 // Argument types are too different. Abort. 2645 return false; 2646 } 2647 } 2648 2649 if (HasObjCConversion) { 2650 // We had an Objective-C conversion. Allow this pointer 2651 // conversion, but complain about it. 2652 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2653 IncompatibleObjC = true; 2654 return true; 2655 } 2656 } 2657 2658 return false; 2659 } 2660 2661 /// Determine whether this is an Objective-C writeback conversion, 2662 /// used for parameter passing when performing automatic reference counting. 2663 /// 2664 /// \param FromType The type we're converting form. 2665 /// 2666 /// \param ToType The type we're converting to. 2667 /// 2668 /// \param ConvertedType The type that will be produced after applying 2669 /// this conversion. 2670 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2671 QualType &ConvertedType) { 2672 if (!getLangOpts().ObjCAutoRefCount || 2673 Context.hasSameUnqualifiedType(FromType, ToType)) 2674 return false; 2675 2676 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2677 QualType ToPointee; 2678 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2679 ToPointee = ToPointer->getPointeeType(); 2680 else 2681 return false; 2682 2683 Qualifiers ToQuals = ToPointee.getQualifiers(); 2684 if (!ToPointee->isObjCLifetimeType() || 2685 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2686 !ToQuals.withoutObjCLifetime().empty()) 2687 return false; 2688 2689 // Argument must be a pointer to __strong to __weak. 2690 QualType FromPointee; 2691 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2692 FromPointee = FromPointer->getPointeeType(); 2693 else 2694 return false; 2695 2696 Qualifiers FromQuals = FromPointee.getQualifiers(); 2697 if (!FromPointee->isObjCLifetimeType() || 2698 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2699 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2700 return false; 2701 2702 // Make sure that we have compatible qualifiers. 2703 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2704 if (!ToQuals.compatiblyIncludes(FromQuals)) 2705 return false; 2706 2707 // Remove qualifiers from the pointee type we're converting from; they 2708 // aren't used in the compatibility check belong, and we'll be adding back 2709 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2710 FromPointee = FromPointee.getUnqualifiedType(); 2711 2712 // The unqualified form of the pointee types must be compatible. 2713 ToPointee = ToPointee.getUnqualifiedType(); 2714 bool IncompatibleObjC; 2715 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2716 FromPointee = ToPointee; 2717 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2718 IncompatibleObjC)) 2719 return false; 2720 2721 /// Construct the type we're converting to, which is a pointer to 2722 /// __autoreleasing pointee. 2723 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2724 ConvertedType = Context.getPointerType(FromPointee); 2725 return true; 2726 } 2727 2728 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2729 QualType& ConvertedType) { 2730 QualType ToPointeeType; 2731 if (const BlockPointerType *ToBlockPtr = 2732 ToType->getAs<BlockPointerType>()) 2733 ToPointeeType = ToBlockPtr->getPointeeType(); 2734 else 2735 return false; 2736 2737 QualType FromPointeeType; 2738 if (const BlockPointerType *FromBlockPtr = 2739 FromType->getAs<BlockPointerType>()) 2740 FromPointeeType = FromBlockPtr->getPointeeType(); 2741 else 2742 return false; 2743 // We have pointer to blocks, check whether the only 2744 // differences in the argument and result types are in Objective-C 2745 // pointer conversions. If so, we permit the conversion. 2746 2747 const FunctionProtoType *FromFunctionType 2748 = FromPointeeType->getAs<FunctionProtoType>(); 2749 const FunctionProtoType *ToFunctionType 2750 = ToPointeeType->getAs<FunctionProtoType>(); 2751 2752 if (!FromFunctionType || !ToFunctionType) 2753 return false; 2754 2755 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2756 return true; 2757 2758 // Perform the quick checks that will tell us whether these 2759 // function types are obviously different. 2760 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2761 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2762 return false; 2763 2764 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2765 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2766 if (FromEInfo != ToEInfo) 2767 return false; 2768 2769 bool IncompatibleObjC = false; 2770 if (Context.hasSameType(FromFunctionType->getReturnType(), 2771 ToFunctionType->getReturnType())) { 2772 // Okay, the types match exactly. Nothing to do. 2773 } else { 2774 QualType RHS = FromFunctionType->getReturnType(); 2775 QualType LHS = ToFunctionType->getReturnType(); 2776 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2777 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2778 LHS = LHS.getUnqualifiedType(); 2779 2780 if (Context.hasSameType(RHS,LHS)) { 2781 // OK exact match. 2782 } else if (isObjCPointerConversion(RHS, LHS, 2783 ConvertedType, IncompatibleObjC)) { 2784 if (IncompatibleObjC) 2785 return false; 2786 // Okay, we have an Objective-C pointer conversion. 2787 } 2788 else 2789 return false; 2790 } 2791 2792 // Check argument types. 2793 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2794 ArgIdx != NumArgs; ++ArgIdx) { 2795 IncompatibleObjC = false; 2796 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2797 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2798 if (Context.hasSameType(FromArgType, ToArgType)) { 2799 // Okay, the types match exactly. Nothing to do. 2800 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2801 ConvertedType, IncompatibleObjC)) { 2802 if (IncompatibleObjC) 2803 return false; 2804 // Okay, we have an Objective-C pointer conversion. 2805 } else 2806 // Argument types are too different. Abort. 2807 return false; 2808 } 2809 2810 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2811 bool CanUseToFPT, CanUseFromFPT; 2812 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2813 CanUseToFPT, CanUseFromFPT, 2814 NewParamInfos)) 2815 return false; 2816 2817 ConvertedType = ToType; 2818 return true; 2819 } 2820 2821 enum { 2822 ft_default, 2823 ft_different_class, 2824 ft_parameter_arity, 2825 ft_parameter_mismatch, 2826 ft_return_type, 2827 ft_qualifer_mismatch, 2828 ft_noexcept 2829 }; 2830 2831 /// Attempts to get the FunctionProtoType from a Type. Handles 2832 /// MemberFunctionPointers properly. 2833 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2834 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2835 return FPT; 2836 2837 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2838 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2839 2840 return nullptr; 2841 } 2842 2843 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2844 /// function types. Catches different number of parameter, mismatch in 2845 /// parameter types, and different return types. 2846 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2847 QualType FromType, QualType ToType) { 2848 // If either type is not valid, include no extra info. 2849 if (FromType.isNull() || ToType.isNull()) { 2850 PDiag << ft_default; 2851 return; 2852 } 2853 2854 // Get the function type from the pointers. 2855 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2856 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2857 *ToMember = ToType->castAs<MemberPointerType>(); 2858 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2859 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2860 << QualType(FromMember->getClass(), 0); 2861 return; 2862 } 2863 FromType = FromMember->getPointeeType(); 2864 ToType = ToMember->getPointeeType(); 2865 } 2866 2867 if (FromType->isPointerType()) 2868 FromType = FromType->getPointeeType(); 2869 if (ToType->isPointerType()) 2870 ToType = ToType->getPointeeType(); 2871 2872 // Remove references. 2873 FromType = FromType.getNonReferenceType(); 2874 ToType = ToType.getNonReferenceType(); 2875 2876 // Don't print extra info for non-specialized template functions. 2877 if (FromType->isInstantiationDependentType() && 2878 !FromType->getAs<TemplateSpecializationType>()) { 2879 PDiag << ft_default; 2880 return; 2881 } 2882 2883 // No extra info for same types. 2884 if (Context.hasSameType(FromType, ToType)) { 2885 PDiag << ft_default; 2886 return; 2887 } 2888 2889 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2890 *ToFunction = tryGetFunctionProtoType(ToType); 2891 2892 // Both types need to be function types. 2893 if (!FromFunction || !ToFunction) { 2894 PDiag << ft_default; 2895 return; 2896 } 2897 2898 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2899 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2900 << FromFunction->getNumParams(); 2901 return; 2902 } 2903 2904 // Handle different parameter types. 2905 unsigned ArgPos; 2906 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2907 PDiag << ft_parameter_mismatch << ArgPos + 1 2908 << ToFunction->getParamType(ArgPos) 2909 << FromFunction->getParamType(ArgPos); 2910 return; 2911 } 2912 2913 // Handle different return type. 2914 if (!Context.hasSameType(FromFunction->getReturnType(), 2915 ToFunction->getReturnType())) { 2916 PDiag << ft_return_type << ToFunction->getReturnType() 2917 << FromFunction->getReturnType(); 2918 return; 2919 } 2920 2921 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2922 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2923 << FromFunction->getMethodQuals(); 2924 return; 2925 } 2926 2927 // Handle exception specification differences on canonical type (in C++17 2928 // onwards). 2929 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2930 ->isNothrow() != 2931 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2932 ->isNothrow()) { 2933 PDiag << ft_noexcept; 2934 return; 2935 } 2936 2937 // Unable to find a difference, so add no extra info. 2938 PDiag << ft_default; 2939 } 2940 2941 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2942 /// for equality of their argument types. Caller has already checked that 2943 /// they have same number of arguments. If the parameters are different, 2944 /// ArgPos will have the parameter index of the first different parameter. 2945 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2946 const FunctionProtoType *NewType, 2947 unsigned *ArgPos) { 2948 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2949 N = NewType->param_type_begin(), 2950 E = OldType->param_type_end(); 2951 O && (O != E); ++O, ++N) { 2952 // Ignore address spaces in pointee type. This is to disallow overloading 2953 // on __ptr32/__ptr64 address spaces. 2954 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2955 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2956 2957 if (!Context.hasSameType(Old, New)) { 2958 if (ArgPos) 2959 *ArgPos = O - OldType->param_type_begin(); 2960 return false; 2961 } 2962 } 2963 return true; 2964 } 2965 2966 /// CheckPointerConversion - Check the pointer conversion from the 2967 /// expression From to the type ToType. This routine checks for 2968 /// ambiguous or inaccessible derived-to-base pointer 2969 /// conversions for which IsPointerConversion has already returned 2970 /// true. It returns true and produces a diagnostic if there was an 2971 /// error, or returns false otherwise. 2972 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2973 CastKind &Kind, 2974 CXXCastPath& BasePath, 2975 bool IgnoreBaseAccess, 2976 bool Diagnose) { 2977 QualType FromType = From->getType(); 2978 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2979 2980 Kind = CK_BitCast; 2981 2982 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2983 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2984 Expr::NPCK_ZeroExpression) { 2985 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2986 DiagRuntimeBehavior(From->getExprLoc(), From, 2987 PDiag(diag::warn_impcast_bool_to_null_pointer) 2988 << ToType << From->getSourceRange()); 2989 else if (!isUnevaluatedContext()) 2990 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2991 << ToType << From->getSourceRange(); 2992 } 2993 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2994 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2995 QualType FromPointeeType = FromPtrType->getPointeeType(), 2996 ToPointeeType = ToPtrType->getPointeeType(); 2997 2998 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2999 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3000 // We must have a derived-to-base conversion. Check an 3001 // ambiguous or inaccessible conversion. 3002 unsigned InaccessibleID = 0; 3003 unsigned AmbigiousID = 0; 3004 if (Diagnose) { 3005 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3006 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 3007 } 3008 if (CheckDerivedToBaseConversion( 3009 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 3010 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3011 &BasePath, IgnoreBaseAccess)) 3012 return true; 3013 3014 // The conversion was successful. 3015 Kind = CK_DerivedToBase; 3016 } 3017 3018 if (Diagnose && !IsCStyleOrFunctionalCast && 3019 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3020 assert(getLangOpts().MSVCCompat && 3021 "this should only be possible with MSVCCompat!"); 3022 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3023 << From->getSourceRange(); 3024 } 3025 } 3026 } else if (const ObjCObjectPointerType *ToPtrType = 3027 ToType->getAs<ObjCObjectPointerType>()) { 3028 if (const ObjCObjectPointerType *FromPtrType = 3029 FromType->getAs<ObjCObjectPointerType>()) { 3030 // Objective-C++ conversions are always okay. 3031 // FIXME: We should have a different class of conversions for the 3032 // Objective-C++ implicit conversions. 3033 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3034 return false; 3035 } else if (FromType->isBlockPointerType()) { 3036 Kind = CK_BlockPointerToObjCPointerCast; 3037 } else { 3038 Kind = CK_CPointerToObjCPointerCast; 3039 } 3040 } else if (ToType->isBlockPointerType()) { 3041 if (!FromType->isBlockPointerType()) 3042 Kind = CK_AnyPointerToBlockPointerCast; 3043 } 3044 3045 // We shouldn't fall into this case unless it's valid for other 3046 // reasons. 3047 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3048 Kind = CK_NullToPointer; 3049 3050 return false; 3051 } 3052 3053 /// IsMemberPointerConversion - Determines whether the conversion of the 3054 /// expression From, which has the (possibly adjusted) type FromType, can be 3055 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3056 /// If so, returns true and places the converted type (that might differ from 3057 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3058 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3059 QualType ToType, 3060 bool InOverloadResolution, 3061 QualType &ConvertedType) { 3062 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3063 if (!ToTypePtr) 3064 return false; 3065 3066 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3067 if (From->isNullPointerConstant(Context, 3068 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3069 : Expr::NPC_ValueDependentIsNull)) { 3070 ConvertedType = ToType; 3071 return true; 3072 } 3073 3074 // Otherwise, both types have to be member pointers. 3075 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3076 if (!FromTypePtr) 3077 return false; 3078 3079 // A pointer to member of B can be converted to a pointer to member of D, 3080 // where D is derived from B (C++ 4.11p2). 3081 QualType FromClass(FromTypePtr->getClass(), 0); 3082 QualType ToClass(ToTypePtr->getClass(), 0); 3083 3084 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3085 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3086 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3087 ToClass.getTypePtr()); 3088 return true; 3089 } 3090 3091 return false; 3092 } 3093 3094 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3095 /// expression From to the type ToType. This routine checks for ambiguous or 3096 /// virtual or inaccessible base-to-derived member pointer conversions 3097 /// for which IsMemberPointerConversion has already returned true. It returns 3098 /// true and produces a diagnostic if there was an error, or returns false 3099 /// otherwise. 3100 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3101 CastKind &Kind, 3102 CXXCastPath &BasePath, 3103 bool IgnoreBaseAccess) { 3104 QualType FromType = From->getType(); 3105 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3106 if (!FromPtrType) { 3107 // This must be a null pointer to member pointer conversion 3108 assert(From->isNullPointerConstant(Context, 3109 Expr::NPC_ValueDependentIsNull) && 3110 "Expr must be null pointer constant!"); 3111 Kind = CK_NullToMemberPointer; 3112 return false; 3113 } 3114 3115 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3116 assert(ToPtrType && "No member pointer cast has a target type " 3117 "that is not a member pointer."); 3118 3119 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3120 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3121 3122 // FIXME: What about dependent types? 3123 assert(FromClass->isRecordType() && "Pointer into non-class."); 3124 assert(ToClass->isRecordType() && "Pointer into non-class."); 3125 3126 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3127 /*DetectVirtual=*/true); 3128 bool DerivationOkay = 3129 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3130 assert(DerivationOkay && 3131 "Should not have been called if derivation isn't OK."); 3132 (void)DerivationOkay; 3133 3134 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3135 getUnqualifiedType())) { 3136 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3137 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3138 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3139 return true; 3140 } 3141 3142 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3143 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3144 << FromClass << ToClass << QualType(VBase, 0) 3145 << From->getSourceRange(); 3146 return true; 3147 } 3148 3149 if (!IgnoreBaseAccess) 3150 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3151 Paths.front(), 3152 diag::err_downcast_from_inaccessible_base); 3153 3154 // Must be a base to derived member conversion. 3155 BuildBasePathArray(Paths, BasePath); 3156 Kind = CK_BaseToDerivedMemberPointer; 3157 return false; 3158 } 3159 3160 /// Determine whether the lifetime conversion between the two given 3161 /// qualifiers sets is nontrivial. 3162 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3163 Qualifiers ToQuals) { 3164 // Converting anything to const __unsafe_unretained is trivial. 3165 if (ToQuals.hasConst() && 3166 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3167 return false; 3168 3169 return true; 3170 } 3171 3172 /// Perform a single iteration of the loop for checking if a qualification 3173 /// conversion is valid. 3174 /// 3175 /// Specifically, check whether any change between the qualifiers of \p 3176 /// FromType and \p ToType is permissible, given knowledge about whether every 3177 /// outer layer is const-qualified. 3178 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3179 bool CStyle, 3180 bool &PreviousToQualsIncludeConst, 3181 bool &ObjCLifetimeConversion) { 3182 Qualifiers FromQuals = FromType.getQualifiers(); 3183 Qualifiers ToQuals = ToType.getQualifiers(); 3184 3185 // Ignore __unaligned qualifier if this type is void. 3186 if (ToType.getUnqualifiedType()->isVoidType()) 3187 FromQuals.removeUnaligned(); 3188 3189 // Objective-C ARC: 3190 // Check Objective-C lifetime conversions. 3191 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3192 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3193 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3194 ObjCLifetimeConversion = true; 3195 FromQuals.removeObjCLifetime(); 3196 ToQuals.removeObjCLifetime(); 3197 } else { 3198 // Qualification conversions cannot cast between different 3199 // Objective-C lifetime qualifiers. 3200 return false; 3201 } 3202 } 3203 3204 // Allow addition/removal of GC attributes but not changing GC attributes. 3205 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3206 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3207 FromQuals.removeObjCGCAttr(); 3208 ToQuals.removeObjCGCAttr(); 3209 } 3210 3211 // -- for every j > 0, if const is in cv 1,j then const is in cv 3212 // 2,j, and similarly for volatile. 3213 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3214 return false; 3215 3216 // For a C-style cast, just require the address spaces to overlap. 3217 // FIXME: Does "superset" also imply the representation of a pointer is the 3218 // same? We're assuming that it does here and in compatiblyIncludes. 3219 if (CStyle && !ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3220 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) 3221 return false; 3222 3223 // -- if the cv 1,j and cv 2,j are different, then const is in 3224 // every cv for 0 < k < j. 3225 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3226 !PreviousToQualsIncludeConst) 3227 return false; 3228 3229 // Keep track of whether all prior cv-qualifiers in the "to" type 3230 // include const. 3231 PreviousToQualsIncludeConst = 3232 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3233 return true; 3234 } 3235 3236 /// IsQualificationConversion - Determines whether the conversion from 3237 /// an rvalue of type FromType to ToType is a qualification conversion 3238 /// (C++ 4.4). 3239 /// 3240 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3241 /// when the qualification conversion involves a change in the Objective-C 3242 /// object lifetime. 3243 bool 3244 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3245 bool CStyle, bool &ObjCLifetimeConversion) { 3246 FromType = Context.getCanonicalType(FromType); 3247 ToType = Context.getCanonicalType(ToType); 3248 ObjCLifetimeConversion = false; 3249 3250 // If FromType and ToType are the same type, this is not a 3251 // qualification conversion. 3252 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3253 return false; 3254 3255 // (C++ 4.4p4): 3256 // A conversion can add cv-qualifiers at levels other than the first 3257 // in multi-level pointers, subject to the following rules: [...] 3258 bool PreviousToQualsIncludeConst = true; 3259 bool UnwrappedAnyPointer = false; 3260 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3261 if (!isQualificationConversionStep(FromType, ToType, CStyle, 3262 PreviousToQualsIncludeConst, 3263 ObjCLifetimeConversion)) 3264 return false; 3265 UnwrappedAnyPointer = true; 3266 } 3267 3268 // We are left with FromType and ToType being the pointee types 3269 // after unwrapping the original FromType and ToType the same number 3270 // of times. If we unwrapped any pointers, and if FromType and 3271 // ToType have the same unqualified type (since we checked 3272 // qualifiers above), then this is a qualification conversion. 3273 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3274 } 3275 3276 /// - Determine whether this is a conversion from a scalar type to an 3277 /// atomic type. 3278 /// 3279 /// If successful, updates \c SCS's second and third steps in the conversion 3280 /// sequence to finish the conversion. 3281 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3282 bool InOverloadResolution, 3283 StandardConversionSequence &SCS, 3284 bool CStyle) { 3285 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3286 if (!ToAtomic) 3287 return false; 3288 3289 StandardConversionSequence InnerSCS; 3290 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3291 InOverloadResolution, InnerSCS, 3292 CStyle, /*AllowObjCWritebackConversion=*/false)) 3293 return false; 3294 3295 SCS.Second = InnerSCS.Second; 3296 SCS.setToType(1, InnerSCS.getToType(1)); 3297 SCS.Third = InnerSCS.Third; 3298 SCS.QualificationIncludesObjCLifetime 3299 = InnerSCS.QualificationIncludesObjCLifetime; 3300 SCS.setToType(2, InnerSCS.getToType(2)); 3301 return true; 3302 } 3303 3304 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3305 CXXConstructorDecl *Constructor, 3306 QualType Type) { 3307 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3308 if (CtorType->getNumParams() > 0) { 3309 QualType FirstArg = CtorType->getParamType(0); 3310 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3311 return true; 3312 } 3313 return false; 3314 } 3315 3316 static OverloadingResult 3317 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3318 CXXRecordDecl *To, 3319 UserDefinedConversionSequence &User, 3320 OverloadCandidateSet &CandidateSet, 3321 bool AllowExplicit) { 3322 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3323 for (auto *D : S.LookupConstructors(To)) { 3324 auto Info = getConstructorInfo(D); 3325 if (!Info) 3326 continue; 3327 3328 bool Usable = !Info.Constructor->isInvalidDecl() && 3329 S.isInitListConstructor(Info.Constructor); 3330 if (Usable) { 3331 // If the first argument is (a reference to) the target type, 3332 // suppress conversions. 3333 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3334 S.Context, Info.Constructor, ToType); 3335 if (Info.ConstructorTmpl) 3336 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3337 /*ExplicitArgs*/ nullptr, From, 3338 CandidateSet, SuppressUserConversions, 3339 /*PartialOverloading*/ false, 3340 AllowExplicit); 3341 else 3342 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3343 CandidateSet, SuppressUserConversions, 3344 /*PartialOverloading*/ false, AllowExplicit); 3345 } 3346 } 3347 3348 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3349 3350 OverloadCandidateSet::iterator Best; 3351 switch (auto Result = 3352 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3353 case OR_Deleted: 3354 case OR_Success: { 3355 // Record the standard conversion we used and the conversion function. 3356 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3357 QualType ThisType = Constructor->getThisType(); 3358 // Initializer lists don't have conversions as such. 3359 User.Before.setAsIdentityConversion(); 3360 User.HadMultipleCandidates = HadMultipleCandidates; 3361 User.ConversionFunction = Constructor; 3362 User.FoundConversionFunction = Best->FoundDecl; 3363 User.After.setAsIdentityConversion(); 3364 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3365 User.After.setAllToTypes(ToType); 3366 return Result; 3367 } 3368 3369 case OR_No_Viable_Function: 3370 return OR_No_Viable_Function; 3371 case OR_Ambiguous: 3372 return OR_Ambiguous; 3373 } 3374 3375 llvm_unreachable("Invalid OverloadResult!"); 3376 } 3377 3378 /// Determines whether there is a user-defined conversion sequence 3379 /// (C++ [over.ics.user]) that converts expression From to the type 3380 /// ToType. If such a conversion exists, User will contain the 3381 /// user-defined conversion sequence that performs such a conversion 3382 /// and this routine will return true. Otherwise, this routine returns 3383 /// false and User is unspecified. 3384 /// 3385 /// \param AllowExplicit true if the conversion should consider C++0x 3386 /// "explicit" conversion functions as well as non-explicit conversion 3387 /// functions (C++0x [class.conv.fct]p2). 3388 /// 3389 /// \param AllowObjCConversionOnExplicit true if the conversion should 3390 /// allow an extra Objective-C pointer conversion on uses of explicit 3391 /// constructors. Requires \c AllowExplicit to also be set. 3392 static OverloadingResult 3393 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3394 UserDefinedConversionSequence &User, 3395 OverloadCandidateSet &CandidateSet, 3396 bool AllowExplicit, 3397 bool AllowObjCConversionOnExplicit) { 3398 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3399 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3400 3401 // Whether we will only visit constructors. 3402 bool ConstructorsOnly = false; 3403 3404 // If the type we are conversion to is a class type, enumerate its 3405 // constructors. 3406 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3407 // C++ [over.match.ctor]p1: 3408 // When objects of class type are direct-initialized (8.5), or 3409 // copy-initialized from an expression of the same or a 3410 // derived class type (8.5), overload resolution selects the 3411 // constructor. [...] For copy-initialization, the candidate 3412 // functions are all the converting constructors (12.3.1) of 3413 // that class. The argument list is the expression-list within 3414 // the parentheses of the initializer. 3415 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3416 (From->getType()->getAs<RecordType>() && 3417 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3418 ConstructorsOnly = true; 3419 3420 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3421 // We're not going to find any constructors. 3422 } else if (CXXRecordDecl *ToRecordDecl 3423 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3424 3425 Expr **Args = &From; 3426 unsigned NumArgs = 1; 3427 bool ListInitializing = false; 3428 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3429 // But first, see if there is an init-list-constructor that will work. 3430 OverloadingResult Result = IsInitializerListConstructorConversion( 3431 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3432 if (Result != OR_No_Viable_Function) 3433 return Result; 3434 // Never mind. 3435 CandidateSet.clear( 3436 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3437 3438 // If we're list-initializing, we pass the individual elements as 3439 // arguments, not the entire list. 3440 Args = InitList->getInits(); 3441 NumArgs = InitList->getNumInits(); 3442 ListInitializing = true; 3443 } 3444 3445 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3446 auto Info = getConstructorInfo(D); 3447 if (!Info) 3448 continue; 3449 3450 bool Usable = !Info.Constructor->isInvalidDecl(); 3451 if (!ListInitializing) 3452 Usable = Usable && Info.Constructor->isConvertingConstructor( 3453 /*AllowExplicit*/ true); 3454 if (Usable) { 3455 bool SuppressUserConversions = !ConstructorsOnly; 3456 if (SuppressUserConversions && ListInitializing) { 3457 SuppressUserConversions = false; 3458 if (NumArgs == 1) { 3459 // If the first argument is (a reference to) the target type, 3460 // suppress conversions. 3461 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3462 S.Context, Info.Constructor, ToType); 3463 } 3464 } 3465 if (Info.ConstructorTmpl) 3466 S.AddTemplateOverloadCandidate( 3467 Info.ConstructorTmpl, Info.FoundDecl, 3468 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3469 CandidateSet, SuppressUserConversions, 3470 /*PartialOverloading*/ false, AllowExplicit); 3471 else 3472 // Allow one user-defined conversion when user specifies a 3473 // From->ToType conversion via an static cast (c-style, etc). 3474 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3475 llvm::makeArrayRef(Args, NumArgs), 3476 CandidateSet, SuppressUserConversions, 3477 /*PartialOverloading*/ false, AllowExplicit); 3478 } 3479 } 3480 } 3481 } 3482 3483 // Enumerate conversion functions, if we're allowed to. 3484 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3485 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3486 // No conversion functions from incomplete types. 3487 } else if (const RecordType *FromRecordType = 3488 From->getType()->getAs<RecordType>()) { 3489 if (CXXRecordDecl *FromRecordDecl 3490 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3491 // Add all of the conversion functions as candidates. 3492 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3493 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3494 DeclAccessPair FoundDecl = I.getPair(); 3495 NamedDecl *D = FoundDecl.getDecl(); 3496 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3497 if (isa<UsingShadowDecl>(D)) 3498 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3499 3500 CXXConversionDecl *Conv; 3501 FunctionTemplateDecl *ConvTemplate; 3502 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3503 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3504 else 3505 Conv = cast<CXXConversionDecl>(D); 3506 3507 if (ConvTemplate) 3508 S.AddTemplateConversionCandidate( 3509 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3510 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit); 3511 else 3512 S.AddConversionCandidate( 3513 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet, 3514 AllowObjCConversionOnExplicit, AllowExplicit); 3515 } 3516 } 3517 } 3518 3519 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3520 3521 OverloadCandidateSet::iterator Best; 3522 switch (auto Result = 3523 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3524 case OR_Success: 3525 case OR_Deleted: 3526 // Record the standard conversion we used and the conversion function. 3527 if (CXXConstructorDecl *Constructor 3528 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3529 // C++ [over.ics.user]p1: 3530 // If the user-defined conversion is specified by a 3531 // constructor (12.3.1), the initial standard conversion 3532 // sequence converts the source type to the type required by 3533 // the argument of the constructor. 3534 // 3535 QualType ThisType = Constructor->getThisType(); 3536 if (isa<InitListExpr>(From)) { 3537 // Initializer lists don't have conversions as such. 3538 User.Before.setAsIdentityConversion(); 3539 } else { 3540 if (Best->Conversions[0].isEllipsis()) 3541 User.EllipsisConversion = true; 3542 else { 3543 User.Before = Best->Conversions[0].Standard; 3544 User.EllipsisConversion = false; 3545 } 3546 } 3547 User.HadMultipleCandidates = HadMultipleCandidates; 3548 User.ConversionFunction = Constructor; 3549 User.FoundConversionFunction = Best->FoundDecl; 3550 User.After.setAsIdentityConversion(); 3551 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3552 User.After.setAllToTypes(ToType); 3553 return Result; 3554 } 3555 if (CXXConversionDecl *Conversion 3556 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3557 // C++ [over.ics.user]p1: 3558 // 3559 // [...] If the user-defined conversion is specified by a 3560 // conversion function (12.3.2), the initial standard 3561 // conversion sequence converts the source type to the 3562 // implicit object parameter of the conversion function. 3563 User.Before = Best->Conversions[0].Standard; 3564 User.HadMultipleCandidates = HadMultipleCandidates; 3565 User.ConversionFunction = Conversion; 3566 User.FoundConversionFunction = Best->FoundDecl; 3567 User.EllipsisConversion = false; 3568 3569 // C++ [over.ics.user]p2: 3570 // The second standard conversion sequence converts the 3571 // result of the user-defined conversion to the target type 3572 // for the sequence. Since an implicit conversion sequence 3573 // is an initialization, the special rules for 3574 // initialization by user-defined conversion apply when 3575 // selecting the best user-defined conversion for a 3576 // user-defined conversion sequence (see 13.3.3 and 3577 // 13.3.3.1). 3578 User.After = Best->FinalConversion; 3579 return Result; 3580 } 3581 llvm_unreachable("Not a constructor or conversion function?"); 3582 3583 case OR_No_Viable_Function: 3584 return OR_No_Viable_Function; 3585 3586 case OR_Ambiguous: 3587 return OR_Ambiguous; 3588 } 3589 3590 llvm_unreachable("Invalid OverloadResult!"); 3591 } 3592 3593 bool 3594 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3595 ImplicitConversionSequence ICS; 3596 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3597 OverloadCandidateSet::CSK_Normal); 3598 OverloadingResult OvResult = 3599 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3600 CandidateSet, false, false); 3601 3602 if (!(OvResult == OR_Ambiguous || 3603 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3604 return false; 3605 3606 auto Cands = CandidateSet.CompleteCandidates( 3607 *this, 3608 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3609 From); 3610 if (OvResult == OR_Ambiguous) 3611 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3612 << From->getType() << ToType << From->getSourceRange(); 3613 else { // OR_No_Viable_Function && !CandidateSet.empty() 3614 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3615 diag::err_typecheck_nonviable_condition_incomplete, 3616 From->getType(), From->getSourceRange())) 3617 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3618 << false << From->getType() << From->getSourceRange() << ToType; 3619 } 3620 3621 CandidateSet.NoteCandidates( 3622 *this, From, Cands); 3623 return true; 3624 } 3625 3626 /// Compare the user-defined conversion functions or constructors 3627 /// of two user-defined conversion sequences to determine whether any ordering 3628 /// is possible. 3629 static ImplicitConversionSequence::CompareKind 3630 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3631 FunctionDecl *Function2) { 3632 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3633 return ImplicitConversionSequence::Indistinguishable; 3634 3635 // Objective-C++: 3636 // If both conversion functions are implicitly-declared conversions from 3637 // a lambda closure type to a function pointer and a block pointer, 3638 // respectively, always prefer the conversion to a function pointer, 3639 // because the function pointer is more lightweight and is more likely 3640 // to keep code working. 3641 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3642 if (!Conv1) 3643 return ImplicitConversionSequence::Indistinguishable; 3644 3645 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3646 if (!Conv2) 3647 return ImplicitConversionSequence::Indistinguishable; 3648 3649 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3650 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3651 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3652 if (Block1 != Block2) 3653 return Block1 ? ImplicitConversionSequence::Worse 3654 : ImplicitConversionSequence::Better; 3655 } 3656 3657 return ImplicitConversionSequence::Indistinguishable; 3658 } 3659 3660 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3661 const ImplicitConversionSequence &ICS) { 3662 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3663 (ICS.isUserDefined() && 3664 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3665 } 3666 3667 /// CompareImplicitConversionSequences - Compare two implicit 3668 /// conversion sequences to determine whether one is better than the 3669 /// other or if they are indistinguishable (C++ 13.3.3.2). 3670 static ImplicitConversionSequence::CompareKind 3671 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3672 const ImplicitConversionSequence& ICS1, 3673 const ImplicitConversionSequence& ICS2) 3674 { 3675 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3676 // conversion sequences (as defined in 13.3.3.1) 3677 // -- a standard conversion sequence (13.3.3.1.1) is a better 3678 // conversion sequence than a user-defined conversion sequence or 3679 // an ellipsis conversion sequence, and 3680 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3681 // conversion sequence than an ellipsis conversion sequence 3682 // (13.3.3.1.3). 3683 // 3684 // C++0x [over.best.ics]p10: 3685 // For the purpose of ranking implicit conversion sequences as 3686 // described in 13.3.3.2, the ambiguous conversion sequence is 3687 // treated as a user-defined sequence that is indistinguishable 3688 // from any other user-defined conversion sequence. 3689 3690 // String literal to 'char *' conversion has been deprecated in C++03. It has 3691 // been removed from C++11. We still accept this conversion, if it happens at 3692 // the best viable function. Otherwise, this conversion is considered worse 3693 // than ellipsis conversion. Consider this as an extension; this is not in the 3694 // standard. For example: 3695 // 3696 // int &f(...); // #1 3697 // void f(char*); // #2 3698 // void g() { int &r = f("foo"); } 3699 // 3700 // In C++03, we pick #2 as the best viable function. 3701 // In C++11, we pick #1 as the best viable function, because ellipsis 3702 // conversion is better than string-literal to char* conversion (since there 3703 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3704 // convert arguments, #2 would be the best viable function in C++11. 3705 // If the best viable function has this conversion, a warning will be issued 3706 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3707 3708 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3709 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3710 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3711 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3712 ? ImplicitConversionSequence::Worse 3713 : ImplicitConversionSequence::Better; 3714 3715 if (ICS1.getKindRank() < ICS2.getKindRank()) 3716 return ImplicitConversionSequence::Better; 3717 if (ICS2.getKindRank() < ICS1.getKindRank()) 3718 return ImplicitConversionSequence::Worse; 3719 3720 // The following checks require both conversion sequences to be of 3721 // the same kind. 3722 if (ICS1.getKind() != ICS2.getKind()) 3723 return ImplicitConversionSequence::Indistinguishable; 3724 3725 ImplicitConversionSequence::CompareKind Result = 3726 ImplicitConversionSequence::Indistinguishable; 3727 3728 // Two implicit conversion sequences of the same form are 3729 // indistinguishable conversion sequences unless one of the 3730 // following rules apply: (C++ 13.3.3.2p3): 3731 3732 // List-initialization sequence L1 is a better conversion sequence than 3733 // list-initialization sequence L2 if: 3734 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3735 // if not that, 3736 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3737 // and N1 is smaller than N2., 3738 // even if one of the other rules in this paragraph would otherwise apply. 3739 if (!ICS1.isBad()) { 3740 if (ICS1.isStdInitializerListElement() && 3741 !ICS2.isStdInitializerListElement()) 3742 return ImplicitConversionSequence::Better; 3743 if (!ICS1.isStdInitializerListElement() && 3744 ICS2.isStdInitializerListElement()) 3745 return ImplicitConversionSequence::Worse; 3746 } 3747 3748 if (ICS1.isStandard()) 3749 // Standard conversion sequence S1 is a better conversion sequence than 3750 // standard conversion sequence S2 if [...] 3751 Result = CompareStandardConversionSequences(S, Loc, 3752 ICS1.Standard, ICS2.Standard); 3753 else if (ICS1.isUserDefined()) { 3754 // User-defined conversion sequence U1 is a better conversion 3755 // sequence than another user-defined conversion sequence U2 if 3756 // they contain the same user-defined conversion function or 3757 // constructor and if the second standard conversion sequence of 3758 // U1 is better than the second standard conversion sequence of 3759 // U2 (C++ 13.3.3.2p3). 3760 if (ICS1.UserDefined.ConversionFunction == 3761 ICS2.UserDefined.ConversionFunction) 3762 Result = CompareStandardConversionSequences(S, Loc, 3763 ICS1.UserDefined.After, 3764 ICS2.UserDefined.After); 3765 else 3766 Result = compareConversionFunctions(S, 3767 ICS1.UserDefined.ConversionFunction, 3768 ICS2.UserDefined.ConversionFunction); 3769 } 3770 3771 return Result; 3772 } 3773 3774 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3775 // determine if one is a proper subset of the other. 3776 static ImplicitConversionSequence::CompareKind 3777 compareStandardConversionSubsets(ASTContext &Context, 3778 const StandardConversionSequence& SCS1, 3779 const StandardConversionSequence& SCS2) { 3780 ImplicitConversionSequence::CompareKind Result 3781 = ImplicitConversionSequence::Indistinguishable; 3782 3783 // the identity conversion sequence is considered to be a subsequence of 3784 // any non-identity conversion sequence 3785 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3786 return ImplicitConversionSequence::Better; 3787 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3788 return ImplicitConversionSequence::Worse; 3789 3790 if (SCS1.Second != SCS2.Second) { 3791 if (SCS1.Second == ICK_Identity) 3792 Result = ImplicitConversionSequence::Better; 3793 else if (SCS2.Second == ICK_Identity) 3794 Result = ImplicitConversionSequence::Worse; 3795 else 3796 return ImplicitConversionSequence::Indistinguishable; 3797 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3798 return ImplicitConversionSequence::Indistinguishable; 3799 3800 if (SCS1.Third == SCS2.Third) { 3801 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3802 : ImplicitConversionSequence::Indistinguishable; 3803 } 3804 3805 if (SCS1.Third == ICK_Identity) 3806 return Result == ImplicitConversionSequence::Worse 3807 ? ImplicitConversionSequence::Indistinguishable 3808 : ImplicitConversionSequence::Better; 3809 3810 if (SCS2.Third == ICK_Identity) 3811 return Result == ImplicitConversionSequence::Better 3812 ? ImplicitConversionSequence::Indistinguishable 3813 : ImplicitConversionSequence::Worse; 3814 3815 return ImplicitConversionSequence::Indistinguishable; 3816 } 3817 3818 /// Determine whether one of the given reference bindings is better 3819 /// than the other based on what kind of bindings they are. 3820 static bool 3821 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3822 const StandardConversionSequence &SCS2) { 3823 // C++0x [over.ics.rank]p3b4: 3824 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3825 // implicit object parameter of a non-static member function declared 3826 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3827 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3828 // lvalue reference to a function lvalue and S2 binds an rvalue 3829 // reference*. 3830 // 3831 // FIXME: Rvalue references. We're going rogue with the above edits, 3832 // because the semantics in the current C++0x working paper (N3225 at the 3833 // time of this writing) break the standard definition of std::forward 3834 // and std::reference_wrapper when dealing with references to functions. 3835 // Proposed wording changes submitted to CWG for consideration. 3836 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3837 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3838 return false; 3839 3840 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3841 SCS2.IsLvalueReference) || 3842 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3843 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3844 } 3845 3846 enum class FixedEnumPromotion { 3847 None, 3848 ToUnderlyingType, 3849 ToPromotedUnderlyingType 3850 }; 3851 3852 /// Returns kind of fixed enum promotion the \a SCS uses. 3853 static FixedEnumPromotion 3854 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3855 3856 if (SCS.Second != ICK_Integral_Promotion) 3857 return FixedEnumPromotion::None; 3858 3859 QualType FromType = SCS.getFromType(); 3860 if (!FromType->isEnumeralType()) 3861 return FixedEnumPromotion::None; 3862 3863 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3864 if (!Enum->isFixed()) 3865 return FixedEnumPromotion::None; 3866 3867 QualType UnderlyingType = Enum->getIntegerType(); 3868 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3869 return FixedEnumPromotion::ToUnderlyingType; 3870 3871 return FixedEnumPromotion::ToPromotedUnderlyingType; 3872 } 3873 3874 /// CompareStandardConversionSequences - Compare two standard 3875 /// conversion sequences to determine whether one is better than the 3876 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3877 static ImplicitConversionSequence::CompareKind 3878 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3879 const StandardConversionSequence& SCS1, 3880 const StandardConversionSequence& SCS2) 3881 { 3882 // Standard conversion sequence S1 is a better conversion sequence 3883 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3884 3885 // -- S1 is a proper subsequence of S2 (comparing the conversion 3886 // sequences in the canonical form defined by 13.3.3.1.1, 3887 // excluding any Lvalue Transformation; the identity conversion 3888 // sequence is considered to be a subsequence of any 3889 // non-identity conversion sequence) or, if not that, 3890 if (ImplicitConversionSequence::CompareKind CK 3891 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3892 return CK; 3893 3894 // -- the rank of S1 is better than the rank of S2 (by the rules 3895 // defined below), or, if not that, 3896 ImplicitConversionRank Rank1 = SCS1.getRank(); 3897 ImplicitConversionRank Rank2 = SCS2.getRank(); 3898 if (Rank1 < Rank2) 3899 return ImplicitConversionSequence::Better; 3900 else if (Rank2 < Rank1) 3901 return ImplicitConversionSequence::Worse; 3902 3903 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3904 // are indistinguishable unless one of the following rules 3905 // applies: 3906 3907 // A conversion that is not a conversion of a pointer, or 3908 // pointer to member, to bool is better than another conversion 3909 // that is such a conversion. 3910 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3911 return SCS2.isPointerConversionToBool() 3912 ? ImplicitConversionSequence::Better 3913 : ImplicitConversionSequence::Worse; 3914 3915 // C++14 [over.ics.rank]p4b2: 3916 // This is retroactively applied to C++11 by CWG 1601. 3917 // 3918 // A conversion that promotes an enumeration whose underlying type is fixed 3919 // to its underlying type is better than one that promotes to the promoted 3920 // underlying type, if the two are different. 3921 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3922 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3923 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3924 FEP1 != FEP2) 3925 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3926 ? ImplicitConversionSequence::Better 3927 : ImplicitConversionSequence::Worse; 3928 3929 // C++ [over.ics.rank]p4b2: 3930 // 3931 // If class B is derived directly or indirectly from class A, 3932 // conversion of B* to A* is better than conversion of B* to 3933 // void*, and conversion of A* to void* is better than conversion 3934 // of B* to void*. 3935 bool SCS1ConvertsToVoid 3936 = SCS1.isPointerConversionToVoidPointer(S.Context); 3937 bool SCS2ConvertsToVoid 3938 = SCS2.isPointerConversionToVoidPointer(S.Context); 3939 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3940 // Exactly one of the conversion sequences is a conversion to 3941 // a void pointer; it's the worse conversion. 3942 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3943 : ImplicitConversionSequence::Worse; 3944 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3945 // Neither conversion sequence converts to a void pointer; compare 3946 // their derived-to-base conversions. 3947 if (ImplicitConversionSequence::CompareKind DerivedCK 3948 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3949 return DerivedCK; 3950 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3951 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3952 // Both conversion sequences are conversions to void 3953 // pointers. Compare the source types to determine if there's an 3954 // inheritance relationship in their sources. 3955 QualType FromType1 = SCS1.getFromType(); 3956 QualType FromType2 = SCS2.getFromType(); 3957 3958 // Adjust the types we're converting from via the array-to-pointer 3959 // conversion, if we need to. 3960 if (SCS1.First == ICK_Array_To_Pointer) 3961 FromType1 = S.Context.getArrayDecayedType(FromType1); 3962 if (SCS2.First == ICK_Array_To_Pointer) 3963 FromType2 = S.Context.getArrayDecayedType(FromType2); 3964 3965 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3966 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3967 3968 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3969 return ImplicitConversionSequence::Better; 3970 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3971 return ImplicitConversionSequence::Worse; 3972 3973 // Objective-C++: If one interface is more specific than the 3974 // other, it is the better one. 3975 const ObjCObjectPointerType* FromObjCPtr1 3976 = FromType1->getAs<ObjCObjectPointerType>(); 3977 const ObjCObjectPointerType* FromObjCPtr2 3978 = FromType2->getAs<ObjCObjectPointerType>(); 3979 if (FromObjCPtr1 && FromObjCPtr2) { 3980 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3981 FromObjCPtr2); 3982 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3983 FromObjCPtr1); 3984 if (AssignLeft != AssignRight) { 3985 return AssignLeft? ImplicitConversionSequence::Better 3986 : ImplicitConversionSequence::Worse; 3987 } 3988 } 3989 } 3990 3991 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3992 // Check for a better reference binding based on the kind of bindings. 3993 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3994 return ImplicitConversionSequence::Better; 3995 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3996 return ImplicitConversionSequence::Worse; 3997 } 3998 3999 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4000 // bullet 3). 4001 if (ImplicitConversionSequence::CompareKind QualCK 4002 = CompareQualificationConversions(S, SCS1, SCS2)) 4003 return QualCK; 4004 4005 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4006 // C++ [over.ics.rank]p3b4: 4007 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4008 // which the references refer are the same type except for 4009 // top-level cv-qualifiers, and the type to which the reference 4010 // initialized by S2 refers is more cv-qualified than the type 4011 // to which the reference initialized by S1 refers. 4012 QualType T1 = SCS1.getToType(2); 4013 QualType T2 = SCS2.getToType(2); 4014 T1 = S.Context.getCanonicalType(T1); 4015 T2 = S.Context.getCanonicalType(T2); 4016 Qualifiers T1Quals, T2Quals; 4017 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4018 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4019 if (UnqualT1 == UnqualT2) { 4020 // Objective-C++ ARC: If the references refer to objects with different 4021 // lifetimes, prefer bindings that don't change lifetime. 4022 if (SCS1.ObjCLifetimeConversionBinding != 4023 SCS2.ObjCLifetimeConversionBinding) { 4024 return SCS1.ObjCLifetimeConversionBinding 4025 ? ImplicitConversionSequence::Worse 4026 : ImplicitConversionSequence::Better; 4027 } 4028 4029 // If the type is an array type, promote the element qualifiers to the 4030 // type for comparison. 4031 if (isa<ArrayType>(T1) && T1Quals) 4032 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4033 if (isa<ArrayType>(T2) && T2Quals) 4034 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4035 if (T2.isMoreQualifiedThan(T1)) 4036 return ImplicitConversionSequence::Better; 4037 if (T1.isMoreQualifiedThan(T2)) 4038 return ImplicitConversionSequence::Worse; 4039 } 4040 } 4041 4042 // In Microsoft mode, prefer an integral conversion to a 4043 // floating-to-integral conversion if the integral conversion 4044 // is between types of the same size. 4045 // For example: 4046 // void f(float); 4047 // void f(int); 4048 // int main { 4049 // long a; 4050 // f(a); 4051 // } 4052 // Here, MSVC will call f(int) instead of generating a compile error 4053 // as clang will do in standard mode. 4054 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 4055 SCS2.Second == ICK_Floating_Integral && 4056 S.Context.getTypeSize(SCS1.getFromType()) == 4057 S.Context.getTypeSize(SCS1.getToType(2))) 4058 return ImplicitConversionSequence::Better; 4059 4060 // Prefer a compatible vector conversion over a lax vector conversion 4061 // For example: 4062 // 4063 // typedef float __v4sf __attribute__((__vector_size__(16))); 4064 // void f(vector float); 4065 // void f(vector signed int); 4066 // int main() { 4067 // __v4sf a; 4068 // f(a); 4069 // } 4070 // Here, we'd like to choose f(vector float) and not 4071 // report an ambiguous call error 4072 if (SCS1.Second == ICK_Vector_Conversion && 4073 SCS2.Second == ICK_Vector_Conversion) { 4074 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4075 SCS1.getFromType(), SCS1.getToType(2)); 4076 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4077 SCS2.getFromType(), SCS2.getToType(2)); 4078 4079 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4080 return SCS1IsCompatibleVectorConversion 4081 ? ImplicitConversionSequence::Better 4082 : ImplicitConversionSequence::Worse; 4083 } 4084 4085 return ImplicitConversionSequence::Indistinguishable; 4086 } 4087 4088 /// CompareQualificationConversions - Compares two standard conversion 4089 /// sequences to determine whether they can be ranked based on their 4090 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4091 static ImplicitConversionSequence::CompareKind 4092 CompareQualificationConversions(Sema &S, 4093 const StandardConversionSequence& SCS1, 4094 const StandardConversionSequence& SCS2) { 4095 // C++ 13.3.3.2p3: 4096 // -- S1 and S2 differ only in their qualification conversion and 4097 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4098 // cv-qualification signature of type T1 is a proper subset of 4099 // the cv-qualification signature of type T2, and S1 is not the 4100 // deprecated string literal array-to-pointer conversion (4.2). 4101 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4102 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4103 return ImplicitConversionSequence::Indistinguishable; 4104 4105 // FIXME: the example in the standard doesn't use a qualification 4106 // conversion (!) 4107 QualType T1 = SCS1.getToType(2); 4108 QualType T2 = SCS2.getToType(2); 4109 T1 = S.Context.getCanonicalType(T1); 4110 T2 = S.Context.getCanonicalType(T2); 4111 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4112 Qualifiers T1Quals, T2Quals; 4113 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4114 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4115 4116 // If the types are the same, we won't learn anything by unwrapping 4117 // them. 4118 if (UnqualT1 == UnqualT2) 4119 return ImplicitConversionSequence::Indistinguishable; 4120 4121 ImplicitConversionSequence::CompareKind Result 4122 = ImplicitConversionSequence::Indistinguishable; 4123 4124 // Objective-C++ ARC: 4125 // Prefer qualification conversions not involving a change in lifetime 4126 // to qualification conversions that do not change lifetime. 4127 if (SCS1.QualificationIncludesObjCLifetime != 4128 SCS2.QualificationIncludesObjCLifetime) { 4129 Result = SCS1.QualificationIncludesObjCLifetime 4130 ? ImplicitConversionSequence::Worse 4131 : ImplicitConversionSequence::Better; 4132 } 4133 4134 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4135 // Within each iteration of the loop, we check the qualifiers to 4136 // determine if this still looks like a qualification 4137 // conversion. Then, if all is well, we unwrap one more level of 4138 // pointers or pointers-to-members and do it all again 4139 // until there are no more pointers or pointers-to-members left 4140 // to unwrap. This essentially mimics what 4141 // IsQualificationConversion does, but here we're checking for a 4142 // strict subset of qualifiers. 4143 if (T1.getQualifiers().withoutObjCLifetime() == 4144 T2.getQualifiers().withoutObjCLifetime()) 4145 // The qualifiers are the same, so this doesn't tell us anything 4146 // about how the sequences rank. 4147 // ObjC ownership quals are omitted above as they interfere with 4148 // the ARC overload rule. 4149 ; 4150 else if (T2.isMoreQualifiedThan(T1)) { 4151 // T1 has fewer qualifiers, so it could be the better sequence. 4152 if (Result == ImplicitConversionSequence::Worse) 4153 // Neither has qualifiers that are a subset of the other's 4154 // qualifiers. 4155 return ImplicitConversionSequence::Indistinguishable; 4156 4157 Result = ImplicitConversionSequence::Better; 4158 } else if (T1.isMoreQualifiedThan(T2)) { 4159 // T2 has fewer qualifiers, so it could be the better sequence. 4160 if (Result == ImplicitConversionSequence::Better) 4161 // Neither has qualifiers that are a subset of the other's 4162 // qualifiers. 4163 return ImplicitConversionSequence::Indistinguishable; 4164 4165 Result = ImplicitConversionSequence::Worse; 4166 } else { 4167 // Qualifiers are disjoint. 4168 return ImplicitConversionSequence::Indistinguishable; 4169 } 4170 4171 // If the types after this point are equivalent, we're done. 4172 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4173 break; 4174 } 4175 4176 // Check that the winning standard conversion sequence isn't using 4177 // the deprecated string literal array to pointer conversion. 4178 switch (Result) { 4179 case ImplicitConversionSequence::Better: 4180 if (SCS1.DeprecatedStringLiteralToCharPtr) 4181 Result = ImplicitConversionSequence::Indistinguishable; 4182 break; 4183 4184 case ImplicitConversionSequence::Indistinguishable: 4185 break; 4186 4187 case ImplicitConversionSequence::Worse: 4188 if (SCS2.DeprecatedStringLiteralToCharPtr) 4189 Result = ImplicitConversionSequence::Indistinguishable; 4190 break; 4191 } 4192 4193 return Result; 4194 } 4195 4196 /// CompareDerivedToBaseConversions - Compares two standard conversion 4197 /// sequences to determine whether they can be ranked based on their 4198 /// various kinds of derived-to-base conversions (C++ 4199 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4200 /// conversions between Objective-C interface types. 4201 static ImplicitConversionSequence::CompareKind 4202 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4203 const StandardConversionSequence& SCS1, 4204 const StandardConversionSequence& SCS2) { 4205 QualType FromType1 = SCS1.getFromType(); 4206 QualType ToType1 = SCS1.getToType(1); 4207 QualType FromType2 = SCS2.getFromType(); 4208 QualType ToType2 = SCS2.getToType(1); 4209 4210 // Adjust the types we're converting from via the array-to-pointer 4211 // conversion, if we need to. 4212 if (SCS1.First == ICK_Array_To_Pointer) 4213 FromType1 = S.Context.getArrayDecayedType(FromType1); 4214 if (SCS2.First == ICK_Array_To_Pointer) 4215 FromType2 = S.Context.getArrayDecayedType(FromType2); 4216 4217 // Canonicalize all of the types. 4218 FromType1 = S.Context.getCanonicalType(FromType1); 4219 ToType1 = S.Context.getCanonicalType(ToType1); 4220 FromType2 = S.Context.getCanonicalType(FromType2); 4221 ToType2 = S.Context.getCanonicalType(ToType2); 4222 4223 // C++ [over.ics.rank]p4b3: 4224 // 4225 // If class B is derived directly or indirectly from class A and 4226 // class C is derived directly or indirectly from B, 4227 // 4228 // Compare based on pointer conversions. 4229 if (SCS1.Second == ICK_Pointer_Conversion && 4230 SCS2.Second == ICK_Pointer_Conversion && 4231 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4232 FromType1->isPointerType() && FromType2->isPointerType() && 4233 ToType1->isPointerType() && ToType2->isPointerType()) { 4234 QualType FromPointee1 = 4235 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4236 QualType ToPointee1 = 4237 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4238 QualType FromPointee2 = 4239 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4240 QualType ToPointee2 = 4241 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4242 4243 // -- conversion of C* to B* is better than conversion of C* to A*, 4244 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4245 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4246 return ImplicitConversionSequence::Better; 4247 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4248 return ImplicitConversionSequence::Worse; 4249 } 4250 4251 // -- conversion of B* to A* is better than conversion of C* to A*, 4252 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4253 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4254 return ImplicitConversionSequence::Better; 4255 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4256 return ImplicitConversionSequence::Worse; 4257 } 4258 } else if (SCS1.Second == ICK_Pointer_Conversion && 4259 SCS2.Second == ICK_Pointer_Conversion) { 4260 const ObjCObjectPointerType *FromPtr1 4261 = FromType1->getAs<ObjCObjectPointerType>(); 4262 const ObjCObjectPointerType *FromPtr2 4263 = FromType2->getAs<ObjCObjectPointerType>(); 4264 const ObjCObjectPointerType *ToPtr1 4265 = ToType1->getAs<ObjCObjectPointerType>(); 4266 const ObjCObjectPointerType *ToPtr2 4267 = ToType2->getAs<ObjCObjectPointerType>(); 4268 4269 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4270 // Apply the same conversion ranking rules for Objective-C pointer types 4271 // that we do for C++ pointers to class types. However, we employ the 4272 // Objective-C pseudo-subtyping relationship used for assignment of 4273 // Objective-C pointer types. 4274 bool FromAssignLeft 4275 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4276 bool FromAssignRight 4277 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4278 bool ToAssignLeft 4279 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4280 bool ToAssignRight 4281 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4282 4283 // A conversion to an a non-id object pointer type or qualified 'id' 4284 // type is better than a conversion to 'id'. 4285 if (ToPtr1->isObjCIdType() && 4286 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4287 return ImplicitConversionSequence::Worse; 4288 if (ToPtr2->isObjCIdType() && 4289 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4290 return ImplicitConversionSequence::Better; 4291 4292 // A conversion to a non-id object pointer type is better than a 4293 // conversion to a qualified 'id' type 4294 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4295 return ImplicitConversionSequence::Worse; 4296 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4297 return ImplicitConversionSequence::Better; 4298 4299 // A conversion to an a non-Class object pointer type or qualified 'Class' 4300 // type is better than a conversion to 'Class'. 4301 if (ToPtr1->isObjCClassType() && 4302 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4303 return ImplicitConversionSequence::Worse; 4304 if (ToPtr2->isObjCClassType() && 4305 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4306 return ImplicitConversionSequence::Better; 4307 4308 // A conversion to a non-Class object pointer type is better than a 4309 // conversion to a qualified 'Class' type. 4310 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4311 return ImplicitConversionSequence::Worse; 4312 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4313 return ImplicitConversionSequence::Better; 4314 4315 // -- "conversion of C* to B* is better than conversion of C* to A*," 4316 if (S.Context.hasSameType(FromType1, FromType2) && 4317 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4318 (ToAssignLeft != ToAssignRight)) { 4319 if (FromPtr1->isSpecialized()) { 4320 // "conversion of B<A> * to B * is better than conversion of B * to 4321 // C *. 4322 bool IsFirstSame = 4323 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4324 bool IsSecondSame = 4325 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4326 if (IsFirstSame) { 4327 if (!IsSecondSame) 4328 return ImplicitConversionSequence::Better; 4329 } else if (IsSecondSame) 4330 return ImplicitConversionSequence::Worse; 4331 } 4332 return ToAssignLeft? ImplicitConversionSequence::Worse 4333 : ImplicitConversionSequence::Better; 4334 } 4335 4336 // -- "conversion of B* to A* is better than conversion of C* to A*," 4337 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4338 (FromAssignLeft != FromAssignRight)) 4339 return FromAssignLeft? ImplicitConversionSequence::Better 4340 : ImplicitConversionSequence::Worse; 4341 } 4342 } 4343 4344 // Ranking of member-pointer types. 4345 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4346 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4347 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4348 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4349 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4350 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4351 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4352 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4353 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4354 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4355 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4356 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4357 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4358 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4359 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4360 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4361 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4362 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4363 return ImplicitConversionSequence::Worse; 4364 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4365 return ImplicitConversionSequence::Better; 4366 } 4367 // conversion of B::* to C::* is better than conversion of A::* to C::* 4368 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4369 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4370 return ImplicitConversionSequence::Better; 4371 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4372 return ImplicitConversionSequence::Worse; 4373 } 4374 } 4375 4376 if (SCS1.Second == ICK_Derived_To_Base) { 4377 // -- conversion of C to B is better than conversion of C to A, 4378 // -- binding of an expression of type C to a reference of type 4379 // B& is better than binding an expression of type C to a 4380 // reference of type A&, 4381 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4382 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4383 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4384 return ImplicitConversionSequence::Better; 4385 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4386 return ImplicitConversionSequence::Worse; 4387 } 4388 4389 // -- conversion of B to A is better than conversion of C to A. 4390 // -- binding of an expression of type B to a reference of type 4391 // A& is better than binding an expression of type C to a 4392 // reference of type A&, 4393 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4394 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4395 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4396 return ImplicitConversionSequence::Better; 4397 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4398 return ImplicitConversionSequence::Worse; 4399 } 4400 } 4401 4402 return ImplicitConversionSequence::Indistinguishable; 4403 } 4404 4405 /// Determine whether the given type is valid, e.g., it is not an invalid 4406 /// C++ class. 4407 static bool isTypeValid(QualType T) { 4408 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4409 return !Record->isInvalidDecl(); 4410 4411 return true; 4412 } 4413 4414 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4415 if (!T.getQualifiers().hasUnaligned()) 4416 return T; 4417 4418 Qualifiers Q; 4419 T = Ctx.getUnqualifiedArrayType(T, Q); 4420 Q.removeUnaligned(); 4421 return Ctx.getQualifiedType(T, Q); 4422 } 4423 4424 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4425 /// determine whether they are reference-compatible, 4426 /// reference-related, or incompatible, for use in C++ initialization by 4427 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4428 /// type, and the first type (T1) is the pointee type of the reference 4429 /// type being initialized. 4430 Sema::ReferenceCompareResult 4431 Sema::CompareReferenceRelationship(SourceLocation Loc, 4432 QualType OrigT1, QualType OrigT2, 4433 ReferenceConversions *ConvOut) { 4434 assert(!OrigT1->isReferenceType() && 4435 "T1 must be the pointee type of the reference type"); 4436 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4437 4438 QualType T1 = Context.getCanonicalType(OrigT1); 4439 QualType T2 = Context.getCanonicalType(OrigT2); 4440 Qualifiers T1Quals, T2Quals; 4441 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4442 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4443 4444 ReferenceConversions ConvTmp; 4445 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4446 Conv = ReferenceConversions(); 4447 4448 // C++2a [dcl.init.ref]p4: 4449 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4450 // reference-related to "cv2 T2" if T1 is similar to T2, or 4451 // T1 is a base class of T2. 4452 // "cv1 T1" is reference-compatible with "cv2 T2" if 4453 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4454 // "pointer to cv1 T1" via a standard conversion sequence. 4455 4456 // Check for standard conversions we can apply to pointers: derived-to-base 4457 // conversions, ObjC pointer conversions, and function pointer conversions. 4458 // (Qualification conversions are checked last.) 4459 QualType ConvertedT2; 4460 if (UnqualT1 == UnqualT2) { 4461 // Nothing to do. 4462 } else if (isCompleteType(Loc, OrigT2) && 4463 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4464 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4465 Conv |= ReferenceConversions::DerivedToBase; 4466 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4467 UnqualT2->isObjCObjectOrInterfaceType() && 4468 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4469 Conv |= ReferenceConversions::ObjC; 4470 else if (UnqualT2->isFunctionType() && 4471 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4472 Conv |= ReferenceConversions::Function; 4473 // No need to check qualifiers; function types don't have them. 4474 return Ref_Compatible; 4475 } 4476 bool ConvertedReferent = Conv != 0; 4477 4478 // We can have a qualification conversion. Compute whether the types are 4479 // similar at the same time. 4480 bool PreviousToQualsIncludeConst = true; 4481 bool TopLevel = true; 4482 do { 4483 if (T1 == T2) 4484 break; 4485 4486 // We will need a qualification conversion. 4487 Conv |= ReferenceConversions::Qualification; 4488 4489 // Track whether we performed a qualification conversion anywhere other 4490 // than the top level. This matters for ranking reference bindings in 4491 // overload resolution. 4492 if (!TopLevel) 4493 Conv |= ReferenceConversions::NestedQualification; 4494 4495 // MS compiler ignores __unaligned qualifier for references; do the same. 4496 T1 = withoutUnaligned(Context, T1); 4497 T2 = withoutUnaligned(Context, T2); 4498 4499 // If we find a qualifier mismatch, the types are not reference-compatible, 4500 // but are still be reference-related if they're similar. 4501 bool ObjCLifetimeConversion = false; 4502 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, 4503 PreviousToQualsIncludeConst, 4504 ObjCLifetimeConversion)) 4505 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4506 ? Ref_Related 4507 : Ref_Incompatible; 4508 4509 // FIXME: Should we track this for any level other than the first? 4510 if (ObjCLifetimeConversion) 4511 Conv |= ReferenceConversions::ObjCLifetime; 4512 4513 TopLevel = false; 4514 } while (Context.UnwrapSimilarTypes(T1, T2)); 4515 4516 // At this point, if the types are reference-related, we must either have the 4517 // same inner type (ignoring qualifiers), or must have already worked out how 4518 // to convert the referent. 4519 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4520 ? Ref_Compatible 4521 : Ref_Incompatible; 4522 } 4523 4524 /// Look for a user-defined conversion to a value reference-compatible 4525 /// with DeclType. Return true if something definite is found. 4526 static bool 4527 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4528 QualType DeclType, SourceLocation DeclLoc, 4529 Expr *Init, QualType T2, bool AllowRvalues, 4530 bool AllowExplicit) { 4531 assert(T2->isRecordType() && "Can only find conversions of record types."); 4532 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4533 4534 OverloadCandidateSet CandidateSet( 4535 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4536 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4537 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4538 NamedDecl *D = *I; 4539 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4540 if (isa<UsingShadowDecl>(D)) 4541 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4542 4543 FunctionTemplateDecl *ConvTemplate 4544 = dyn_cast<FunctionTemplateDecl>(D); 4545 CXXConversionDecl *Conv; 4546 if (ConvTemplate) 4547 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4548 else 4549 Conv = cast<CXXConversionDecl>(D); 4550 4551 if (AllowRvalues) { 4552 // If we are initializing an rvalue reference, don't permit conversion 4553 // functions that return lvalues. 4554 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4555 const ReferenceType *RefType 4556 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4557 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4558 continue; 4559 } 4560 4561 if (!ConvTemplate && 4562 S.CompareReferenceRelationship( 4563 DeclLoc, 4564 Conv->getConversionType() 4565 .getNonReferenceType() 4566 .getUnqualifiedType(), 4567 DeclType.getNonReferenceType().getUnqualifiedType()) == 4568 Sema::Ref_Incompatible) 4569 continue; 4570 } else { 4571 // If the conversion function doesn't return a reference type, 4572 // it can't be considered for this conversion. An rvalue reference 4573 // is only acceptable if its referencee is a function type. 4574 4575 const ReferenceType *RefType = 4576 Conv->getConversionType()->getAs<ReferenceType>(); 4577 if (!RefType || 4578 (!RefType->isLValueReferenceType() && 4579 !RefType->getPointeeType()->isFunctionType())) 4580 continue; 4581 } 4582 4583 if (ConvTemplate) 4584 S.AddTemplateConversionCandidate( 4585 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4586 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4587 else 4588 S.AddConversionCandidate( 4589 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4590 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4591 } 4592 4593 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4594 4595 OverloadCandidateSet::iterator Best; 4596 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4597 case OR_Success: 4598 // C++ [over.ics.ref]p1: 4599 // 4600 // [...] If the parameter binds directly to the result of 4601 // applying a conversion function to the argument 4602 // expression, the implicit conversion sequence is a 4603 // user-defined conversion sequence (13.3.3.1.2), with the 4604 // second standard conversion sequence either an identity 4605 // conversion or, if the conversion function returns an 4606 // entity of a type that is a derived class of the parameter 4607 // type, a derived-to-base Conversion. 4608 if (!Best->FinalConversion.DirectBinding) 4609 return false; 4610 4611 ICS.setUserDefined(); 4612 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4613 ICS.UserDefined.After = Best->FinalConversion; 4614 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4615 ICS.UserDefined.ConversionFunction = Best->Function; 4616 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4617 ICS.UserDefined.EllipsisConversion = false; 4618 assert(ICS.UserDefined.After.ReferenceBinding && 4619 ICS.UserDefined.After.DirectBinding && 4620 "Expected a direct reference binding!"); 4621 return true; 4622 4623 case OR_Ambiguous: 4624 ICS.setAmbiguous(); 4625 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4626 Cand != CandidateSet.end(); ++Cand) 4627 if (Cand->Best) 4628 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4629 return true; 4630 4631 case OR_No_Viable_Function: 4632 case OR_Deleted: 4633 // There was no suitable conversion, or we found a deleted 4634 // conversion; continue with other checks. 4635 return false; 4636 } 4637 4638 llvm_unreachable("Invalid OverloadResult!"); 4639 } 4640 4641 /// Compute an implicit conversion sequence for reference 4642 /// initialization. 4643 static ImplicitConversionSequence 4644 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4645 SourceLocation DeclLoc, 4646 bool SuppressUserConversions, 4647 bool AllowExplicit) { 4648 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4649 4650 // Most paths end in a failed conversion. 4651 ImplicitConversionSequence ICS; 4652 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4653 4654 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4655 QualType T2 = Init->getType(); 4656 4657 // If the initializer is the address of an overloaded function, try 4658 // to resolve the overloaded function. If all goes well, T2 is the 4659 // type of the resulting function. 4660 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4661 DeclAccessPair Found; 4662 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4663 false, Found)) 4664 T2 = Fn->getType(); 4665 } 4666 4667 // Compute some basic properties of the types and the initializer. 4668 bool isRValRef = DeclType->isRValueReferenceType(); 4669 Expr::Classification InitCategory = Init->Classify(S.Context); 4670 4671 Sema::ReferenceConversions RefConv; 4672 Sema::ReferenceCompareResult RefRelationship = 4673 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4674 4675 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4676 ICS.setStandard(); 4677 ICS.Standard.First = ICK_Identity; 4678 // FIXME: A reference binding can be a function conversion too. We should 4679 // consider that when ordering reference-to-function bindings. 4680 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4681 ? ICK_Derived_To_Base 4682 : (RefConv & Sema::ReferenceConversions::ObjC) 4683 ? ICK_Compatible_Conversion 4684 : ICK_Identity; 4685 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4686 // a reference binding that performs a non-top-level qualification 4687 // conversion as a qualification conversion, not as an identity conversion. 4688 ICS.Standard.Third = (RefConv & 4689 Sema::ReferenceConversions::NestedQualification) 4690 ? ICK_Qualification 4691 : ICK_Identity; 4692 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4693 ICS.Standard.setToType(0, T2); 4694 ICS.Standard.setToType(1, T1); 4695 ICS.Standard.setToType(2, T1); 4696 ICS.Standard.ReferenceBinding = true; 4697 ICS.Standard.DirectBinding = BindsDirectly; 4698 ICS.Standard.IsLvalueReference = !isRValRef; 4699 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4700 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4701 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4702 ICS.Standard.ObjCLifetimeConversionBinding = 4703 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4704 ICS.Standard.CopyConstructor = nullptr; 4705 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4706 }; 4707 4708 // C++0x [dcl.init.ref]p5: 4709 // A reference to type "cv1 T1" is initialized by an expression 4710 // of type "cv2 T2" as follows: 4711 4712 // -- If reference is an lvalue reference and the initializer expression 4713 if (!isRValRef) { 4714 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4715 // reference-compatible with "cv2 T2," or 4716 // 4717 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4718 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4719 // C++ [over.ics.ref]p1: 4720 // When a parameter of reference type binds directly (8.5.3) 4721 // to an argument expression, the implicit conversion sequence 4722 // is the identity conversion, unless the argument expression 4723 // has a type that is a derived class of the parameter type, 4724 // in which case the implicit conversion sequence is a 4725 // derived-to-base Conversion (13.3.3.1). 4726 SetAsReferenceBinding(/*BindsDirectly=*/true); 4727 4728 // Nothing more to do: the inaccessibility/ambiguity check for 4729 // derived-to-base conversions is suppressed when we're 4730 // computing the implicit conversion sequence (C++ 4731 // [over.best.ics]p2). 4732 return ICS; 4733 } 4734 4735 // -- has a class type (i.e., T2 is a class type), where T1 is 4736 // not reference-related to T2, and can be implicitly 4737 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4738 // is reference-compatible with "cv3 T3" 92) (this 4739 // conversion is selected by enumerating the applicable 4740 // conversion functions (13.3.1.6) and choosing the best 4741 // one through overload resolution (13.3)), 4742 if (!SuppressUserConversions && T2->isRecordType() && 4743 S.isCompleteType(DeclLoc, T2) && 4744 RefRelationship == Sema::Ref_Incompatible) { 4745 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4746 Init, T2, /*AllowRvalues=*/false, 4747 AllowExplicit)) 4748 return ICS; 4749 } 4750 } 4751 4752 // -- Otherwise, the reference shall be an lvalue reference to a 4753 // non-volatile const type (i.e., cv1 shall be const), or the reference 4754 // shall be an rvalue reference. 4755 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4756 return ICS; 4757 4758 // -- If the initializer expression 4759 // 4760 // -- is an xvalue, class prvalue, array prvalue or function 4761 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4762 if (RefRelationship == Sema::Ref_Compatible && 4763 (InitCategory.isXValue() || 4764 (InitCategory.isPRValue() && 4765 (T2->isRecordType() || T2->isArrayType())) || 4766 (InitCategory.isLValue() && T2->isFunctionType()))) { 4767 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4768 // binding unless we're binding to a class prvalue. 4769 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4770 // allow the use of rvalue references in C++98/03 for the benefit of 4771 // standard library implementors; therefore, we need the xvalue check here. 4772 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4773 !(InitCategory.isPRValue() || T2->isRecordType())); 4774 return ICS; 4775 } 4776 4777 // -- has a class type (i.e., T2 is a class type), where T1 is not 4778 // reference-related to T2, and can be implicitly converted to 4779 // an xvalue, class prvalue, or function lvalue of type 4780 // "cv3 T3", where "cv1 T1" is reference-compatible with 4781 // "cv3 T3", 4782 // 4783 // then the reference is bound to the value of the initializer 4784 // expression in the first case and to the result of the conversion 4785 // in the second case (or, in either case, to an appropriate base 4786 // class subobject). 4787 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4788 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4789 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4790 Init, T2, /*AllowRvalues=*/true, 4791 AllowExplicit)) { 4792 // In the second case, if the reference is an rvalue reference 4793 // and the second standard conversion sequence of the 4794 // user-defined conversion sequence includes an lvalue-to-rvalue 4795 // conversion, the program is ill-formed. 4796 if (ICS.isUserDefined() && isRValRef && 4797 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4798 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4799 4800 return ICS; 4801 } 4802 4803 // A temporary of function type cannot be created; don't even try. 4804 if (T1->isFunctionType()) 4805 return ICS; 4806 4807 // -- Otherwise, a temporary of type "cv1 T1" is created and 4808 // initialized from the initializer expression using the 4809 // rules for a non-reference copy initialization (8.5). The 4810 // reference is then bound to the temporary. If T1 is 4811 // reference-related to T2, cv1 must be the same 4812 // cv-qualification as, or greater cv-qualification than, 4813 // cv2; otherwise, the program is ill-formed. 4814 if (RefRelationship == Sema::Ref_Related) { 4815 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4816 // we would be reference-compatible or reference-compatible with 4817 // added qualification. But that wasn't the case, so the reference 4818 // initialization fails. 4819 // 4820 // Note that we only want to check address spaces and cvr-qualifiers here. 4821 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4822 Qualifiers T1Quals = T1.getQualifiers(); 4823 Qualifiers T2Quals = T2.getQualifiers(); 4824 T1Quals.removeObjCGCAttr(); 4825 T1Quals.removeObjCLifetime(); 4826 T2Quals.removeObjCGCAttr(); 4827 T2Quals.removeObjCLifetime(); 4828 // MS compiler ignores __unaligned qualifier for references; do the same. 4829 T1Quals.removeUnaligned(); 4830 T2Quals.removeUnaligned(); 4831 if (!T1Quals.compatiblyIncludes(T2Quals)) 4832 return ICS; 4833 } 4834 4835 // If at least one of the types is a class type, the types are not 4836 // related, and we aren't allowed any user conversions, the 4837 // reference binding fails. This case is important for breaking 4838 // recursion, since TryImplicitConversion below will attempt to 4839 // create a temporary through the use of a copy constructor. 4840 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4841 (T1->isRecordType() || T2->isRecordType())) 4842 return ICS; 4843 4844 // If T1 is reference-related to T2 and the reference is an rvalue 4845 // reference, the initializer expression shall not be an lvalue. 4846 if (RefRelationship >= Sema::Ref_Related && 4847 isRValRef && Init->Classify(S.Context).isLValue()) 4848 return ICS; 4849 4850 // C++ [over.ics.ref]p2: 4851 // When a parameter of reference type is not bound directly to 4852 // an argument expression, the conversion sequence is the one 4853 // required to convert the argument expression to the 4854 // underlying type of the reference according to 4855 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4856 // to copy-initializing a temporary of the underlying type with 4857 // the argument expression. Any difference in top-level 4858 // cv-qualification is subsumed by the initialization itself 4859 // and does not constitute a conversion. 4860 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4861 /*AllowExplicit=*/false, 4862 /*InOverloadResolution=*/false, 4863 /*CStyle=*/false, 4864 /*AllowObjCWritebackConversion=*/false, 4865 /*AllowObjCConversionOnExplicit=*/false); 4866 4867 // Of course, that's still a reference binding. 4868 if (ICS.isStandard()) { 4869 ICS.Standard.ReferenceBinding = true; 4870 ICS.Standard.IsLvalueReference = !isRValRef; 4871 ICS.Standard.BindsToFunctionLvalue = false; 4872 ICS.Standard.BindsToRvalue = true; 4873 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4874 ICS.Standard.ObjCLifetimeConversionBinding = false; 4875 } else if (ICS.isUserDefined()) { 4876 const ReferenceType *LValRefType = 4877 ICS.UserDefined.ConversionFunction->getReturnType() 4878 ->getAs<LValueReferenceType>(); 4879 4880 // C++ [over.ics.ref]p3: 4881 // Except for an implicit object parameter, for which see 13.3.1, a 4882 // standard conversion sequence cannot be formed if it requires [...] 4883 // binding an rvalue reference to an lvalue other than a function 4884 // lvalue. 4885 // Note that the function case is not possible here. 4886 if (DeclType->isRValueReferenceType() && LValRefType) { 4887 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4888 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4889 // reference to an rvalue! 4890 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4891 return ICS; 4892 } 4893 4894 ICS.UserDefined.After.ReferenceBinding = true; 4895 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4896 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4897 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4898 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4899 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4900 } 4901 4902 return ICS; 4903 } 4904 4905 static ImplicitConversionSequence 4906 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4907 bool SuppressUserConversions, 4908 bool InOverloadResolution, 4909 bool AllowObjCWritebackConversion, 4910 bool AllowExplicit = false); 4911 4912 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4913 /// initializer list From. 4914 static ImplicitConversionSequence 4915 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4916 bool SuppressUserConversions, 4917 bool InOverloadResolution, 4918 bool AllowObjCWritebackConversion) { 4919 // C++11 [over.ics.list]p1: 4920 // When an argument is an initializer list, it is not an expression and 4921 // special rules apply for converting it to a parameter type. 4922 4923 ImplicitConversionSequence Result; 4924 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4925 4926 // We need a complete type for what follows. Incomplete types can never be 4927 // initialized from init lists. 4928 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4929 return Result; 4930 4931 // Per DR1467: 4932 // If the parameter type is a class X and the initializer list has a single 4933 // element of type cv U, where U is X or a class derived from X, the 4934 // implicit conversion sequence is the one required to convert the element 4935 // to the parameter type. 4936 // 4937 // Otherwise, if the parameter type is a character array [... ] 4938 // and the initializer list has a single element that is an 4939 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4940 // implicit conversion sequence is the identity conversion. 4941 if (From->getNumInits() == 1) { 4942 if (ToType->isRecordType()) { 4943 QualType InitType = From->getInit(0)->getType(); 4944 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4945 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4946 return TryCopyInitialization(S, From->getInit(0), ToType, 4947 SuppressUserConversions, 4948 InOverloadResolution, 4949 AllowObjCWritebackConversion); 4950 } 4951 // FIXME: Check the other conditions here: array of character type, 4952 // initializer is a string literal. 4953 if (ToType->isArrayType()) { 4954 InitializedEntity Entity = 4955 InitializedEntity::InitializeParameter(S.Context, ToType, 4956 /*Consumed=*/false); 4957 if (S.CanPerformCopyInitialization(Entity, From)) { 4958 Result.setStandard(); 4959 Result.Standard.setAsIdentityConversion(); 4960 Result.Standard.setFromType(ToType); 4961 Result.Standard.setAllToTypes(ToType); 4962 return Result; 4963 } 4964 } 4965 } 4966 4967 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4968 // C++11 [over.ics.list]p2: 4969 // If the parameter type is std::initializer_list<X> or "array of X" and 4970 // all the elements can be implicitly converted to X, the implicit 4971 // conversion sequence is the worst conversion necessary to convert an 4972 // element of the list to X. 4973 // 4974 // C++14 [over.ics.list]p3: 4975 // Otherwise, if the parameter type is "array of N X", if the initializer 4976 // list has exactly N elements or if it has fewer than N elements and X is 4977 // default-constructible, and if all the elements of the initializer list 4978 // can be implicitly converted to X, the implicit conversion sequence is 4979 // the worst conversion necessary to convert an element of the list to X. 4980 // 4981 // FIXME: We're missing a lot of these checks. 4982 bool toStdInitializerList = false; 4983 QualType X; 4984 if (ToType->isArrayType()) 4985 X = S.Context.getAsArrayType(ToType)->getElementType(); 4986 else 4987 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4988 if (!X.isNull()) { 4989 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4990 Expr *Init = From->getInit(i); 4991 ImplicitConversionSequence ICS = 4992 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4993 InOverloadResolution, 4994 AllowObjCWritebackConversion); 4995 // If a single element isn't convertible, fail. 4996 if (ICS.isBad()) { 4997 Result = ICS; 4998 break; 4999 } 5000 // Otherwise, look for the worst conversion. 5001 if (Result.isBad() || CompareImplicitConversionSequences( 5002 S, From->getBeginLoc(), ICS, Result) == 5003 ImplicitConversionSequence::Worse) 5004 Result = ICS; 5005 } 5006 5007 // For an empty list, we won't have computed any conversion sequence. 5008 // Introduce the identity conversion sequence. 5009 if (From->getNumInits() == 0) { 5010 Result.setStandard(); 5011 Result.Standard.setAsIdentityConversion(); 5012 Result.Standard.setFromType(ToType); 5013 Result.Standard.setAllToTypes(ToType); 5014 } 5015 5016 Result.setStdInitializerListElement(toStdInitializerList); 5017 return Result; 5018 } 5019 5020 // C++14 [over.ics.list]p4: 5021 // C++11 [over.ics.list]p3: 5022 // Otherwise, if the parameter is a non-aggregate class X and overload 5023 // resolution chooses a single best constructor [...] the implicit 5024 // conversion sequence is a user-defined conversion sequence. If multiple 5025 // constructors are viable but none is better than the others, the 5026 // implicit conversion sequence is a user-defined conversion sequence. 5027 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5028 // This function can deal with initializer lists. 5029 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5030 /*AllowExplicit=*/false, 5031 InOverloadResolution, /*CStyle=*/false, 5032 AllowObjCWritebackConversion, 5033 /*AllowObjCConversionOnExplicit=*/false); 5034 } 5035 5036 // C++14 [over.ics.list]p5: 5037 // C++11 [over.ics.list]p4: 5038 // Otherwise, if the parameter has an aggregate type which can be 5039 // initialized from the initializer list [...] the implicit conversion 5040 // sequence is a user-defined conversion sequence. 5041 if (ToType->isAggregateType()) { 5042 // Type is an aggregate, argument is an init list. At this point it comes 5043 // down to checking whether the initialization works. 5044 // FIXME: Find out whether this parameter is consumed or not. 5045 InitializedEntity Entity = 5046 InitializedEntity::InitializeParameter(S.Context, ToType, 5047 /*Consumed=*/false); 5048 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5049 From)) { 5050 Result.setUserDefined(); 5051 Result.UserDefined.Before.setAsIdentityConversion(); 5052 // Initializer lists don't have a type. 5053 Result.UserDefined.Before.setFromType(QualType()); 5054 Result.UserDefined.Before.setAllToTypes(QualType()); 5055 5056 Result.UserDefined.After.setAsIdentityConversion(); 5057 Result.UserDefined.After.setFromType(ToType); 5058 Result.UserDefined.After.setAllToTypes(ToType); 5059 Result.UserDefined.ConversionFunction = nullptr; 5060 } 5061 return Result; 5062 } 5063 5064 // C++14 [over.ics.list]p6: 5065 // C++11 [over.ics.list]p5: 5066 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5067 if (ToType->isReferenceType()) { 5068 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5069 // mention initializer lists in any way. So we go by what list- 5070 // initialization would do and try to extrapolate from that. 5071 5072 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5073 5074 // If the initializer list has a single element that is reference-related 5075 // to the parameter type, we initialize the reference from that. 5076 if (From->getNumInits() == 1) { 5077 Expr *Init = From->getInit(0); 5078 5079 QualType T2 = Init->getType(); 5080 5081 // If the initializer is the address of an overloaded function, try 5082 // to resolve the overloaded function. If all goes well, T2 is the 5083 // type of the resulting function. 5084 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5085 DeclAccessPair Found; 5086 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5087 Init, ToType, false, Found)) 5088 T2 = Fn->getType(); 5089 } 5090 5091 // Compute some basic properties of the types and the initializer. 5092 Sema::ReferenceCompareResult RefRelationship = 5093 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5094 5095 if (RefRelationship >= Sema::Ref_Related) { 5096 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5097 SuppressUserConversions, 5098 /*AllowExplicit=*/false); 5099 } 5100 } 5101 5102 // Otherwise, we bind the reference to a temporary created from the 5103 // initializer list. 5104 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5105 InOverloadResolution, 5106 AllowObjCWritebackConversion); 5107 if (Result.isFailure()) 5108 return Result; 5109 assert(!Result.isEllipsis() && 5110 "Sub-initialization cannot result in ellipsis conversion."); 5111 5112 // Can we even bind to a temporary? 5113 if (ToType->isRValueReferenceType() || 5114 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5115 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5116 Result.UserDefined.After; 5117 SCS.ReferenceBinding = true; 5118 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5119 SCS.BindsToRvalue = true; 5120 SCS.BindsToFunctionLvalue = false; 5121 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5122 SCS.ObjCLifetimeConversionBinding = false; 5123 } else 5124 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5125 From, ToType); 5126 return Result; 5127 } 5128 5129 // C++14 [over.ics.list]p7: 5130 // C++11 [over.ics.list]p6: 5131 // Otherwise, if the parameter type is not a class: 5132 if (!ToType->isRecordType()) { 5133 // - if the initializer list has one element that is not itself an 5134 // initializer list, the implicit conversion sequence is the one 5135 // required to convert the element to the parameter type. 5136 unsigned NumInits = From->getNumInits(); 5137 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5138 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5139 SuppressUserConversions, 5140 InOverloadResolution, 5141 AllowObjCWritebackConversion); 5142 // - if the initializer list has no elements, the implicit conversion 5143 // sequence is the identity conversion. 5144 else if (NumInits == 0) { 5145 Result.setStandard(); 5146 Result.Standard.setAsIdentityConversion(); 5147 Result.Standard.setFromType(ToType); 5148 Result.Standard.setAllToTypes(ToType); 5149 } 5150 return Result; 5151 } 5152 5153 // C++14 [over.ics.list]p8: 5154 // C++11 [over.ics.list]p7: 5155 // In all cases other than those enumerated above, no conversion is possible 5156 return Result; 5157 } 5158 5159 /// TryCopyInitialization - Try to copy-initialize a value of type 5160 /// ToType from the expression From. Return the implicit conversion 5161 /// sequence required to pass this argument, which may be a bad 5162 /// conversion sequence (meaning that the argument cannot be passed to 5163 /// a parameter of this type). If @p SuppressUserConversions, then we 5164 /// do not permit any user-defined conversion sequences. 5165 static ImplicitConversionSequence 5166 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5167 bool SuppressUserConversions, 5168 bool InOverloadResolution, 5169 bool AllowObjCWritebackConversion, 5170 bool AllowExplicit) { 5171 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5172 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5173 InOverloadResolution,AllowObjCWritebackConversion); 5174 5175 if (ToType->isReferenceType()) 5176 return TryReferenceInit(S, From, ToType, 5177 /*FIXME:*/ From->getBeginLoc(), 5178 SuppressUserConversions, AllowExplicit); 5179 5180 return TryImplicitConversion(S, From, ToType, 5181 SuppressUserConversions, 5182 /*AllowExplicit=*/false, 5183 InOverloadResolution, 5184 /*CStyle=*/false, 5185 AllowObjCWritebackConversion, 5186 /*AllowObjCConversionOnExplicit=*/false); 5187 } 5188 5189 static bool TryCopyInitialization(const CanQualType FromQTy, 5190 const CanQualType ToQTy, 5191 Sema &S, 5192 SourceLocation Loc, 5193 ExprValueKind FromVK) { 5194 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5195 ImplicitConversionSequence ICS = 5196 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5197 5198 return !ICS.isBad(); 5199 } 5200 5201 /// TryObjectArgumentInitialization - Try to initialize the object 5202 /// parameter of the given member function (@c Method) from the 5203 /// expression @p From. 5204 static ImplicitConversionSequence 5205 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5206 Expr::Classification FromClassification, 5207 CXXMethodDecl *Method, 5208 CXXRecordDecl *ActingContext) { 5209 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5210 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5211 // const volatile object. 5212 Qualifiers Quals = Method->getMethodQualifiers(); 5213 if (isa<CXXDestructorDecl>(Method)) { 5214 Quals.addConst(); 5215 Quals.addVolatile(); 5216 } 5217 5218 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5219 5220 // Set up the conversion sequence as a "bad" conversion, to allow us 5221 // to exit early. 5222 ImplicitConversionSequence ICS; 5223 5224 // We need to have an object of class type. 5225 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5226 FromType = PT->getPointeeType(); 5227 5228 // When we had a pointer, it's implicitly dereferenced, so we 5229 // better have an lvalue. 5230 assert(FromClassification.isLValue()); 5231 } 5232 5233 assert(FromType->isRecordType()); 5234 5235 // C++0x [over.match.funcs]p4: 5236 // For non-static member functions, the type of the implicit object 5237 // parameter is 5238 // 5239 // - "lvalue reference to cv X" for functions declared without a 5240 // ref-qualifier or with the & ref-qualifier 5241 // - "rvalue reference to cv X" for functions declared with the && 5242 // ref-qualifier 5243 // 5244 // where X is the class of which the function is a member and cv is the 5245 // cv-qualification on the member function declaration. 5246 // 5247 // However, when finding an implicit conversion sequence for the argument, we 5248 // are not allowed to perform user-defined conversions 5249 // (C++ [over.match.funcs]p5). We perform a simplified version of 5250 // reference binding here, that allows class rvalues to bind to 5251 // non-constant references. 5252 5253 // First check the qualifiers. 5254 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5255 if (ImplicitParamType.getCVRQualifiers() 5256 != FromTypeCanon.getLocalCVRQualifiers() && 5257 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5258 ICS.setBad(BadConversionSequence::bad_qualifiers, 5259 FromType, ImplicitParamType); 5260 return ICS; 5261 } 5262 5263 if (FromTypeCanon.hasAddressSpace()) { 5264 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5265 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5266 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5267 ICS.setBad(BadConversionSequence::bad_qualifiers, 5268 FromType, ImplicitParamType); 5269 return ICS; 5270 } 5271 } 5272 5273 // Check that we have either the same type or a derived type. It 5274 // affects the conversion rank. 5275 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5276 ImplicitConversionKind SecondKind; 5277 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5278 SecondKind = ICK_Identity; 5279 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5280 SecondKind = ICK_Derived_To_Base; 5281 else { 5282 ICS.setBad(BadConversionSequence::unrelated_class, 5283 FromType, ImplicitParamType); 5284 return ICS; 5285 } 5286 5287 // Check the ref-qualifier. 5288 switch (Method->getRefQualifier()) { 5289 case RQ_None: 5290 // Do nothing; we don't care about lvalueness or rvalueness. 5291 break; 5292 5293 case RQ_LValue: 5294 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5295 // non-const lvalue reference cannot bind to an rvalue 5296 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5297 ImplicitParamType); 5298 return ICS; 5299 } 5300 break; 5301 5302 case RQ_RValue: 5303 if (!FromClassification.isRValue()) { 5304 // rvalue reference cannot bind to an lvalue 5305 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5306 ImplicitParamType); 5307 return ICS; 5308 } 5309 break; 5310 } 5311 5312 // Success. Mark this as a reference binding. 5313 ICS.setStandard(); 5314 ICS.Standard.setAsIdentityConversion(); 5315 ICS.Standard.Second = SecondKind; 5316 ICS.Standard.setFromType(FromType); 5317 ICS.Standard.setAllToTypes(ImplicitParamType); 5318 ICS.Standard.ReferenceBinding = true; 5319 ICS.Standard.DirectBinding = true; 5320 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5321 ICS.Standard.BindsToFunctionLvalue = false; 5322 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5323 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5324 = (Method->getRefQualifier() == RQ_None); 5325 return ICS; 5326 } 5327 5328 /// PerformObjectArgumentInitialization - Perform initialization of 5329 /// the implicit object parameter for the given Method with the given 5330 /// expression. 5331 ExprResult 5332 Sema::PerformObjectArgumentInitialization(Expr *From, 5333 NestedNameSpecifier *Qualifier, 5334 NamedDecl *FoundDecl, 5335 CXXMethodDecl *Method) { 5336 QualType FromRecordType, DestType; 5337 QualType ImplicitParamRecordType = 5338 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5339 5340 Expr::Classification FromClassification; 5341 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5342 FromRecordType = PT->getPointeeType(); 5343 DestType = Method->getThisType(); 5344 FromClassification = Expr::Classification::makeSimpleLValue(); 5345 } else { 5346 FromRecordType = From->getType(); 5347 DestType = ImplicitParamRecordType; 5348 FromClassification = From->Classify(Context); 5349 5350 // When performing member access on an rvalue, materialize a temporary. 5351 if (From->isRValue()) { 5352 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5353 Method->getRefQualifier() != 5354 RefQualifierKind::RQ_RValue); 5355 } 5356 } 5357 5358 // Note that we always use the true parent context when performing 5359 // the actual argument initialization. 5360 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5361 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5362 Method->getParent()); 5363 if (ICS.isBad()) { 5364 switch (ICS.Bad.Kind) { 5365 case BadConversionSequence::bad_qualifiers: { 5366 Qualifiers FromQs = FromRecordType.getQualifiers(); 5367 Qualifiers ToQs = DestType.getQualifiers(); 5368 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5369 if (CVR) { 5370 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5371 << Method->getDeclName() << FromRecordType << (CVR - 1) 5372 << From->getSourceRange(); 5373 Diag(Method->getLocation(), diag::note_previous_decl) 5374 << Method->getDeclName(); 5375 return ExprError(); 5376 } 5377 break; 5378 } 5379 5380 case BadConversionSequence::lvalue_ref_to_rvalue: 5381 case BadConversionSequence::rvalue_ref_to_lvalue: { 5382 bool IsRValueQualified = 5383 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5384 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5385 << Method->getDeclName() << FromClassification.isRValue() 5386 << IsRValueQualified; 5387 Diag(Method->getLocation(), diag::note_previous_decl) 5388 << Method->getDeclName(); 5389 return ExprError(); 5390 } 5391 5392 case BadConversionSequence::no_conversion: 5393 case BadConversionSequence::unrelated_class: 5394 break; 5395 } 5396 5397 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5398 << ImplicitParamRecordType << FromRecordType 5399 << From->getSourceRange(); 5400 } 5401 5402 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5403 ExprResult FromRes = 5404 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5405 if (FromRes.isInvalid()) 5406 return ExprError(); 5407 From = FromRes.get(); 5408 } 5409 5410 if (!Context.hasSameType(From->getType(), DestType)) { 5411 CastKind CK; 5412 QualType PteeTy = DestType->getPointeeType(); 5413 LangAS DestAS = 5414 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5415 if (FromRecordType.getAddressSpace() != DestAS) 5416 CK = CK_AddressSpaceConversion; 5417 else 5418 CK = CK_NoOp; 5419 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5420 } 5421 return From; 5422 } 5423 5424 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5425 /// expression From to bool (C++0x [conv]p3). 5426 static ImplicitConversionSequence 5427 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5428 return TryImplicitConversion(S, From, S.Context.BoolTy, 5429 /*SuppressUserConversions=*/false, 5430 /*AllowExplicit=*/true, 5431 /*InOverloadResolution=*/false, 5432 /*CStyle=*/false, 5433 /*AllowObjCWritebackConversion=*/false, 5434 /*AllowObjCConversionOnExplicit=*/false); 5435 } 5436 5437 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5438 /// of the expression From to bool (C++0x [conv]p3). 5439 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5440 if (checkPlaceholderForOverload(*this, From)) 5441 return ExprError(); 5442 5443 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5444 if (!ICS.isBad()) 5445 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5446 5447 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5448 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5449 << From->getType() << From->getSourceRange(); 5450 return ExprError(); 5451 } 5452 5453 /// Check that the specified conversion is permitted in a converted constant 5454 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5455 /// is acceptable. 5456 static bool CheckConvertedConstantConversions(Sema &S, 5457 StandardConversionSequence &SCS) { 5458 // Since we know that the target type is an integral or unscoped enumeration 5459 // type, most conversion kinds are impossible. All possible First and Third 5460 // conversions are fine. 5461 switch (SCS.Second) { 5462 case ICK_Identity: 5463 case ICK_Function_Conversion: 5464 case ICK_Integral_Promotion: 5465 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5466 case ICK_Zero_Queue_Conversion: 5467 return true; 5468 5469 case ICK_Boolean_Conversion: 5470 // Conversion from an integral or unscoped enumeration type to bool is 5471 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5472 // conversion, so we allow it in a converted constant expression. 5473 // 5474 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5475 // a lot of popular code. We should at least add a warning for this 5476 // (non-conforming) extension. 5477 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5478 SCS.getToType(2)->isBooleanType(); 5479 5480 case ICK_Pointer_Conversion: 5481 case ICK_Pointer_Member: 5482 // C++1z: null pointer conversions and null member pointer conversions are 5483 // only permitted if the source type is std::nullptr_t. 5484 return SCS.getFromType()->isNullPtrType(); 5485 5486 case ICK_Floating_Promotion: 5487 case ICK_Complex_Promotion: 5488 case ICK_Floating_Conversion: 5489 case ICK_Complex_Conversion: 5490 case ICK_Floating_Integral: 5491 case ICK_Compatible_Conversion: 5492 case ICK_Derived_To_Base: 5493 case ICK_Vector_Conversion: 5494 case ICK_Vector_Splat: 5495 case ICK_Complex_Real: 5496 case ICK_Block_Pointer_Conversion: 5497 case ICK_TransparentUnionConversion: 5498 case ICK_Writeback_Conversion: 5499 case ICK_Zero_Event_Conversion: 5500 case ICK_C_Only_Conversion: 5501 case ICK_Incompatible_Pointer_Conversion: 5502 return false; 5503 5504 case ICK_Lvalue_To_Rvalue: 5505 case ICK_Array_To_Pointer: 5506 case ICK_Function_To_Pointer: 5507 llvm_unreachable("found a first conversion kind in Second"); 5508 5509 case ICK_Qualification: 5510 llvm_unreachable("found a third conversion kind in Second"); 5511 5512 case ICK_Num_Conversion_Kinds: 5513 break; 5514 } 5515 5516 llvm_unreachable("unknown conversion kind"); 5517 } 5518 5519 /// CheckConvertedConstantExpression - Check that the expression From is a 5520 /// converted constant expression of type T, perform the conversion and produce 5521 /// the converted expression, per C++11 [expr.const]p3. 5522 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5523 QualType T, APValue &Value, 5524 Sema::CCEKind CCE, 5525 bool RequireInt) { 5526 assert(S.getLangOpts().CPlusPlus11 && 5527 "converted constant expression outside C++11"); 5528 5529 if (checkPlaceholderForOverload(S, From)) 5530 return ExprError(); 5531 5532 // C++1z [expr.const]p3: 5533 // A converted constant expression of type T is an expression, 5534 // implicitly converted to type T, where the converted 5535 // expression is a constant expression and the implicit conversion 5536 // sequence contains only [... list of conversions ...]. 5537 // C++1z [stmt.if]p2: 5538 // If the if statement is of the form if constexpr, the value of the 5539 // condition shall be a contextually converted constant expression of type 5540 // bool. 5541 ImplicitConversionSequence ICS = 5542 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5543 ? TryContextuallyConvertToBool(S, From) 5544 : TryCopyInitialization(S, From, T, 5545 /*SuppressUserConversions=*/false, 5546 /*InOverloadResolution=*/false, 5547 /*AllowObjCWritebackConversion=*/false, 5548 /*AllowExplicit=*/false); 5549 StandardConversionSequence *SCS = nullptr; 5550 switch (ICS.getKind()) { 5551 case ImplicitConversionSequence::StandardConversion: 5552 SCS = &ICS.Standard; 5553 break; 5554 case ImplicitConversionSequence::UserDefinedConversion: 5555 // We are converting to a non-class type, so the Before sequence 5556 // must be trivial. 5557 SCS = &ICS.UserDefined.After; 5558 break; 5559 case ImplicitConversionSequence::AmbiguousConversion: 5560 case ImplicitConversionSequence::BadConversion: 5561 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5562 return S.Diag(From->getBeginLoc(), 5563 diag::err_typecheck_converted_constant_expression) 5564 << From->getType() << From->getSourceRange() << T; 5565 return ExprError(); 5566 5567 case ImplicitConversionSequence::EllipsisConversion: 5568 llvm_unreachable("ellipsis conversion in converted constant expression"); 5569 } 5570 5571 // Check that we would only use permitted conversions. 5572 if (!CheckConvertedConstantConversions(S, *SCS)) { 5573 return S.Diag(From->getBeginLoc(), 5574 diag::err_typecheck_converted_constant_expression_disallowed) 5575 << From->getType() << From->getSourceRange() << T; 5576 } 5577 // [...] and where the reference binding (if any) binds directly. 5578 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5579 return S.Diag(From->getBeginLoc(), 5580 diag::err_typecheck_converted_constant_expression_indirect) 5581 << From->getType() << From->getSourceRange() << T; 5582 } 5583 5584 ExprResult Result = 5585 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5586 if (Result.isInvalid()) 5587 return Result; 5588 5589 // C++2a [intro.execution]p5: 5590 // A full-expression is [...] a constant-expression [...] 5591 Result = 5592 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5593 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5594 if (Result.isInvalid()) 5595 return Result; 5596 5597 // Check for a narrowing implicit conversion. 5598 APValue PreNarrowingValue; 5599 QualType PreNarrowingType; 5600 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5601 PreNarrowingType)) { 5602 case NK_Dependent_Narrowing: 5603 // Implicit conversion to a narrower type, but the expression is 5604 // value-dependent so we can't tell whether it's actually narrowing. 5605 case NK_Variable_Narrowing: 5606 // Implicit conversion to a narrower type, and the value is not a constant 5607 // expression. We'll diagnose this in a moment. 5608 case NK_Not_Narrowing: 5609 break; 5610 5611 case NK_Constant_Narrowing: 5612 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5613 << CCE << /*Constant*/ 1 5614 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5615 break; 5616 5617 case NK_Type_Narrowing: 5618 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5619 << CCE << /*Constant*/ 0 << From->getType() << T; 5620 break; 5621 } 5622 5623 if (Result.get()->isValueDependent()) { 5624 Value = APValue(); 5625 return Result; 5626 } 5627 5628 // Check the expression is a constant expression. 5629 SmallVector<PartialDiagnosticAt, 8> Notes; 5630 Expr::EvalResult Eval; 5631 Eval.Diag = &Notes; 5632 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5633 ? Expr::EvaluateForMangling 5634 : Expr::EvaluateForCodeGen; 5635 5636 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5637 (RequireInt && !Eval.Val.isInt())) { 5638 // The expression can't be folded, so we can't keep it at this position in 5639 // the AST. 5640 Result = ExprError(); 5641 } else { 5642 Value = Eval.Val; 5643 5644 if (Notes.empty()) { 5645 // It's a constant expression. 5646 return ConstantExpr::Create(S.Context, Result.get(), Value); 5647 } 5648 } 5649 5650 // It's not a constant expression. Produce an appropriate diagnostic. 5651 if (Notes.size() == 1 && 5652 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5653 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5654 else { 5655 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5656 << CCE << From->getSourceRange(); 5657 for (unsigned I = 0; I < Notes.size(); ++I) 5658 S.Diag(Notes[I].first, Notes[I].second); 5659 } 5660 return ExprError(); 5661 } 5662 5663 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5664 APValue &Value, CCEKind CCE) { 5665 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5666 } 5667 5668 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5669 llvm::APSInt &Value, 5670 CCEKind CCE) { 5671 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5672 5673 APValue V; 5674 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5675 if (!R.isInvalid() && !R.get()->isValueDependent()) 5676 Value = V.getInt(); 5677 return R; 5678 } 5679 5680 5681 /// dropPointerConversions - If the given standard conversion sequence 5682 /// involves any pointer conversions, remove them. This may change 5683 /// the result type of the conversion sequence. 5684 static void dropPointerConversion(StandardConversionSequence &SCS) { 5685 if (SCS.Second == ICK_Pointer_Conversion) { 5686 SCS.Second = ICK_Identity; 5687 SCS.Third = ICK_Identity; 5688 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5689 } 5690 } 5691 5692 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5693 /// convert the expression From to an Objective-C pointer type. 5694 static ImplicitConversionSequence 5695 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5696 // Do an implicit conversion to 'id'. 5697 QualType Ty = S.Context.getObjCIdType(); 5698 ImplicitConversionSequence ICS 5699 = TryImplicitConversion(S, From, Ty, 5700 // FIXME: Are these flags correct? 5701 /*SuppressUserConversions=*/false, 5702 /*AllowExplicit=*/true, 5703 /*InOverloadResolution=*/false, 5704 /*CStyle=*/false, 5705 /*AllowObjCWritebackConversion=*/false, 5706 /*AllowObjCConversionOnExplicit=*/true); 5707 5708 // Strip off any final conversions to 'id'. 5709 switch (ICS.getKind()) { 5710 case ImplicitConversionSequence::BadConversion: 5711 case ImplicitConversionSequence::AmbiguousConversion: 5712 case ImplicitConversionSequence::EllipsisConversion: 5713 break; 5714 5715 case ImplicitConversionSequence::UserDefinedConversion: 5716 dropPointerConversion(ICS.UserDefined.After); 5717 break; 5718 5719 case ImplicitConversionSequence::StandardConversion: 5720 dropPointerConversion(ICS.Standard); 5721 break; 5722 } 5723 5724 return ICS; 5725 } 5726 5727 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5728 /// conversion of the expression From to an Objective-C pointer type. 5729 /// Returns a valid but null ExprResult if no conversion sequence exists. 5730 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5731 if (checkPlaceholderForOverload(*this, From)) 5732 return ExprError(); 5733 5734 QualType Ty = Context.getObjCIdType(); 5735 ImplicitConversionSequence ICS = 5736 TryContextuallyConvertToObjCPointer(*this, From); 5737 if (!ICS.isBad()) 5738 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5739 return ExprResult(); 5740 } 5741 5742 /// Determine whether the provided type is an integral type, or an enumeration 5743 /// type of a permitted flavor. 5744 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5745 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5746 : T->isIntegralOrUnscopedEnumerationType(); 5747 } 5748 5749 static ExprResult 5750 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5751 Sema::ContextualImplicitConverter &Converter, 5752 QualType T, UnresolvedSetImpl &ViableConversions) { 5753 5754 if (Converter.Suppress) 5755 return ExprError(); 5756 5757 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5758 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5759 CXXConversionDecl *Conv = 5760 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5761 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5762 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5763 } 5764 return From; 5765 } 5766 5767 static bool 5768 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5769 Sema::ContextualImplicitConverter &Converter, 5770 QualType T, bool HadMultipleCandidates, 5771 UnresolvedSetImpl &ExplicitConversions) { 5772 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5773 DeclAccessPair Found = ExplicitConversions[0]; 5774 CXXConversionDecl *Conversion = 5775 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5776 5777 // The user probably meant to invoke the given explicit 5778 // conversion; use it. 5779 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5780 std::string TypeStr; 5781 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5782 5783 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5784 << FixItHint::CreateInsertion(From->getBeginLoc(), 5785 "static_cast<" + TypeStr + ">(") 5786 << FixItHint::CreateInsertion( 5787 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5788 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5789 5790 // If we aren't in a SFINAE context, build a call to the 5791 // explicit conversion function. 5792 if (SemaRef.isSFINAEContext()) 5793 return true; 5794 5795 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5796 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5797 HadMultipleCandidates); 5798 if (Result.isInvalid()) 5799 return true; 5800 // Record usage of conversion in an implicit cast. 5801 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5802 CK_UserDefinedConversion, Result.get(), 5803 nullptr, Result.get()->getValueKind()); 5804 } 5805 return false; 5806 } 5807 5808 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5809 Sema::ContextualImplicitConverter &Converter, 5810 QualType T, bool HadMultipleCandidates, 5811 DeclAccessPair &Found) { 5812 CXXConversionDecl *Conversion = 5813 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5814 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5815 5816 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5817 if (!Converter.SuppressConversion) { 5818 if (SemaRef.isSFINAEContext()) 5819 return true; 5820 5821 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5822 << From->getSourceRange(); 5823 } 5824 5825 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5826 HadMultipleCandidates); 5827 if (Result.isInvalid()) 5828 return true; 5829 // Record usage of conversion in an implicit cast. 5830 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5831 CK_UserDefinedConversion, Result.get(), 5832 nullptr, Result.get()->getValueKind()); 5833 return false; 5834 } 5835 5836 static ExprResult finishContextualImplicitConversion( 5837 Sema &SemaRef, SourceLocation Loc, Expr *From, 5838 Sema::ContextualImplicitConverter &Converter) { 5839 if (!Converter.match(From->getType()) && !Converter.Suppress) 5840 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5841 << From->getSourceRange(); 5842 5843 return SemaRef.DefaultLvalueConversion(From); 5844 } 5845 5846 static void 5847 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5848 UnresolvedSetImpl &ViableConversions, 5849 OverloadCandidateSet &CandidateSet) { 5850 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5851 DeclAccessPair FoundDecl = ViableConversions[I]; 5852 NamedDecl *D = FoundDecl.getDecl(); 5853 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5854 if (isa<UsingShadowDecl>(D)) 5855 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5856 5857 CXXConversionDecl *Conv; 5858 FunctionTemplateDecl *ConvTemplate; 5859 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5860 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5861 else 5862 Conv = cast<CXXConversionDecl>(D); 5863 5864 if (ConvTemplate) 5865 SemaRef.AddTemplateConversionCandidate( 5866 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5867 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5868 else 5869 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5870 ToType, CandidateSet, 5871 /*AllowObjCConversionOnExplicit=*/false, 5872 /*AllowExplicit*/ true); 5873 } 5874 } 5875 5876 /// Attempt to convert the given expression to a type which is accepted 5877 /// by the given converter. 5878 /// 5879 /// This routine will attempt to convert an expression of class type to a 5880 /// type accepted by the specified converter. In C++11 and before, the class 5881 /// must have a single non-explicit conversion function converting to a matching 5882 /// type. In C++1y, there can be multiple such conversion functions, but only 5883 /// one target type. 5884 /// 5885 /// \param Loc The source location of the construct that requires the 5886 /// conversion. 5887 /// 5888 /// \param From The expression we're converting from. 5889 /// 5890 /// \param Converter Used to control and diagnose the conversion process. 5891 /// 5892 /// \returns The expression, converted to an integral or enumeration type if 5893 /// successful. 5894 ExprResult Sema::PerformContextualImplicitConversion( 5895 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5896 // We can't perform any more checking for type-dependent expressions. 5897 if (From->isTypeDependent()) 5898 return From; 5899 5900 // Process placeholders immediately. 5901 if (From->hasPlaceholderType()) { 5902 ExprResult result = CheckPlaceholderExpr(From); 5903 if (result.isInvalid()) 5904 return result; 5905 From = result.get(); 5906 } 5907 5908 // If the expression already has a matching type, we're golden. 5909 QualType T = From->getType(); 5910 if (Converter.match(T)) 5911 return DefaultLvalueConversion(From); 5912 5913 // FIXME: Check for missing '()' if T is a function type? 5914 5915 // We can only perform contextual implicit conversions on objects of class 5916 // type. 5917 const RecordType *RecordTy = T->getAs<RecordType>(); 5918 if (!RecordTy || !getLangOpts().CPlusPlus) { 5919 if (!Converter.Suppress) 5920 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5921 return From; 5922 } 5923 5924 // We must have a complete class type. 5925 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5926 ContextualImplicitConverter &Converter; 5927 Expr *From; 5928 5929 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5930 : Converter(Converter), From(From) {} 5931 5932 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5933 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5934 } 5935 } IncompleteDiagnoser(Converter, From); 5936 5937 if (Converter.Suppress ? !isCompleteType(Loc, T) 5938 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5939 return From; 5940 5941 // Look for a conversion to an integral or enumeration type. 5942 UnresolvedSet<4> 5943 ViableConversions; // These are *potentially* viable in C++1y. 5944 UnresolvedSet<4> ExplicitConversions; 5945 const auto &Conversions = 5946 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5947 5948 bool HadMultipleCandidates = 5949 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5950 5951 // To check that there is only one target type, in C++1y: 5952 QualType ToType; 5953 bool HasUniqueTargetType = true; 5954 5955 // Collect explicit or viable (potentially in C++1y) conversions. 5956 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5957 NamedDecl *D = (*I)->getUnderlyingDecl(); 5958 CXXConversionDecl *Conversion; 5959 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5960 if (ConvTemplate) { 5961 if (getLangOpts().CPlusPlus14) 5962 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5963 else 5964 continue; // C++11 does not consider conversion operator templates(?). 5965 } else 5966 Conversion = cast<CXXConversionDecl>(D); 5967 5968 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5969 "Conversion operator templates are considered potentially " 5970 "viable in C++1y"); 5971 5972 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5973 if (Converter.match(CurToType) || ConvTemplate) { 5974 5975 if (Conversion->isExplicit()) { 5976 // FIXME: For C++1y, do we need this restriction? 5977 // cf. diagnoseNoViableConversion() 5978 if (!ConvTemplate) 5979 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5980 } else { 5981 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5982 if (ToType.isNull()) 5983 ToType = CurToType.getUnqualifiedType(); 5984 else if (HasUniqueTargetType && 5985 (CurToType.getUnqualifiedType() != ToType)) 5986 HasUniqueTargetType = false; 5987 } 5988 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5989 } 5990 } 5991 } 5992 5993 if (getLangOpts().CPlusPlus14) { 5994 // C++1y [conv]p6: 5995 // ... An expression e of class type E appearing in such a context 5996 // is said to be contextually implicitly converted to a specified 5997 // type T and is well-formed if and only if e can be implicitly 5998 // converted to a type T that is determined as follows: E is searched 5999 // for conversion functions whose return type is cv T or reference to 6000 // cv T such that T is allowed by the context. There shall be 6001 // exactly one such T. 6002 6003 // If no unique T is found: 6004 if (ToType.isNull()) { 6005 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6006 HadMultipleCandidates, 6007 ExplicitConversions)) 6008 return ExprError(); 6009 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6010 } 6011 6012 // If more than one unique Ts are found: 6013 if (!HasUniqueTargetType) 6014 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6015 ViableConversions); 6016 6017 // If one unique T is found: 6018 // First, build a candidate set from the previously recorded 6019 // potentially viable conversions. 6020 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6021 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6022 CandidateSet); 6023 6024 // Then, perform overload resolution over the candidate set. 6025 OverloadCandidateSet::iterator Best; 6026 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6027 case OR_Success: { 6028 // Apply this conversion. 6029 DeclAccessPair Found = 6030 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6031 if (recordConversion(*this, Loc, From, Converter, T, 6032 HadMultipleCandidates, Found)) 6033 return ExprError(); 6034 break; 6035 } 6036 case OR_Ambiguous: 6037 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6038 ViableConversions); 6039 case OR_No_Viable_Function: 6040 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6041 HadMultipleCandidates, 6042 ExplicitConversions)) 6043 return ExprError(); 6044 LLVM_FALLTHROUGH; 6045 case OR_Deleted: 6046 // We'll complain below about a non-integral condition type. 6047 break; 6048 } 6049 } else { 6050 switch (ViableConversions.size()) { 6051 case 0: { 6052 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6053 HadMultipleCandidates, 6054 ExplicitConversions)) 6055 return ExprError(); 6056 6057 // We'll complain below about a non-integral condition type. 6058 break; 6059 } 6060 case 1: { 6061 // Apply this conversion. 6062 DeclAccessPair Found = ViableConversions[0]; 6063 if (recordConversion(*this, Loc, From, Converter, T, 6064 HadMultipleCandidates, Found)) 6065 return ExprError(); 6066 break; 6067 } 6068 default: 6069 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6070 ViableConversions); 6071 } 6072 } 6073 6074 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6075 } 6076 6077 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6078 /// an acceptable non-member overloaded operator for a call whose 6079 /// arguments have types T1 (and, if non-empty, T2). This routine 6080 /// implements the check in C++ [over.match.oper]p3b2 concerning 6081 /// enumeration types. 6082 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6083 FunctionDecl *Fn, 6084 ArrayRef<Expr *> Args) { 6085 QualType T1 = Args[0]->getType(); 6086 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6087 6088 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6089 return true; 6090 6091 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6092 return true; 6093 6094 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6095 if (Proto->getNumParams() < 1) 6096 return false; 6097 6098 if (T1->isEnumeralType()) { 6099 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6100 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6101 return true; 6102 } 6103 6104 if (Proto->getNumParams() < 2) 6105 return false; 6106 6107 if (!T2.isNull() && T2->isEnumeralType()) { 6108 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6109 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6110 return true; 6111 } 6112 6113 return false; 6114 } 6115 6116 /// AddOverloadCandidate - Adds the given function to the set of 6117 /// candidate functions, using the given function call arguments. If 6118 /// @p SuppressUserConversions, then don't allow user-defined 6119 /// conversions via constructors or conversion operators. 6120 /// 6121 /// \param PartialOverloading true if we are performing "partial" overloading 6122 /// based on an incomplete set of function arguments. This feature is used by 6123 /// code completion. 6124 void Sema::AddOverloadCandidate( 6125 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6126 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6127 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6128 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6129 OverloadCandidateParamOrder PO) { 6130 const FunctionProtoType *Proto 6131 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6132 assert(Proto && "Functions without a prototype cannot be overloaded"); 6133 assert(!Function->getDescribedFunctionTemplate() && 6134 "Use AddTemplateOverloadCandidate for function templates"); 6135 6136 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6137 if (!isa<CXXConstructorDecl>(Method)) { 6138 // If we get here, it's because we're calling a member function 6139 // that is named without a member access expression (e.g., 6140 // "this->f") that was either written explicitly or created 6141 // implicitly. This can happen with a qualified call to a member 6142 // function, e.g., X::f(). We use an empty type for the implied 6143 // object argument (C++ [over.call.func]p3), and the acting context 6144 // is irrelevant. 6145 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6146 Expr::Classification::makeSimpleLValue(), Args, 6147 CandidateSet, SuppressUserConversions, 6148 PartialOverloading, EarlyConversions, PO); 6149 return; 6150 } 6151 // We treat a constructor like a non-member function, since its object 6152 // argument doesn't participate in overload resolution. 6153 } 6154 6155 if (!CandidateSet.isNewCandidate(Function, PO)) 6156 return; 6157 6158 // C++11 [class.copy]p11: [DR1402] 6159 // A defaulted move constructor that is defined as deleted is ignored by 6160 // overload resolution. 6161 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6162 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6163 Constructor->isMoveConstructor()) 6164 return; 6165 6166 // Overload resolution is always an unevaluated context. 6167 EnterExpressionEvaluationContext Unevaluated( 6168 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6169 6170 // C++ [over.match.oper]p3: 6171 // if no operand has a class type, only those non-member functions in the 6172 // lookup set that have a first parameter of type T1 or "reference to 6173 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6174 // is a right operand) a second parameter of type T2 or "reference to 6175 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6176 // candidate functions. 6177 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6178 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6179 return; 6180 6181 // Add this candidate 6182 OverloadCandidate &Candidate = 6183 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6184 Candidate.FoundDecl = FoundDecl; 6185 Candidate.Function = Function; 6186 Candidate.Viable = true; 6187 Candidate.RewriteKind = 6188 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6189 Candidate.IsSurrogate = false; 6190 Candidate.IsADLCandidate = IsADLCandidate; 6191 Candidate.IgnoreObjectArgument = false; 6192 Candidate.ExplicitCallArguments = Args.size(); 6193 6194 // Explicit functions are not actually candidates at all if we're not 6195 // allowing them in this context, but keep them around so we can point 6196 // to them in diagnostics. 6197 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6198 Candidate.Viable = false; 6199 Candidate.FailureKind = ovl_fail_explicit; 6200 return; 6201 } 6202 6203 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6204 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6205 Candidate.Viable = false; 6206 Candidate.FailureKind = ovl_non_default_multiversion_function; 6207 return; 6208 } 6209 6210 if (Constructor) { 6211 // C++ [class.copy]p3: 6212 // A member function template is never instantiated to perform the copy 6213 // of a class object to an object of its class type. 6214 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6215 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6216 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6217 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6218 ClassType))) { 6219 Candidate.Viable = false; 6220 Candidate.FailureKind = ovl_fail_illegal_constructor; 6221 return; 6222 } 6223 6224 // C++ [over.match.funcs]p8: (proposed DR resolution) 6225 // A constructor inherited from class type C that has a first parameter 6226 // of type "reference to P" (including such a constructor instantiated 6227 // from a template) is excluded from the set of candidate functions when 6228 // constructing an object of type cv D if the argument list has exactly 6229 // one argument and D is reference-related to P and P is reference-related 6230 // to C. 6231 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6232 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6233 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6234 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6235 QualType C = Context.getRecordType(Constructor->getParent()); 6236 QualType D = Context.getRecordType(Shadow->getParent()); 6237 SourceLocation Loc = Args.front()->getExprLoc(); 6238 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6239 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6240 Candidate.Viable = false; 6241 Candidate.FailureKind = ovl_fail_inhctor_slice; 6242 return; 6243 } 6244 } 6245 6246 // Check that the constructor is capable of constructing an object in the 6247 // destination address space. 6248 if (!Qualifiers::isAddressSpaceSupersetOf( 6249 Constructor->getMethodQualifiers().getAddressSpace(), 6250 CandidateSet.getDestAS())) { 6251 Candidate.Viable = false; 6252 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6253 } 6254 } 6255 6256 unsigned NumParams = Proto->getNumParams(); 6257 6258 // (C++ 13.3.2p2): A candidate function having fewer than m 6259 // parameters is viable only if it has an ellipsis in its parameter 6260 // list (8.3.5). 6261 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6262 !Proto->isVariadic()) { 6263 Candidate.Viable = false; 6264 Candidate.FailureKind = ovl_fail_too_many_arguments; 6265 return; 6266 } 6267 6268 // (C++ 13.3.2p2): A candidate function having more than m parameters 6269 // is viable only if the (m+1)st parameter has a default argument 6270 // (8.3.6). For the purposes of overload resolution, the 6271 // parameter list is truncated on the right, so that there are 6272 // exactly m parameters. 6273 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6274 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6275 // Not enough arguments. 6276 Candidate.Viable = false; 6277 Candidate.FailureKind = ovl_fail_too_few_arguments; 6278 return; 6279 } 6280 6281 // (CUDA B.1): Check for invalid calls between targets. 6282 if (getLangOpts().CUDA) 6283 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6284 // Skip the check for callers that are implicit members, because in this 6285 // case we may not yet know what the member's target is; the target is 6286 // inferred for the member automatically, based on the bases and fields of 6287 // the class. 6288 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6289 Candidate.Viable = false; 6290 Candidate.FailureKind = ovl_fail_bad_target; 6291 return; 6292 } 6293 6294 if (Expr *RequiresClause = Function->getTrailingRequiresClause()) { 6295 ConstraintSatisfaction Satisfaction; 6296 if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) || 6297 !Satisfaction.IsSatisfied) { 6298 Candidate.Viable = false; 6299 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6300 return; 6301 } 6302 } 6303 6304 // Determine the implicit conversion sequences for each of the 6305 // arguments. 6306 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6307 unsigned ConvIdx = 6308 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6309 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6310 // We already formed a conversion sequence for this parameter during 6311 // template argument deduction. 6312 } else if (ArgIdx < NumParams) { 6313 // (C++ 13.3.2p3): for F to be a viable function, there shall 6314 // exist for each argument an implicit conversion sequence 6315 // (13.3.3.1) that converts that argument to the corresponding 6316 // parameter of F. 6317 QualType ParamType = Proto->getParamType(ArgIdx); 6318 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6319 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6320 /*InOverloadResolution=*/true, 6321 /*AllowObjCWritebackConversion=*/ 6322 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6323 if (Candidate.Conversions[ConvIdx].isBad()) { 6324 Candidate.Viable = false; 6325 Candidate.FailureKind = ovl_fail_bad_conversion; 6326 return; 6327 } 6328 } else { 6329 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6330 // argument for which there is no corresponding parameter is 6331 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6332 Candidate.Conversions[ConvIdx].setEllipsis(); 6333 } 6334 } 6335 6336 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6337 Candidate.Viable = false; 6338 Candidate.FailureKind = ovl_fail_enable_if; 6339 Candidate.DeductionFailure.Data = FailedAttr; 6340 return; 6341 } 6342 6343 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6344 Candidate.Viable = false; 6345 Candidate.FailureKind = ovl_fail_ext_disabled; 6346 return; 6347 } 6348 } 6349 6350 ObjCMethodDecl * 6351 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6352 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6353 if (Methods.size() <= 1) 6354 return nullptr; 6355 6356 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6357 bool Match = true; 6358 ObjCMethodDecl *Method = Methods[b]; 6359 unsigned NumNamedArgs = Sel.getNumArgs(); 6360 // Method might have more arguments than selector indicates. This is due 6361 // to addition of c-style arguments in method. 6362 if (Method->param_size() > NumNamedArgs) 6363 NumNamedArgs = Method->param_size(); 6364 if (Args.size() < NumNamedArgs) 6365 continue; 6366 6367 for (unsigned i = 0; i < NumNamedArgs; i++) { 6368 // We can't do any type-checking on a type-dependent argument. 6369 if (Args[i]->isTypeDependent()) { 6370 Match = false; 6371 break; 6372 } 6373 6374 ParmVarDecl *param = Method->parameters()[i]; 6375 Expr *argExpr = Args[i]; 6376 assert(argExpr && "SelectBestMethod(): missing expression"); 6377 6378 // Strip the unbridged-cast placeholder expression off unless it's 6379 // a consumed argument. 6380 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6381 !param->hasAttr<CFConsumedAttr>()) 6382 argExpr = stripARCUnbridgedCast(argExpr); 6383 6384 // If the parameter is __unknown_anytype, move on to the next method. 6385 if (param->getType() == Context.UnknownAnyTy) { 6386 Match = false; 6387 break; 6388 } 6389 6390 ImplicitConversionSequence ConversionState 6391 = TryCopyInitialization(*this, argExpr, param->getType(), 6392 /*SuppressUserConversions*/false, 6393 /*InOverloadResolution=*/true, 6394 /*AllowObjCWritebackConversion=*/ 6395 getLangOpts().ObjCAutoRefCount, 6396 /*AllowExplicit*/false); 6397 // This function looks for a reasonably-exact match, so we consider 6398 // incompatible pointer conversions to be a failure here. 6399 if (ConversionState.isBad() || 6400 (ConversionState.isStandard() && 6401 ConversionState.Standard.Second == 6402 ICK_Incompatible_Pointer_Conversion)) { 6403 Match = false; 6404 break; 6405 } 6406 } 6407 // Promote additional arguments to variadic methods. 6408 if (Match && Method->isVariadic()) { 6409 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6410 if (Args[i]->isTypeDependent()) { 6411 Match = false; 6412 break; 6413 } 6414 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6415 nullptr); 6416 if (Arg.isInvalid()) { 6417 Match = false; 6418 break; 6419 } 6420 } 6421 } else { 6422 // Check for extra arguments to non-variadic methods. 6423 if (Args.size() != NumNamedArgs) 6424 Match = false; 6425 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6426 // Special case when selectors have no argument. In this case, select 6427 // one with the most general result type of 'id'. 6428 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6429 QualType ReturnT = Methods[b]->getReturnType(); 6430 if (ReturnT->isObjCIdType()) 6431 return Methods[b]; 6432 } 6433 } 6434 } 6435 6436 if (Match) 6437 return Method; 6438 } 6439 return nullptr; 6440 } 6441 6442 static bool 6443 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6444 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6445 bool MissingImplicitThis, Expr *&ConvertedThis, 6446 SmallVectorImpl<Expr *> &ConvertedArgs) { 6447 if (ThisArg) { 6448 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6449 assert(!isa<CXXConstructorDecl>(Method) && 6450 "Shouldn't have `this` for ctors!"); 6451 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6452 ExprResult R = S.PerformObjectArgumentInitialization( 6453 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6454 if (R.isInvalid()) 6455 return false; 6456 ConvertedThis = R.get(); 6457 } else { 6458 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6459 (void)MD; 6460 assert((MissingImplicitThis || MD->isStatic() || 6461 isa<CXXConstructorDecl>(MD)) && 6462 "Expected `this` for non-ctor instance methods"); 6463 } 6464 ConvertedThis = nullptr; 6465 } 6466 6467 // Ignore any variadic arguments. Converting them is pointless, since the 6468 // user can't refer to them in the function condition. 6469 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6470 6471 // Convert the arguments. 6472 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6473 ExprResult R; 6474 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6475 S.Context, Function->getParamDecl(I)), 6476 SourceLocation(), Args[I]); 6477 6478 if (R.isInvalid()) 6479 return false; 6480 6481 ConvertedArgs.push_back(R.get()); 6482 } 6483 6484 if (Trap.hasErrorOccurred()) 6485 return false; 6486 6487 // Push default arguments if needed. 6488 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6489 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6490 ParmVarDecl *P = Function->getParamDecl(i); 6491 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6492 ? P->getUninstantiatedDefaultArg() 6493 : P->getDefaultArg(); 6494 // This can only happen in code completion, i.e. when PartialOverloading 6495 // is true. 6496 if (!DefArg) 6497 return false; 6498 ExprResult R = 6499 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6500 S.Context, Function->getParamDecl(i)), 6501 SourceLocation(), DefArg); 6502 if (R.isInvalid()) 6503 return false; 6504 ConvertedArgs.push_back(R.get()); 6505 } 6506 6507 if (Trap.hasErrorOccurred()) 6508 return false; 6509 } 6510 return true; 6511 } 6512 6513 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6514 bool MissingImplicitThis) { 6515 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6516 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6517 return nullptr; 6518 6519 SFINAETrap Trap(*this); 6520 SmallVector<Expr *, 16> ConvertedArgs; 6521 // FIXME: We should look into making enable_if late-parsed. 6522 Expr *DiscardedThis; 6523 if (!convertArgsForAvailabilityChecks( 6524 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6525 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6526 return *EnableIfAttrs.begin(); 6527 6528 for (auto *EIA : EnableIfAttrs) { 6529 APValue Result; 6530 // FIXME: This doesn't consider value-dependent cases, because doing so is 6531 // very difficult. Ideally, we should handle them more gracefully. 6532 if (EIA->getCond()->isValueDependent() || 6533 !EIA->getCond()->EvaluateWithSubstitution( 6534 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6535 return EIA; 6536 6537 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6538 return EIA; 6539 } 6540 return nullptr; 6541 } 6542 6543 template <typename CheckFn> 6544 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6545 bool ArgDependent, SourceLocation Loc, 6546 CheckFn &&IsSuccessful) { 6547 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6548 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6549 if (ArgDependent == DIA->getArgDependent()) 6550 Attrs.push_back(DIA); 6551 } 6552 6553 // Common case: No diagnose_if attributes, so we can quit early. 6554 if (Attrs.empty()) 6555 return false; 6556 6557 auto WarningBegin = std::stable_partition( 6558 Attrs.begin(), Attrs.end(), 6559 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6560 6561 // Note that diagnose_if attributes are late-parsed, so they appear in the 6562 // correct order (unlike enable_if attributes). 6563 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6564 IsSuccessful); 6565 if (ErrAttr != WarningBegin) { 6566 const DiagnoseIfAttr *DIA = *ErrAttr; 6567 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6568 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6569 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6570 return true; 6571 } 6572 6573 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6574 if (IsSuccessful(DIA)) { 6575 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6576 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6577 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6578 } 6579 6580 return false; 6581 } 6582 6583 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6584 const Expr *ThisArg, 6585 ArrayRef<const Expr *> Args, 6586 SourceLocation Loc) { 6587 return diagnoseDiagnoseIfAttrsWith( 6588 *this, Function, /*ArgDependent=*/true, Loc, 6589 [&](const DiagnoseIfAttr *DIA) { 6590 APValue Result; 6591 // It's sane to use the same Args for any redecl of this function, since 6592 // EvaluateWithSubstitution only cares about the position of each 6593 // argument in the arg list, not the ParmVarDecl* it maps to. 6594 if (!DIA->getCond()->EvaluateWithSubstitution( 6595 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6596 return false; 6597 return Result.isInt() && Result.getInt().getBoolValue(); 6598 }); 6599 } 6600 6601 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6602 SourceLocation Loc) { 6603 return diagnoseDiagnoseIfAttrsWith( 6604 *this, ND, /*ArgDependent=*/false, Loc, 6605 [&](const DiagnoseIfAttr *DIA) { 6606 bool Result; 6607 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6608 Result; 6609 }); 6610 } 6611 6612 /// Add all of the function declarations in the given function set to 6613 /// the overload candidate set. 6614 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6615 ArrayRef<Expr *> Args, 6616 OverloadCandidateSet &CandidateSet, 6617 TemplateArgumentListInfo *ExplicitTemplateArgs, 6618 bool SuppressUserConversions, 6619 bool PartialOverloading, 6620 bool FirstArgumentIsBase) { 6621 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6622 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6623 ArrayRef<Expr *> FunctionArgs = Args; 6624 6625 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6626 FunctionDecl *FD = 6627 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6628 6629 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6630 QualType ObjectType; 6631 Expr::Classification ObjectClassification; 6632 if (Args.size() > 0) { 6633 if (Expr *E = Args[0]) { 6634 // Use the explicit base to restrict the lookup: 6635 ObjectType = E->getType(); 6636 // Pointers in the object arguments are implicitly dereferenced, so we 6637 // always classify them as l-values. 6638 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6639 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6640 else 6641 ObjectClassification = E->Classify(Context); 6642 } // .. else there is an implicit base. 6643 FunctionArgs = Args.slice(1); 6644 } 6645 if (FunTmpl) { 6646 AddMethodTemplateCandidate( 6647 FunTmpl, F.getPair(), 6648 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6649 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6650 FunctionArgs, CandidateSet, SuppressUserConversions, 6651 PartialOverloading); 6652 } else { 6653 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6654 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6655 ObjectClassification, FunctionArgs, CandidateSet, 6656 SuppressUserConversions, PartialOverloading); 6657 } 6658 } else { 6659 // This branch handles both standalone functions and static methods. 6660 6661 // Slice the first argument (which is the base) when we access 6662 // static method as non-static. 6663 if (Args.size() > 0 && 6664 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6665 !isa<CXXConstructorDecl>(FD)))) { 6666 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6667 FunctionArgs = Args.slice(1); 6668 } 6669 if (FunTmpl) { 6670 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6671 ExplicitTemplateArgs, FunctionArgs, 6672 CandidateSet, SuppressUserConversions, 6673 PartialOverloading); 6674 } else { 6675 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6676 SuppressUserConversions, PartialOverloading); 6677 } 6678 } 6679 } 6680 } 6681 6682 /// AddMethodCandidate - Adds a named decl (which is some kind of 6683 /// method) as a method candidate to the given overload set. 6684 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6685 Expr::Classification ObjectClassification, 6686 ArrayRef<Expr *> Args, 6687 OverloadCandidateSet &CandidateSet, 6688 bool SuppressUserConversions, 6689 OverloadCandidateParamOrder PO) { 6690 NamedDecl *Decl = FoundDecl.getDecl(); 6691 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6692 6693 if (isa<UsingShadowDecl>(Decl)) 6694 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6695 6696 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6697 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6698 "Expected a member function template"); 6699 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6700 /*ExplicitArgs*/ nullptr, ObjectType, 6701 ObjectClassification, Args, CandidateSet, 6702 SuppressUserConversions, false, PO); 6703 } else { 6704 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6705 ObjectType, ObjectClassification, Args, CandidateSet, 6706 SuppressUserConversions, false, None, PO); 6707 } 6708 } 6709 6710 /// AddMethodCandidate - Adds the given C++ member function to the set 6711 /// of candidate functions, using the given function call arguments 6712 /// and the object argument (@c Object). For example, in a call 6713 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6714 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6715 /// allow user-defined conversions via constructors or conversion 6716 /// operators. 6717 void 6718 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6719 CXXRecordDecl *ActingContext, QualType ObjectType, 6720 Expr::Classification ObjectClassification, 6721 ArrayRef<Expr *> Args, 6722 OverloadCandidateSet &CandidateSet, 6723 bool SuppressUserConversions, 6724 bool PartialOverloading, 6725 ConversionSequenceList EarlyConversions, 6726 OverloadCandidateParamOrder PO) { 6727 const FunctionProtoType *Proto 6728 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6729 assert(Proto && "Methods without a prototype cannot be overloaded"); 6730 assert(!isa<CXXConstructorDecl>(Method) && 6731 "Use AddOverloadCandidate for constructors"); 6732 6733 if (!CandidateSet.isNewCandidate(Method, PO)) 6734 return; 6735 6736 // C++11 [class.copy]p23: [DR1402] 6737 // A defaulted move assignment operator that is defined as deleted is 6738 // ignored by overload resolution. 6739 if (Method->isDefaulted() && Method->isDeleted() && 6740 Method->isMoveAssignmentOperator()) 6741 return; 6742 6743 // Overload resolution is always an unevaluated context. 6744 EnterExpressionEvaluationContext Unevaluated( 6745 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6746 6747 // Add this candidate 6748 OverloadCandidate &Candidate = 6749 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6750 Candidate.FoundDecl = FoundDecl; 6751 Candidate.Function = Method; 6752 Candidate.RewriteKind = 6753 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6754 Candidate.IsSurrogate = false; 6755 Candidate.IgnoreObjectArgument = false; 6756 Candidate.ExplicitCallArguments = Args.size(); 6757 6758 unsigned NumParams = Proto->getNumParams(); 6759 6760 // (C++ 13.3.2p2): A candidate function having fewer than m 6761 // parameters is viable only if it has an ellipsis in its parameter 6762 // list (8.3.5). 6763 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6764 !Proto->isVariadic()) { 6765 Candidate.Viable = false; 6766 Candidate.FailureKind = ovl_fail_too_many_arguments; 6767 return; 6768 } 6769 6770 // (C++ 13.3.2p2): A candidate function having more than m parameters 6771 // is viable only if the (m+1)st parameter has a default argument 6772 // (8.3.6). For the purposes of overload resolution, the 6773 // parameter list is truncated on the right, so that there are 6774 // exactly m parameters. 6775 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6776 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6777 // Not enough arguments. 6778 Candidate.Viable = false; 6779 Candidate.FailureKind = ovl_fail_too_few_arguments; 6780 return; 6781 } 6782 6783 Candidate.Viable = true; 6784 6785 if (Method->isStatic() || ObjectType.isNull()) 6786 // The implicit object argument is ignored. 6787 Candidate.IgnoreObjectArgument = true; 6788 else { 6789 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6790 // Determine the implicit conversion sequence for the object 6791 // parameter. 6792 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6793 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6794 Method, ActingContext); 6795 if (Candidate.Conversions[ConvIdx].isBad()) { 6796 Candidate.Viable = false; 6797 Candidate.FailureKind = ovl_fail_bad_conversion; 6798 return; 6799 } 6800 } 6801 6802 // (CUDA B.1): Check for invalid calls between targets. 6803 if (getLangOpts().CUDA) 6804 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6805 if (!IsAllowedCUDACall(Caller, Method)) { 6806 Candidate.Viable = false; 6807 Candidate.FailureKind = ovl_fail_bad_target; 6808 return; 6809 } 6810 6811 if (Expr *RequiresClause = Method->getTrailingRequiresClause()) { 6812 ConstraintSatisfaction Satisfaction; 6813 if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) || 6814 !Satisfaction.IsSatisfied) { 6815 Candidate.Viable = false; 6816 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6817 return; 6818 } 6819 } 6820 6821 // Determine the implicit conversion sequences for each of the 6822 // arguments. 6823 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6824 unsigned ConvIdx = 6825 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6826 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6827 // We already formed a conversion sequence for this parameter during 6828 // template argument deduction. 6829 } else if (ArgIdx < NumParams) { 6830 // (C++ 13.3.2p3): for F to be a viable function, there shall 6831 // exist for each argument an implicit conversion sequence 6832 // (13.3.3.1) that converts that argument to the corresponding 6833 // parameter of F. 6834 QualType ParamType = Proto->getParamType(ArgIdx); 6835 Candidate.Conversions[ConvIdx] 6836 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6837 SuppressUserConversions, 6838 /*InOverloadResolution=*/true, 6839 /*AllowObjCWritebackConversion=*/ 6840 getLangOpts().ObjCAutoRefCount); 6841 if (Candidate.Conversions[ConvIdx].isBad()) { 6842 Candidate.Viable = false; 6843 Candidate.FailureKind = ovl_fail_bad_conversion; 6844 return; 6845 } 6846 } else { 6847 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6848 // argument for which there is no corresponding parameter is 6849 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6850 Candidate.Conversions[ConvIdx].setEllipsis(); 6851 } 6852 } 6853 6854 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6855 Candidate.Viable = false; 6856 Candidate.FailureKind = ovl_fail_enable_if; 6857 Candidate.DeductionFailure.Data = FailedAttr; 6858 return; 6859 } 6860 6861 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6862 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6863 Candidate.Viable = false; 6864 Candidate.FailureKind = ovl_non_default_multiversion_function; 6865 } 6866 } 6867 6868 /// Add a C++ member function template as a candidate to the candidate 6869 /// set, using template argument deduction to produce an appropriate member 6870 /// function template specialization. 6871 void Sema::AddMethodTemplateCandidate( 6872 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 6873 CXXRecordDecl *ActingContext, 6874 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 6875 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 6876 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6877 bool PartialOverloading, OverloadCandidateParamOrder PO) { 6878 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 6879 return; 6880 6881 // C++ [over.match.funcs]p7: 6882 // In each case where a candidate is a function template, candidate 6883 // function template specializations are generated using template argument 6884 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6885 // candidate functions in the usual way.113) A given name can refer to one 6886 // or more function templates and also to a set of overloaded non-template 6887 // functions. In such a case, the candidate functions generated from each 6888 // function template are combined with the set of non-template candidate 6889 // functions. 6890 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6891 FunctionDecl *Specialization = nullptr; 6892 ConversionSequenceList Conversions; 6893 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6894 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6895 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6896 return CheckNonDependentConversions( 6897 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6898 SuppressUserConversions, ActingContext, ObjectType, 6899 ObjectClassification, PO); 6900 })) { 6901 OverloadCandidate &Candidate = 6902 CandidateSet.addCandidate(Conversions.size(), Conversions); 6903 Candidate.FoundDecl = FoundDecl; 6904 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6905 Candidate.Viable = false; 6906 Candidate.RewriteKind = 6907 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6908 Candidate.IsSurrogate = false; 6909 Candidate.IgnoreObjectArgument = 6910 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6911 ObjectType.isNull(); 6912 Candidate.ExplicitCallArguments = Args.size(); 6913 if (Result == TDK_NonDependentConversionFailure) 6914 Candidate.FailureKind = ovl_fail_bad_conversion; 6915 else { 6916 Candidate.FailureKind = ovl_fail_bad_deduction; 6917 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6918 Info); 6919 } 6920 return; 6921 } 6922 6923 // Add the function template specialization produced by template argument 6924 // deduction as a candidate. 6925 assert(Specialization && "Missing member function template specialization?"); 6926 assert(isa<CXXMethodDecl>(Specialization) && 6927 "Specialization is not a member function?"); 6928 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6929 ActingContext, ObjectType, ObjectClassification, Args, 6930 CandidateSet, SuppressUserConversions, PartialOverloading, 6931 Conversions, PO); 6932 } 6933 6934 /// Determine whether a given function template has a simple explicit specifier 6935 /// or a non-value-dependent explicit-specification that evaluates to true. 6936 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 6937 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 6938 } 6939 6940 /// Add a C++ function template specialization as a candidate 6941 /// in the candidate set, using template argument deduction to produce 6942 /// an appropriate function template specialization. 6943 void Sema::AddTemplateOverloadCandidate( 6944 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6945 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6946 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6947 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 6948 OverloadCandidateParamOrder PO) { 6949 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 6950 return; 6951 6952 // If the function template has a non-dependent explicit specification, 6953 // exclude it now if appropriate; we are not permitted to perform deduction 6954 // and substitution in this case. 6955 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 6956 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6957 Candidate.FoundDecl = FoundDecl; 6958 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6959 Candidate.Viable = false; 6960 Candidate.FailureKind = ovl_fail_explicit; 6961 return; 6962 } 6963 6964 // C++ [over.match.funcs]p7: 6965 // In each case where a candidate is a function template, candidate 6966 // function template specializations are generated using template argument 6967 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6968 // candidate functions in the usual way.113) A given name can refer to one 6969 // or more function templates and also to a set of overloaded non-template 6970 // functions. In such a case, the candidate functions generated from each 6971 // function template are combined with the set of non-template candidate 6972 // functions. 6973 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6974 FunctionDecl *Specialization = nullptr; 6975 ConversionSequenceList Conversions; 6976 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6977 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6978 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6979 return CheckNonDependentConversions( 6980 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 6981 SuppressUserConversions, nullptr, QualType(), {}, PO); 6982 })) { 6983 OverloadCandidate &Candidate = 6984 CandidateSet.addCandidate(Conversions.size(), Conversions); 6985 Candidate.FoundDecl = FoundDecl; 6986 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6987 Candidate.Viable = false; 6988 Candidate.RewriteKind = 6989 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6990 Candidate.IsSurrogate = false; 6991 Candidate.IsADLCandidate = IsADLCandidate; 6992 // Ignore the object argument if there is one, since we don't have an object 6993 // type. 6994 Candidate.IgnoreObjectArgument = 6995 isa<CXXMethodDecl>(Candidate.Function) && 6996 !isa<CXXConstructorDecl>(Candidate.Function); 6997 Candidate.ExplicitCallArguments = Args.size(); 6998 if (Result == TDK_NonDependentConversionFailure) 6999 Candidate.FailureKind = ovl_fail_bad_conversion; 7000 else { 7001 Candidate.FailureKind = ovl_fail_bad_deduction; 7002 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7003 Info); 7004 } 7005 return; 7006 } 7007 7008 // Add the function template specialization produced by template argument 7009 // deduction as a candidate. 7010 assert(Specialization && "Missing function template specialization?"); 7011 AddOverloadCandidate( 7012 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7013 PartialOverloading, AllowExplicit, 7014 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7015 } 7016 7017 /// Check that implicit conversion sequences can be formed for each argument 7018 /// whose corresponding parameter has a non-dependent type, per DR1391's 7019 /// [temp.deduct.call]p10. 7020 bool Sema::CheckNonDependentConversions( 7021 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7022 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7023 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7024 CXXRecordDecl *ActingContext, QualType ObjectType, 7025 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7026 // FIXME: The cases in which we allow explicit conversions for constructor 7027 // arguments never consider calling a constructor template. It's not clear 7028 // that is correct. 7029 const bool AllowExplicit = false; 7030 7031 auto *FD = FunctionTemplate->getTemplatedDecl(); 7032 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7033 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7034 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7035 7036 Conversions = 7037 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7038 7039 // Overload resolution is always an unevaluated context. 7040 EnterExpressionEvaluationContext Unevaluated( 7041 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7042 7043 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7044 // require that, but this check should never result in a hard error, and 7045 // overload resolution is permitted to sidestep instantiations. 7046 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7047 !ObjectType.isNull()) { 7048 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7049 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7050 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7051 Method, ActingContext); 7052 if (Conversions[ConvIdx].isBad()) 7053 return true; 7054 } 7055 7056 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7057 ++I) { 7058 QualType ParamType = ParamTypes[I]; 7059 if (!ParamType->isDependentType()) { 7060 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7061 ? 0 7062 : (ThisConversions + I); 7063 Conversions[ConvIdx] 7064 = TryCopyInitialization(*this, Args[I], ParamType, 7065 SuppressUserConversions, 7066 /*InOverloadResolution=*/true, 7067 /*AllowObjCWritebackConversion=*/ 7068 getLangOpts().ObjCAutoRefCount, 7069 AllowExplicit); 7070 if (Conversions[ConvIdx].isBad()) 7071 return true; 7072 } 7073 } 7074 7075 return false; 7076 } 7077 7078 /// Determine whether this is an allowable conversion from the result 7079 /// of an explicit conversion operator to the expected type, per C++ 7080 /// [over.match.conv]p1 and [over.match.ref]p1. 7081 /// 7082 /// \param ConvType The return type of the conversion function. 7083 /// 7084 /// \param ToType The type we are converting to. 7085 /// 7086 /// \param AllowObjCPointerConversion Allow a conversion from one 7087 /// Objective-C pointer to another. 7088 /// 7089 /// \returns true if the conversion is allowable, false otherwise. 7090 static bool isAllowableExplicitConversion(Sema &S, 7091 QualType ConvType, QualType ToType, 7092 bool AllowObjCPointerConversion) { 7093 QualType ToNonRefType = ToType.getNonReferenceType(); 7094 7095 // Easy case: the types are the same. 7096 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7097 return true; 7098 7099 // Allow qualification conversions. 7100 bool ObjCLifetimeConversion; 7101 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7102 ObjCLifetimeConversion)) 7103 return true; 7104 7105 // If we're not allowed to consider Objective-C pointer conversions, 7106 // we're done. 7107 if (!AllowObjCPointerConversion) 7108 return false; 7109 7110 // Is this an Objective-C pointer conversion? 7111 bool IncompatibleObjC = false; 7112 QualType ConvertedType; 7113 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7114 IncompatibleObjC); 7115 } 7116 7117 /// AddConversionCandidate - Add a C++ conversion function as a 7118 /// candidate in the candidate set (C++ [over.match.conv], 7119 /// C++ [over.match.copy]). From is the expression we're converting from, 7120 /// and ToType is the type that we're eventually trying to convert to 7121 /// (which may or may not be the same type as the type that the 7122 /// conversion function produces). 7123 void Sema::AddConversionCandidate( 7124 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7125 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7126 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7127 bool AllowExplicit, bool AllowResultConversion) { 7128 assert(!Conversion->getDescribedFunctionTemplate() && 7129 "Conversion function templates use AddTemplateConversionCandidate"); 7130 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7131 if (!CandidateSet.isNewCandidate(Conversion)) 7132 return; 7133 7134 // If the conversion function has an undeduced return type, trigger its 7135 // deduction now. 7136 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7137 if (DeduceReturnType(Conversion, From->getExprLoc())) 7138 return; 7139 ConvType = Conversion->getConversionType().getNonReferenceType(); 7140 } 7141 7142 // If we don't allow any conversion of the result type, ignore conversion 7143 // functions that don't convert to exactly (possibly cv-qualified) T. 7144 if (!AllowResultConversion && 7145 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7146 return; 7147 7148 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7149 // operator is only a candidate if its return type is the target type or 7150 // can be converted to the target type with a qualification conversion. 7151 // 7152 // FIXME: Include such functions in the candidate list and explain why we 7153 // can't select them. 7154 if (Conversion->isExplicit() && 7155 !isAllowableExplicitConversion(*this, ConvType, ToType, 7156 AllowObjCConversionOnExplicit)) 7157 return; 7158 7159 // Overload resolution is always an unevaluated context. 7160 EnterExpressionEvaluationContext Unevaluated( 7161 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7162 7163 // Add this candidate 7164 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7165 Candidate.FoundDecl = FoundDecl; 7166 Candidate.Function = Conversion; 7167 Candidate.IsSurrogate = false; 7168 Candidate.IgnoreObjectArgument = false; 7169 Candidate.FinalConversion.setAsIdentityConversion(); 7170 Candidate.FinalConversion.setFromType(ConvType); 7171 Candidate.FinalConversion.setAllToTypes(ToType); 7172 Candidate.Viable = true; 7173 Candidate.ExplicitCallArguments = 1; 7174 7175 // Explicit functions are not actually candidates at all if we're not 7176 // allowing them in this context, but keep them around so we can point 7177 // to them in diagnostics. 7178 if (!AllowExplicit && Conversion->isExplicit()) { 7179 Candidate.Viable = false; 7180 Candidate.FailureKind = ovl_fail_explicit; 7181 return; 7182 } 7183 7184 // C++ [over.match.funcs]p4: 7185 // For conversion functions, the function is considered to be a member of 7186 // the class of the implicit implied object argument for the purpose of 7187 // defining the type of the implicit object parameter. 7188 // 7189 // Determine the implicit conversion sequence for the implicit 7190 // object parameter. 7191 QualType ImplicitParamType = From->getType(); 7192 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7193 ImplicitParamType = FromPtrType->getPointeeType(); 7194 CXXRecordDecl *ConversionContext 7195 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7196 7197 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7198 *this, CandidateSet.getLocation(), From->getType(), 7199 From->Classify(Context), Conversion, ConversionContext); 7200 7201 if (Candidate.Conversions[0].isBad()) { 7202 Candidate.Viable = false; 7203 Candidate.FailureKind = ovl_fail_bad_conversion; 7204 return; 7205 } 7206 7207 Expr *RequiresClause = Conversion->getTrailingRequiresClause(); 7208 if (RequiresClause) { 7209 ConstraintSatisfaction Satisfaction; 7210 if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) || 7211 !Satisfaction.IsSatisfied) { 7212 Candidate.Viable = false; 7213 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7214 return; 7215 } 7216 } 7217 7218 // We won't go through a user-defined type conversion function to convert a 7219 // derived to base as such conversions are given Conversion Rank. They only 7220 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7221 QualType FromCanon 7222 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7223 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7224 if (FromCanon == ToCanon || 7225 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7226 Candidate.Viable = false; 7227 Candidate.FailureKind = ovl_fail_trivial_conversion; 7228 return; 7229 } 7230 7231 // To determine what the conversion from the result of calling the 7232 // conversion function to the type we're eventually trying to 7233 // convert to (ToType), we need to synthesize a call to the 7234 // conversion function and attempt copy initialization from it. This 7235 // makes sure that we get the right semantics with respect to 7236 // lvalues/rvalues and the type. Fortunately, we can allocate this 7237 // call on the stack and we don't need its arguments to be 7238 // well-formed. 7239 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7240 VK_LValue, From->getBeginLoc()); 7241 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7242 Context.getPointerType(Conversion->getType()), 7243 CK_FunctionToPointerDecay, 7244 &ConversionRef, VK_RValue); 7245 7246 QualType ConversionType = Conversion->getConversionType(); 7247 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7248 Candidate.Viable = false; 7249 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7250 return; 7251 } 7252 7253 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7254 7255 // Note that it is safe to allocate CallExpr on the stack here because 7256 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7257 // allocator). 7258 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7259 7260 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7261 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7262 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7263 7264 ImplicitConversionSequence ICS = 7265 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7266 /*SuppressUserConversions=*/true, 7267 /*InOverloadResolution=*/false, 7268 /*AllowObjCWritebackConversion=*/false); 7269 7270 switch (ICS.getKind()) { 7271 case ImplicitConversionSequence::StandardConversion: 7272 Candidate.FinalConversion = ICS.Standard; 7273 7274 // C++ [over.ics.user]p3: 7275 // If the user-defined conversion is specified by a specialization of a 7276 // conversion function template, the second standard conversion sequence 7277 // shall have exact match rank. 7278 if (Conversion->getPrimaryTemplate() && 7279 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7280 Candidate.Viable = false; 7281 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7282 return; 7283 } 7284 7285 // C++0x [dcl.init.ref]p5: 7286 // In the second case, if the reference is an rvalue reference and 7287 // the second standard conversion sequence of the user-defined 7288 // conversion sequence includes an lvalue-to-rvalue conversion, the 7289 // program is ill-formed. 7290 if (ToType->isRValueReferenceType() && 7291 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7292 Candidate.Viable = false; 7293 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7294 return; 7295 } 7296 break; 7297 7298 case ImplicitConversionSequence::BadConversion: 7299 Candidate.Viable = false; 7300 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7301 return; 7302 7303 default: 7304 llvm_unreachable( 7305 "Can only end up with a standard conversion sequence or failure"); 7306 } 7307 7308 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7309 Candidate.Viable = false; 7310 Candidate.FailureKind = ovl_fail_enable_if; 7311 Candidate.DeductionFailure.Data = FailedAttr; 7312 return; 7313 } 7314 7315 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7316 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7317 Candidate.Viable = false; 7318 Candidate.FailureKind = ovl_non_default_multiversion_function; 7319 } 7320 } 7321 7322 /// Adds a conversion function template specialization 7323 /// candidate to the overload set, using template argument deduction 7324 /// to deduce the template arguments of the conversion function 7325 /// template from the type that we are converting to (C++ 7326 /// [temp.deduct.conv]). 7327 void Sema::AddTemplateConversionCandidate( 7328 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7329 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7330 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7331 bool AllowExplicit, bool AllowResultConversion) { 7332 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7333 "Only conversion function templates permitted here"); 7334 7335 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7336 return; 7337 7338 // If the function template has a non-dependent explicit specification, 7339 // exclude it now if appropriate; we are not permitted to perform deduction 7340 // and substitution in this case. 7341 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7342 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7343 Candidate.FoundDecl = FoundDecl; 7344 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7345 Candidate.Viable = false; 7346 Candidate.FailureKind = ovl_fail_explicit; 7347 return; 7348 } 7349 7350 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7351 CXXConversionDecl *Specialization = nullptr; 7352 if (TemplateDeductionResult Result 7353 = DeduceTemplateArguments(FunctionTemplate, ToType, 7354 Specialization, Info)) { 7355 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7356 Candidate.FoundDecl = FoundDecl; 7357 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7358 Candidate.Viable = false; 7359 Candidate.FailureKind = ovl_fail_bad_deduction; 7360 Candidate.IsSurrogate = false; 7361 Candidate.IgnoreObjectArgument = false; 7362 Candidate.ExplicitCallArguments = 1; 7363 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7364 Info); 7365 return; 7366 } 7367 7368 // Add the conversion function template specialization produced by 7369 // template argument deduction as a candidate. 7370 assert(Specialization && "Missing function template specialization?"); 7371 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7372 CandidateSet, AllowObjCConversionOnExplicit, 7373 AllowExplicit, AllowResultConversion); 7374 } 7375 7376 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7377 /// converts the given @c Object to a function pointer via the 7378 /// conversion function @c Conversion, and then attempts to call it 7379 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7380 /// the type of function that we'll eventually be calling. 7381 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7382 DeclAccessPair FoundDecl, 7383 CXXRecordDecl *ActingContext, 7384 const FunctionProtoType *Proto, 7385 Expr *Object, 7386 ArrayRef<Expr *> Args, 7387 OverloadCandidateSet& CandidateSet) { 7388 if (!CandidateSet.isNewCandidate(Conversion)) 7389 return; 7390 7391 // Overload resolution is always an unevaluated context. 7392 EnterExpressionEvaluationContext Unevaluated( 7393 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7394 7395 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7396 Candidate.FoundDecl = FoundDecl; 7397 Candidate.Function = nullptr; 7398 Candidate.Surrogate = Conversion; 7399 Candidate.Viable = true; 7400 Candidate.IsSurrogate = true; 7401 Candidate.IgnoreObjectArgument = false; 7402 Candidate.ExplicitCallArguments = Args.size(); 7403 7404 // Determine the implicit conversion sequence for the implicit 7405 // object parameter. 7406 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7407 *this, CandidateSet.getLocation(), Object->getType(), 7408 Object->Classify(Context), Conversion, ActingContext); 7409 if (ObjectInit.isBad()) { 7410 Candidate.Viable = false; 7411 Candidate.FailureKind = ovl_fail_bad_conversion; 7412 Candidate.Conversions[0] = ObjectInit; 7413 return; 7414 } 7415 7416 // The first conversion is actually a user-defined conversion whose 7417 // first conversion is ObjectInit's standard conversion (which is 7418 // effectively a reference binding). Record it as such. 7419 Candidate.Conversions[0].setUserDefined(); 7420 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7421 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7422 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7423 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7424 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7425 Candidate.Conversions[0].UserDefined.After 7426 = Candidate.Conversions[0].UserDefined.Before; 7427 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7428 7429 // Find the 7430 unsigned NumParams = Proto->getNumParams(); 7431 7432 // (C++ 13.3.2p2): A candidate function having fewer than m 7433 // parameters is viable only if it has an ellipsis in its parameter 7434 // list (8.3.5). 7435 if (Args.size() > NumParams && !Proto->isVariadic()) { 7436 Candidate.Viable = false; 7437 Candidate.FailureKind = ovl_fail_too_many_arguments; 7438 return; 7439 } 7440 7441 // Function types don't have any default arguments, so just check if 7442 // we have enough arguments. 7443 if (Args.size() < NumParams) { 7444 // Not enough arguments. 7445 Candidate.Viable = false; 7446 Candidate.FailureKind = ovl_fail_too_few_arguments; 7447 return; 7448 } 7449 7450 // Determine the implicit conversion sequences for each of the 7451 // arguments. 7452 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7453 if (ArgIdx < NumParams) { 7454 // (C++ 13.3.2p3): for F to be a viable function, there shall 7455 // exist for each argument an implicit conversion sequence 7456 // (13.3.3.1) that converts that argument to the corresponding 7457 // parameter of F. 7458 QualType ParamType = Proto->getParamType(ArgIdx); 7459 Candidate.Conversions[ArgIdx + 1] 7460 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7461 /*SuppressUserConversions=*/false, 7462 /*InOverloadResolution=*/false, 7463 /*AllowObjCWritebackConversion=*/ 7464 getLangOpts().ObjCAutoRefCount); 7465 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7466 Candidate.Viable = false; 7467 Candidate.FailureKind = ovl_fail_bad_conversion; 7468 return; 7469 } 7470 } else { 7471 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7472 // argument for which there is no corresponding parameter is 7473 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7474 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7475 } 7476 } 7477 7478 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7479 Candidate.Viable = false; 7480 Candidate.FailureKind = ovl_fail_enable_if; 7481 Candidate.DeductionFailure.Data = FailedAttr; 7482 return; 7483 } 7484 } 7485 7486 /// Add all of the non-member operator function declarations in the given 7487 /// function set to the overload candidate set. 7488 void Sema::AddNonMemberOperatorCandidates( 7489 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7490 OverloadCandidateSet &CandidateSet, 7491 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7492 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7493 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7494 ArrayRef<Expr *> FunctionArgs = Args; 7495 7496 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7497 FunctionDecl *FD = 7498 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7499 7500 // Don't consider rewritten functions if we're not rewriting. 7501 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7502 continue; 7503 7504 assert(!isa<CXXMethodDecl>(FD) && 7505 "unqualified operator lookup found a member function"); 7506 7507 if (FunTmpl) { 7508 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7509 FunctionArgs, CandidateSet); 7510 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7511 AddTemplateOverloadCandidate( 7512 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7513 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7514 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7515 } else { 7516 if (ExplicitTemplateArgs) 7517 continue; 7518 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7519 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7520 AddOverloadCandidate(FD, F.getPair(), 7521 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7522 false, false, true, false, ADLCallKind::NotADL, 7523 None, OverloadCandidateParamOrder::Reversed); 7524 } 7525 } 7526 } 7527 7528 /// Add overload candidates for overloaded operators that are 7529 /// member functions. 7530 /// 7531 /// Add the overloaded operator candidates that are member functions 7532 /// for the operator Op that was used in an operator expression such 7533 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7534 /// CandidateSet will store the added overload candidates. (C++ 7535 /// [over.match.oper]). 7536 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7537 SourceLocation OpLoc, 7538 ArrayRef<Expr *> Args, 7539 OverloadCandidateSet &CandidateSet, 7540 OverloadCandidateParamOrder PO) { 7541 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7542 7543 // C++ [over.match.oper]p3: 7544 // For a unary operator @ with an operand of a type whose 7545 // cv-unqualified version is T1, and for a binary operator @ with 7546 // a left operand of a type whose cv-unqualified version is T1 and 7547 // a right operand of a type whose cv-unqualified version is T2, 7548 // three sets of candidate functions, designated member 7549 // candidates, non-member candidates and built-in candidates, are 7550 // constructed as follows: 7551 QualType T1 = Args[0]->getType(); 7552 7553 // -- If T1 is a complete class type or a class currently being 7554 // defined, the set of member candidates is the result of the 7555 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7556 // the set of member candidates is empty. 7557 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7558 // Complete the type if it can be completed. 7559 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7560 return; 7561 // If the type is neither complete nor being defined, bail out now. 7562 if (!T1Rec->getDecl()->getDefinition()) 7563 return; 7564 7565 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7566 LookupQualifiedName(Operators, T1Rec->getDecl()); 7567 Operators.suppressDiagnostics(); 7568 7569 for (LookupResult::iterator Oper = Operators.begin(), 7570 OperEnd = Operators.end(); 7571 Oper != OperEnd; 7572 ++Oper) 7573 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7574 Args[0]->Classify(Context), Args.slice(1), 7575 CandidateSet, /*SuppressUserConversion=*/false, PO); 7576 } 7577 } 7578 7579 /// AddBuiltinCandidate - Add a candidate for a built-in 7580 /// operator. ResultTy and ParamTys are the result and parameter types 7581 /// of the built-in candidate, respectively. Args and NumArgs are the 7582 /// arguments being passed to the candidate. IsAssignmentOperator 7583 /// should be true when this built-in candidate is an assignment 7584 /// operator. NumContextualBoolArguments is the number of arguments 7585 /// (at the beginning of the argument list) that will be contextually 7586 /// converted to bool. 7587 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7588 OverloadCandidateSet& CandidateSet, 7589 bool IsAssignmentOperator, 7590 unsigned NumContextualBoolArguments) { 7591 // Overload resolution is always an unevaluated context. 7592 EnterExpressionEvaluationContext Unevaluated( 7593 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7594 7595 // Add this candidate 7596 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7597 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7598 Candidate.Function = nullptr; 7599 Candidate.IsSurrogate = false; 7600 Candidate.IgnoreObjectArgument = false; 7601 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7602 7603 // Determine the implicit conversion sequences for each of the 7604 // arguments. 7605 Candidate.Viable = true; 7606 Candidate.ExplicitCallArguments = Args.size(); 7607 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7608 // C++ [over.match.oper]p4: 7609 // For the built-in assignment operators, conversions of the 7610 // left operand are restricted as follows: 7611 // -- no temporaries are introduced to hold the left operand, and 7612 // -- no user-defined conversions are applied to the left 7613 // operand to achieve a type match with the left-most 7614 // parameter of a built-in candidate. 7615 // 7616 // We block these conversions by turning off user-defined 7617 // conversions, since that is the only way that initialization of 7618 // a reference to a non-class type can occur from something that 7619 // is not of the same type. 7620 if (ArgIdx < NumContextualBoolArguments) { 7621 assert(ParamTys[ArgIdx] == Context.BoolTy && 7622 "Contextual conversion to bool requires bool type"); 7623 Candidate.Conversions[ArgIdx] 7624 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7625 } else { 7626 Candidate.Conversions[ArgIdx] 7627 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7628 ArgIdx == 0 && IsAssignmentOperator, 7629 /*InOverloadResolution=*/false, 7630 /*AllowObjCWritebackConversion=*/ 7631 getLangOpts().ObjCAutoRefCount); 7632 } 7633 if (Candidate.Conversions[ArgIdx].isBad()) { 7634 Candidate.Viable = false; 7635 Candidate.FailureKind = ovl_fail_bad_conversion; 7636 break; 7637 } 7638 } 7639 } 7640 7641 namespace { 7642 7643 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7644 /// candidate operator functions for built-in operators (C++ 7645 /// [over.built]). The types are separated into pointer types and 7646 /// enumeration types. 7647 class BuiltinCandidateTypeSet { 7648 /// TypeSet - A set of types. 7649 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7650 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7651 7652 /// PointerTypes - The set of pointer types that will be used in the 7653 /// built-in candidates. 7654 TypeSet PointerTypes; 7655 7656 /// MemberPointerTypes - The set of member pointer types that will be 7657 /// used in the built-in candidates. 7658 TypeSet MemberPointerTypes; 7659 7660 /// EnumerationTypes - The set of enumeration types that will be 7661 /// used in the built-in candidates. 7662 TypeSet EnumerationTypes; 7663 7664 /// The set of vector types that will be used in the built-in 7665 /// candidates. 7666 TypeSet VectorTypes; 7667 7668 /// A flag indicating non-record types are viable candidates 7669 bool HasNonRecordTypes; 7670 7671 /// A flag indicating whether either arithmetic or enumeration types 7672 /// were present in the candidate set. 7673 bool HasArithmeticOrEnumeralTypes; 7674 7675 /// A flag indicating whether the nullptr type was present in the 7676 /// candidate set. 7677 bool HasNullPtrType; 7678 7679 /// Sema - The semantic analysis instance where we are building the 7680 /// candidate type set. 7681 Sema &SemaRef; 7682 7683 /// Context - The AST context in which we will build the type sets. 7684 ASTContext &Context; 7685 7686 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7687 const Qualifiers &VisibleQuals); 7688 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7689 7690 public: 7691 /// iterator - Iterates through the types that are part of the set. 7692 typedef TypeSet::iterator iterator; 7693 7694 BuiltinCandidateTypeSet(Sema &SemaRef) 7695 : HasNonRecordTypes(false), 7696 HasArithmeticOrEnumeralTypes(false), 7697 HasNullPtrType(false), 7698 SemaRef(SemaRef), 7699 Context(SemaRef.Context) { } 7700 7701 void AddTypesConvertedFrom(QualType Ty, 7702 SourceLocation Loc, 7703 bool AllowUserConversions, 7704 bool AllowExplicitConversions, 7705 const Qualifiers &VisibleTypeConversionsQuals); 7706 7707 /// pointer_begin - First pointer type found; 7708 iterator pointer_begin() { return PointerTypes.begin(); } 7709 7710 /// pointer_end - Past the last pointer type found; 7711 iterator pointer_end() { return PointerTypes.end(); } 7712 7713 /// member_pointer_begin - First member pointer type found; 7714 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7715 7716 /// member_pointer_end - Past the last member pointer type found; 7717 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7718 7719 /// enumeration_begin - First enumeration type found; 7720 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7721 7722 /// enumeration_end - Past the last enumeration type found; 7723 iterator enumeration_end() { return EnumerationTypes.end(); } 7724 7725 iterator vector_begin() { return VectorTypes.begin(); } 7726 iterator vector_end() { return VectorTypes.end(); } 7727 7728 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7729 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7730 bool hasNullPtrType() const { return HasNullPtrType; } 7731 }; 7732 7733 } // end anonymous namespace 7734 7735 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7736 /// the set of pointer types along with any more-qualified variants of 7737 /// that type. For example, if @p Ty is "int const *", this routine 7738 /// will add "int const *", "int const volatile *", "int const 7739 /// restrict *", and "int const volatile restrict *" to the set of 7740 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7741 /// false otherwise. 7742 /// 7743 /// FIXME: what to do about extended qualifiers? 7744 bool 7745 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7746 const Qualifiers &VisibleQuals) { 7747 7748 // Insert this type. 7749 if (!PointerTypes.insert(Ty)) 7750 return false; 7751 7752 QualType PointeeTy; 7753 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7754 bool buildObjCPtr = false; 7755 if (!PointerTy) { 7756 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7757 PointeeTy = PTy->getPointeeType(); 7758 buildObjCPtr = true; 7759 } else { 7760 PointeeTy = PointerTy->getPointeeType(); 7761 } 7762 7763 // Don't add qualified variants of arrays. For one, they're not allowed 7764 // (the qualifier would sink to the element type), and for another, the 7765 // only overload situation where it matters is subscript or pointer +- int, 7766 // and those shouldn't have qualifier variants anyway. 7767 if (PointeeTy->isArrayType()) 7768 return true; 7769 7770 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7771 bool hasVolatile = VisibleQuals.hasVolatile(); 7772 bool hasRestrict = VisibleQuals.hasRestrict(); 7773 7774 // Iterate through all strict supersets of BaseCVR. 7775 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7776 if ((CVR | BaseCVR) != CVR) continue; 7777 // Skip over volatile if no volatile found anywhere in the types. 7778 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7779 7780 // Skip over restrict if no restrict found anywhere in the types, or if 7781 // the type cannot be restrict-qualified. 7782 if ((CVR & Qualifiers::Restrict) && 7783 (!hasRestrict || 7784 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7785 continue; 7786 7787 // Build qualified pointee type. 7788 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7789 7790 // Build qualified pointer type. 7791 QualType QPointerTy; 7792 if (!buildObjCPtr) 7793 QPointerTy = Context.getPointerType(QPointeeTy); 7794 else 7795 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7796 7797 // Insert qualified pointer type. 7798 PointerTypes.insert(QPointerTy); 7799 } 7800 7801 return true; 7802 } 7803 7804 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7805 /// to the set of pointer types along with any more-qualified variants of 7806 /// that type. For example, if @p Ty is "int const *", this routine 7807 /// will add "int const *", "int const volatile *", "int const 7808 /// restrict *", and "int const volatile restrict *" to the set of 7809 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7810 /// false otherwise. 7811 /// 7812 /// FIXME: what to do about extended qualifiers? 7813 bool 7814 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7815 QualType Ty) { 7816 // Insert this type. 7817 if (!MemberPointerTypes.insert(Ty)) 7818 return false; 7819 7820 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7821 assert(PointerTy && "type was not a member pointer type!"); 7822 7823 QualType PointeeTy = PointerTy->getPointeeType(); 7824 // Don't add qualified variants of arrays. For one, they're not allowed 7825 // (the qualifier would sink to the element type), and for another, the 7826 // only overload situation where it matters is subscript or pointer +- int, 7827 // and those shouldn't have qualifier variants anyway. 7828 if (PointeeTy->isArrayType()) 7829 return true; 7830 const Type *ClassTy = PointerTy->getClass(); 7831 7832 // Iterate through all strict supersets of the pointee type's CVR 7833 // qualifiers. 7834 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7835 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7836 if ((CVR | BaseCVR) != CVR) continue; 7837 7838 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7839 MemberPointerTypes.insert( 7840 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7841 } 7842 7843 return true; 7844 } 7845 7846 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7847 /// Ty can be implicit converted to the given set of @p Types. We're 7848 /// primarily interested in pointer types and enumeration types. We also 7849 /// take member pointer types, for the conditional operator. 7850 /// AllowUserConversions is true if we should look at the conversion 7851 /// functions of a class type, and AllowExplicitConversions if we 7852 /// should also include the explicit conversion functions of a class 7853 /// type. 7854 void 7855 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7856 SourceLocation Loc, 7857 bool AllowUserConversions, 7858 bool AllowExplicitConversions, 7859 const Qualifiers &VisibleQuals) { 7860 // Only deal with canonical types. 7861 Ty = Context.getCanonicalType(Ty); 7862 7863 // Look through reference types; they aren't part of the type of an 7864 // expression for the purposes of conversions. 7865 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7866 Ty = RefTy->getPointeeType(); 7867 7868 // If we're dealing with an array type, decay to the pointer. 7869 if (Ty->isArrayType()) 7870 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7871 7872 // Otherwise, we don't care about qualifiers on the type. 7873 Ty = Ty.getLocalUnqualifiedType(); 7874 7875 // Flag if we ever add a non-record type. 7876 const RecordType *TyRec = Ty->getAs<RecordType>(); 7877 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7878 7879 // Flag if we encounter an arithmetic type. 7880 HasArithmeticOrEnumeralTypes = 7881 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7882 7883 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7884 PointerTypes.insert(Ty); 7885 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7886 // Insert our type, and its more-qualified variants, into the set 7887 // of types. 7888 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7889 return; 7890 } else if (Ty->isMemberPointerType()) { 7891 // Member pointers are far easier, since the pointee can't be converted. 7892 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7893 return; 7894 } else if (Ty->isEnumeralType()) { 7895 HasArithmeticOrEnumeralTypes = true; 7896 EnumerationTypes.insert(Ty); 7897 } else if (Ty->isVectorType()) { 7898 // We treat vector types as arithmetic types in many contexts as an 7899 // extension. 7900 HasArithmeticOrEnumeralTypes = true; 7901 VectorTypes.insert(Ty); 7902 } else if (Ty->isNullPtrType()) { 7903 HasNullPtrType = true; 7904 } else if (AllowUserConversions && TyRec) { 7905 // No conversion functions in incomplete types. 7906 if (!SemaRef.isCompleteType(Loc, Ty)) 7907 return; 7908 7909 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7910 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7911 if (isa<UsingShadowDecl>(D)) 7912 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7913 7914 // Skip conversion function templates; they don't tell us anything 7915 // about which builtin types we can convert to. 7916 if (isa<FunctionTemplateDecl>(D)) 7917 continue; 7918 7919 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7920 if (AllowExplicitConversions || !Conv->isExplicit()) { 7921 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7922 VisibleQuals); 7923 } 7924 } 7925 } 7926 } 7927 /// Helper function for adjusting address spaces for the pointer or reference 7928 /// operands of builtin operators depending on the argument. 7929 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7930 Expr *Arg) { 7931 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7932 } 7933 7934 /// Helper function for AddBuiltinOperatorCandidates() that adds 7935 /// the volatile- and non-volatile-qualified assignment operators for the 7936 /// given type to the candidate set. 7937 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7938 QualType T, 7939 ArrayRef<Expr *> Args, 7940 OverloadCandidateSet &CandidateSet) { 7941 QualType ParamTypes[2]; 7942 7943 // T& operator=(T&, T) 7944 ParamTypes[0] = S.Context.getLValueReferenceType( 7945 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7946 ParamTypes[1] = T; 7947 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7948 /*IsAssignmentOperator=*/true); 7949 7950 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7951 // volatile T& operator=(volatile T&, T) 7952 ParamTypes[0] = S.Context.getLValueReferenceType( 7953 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7954 Args[0])); 7955 ParamTypes[1] = T; 7956 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7957 /*IsAssignmentOperator=*/true); 7958 } 7959 } 7960 7961 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7962 /// if any, found in visible type conversion functions found in ArgExpr's type. 7963 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7964 Qualifiers VRQuals; 7965 const RecordType *TyRec; 7966 if (const MemberPointerType *RHSMPType = 7967 ArgExpr->getType()->getAs<MemberPointerType>()) 7968 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7969 else 7970 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7971 if (!TyRec) { 7972 // Just to be safe, assume the worst case. 7973 VRQuals.addVolatile(); 7974 VRQuals.addRestrict(); 7975 return VRQuals; 7976 } 7977 7978 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7979 if (!ClassDecl->hasDefinition()) 7980 return VRQuals; 7981 7982 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7983 if (isa<UsingShadowDecl>(D)) 7984 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7985 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7986 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7987 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7988 CanTy = ResTypeRef->getPointeeType(); 7989 // Need to go down the pointer/mempointer chain and add qualifiers 7990 // as see them. 7991 bool done = false; 7992 while (!done) { 7993 if (CanTy.isRestrictQualified()) 7994 VRQuals.addRestrict(); 7995 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7996 CanTy = ResTypePtr->getPointeeType(); 7997 else if (const MemberPointerType *ResTypeMPtr = 7998 CanTy->getAs<MemberPointerType>()) 7999 CanTy = ResTypeMPtr->getPointeeType(); 8000 else 8001 done = true; 8002 if (CanTy.isVolatileQualified()) 8003 VRQuals.addVolatile(); 8004 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8005 return VRQuals; 8006 } 8007 } 8008 } 8009 return VRQuals; 8010 } 8011 8012 namespace { 8013 8014 /// Helper class to manage the addition of builtin operator overload 8015 /// candidates. It provides shared state and utility methods used throughout 8016 /// the process, as well as a helper method to add each group of builtin 8017 /// operator overloads from the standard to a candidate set. 8018 class BuiltinOperatorOverloadBuilder { 8019 // Common instance state available to all overload candidate addition methods. 8020 Sema &S; 8021 ArrayRef<Expr *> Args; 8022 Qualifiers VisibleTypeConversionsQuals; 8023 bool HasArithmeticOrEnumeralCandidateType; 8024 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8025 OverloadCandidateSet &CandidateSet; 8026 8027 static constexpr int ArithmeticTypesCap = 24; 8028 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8029 8030 // Define some indices used to iterate over the arithmetic types in 8031 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8032 // types are that preserved by promotion (C++ [over.built]p2). 8033 unsigned FirstIntegralType, 8034 LastIntegralType; 8035 unsigned FirstPromotedIntegralType, 8036 LastPromotedIntegralType; 8037 unsigned FirstPromotedArithmeticType, 8038 LastPromotedArithmeticType; 8039 unsigned NumArithmeticTypes; 8040 8041 void InitArithmeticTypes() { 8042 // Start of promoted types. 8043 FirstPromotedArithmeticType = 0; 8044 ArithmeticTypes.push_back(S.Context.FloatTy); 8045 ArithmeticTypes.push_back(S.Context.DoubleTy); 8046 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8047 if (S.Context.getTargetInfo().hasFloat128Type()) 8048 ArithmeticTypes.push_back(S.Context.Float128Ty); 8049 8050 // Start of integral types. 8051 FirstIntegralType = ArithmeticTypes.size(); 8052 FirstPromotedIntegralType = ArithmeticTypes.size(); 8053 ArithmeticTypes.push_back(S.Context.IntTy); 8054 ArithmeticTypes.push_back(S.Context.LongTy); 8055 ArithmeticTypes.push_back(S.Context.LongLongTy); 8056 if (S.Context.getTargetInfo().hasInt128Type()) 8057 ArithmeticTypes.push_back(S.Context.Int128Ty); 8058 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8059 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8060 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8061 if (S.Context.getTargetInfo().hasInt128Type()) 8062 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8063 LastPromotedIntegralType = ArithmeticTypes.size(); 8064 LastPromotedArithmeticType = ArithmeticTypes.size(); 8065 // End of promoted types. 8066 8067 ArithmeticTypes.push_back(S.Context.BoolTy); 8068 ArithmeticTypes.push_back(S.Context.CharTy); 8069 ArithmeticTypes.push_back(S.Context.WCharTy); 8070 if (S.Context.getLangOpts().Char8) 8071 ArithmeticTypes.push_back(S.Context.Char8Ty); 8072 ArithmeticTypes.push_back(S.Context.Char16Ty); 8073 ArithmeticTypes.push_back(S.Context.Char32Ty); 8074 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8075 ArithmeticTypes.push_back(S.Context.ShortTy); 8076 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8077 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8078 LastIntegralType = ArithmeticTypes.size(); 8079 NumArithmeticTypes = ArithmeticTypes.size(); 8080 // End of integral types. 8081 // FIXME: What about complex? What about half? 8082 8083 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8084 "Enough inline storage for all arithmetic types."); 8085 } 8086 8087 /// Helper method to factor out the common pattern of adding overloads 8088 /// for '++' and '--' builtin operators. 8089 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8090 bool HasVolatile, 8091 bool HasRestrict) { 8092 QualType ParamTypes[2] = { 8093 S.Context.getLValueReferenceType(CandidateTy), 8094 S.Context.IntTy 8095 }; 8096 8097 // Non-volatile version. 8098 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8099 8100 // Use a heuristic to reduce number of builtin candidates in the set: 8101 // add volatile version only if there are conversions to a volatile type. 8102 if (HasVolatile) { 8103 ParamTypes[0] = 8104 S.Context.getLValueReferenceType( 8105 S.Context.getVolatileType(CandidateTy)); 8106 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8107 } 8108 8109 // Add restrict version only if there are conversions to a restrict type 8110 // and our candidate type is a non-restrict-qualified pointer. 8111 if (HasRestrict && CandidateTy->isAnyPointerType() && 8112 !CandidateTy.isRestrictQualified()) { 8113 ParamTypes[0] 8114 = S.Context.getLValueReferenceType( 8115 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8116 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8117 8118 if (HasVolatile) { 8119 ParamTypes[0] 8120 = S.Context.getLValueReferenceType( 8121 S.Context.getCVRQualifiedType(CandidateTy, 8122 (Qualifiers::Volatile | 8123 Qualifiers::Restrict))); 8124 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8125 } 8126 } 8127 8128 } 8129 8130 public: 8131 BuiltinOperatorOverloadBuilder( 8132 Sema &S, ArrayRef<Expr *> Args, 8133 Qualifiers VisibleTypeConversionsQuals, 8134 bool HasArithmeticOrEnumeralCandidateType, 8135 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8136 OverloadCandidateSet &CandidateSet) 8137 : S(S), Args(Args), 8138 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8139 HasArithmeticOrEnumeralCandidateType( 8140 HasArithmeticOrEnumeralCandidateType), 8141 CandidateTypes(CandidateTypes), 8142 CandidateSet(CandidateSet) { 8143 8144 InitArithmeticTypes(); 8145 } 8146 8147 // Increment is deprecated for bool since C++17. 8148 // 8149 // C++ [over.built]p3: 8150 // 8151 // For every pair (T, VQ), where T is an arithmetic type other 8152 // than bool, and VQ is either volatile or empty, there exist 8153 // candidate operator functions of the form 8154 // 8155 // VQ T& operator++(VQ T&); 8156 // T operator++(VQ T&, int); 8157 // 8158 // C++ [over.built]p4: 8159 // 8160 // For every pair (T, VQ), where T is an arithmetic type other 8161 // than bool, and VQ is either volatile or empty, there exist 8162 // candidate operator functions of the form 8163 // 8164 // VQ T& operator--(VQ T&); 8165 // T operator--(VQ T&, int); 8166 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8167 if (!HasArithmeticOrEnumeralCandidateType) 8168 return; 8169 8170 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8171 const auto TypeOfT = ArithmeticTypes[Arith]; 8172 if (TypeOfT == S.Context.BoolTy) { 8173 if (Op == OO_MinusMinus) 8174 continue; 8175 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8176 continue; 8177 } 8178 addPlusPlusMinusMinusStyleOverloads( 8179 TypeOfT, 8180 VisibleTypeConversionsQuals.hasVolatile(), 8181 VisibleTypeConversionsQuals.hasRestrict()); 8182 } 8183 } 8184 8185 // C++ [over.built]p5: 8186 // 8187 // For every pair (T, VQ), where T is a cv-qualified or 8188 // cv-unqualified object type, and VQ is either volatile or 8189 // empty, there exist candidate operator functions of the form 8190 // 8191 // T*VQ& operator++(T*VQ&); 8192 // T*VQ& operator--(T*VQ&); 8193 // T* operator++(T*VQ&, int); 8194 // T* operator--(T*VQ&, int); 8195 void addPlusPlusMinusMinusPointerOverloads() { 8196 for (BuiltinCandidateTypeSet::iterator 8197 Ptr = CandidateTypes[0].pointer_begin(), 8198 PtrEnd = CandidateTypes[0].pointer_end(); 8199 Ptr != PtrEnd; ++Ptr) { 8200 // Skip pointer types that aren't pointers to object types. 8201 if (!(*Ptr)->getPointeeType()->isObjectType()) 8202 continue; 8203 8204 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8205 (!(*Ptr).isVolatileQualified() && 8206 VisibleTypeConversionsQuals.hasVolatile()), 8207 (!(*Ptr).isRestrictQualified() && 8208 VisibleTypeConversionsQuals.hasRestrict())); 8209 } 8210 } 8211 8212 // C++ [over.built]p6: 8213 // For every cv-qualified or cv-unqualified object type T, there 8214 // exist candidate operator functions of the form 8215 // 8216 // T& operator*(T*); 8217 // 8218 // C++ [over.built]p7: 8219 // For every function type T that does not have cv-qualifiers or a 8220 // ref-qualifier, there exist candidate operator functions of the form 8221 // T& operator*(T*); 8222 void addUnaryStarPointerOverloads() { 8223 for (BuiltinCandidateTypeSet::iterator 8224 Ptr = CandidateTypes[0].pointer_begin(), 8225 PtrEnd = CandidateTypes[0].pointer_end(); 8226 Ptr != PtrEnd; ++Ptr) { 8227 QualType ParamTy = *Ptr; 8228 QualType PointeeTy = ParamTy->getPointeeType(); 8229 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8230 continue; 8231 8232 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8233 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8234 continue; 8235 8236 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8237 } 8238 } 8239 8240 // C++ [over.built]p9: 8241 // For every promoted arithmetic type T, there exist candidate 8242 // operator functions of the form 8243 // 8244 // T operator+(T); 8245 // T operator-(T); 8246 void addUnaryPlusOrMinusArithmeticOverloads() { 8247 if (!HasArithmeticOrEnumeralCandidateType) 8248 return; 8249 8250 for (unsigned Arith = FirstPromotedArithmeticType; 8251 Arith < LastPromotedArithmeticType; ++Arith) { 8252 QualType ArithTy = ArithmeticTypes[Arith]; 8253 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8254 } 8255 8256 // Extension: We also add these operators for vector types. 8257 for (BuiltinCandidateTypeSet::iterator 8258 Vec = CandidateTypes[0].vector_begin(), 8259 VecEnd = CandidateTypes[0].vector_end(); 8260 Vec != VecEnd; ++Vec) { 8261 QualType VecTy = *Vec; 8262 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8263 } 8264 } 8265 8266 // C++ [over.built]p8: 8267 // For every type T, there exist candidate operator functions of 8268 // the form 8269 // 8270 // T* operator+(T*); 8271 void addUnaryPlusPointerOverloads() { 8272 for (BuiltinCandidateTypeSet::iterator 8273 Ptr = CandidateTypes[0].pointer_begin(), 8274 PtrEnd = CandidateTypes[0].pointer_end(); 8275 Ptr != PtrEnd; ++Ptr) { 8276 QualType ParamTy = *Ptr; 8277 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8278 } 8279 } 8280 8281 // C++ [over.built]p10: 8282 // For every promoted integral type T, there exist candidate 8283 // operator functions of the form 8284 // 8285 // T operator~(T); 8286 void addUnaryTildePromotedIntegralOverloads() { 8287 if (!HasArithmeticOrEnumeralCandidateType) 8288 return; 8289 8290 for (unsigned Int = FirstPromotedIntegralType; 8291 Int < LastPromotedIntegralType; ++Int) { 8292 QualType IntTy = ArithmeticTypes[Int]; 8293 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8294 } 8295 8296 // Extension: We also add this operator for vector types. 8297 for (BuiltinCandidateTypeSet::iterator 8298 Vec = CandidateTypes[0].vector_begin(), 8299 VecEnd = CandidateTypes[0].vector_end(); 8300 Vec != VecEnd; ++Vec) { 8301 QualType VecTy = *Vec; 8302 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8303 } 8304 } 8305 8306 // C++ [over.match.oper]p16: 8307 // For every pointer to member type T or type std::nullptr_t, there 8308 // exist candidate operator functions of the form 8309 // 8310 // bool operator==(T,T); 8311 // bool operator!=(T,T); 8312 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8313 /// Set of (canonical) types that we've already handled. 8314 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8315 8316 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8317 for (BuiltinCandidateTypeSet::iterator 8318 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8319 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8320 MemPtr != MemPtrEnd; 8321 ++MemPtr) { 8322 // Don't add the same builtin candidate twice. 8323 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8324 continue; 8325 8326 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8327 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8328 } 8329 8330 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8331 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8332 if (AddedTypes.insert(NullPtrTy).second) { 8333 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8334 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8335 } 8336 } 8337 } 8338 } 8339 8340 // C++ [over.built]p15: 8341 // 8342 // For every T, where T is an enumeration type or a pointer type, 8343 // there exist candidate operator functions of the form 8344 // 8345 // bool operator<(T, T); 8346 // bool operator>(T, T); 8347 // bool operator<=(T, T); 8348 // bool operator>=(T, T); 8349 // bool operator==(T, T); 8350 // bool operator!=(T, T); 8351 // R operator<=>(T, T) 8352 void addGenericBinaryPointerOrEnumeralOverloads() { 8353 // C++ [over.match.oper]p3: 8354 // [...]the built-in candidates include all of the candidate operator 8355 // functions defined in 13.6 that, compared to the given operator, [...] 8356 // do not have the same parameter-type-list as any non-template non-member 8357 // candidate. 8358 // 8359 // Note that in practice, this only affects enumeration types because there 8360 // aren't any built-in candidates of record type, and a user-defined operator 8361 // must have an operand of record or enumeration type. Also, the only other 8362 // overloaded operator with enumeration arguments, operator=, 8363 // cannot be overloaded for enumeration types, so this is the only place 8364 // where we must suppress candidates like this. 8365 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8366 UserDefinedBinaryOperators; 8367 8368 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8369 if (CandidateTypes[ArgIdx].enumeration_begin() != 8370 CandidateTypes[ArgIdx].enumeration_end()) { 8371 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8372 CEnd = CandidateSet.end(); 8373 C != CEnd; ++C) { 8374 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8375 continue; 8376 8377 if (C->Function->isFunctionTemplateSpecialization()) 8378 continue; 8379 8380 // We interpret "same parameter-type-list" as applying to the 8381 // "synthesized candidate, with the order of the two parameters 8382 // reversed", not to the original function. 8383 bool Reversed = C->RewriteKind & CRK_Reversed; 8384 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8385 ->getType() 8386 .getUnqualifiedType(); 8387 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8388 ->getType() 8389 .getUnqualifiedType(); 8390 8391 // Skip if either parameter isn't of enumeral type. 8392 if (!FirstParamType->isEnumeralType() || 8393 !SecondParamType->isEnumeralType()) 8394 continue; 8395 8396 // Add this operator to the set of known user-defined operators. 8397 UserDefinedBinaryOperators.insert( 8398 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8399 S.Context.getCanonicalType(SecondParamType))); 8400 } 8401 } 8402 } 8403 8404 /// Set of (canonical) types that we've already handled. 8405 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8406 8407 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8408 for (BuiltinCandidateTypeSet::iterator 8409 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8410 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8411 Ptr != PtrEnd; ++Ptr) { 8412 // Don't add the same builtin candidate twice. 8413 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8414 continue; 8415 8416 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8417 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8418 } 8419 for (BuiltinCandidateTypeSet::iterator 8420 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8421 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8422 Enum != EnumEnd; ++Enum) { 8423 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8424 8425 // Don't add the same builtin candidate twice, or if a user defined 8426 // candidate exists. 8427 if (!AddedTypes.insert(CanonType).second || 8428 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8429 CanonType))) 8430 continue; 8431 QualType ParamTypes[2] = { *Enum, *Enum }; 8432 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8433 } 8434 } 8435 } 8436 8437 // C++ [over.built]p13: 8438 // 8439 // For every cv-qualified or cv-unqualified object type T 8440 // there exist candidate operator functions of the form 8441 // 8442 // T* operator+(T*, ptrdiff_t); 8443 // T& operator[](T*, ptrdiff_t); [BELOW] 8444 // T* operator-(T*, ptrdiff_t); 8445 // T* operator+(ptrdiff_t, T*); 8446 // T& operator[](ptrdiff_t, T*); [BELOW] 8447 // 8448 // C++ [over.built]p14: 8449 // 8450 // For every T, where T is a pointer to object type, there 8451 // exist candidate operator functions of the form 8452 // 8453 // ptrdiff_t operator-(T, T); 8454 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8455 /// Set of (canonical) types that we've already handled. 8456 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8457 8458 for (int Arg = 0; Arg < 2; ++Arg) { 8459 QualType AsymmetricParamTypes[2] = { 8460 S.Context.getPointerDiffType(), 8461 S.Context.getPointerDiffType(), 8462 }; 8463 for (BuiltinCandidateTypeSet::iterator 8464 Ptr = CandidateTypes[Arg].pointer_begin(), 8465 PtrEnd = CandidateTypes[Arg].pointer_end(); 8466 Ptr != PtrEnd; ++Ptr) { 8467 QualType PointeeTy = (*Ptr)->getPointeeType(); 8468 if (!PointeeTy->isObjectType()) 8469 continue; 8470 8471 AsymmetricParamTypes[Arg] = *Ptr; 8472 if (Arg == 0 || Op == OO_Plus) { 8473 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8474 // T* operator+(ptrdiff_t, T*); 8475 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8476 } 8477 if (Op == OO_Minus) { 8478 // ptrdiff_t operator-(T, T); 8479 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8480 continue; 8481 8482 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8483 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8484 } 8485 } 8486 } 8487 } 8488 8489 // C++ [over.built]p12: 8490 // 8491 // For every pair of promoted arithmetic types L and R, there 8492 // exist candidate operator functions of the form 8493 // 8494 // LR operator*(L, R); 8495 // LR operator/(L, R); 8496 // LR operator+(L, R); 8497 // LR operator-(L, R); 8498 // bool operator<(L, R); 8499 // bool operator>(L, R); 8500 // bool operator<=(L, R); 8501 // bool operator>=(L, R); 8502 // bool operator==(L, R); 8503 // bool operator!=(L, R); 8504 // 8505 // where LR is the result of the usual arithmetic conversions 8506 // between types L and R. 8507 // 8508 // C++ [over.built]p24: 8509 // 8510 // For every pair of promoted arithmetic types L and R, there exist 8511 // candidate operator functions of the form 8512 // 8513 // LR operator?(bool, L, R); 8514 // 8515 // where LR is the result of the usual arithmetic conversions 8516 // between types L and R. 8517 // Our candidates ignore the first parameter. 8518 void addGenericBinaryArithmeticOverloads() { 8519 if (!HasArithmeticOrEnumeralCandidateType) 8520 return; 8521 8522 for (unsigned Left = FirstPromotedArithmeticType; 8523 Left < LastPromotedArithmeticType; ++Left) { 8524 for (unsigned Right = FirstPromotedArithmeticType; 8525 Right < LastPromotedArithmeticType; ++Right) { 8526 QualType LandR[2] = { ArithmeticTypes[Left], 8527 ArithmeticTypes[Right] }; 8528 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8529 } 8530 } 8531 8532 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8533 // conditional operator for vector types. 8534 for (BuiltinCandidateTypeSet::iterator 8535 Vec1 = CandidateTypes[0].vector_begin(), 8536 Vec1End = CandidateTypes[0].vector_end(); 8537 Vec1 != Vec1End; ++Vec1) { 8538 for (BuiltinCandidateTypeSet::iterator 8539 Vec2 = CandidateTypes[1].vector_begin(), 8540 Vec2End = CandidateTypes[1].vector_end(); 8541 Vec2 != Vec2End; ++Vec2) { 8542 QualType LandR[2] = { *Vec1, *Vec2 }; 8543 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8544 } 8545 } 8546 } 8547 8548 // C++2a [over.built]p14: 8549 // 8550 // For every integral type T there exists a candidate operator function 8551 // of the form 8552 // 8553 // std::strong_ordering operator<=>(T, T) 8554 // 8555 // C++2a [over.built]p15: 8556 // 8557 // For every pair of floating-point types L and R, there exists a candidate 8558 // operator function of the form 8559 // 8560 // std::partial_ordering operator<=>(L, R); 8561 // 8562 // FIXME: The current specification for integral types doesn't play nice with 8563 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8564 // comparisons. Under the current spec this can lead to ambiguity during 8565 // overload resolution. For example: 8566 // 8567 // enum A : int {a}; 8568 // auto x = (a <=> (long)42); 8569 // 8570 // error: call is ambiguous for arguments 'A' and 'long'. 8571 // note: candidate operator<=>(int, int) 8572 // note: candidate operator<=>(long, long) 8573 // 8574 // To avoid this error, this function deviates from the specification and adds 8575 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8576 // arithmetic types (the same as the generic relational overloads). 8577 // 8578 // For now this function acts as a placeholder. 8579 void addThreeWayArithmeticOverloads() { 8580 addGenericBinaryArithmeticOverloads(); 8581 } 8582 8583 // C++ [over.built]p17: 8584 // 8585 // For every pair of promoted integral types L and R, there 8586 // exist candidate operator functions of the form 8587 // 8588 // LR operator%(L, R); 8589 // LR operator&(L, R); 8590 // LR operator^(L, R); 8591 // LR operator|(L, R); 8592 // L operator<<(L, R); 8593 // L operator>>(L, R); 8594 // 8595 // where LR is the result of the usual arithmetic conversions 8596 // between types L and R. 8597 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8598 if (!HasArithmeticOrEnumeralCandidateType) 8599 return; 8600 8601 for (unsigned Left = FirstPromotedIntegralType; 8602 Left < LastPromotedIntegralType; ++Left) { 8603 for (unsigned Right = FirstPromotedIntegralType; 8604 Right < LastPromotedIntegralType; ++Right) { 8605 QualType LandR[2] = { ArithmeticTypes[Left], 8606 ArithmeticTypes[Right] }; 8607 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8608 } 8609 } 8610 } 8611 8612 // C++ [over.built]p20: 8613 // 8614 // For every pair (T, VQ), where T is an enumeration or 8615 // pointer to member type and VQ is either volatile or 8616 // empty, there exist candidate operator functions of the form 8617 // 8618 // VQ T& operator=(VQ T&, T); 8619 void addAssignmentMemberPointerOrEnumeralOverloads() { 8620 /// Set of (canonical) types that we've already handled. 8621 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8622 8623 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8624 for (BuiltinCandidateTypeSet::iterator 8625 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8626 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8627 Enum != EnumEnd; ++Enum) { 8628 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8629 continue; 8630 8631 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8632 } 8633 8634 for (BuiltinCandidateTypeSet::iterator 8635 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8636 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8637 MemPtr != MemPtrEnd; ++MemPtr) { 8638 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8639 continue; 8640 8641 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8642 } 8643 } 8644 } 8645 8646 // C++ [over.built]p19: 8647 // 8648 // For every pair (T, VQ), where T is any type and VQ is either 8649 // volatile or empty, there exist candidate operator functions 8650 // of the form 8651 // 8652 // T*VQ& operator=(T*VQ&, T*); 8653 // 8654 // C++ [over.built]p21: 8655 // 8656 // For every pair (T, VQ), where T is a cv-qualified or 8657 // cv-unqualified object type and VQ is either volatile or 8658 // empty, there exist candidate operator functions of the form 8659 // 8660 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8661 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8662 void addAssignmentPointerOverloads(bool isEqualOp) { 8663 /// Set of (canonical) types that we've already handled. 8664 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8665 8666 for (BuiltinCandidateTypeSet::iterator 8667 Ptr = CandidateTypes[0].pointer_begin(), 8668 PtrEnd = CandidateTypes[0].pointer_end(); 8669 Ptr != PtrEnd; ++Ptr) { 8670 // If this is operator=, keep track of the builtin candidates we added. 8671 if (isEqualOp) 8672 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8673 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8674 continue; 8675 8676 // non-volatile version 8677 QualType ParamTypes[2] = { 8678 S.Context.getLValueReferenceType(*Ptr), 8679 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8680 }; 8681 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8682 /*IsAssignmentOperator=*/ isEqualOp); 8683 8684 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8685 VisibleTypeConversionsQuals.hasVolatile(); 8686 if (NeedVolatile) { 8687 // volatile version 8688 ParamTypes[0] = 8689 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8690 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8691 /*IsAssignmentOperator=*/isEqualOp); 8692 } 8693 8694 if (!(*Ptr).isRestrictQualified() && 8695 VisibleTypeConversionsQuals.hasRestrict()) { 8696 // restrict version 8697 ParamTypes[0] 8698 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8699 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8700 /*IsAssignmentOperator=*/isEqualOp); 8701 8702 if (NeedVolatile) { 8703 // volatile restrict version 8704 ParamTypes[0] 8705 = S.Context.getLValueReferenceType( 8706 S.Context.getCVRQualifiedType(*Ptr, 8707 (Qualifiers::Volatile | 8708 Qualifiers::Restrict))); 8709 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8710 /*IsAssignmentOperator=*/isEqualOp); 8711 } 8712 } 8713 } 8714 8715 if (isEqualOp) { 8716 for (BuiltinCandidateTypeSet::iterator 8717 Ptr = CandidateTypes[1].pointer_begin(), 8718 PtrEnd = CandidateTypes[1].pointer_end(); 8719 Ptr != PtrEnd; ++Ptr) { 8720 // Make sure we don't add the same candidate twice. 8721 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8722 continue; 8723 8724 QualType ParamTypes[2] = { 8725 S.Context.getLValueReferenceType(*Ptr), 8726 *Ptr, 8727 }; 8728 8729 // non-volatile version 8730 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8731 /*IsAssignmentOperator=*/true); 8732 8733 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8734 VisibleTypeConversionsQuals.hasVolatile(); 8735 if (NeedVolatile) { 8736 // volatile version 8737 ParamTypes[0] = 8738 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8739 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8740 /*IsAssignmentOperator=*/true); 8741 } 8742 8743 if (!(*Ptr).isRestrictQualified() && 8744 VisibleTypeConversionsQuals.hasRestrict()) { 8745 // restrict version 8746 ParamTypes[0] 8747 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8748 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8749 /*IsAssignmentOperator=*/true); 8750 8751 if (NeedVolatile) { 8752 // volatile restrict version 8753 ParamTypes[0] 8754 = S.Context.getLValueReferenceType( 8755 S.Context.getCVRQualifiedType(*Ptr, 8756 (Qualifiers::Volatile | 8757 Qualifiers::Restrict))); 8758 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8759 /*IsAssignmentOperator=*/true); 8760 } 8761 } 8762 } 8763 } 8764 } 8765 8766 // C++ [over.built]p18: 8767 // 8768 // For every triple (L, VQ, R), where L is an arithmetic type, 8769 // VQ is either volatile or empty, and R is a promoted 8770 // arithmetic type, there exist candidate operator functions of 8771 // the form 8772 // 8773 // VQ L& operator=(VQ L&, R); 8774 // VQ L& operator*=(VQ L&, R); 8775 // VQ L& operator/=(VQ L&, R); 8776 // VQ L& operator+=(VQ L&, R); 8777 // VQ L& operator-=(VQ L&, R); 8778 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8779 if (!HasArithmeticOrEnumeralCandidateType) 8780 return; 8781 8782 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8783 for (unsigned Right = FirstPromotedArithmeticType; 8784 Right < LastPromotedArithmeticType; ++Right) { 8785 QualType ParamTypes[2]; 8786 ParamTypes[1] = ArithmeticTypes[Right]; 8787 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8788 S, ArithmeticTypes[Left], Args[0]); 8789 // Add this built-in operator as a candidate (VQ is empty). 8790 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8791 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8792 /*IsAssignmentOperator=*/isEqualOp); 8793 8794 // Add this built-in operator as a candidate (VQ is 'volatile'). 8795 if (VisibleTypeConversionsQuals.hasVolatile()) { 8796 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8797 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8798 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8799 /*IsAssignmentOperator=*/isEqualOp); 8800 } 8801 } 8802 } 8803 8804 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8805 for (BuiltinCandidateTypeSet::iterator 8806 Vec1 = CandidateTypes[0].vector_begin(), 8807 Vec1End = CandidateTypes[0].vector_end(); 8808 Vec1 != Vec1End; ++Vec1) { 8809 for (BuiltinCandidateTypeSet::iterator 8810 Vec2 = CandidateTypes[1].vector_begin(), 8811 Vec2End = CandidateTypes[1].vector_end(); 8812 Vec2 != Vec2End; ++Vec2) { 8813 QualType ParamTypes[2]; 8814 ParamTypes[1] = *Vec2; 8815 // Add this built-in operator as a candidate (VQ is empty). 8816 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8817 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8818 /*IsAssignmentOperator=*/isEqualOp); 8819 8820 // Add this built-in operator as a candidate (VQ is 'volatile'). 8821 if (VisibleTypeConversionsQuals.hasVolatile()) { 8822 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8823 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8824 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8825 /*IsAssignmentOperator=*/isEqualOp); 8826 } 8827 } 8828 } 8829 } 8830 8831 // C++ [over.built]p22: 8832 // 8833 // For every triple (L, VQ, R), where L is an integral type, VQ 8834 // is either volatile or empty, and R is a promoted integral 8835 // type, there exist candidate operator functions of the form 8836 // 8837 // VQ L& operator%=(VQ L&, R); 8838 // VQ L& operator<<=(VQ L&, R); 8839 // VQ L& operator>>=(VQ L&, R); 8840 // VQ L& operator&=(VQ L&, R); 8841 // VQ L& operator^=(VQ L&, R); 8842 // VQ L& operator|=(VQ L&, R); 8843 void addAssignmentIntegralOverloads() { 8844 if (!HasArithmeticOrEnumeralCandidateType) 8845 return; 8846 8847 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8848 for (unsigned Right = FirstPromotedIntegralType; 8849 Right < LastPromotedIntegralType; ++Right) { 8850 QualType ParamTypes[2]; 8851 ParamTypes[1] = ArithmeticTypes[Right]; 8852 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8853 S, ArithmeticTypes[Left], Args[0]); 8854 // Add this built-in operator as a candidate (VQ is empty). 8855 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8856 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8857 if (VisibleTypeConversionsQuals.hasVolatile()) { 8858 // Add this built-in operator as a candidate (VQ is 'volatile'). 8859 ParamTypes[0] = LeftBaseTy; 8860 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8861 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8862 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8863 } 8864 } 8865 } 8866 } 8867 8868 // C++ [over.operator]p23: 8869 // 8870 // There also exist candidate operator functions of the form 8871 // 8872 // bool operator!(bool); 8873 // bool operator&&(bool, bool); 8874 // bool operator||(bool, bool); 8875 void addExclaimOverload() { 8876 QualType ParamTy = S.Context.BoolTy; 8877 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8878 /*IsAssignmentOperator=*/false, 8879 /*NumContextualBoolArguments=*/1); 8880 } 8881 void addAmpAmpOrPipePipeOverload() { 8882 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8883 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8884 /*IsAssignmentOperator=*/false, 8885 /*NumContextualBoolArguments=*/2); 8886 } 8887 8888 // C++ [over.built]p13: 8889 // 8890 // For every cv-qualified or cv-unqualified object type T there 8891 // exist candidate operator functions of the form 8892 // 8893 // T* operator+(T*, ptrdiff_t); [ABOVE] 8894 // T& operator[](T*, ptrdiff_t); 8895 // T* operator-(T*, ptrdiff_t); [ABOVE] 8896 // T* operator+(ptrdiff_t, T*); [ABOVE] 8897 // T& operator[](ptrdiff_t, T*); 8898 void addSubscriptOverloads() { 8899 for (BuiltinCandidateTypeSet::iterator 8900 Ptr = CandidateTypes[0].pointer_begin(), 8901 PtrEnd = CandidateTypes[0].pointer_end(); 8902 Ptr != PtrEnd; ++Ptr) { 8903 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8904 QualType PointeeType = (*Ptr)->getPointeeType(); 8905 if (!PointeeType->isObjectType()) 8906 continue; 8907 8908 // T& operator[](T*, ptrdiff_t) 8909 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8910 } 8911 8912 for (BuiltinCandidateTypeSet::iterator 8913 Ptr = CandidateTypes[1].pointer_begin(), 8914 PtrEnd = CandidateTypes[1].pointer_end(); 8915 Ptr != PtrEnd; ++Ptr) { 8916 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8917 QualType PointeeType = (*Ptr)->getPointeeType(); 8918 if (!PointeeType->isObjectType()) 8919 continue; 8920 8921 // T& operator[](ptrdiff_t, T*) 8922 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8923 } 8924 } 8925 8926 // C++ [over.built]p11: 8927 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8928 // C1 is the same type as C2 or is a derived class of C2, T is an object 8929 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8930 // there exist candidate operator functions of the form 8931 // 8932 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8933 // 8934 // where CV12 is the union of CV1 and CV2. 8935 void addArrowStarOverloads() { 8936 for (BuiltinCandidateTypeSet::iterator 8937 Ptr = CandidateTypes[0].pointer_begin(), 8938 PtrEnd = CandidateTypes[0].pointer_end(); 8939 Ptr != PtrEnd; ++Ptr) { 8940 QualType C1Ty = (*Ptr); 8941 QualType C1; 8942 QualifierCollector Q1; 8943 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8944 if (!isa<RecordType>(C1)) 8945 continue; 8946 // heuristic to reduce number of builtin candidates in the set. 8947 // Add volatile/restrict version only if there are conversions to a 8948 // volatile/restrict type. 8949 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8950 continue; 8951 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8952 continue; 8953 for (BuiltinCandidateTypeSet::iterator 8954 MemPtr = CandidateTypes[1].member_pointer_begin(), 8955 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8956 MemPtr != MemPtrEnd; ++MemPtr) { 8957 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8958 QualType C2 = QualType(mptr->getClass(), 0); 8959 C2 = C2.getUnqualifiedType(); 8960 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8961 break; 8962 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8963 // build CV12 T& 8964 QualType T = mptr->getPointeeType(); 8965 if (!VisibleTypeConversionsQuals.hasVolatile() && 8966 T.isVolatileQualified()) 8967 continue; 8968 if (!VisibleTypeConversionsQuals.hasRestrict() && 8969 T.isRestrictQualified()) 8970 continue; 8971 T = Q1.apply(S.Context, T); 8972 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8973 } 8974 } 8975 } 8976 8977 // Note that we don't consider the first argument, since it has been 8978 // contextually converted to bool long ago. The candidates below are 8979 // therefore added as binary. 8980 // 8981 // C++ [over.built]p25: 8982 // For every type T, where T is a pointer, pointer-to-member, or scoped 8983 // enumeration type, there exist candidate operator functions of the form 8984 // 8985 // T operator?(bool, T, T); 8986 // 8987 void addConditionalOperatorOverloads() { 8988 /// Set of (canonical) types that we've already handled. 8989 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8990 8991 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8992 for (BuiltinCandidateTypeSet::iterator 8993 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8994 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8995 Ptr != PtrEnd; ++Ptr) { 8996 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8997 continue; 8998 8999 QualType ParamTypes[2] = { *Ptr, *Ptr }; 9000 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9001 } 9002 9003 for (BuiltinCandidateTypeSet::iterator 9004 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 9005 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 9006 MemPtr != MemPtrEnd; ++MemPtr) { 9007 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 9008 continue; 9009 9010 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 9011 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9012 } 9013 9014 if (S.getLangOpts().CPlusPlus11) { 9015 for (BuiltinCandidateTypeSet::iterator 9016 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 9017 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 9018 Enum != EnumEnd; ++Enum) { 9019 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 9020 continue; 9021 9022 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 9023 continue; 9024 9025 QualType ParamTypes[2] = { *Enum, *Enum }; 9026 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9027 } 9028 } 9029 } 9030 } 9031 }; 9032 9033 } // end anonymous namespace 9034 9035 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9036 /// operator overloads to the candidate set (C++ [over.built]), based 9037 /// on the operator @p Op and the arguments given. For example, if the 9038 /// operator is a binary '+', this routine might add "int 9039 /// operator+(int, int)" to cover integer addition. 9040 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9041 SourceLocation OpLoc, 9042 ArrayRef<Expr *> Args, 9043 OverloadCandidateSet &CandidateSet) { 9044 // Find all of the types that the arguments can convert to, but only 9045 // if the operator we're looking at has built-in operator candidates 9046 // that make use of these types. Also record whether we encounter non-record 9047 // candidate types or either arithmetic or enumeral candidate types. 9048 Qualifiers VisibleTypeConversionsQuals; 9049 VisibleTypeConversionsQuals.addConst(); 9050 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9051 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9052 9053 bool HasNonRecordCandidateType = false; 9054 bool HasArithmeticOrEnumeralCandidateType = false; 9055 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9056 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9057 CandidateTypes.emplace_back(*this); 9058 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9059 OpLoc, 9060 true, 9061 (Op == OO_Exclaim || 9062 Op == OO_AmpAmp || 9063 Op == OO_PipePipe), 9064 VisibleTypeConversionsQuals); 9065 HasNonRecordCandidateType = HasNonRecordCandidateType || 9066 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9067 HasArithmeticOrEnumeralCandidateType = 9068 HasArithmeticOrEnumeralCandidateType || 9069 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9070 } 9071 9072 // Exit early when no non-record types have been added to the candidate set 9073 // for any of the arguments to the operator. 9074 // 9075 // We can't exit early for !, ||, or &&, since there we have always have 9076 // 'bool' overloads. 9077 if (!HasNonRecordCandidateType && 9078 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9079 return; 9080 9081 // Setup an object to manage the common state for building overloads. 9082 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9083 VisibleTypeConversionsQuals, 9084 HasArithmeticOrEnumeralCandidateType, 9085 CandidateTypes, CandidateSet); 9086 9087 // Dispatch over the operation to add in only those overloads which apply. 9088 switch (Op) { 9089 case OO_None: 9090 case NUM_OVERLOADED_OPERATORS: 9091 llvm_unreachable("Expected an overloaded operator"); 9092 9093 case OO_New: 9094 case OO_Delete: 9095 case OO_Array_New: 9096 case OO_Array_Delete: 9097 case OO_Call: 9098 llvm_unreachable( 9099 "Special operators don't use AddBuiltinOperatorCandidates"); 9100 9101 case OO_Comma: 9102 case OO_Arrow: 9103 case OO_Coawait: 9104 // C++ [over.match.oper]p3: 9105 // -- For the operator ',', the unary operator '&', the 9106 // operator '->', or the operator 'co_await', the 9107 // built-in candidates set is empty. 9108 break; 9109 9110 case OO_Plus: // '+' is either unary or binary 9111 if (Args.size() == 1) 9112 OpBuilder.addUnaryPlusPointerOverloads(); 9113 LLVM_FALLTHROUGH; 9114 9115 case OO_Minus: // '-' is either unary or binary 9116 if (Args.size() == 1) { 9117 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9118 } else { 9119 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9120 OpBuilder.addGenericBinaryArithmeticOverloads(); 9121 } 9122 break; 9123 9124 case OO_Star: // '*' is either unary or binary 9125 if (Args.size() == 1) 9126 OpBuilder.addUnaryStarPointerOverloads(); 9127 else 9128 OpBuilder.addGenericBinaryArithmeticOverloads(); 9129 break; 9130 9131 case OO_Slash: 9132 OpBuilder.addGenericBinaryArithmeticOverloads(); 9133 break; 9134 9135 case OO_PlusPlus: 9136 case OO_MinusMinus: 9137 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9138 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9139 break; 9140 9141 case OO_EqualEqual: 9142 case OO_ExclaimEqual: 9143 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9144 LLVM_FALLTHROUGH; 9145 9146 case OO_Less: 9147 case OO_Greater: 9148 case OO_LessEqual: 9149 case OO_GreaterEqual: 9150 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9151 OpBuilder.addGenericBinaryArithmeticOverloads(); 9152 break; 9153 9154 case OO_Spaceship: 9155 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9156 OpBuilder.addThreeWayArithmeticOverloads(); 9157 break; 9158 9159 case OO_Percent: 9160 case OO_Caret: 9161 case OO_Pipe: 9162 case OO_LessLess: 9163 case OO_GreaterGreater: 9164 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9165 break; 9166 9167 case OO_Amp: // '&' is either unary or binary 9168 if (Args.size() == 1) 9169 // C++ [over.match.oper]p3: 9170 // -- For the operator ',', the unary operator '&', or the 9171 // operator '->', the built-in candidates set is empty. 9172 break; 9173 9174 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9175 break; 9176 9177 case OO_Tilde: 9178 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9179 break; 9180 9181 case OO_Equal: 9182 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9183 LLVM_FALLTHROUGH; 9184 9185 case OO_PlusEqual: 9186 case OO_MinusEqual: 9187 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9188 LLVM_FALLTHROUGH; 9189 9190 case OO_StarEqual: 9191 case OO_SlashEqual: 9192 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9193 break; 9194 9195 case OO_PercentEqual: 9196 case OO_LessLessEqual: 9197 case OO_GreaterGreaterEqual: 9198 case OO_AmpEqual: 9199 case OO_CaretEqual: 9200 case OO_PipeEqual: 9201 OpBuilder.addAssignmentIntegralOverloads(); 9202 break; 9203 9204 case OO_Exclaim: 9205 OpBuilder.addExclaimOverload(); 9206 break; 9207 9208 case OO_AmpAmp: 9209 case OO_PipePipe: 9210 OpBuilder.addAmpAmpOrPipePipeOverload(); 9211 break; 9212 9213 case OO_Subscript: 9214 OpBuilder.addSubscriptOverloads(); 9215 break; 9216 9217 case OO_ArrowStar: 9218 OpBuilder.addArrowStarOverloads(); 9219 break; 9220 9221 case OO_Conditional: 9222 OpBuilder.addConditionalOperatorOverloads(); 9223 OpBuilder.addGenericBinaryArithmeticOverloads(); 9224 break; 9225 } 9226 } 9227 9228 /// Add function candidates found via argument-dependent lookup 9229 /// to the set of overloading candidates. 9230 /// 9231 /// This routine performs argument-dependent name lookup based on the 9232 /// given function name (which may also be an operator name) and adds 9233 /// all of the overload candidates found by ADL to the overload 9234 /// candidate set (C++ [basic.lookup.argdep]). 9235 void 9236 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9237 SourceLocation Loc, 9238 ArrayRef<Expr *> Args, 9239 TemplateArgumentListInfo *ExplicitTemplateArgs, 9240 OverloadCandidateSet& CandidateSet, 9241 bool PartialOverloading) { 9242 ADLResult Fns; 9243 9244 // FIXME: This approach for uniquing ADL results (and removing 9245 // redundant candidates from the set) relies on pointer-equality, 9246 // which means we need to key off the canonical decl. However, 9247 // always going back to the canonical decl might not get us the 9248 // right set of default arguments. What default arguments are 9249 // we supposed to consider on ADL candidates, anyway? 9250 9251 // FIXME: Pass in the explicit template arguments? 9252 ArgumentDependentLookup(Name, Loc, Args, Fns); 9253 9254 // Erase all of the candidates we already knew about. 9255 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9256 CandEnd = CandidateSet.end(); 9257 Cand != CandEnd; ++Cand) 9258 if (Cand->Function) { 9259 Fns.erase(Cand->Function); 9260 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9261 Fns.erase(FunTmpl); 9262 } 9263 9264 // For each of the ADL candidates we found, add it to the overload 9265 // set. 9266 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9267 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9268 9269 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9270 if (ExplicitTemplateArgs) 9271 continue; 9272 9273 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, 9274 /*SuppressUserConversions=*/false, PartialOverloading, 9275 /*AllowExplicit*/ true, 9276 /*AllowExplicitConversions*/ false, 9277 ADLCallKind::UsesADL); 9278 } else { 9279 AddTemplateOverloadCandidate( 9280 cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args, 9281 CandidateSet, 9282 /*SuppressUserConversions=*/false, PartialOverloading, 9283 /*AllowExplicit*/true, ADLCallKind::UsesADL); 9284 } 9285 } 9286 } 9287 9288 namespace { 9289 enum class Comparison { Equal, Better, Worse }; 9290 } 9291 9292 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9293 /// overload resolution. 9294 /// 9295 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9296 /// Cand1's first N enable_if attributes have precisely the same conditions as 9297 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9298 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9299 /// 9300 /// Note that you can have a pair of candidates such that Cand1's enable_if 9301 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9302 /// worse than Cand1's. 9303 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9304 const FunctionDecl *Cand2) { 9305 // Common case: One (or both) decls don't have enable_if attrs. 9306 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9307 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9308 if (!Cand1Attr || !Cand2Attr) { 9309 if (Cand1Attr == Cand2Attr) 9310 return Comparison::Equal; 9311 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9312 } 9313 9314 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9315 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9316 9317 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9318 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9319 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9320 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9321 9322 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9323 // has fewer enable_if attributes than Cand2, and vice versa. 9324 if (!Cand1A) 9325 return Comparison::Worse; 9326 if (!Cand2A) 9327 return Comparison::Better; 9328 9329 Cand1ID.clear(); 9330 Cand2ID.clear(); 9331 9332 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9333 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9334 if (Cand1ID != Cand2ID) 9335 return Comparison::Worse; 9336 } 9337 9338 return Comparison::Equal; 9339 } 9340 9341 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9342 const OverloadCandidate &Cand2) { 9343 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9344 !Cand2.Function->isMultiVersion()) 9345 return false; 9346 9347 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9348 // is obviously better. 9349 if (Cand1.Function->isInvalidDecl()) return false; 9350 if (Cand2.Function->isInvalidDecl()) return true; 9351 9352 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9353 // cpu_dispatch, else arbitrarily based on the identifiers. 9354 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9355 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9356 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9357 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9358 9359 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9360 return false; 9361 9362 if (Cand1CPUDisp && !Cand2CPUDisp) 9363 return true; 9364 if (Cand2CPUDisp && !Cand1CPUDisp) 9365 return false; 9366 9367 if (Cand1CPUSpec && Cand2CPUSpec) { 9368 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9369 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9370 9371 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9372 FirstDiff = std::mismatch( 9373 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9374 Cand2CPUSpec->cpus_begin(), 9375 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9376 return LHS->getName() == RHS->getName(); 9377 }); 9378 9379 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9380 "Two different cpu-specific versions should not have the same " 9381 "identifier list, otherwise they'd be the same decl!"); 9382 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9383 } 9384 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9385 } 9386 9387 /// isBetterOverloadCandidate - Determines whether the first overload 9388 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9389 bool clang::isBetterOverloadCandidate( 9390 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9391 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9392 // Define viable functions to be better candidates than non-viable 9393 // functions. 9394 if (!Cand2.Viable) 9395 return Cand1.Viable; 9396 else if (!Cand1.Viable) 9397 return false; 9398 9399 // C++ [over.match.best]p1: 9400 // 9401 // -- if F is a static member function, ICS1(F) is defined such 9402 // that ICS1(F) is neither better nor worse than ICS1(G) for 9403 // any function G, and, symmetrically, ICS1(G) is neither 9404 // better nor worse than ICS1(F). 9405 unsigned StartArg = 0; 9406 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9407 StartArg = 1; 9408 9409 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9410 // We don't allow incompatible pointer conversions in C++. 9411 if (!S.getLangOpts().CPlusPlus) 9412 return ICS.isStandard() && 9413 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9414 9415 // The only ill-formed conversion we allow in C++ is the string literal to 9416 // char* conversion, which is only considered ill-formed after C++11. 9417 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9418 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9419 }; 9420 9421 // Define functions that don't require ill-formed conversions for a given 9422 // argument to be better candidates than functions that do. 9423 unsigned NumArgs = Cand1.Conversions.size(); 9424 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9425 bool HasBetterConversion = false; 9426 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9427 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9428 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9429 if (Cand1Bad != Cand2Bad) { 9430 if (Cand1Bad) 9431 return false; 9432 HasBetterConversion = true; 9433 } 9434 } 9435 9436 if (HasBetterConversion) 9437 return true; 9438 9439 // C++ [over.match.best]p1: 9440 // A viable function F1 is defined to be a better function than another 9441 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9442 // conversion sequence than ICSi(F2), and then... 9443 bool HasWorseConversion = false; 9444 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9445 switch (CompareImplicitConversionSequences(S, Loc, 9446 Cand1.Conversions[ArgIdx], 9447 Cand2.Conversions[ArgIdx])) { 9448 case ImplicitConversionSequence::Better: 9449 // Cand1 has a better conversion sequence. 9450 HasBetterConversion = true; 9451 break; 9452 9453 case ImplicitConversionSequence::Worse: 9454 if (Cand1.Function && Cand1.Function == Cand2.Function && 9455 (Cand2.RewriteKind & CRK_Reversed) != 0) { 9456 // Work around large-scale breakage caused by considering reversed 9457 // forms of operator== in C++20: 9458 // 9459 // When comparing a function against its reversed form, if we have a 9460 // better conversion for one argument and a worse conversion for the 9461 // other, we prefer the non-reversed form. 9462 // 9463 // This prevents a conversion function from being considered ambiguous 9464 // with its own reversed form in various where it's only incidentally 9465 // heterogeneous. 9466 // 9467 // We diagnose this as an extension from CreateOverloadedBinOp. 9468 HasWorseConversion = true; 9469 break; 9470 } 9471 9472 // Cand1 can't be better than Cand2. 9473 return false; 9474 9475 case ImplicitConversionSequence::Indistinguishable: 9476 // Do nothing. 9477 break; 9478 } 9479 } 9480 9481 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9482 // ICSj(F2), or, if not that, 9483 if (HasBetterConversion) 9484 return true; 9485 if (HasWorseConversion) 9486 return false; 9487 9488 // -- the context is an initialization by user-defined conversion 9489 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9490 // from the return type of F1 to the destination type (i.e., 9491 // the type of the entity being initialized) is a better 9492 // conversion sequence than the standard conversion sequence 9493 // from the return type of F2 to the destination type. 9494 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9495 Cand1.Function && Cand2.Function && 9496 isa<CXXConversionDecl>(Cand1.Function) && 9497 isa<CXXConversionDecl>(Cand2.Function)) { 9498 // First check whether we prefer one of the conversion functions over the 9499 // other. This only distinguishes the results in non-standard, extension 9500 // cases such as the conversion from a lambda closure type to a function 9501 // pointer or block. 9502 ImplicitConversionSequence::CompareKind Result = 9503 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9504 if (Result == ImplicitConversionSequence::Indistinguishable) 9505 Result = CompareStandardConversionSequences(S, Loc, 9506 Cand1.FinalConversion, 9507 Cand2.FinalConversion); 9508 9509 if (Result != ImplicitConversionSequence::Indistinguishable) 9510 return Result == ImplicitConversionSequence::Better; 9511 9512 // FIXME: Compare kind of reference binding if conversion functions 9513 // convert to a reference type used in direct reference binding, per 9514 // C++14 [over.match.best]p1 section 2 bullet 3. 9515 } 9516 9517 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9518 // as combined with the resolution to CWG issue 243. 9519 // 9520 // When the context is initialization by constructor ([over.match.ctor] or 9521 // either phase of [over.match.list]), a constructor is preferred over 9522 // a conversion function. 9523 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9524 Cand1.Function && Cand2.Function && 9525 isa<CXXConstructorDecl>(Cand1.Function) != 9526 isa<CXXConstructorDecl>(Cand2.Function)) 9527 return isa<CXXConstructorDecl>(Cand1.Function); 9528 9529 // -- F1 is a non-template function and F2 is a function template 9530 // specialization, or, if not that, 9531 bool Cand1IsSpecialization = Cand1.Function && 9532 Cand1.Function->getPrimaryTemplate(); 9533 bool Cand2IsSpecialization = Cand2.Function && 9534 Cand2.Function->getPrimaryTemplate(); 9535 if (Cand1IsSpecialization != Cand2IsSpecialization) 9536 return Cand2IsSpecialization; 9537 9538 // -- F1 and F2 are function template specializations, and the function 9539 // template for F1 is more specialized than the template for F2 9540 // according to the partial ordering rules described in 14.5.5.2, or, 9541 // if not that, 9542 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9543 if (FunctionTemplateDecl *BetterTemplate 9544 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9545 Cand2.Function->getPrimaryTemplate(), 9546 Loc, 9547 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9548 : TPOC_Call, 9549 Cand1.ExplicitCallArguments, 9550 Cand2.ExplicitCallArguments)) 9551 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9552 } 9553 9554 // -— F1 and F2 are non-template functions with the same 9555 // parameter-type-lists, and F1 is more constrained than F2 [...], 9556 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9557 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9558 Cand2.Function->hasPrototype()) { 9559 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9560 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9561 if (PT1->getNumParams() == PT2->getNumParams() && 9562 PT1->isVariadic() == PT2->isVariadic() && 9563 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9564 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9565 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9566 if (RC1 && RC2) { 9567 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9568 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9569 {RC2}, AtLeastAsConstrained1)) 9570 return false; 9571 if (!AtLeastAsConstrained1) 9572 return false; 9573 if (S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9574 {RC1}, AtLeastAsConstrained2)) 9575 return false; 9576 if (!AtLeastAsConstrained2) 9577 return true; 9578 } else if (RC1 || RC2) 9579 return RC1 != nullptr; 9580 } 9581 } 9582 9583 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9584 // class B of D, and for all arguments the corresponding parameters of 9585 // F1 and F2 have the same type. 9586 // FIXME: Implement the "all parameters have the same type" check. 9587 bool Cand1IsInherited = 9588 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9589 bool Cand2IsInherited = 9590 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9591 if (Cand1IsInherited != Cand2IsInherited) 9592 return Cand2IsInherited; 9593 else if (Cand1IsInherited) { 9594 assert(Cand2IsInherited); 9595 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9596 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9597 if (Cand1Class->isDerivedFrom(Cand2Class)) 9598 return true; 9599 if (Cand2Class->isDerivedFrom(Cand1Class)) 9600 return false; 9601 // Inherited from sibling base classes: still ambiguous. 9602 } 9603 9604 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9605 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9606 // with reversed order of parameters and F1 is not 9607 // 9608 // We rank reversed + different operator as worse than just reversed, but 9609 // that comparison can never happen, because we only consider reversing for 9610 // the maximally-rewritten operator (== or <=>). 9611 if (Cand1.RewriteKind != Cand2.RewriteKind) 9612 return Cand1.RewriteKind < Cand2.RewriteKind; 9613 9614 // Check C++17 tie-breakers for deduction guides. 9615 { 9616 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9617 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9618 if (Guide1 && Guide2) { 9619 // -- F1 is generated from a deduction-guide and F2 is not 9620 if (Guide1->isImplicit() != Guide2->isImplicit()) 9621 return Guide2->isImplicit(); 9622 9623 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9624 if (Guide1->isCopyDeductionCandidate()) 9625 return true; 9626 } 9627 } 9628 9629 // Check for enable_if value-based overload resolution. 9630 if (Cand1.Function && Cand2.Function) { 9631 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9632 if (Cmp != Comparison::Equal) 9633 return Cmp == Comparison::Better; 9634 } 9635 9636 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9637 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9638 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9639 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9640 } 9641 9642 bool HasPS1 = Cand1.Function != nullptr && 9643 functionHasPassObjectSizeParams(Cand1.Function); 9644 bool HasPS2 = Cand2.Function != nullptr && 9645 functionHasPassObjectSizeParams(Cand2.Function); 9646 if (HasPS1 != HasPS2 && HasPS1) 9647 return true; 9648 9649 return isBetterMultiversionCandidate(Cand1, Cand2); 9650 } 9651 9652 /// Determine whether two declarations are "equivalent" for the purposes of 9653 /// name lookup and overload resolution. This applies when the same internal/no 9654 /// linkage entity is defined by two modules (probably by textually including 9655 /// the same header). In such a case, we don't consider the declarations to 9656 /// declare the same entity, but we also don't want lookups with both 9657 /// declarations visible to be ambiguous in some cases (this happens when using 9658 /// a modularized libstdc++). 9659 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9660 const NamedDecl *B) { 9661 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9662 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9663 if (!VA || !VB) 9664 return false; 9665 9666 // The declarations must be declaring the same name as an internal linkage 9667 // entity in different modules. 9668 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9669 VB->getDeclContext()->getRedeclContext()) || 9670 getOwningModule(VA) == getOwningModule(VB) || 9671 VA->isExternallyVisible() || VB->isExternallyVisible()) 9672 return false; 9673 9674 // Check that the declarations appear to be equivalent. 9675 // 9676 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9677 // For constants and functions, we should check the initializer or body is 9678 // the same. For non-constant variables, we shouldn't allow it at all. 9679 if (Context.hasSameType(VA->getType(), VB->getType())) 9680 return true; 9681 9682 // Enum constants within unnamed enumerations will have different types, but 9683 // may still be similar enough to be interchangeable for our purposes. 9684 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9685 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9686 // Only handle anonymous enums. If the enumerations were named and 9687 // equivalent, they would have been merged to the same type. 9688 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9689 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9690 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9691 !Context.hasSameType(EnumA->getIntegerType(), 9692 EnumB->getIntegerType())) 9693 return false; 9694 // Allow this only if the value is the same for both enumerators. 9695 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9696 } 9697 } 9698 9699 // Nothing else is sufficiently similar. 9700 return false; 9701 } 9702 9703 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9704 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9705 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9706 9707 Module *M = getOwningModule(D); 9708 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9709 << !M << (M ? M->getFullModuleName() : ""); 9710 9711 for (auto *E : Equiv) { 9712 Module *M = getOwningModule(E); 9713 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9714 << !M << (M ? M->getFullModuleName() : ""); 9715 } 9716 } 9717 9718 /// Computes the best viable function (C++ 13.3.3) 9719 /// within an overload candidate set. 9720 /// 9721 /// \param Loc The location of the function name (or operator symbol) for 9722 /// which overload resolution occurs. 9723 /// 9724 /// \param Best If overload resolution was successful or found a deleted 9725 /// function, \p Best points to the candidate function found. 9726 /// 9727 /// \returns The result of overload resolution. 9728 OverloadingResult 9729 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9730 iterator &Best) { 9731 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9732 std::transform(begin(), end(), std::back_inserter(Candidates), 9733 [](OverloadCandidate &Cand) { return &Cand; }); 9734 9735 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9736 // are accepted by both clang and NVCC. However, during a particular 9737 // compilation mode only one call variant is viable. We need to 9738 // exclude non-viable overload candidates from consideration based 9739 // only on their host/device attributes. Specifically, if one 9740 // candidate call is WrongSide and the other is SameSide, we ignore 9741 // the WrongSide candidate. 9742 if (S.getLangOpts().CUDA) { 9743 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9744 bool ContainsSameSideCandidate = 9745 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9746 // Check viable function only. 9747 return Cand->Viable && Cand->Function && 9748 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9749 Sema::CFP_SameSide; 9750 }); 9751 if (ContainsSameSideCandidate) { 9752 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9753 // Check viable function only to avoid unnecessary data copying/moving. 9754 return Cand->Viable && Cand->Function && 9755 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9756 Sema::CFP_WrongSide; 9757 }; 9758 llvm::erase_if(Candidates, IsWrongSideCandidate); 9759 } 9760 } 9761 9762 // Find the best viable function. 9763 Best = end(); 9764 for (auto *Cand : Candidates) { 9765 Cand->Best = false; 9766 if (Cand->Viable) 9767 if (Best == end() || 9768 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9769 Best = Cand; 9770 } 9771 9772 // If we didn't find any viable functions, abort. 9773 if (Best == end()) 9774 return OR_No_Viable_Function; 9775 9776 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9777 9778 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 9779 PendingBest.push_back(&*Best); 9780 Best->Best = true; 9781 9782 // Make sure that this function is better than every other viable 9783 // function. If not, we have an ambiguity. 9784 while (!PendingBest.empty()) { 9785 auto *Curr = PendingBest.pop_back_val(); 9786 for (auto *Cand : Candidates) { 9787 if (Cand->Viable && !Cand->Best && 9788 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 9789 PendingBest.push_back(Cand); 9790 Cand->Best = true; 9791 9792 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 9793 Curr->Function)) 9794 EquivalentCands.push_back(Cand->Function); 9795 else 9796 Best = end(); 9797 } 9798 } 9799 } 9800 9801 // If we found more than one best candidate, this is ambiguous. 9802 if (Best == end()) 9803 return OR_Ambiguous; 9804 9805 // Best is the best viable function. 9806 if (Best->Function && Best->Function->isDeleted()) 9807 return OR_Deleted; 9808 9809 if (!EquivalentCands.empty()) 9810 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9811 EquivalentCands); 9812 9813 return OR_Success; 9814 } 9815 9816 namespace { 9817 9818 enum OverloadCandidateKind { 9819 oc_function, 9820 oc_method, 9821 oc_reversed_binary_operator, 9822 oc_constructor, 9823 oc_implicit_default_constructor, 9824 oc_implicit_copy_constructor, 9825 oc_implicit_move_constructor, 9826 oc_implicit_copy_assignment, 9827 oc_implicit_move_assignment, 9828 oc_implicit_equality_comparison, 9829 oc_inherited_constructor 9830 }; 9831 9832 enum OverloadCandidateSelect { 9833 ocs_non_template, 9834 ocs_template, 9835 ocs_described_template, 9836 }; 9837 9838 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9839 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9840 OverloadCandidateRewriteKind CRK, 9841 std::string &Description) { 9842 9843 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9844 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9845 isTemplate = true; 9846 Description = S.getTemplateArgumentBindingsText( 9847 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9848 } 9849 9850 OverloadCandidateSelect Select = [&]() { 9851 if (!Description.empty()) 9852 return ocs_described_template; 9853 return isTemplate ? ocs_template : ocs_non_template; 9854 }(); 9855 9856 OverloadCandidateKind Kind = [&]() { 9857 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 9858 return oc_implicit_equality_comparison; 9859 9860 if (CRK & CRK_Reversed) 9861 return oc_reversed_binary_operator; 9862 9863 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9864 if (!Ctor->isImplicit()) { 9865 if (isa<ConstructorUsingShadowDecl>(Found)) 9866 return oc_inherited_constructor; 9867 else 9868 return oc_constructor; 9869 } 9870 9871 if (Ctor->isDefaultConstructor()) 9872 return oc_implicit_default_constructor; 9873 9874 if (Ctor->isMoveConstructor()) 9875 return oc_implicit_move_constructor; 9876 9877 assert(Ctor->isCopyConstructor() && 9878 "unexpected sort of implicit constructor"); 9879 return oc_implicit_copy_constructor; 9880 } 9881 9882 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9883 // This actually gets spelled 'candidate function' for now, but 9884 // it doesn't hurt to split it out. 9885 if (!Meth->isImplicit()) 9886 return oc_method; 9887 9888 if (Meth->isMoveAssignmentOperator()) 9889 return oc_implicit_move_assignment; 9890 9891 if (Meth->isCopyAssignmentOperator()) 9892 return oc_implicit_copy_assignment; 9893 9894 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9895 return oc_method; 9896 } 9897 9898 return oc_function; 9899 }(); 9900 9901 return std::make_pair(Kind, Select); 9902 } 9903 9904 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9905 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9906 // set. 9907 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9908 S.Diag(FoundDecl->getLocation(), 9909 diag::note_ovl_candidate_inherited_constructor) 9910 << Shadow->getNominatedBaseClass(); 9911 } 9912 9913 } // end anonymous namespace 9914 9915 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9916 const FunctionDecl *FD) { 9917 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9918 bool AlwaysTrue; 9919 if (EnableIf->getCond()->isValueDependent() || 9920 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9921 return false; 9922 if (!AlwaysTrue) 9923 return false; 9924 } 9925 return true; 9926 } 9927 9928 /// Returns true if we can take the address of the function. 9929 /// 9930 /// \param Complain - If true, we'll emit a diagnostic 9931 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9932 /// we in overload resolution? 9933 /// \param Loc - The location of the statement we're complaining about. Ignored 9934 /// if we're not complaining, or if we're in overload resolution. 9935 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9936 bool Complain, 9937 bool InOverloadResolution, 9938 SourceLocation Loc) { 9939 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9940 if (Complain) { 9941 if (InOverloadResolution) 9942 S.Diag(FD->getBeginLoc(), 9943 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9944 else 9945 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9946 } 9947 return false; 9948 } 9949 9950 if (const Expr *RC = FD->getTrailingRequiresClause()) { 9951 ConstraintSatisfaction Satisfaction; 9952 if (S.CheckConstraintSatisfaction(RC, Satisfaction)) 9953 return false; 9954 if (!Satisfaction.IsSatisfied) { 9955 if (Complain) { 9956 if (InOverloadResolution) 9957 S.Diag(FD->getBeginLoc(), 9958 diag::note_ovl_candidate_unsatisfied_constraints); 9959 else 9960 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 9961 << FD; 9962 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 9963 } 9964 return false; 9965 } 9966 } 9967 9968 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9969 return P->hasAttr<PassObjectSizeAttr>(); 9970 }); 9971 if (I == FD->param_end()) 9972 return true; 9973 9974 if (Complain) { 9975 // Add one to ParamNo because it's user-facing 9976 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9977 if (InOverloadResolution) 9978 S.Diag(FD->getLocation(), 9979 diag::note_ovl_candidate_has_pass_object_size_params) 9980 << ParamNo; 9981 else 9982 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9983 << FD << ParamNo; 9984 } 9985 return false; 9986 } 9987 9988 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9989 const FunctionDecl *FD) { 9990 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9991 /*InOverloadResolution=*/true, 9992 /*Loc=*/SourceLocation()); 9993 } 9994 9995 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9996 bool Complain, 9997 SourceLocation Loc) { 9998 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9999 /*InOverloadResolution=*/false, 10000 Loc); 10001 } 10002 10003 // Notes the location of an overload candidate. 10004 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10005 OverloadCandidateRewriteKind RewriteKind, 10006 QualType DestType, bool TakingAddress) { 10007 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10008 return; 10009 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10010 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10011 return; 10012 10013 std::string FnDesc; 10014 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10015 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10016 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10017 << (unsigned)KSPair.first << (unsigned)KSPair.second 10018 << Fn << FnDesc; 10019 10020 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10021 Diag(Fn->getLocation(), PD); 10022 MaybeEmitInheritedConstructorNote(*this, Found); 10023 } 10024 10025 static void 10026 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10027 // Perhaps the ambiguity was caused by two atomic constraints that are 10028 // 'identical' but not equivalent: 10029 // 10030 // void foo() requires (sizeof(T) > 4) { } // #1 10031 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10032 // 10033 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10034 // #2 to subsume #1, but these constraint are not considered equivalent 10035 // according to the subsumption rules because they are not the same 10036 // source-level construct. This behavior is quite confusing and we should try 10037 // to help the user figure out what happened. 10038 10039 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10040 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10041 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10042 if (!I->Function) 10043 continue; 10044 SmallVector<const Expr *, 3> AC; 10045 if (auto *Template = I->Function->getPrimaryTemplate()) 10046 Template->getAssociatedConstraints(AC); 10047 else 10048 I->Function->getAssociatedConstraints(AC); 10049 if (AC.empty()) 10050 continue; 10051 if (FirstCand == nullptr) { 10052 FirstCand = I->Function; 10053 FirstAC = AC; 10054 } else if (SecondCand == nullptr) { 10055 SecondCand = I->Function; 10056 SecondAC = AC; 10057 } else { 10058 // We have more than one pair of constrained functions - this check is 10059 // expensive and we'd rather not try to diagnose it. 10060 return; 10061 } 10062 } 10063 if (!SecondCand) 10064 return; 10065 // The diagnostic can only happen if there are associated constraints on 10066 // both sides (there needs to be some identical atomic constraint). 10067 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10068 SecondCand, SecondAC)) 10069 // Just show the user one diagnostic, they'll probably figure it out 10070 // from here. 10071 return; 10072 } 10073 10074 // Notes the location of all overload candidates designated through 10075 // OverloadedExpr 10076 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10077 bool TakingAddress) { 10078 assert(OverloadedExpr->getType() == Context.OverloadTy); 10079 10080 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10081 OverloadExpr *OvlExpr = Ovl.Expression; 10082 10083 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10084 IEnd = OvlExpr->decls_end(); 10085 I != IEnd; ++I) { 10086 if (FunctionTemplateDecl *FunTmpl = 10087 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10088 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10089 TakingAddress); 10090 } else if (FunctionDecl *Fun 10091 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10092 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10093 } 10094 } 10095 } 10096 10097 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10098 /// "lead" diagnostic; it will be given two arguments, the source and 10099 /// target types of the conversion. 10100 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10101 Sema &S, 10102 SourceLocation CaretLoc, 10103 const PartialDiagnostic &PDiag) const { 10104 S.Diag(CaretLoc, PDiag) 10105 << Ambiguous.getFromType() << Ambiguous.getToType(); 10106 // FIXME: The note limiting machinery is borrowed from 10107 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 10108 // refactoring here. 10109 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10110 unsigned CandsShown = 0; 10111 AmbiguousConversionSequence::const_iterator I, E; 10112 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10113 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10114 break; 10115 ++CandsShown; 10116 S.NoteOverloadCandidate(I->first, I->second); 10117 } 10118 if (I != E) 10119 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10120 } 10121 10122 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10123 unsigned I, bool TakingCandidateAddress) { 10124 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10125 assert(Conv.isBad()); 10126 assert(Cand->Function && "for now, candidate must be a function"); 10127 FunctionDecl *Fn = Cand->Function; 10128 10129 // There's a conversion slot for the object argument if this is a 10130 // non-constructor method. Note that 'I' corresponds the 10131 // conversion-slot index. 10132 bool isObjectArgument = false; 10133 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10134 if (I == 0) 10135 isObjectArgument = true; 10136 else 10137 I--; 10138 } 10139 10140 std::string FnDesc; 10141 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10142 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10143 FnDesc); 10144 10145 Expr *FromExpr = Conv.Bad.FromExpr; 10146 QualType FromTy = Conv.Bad.getFromType(); 10147 QualType ToTy = Conv.Bad.getToType(); 10148 10149 if (FromTy == S.Context.OverloadTy) { 10150 assert(FromExpr && "overload set argument came from implicit argument?"); 10151 Expr *E = FromExpr->IgnoreParens(); 10152 if (isa<UnaryOperator>(E)) 10153 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10154 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10155 10156 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10157 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10158 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10159 << Name << I + 1; 10160 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10161 return; 10162 } 10163 10164 // Do some hand-waving analysis to see if the non-viability is due 10165 // to a qualifier mismatch. 10166 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10167 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10168 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10169 CToTy = RT->getPointeeType(); 10170 else { 10171 // TODO: detect and diagnose the full richness of const mismatches. 10172 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10173 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10174 CFromTy = FromPT->getPointeeType(); 10175 CToTy = ToPT->getPointeeType(); 10176 } 10177 } 10178 10179 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10180 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10181 Qualifiers FromQs = CFromTy.getQualifiers(); 10182 Qualifiers ToQs = CToTy.getQualifiers(); 10183 10184 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10185 if (isObjectArgument) 10186 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10187 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10188 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10189 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10190 else 10191 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10192 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10193 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10194 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10195 << ToTy->isReferenceType() << I + 1; 10196 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10197 return; 10198 } 10199 10200 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10201 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10202 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10203 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10204 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10205 << (unsigned)isObjectArgument << I + 1; 10206 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10207 return; 10208 } 10209 10210 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10211 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10212 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10213 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10214 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10215 << (unsigned)isObjectArgument << I + 1; 10216 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10217 return; 10218 } 10219 10220 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10221 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10222 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10223 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10224 << FromQs.hasUnaligned() << I + 1; 10225 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10226 return; 10227 } 10228 10229 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10230 assert(CVR && "unexpected qualifiers mismatch"); 10231 10232 if (isObjectArgument) { 10233 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10234 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10235 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10236 << (CVR - 1); 10237 } else { 10238 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10239 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10240 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10241 << (CVR - 1) << I + 1; 10242 } 10243 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10244 return; 10245 } 10246 10247 // Special diagnostic for failure to convert an initializer list, since 10248 // telling the user that it has type void is not useful. 10249 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10250 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10251 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10252 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10253 << ToTy << (unsigned)isObjectArgument << I + 1; 10254 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10255 return; 10256 } 10257 10258 // Diagnose references or pointers to incomplete types differently, 10259 // since it's far from impossible that the incompleteness triggered 10260 // the failure. 10261 QualType TempFromTy = FromTy.getNonReferenceType(); 10262 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10263 TempFromTy = PTy->getPointeeType(); 10264 if (TempFromTy->isIncompleteType()) { 10265 // Emit the generic diagnostic and, optionally, add the hints to it. 10266 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10267 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10268 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10269 << ToTy << (unsigned)isObjectArgument << I + 1 10270 << (unsigned)(Cand->Fix.Kind); 10271 10272 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10273 return; 10274 } 10275 10276 // Diagnose base -> derived pointer conversions. 10277 unsigned BaseToDerivedConversion = 0; 10278 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10279 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10280 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10281 FromPtrTy->getPointeeType()) && 10282 !FromPtrTy->getPointeeType()->isIncompleteType() && 10283 !ToPtrTy->getPointeeType()->isIncompleteType() && 10284 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10285 FromPtrTy->getPointeeType())) 10286 BaseToDerivedConversion = 1; 10287 } 10288 } else if (const ObjCObjectPointerType *FromPtrTy 10289 = FromTy->getAs<ObjCObjectPointerType>()) { 10290 if (const ObjCObjectPointerType *ToPtrTy 10291 = ToTy->getAs<ObjCObjectPointerType>()) 10292 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10293 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10294 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10295 FromPtrTy->getPointeeType()) && 10296 FromIface->isSuperClassOf(ToIface)) 10297 BaseToDerivedConversion = 2; 10298 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10299 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10300 !FromTy->isIncompleteType() && 10301 !ToRefTy->getPointeeType()->isIncompleteType() && 10302 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10303 BaseToDerivedConversion = 3; 10304 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 10305 ToTy.getNonReferenceType().getCanonicalType() == 10306 FromTy.getNonReferenceType().getCanonicalType()) { 10307 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10308 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10309 << (unsigned)isObjectArgument << I + 1 10310 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10311 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10312 return; 10313 } 10314 } 10315 10316 if (BaseToDerivedConversion) { 10317 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10318 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10319 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10320 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10321 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10322 return; 10323 } 10324 10325 if (isa<ObjCObjectPointerType>(CFromTy) && 10326 isa<PointerType>(CToTy)) { 10327 Qualifiers FromQs = CFromTy.getQualifiers(); 10328 Qualifiers ToQs = CToTy.getQualifiers(); 10329 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10330 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10331 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10332 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10333 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10334 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10335 return; 10336 } 10337 } 10338 10339 if (TakingCandidateAddress && 10340 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10341 return; 10342 10343 // Emit the generic diagnostic and, optionally, add the hints to it. 10344 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10345 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10346 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10347 << ToTy << (unsigned)isObjectArgument << I + 1 10348 << (unsigned)(Cand->Fix.Kind); 10349 10350 // If we can fix the conversion, suggest the FixIts. 10351 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10352 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10353 FDiag << *HI; 10354 S.Diag(Fn->getLocation(), FDiag); 10355 10356 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10357 } 10358 10359 /// Additional arity mismatch diagnosis specific to a function overload 10360 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10361 /// over a candidate in any candidate set. 10362 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10363 unsigned NumArgs) { 10364 FunctionDecl *Fn = Cand->Function; 10365 unsigned MinParams = Fn->getMinRequiredArguments(); 10366 10367 // With invalid overloaded operators, it's possible that we think we 10368 // have an arity mismatch when in fact it looks like we have the 10369 // right number of arguments, because only overloaded operators have 10370 // the weird behavior of overloading member and non-member functions. 10371 // Just don't report anything. 10372 if (Fn->isInvalidDecl() && 10373 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10374 return true; 10375 10376 if (NumArgs < MinParams) { 10377 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10378 (Cand->FailureKind == ovl_fail_bad_deduction && 10379 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10380 } else { 10381 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10382 (Cand->FailureKind == ovl_fail_bad_deduction && 10383 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10384 } 10385 10386 return false; 10387 } 10388 10389 /// General arity mismatch diagnosis over a candidate in a candidate set. 10390 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10391 unsigned NumFormalArgs) { 10392 assert(isa<FunctionDecl>(D) && 10393 "The templated declaration should at least be a function" 10394 " when diagnosing bad template argument deduction due to too many" 10395 " or too few arguments"); 10396 10397 FunctionDecl *Fn = cast<FunctionDecl>(D); 10398 10399 // TODO: treat calls to a missing default constructor as a special case 10400 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10401 unsigned MinParams = Fn->getMinRequiredArguments(); 10402 10403 // at least / at most / exactly 10404 unsigned mode, modeCount; 10405 if (NumFormalArgs < MinParams) { 10406 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10407 FnTy->isTemplateVariadic()) 10408 mode = 0; // "at least" 10409 else 10410 mode = 2; // "exactly" 10411 modeCount = MinParams; 10412 } else { 10413 if (MinParams != FnTy->getNumParams()) 10414 mode = 1; // "at most" 10415 else 10416 mode = 2; // "exactly" 10417 modeCount = FnTy->getNumParams(); 10418 } 10419 10420 std::string Description; 10421 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10422 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10423 10424 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10425 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10426 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10427 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10428 else 10429 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10430 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10431 << Description << mode << modeCount << NumFormalArgs; 10432 10433 MaybeEmitInheritedConstructorNote(S, Found); 10434 } 10435 10436 /// Arity mismatch diagnosis specific to a function overload candidate. 10437 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10438 unsigned NumFormalArgs) { 10439 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10440 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10441 } 10442 10443 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10444 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10445 return TD; 10446 llvm_unreachable("Unsupported: Getting the described template declaration" 10447 " for bad deduction diagnosis"); 10448 } 10449 10450 /// Diagnose a failed template-argument deduction. 10451 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10452 DeductionFailureInfo &DeductionFailure, 10453 unsigned NumArgs, 10454 bool TakingCandidateAddress) { 10455 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10456 NamedDecl *ParamD; 10457 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10458 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10459 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10460 switch (DeductionFailure.Result) { 10461 case Sema::TDK_Success: 10462 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10463 10464 case Sema::TDK_Incomplete: { 10465 assert(ParamD && "no parameter found for incomplete deduction result"); 10466 S.Diag(Templated->getLocation(), 10467 diag::note_ovl_candidate_incomplete_deduction) 10468 << ParamD->getDeclName(); 10469 MaybeEmitInheritedConstructorNote(S, Found); 10470 return; 10471 } 10472 10473 case Sema::TDK_IncompletePack: { 10474 assert(ParamD && "no parameter found for incomplete deduction result"); 10475 S.Diag(Templated->getLocation(), 10476 diag::note_ovl_candidate_incomplete_deduction_pack) 10477 << ParamD->getDeclName() 10478 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10479 << *DeductionFailure.getFirstArg(); 10480 MaybeEmitInheritedConstructorNote(S, Found); 10481 return; 10482 } 10483 10484 case Sema::TDK_Underqualified: { 10485 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10486 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10487 10488 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10489 10490 // Param will have been canonicalized, but it should just be a 10491 // qualified version of ParamD, so move the qualifiers to that. 10492 QualifierCollector Qs; 10493 Qs.strip(Param); 10494 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10495 assert(S.Context.hasSameType(Param, NonCanonParam)); 10496 10497 // Arg has also been canonicalized, but there's nothing we can do 10498 // about that. It also doesn't matter as much, because it won't 10499 // have any template parameters in it (because deduction isn't 10500 // done on dependent types). 10501 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10502 10503 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10504 << ParamD->getDeclName() << Arg << NonCanonParam; 10505 MaybeEmitInheritedConstructorNote(S, Found); 10506 return; 10507 } 10508 10509 case Sema::TDK_Inconsistent: { 10510 assert(ParamD && "no parameter found for inconsistent deduction result"); 10511 int which = 0; 10512 if (isa<TemplateTypeParmDecl>(ParamD)) 10513 which = 0; 10514 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10515 // Deduction might have failed because we deduced arguments of two 10516 // different types for a non-type template parameter. 10517 // FIXME: Use a different TDK value for this. 10518 QualType T1 = 10519 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10520 QualType T2 = 10521 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10522 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10523 S.Diag(Templated->getLocation(), 10524 diag::note_ovl_candidate_inconsistent_deduction_types) 10525 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10526 << *DeductionFailure.getSecondArg() << T2; 10527 MaybeEmitInheritedConstructorNote(S, Found); 10528 return; 10529 } 10530 10531 which = 1; 10532 } else { 10533 which = 2; 10534 } 10535 10536 // Tweak the diagnostic if the problem is that we deduced packs of 10537 // different arities. We'll print the actual packs anyway in case that 10538 // includes additional useful information. 10539 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10540 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10541 DeductionFailure.getFirstArg()->pack_size() != 10542 DeductionFailure.getSecondArg()->pack_size()) { 10543 which = 3; 10544 } 10545 10546 S.Diag(Templated->getLocation(), 10547 diag::note_ovl_candidate_inconsistent_deduction) 10548 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10549 << *DeductionFailure.getSecondArg(); 10550 MaybeEmitInheritedConstructorNote(S, Found); 10551 return; 10552 } 10553 10554 case Sema::TDK_InvalidExplicitArguments: 10555 assert(ParamD && "no parameter found for invalid explicit arguments"); 10556 if (ParamD->getDeclName()) 10557 S.Diag(Templated->getLocation(), 10558 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10559 << ParamD->getDeclName(); 10560 else { 10561 int index = 0; 10562 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10563 index = TTP->getIndex(); 10564 else if (NonTypeTemplateParmDecl *NTTP 10565 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10566 index = NTTP->getIndex(); 10567 else 10568 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10569 S.Diag(Templated->getLocation(), 10570 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10571 << (index + 1); 10572 } 10573 MaybeEmitInheritedConstructorNote(S, Found); 10574 return; 10575 10576 case Sema::TDK_ConstraintsNotSatisfied: { 10577 // Format the template argument list into the argument string. 10578 SmallString<128> TemplateArgString; 10579 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10580 TemplateArgString = " "; 10581 TemplateArgString += S.getTemplateArgumentBindingsText( 10582 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10583 if (TemplateArgString.size() == 1) 10584 TemplateArgString.clear(); 10585 S.Diag(Templated->getLocation(), 10586 diag::note_ovl_candidate_unsatisfied_constraints) 10587 << TemplateArgString; 10588 10589 S.DiagnoseUnsatisfiedConstraint( 10590 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10591 return; 10592 } 10593 case Sema::TDK_TooManyArguments: 10594 case Sema::TDK_TooFewArguments: 10595 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10596 return; 10597 10598 case Sema::TDK_InstantiationDepth: 10599 S.Diag(Templated->getLocation(), 10600 diag::note_ovl_candidate_instantiation_depth); 10601 MaybeEmitInheritedConstructorNote(S, Found); 10602 return; 10603 10604 case Sema::TDK_SubstitutionFailure: { 10605 // Format the template argument list into the argument string. 10606 SmallString<128> TemplateArgString; 10607 if (TemplateArgumentList *Args = 10608 DeductionFailure.getTemplateArgumentList()) { 10609 TemplateArgString = " "; 10610 TemplateArgString += S.getTemplateArgumentBindingsText( 10611 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10612 if (TemplateArgString.size() == 1) 10613 TemplateArgString.clear(); 10614 } 10615 10616 // If this candidate was disabled by enable_if, say so. 10617 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10618 if (PDiag && PDiag->second.getDiagID() == 10619 diag::err_typename_nested_not_found_enable_if) { 10620 // FIXME: Use the source range of the condition, and the fully-qualified 10621 // name of the enable_if template. These are both present in PDiag. 10622 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10623 << "'enable_if'" << TemplateArgString; 10624 return; 10625 } 10626 10627 // We found a specific requirement that disabled the enable_if. 10628 if (PDiag && PDiag->second.getDiagID() == 10629 diag::err_typename_nested_not_found_requirement) { 10630 S.Diag(Templated->getLocation(), 10631 diag::note_ovl_candidate_disabled_by_requirement) 10632 << PDiag->second.getStringArg(0) << TemplateArgString; 10633 return; 10634 } 10635 10636 // Format the SFINAE diagnostic into the argument string. 10637 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10638 // formatted message in another diagnostic. 10639 SmallString<128> SFINAEArgString; 10640 SourceRange R; 10641 if (PDiag) { 10642 SFINAEArgString = ": "; 10643 R = SourceRange(PDiag->first, PDiag->first); 10644 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10645 } 10646 10647 S.Diag(Templated->getLocation(), 10648 diag::note_ovl_candidate_substitution_failure) 10649 << TemplateArgString << SFINAEArgString << R; 10650 MaybeEmitInheritedConstructorNote(S, Found); 10651 return; 10652 } 10653 10654 case Sema::TDK_DeducedMismatch: 10655 case Sema::TDK_DeducedMismatchNested: { 10656 // Format the template argument list into the argument string. 10657 SmallString<128> TemplateArgString; 10658 if (TemplateArgumentList *Args = 10659 DeductionFailure.getTemplateArgumentList()) { 10660 TemplateArgString = " "; 10661 TemplateArgString += S.getTemplateArgumentBindingsText( 10662 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10663 if (TemplateArgString.size() == 1) 10664 TemplateArgString.clear(); 10665 } 10666 10667 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10668 << (*DeductionFailure.getCallArgIndex() + 1) 10669 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10670 << TemplateArgString 10671 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10672 break; 10673 } 10674 10675 case Sema::TDK_NonDeducedMismatch: { 10676 // FIXME: Provide a source location to indicate what we couldn't match. 10677 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10678 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10679 if (FirstTA.getKind() == TemplateArgument::Template && 10680 SecondTA.getKind() == TemplateArgument::Template) { 10681 TemplateName FirstTN = FirstTA.getAsTemplate(); 10682 TemplateName SecondTN = SecondTA.getAsTemplate(); 10683 if (FirstTN.getKind() == TemplateName::Template && 10684 SecondTN.getKind() == TemplateName::Template) { 10685 if (FirstTN.getAsTemplateDecl()->getName() == 10686 SecondTN.getAsTemplateDecl()->getName()) { 10687 // FIXME: This fixes a bad diagnostic where both templates are named 10688 // the same. This particular case is a bit difficult since: 10689 // 1) It is passed as a string to the diagnostic printer. 10690 // 2) The diagnostic printer only attempts to find a better 10691 // name for types, not decls. 10692 // Ideally, this should folded into the diagnostic printer. 10693 S.Diag(Templated->getLocation(), 10694 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10695 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10696 return; 10697 } 10698 } 10699 } 10700 10701 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10702 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10703 return; 10704 10705 // FIXME: For generic lambda parameters, check if the function is a lambda 10706 // call operator, and if so, emit a prettier and more informative 10707 // diagnostic that mentions 'auto' and lambda in addition to 10708 // (or instead of?) the canonical template type parameters. 10709 S.Diag(Templated->getLocation(), 10710 diag::note_ovl_candidate_non_deduced_mismatch) 10711 << FirstTA << SecondTA; 10712 return; 10713 } 10714 // TODO: diagnose these individually, then kill off 10715 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10716 case Sema::TDK_MiscellaneousDeductionFailure: 10717 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10718 MaybeEmitInheritedConstructorNote(S, Found); 10719 return; 10720 case Sema::TDK_CUDATargetMismatch: 10721 S.Diag(Templated->getLocation(), 10722 diag::note_cuda_ovl_candidate_target_mismatch); 10723 return; 10724 } 10725 } 10726 10727 /// Diagnose a failed template-argument deduction, for function calls. 10728 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10729 unsigned NumArgs, 10730 bool TakingCandidateAddress) { 10731 unsigned TDK = Cand->DeductionFailure.Result; 10732 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10733 if (CheckArityMismatch(S, Cand, NumArgs)) 10734 return; 10735 } 10736 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10737 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10738 } 10739 10740 /// CUDA: diagnose an invalid call across targets. 10741 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10742 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10743 FunctionDecl *Callee = Cand->Function; 10744 10745 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10746 CalleeTarget = S.IdentifyCUDATarget(Callee); 10747 10748 std::string FnDesc; 10749 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10750 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 10751 Cand->getRewriteKind(), FnDesc); 10752 10753 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10754 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10755 << FnDesc /* Ignored */ 10756 << CalleeTarget << CallerTarget; 10757 10758 // This could be an implicit constructor for which we could not infer the 10759 // target due to a collsion. Diagnose that case. 10760 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10761 if (Meth != nullptr && Meth->isImplicit()) { 10762 CXXRecordDecl *ParentClass = Meth->getParent(); 10763 Sema::CXXSpecialMember CSM; 10764 10765 switch (FnKindPair.first) { 10766 default: 10767 return; 10768 case oc_implicit_default_constructor: 10769 CSM = Sema::CXXDefaultConstructor; 10770 break; 10771 case oc_implicit_copy_constructor: 10772 CSM = Sema::CXXCopyConstructor; 10773 break; 10774 case oc_implicit_move_constructor: 10775 CSM = Sema::CXXMoveConstructor; 10776 break; 10777 case oc_implicit_copy_assignment: 10778 CSM = Sema::CXXCopyAssignment; 10779 break; 10780 case oc_implicit_move_assignment: 10781 CSM = Sema::CXXMoveAssignment; 10782 break; 10783 }; 10784 10785 bool ConstRHS = false; 10786 if (Meth->getNumParams()) { 10787 if (const ReferenceType *RT = 10788 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10789 ConstRHS = RT->getPointeeType().isConstQualified(); 10790 } 10791 } 10792 10793 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10794 /* ConstRHS */ ConstRHS, 10795 /* Diagnose */ true); 10796 } 10797 } 10798 10799 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10800 FunctionDecl *Callee = Cand->Function; 10801 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10802 10803 S.Diag(Callee->getLocation(), 10804 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10805 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10806 } 10807 10808 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10809 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 10810 assert(ES.isExplicit() && "not an explicit candidate"); 10811 10812 unsigned Kind; 10813 switch (Cand->Function->getDeclKind()) { 10814 case Decl::Kind::CXXConstructor: 10815 Kind = 0; 10816 break; 10817 case Decl::Kind::CXXConversion: 10818 Kind = 1; 10819 break; 10820 case Decl::Kind::CXXDeductionGuide: 10821 Kind = Cand->Function->isImplicit() ? 0 : 2; 10822 break; 10823 default: 10824 llvm_unreachable("invalid Decl"); 10825 } 10826 10827 // Note the location of the first (in-class) declaration; a redeclaration 10828 // (particularly an out-of-class definition) will typically lack the 10829 // 'explicit' specifier. 10830 // FIXME: This is probably a good thing to do for all 'candidate' notes. 10831 FunctionDecl *First = Cand->Function->getFirstDecl(); 10832 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 10833 First = Pattern->getFirstDecl(); 10834 10835 S.Diag(First->getLocation(), 10836 diag::note_ovl_candidate_explicit) 10837 << Kind << (ES.getExpr() ? 1 : 0) 10838 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 10839 } 10840 10841 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10842 FunctionDecl *Callee = Cand->Function; 10843 10844 S.Diag(Callee->getLocation(), 10845 diag::note_ovl_candidate_disabled_by_extension) 10846 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10847 } 10848 10849 /// Generates a 'note' diagnostic for an overload candidate. We've 10850 /// already generated a primary error at the call site. 10851 /// 10852 /// It really does need to be a single diagnostic with its caret 10853 /// pointed at the candidate declaration. Yes, this creates some 10854 /// major challenges of technical writing. Yes, this makes pointing 10855 /// out problems with specific arguments quite awkward. It's still 10856 /// better than generating twenty screens of text for every failed 10857 /// overload. 10858 /// 10859 /// It would be great to be able to express per-candidate problems 10860 /// more richly for those diagnostic clients that cared, but we'd 10861 /// still have to be just as careful with the default diagnostics. 10862 /// \param CtorDestAS Addr space of object being constructed (for ctor 10863 /// candidates only). 10864 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10865 unsigned NumArgs, 10866 bool TakingCandidateAddress, 10867 LangAS CtorDestAS = LangAS::Default) { 10868 FunctionDecl *Fn = Cand->Function; 10869 10870 // Note deleted candidates, but only if they're viable. 10871 if (Cand->Viable) { 10872 if (Fn->isDeleted()) { 10873 std::string FnDesc; 10874 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10875 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 10876 Cand->getRewriteKind(), FnDesc); 10877 10878 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10879 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10880 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10881 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10882 return; 10883 } 10884 10885 // We don't really have anything else to say about viable candidates. 10886 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10887 return; 10888 } 10889 10890 switch (Cand->FailureKind) { 10891 case ovl_fail_too_many_arguments: 10892 case ovl_fail_too_few_arguments: 10893 return DiagnoseArityMismatch(S, Cand, NumArgs); 10894 10895 case ovl_fail_bad_deduction: 10896 return DiagnoseBadDeduction(S, Cand, NumArgs, 10897 TakingCandidateAddress); 10898 10899 case ovl_fail_illegal_constructor: { 10900 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10901 << (Fn->getPrimaryTemplate() ? 1 : 0); 10902 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10903 return; 10904 } 10905 10906 case ovl_fail_object_addrspace_mismatch: { 10907 Qualifiers QualsForPrinting; 10908 QualsForPrinting.setAddressSpace(CtorDestAS); 10909 S.Diag(Fn->getLocation(), 10910 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 10911 << QualsForPrinting; 10912 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10913 return; 10914 } 10915 10916 case ovl_fail_trivial_conversion: 10917 case ovl_fail_bad_final_conversion: 10918 case ovl_fail_final_conversion_not_exact: 10919 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10920 10921 case ovl_fail_bad_conversion: { 10922 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10923 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10924 if (Cand->Conversions[I].isBad()) 10925 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10926 10927 // FIXME: this currently happens when we're called from SemaInit 10928 // when user-conversion overload fails. Figure out how to handle 10929 // those conditions and diagnose them well. 10930 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10931 } 10932 10933 case ovl_fail_bad_target: 10934 return DiagnoseBadTarget(S, Cand); 10935 10936 case ovl_fail_enable_if: 10937 return DiagnoseFailedEnableIfAttr(S, Cand); 10938 10939 case ovl_fail_explicit: 10940 return DiagnoseFailedExplicitSpec(S, Cand); 10941 10942 case ovl_fail_ext_disabled: 10943 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10944 10945 case ovl_fail_inhctor_slice: 10946 // It's generally not interesting to note copy/move constructors here. 10947 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10948 return; 10949 S.Diag(Fn->getLocation(), 10950 diag::note_ovl_candidate_inherited_constructor_slice) 10951 << (Fn->getPrimaryTemplate() ? 1 : 0) 10952 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10953 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10954 return; 10955 10956 case ovl_fail_addr_not_available: { 10957 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10958 (void)Available; 10959 assert(!Available); 10960 break; 10961 } 10962 case ovl_non_default_multiversion_function: 10963 // Do nothing, these should simply be ignored. 10964 break; 10965 10966 case ovl_fail_constraints_not_satisfied: { 10967 std::string FnDesc; 10968 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10969 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 10970 Cand->getRewriteKind(), FnDesc); 10971 10972 S.Diag(Fn->getLocation(), 10973 diag::note_ovl_candidate_constraints_not_satisfied) 10974 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10975 << FnDesc /* Ignored */; 10976 ConstraintSatisfaction Satisfaction; 10977 if (S.CheckConstraintSatisfaction(Fn->getTrailingRequiresClause(), 10978 Satisfaction)) 10979 break; 10980 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10981 } 10982 } 10983 } 10984 10985 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10986 // Desugar the type of the surrogate down to a function type, 10987 // retaining as many typedefs as possible while still showing 10988 // the function type (and, therefore, its parameter types). 10989 QualType FnType = Cand->Surrogate->getConversionType(); 10990 bool isLValueReference = false; 10991 bool isRValueReference = false; 10992 bool isPointer = false; 10993 if (const LValueReferenceType *FnTypeRef = 10994 FnType->getAs<LValueReferenceType>()) { 10995 FnType = FnTypeRef->getPointeeType(); 10996 isLValueReference = true; 10997 } else if (const RValueReferenceType *FnTypeRef = 10998 FnType->getAs<RValueReferenceType>()) { 10999 FnType = FnTypeRef->getPointeeType(); 11000 isRValueReference = true; 11001 } 11002 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11003 FnType = FnTypePtr->getPointeeType(); 11004 isPointer = true; 11005 } 11006 // Desugar down to a function type. 11007 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11008 // Reconstruct the pointer/reference as appropriate. 11009 if (isPointer) FnType = S.Context.getPointerType(FnType); 11010 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11011 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11012 11013 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11014 << FnType; 11015 } 11016 11017 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11018 SourceLocation OpLoc, 11019 OverloadCandidate *Cand) { 11020 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11021 std::string TypeStr("operator"); 11022 TypeStr += Opc; 11023 TypeStr += "("; 11024 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11025 if (Cand->Conversions.size() == 1) { 11026 TypeStr += ")"; 11027 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11028 } else { 11029 TypeStr += ", "; 11030 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11031 TypeStr += ")"; 11032 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11033 } 11034 } 11035 11036 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11037 OverloadCandidate *Cand) { 11038 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11039 if (ICS.isBad()) break; // all meaningless after first invalid 11040 if (!ICS.isAmbiguous()) continue; 11041 11042 ICS.DiagnoseAmbiguousConversion( 11043 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11044 } 11045 } 11046 11047 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11048 if (Cand->Function) 11049 return Cand->Function->getLocation(); 11050 if (Cand->IsSurrogate) 11051 return Cand->Surrogate->getLocation(); 11052 return SourceLocation(); 11053 } 11054 11055 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11056 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11057 case Sema::TDK_Success: 11058 case Sema::TDK_NonDependentConversionFailure: 11059 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11060 11061 case Sema::TDK_Invalid: 11062 case Sema::TDK_Incomplete: 11063 case Sema::TDK_IncompletePack: 11064 return 1; 11065 11066 case Sema::TDK_Underqualified: 11067 case Sema::TDK_Inconsistent: 11068 return 2; 11069 11070 case Sema::TDK_SubstitutionFailure: 11071 case Sema::TDK_DeducedMismatch: 11072 case Sema::TDK_ConstraintsNotSatisfied: 11073 case Sema::TDK_DeducedMismatchNested: 11074 case Sema::TDK_NonDeducedMismatch: 11075 case Sema::TDK_MiscellaneousDeductionFailure: 11076 case Sema::TDK_CUDATargetMismatch: 11077 return 3; 11078 11079 case Sema::TDK_InstantiationDepth: 11080 return 4; 11081 11082 case Sema::TDK_InvalidExplicitArguments: 11083 return 5; 11084 11085 case Sema::TDK_TooManyArguments: 11086 case Sema::TDK_TooFewArguments: 11087 return 6; 11088 } 11089 llvm_unreachable("Unhandled deduction result"); 11090 } 11091 11092 namespace { 11093 struct CompareOverloadCandidatesForDisplay { 11094 Sema &S; 11095 SourceLocation Loc; 11096 size_t NumArgs; 11097 OverloadCandidateSet::CandidateSetKind CSK; 11098 11099 CompareOverloadCandidatesForDisplay( 11100 Sema &S, SourceLocation Loc, size_t NArgs, 11101 OverloadCandidateSet::CandidateSetKind CSK) 11102 : S(S), NumArgs(NArgs), CSK(CSK) {} 11103 11104 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11105 // If there are too many or too few arguments, that's the high-order bit we 11106 // want to sort by, even if the immediate failure kind was something else. 11107 if (C->FailureKind == ovl_fail_too_many_arguments || 11108 C->FailureKind == ovl_fail_too_few_arguments) 11109 return static_cast<OverloadFailureKind>(C->FailureKind); 11110 11111 if (C->Function) { 11112 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11113 return ovl_fail_too_many_arguments; 11114 if (NumArgs < C->Function->getMinRequiredArguments()) 11115 return ovl_fail_too_few_arguments; 11116 } 11117 11118 return static_cast<OverloadFailureKind>(C->FailureKind); 11119 } 11120 11121 bool operator()(const OverloadCandidate *L, 11122 const OverloadCandidate *R) { 11123 // Fast-path this check. 11124 if (L == R) return false; 11125 11126 // Order first by viability. 11127 if (L->Viable) { 11128 if (!R->Viable) return true; 11129 11130 // TODO: introduce a tri-valued comparison for overload 11131 // candidates. Would be more worthwhile if we had a sort 11132 // that could exploit it. 11133 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11134 return true; 11135 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11136 return false; 11137 } else if (R->Viable) 11138 return false; 11139 11140 assert(L->Viable == R->Viable); 11141 11142 // Criteria by which we can sort non-viable candidates: 11143 if (!L->Viable) { 11144 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11145 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11146 11147 // 1. Arity mismatches come after other candidates. 11148 if (LFailureKind == ovl_fail_too_many_arguments || 11149 LFailureKind == ovl_fail_too_few_arguments) { 11150 if (RFailureKind == ovl_fail_too_many_arguments || 11151 RFailureKind == ovl_fail_too_few_arguments) { 11152 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11153 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11154 if (LDist == RDist) { 11155 if (LFailureKind == RFailureKind) 11156 // Sort non-surrogates before surrogates. 11157 return !L->IsSurrogate && R->IsSurrogate; 11158 // Sort candidates requiring fewer parameters than there were 11159 // arguments given after candidates requiring more parameters 11160 // than there were arguments given. 11161 return LFailureKind == ovl_fail_too_many_arguments; 11162 } 11163 return LDist < RDist; 11164 } 11165 return false; 11166 } 11167 if (RFailureKind == ovl_fail_too_many_arguments || 11168 RFailureKind == ovl_fail_too_few_arguments) 11169 return true; 11170 11171 // 2. Bad conversions come first and are ordered by the number 11172 // of bad conversions and quality of good conversions. 11173 if (LFailureKind == ovl_fail_bad_conversion) { 11174 if (RFailureKind != ovl_fail_bad_conversion) 11175 return true; 11176 11177 // The conversion that can be fixed with a smaller number of changes, 11178 // comes first. 11179 unsigned numLFixes = L->Fix.NumConversionsFixed; 11180 unsigned numRFixes = R->Fix.NumConversionsFixed; 11181 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11182 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11183 if (numLFixes != numRFixes) { 11184 return numLFixes < numRFixes; 11185 } 11186 11187 // If there's any ordering between the defined conversions... 11188 // FIXME: this might not be transitive. 11189 assert(L->Conversions.size() == R->Conversions.size()); 11190 11191 int leftBetter = 0; 11192 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11193 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11194 switch (CompareImplicitConversionSequences(S, Loc, 11195 L->Conversions[I], 11196 R->Conversions[I])) { 11197 case ImplicitConversionSequence::Better: 11198 leftBetter++; 11199 break; 11200 11201 case ImplicitConversionSequence::Worse: 11202 leftBetter--; 11203 break; 11204 11205 case ImplicitConversionSequence::Indistinguishable: 11206 break; 11207 } 11208 } 11209 if (leftBetter > 0) return true; 11210 if (leftBetter < 0) return false; 11211 11212 } else if (RFailureKind == ovl_fail_bad_conversion) 11213 return false; 11214 11215 if (LFailureKind == ovl_fail_bad_deduction) { 11216 if (RFailureKind != ovl_fail_bad_deduction) 11217 return true; 11218 11219 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11220 return RankDeductionFailure(L->DeductionFailure) 11221 < RankDeductionFailure(R->DeductionFailure); 11222 } else if (RFailureKind == ovl_fail_bad_deduction) 11223 return false; 11224 11225 // TODO: others? 11226 } 11227 11228 // Sort everything else by location. 11229 SourceLocation LLoc = GetLocationForCandidate(L); 11230 SourceLocation RLoc = GetLocationForCandidate(R); 11231 11232 // Put candidates without locations (e.g. builtins) at the end. 11233 if (LLoc.isInvalid()) return false; 11234 if (RLoc.isInvalid()) return true; 11235 11236 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11237 } 11238 }; 11239 } 11240 11241 /// CompleteNonViableCandidate - Normally, overload resolution only 11242 /// computes up to the first bad conversion. Produces the FixIt set if 11243 /// possible. 11244 static void 11245 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11246 ArrayRef<Expr *> Args, 11247 OverloadCandidateSet::CandidateSetKind CSK) { 11248 assert(!Cand->Viable); 11249 11250 // Don't do anything on failures other than bad conversion. 11251 if (Cand->FailureKind != ovl_fail_bad_conversion) 11252 return; 11253 11254 // We only want the FixIts if all the arguments can be corrected. 11255 bool Unfixable = false; 11256 // Use a implicit copy initialization to check conversion fixes. 11257 Cand->Fix.setConversionChecker(TryCopyInitialization); 11258 11259 // Attempt to fix the bad conversion. 11260 unsigned ConvCount = Cand->Conversions.size(); 11261 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11262 ++ConvIdx) { 11263 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11264 if (Cand->Conversions[ConvIdx].isInitialized() && 11265 Cand->Conversions[ConvIdx].isBad()) { 11266 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11267 break; 11268 } 11269 } 11270 11271 // FIXME: this should probably be preserved from the overload 11272 // operation somehow. 11273 bool SuppressUserConversions = false; 11274 11275 unsigned ConvIdx = 0; 11276 unsigned ArgIdx = 0; 11277 ArrayRef<QualType> ParamTypes; 11278 bool Reversed = Cand->RewriteKind & CRK_Reversed; 11279 11280 if (Cand->IsSurrogate) { 11281 QualType ConvType 11282 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11283 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11284 ConvType = ConvPtrType->getPointeeType(); 11285 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11286 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11287 ConvIdx = 1; 11288 } else if (Cand->Function) { 11289 ParamTypes = 11290 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11291 if (isa<CXXMethodDecl>(Cand->Function) && 11292 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11293 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11294 ConvIdx = 1; 11295 if (CSK == OverloadCandidateSet::CSK_Operator && 11296 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11297 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11298 ArgIdx = 1; 11299 } 11300 } else { 11301 // Builtin operator. 11302 assert(ConvCount <= 3); 11303 ParamTypes = Cand->BuiltinParamTypes; 11304 } 11305 11306 // Fill in the rest of the conversions. 11307 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11308 ConvIdx != ConvCount; 11309 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11310 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11311 if (Cand->Conversions[ConvIdx].isInitialized()) { 11312 // We've already checked this conversion. 11313 } else if (ParamIdx < ParamTypes.size()) { 11314 if (ParamTypes[ParamIdx]->isDependentType()) 11315 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11316 Args[ArgIdx]->getType()); 11317 else { 11318 Cand->Conversions[ConvIdx] = 11319 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11320 SuppressUserConversions, 11321 /*InOverloadResolution=*/true, 11322 /*AllowObjCWritebackConversion=*/ 11323 S.getLangOpts().ObjCAutoRefCount); 11324 // Store the FixIt in the candidate if it exists. 11325 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11326 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11327 } 11328 } else 11329 Cand->Conversions[ConvIdx].setEllipsis(); 11330 } 11331 } 11332 11333 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11334 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11335 SourceLocation OpLoc, 11336 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11337 // Sort the candidates by viability and position. Sorting directly would 11338 // be prohibitive, so we make a set of pointers and sort those. 11339 SmallVector<OverloadCandidate*, 32> Cands; 11340 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11341 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11342 if (!Filter(*Cand)) 11343 continue; 11344 switch (OCD) { 11345 case OCD_AllCandidates: 11346 if (!Cand->Viable) { 11347 if (!Cand->Function && !Cand->IsSurrogate) { 11348 // This a non-viable builtin candidate. We do not, in general, 11349 // want to list every possible builtin candidate. 11350 continue; 11351 } 11352 CompleteNonViableCandidate(S, Cand, Args, Kind); 11353 } 11354 break; 11355 11356 case OCD_ViableCandidates: 11357 if (!Cand->Viable) 11358 continue; 11359 break; 11360 11361 case OCD_AmbiguousCandidates: 11362 if (!Cand->Best) 11363 continue; 11364 break; 11365 } 11366 11367 Cands.push_back(Cand); 11368 } 11369 11370 llvm::stable_sort( 11371 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11372 11373 return Cands; 11374 } 11375 11376 /// When overload resolution fails, prints diagnostic messages containing the 11377 /// candidates in the candidate set. 11378 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11379 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11380 StringRef Opc, SourceLocation OpLoc, 11381 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11382 11383 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11384 11385 S.Diag(PD.first, PD.second); 11386 11387 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11388 11389 if (OCD == OCD_AmbiguousCandidates) 11390 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11391 } 11392 11393 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11394 ArrayRef<OverloadCandidate *> Cands, 11395 StringRef Opc, SourceLocation OpLoc) { 11396 bool ReportedAmbiguousConversions = false; 11397 11398 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11399 unsigned CandsShown = 0; 11400 auto I = Cands.begin(), E = Cands.end(); 11401 for (; I != E; ++I) { 11402 OverloadCandidate *Cand = *I; 11403 11404 // Set an arbitrary limit on the number of candidate functions we'll spam 11405 // the user with. FIXME: This limit should depend on details of the 11406 // candidate list. 11407 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11408 break; 11409 } 11410 ++CandsShown; 11411 11412 if (Cand->Function) 11413 NoteFunctionCandidate(S, Cand, Args.size(), 11414 /*TakingCandidateAddress=*/false, DestAS); 11415 else if (Cand->IsSurrogate) 11416 NoteSurrogateCandidate(S, Cand); 11417 else { 11418 assert(Cand->Viable && 11419 "Non-viable built-in candidates are not added to Cands."); 11420 // Generally we only see ambiguities including viable builtin 11421 // operators if overload resolution got screwed up by an 11422 // ambiguous user-defined conversion. 11423 // 11424 // FIXME: It's quite possible for different conversions to see 11425 // different ambiguities, though. 11426 if (!ReportedAmbiguousConversions) { 11427 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11428 ReportedAmbiguousConversions = true; 11429 } 11430 11431 // If this is a viable builtin, print it. 11432 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11433 } 11434 } 11435 11436 if (I != E) 11437 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11438 } 11439 11440 static SourceLocation 11441 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11442 return Cand->Specialization ? Cand->Specialization->getLocation() 11443 : SourceLocation(); 11444 } 11445 11446 namespace { 11447 struct CompareTemplateSpecCandidatesForDisplay { 11448 Sema &S; 11449 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11450 11451 bool operator()(const TemplateSpecCandidate *L, 11452 const TemplateSpecCandidate *R) { 11453 // Fast-path this check. 11454 if (L == R) 11455 return false; 11456 11457 // Assuming that both candidates are not matches... 11458 11459 // Sort by the ranking of deduction failures. 11460 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11461 return RankDeductionFailure(L->DeductionFailure) < 11462 RankDeductionFailure(R->DeductionFailure); 11463 11464 // Sort everything else by location. 11465 SourceLocation LLoc = GetLocationForCandidate(L); 11466 SourceLocation RLoc = GetLocationForCandidate(R); 11467 11468 // Put candidates without locations (e.g. builtins) at the end. 11469 if (LLoc.isInvalid()) 11470 return false; 11471 if (RLoc.isInvalid()) 11472 return true; 11473 11474 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11475 } 11476 }; 11477 } 11478 11479 /// Diagnose a template argument deduction failure. 11480 /// We are treating these failures as overload failures due to bad 11481 /// deductions. 11482 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11483 bool ForTakingAddress) { 11484 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11485 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11486 } 11487 11488 void TemplateSpecCandidateSet::destroyCandidates() { 11489 for (iterator i = begin(), e = end(); i != e; ++i) { 11490 i->DeductionFailure.Destroy(); 11491 } 11492 } 11493 11494 void TemplateSpecCandidateSet::clear() { 11495 destroyCandidates(); 11496 Candidates.clear(); 11497 } 11498 11499 /// NoteCandidates - When no template specialization match is found, prints 11500 /// diagnostic messages containing the non-matching specializations that form 11501 /// the candidate set. 11502 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11503 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11504 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11505 // Sort the candidates by position (assuming no candidate is a match). 11506 // Sorting directly would be prohibitive, so we make a set of pointers 11507 // and sort those. 11508 SmallVector<TemplateSpecCandidate *, 32> Cands; 11509 Cands.reserve(size()); 11510 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11511 if (Cand->Specialization) 11512 Cands.push_back(Cand); 11513 // Otherwise, this is a non-matching builtin candidate. We do not, 11514 // in general, want to list every possible builtin candidate. 11515 } 11516 11517 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11518 11519 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11520 // for generalization purposes (?). 11521 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11522 11523 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11524 unsigned CandsShown = 0; 11525 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11526 TemplateSpecCandidate *Cand = *I; 11527 11528 // Set an arbitrary limit on the number of candidates we'll spam 11529 // the user with. FIXME: This limit should depend on details of the 11530 // candidate list. 11531 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11532 break; 11533 ++CandsShown; 11534 11535 assert(Cand->Specialization && 11536 "Non-matching built-in candidates are not added to Cands."); 11537 Cand->NoteDeductionFailure(S, ForTakingAddress); 11538 } 11539 11540 if (I != E) 11541 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11542 } 11543 11544 // [PossiblyAFunctionType] --> [Return] 11545 // NonFunctionType --> NonFunctionType 11546 // R (A) --> R(A) 11547 // R (*)(A) --> R (A) 11548 // R (&)(A) --> R (A) 11549 // R (S::*)(A) --> R (A) 11550 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11551 QualType Ret = PossiblyAFunctionType; 11552 if (const PointerType *ToTypePtr = 11553 PossiblyAFunctionType->getAs<PointerType>()) 11554 Ret = ToTypePtr->getPointeeType(); 11555 else if (const ReferenceType *ToTypeRef = 11556 PossiblyAFunctionType->getAs<ReferenceType>()) 11557 Ret = ToTypeRef->getPointeeType(); 11558 else if (const MemberPointerType *MemTypePtr = 11559 PossiblyAFunctionType->getAs<MemberPointerType>()) 11560 Ret = MemTypePtr->getPointeeType(); 11561 Ret = 11562 Context.getCanonicalType(Ret).getUnqualifiedType(); 11563 return Ret; 11564 } 11565 11566 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11567 bool Complain = true) { 11568 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11569 S.DeduceReturnType(FD, Loc, Complain)) 11570 return true; 11571 11572 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11573 if (S.getLangOpts().CPlusPlus17 && 11574 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11575 !S.ResolveExceptionSpec(Loc, FPT)) 11576 return true; 11577 11578 return false; 11579 } 11580 11581 namespace { 11582 // A helper class to help with address of function resolution 11583 // - allows us to avoid passing around all those ugly parameters 11584 class AddressOfFunctionResolver { 11585 Sema& S; 11586 Expr* SourceExpr; 11587 const QualType& TargetType; 11588 QualType TargetFunctionType; // Extracted function type from target type 11589 11590 bool Complain; 11591 //DeclAccessPair& ResultFunctionAccessPair; 11592 ASTContext& Context; 11593 11594 bool TargetTypeIsNonStaticMemberFunction; 11595 bool FoundNonTemplateFunction; 11596 bool StaticMemberFunctionFromBoundPointer; 11597 bool HasComplained; 11598 11599 OverloadExpr::FindResult OvlExprInfo; 11600 OverloadExpr *OvlExpr; 11601 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11602 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11603 TemplateSpecCandidateSet FailedCandidates; 11604 11605 public: 11606 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11607 const QualType &TargetType, bool Complain) 11608 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11609 Complain(Complain), Context(S.getASTContext()), 11610 TargetTypeIsNonStaticMemberFunction( 11611 !!TargetType->getAs<MemberPointerType>()), 11612 FoundNonTemplateFunction(false), 11613 StaticMemberFunctionFromBoundPointer(false), 11614 HasComplained(false), 11615 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11616 OvlExpr(OvlExprInfo.Expression), 11617 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11618 ExtractUnqualifiedFunctionTypeFromTargetType(); 11619 11620 if (TargetFunctionType->isFunctionType()) { 11621 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11622 if (!UME->isImplicitAccess() && 11623 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11624 StaticMemberFunctionFromBoundPointer = true; 11625 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11626 DeclAccessPair dap; 11627 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11628 OvlExpr, false, &dap)) { 11629 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11630 if (!Method->isStatic()) { 11631 // If the target type is a non-function type and the function found 11632 // is a non-static member function, pretend as if that was the 11633 // target, it's the only possible type to end up with. 11634 TargetTypeIsNonStaticMemberFunction = true; 11635 11636 // And skip adding the function if its not in the proper form. 11637 // We'll diagnose this due to an empty set of functions. 11638 if (!OvlExprInfo.HasFormOfMemberPointer) 11639 return; 11640 } 11641 11642 Matches.push_back(std::make_pair(dap, Fn)); 11643 } 11644 return; 11645 } 11646 11647 if (OvlExpr->hasExplicitTemplateArgs()) 11648 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11649 11650 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11651 // C++ [over.over]p4: 11652 // If more than one function is selected, [...] 11653 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11654 if (FoundNonTemplateFunction) 11655 EliminateAllTemplateMatches(); 11656 else 11657 EliminateAllExceptMostSpecializedTemplate(); 11658 } 11659 } 11660 11661 if (S.getLangOpts().CUDA && Matches.size() > 1) 11662 EliminateSuboptimalCudaMatches(); 11663 } 11664 11665 bool hasComplained() const { return HasComplained; } 11666 11667 private: 11668 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11669 QualType Discard; 11670 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11671 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11672 } 11673 11674 /// \return true if A is considered a better overload candidate for the 11675 /// desired type than B. 11676 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11677 // If A doesn't have exactly the correct type, we don't want to classify it 11678 // as "better" than anything else. This way, the user is required to 11679 // disambiguate for us if there are multiple candidates and no exact match. 11680 return candidateHasExactlyCorrectType(A) && 11681 (!candidateHasExactlyCorrectType(B) || 11682 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11683 } 11684 11685 /// \return true if we were able to eliminate all but one overload candidate, 11686 /// false otherwise. 11687 bool eliminiateSuboptimalOverloadCandidates() { 11688 // Same algorithm as overload resolution -- one pass to pick the "best", 11689 // another pass to be sure that nothing is better than the best. 11690 auto Best = Matches.begin(); 11691 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11692 if (isBetterCandidate(I->second, Best->second)) 11693 Best = I; 11694 11695 const FunctionDecl *BestFn = Best->second; 11696 auto IsBestOrInferiorToBest = [this, BestFn]( 11697 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11698 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11699 }; 11700 11701 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11702 // option, so we can potentially give the user a better error 11703 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11704 return false; 11705 Matches[0] = *Best; 11706 Matches.resize(1); 11707 return true; 11708 } 11709 11710 bool isTargetTypeAFunction() const { 11711 return TargetFunctionType->isFunctionType(); 11712 } 11713 11714 // [ToType] [Return] 11715 11716 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11717 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11718 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11719 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11720 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11721 } 11722 11723 // return true if any matching specializations were found 11724 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11725 const DeclAccessPair& CurAccessFunPair) { 11726 if (CXXMethodDecl *Method 11727 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11728 // Skip non-static function templates when converting to pointer, and 11729 // static when converting to member pointer. 11730 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11731 return false; 11732 } 11733 else if (TargetTypeIsNonStaticMemberFunction) 11734 return false; 11735 11736 // C++ [over.over]p2: 11737 // If the name is a function template, template argument deduction is 11738 // done (14.8.2.2), and if the argument deduction succeeds, the 11739 // resulting template argument list is used to generate a single 11740 // function template specialization, which is added to the set of 11741 // overloaded functions considered. 11742 FunctionDecl *Specialization = nullptr; 11743 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11744 if (Sema::TemplateDeductionResult Result 11745 = S.DeduceTemplateArguments(FunctionTemplate, 11746 &OvlExplicitTemplateArgs, 11747 TargetFunctionType, Specialization, 11748 Info, /*IsAddressOfFunction*/true)) { 11749 // Make a note of the failed deduction for diagnostics. 11750 FailedCandidates.addCandidate() 11751 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11752 MakeDeductionFailureInfo(Context, Result, Info)); 11753 return false; 11754 } 11755 11756 // Template argument deduction ensures that we have an exact match or 11757 // compatible pointer-to-function arguments that would be adjusted by ICS. 11758 // This function template specicalization works. 11759 assert(S.isSameOrCompatibleFunctionType( 11760 Context.getCanonicalType(Specialization->getType()), 11761 Context.getCanonicalType(TargetFunctionType))); 11762 11763 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11764 return false; 11765 11766 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11767 return true; 11768 } 11769 11770 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11771 const DeclAccessPair& CurAccessFunPair) { 11772 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11773 // Skip non-static functions when converting to pointer, and static 11774 // when converting to member pointer. 11775 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11776 return false; 11777 } 11778 else if (TargetTypeIsNonStaticMemberFunction) 11779 return false; 11780 11781 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11782 if (S.getLangOpts().CUDA) 11783 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11784 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11785 return false; 11786 if (FunDecl->isMultiVersion()) { 11787 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11788 if (TA && !TA->isDefaultVersion()) 11789 return false; 11790 } 11791 11792 // If any candidate has a placeholder return type, trigger its deduction 11793 // now. 11794 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11795 Complain)) { 11796 HasComplained |= Complain; 11797 return false; 11798 } 11799 11800 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11801 return false; 11802 11803 // If we're in C, we need to support types that aren't exactly identical. 11804 if (!S.getLangOpts().CPlusPlus || 11805 candidateHasExactlyCorrectType(FunDecl)) { 11806 Matches.push_back(std::make_pair( 11807 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11808 FoundNonTemplateFunction = true; 11809 return true; 11810 } 11811 } 11812 11813 return false; 11814 } 11815 11816 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11817 bool Ret = false; 11818 11819 // If the overload expression doesn't have the form of a pointer to 11820 // member, don't try to convert it to a pointer-to-member type. 11821 if (IsInvalidFormOfPointerToMemberFunction()) 11822 return false; 11823 11824 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11825 E = OvlExpr->decls_end(); 11826 I != E; ++I) { 11827 // Look through any using declarations to find the underlying function. 11828 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11829 11830 // C++ [over.over]p3: 11831 // Non-member functions and static member functions match 11832 // targets of type "pointer-to-function" or "reference-to-function." 11833 // Nonstatic member functions match targets of 11834 // type "pointer-to-member-function." 11835 // Note that according to DR 247, the containing class does not matter. 11836 if (FunctionTemplateDecl *FunctionTemplate 11837 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11838 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11839 Ret = true; 11840 } 11841 // If we have explicit template arguments supplied, skip non-templates. 11842 else if (!OvlExpr->hasExplicitTemplateArgs() && 11843 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11844 Ret = true; 11845 } 11846 assert(Ret || Matches.empty()); 11847 return Ret; 11848 } 11849 11850 void EliminateAllExceptMostSpecializedTemplate() { 11851 // [...] and any given function template specialization F1 is 11852 // eliminated if the set contains a second function template 11853 // specialization whose function template is more specialized 11854 // than the function template of F1 according to the partial 11855 // ordering rules of 14.5.5.2. 11856 11857 // The algorithm specified above is quadratic. We instead use a 11858 // two-pass algorithm (similar to the one used to identify the 11859 // best viable function in an overload set) that identifies the 11860 // best function template (if it exists). 11861 11862 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11863 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11864 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11865 11866 // TODO: It looks like FailedCandidates does not serve much purpose 11867 // here, since the no_viable diagnostic has index 0. 11868 UnresolvedSetIterator Result = S.getMostSpecialized( 11869 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11870 SourceExpr->getBeginLoc(), S.PDiag(), 11871 S.PDiag(diag::err_addr_ovl_ambiguous) 11872 << Matches[0].second->getDeclName(), 11873 S.PDiag(diag::note_ovl_candidate) 11874 << (unsigned)oc_function << (unsigned)ocs_described_template, 11875 Complain, TargetFunctionType); 11876 11877 if (Result != MatchesCopy.end()) { 11878 // Make it the first and only element 11879 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11880 Matches[0].second = cast<FunctionDecl>(*Result); 11881 Matches.resize(1); 11882 } else 11883 HasComplained |= Complain; 11884 } 11885 11886 void EliminateAllTemplateMatches() { 11887 // [...] any function template specializations in the set are 11888 // eliminated if the set also contains a non-template function, [...] 11889 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11890 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11891 ++I; 11892 else { 11893 Matches[I] = Matches[--N]; 11894 Matches.resize(N); 11895 } 11896 } 11897 } 11898 11899 void EliminateSuboptimalCudaMatches() { 11900 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11901 } 11902 11903 public: 11904 void ComplainNoMatchesFound() const { 11905 assert(Matches.empty()); 11906 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11907 << OvlExpr->getName() << TargetFunctionType 11908 << OvlExpr->getSourceRange(); 11909 if (FailedCandidates.empty()) 11910 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11911 /*TakingAddress=*/true); 11912 else { 11913 // We have some deduction failure messages. Use them to diagnose 11914 // the function templates, and diagnose the non-template candidates 11915 // normally. 11916 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11917 IEnd = OvlExpr->decls_end(); 11918 I != IEnd; ++I) 11919 if (FunctionDecl *Fun = 11920 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11921 if (!functionHasPassObjectSizeParams(Fun)) 11922 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 11923 /*TakingAddress=*/true); 11924 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11925 } 11926 } 11927 11928 bool IsInvalidFormOfPointerToMemberFunction() const { 11929 return TargetTypeIsNonStaticMemberFunction && 11930 !OvlExprInfo.HasFormOfMemberPointer; 11931 } 11932 11933 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11934 // TODO: Should we condition this on whether any functions might 11935 // have matched, or is it more appropriate to do that in callers? 11936 // TODO: a fixit wouldn't hurt. 11937 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11938 << TargetType << OvlExpr->getSourceRange(); 11939 } 11940 11941 bool IsStaticMemberFunctionFromBoundPointer() const { 11942 return StaticMemberFunctionFromBoundPointer; 11943 } 11944 11945 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11946 S.Diag(OvlExpr->getBeginLoc(), 11947 diag::err_invalid_form_pointer_member_function) 11948 << OvlExpr->getSourceRange(); 11949 } 11950 11951 void ComplainOfInvalidConversion() const { 11952 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11953 << OvlExpr->getName() << TargetType; 11954 } 11955 11956 void ComplainMultipleMatchesFound() const { 11957 assert(Matches.size() > 1); 11958 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11959 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11960 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11961 /*TakingAddress=*/true); 11962 } 11963 11964 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11965 11966 int getNumMatches() const { return Matches.size(); } 11967 11968 FunctionDecl* getMatchingFunctionDecl() const { 11969 if (Matches.size() != 1) return nullptr; 11970 return Matches[0].second; 11971 } 11972 11973 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11974 if (Matches.size() != 1) return nullptr; 11975 return &Matches[0].first; 11976 } 11977 }; 11978 } 11979 11980 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11981 /// an overloaded function (C++ [over.over]), where @p From is an 11982 /// expression with overloaded function type and @p ToType is the type 11983 /// we're trying to resolve to. For example: 11984 /// 11985 /// @code 11986 /// int f(double); 11987 /// int f(int); 11988 /// 11989 /// int (*pfd)(double) = f; // selects f(double) 11990 /// @endcode 11991 /// 11992 /// This routine returns the resulting FunctionDecl if it could be 11993 /// resolved, and NULL otherwise. When @p Complain is true, this 11994 /// routine will emit diagnostics if there is an error. 11995 FunctionDecl * 11996 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11997 QualType TargetType, 11998 bool Complain, 11999 DeclAccessPair &FoundResult, 12000 bool *pHadMultipleCandidates) { 12001 assert(AddressOfExpr->getType() == Context.OverloadTy); 12002 12003 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12004 Complain); 12005 int NumMatches = Resolver.getNumMatches(); 12006 FunctionDecl *Fn = nullptr; 12007 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12008 if (NumMatches == 0 && ShouldComplain) { 12009 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12010 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12011 else 12012 Resolver.ComplainNoMatchesFound(); 12013 } 12014 else if (NumMatches > 1 && ShouldComplain) 12015 Resolver.ComplainMultipleMatchesFound(); 12016 else if (NumMatches == 1) { 12017 Fn = Resolver.getMatchingFunctionDecl(); 12018 assert(Fn); 12019 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12020 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12021 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12022 if (Complain) { 12023 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12024 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12025 else 12026 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12027 } 12028 } 12029 12030 if (pHadMultipleCandidates) 12031 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12032 return Fn; 12033 } 12034 12035 /// Given an expression that refers to an overloaded function, try to 12036 /// resolve that function to a single function that can have its address taken. 12037 /// This will modify `Pair` iff it returns non-null. 12038 /// 12039 /// This routine can only succeed if from all of the candidates in the overload 12040 /// set for SrcExpr that can have their addresses taken, there is one candidate 12041 /// that is more constrained than the rest. 12042 FunctionDecl * 12043 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12044 OverloadExpr::FindResult R = OverloadExpr::find(E); 12045 OverloadExpr *Ovl = R.Expression; 12046 bool IsResultAmbiguous = false; 12047 FunctionDecl *Result = nullptr; 12048 DeclAccessPair DAP; 12049 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12050 12051 auto CheckMoreConstrained = 12052 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12053 SmallVector<const Expr *, 1> AC1, AC2; 12054 FD1->getAssociatedConstraints(AC1); 12055 FD2->getAssociatedConstraints(AC2); 12056 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12057 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12058 return None; 12059 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12060 return None; 12061 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12062 return None; 12063 return AtLeastAsConstrained1; 12064 }; 12065 12066 // Don't use the AddressOfResolver because we're specifically looking for 12067 // cases where we have one overload candidate that lacks 12068 // enable_if/pass_object_size/... 12069 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12070 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12071 if (!FD) 12072 return nullptr; 12073 12074 if (!checkAddressOfFunctionIsAvailable(FD)) 12075 continue; 12076 12077 // We have more than one result - see if it is more constrained than the 12078 // previous one. 12079 if (Result) { 12080 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12081 Result); 12082 if (!MoreConstrainedThanPrevious) { 12083 IsResultAmbiguous = true; 12084 AmbiguousDecls.push_back(FD); 12085 continue; 12086 } 12087 if (!*MoreConstrainedThanPrevious) 12088 continue; 12089 // FD is more constrained - replace Result with it. 12090 } 12091 IsResultAmbiguous = false; 12092 DAP = I.getPair(); 12093 Result = FD; 12094 } 12095 12096 if (IsResultAmbiguous) 12097 return nullptr; 12098 12099 if (Result) { 12100 SmallVector<const Expr *, 1> ResultAC; 12101 // We skipped over some ambiguous declarations which might be ambiguous with 12102 // the selected result. 12103 for (FunctionDecl *Skipped : AmbiguousDecls) 12104 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12105 return nullptr; 12106 Pair = DAP; 12107 } 12108 return Result; 12109 } 12110 12111 /// Given an overloaded function, tries to turn it into a non-overloaded 12112 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12113 /// will perform access checks, diagnose the use of the resultant decl, and, if 12114 /// requested, potentially perform a function-to-pointer decay. 12115 /// 12116 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12117 /// Otherwise, returns true. This may emit diagnostics and return true. 12118 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12119 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12120 Expr *E = SrcExpr.get(); 12121 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12122 12123 DeclAccessPair DAP; 12124 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12125 if (!Found || Found->isCPUDispatchMultiVersion() || 12126 Found->isCPUSpecificMultiVersion()) 12127 return false; 12128 12129 // Emitting multiple diagnostics for a function that is both inaccessible and 12130 // unavailable is consistent with our behavior elsewhere. So, always check 12131 // for both. 12132 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12133 CheckAddressOfMemberAccess(E, DAP); 12134 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12135 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12136 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12137 else 12138 SrcExpr = Fixed; 12139 return true; 12140 } 12141 12142 /// Given an expression that refers to an overloaded function, try to 12143 /// resolve that overloaded function expression down to a single function. 12144 /// 12145 /// This routine can only resolve template-ids that refer to a single function 12146 /// template, where that template-id refers to a single template whose template 12147 /// arguments are either provided by the template-id or have defaults, 12148 /// as described in C++0x [temp.arg.explicit]p3. 12149 /// 12150 /// If no template-ids are found, no diagnostics are emitted and NULL is 12151 /// returned. 12152 FunctionDecl * 12153 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12154 bool Complain, 12155 DeclAccessPair *FoundResult) { 12156 // C++ [over.over]p1: 12157 // [...] [Note: any redundant set of parentheses surrounding the 12158 // overloaded function name is ignored (5.1). ] 12159 // C++ [over.over]p1: 12160 // [...] The overloaded function name can be preceded by the & 12161 // operator. 12162 12163 // If we didn't actually find any template-ids, we're done. 12164 if (!ovl->hasExplicitTemplateArgs()) 12165 return nullptr; 12166 12167 TemplateArgumentListInfo ExplicitTemplateArgs; 12168 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12169 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12170 12171 // Look through all of the overloaded functions, searching for one 12172 // whose type matches exactly. 12173 FunctionDecl *Matched = nullptr; 12174 for (UnresolvedSetIterator I = ovl->decls_begin(), 12175 E = ovl->decls_end(); I != E; ++I) { 12176 // C++0x [temp.arg.explicit]p3: 12177 // [...] In contexts where deduction is done and fails, or in contexts 12178 // where deduction is not done, if a template argument list is 12179 // specified and it, along with any default template arguments, 12180 // identifies a single function template specialization, then the 12181 // template-id is an lvalue for the function template specialization. 12182 FunctionTemplateDecl *FunctionTemplate 12183 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12184 12185 // C++ [over.over]p2: 12186 // If the name is a function template, template argument deduction is 12187 // done (14.8.2.2), and if the argument deduction succeeds, the 12188 // resulting template argument list is used to generate a single 12189 // function template specialization, which is added to the set of 12190 // overloaded functions considered. 12191 FunctionDecl *Specialization = nullptr; 12192 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12193 if (TemplateDeductionResult Result 12194 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12195 Specialization, Info, 12196 /*IsAddressOfFunction*/true)) { 12197 // Make a note of the failed deduction for diagnostics. 12198 // TODO: Actually use the failed-deduction info? 12199 FailedCandidates.addCandidate() 12200 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12201 MakeDeductionFailureInfo(Context, Result, Info)); 12202 continue; 12203 } 12204 12205 assert(Specialization && "no specialization and no error?"); 12206 12207 // Multiple matches; we can't resolve to a single declaration. 12208 if (Matched) { 12209 if (Complain) { 12210 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12211 << ovl->getName(); 12212 NoteAllOverloadCandidates(ovl); 12213 } 12214 return nullptr; 12215 } 12216 12217 Matched = Specialization; 12218 if (FoundResult) *FoundResult = I.getPair(); 12219 } 12220 12221 if (Matched && 12222 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12223 return nullptr; 12224 12225 return Matched; 12226 } 12227 12228 // Resolve and fix an overloaded expression that can be resolved 12229 // because it identifies a single function template specialization. 12230 // 12231 // Last three arguments should only be supplied if Complain = true 12232 // 12233 // Return true if it was logically possible to so resolve the 12234 // expression, regardless of whether or not it succeeded. Always 12235 // returns true if 'complain' is set. 12236 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12237 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12238 bool complain, SourceRange OpRangeForComplaining, 12239 QualType DestTypeForComplaining, 12240 unsigned DiagIDForComplaining) { 12241 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12242 12243 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12244 12245 DeclAccessPair found; 12246 ExprResult SingleFunctionExpression; 12247 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12248 ovl.Expression, /*complain*/ false, &found)) { 12249 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12250 SrcExpr = ExprError(); 12251 return true; 12252 } 12253 12254 // It is only correct to resolve to an instance method if we're 12255 // resolving a form that's permitted to be a pointer to member. 12256 // Otherwise we'll end up making a bound member expression, which 12257 // is illegal in all the contexts we resolve like this. 12258 if (!ovl.HasFormOfMemberPointer && 12259 isa<CXXMethodDecl>(fn) && 12260 cast<CXXMethodDecl>(fn)->isInstance()) { 12261 if (!complain) return false; 12262 12263 Diag(ovl.Expression->getExprLoc(), 12264 diag::err_bound_member_function) 12265 << 0 << ovl.Expression->getSourceRange(); 12266 12267 // TODO: I believe we only end up here if there's a mix of 12268 // static and non-static candidates (otherwise the expression 12269 // would have 'bound member' type, not 'overload' type). 12270 // Ideally we would note which candidate was chosen and why 12271 // the static candidates were rejected. 12272 SrcExpr = ExprError(); 12273 return true; 12274 } 12275 12276 // Fix the expression to refer to 'fn'. 12277 SingleFunctionExpression = 12278 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12279 12280 // If desired, do function-to-pointer decay. 12281 if (doFunctionPointerConverion) { 12282 SingleFunctionExpression = 12283 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12284 if (SingleFunctionExpression.isInvalid()) { 12285 SrcExpr = ExprError(); 12286 return true; 12287 } 12288 } 12289 } 12290 12291 if (!SingleFunctionExpression.isUsable()) { 12292 if (complain) { 12293 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12294 << ovl.Expression->getName() 12295 << DestTypeForComplaining 12296 << OpRangeForComplaining 12297 << ovl.Expression->getQualifierLoc().getSourceRange(); 12298 NoteAllOverloadCandidates(SrcExpr.get()); 12299 12300 SrcExpr = ExprError(); 12301 return true; 12302 } 12303 12304 return false; 12305 } 12306 12307 SrcExpr = SingleFunctionExpression; 12308 return true; 12309 } 12310 12311 /// Add a single candidate to the overload set. 12312 static void AddOverloadedCallCandidate(Sema &S, 12313 DeclAccessPair FoundDecl, 12314 TemplateArgumentListInfo *ExplicitTemplateArgs, 12315 ArrayRef<Expr *> Args, 12316 OverloadCandidateSet &CandidateSet, 12317 bool PartialOverloading, 12318 bool KnownValid) { 12319 NamedDecl *Callee = FoundDecl.getDecl(); 12320 if (isa<UsingShadowDecl>(Callee)) 12321 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12322 12323 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12324 if (ExplicitTemplateArgs) { 12325 assert(!KnownValid && "Explicit template arguments?"); 12326 return; 12327 } 12328 // Prevent ill-formed function decls to be added as overload candidates. 12329 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12330 return; 12331 12332 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12333 /*SuppressUserConversions=*/false, 12334 PartialOverloading); 12335 return; 12336 } 12337 12338 if (FunctionTemplateDecl *FuncTemplate 12339 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12340 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12341 ExplicitTemplateArgs, Args, CandidateSet, 12342 /*SuppressUserConversions=*/false, 12343 PartialOverloading); 12344 return; 12345 } 12346 12347 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12348 } 12349 12350 /// Add the overload candidates named by callee and/or found by argument 12351 /// dependent lookup to the given overload set. 12352 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12353 ArrayRef<Expr *> Args, 12354 OverloadCandidateSet &CandidateSet, 12355 bool PartialOverloading) { 12356 12357 #ifndef NDEBUG 12358 // Verify that ArgumentDependentLookup is consistent with the rules 12359 // in C++0x [basic.lookup.argdep]p3: 12360 // 12361 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12362 // and let Y be the lookup set produced by argument dependent 12363 // lookup (defined as follows). If X contains 12364 // 12365 // -- a declaration of a class member, or 12366 // 12367 // -- a block-scope function declaration that is not a 12368 // using-declaration, or 12369 // 12370 // -- a declaration that is neither a function or a function 12371 // template 12372 // 12373 // then Y is empty. 12374 12375 if (ULE->requiresADL()) { 12376 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12377 E = ULE->decls_end(); I != E; ++I) { 12378 assert(!(*I)->getDeclContext()->isRecord()); 12379 assert(isa<UsingShadowDecl>(*I) || 12380 !(*I)->getDeclContext()->isFunctionOrMethod()); 12381 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12382 } 12383 } 12384 #endif 12385 12386 // It would be nice to avoid this copy. 12387 TemplateArgumentListInfo TABuffer; 12388 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12389 if (ULE->hasExplicitTemplateArgs()) { 12390 ULE->copyTemplateArgumentsInto(TABuffer); 12391 ExplicitTemplateArgs = &TABuffer; 12392 } 12393 12394 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12395 E = ULE->decls_end(); I != E; ++I) 12396 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12397 CandidateSet, PartialOverloading, 12398 /*KnownValid*/ true); 12399 12400 if (ULE->requiresADL()) 12401 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12402 Args, ExplicitTemplateArgs, 12403 CandidateSet, PartialOverloading); 12404 } 12405 12406 /// Determine whether a declaration with the specified name could be moved into 12407 /// a different namespace. 12408 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12409 switch (Name.getCXXOverloadedOperator()) { 12410 case OO_New: case OO_Array_New: 12411 case OO_Delete: case OO_Array_Delete: 12412 return false; 12413 12414 default: 12415 return true; 12416 } 12417 } 12418 12419 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12420 /// template, where the non-dependent name was declared after the template 12421 /// was defined. This is common in code written for a compilers which do not 12422 /// correctly implement two-stage name lookup. 12423 /// 12424 /// Returns true if a viable candidate was found and a diagnostic was issued. 12425 static bool 12426 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12427 const CXXScopeSpec &SS, LookupResult &R, 12428 OverloadCandidateSet::CandidateSetKind CSK, 12429 TemplateArgumentListInfo *ExplicitTemplateArgs, 12430 ArrayRef<Expr *> Args, 12431 bool *DoDiagnoseEmptyLookup = nullptr) { 12432 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12433 return false; 12434 12435 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12436 if (DC->isTransparentContext()) 12437 continue; 12438 12439 SemaRef.LookupQualifiedName(R, DC); 12440 12441 if (!R.empty()) { 12442 R.suppressDiagnostics(); 12443 12444 if (isa<CXXRecordDecl>(DC)) { 12445 // Don't diagnose names we find in classes; we get much better 12446 // diagnostics for these from DiagnoseEmptyLookup. 12447 R.clear(); 12448 if (DoDiagnoseEmptyLookup) 12449 *DoDiagnoseEmptyLookup = true; 12450 return false; 12451 } 12452 12453 OverloadCandidateSet Candidates(FnLoc, CSK); 12454 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12455 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12456 ExplicitTemplateArgs, Args, 12457 Candidates, false, /*KnownValid*/ false); 12458 12459 OverloadCandidateSet::iterator Best; 12460 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12461 // No viable functions. Don't bother the user with notes for functions 12462 // which don't work and shouldn't be found anyway. 12463 R.clear(); 12464 return false; 12465 } 12466 12467 // Find the namespaces where ADL would have looked, and suggest 12468 // declaring the function there instead. 12469 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12470 Sema::AssociatedClassSet AssociatedClasses; 12471 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12472 AssociatedNamespaces, 12473 AssociatedClasses); 12474 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12475 if (canBeDeclaredInNamespace(R.getLookupName())) { 12476 DeclContext *Std = SemaRef.getStdNamespace(); 12477 for (Sema::AssociatedNamespaceSet::iterator 12478 it = AssociatedNamespaces.begin(), 12479 end = AssociatedNamespaces.end(); it != end; ++it) { 12480 // Never suggest declaring a function within namespace 'std'. 12481 if (Std && Std->Encloses(*it)) 12482 continue; 12483 12484 // Never suggest declaring a function within a namespace with a 12485 // reserved name, like __gnu_cxx. 12486 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12487 if (NS && 12488 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12489 continue; 12490 12491 SuggestedNamespaces.insert(*it); 12492 } 12493 } 12494 12495 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12496 << R.getLookupName(); 12497 if (SuggestedNamespaces.empty()) { 12498 SemaRef.Diag(Best->Function->getLocation(), 12499 diag::note_not_found_by_two_phase_lookup) 12500 << R.getLookupName() << 0; 12501 } else if (SuggestedNamespaces.size() == 1) { 12502 SemaRef.Diag(Best->Function->getLocation(), 12503 diag::note_not_found_by_two_phase_lookup) 12504 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12505 } else { 12506 // FIXME: It would be useful to list the associated namespaces here, 12507 // but the diagnostics infrastructure doesn't provide a way to produce 12508 // a localized representation of a list of items. 12509 SemaRef.Diag(Best->Function->getLocation(), 12510 diag::note_not_found_by_two_phase_lookup) 12511 << R.getLookupName() << 2; 12512 } 12513 12514 // Try to recover by calling this function. 12515 return true; 12516 } 12517 12518 R.clear(); 12519 } 12520 12521 return false; 12522 } 12523 12524 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12525 /// template, where the non-dependent operator was declared after the template 12526 /// was defined. 12527 /// 12528 /// Returns true if a viable candidate was found and a diagnostic was issued. 12529 static bool 12530 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12531 SourceLocation OpLoc, 12532 ArrayRef<Expr *> Args) { 12533 DeclarationName OpName = 12534 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12535 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12536 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12537 OverloadCandidateSet::CSK_Operator, 12538 /*ExplicitTemplateArgs=*/nullptr, Args); 12539 } 12540 12541 namespace { 12542 class BuildRecoveryCallExprRAII { 12543 Sema &SemaRef; 12544 public: 12545 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12546 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12547 SemaRef.IsBuildingRecoveryCallExpr = true; 12548 } 12549 12550 ~BuildRecoveryCallExprRAII() { 12551 SemaRef.IsBuildingRecoveryCallExpr = false; 12552 } 12553 }; 12554 12555 } 12556 12557 /// Attempts to recover from a call where no functions were found. 12558 /// 12559 /// Returns true if new candidates were found. 12560 static ExprResult 12561 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12562 UnresolvedLookupExpr *ULE, 12563 SourceLocation LParenLoc, 12564 MutableArrayRef<Expr *> Args, 12565 SourceLocation RParenLoc, 12566 bool EmptyLookup, bool AllowTypoCorrection) { 12567 // Do not try to recover if it is already building a recovery call. 12568 // This stops infinite loops for template instantiations like 12569 // 12570 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12571 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12572 // 12573 if (SemaRef.IsBuildingRecoveryCallExpr) 12574 return ExprError(); 12575 BuildRecoveryCallExprRAII RCE(SemaRef); 12576 12577 CXXScopeSpec SS; 12578 SS.Adopt(ULE->getQualifierLoc()); 12579 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12580 12581 TemplateArgumentListInfo TABuffer; 12582 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12583 if (ULE->hasExplicitTemplateArgs()) { 12584 ULE->copyTemplateArgumentsInto(TABuffer); 12585 ExplicitTemplateArgs = &TABuffer; 12586 } 12587 12588 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12589 Sema::LookupOrdinaryName); 12590 bool DoDiagnoseEmptyLookup = EmptyLookup; 12591 if (!DiagnoseTwoPhaseLookup( 12592 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12593 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12594 NoTypoCorrectionCCC NoTypoValidator{}; 12595 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12596 ExplicitTemplateArgs != nullptr, 12597 dyn_cast<MemberExpr>(Fn)); 12598 CorrectionCandidateCallback &Validator = 12599 AllowTypoCorrection 12600 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12601 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12602 if (!DoDiagnoseEmptyLookup || 12603 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12604 Args)) 12605 return ExprError(); 12606 } 12607 12608 assert(!R.empty() && "lookup results empty despite recovery"); 12609 12610 // If recovery created an ambiguity, just bail out. 12611 if (R.isAmbiguous()) { 12612 R.suppressDiagnostics(); 12613 return ExprError(); 12614 } 12615 12616 // Build an implicit member call if appropriate. Just drop the 12617 // casts and such from the call, we don't really care. 12618 ExprResult NewFn = ExprError(); 12619 if ((*R.begin())->isCXXClassMember()) 12620 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12621 ExplicitTemplateArgs, S); 12622 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12623 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12624 ExplicitTemplateArgs); 12625 else 12626 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12627 12628 if (NewFn.isInvalid()) 12629 return ExprError(); 12630 12631 // This shouldn't cause an infinite loop because we're giving it 12632 // an expression with viable lookup results, which should never 12633 // end up here. 12634 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12635 MultiExprArg(Args.data(), Args.size()), 12636 RParenLoc); 12637 } 12638 12639 /// Constructs and populates an OverloadedCandidateSet from 12640 /// the given function. 12641 /// \returns true when an the ExprResult output parameter has been set. 12642 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12643 UnresolvedLookupExpr *ULE, 12644 MultiExprArg Args, 12645 SourceLocation RParenLoc, 12646 OverloadCandidateSet *CandidateSet, 12647 ExprResult *Result) { 12648 #ifndef NDEBUG 12649 if (ULE->requiresADL()) { 12650 // To do ADL, we must have found an unqualified name. 12651 assert(!ULE->getQualifier() && "qualified name with ADL"); 12652 12653 // We don't perform ADL for implicit declarations of builtins. 12654 // Verify that this was correctly set up. 12655 FunctionDecl *F; 12656 if (ULE->decls_begin() != ULE->decls_end() && 12657 ULE->decls_begin() + 1 == ULE->decls_end() && 12658 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12659 F->getBuiltinID() && F->isImplicit()) 12660 llvm_unreachable("performing ADL for builtin"); 12661 12662 // We don't perform ADL in C. 12663 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12664 } 12665 #endif 12666 12667 UnbridgedCastsSet UnbridgedCasts; 12668 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12669 *Result = ExprError(); 12670 return true; 12671 } 12672 12673 // Add the functions denoted by the callee to the set of candidate 12674 // functions, including those from argument-dependent lookup. 12675 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12676 12677 if (getLangOpts().MSVCCompat && 12678 CurContext->isDependentContext() && !isSFINAEContext() && 12679 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12680 12681 OverloadCandidateSet::iterator Best; 12682 if (CandidateSet->empty() || 12683 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12684 OR_No_Viable_Function) { 12685 // In Microsoft mode, if we are inside a template class member function 12686 // then create a type dependent CallExpr. The goal is to postpone name 12687 // lookup to instantiation time to be able to search into type dependent 12688 // base classes. 12689 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12690 VK_RValue, RParenLoc); 12691 CE->setTypeDependent(true); 12692 CE->setValueDependent(true); 12693 CE->setInstantiationDependent(true); 12694 *Result = CE; 12695 return true; 12696 } 12697 } 12698 12699 if (CandidateSet->empty()) 12700 return false; 12701 12702 UnbridgedCasts.restore(); 12703 return false; 12704 } 12705 12706 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12707 /// the completed call expression. If overload resolution fails, emits 12708 /// diagnostics and returns ExprError() 12709 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12710 UnresolvedLookupExpr *ULE, 12711 SourceLocation LParenLoc, 12712 MultiExprArg Args, 12713 SourceLocation RParenLoc, 12714 Expr *ExecConfig, 12715 OverloadCandidateSet *CandidateSet, 12716 OverloadCandidateSet::iterator *Best, 12717 OverloadingResult OverloadResult, 12718 bool AllowTypoCorrection) { 12719 if (CandidateSet->empty()) 12720 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12721 RParenLoc, /*EmptyLookup=*/true, 12722 AllowTypoCorrection); 12723 12724 switch (OverloadResult) { 12725 case OR_Success: { 12726 FunctionDecl *FDecl = (*Best)->Function; 12727 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12728 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12729 return ExprError(); 12730 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12731 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12732 ExecConfig, /*IsExecConfig=*/false, 12733 (*Best)->IsADLCandidate); 12734 } 12735 12736 case OR_No_Viable_Function: { 12737 // Try to recover by looking for viable functions which the user might 12738 // have meant to call. 12739 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12740 Args, RParenLoc, 12741 /*EmptyLookup=*/false, 12742 AllowTypoCorrection); 12743 if (!Recovery.isInvalid()) 12744 return Recovery; 12745 12746 // If the user passes in a function that we can't take the address of, we 12747 // generally end up emitting really bad error messages. Here, we attempt to 12748 // emit better ones. 12749 for (const Expr *Arg : Args) { 12750 if (!Arg->getType()->isFunctionType()) 12751 continue; 12752 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12753 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12754 if (FD && 12755 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12756 Arg->getExprLoc())) 12757 return ExprError(); 12758 } 12759 } 12760 12761 CandidateSet->NoteCandidates( 12762 PartialDiagnosticAt( 12763 Fn->getBeginLoc(), 12764 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12765 << ULE->getName() << Fn->getSourceRange()), 12766 SemaRef, OCD_AllCandidates, Args); 12767 break; 12768 } 12769 12770 case OR_Ambiguous: 12771 CandidateSet->NoteCandidates( 12772 PartialDiagnosticAt(Fn->getBeginLoc(), 12773 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12774 << ULE->getName() << Fn->getSourceRange()), 12775 SemaRef, OCD_AmbiguousCandidates, Args); 12776 break; 12777 12778 case OR_Deleted: { 12779 CandidateSet->NoteCandidates( 12780 PartialDiagnosticAt(Fn->getBeginLoc(), 12781 SemaRef.PDiag(diag::err_ovl_deleted_call) 12782 << ULE->getName() << Fn->getSourceRange()), 12783 SemaRef, OCD_AllCandidates, Args); 12784 12785 // We emitted an error for the unavailable/deleted function call but keep 12786 // the call in the AST. 12787 FunctionDecl *FDecl = (*Best)->Function; 12788 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12789 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12790 ExecConfig, /*IsExecConfig=*/false, 12791 (*Best)->IsADLCandidate); 12792 } 12793 } 12794 12795 // Overload resolution failed. 12796 return ExprError(); 12797 } 12798 12799 static void markUnaddressableCandidatesUnviable(Sema &S, 12800 OverloadCandidateSet &CS) { 12801 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12802 if (I->Viable && 12803 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12804 I->Viable = false; 12805 I->FailureKind = ovl_fail_addr_not_available; 12806 } 12807 } 12808 } 12809 12810 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12811 /// (which eventually refers to the declaration Func) and the call 12812 /// arguments Args/NumArgs, attempt to resolve the function call down 12813 /// to a specific function. If overload resolution succeeds, returns 12814 /// the call expression produced by overload resolution. 12815 /// Otherwise, emits diagnostics and returns ExprError. 12816 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12817 UnresolvedLookupExpr *ULE, 12818 SourceLocation LParenLoc, 12819 MultiExprArg Args, 12820 SourceLocation RParenLoc, 12821 Expr *ExecConfig, 12822 bool AllowTypoCorrection, 12823 bool CalleesAddressIsTaken) { 12824 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12825 OverloadCandidateSet::CSK_Normal); 12826 ExprResult result; 12827 12828 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12829 &result)) 12830 return result; 12831 12832 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12833 // functions that aren't addressible are considered unviable. 12834 if (CalleesAddressIsTaken) 12835 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12836 12837 OverloadCandidateSet::iterator Best; 12838 OverloadingResult OverloadResult = 12839 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12840 12841 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 12842 ExecConfig, &CandidateSet, &Best, 12843 OverloadResult, AllowTypoCorrection); 12844 } 12845 12846 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12847 return Functions.size() > 1 || 12848 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12849 } 12850 12851 /// Create a unary operation that may resolve to an overloaded 12852 /// operator. 12853 /// 12854 /// \param OpLoc The location of the operator itself (e.g., '*'). 12855 /// 12856 /// \param Opc The UnaryOperatorKind that describes this operator. 12857 /// 12858 /// \param Fns The set of non-member functions that will be 12859 /// considered by overload resolution. The caller needs to build this 12860 /// set based on the context using, e.g., 12861 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12862 /// set should not contain any member functions; those will be added 12863 /// by CreateOverloadedUnaryOp(). 12864 /// 12865 /// \param Input The input argument. 12866 ExprResult 12867 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12868 const UnresolvedSetImpl &Fns, 12869 Expr *Input, bool PerformADL) { 12870 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12871 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12872 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12873 // TODO: provide better source location info. 12874 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12875 12876 if (checkPlaceholderForOverload(*this, Input)) 12877 return ExprError(); 12878 12879 Expr *Args[2] = { Input, nullptr }; 12880 unsigned NumArgs = 1; 12881 12882 // For post-increment and post-decrement, add the implicit '0' as 12883 // the second argument, so that we know this is a post-increment or 12884 // post-decrement. 12885 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12886 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12887 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12888 SourceLocation()); 12889 NumArgs = 2; 12890 } 12891 12892 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12893 12894 if (Input->isTypeDependent()) { 12895 if (Fns.empty()) 12896 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12897 VK_RValue, OK_Ordinary, OpLoc, false); 12898 12899 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12900 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12901 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12902 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12903 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12904 Context.DependentTy, VK_RValue, OpLoc, 12905 FPOptions()); 12906 } 12907 12908 // Build an empty overload set. 12909 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12910 12911 // Add the candidates from the given function set. 12912 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 12913 12914 // Add operator candidates that are member functions. 12915 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12916 12917 // Add candidates from ADL. 12918 if (PerformADL) { 12919 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12920 /*ExplicitTemplateArgs*/nullptr, 12921 CandidateSet); 12922 } 12923 12924 // Add builtin operator candidates. 12925 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12926 12927 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12928 12929 // Perform overload resolution. 12930 OverloadCandidateSet::iterator Best; 12931 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12932 case OR_Success: { 12933 // We found a built-in operator or an overloaded operator. 12934 FunctionDecl *FnDecl = Best->Function; 12935 12936 if (FnDecl) { 12937 Expr *Base = nullptr; 12938 // We matched an overloaded operator. Build a call to that 12939 // operator. 12940 12941 // Convert the arguments. 12942 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12943 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12944 12945 ExprResult InputRes = 12946 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12947 Best->FoundDecl, Method); 12948 if (InputRes.isInvalid()) 12949 return ExprError(); 12950 Base = Input = InputRes.get(); 12951 } else { 12952 // Convert the arguments. 12953 ExprResult InputInit 12954 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12955 Context, 12956 FnDecl->getParamDecl(0)), 12957 SourceLocation(), 12958 Input); 12959 if (InputInit.isInvalid()) 12960 return ExprError(); 12961 Input = InputInit.get(); 12962 } 12963 12964 // Build the actual expression node. 12965 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12966 Base, HadMultipleCandidates, 12967 OpLoc); 12968 if (FnExpr.isInvalid()) 12969 return ExprError(); 12970 12971 // Determine the result type. 12972 QualType ResultTy = FnDecl->getReturnType(); 12973 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12974 ResultTy = ResultTy.getNonLValueExprType(Context); 12975 12976 Args[0] = Input; 12977 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12978 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 12979 FPOptions(), Best->IsADLCandidate); 12980 12981 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12982 return ExprError(); 12983 12984 if (CheckFunctionCall(FnDecl, TheCall, 12985 FnDecl->getType()->castAs<FunctionProtoType>())) 12986 return ExprError(); 12987 12988 return MaybeBindToTemporary(TheCall); 12989 } else { 12990 // We matched a built-in operator. Convert the arguments, then 12991 // break out so that we will build the appropriate built-in 12992 // operator node. 12993 ExprResult InputRes = PerformImplicitConversion( 12994 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12995 CCK_ForBuiltinOverloadedOp); 12996 if (InputRes.isInvalid()) 12997 return ExprError(); 12998 Input = InputRes.get(); 12999 break; 13000 } 13001 } 13002 13003 case OR_No_Viable_Function: 13004 // This is an erroneous use of an operator which can be overloaded by 13005 // a non-member function. Check for non-member operators which were 13006 // defined too late to be candidates. 13007 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13008 // FIXME: Recover by calling the found function. 13009 return ExprError(); 13010 13011 // No viable function; fall through to handling this as a 13012 // built-in operator, which will produce an error message for us. 13013 break; 13014 13015 case OR_Ambiguous: 13016 CandidateSet.NoteCandidates( 13017 PartialDiagnosticAt(OpLoc, 13018 PDiag(diag::err_ovl_ambiguous_oper_unary) 13019 << UnaryOperator::getOpcodeStr(Opc) 13020 << Input->getType() << Input->getSourceRange()), 13021 *this, OCD_AmbiguousCandidates, ArgsArray, 13022 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13023 return ExprError(); 13024 13025 case OR_Deleted: 13026 CandidateSet.NoteCandidates( 13027 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13028 << UnaryOperator::getOpcodeStr(Opc) 13029 << Input->getSourceRange()), 13030 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13031 OpLoc); 13032 return ExprError(); 13033 } 13034 13035 // Either we found no viable overloaded operator or we matched a 13036 // built-in operator. In either case, fall through to trying to 13037 // build a built-in operation. 13038 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13039 } 13040 13041 /// Perform lookup for an overloaded binary operator. 13042 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13043 OverloadedOperatorKind Op, 13044 const UnresolvedSetImpl &Fns, 13045 ArrayRef<Expr *> Args, bool PerformADL) { 13046 SourceLocation OpLoc = CandidateSet.getLocation(); 13047 13048 OverloadedOperatorKind ExtraOp = 13049 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13050 ? getRewrittenOverloadedOperator(Op) 13051 : OO_None; 13052 13053 // Add the candidates from the given function set. This also adds the 13054 // rewritten candidates using these functions if necessary. 13055 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13056 13057 // Add operator candidates that are member functions. 13058 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13059 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13060 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13061 OverloadCandidateParamOrder::Reversed); 13062 13063 // In C++20, also add any rewritten member candidates. 13064 if (ExtraOp) { 13065 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13066 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13067 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13068 CandidateSet, 13069 OverloadCandidateParamOrder::Reversed); 13070 } 13071 13072 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13073 // performed for an assignment operator (nor for operator[] nor operator->, 13074 // which don't get here). 13075 if (Op != OO_Equal && PerformADL) { 13076 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13077 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13078 /*ExplicitTemplateArgs*/ nullptr, 13079 CandidateSet); 13080 if (ExtraOp) { 13081 DeclarationName ExtraOpName = 13082 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13083 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13084 /*ExplicitTemplateArgs*/ nullptr, 13085 CandidateSet); 13086 } 13087 } 13088 13089 // Add builtin operator candidates. 13090 // 13091 // FIXME: We don't add any rewritten candidates here. This is strictly 13092 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13093 // resulting in our selecting a rewritten builtin candidate. For example: 13094 // 13095 // enum class E { e }; 13096 // bool operator!=(E, E) requires false; 13097 // bool k = E::e != E::e; 13098 // 13099 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13100 // it seems unreasonable to consider rewritten builtin candidates. A core 13101 // issue has been filed proposing to removed this requirement. 13102 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13103 } 13104 13105 /// Create a binary operation that may resolve to an overloaded 13106 /// operator. 13107 /// 13108 /// \param OpLoc The location of the operator itself (e.g., '+'). 13109 /// 13110 /// \param Opc The BinaryOperatorKind that describes this operator. 13111 /// 13112 /// \param Fns The set of non-member functions that will be 13113 /// considered by overload resolution. The caller needs to build this 13114 /// set based on the context using, e.g., 13115 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13116 /// set should not contain any member functions; those will be added 13117 /// by CreateOverloadedBinOp(). 13118 /// 13119 /// \param LHS Left-hand argument. 13120 /// \param RHS Right-hand argument. 13121 /// \param PerformADL Whether to consider operator candidates found by ADL. 13122 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13123 /// C++20 operator rewrites. 13124 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13125 /// the function in question. Such a function is never a candidate in 13126 /// our overload resolution. This also enables synthesizing a three-way 13127 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13128 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13129 BinaryOperatorKind Opc, 13130 const UnresolvedSetImpl &Fns, Expr *LHS, 13131 Expr *RHS, bool PerformADL, 13132 bool AllowRewrittenCandidates, 13133 FunctionDecl *DefaultedFn) { 13134 Expr *Args[2] = { LHS, RHS }; 13135 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13136 13137 if (!getLangOpts().CPlusPlus2a) 13138 AllowRewrittenCandidates = false; 13139 13140 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13141 13142 // If either side is type-dependent, create an appropriate dependent 13143 // expression. 13144 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13145 if (Fns.empty()) { 13146 // If there are no functions to store, just build a dependent 13147 // BinaryOperator or CompoundAssignment. 13148 if (Opc <= BO_Assign || Opc > BO_OrAssign) 13149 return new (Context) BinaryOperator( 13150 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 13151 OpLoc, FPFeatures); 13152 13153 return new (Context) CompoundAssignOperator( 13154 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 13155 Context.DependentTy, Context.DependentTy, OpLoc, 13156 FPFeatures); 13157 } 13158 13159 // FIXME: save results of ADL from here? 13160 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13161 // TODO: provide better source location info in DNLoc component. 13162 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13163 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13164 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 13165 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 13166 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 13167 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 13168 Context.DependentTy, VK_RValue, OpLoc, 13169 FPFeatures); 13170 } 13171 13172 // Always do placeholder-like conversions on the RHS. 13173 if (checkPlaceholderForOverload(*this, Args[1])) 13174 return ExprError(); 13175 13176 // Do placeholder-like conversion on the LHS; note that we should 13177 // not get here with a PseudoObject LHS. 13178 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13179 if (checkPlaceholderForOverload(*this, Args[0])) 13180 return ExprError(); 13181 13182 // If this is the assignment operator, we only perform overload resolution 13183 // if the left-hand side is a class or enumeration type. This is actually 13184 // a hack. The standard requires that we do overload resolution between the 13185 // various built-in candidates, but as DR507 points out, this can lead to 13186 // problems. So we do it this way, which pretty much follows what GCC does. 13187 // Note that we go the traditional code path for compound assignment forms. 13188 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13189 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13190 13191 // If this is the .* operator, which is not overloadable, just 13192 // create a built-in binary operator. 13193 if (Opc == BO_PtrMemD) 13194 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13195 13196 // Build the overload set. 13197 OverloadCandidateSet CandidateSet( 13198 OpLoc, OverloadCandidateSet::CSK_Operator, 13199 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13200 if (DefaultedFn) 13201 CandidateSet.exclude(DefaultedFn); 13202 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13203 13204 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13205 13206 // Perform overload resolution. 13207 OverloadCandidateSet::iterator Best; 13208 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13209 case OR_Success: { 13210 // We found a built-in operator or an overloaded operator. 13211 FunctionDecl *FnDecl = Best->Function; 13212 13213 bool IsReversed = (Best->RewriteKind & CRK_Reversed); 13214 if (IsReversed) 13215 std::swap(Args[0], Args[1]); 13216 13217 if (FnDecl) { 13218 Expr *Base = nullptr; 13219 // We matched an overloaded operator. Build a call to that 13220 // operator. 13221 13222 OverloadedOperatorKind ChosenOp = 13223 FnDecl->getDeclName().getCXXOverloadedOperator(); 13224 13225 // C++2a [over.match.oper]p9: 13226 // If a rewritten operator== candidate is selected by overload 13227 // resolution for an operator@, its return type shall be cv bool 13228 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13229 !FnDecl->getReturnType()->isBooleanType()) { 13230 Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool) 13231 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13232 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13233 Diag(FnDecl->getLocation(), diag::note_declared_at); 13234 return ExprError(); 13235 } 13236 13237 if (AllowRewrittenCandidates && !IsReversed && 13238 CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) { 13239 // We could have reversed this operator, but didn't. Check if the 13240 // reversed form was a viable candidate, and if so, if it had a 13241 // better conversion for either parameter. If so, this call is 13242 // formally ambiguous, and allowing it is an extension. 13243 for (OverloadCandidate &Cand : CandidateSet) { 13244 if (Cand.Viable && Cand.Function == FnDecl && 13245 Cand.RewriteKind & CRK_Reversed) { 13246 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13247 if (CompareImplicitConversionSequences( 13248 *this, OpLoc, Cand.Conversions[ArgIdx], 13249 Best->Conversions[ArgIdx]) == 13250 ImplicitConversionSequence::Better) { 13251 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13252 << BinaryOperator::getOpcodeStr(Opc) 13253 << Args[0]->getType() << Args[1]->getType() 13254 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13255 Diag(FnDecl->getLocation(), 13256 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13257 } 13258 } 13259 break; 13260 } 13261 } 13262 } 13263 13264 // Convert the arguments. 13265 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13266 // Best->Access is only meaningful for class members. 13267 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13268 13269 ExprResult Arg1 = 13270 PerformCopyInitialization( 13271 InitializedEntity::InitializeParameter(Context, 13272 FnDecl->getParamDecl(0)), 13273 SourceLocation(), Args[1]); 13274 if (Arg1.isInvalid()) 13275 return ExprError(); 13276 13277 ExprResult Arg0 = 13278 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13279 Best->FoundDecl, Method); 13280 if (Arg0.isInvalid()) 13281 return ExprError(); 13282 Base = Args[0] = Arg0.getAs<Expr>(); 13283 Args[1] = RHS = Arg1.getAs<Expr>(); 13284 } else { 13285 // Convert the arguments. 13286 ExprResult Arg0 = PerformCopyInitialization( 13287 InitializedEntity::InitializeParameter(Context, 13288 FnDecl->getParamDecl(0)), 13289 SourceLocation(), Args[0]); 13290 if (Arg0.isInvalid()) 13291 return ExprError(); 13292 13293 ExprResult Arg1 = 13294 PerformCopyInitialization( 13295 InitializedEntity::InitializeParameter(Context, 13296 FnDecl->getParamDecl(1)), 13297 SourceLocation(), Args[1]); 13298 if (Arg1.isInvalid()) 13299 return ExprError(); 13300 Args[0] = LHS = Arg0.getAs<Expr>(); 13301 Args[1] = RHS = Arg1.getAs<Expr>(); 13302 } 13303 13304 // Build the actual expression node. 13305 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13306 Best->FoundDecl, Base, 13307 HadMultipleCandidates, OpLoc); 13308 if (FnExpr.isInvalid()) 13309 return ExprError(); 13310 13311 // Determine the result type. 13312 QualType ResultTy = FnDecl->getReturnType(); 13313 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13314 ResultTy = ResultTy.getNonLValueExprType(Context); 13315 13316 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13317 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13318 FPFeatures, Best->IsADLCandidate); 13319 13320 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13321 FnDecl)) 13322 return ExprError(); 13323 13324 ArrayRef<const Expr *> ArgsArray(Args, 2); 13325 const Expr *ImplicitThis = nullptr; 13326 // Cut off the implicit 'this'. 13327 if (isa<CXXMethodDecl>(FnDecl)) { 13328 ImplicitThis = ArgsArray[0]; 13329 ArgsArray = ArgsArray.slice(1); 13330 } 13331 13332 // Check for a self move. 13333 if (Op == OO_Equal) 13334 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13335 13336 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13337 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13338 VariadicDoesNotApply); 13339 13340 ExprResult R = MaybeBindToTemporary(TheCall); 13341 if (R.isInvalid()) 13342 return ExprError(); 13343 13344 // For a rewritten candidate, we've already reversed the arguments 13345 // if needed. Perform the rest of the rewrite now. 13346 if ((Best->RewriteKind & CRK_DifferentOperator) || 13347 (Op == OO_Spaceship && IsReversed)) { 13348 if (Op == OO_ExclaimEqual) { 13349 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13350 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13351 } else { 13352 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13353 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13354 Expr *ZeroLiteral = 13355 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13356 13357 Sema::CodeSynthesisContext Ctx; 13358 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13359 Ctx.Entity = FnDecl; 13360 pushCodeSynthesisContext(Ctx); 13361 13362 R = CreateOverloadedBinOp( 13363 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13364 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13365 /*AllowRewrittenCandidates=*/false); 13366 13367 popCodeSynthesisContext(); 13368 } 13369 if (R.isInvalid()) 13370 return ExprError(); 13371 } else { 13372 assert(ChosenOp == Op && "unexpected operator name"); 13373 } 13374 13375 // Make a note in the AST if we did any rewriting. 13376 if (Best->RewriteKind != CRK_None) 13377 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13378 13379 return R; 13380 } else { 13381 // We matched a built-in operator. Convert the arguments, then 13382 // break out so that we will build the appropriate built-in 13383 // operator node. 13384 ExprResult ArgsRes0 = PerformImplicitConversion( 13385 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13386 AA_Passing, CCK_ForBuiltinOverloadedOp); 13387 if (ArgsRes0.isInvalid()) 13388 return ExprError(); 13389 Args[0] = ArgsRes0.get(); 13390 13391 ExprResult ArgsRes1 = PerformImplicitConversion( 13392 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13393 AA_Passing, CCK_ForBuiltinOverloadedOp); 13394 if (ArgsRes1.isInvalid()) 13395 return ExprError(); 13396 Args[1] = ArgsRes1.get(); 13397 break; 13398 } 13399 } 13400 13401 case OR_No_Viable_Function: { 13402 // C++ [over.match.oper]p9: 13403 // If the operator is the operator , [...] and there are no 13404 // viable functions, then the operator is assumed to be the 13405 // built-in operator and interpreted according to clause 5. 13406 if (Opc == BO_Comma) 13407 break; 13408 13409 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13410 // compare result using '==' and '<'. 13411 if (DefaultedFn && Opc == BO_Cmp) { 13412 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13413 Args[1], DefaultedFn); 13414 if (E.isInvalid() || E.isUsable()) 13415 return E; 13416 } 13417 13418 // For class as left operand for assignment or compound assignment 13419 // operator do not fall through to handling in built-in, but report that 13420 // no overloaded assignment operator found 13421 ExprResult Result = ExprError(); 13422 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13423 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13424 Args, OpLoc); 13425 if (Args[0]->getType()->isRecordType() && 13426 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13427 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13428 << BinaryOperator::getOpcodeStr(Opc) 13429 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13430 if (Args[0]->getType()->isIncompleteType()) { 13431 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13432 << Args[0]->getType() 13433 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13434 } 13435 } else { 13436 // This is an erroneous use of an operator which can be overloaded by 13437 // a non-member function. Check for non-member operators which were 13438 // defined too late to be candidates. 13439 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13440 // FIXME: Recover by calling the found function. 13441 return ExprError(); 13442 13443 // No viable function; try to create a built-in operation, which will 13444 // produce an error. Then, show the non-viable candidates. 13445 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13446 } 13447 assert(Result.isInvalid() && 13448 "C++ binary operator overloading is missing candidates!"); 13449 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13450 return Result; 13451 } 13452 13453 case OR_Ambiguous: 13454 CandidateSet.NoteCandidates( 13455 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13456 << BinaryOperator::getOpcodeStr(Opc) 13457 << Args[0]->getType() 13458 << Args[1]->getType() 13459 << Args[0]->getSourceRange() 13460 << Args[1]->getSourceRange()), 13461 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13462 OpLoc); 13463 return ExprError(); 13464 13465 case OR_Deleted: 13466 if (isImplicitlyDeleted(Best->Function)) { 13467 FunctionDecl *DeletedFD = Best->Function; 13468 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13469 if (DFK.isSpecialMember()) { 13470 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13471 << Args[0]->getType() << DFK.asSpecialMember(); 13472 } else { 13473 assert(DFK.isComparison()); 13474 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13475 << Args[0]->getType() << DeletedFD; 13476 } 13477 13478 // The user probably meant to call this special member. Just 13479 // explain why it's deleted. 13480 NoteDeletedFunction(DeletedFD); 13481 return ExprError(); 13482 } 13483 CandidateSet.NoteCandidates( 13484 PartialDiagnosticAt( 13485 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13486 << getOperatorSpelling(Best->Function->getDeclName() 13487 .getCXXOverloadedOperator()) 13488 << Args[0]->getSourceRange() 13489 << Args[1]->getSourceRange()), 13490 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13491 OpLoc); 13492 return ExprError(); 13493 } 13494 13495 // We matched a built-in operator; build it. 13496 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13497 } 13498 13499 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13500 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13501 FunctionDecl *DefaultedFn) { 13502 const ComparisonCategoryInfo *Info = 13503 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13504 // If we're not producing a known comparison category type, we can't 13505 // synthesize a three-way comparison. Let the caller diagnose this. 13506 if (!Info) 13507 return ExprResult((Expr*)nullptr); 13508 13509 // If we ever want to perform this synthesis more generally, we will need to 13510 // apply the temporary materialization conversion to the operands. 13511 assert(LHS->isGLValue() && RHS->isGLValue() && 13512 "cannot use prvalue expressions more than once"); 13513 Expr *OrigLHS = LHS; 13514 Expr *OrigRHS = RHS; 13515 13516 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13517 // each of them multiple times below. 13518 LHS = new (Context) 13519 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13520 LHS->getObjectKind(), LHS); 13521 RHS = new (Context) 13522 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13523 RHS->getObjectKind(), RHS); 13524 13525 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13526 DefaultedFn); 13527 if (Eq.isInvalid()) 13528 return ExprError(); 13529 13530 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13531 true, DefaultedFn); 13532 if (Less.isInvalid()) 13533 return ExprError(); 13534 13535 ExprResult Greater; 13536 if (Info->isPartial()) { 13537 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13538 DefaultedFn); 13539 if (Greater.isInvalid()) 13540 return ExprError(); 13541 } 13542 13543 // Form the list of comparisons we're going to perform. 13544 struct Comparison { 13545 ExprResult Cmp; 13546 ComparisonCategoryResult Result; 13547 } Comparisons[4] = 13548 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13549 : ComparisonCategoryResult::Equivalent}, 13550 {Less, ComparisonCategoryResult::Less}, 13551 {Greater, ComparisonCategoryResult::Greater}, 13552 {ExprResult(), ComparisonCategoryResult::Unordered}, 13553 }; 13554 13555 int I = Info->isPartial() ? 3 : 2; 13556 13557 // Combine the comparisons with suitable conditional expressions. 13558 ExprResult Result; 13559 for (; I >= 0; --I) { 13560 // Build a reference to the comparison category constant. 13561 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13562 // FIXME: Missing a constant for a comparison category. Diagnose this? 13563 if (!VI) 13564 return ExprResult((Expr*)nullptr); 13565 ExprResult ThisResult = 13566 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13567 if (ThisResult.isInvalid()) 13568 return ExprError(); 13569 13570 // Build a conditional unless this is the final case. 13571 if (Result.get()) { 13572 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13573 ThisResult.get(), Result.get()); 13574 if (Result.isInvalid()) 13575 return ExprError(); 13576 } else { 13577 Result = ThisResult; 13578 } 13579 } 13580 13581 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13582 // bind the OpaqueValueExprs before they're (repeatedly) used. 13583 Expr *SyntacticForm = new (Context) 13584 BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13585 Result.get()->getValueKind(), 13586 Result.get()->getObjectKind(), OpLoc, FPFeatures); 13587 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13588 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13589 } 13590 13591 ExprResult 13592 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13593 SourceLocation RLoc, 13594 Expr *Base, Expr *Idx) { 13595 Expr *Args[2] = { Base, Idx }; 13596 DeclarationName OpName = 13597 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13598 13599 // If either side is type-dependent, create an appropriate dependent 13600 // expression. 13601 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13602 13603 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13604 // CHECKME: no 'operator' keyword? 13605 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13606 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13607 UnresolvedLookupExpr *Fn 13608 = UnresolvedLookupExpr::Create(Context, NamingClass, 13609 NestedNameSpecifierLoc(), OpNameInfo, 13610 /*ADL*/ true, /*Overloaded*/ false, 13611 UnresolvedSetIterator(), 13612 UnresolvedSetIterator()); 13613 // Can't add any actual overloads yet 13614 13615 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 13616 Context.DependentTy, VK_RValue, RLoc, 13617 FPOptions()); 13618 } 13619 13620 // Handle placeholders on both operands. 13621 if (checkPlaceholderForOverload(*this, Args[0])) 13622 return ExprError(); 13623 if (checkPlaceholderForOverload(*this, Args[1])) 13624 return ExprError(); 13625 13626 // Build an empty overload set. 13627 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13628 13629 // Subscript can only be overloaded as a member function. 13630 13631 // Add operator candidates that are member functions. 13632 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13633 13634 // Add builtin operator candidates. 13635 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13636 13637 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13638 13639 // Perform overload resolution. 13640 OverloadCandidateSet::iterator Best; 13641 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13642 case OR_Success: { 13643 // We found a built-in operator or an overloaded operator. 13644 FunctionDecl *FnDecl = Best->Function; 13645 13646 if (FnDecl) { 13647 // We matched an overloaded operator. Build a call to that 13648 // operator. 13649 13650 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13651 13652 // Convert the arguments. 13653 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13654 ExprResult Arg0 = 13655 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13656 Best->FoundDecl, Method); 13657 if (Arg0.isInvalid()) 13658 return ExprError(); 13659 Args[0] = Arg0.get(); 13660 13661 // Convert the arguments. 13662 ExprResult InputInit 13663 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13664 Context, 13665 FnDecl->getParamDecl(0)), 13666 SourceLocation(), 13667 Args[1]); 13668 if (InputInit.isInvalid()) 13669 return ExprError(); 13670 13671 Args[1] = InputInit.getAs<Expr>(); 13672 13673 // Build the actual expression node. 13674 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13675 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13676 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13677 Best->FoundDecl, 13678 Base, 13679 HadMultipleCandidates, 13680 OpLocInfo.getLoc(), 13681 OpLocInfo.getInfo()); 13682 if (FnExpr.isInvalid()) 13683 return ExprError(); 13684 13685 // Determine the result type 13686 QualType ResultTy = FnDecl->getReturnType(); 13687 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13688 ResultTy = ResultTy.getNonLValueExprType(Context); 13689 13690 CXXOperatorCallExpr *TheCall = 13691 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 13692 Args, ResultTy, VK, RLoc, FPOptions()); 13693 13694 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 13695 return ExprError(); 13696 13697 if (CheckFunctionCall(Method, TheCall, 13698 Method->getType()->castAs<FunctionProtoType>())) 13699 return ExprError(); 13700 13701 return MaybeBindToTemporary(TheCall); 13702 } else { 13703 // We matched a built-in operator. Convert the arguments, then 13704 // break out so that we will build the appropriate built-in 13705 // operator node. 13706 ExprResult ArgsRes0 = PerformImplicitConversion( 13707 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13708 AA_Passing, CCK_ForBuiltinOverloadedOp); 13709 if (ArgsRes0.isInvalid()) 13710 return ExprError(); 13711 Args[0] = ArgsRes0.get(); 13712 13713 ExprResult ArgsRes1 = PerformImplicitConversion( 13714 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13715 AA_Passing, CCK_ForBuiltinOverloadedOp); 13716 if (ArgsRes1.isInvalid()) 13717 return ExprError(); 13718 Args[1] = ArgsRes1.get(); 13719 13720 break; 13721 } 13722 } 13723 13724 case OR_No_Viable_Function: { 13725 PartialDiagnostic PD = CandidateSet.empty() 13726 ? (PDiag(diag::err_ovl_no_oper) 13727 << Args[0]->getType() << /*subscript*/ 0 13728 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 13729 : (PDiag(diag::err_ovl_no_viable_subscript) 13730 << Args[0]->getType() << Args[0]->getSourceRange() 13731 << Args[1]->getSourceRange()); 13732 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 13733 OCD_AllCandidates, Args, "[]", LLoc); 13734 return ExprError(); 13735 } 13736 13737 case OR_Ambiguous: 13738 CandidateSet.NoteCandidates( 13739 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13740 << "[]" << Args[0]->getType() 13741 << Args[1]->getType() 13742 << Args[0]->getSourceRange() 13743 << Args[1]->getSourceRange()), 13744 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 13745 return ExprError(); 13746 13747 case OR_Deleted: 13748 CandidateSet.NoteCandidates( 13749 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 13750 << "[]" << Args[0]->getSourceRange() 13751 << Args[1]->getSourceRange()), 13752 *this, OCD_AllCandidates, Args, "[]", LLoc); 13753 return ExprError(); 13754 } 13755 13756 // We matched a built-in operator; build it. 13757 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 13758 } 13759 13760 /// BuildCallToMemberFunction - Build a call to a member 13761 /// function. MemExpr is the expression that refers to the member 13762 /// function (and includes the object parameter), Args/NumArgs are the 13763 /// arguments to the function call (not including the object 13764 /// parameter). The caller needs to validate that the member 13765 /// expression refers to a non-static member function or an overloaded 13766 /// member function. 13767 ExprResult 13768 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 13769 SourceLocation LParenLoc, 13770 MultiExprArg Args, 13771 SourceLocation RParenLoc) { 13772 assert(MemExprE->getType() == Context.BoundMemberTy || 13773 MemExprE->getType() == Context.OverloadTy); 13774 13775 // Dig out the member expression. This holds both the object 13776 // argument and the member function we're referring to. 13777 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 13778 13779 // Determine whether this is a call to a pointer-to-member function. 13780 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 13781 assert(op->getType() == Context.BoundMemberTy); 13782 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 13783 13784 QualType fnType = 13785 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 13786 13787 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 13788 QualType resultType = proto->getCallResultType(Context); 13789 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 13790 13791 // Check that the object type isn't more qualified than the 13792 // member function we're calling. 13793 Qualifiers funcQuals = proto->getMethodQuals(); 13794 13795 QualType objectType = op->getLHS()->getType(); 13796 if (op->getOpcode() == BO_PtrMemI) 13797 objectType = objectType->castAs<PointerType>()->getPointeeType(); 13798 Qualifiers objectQuals = objectType.getQualifiers(); 13799 13800 Qualifiers difference = objectQuals - funcQuals; 13801 difference.removeObjCGCAttr(); 13802 difference.removeAddressSpace(); 13803 if (difference) { 13804 std::string qualsString = difference.getAsString(); 13805 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 13806 << fnType.getUnqualifiedType() 13807 << qualsString 13808 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 13809 } 13810 13811 CXXMemberCallExpr *call = 13812 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 13813 valueKind, RParenLoc, proto->getNumParams()); 13814 13815 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 13816 call, nullptr)) 13817 return ExprError(); 13818 13819 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 13820 return ExprError(); 13821 13822 if (CheckOtherCall(call, proto)) 13823 return ExprError(); 13824 13825 return MaybeBindToTemporary(call); 13826 } 13827 13828 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 13829 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 13830 RParenLoc); 13831 13832 UnbridgedCastsSet UnbridgedCasts; 13833 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13834 return ExprError(); 13835 13836 MemberExpr *MemExpr; 13837 CXXMethodDecl *Method = nullptr; 13838 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 13839 NestedNameSpecifier *Qualifier = nullptr; 13840 if (isa<MemberExpr>(NakedMemExpr)) { 13841 MemExpr = cast<MemberExpr>(NakedMemExpr); 13842 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 13843 FoundDecl = MemExpr->getFoundDecl(); 13844 Qualifier = MemExpr->getQualifier(); 13845 UnbridgedCasts.restore(); 13846 } else { 13847 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 13848 Qualifier = UnresExpr->getQualifier(); 13849 13850 QualType ObjectType = UnresExpr->getBaseType(); 13851 Expr::Classification ObjectClassification 13852 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 13853 : UnresExpr->getBase()->Classify(Context); 13854 13855 // Add overload candidates 13856 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 13857 OverloadCandidateSet::CSK_Normal); 13858 13859 // FIXME: avoid copy. 13860 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13861 if (UnresExpr->hasExplicitTemplateArgs()) { 13862 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13863 TemplateArgs = &TemplateArgsBuffer; 13864 } 13865 13866 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 13867 E = UnresExpr->decls_end(); I != E; ++I) { 13868 13869 NamedDecl *Func = *I; 13870 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 13871 if (isa<UsingShadowDecl>(Func)) 13872 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 13873 13874 13875 // Microsoft supports direct constructor calls. 13876 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 13877 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 13878 CandidateSet, 13879 /*SuppressUserConversions*/ false); 13880 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 13881 // If explicit template arguments were provided, we can't call a 13882 // non-template member function. 13883 if (TemplateArgs) 13884 continue; 13885 13886 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 13887 ObjectClassification, Args, CandidateSet, 13888 /*SuppressUserConversions=*/false); 13889 } else { 13890 AddMethodTemplateCandidate( 13891 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 13892 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 13893 /*SuppressUserConversions=*/false); 13894 } 13895 } 13896 13897 DeclarationName DeclName = UnresExpr->getMemberName(); 13898 13899 UnbridgedCasts.restore(); 13900 13901 OverloadCandidateSet::iterator Best; 13902 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 13903 Best)) { 13904 case OR_Success: 13905 Method = cast<CXXMethodDecl>(Best->Function); 13906 FoundDecl = Best->FoundDecl; 13907 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13908 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13909 return ExprError(); 13910 // If FoundDecl is different from Method (such as if one is a template 13911 // and the other a specialization), make sure DiagnoseUseOfDecl is 13912 // called on both. 13913 // FIXME: This would be more comprehensively addressed by modifying 13914 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13915 // being used. 13916 if (Method != FoundDecl.getDecl() && 13917 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13918 return ExprError(); 13919 break; 13920 13921 case OR_No_Viable_Function: 13922 CandidateSet.NoteCandidates( 13923 PartialDiagnosticAt( 13924 UnresExpr->getMemberLoc(), 13925 PDiag(diag::err_ovl_no_viable_member_function_in_call) 13926 << DeclName << MemExprE->getSourceRange()), 13927 *this, OCD_AllCandidates, Args); 13928 // FIXME: Leaking incoming expressions! 13929 return ExprError(); 13930 13931 case OR_Ambiguous: 13932 CandidateSet.NoteCandidates( 13933 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13934 PDiag(diag::err_ovl_ambiguous_member_call) 13935 << DeclName << MemExprE->getSourceRange()), 13936 *this, OCD_AmbiguousCandidates, Args); 13937 // FIXME: Leaking incoming expressions! 13938 return ExprError(); 13939 13940 case OR_Deleted: 13941 CandidateSet.NoteCandidates( 13942 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13943 PDiag(diag::err_ovl_deleted_member_call) 13944 << DeclName << MemExprE->getSourceRange()), 13945 *this, OCD_AllCandidates, Args); 13946 // FIXME: Leaking incoming expressions! 13947 return ExprError(); 13948 } 13949 13950 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13951 13952 // If overload resolution picked a static member, build a 13953 // non-member call based on that function. 13954 if (Method->isStatic()) { 13955 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13956 RParenLoc); 13957 } 13958 13959 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13960 } 13961 13962 QualType ResultType = Method->getReturnType(); 13963 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13964 ResultType = ResultType.getNonLValueExprType(Context); 13965 13966 assert(Method && "Member call to something that isn't a method?"); 13967 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 13968 CXXMemberCallExpr *TheCall = 13969 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13970 RParenLoc, Proto->getNumParams()); 13971 13972 // Check for a valid return type. 13973 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13974 TheCall, Method)) 13975 return ExprError(); 13976 13977 // Convert the object argument (for a non-static member function call). 13978 // We only need to do this if there was actually an overload; otherwise 13979 // it was done at lookup. 13980 if (!Method->isStatic()) { 13981 ExprResult ObjectArg = 13982 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13983 FoundDecl, Method); 13984 if (ObjectArg.isInvalid()) 13985 return ExprError(); 13986 MemExpr->setBase(ObjectArg.get()); 13987 } 13988 13989 // Convert the rest of the arguments 13990 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13991 RParenLoc)) 13992 return ExprError(); 13993 13994 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13995 13996 if (CheckFunctionCall(Method, TheCall, Proto)) 13997 return ExprError(); 13998 13999 // In the case the method to call was not selected by the overloading 14000 // resolution process, we still need to handle the enable_if attribute. Do 14001 // that here, so it will not hide previous -- and more relevant -- errors. 14002 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14003 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 14004 Diag(MemE->getMemberLoc(), 14005 diag::err_ovl_no_viable_member_function_in_call) 14006 << Method << Method->getSourceRange(); 14007 Diag(Method->getLocation(), 14008 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14009 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14010 return ExprError(); 14011 } 14012 } 14013 14014 if ((isa<CXXConstructorDecl>(CurContext) || 14015 isa<CXXDestructorDecl>(CurContext)) && 14016 TheCall->getMethodDecl()->isPure()) { 14017 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14018 14019 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14020 MemExpr->performsVirtualDispatch(getLangOpts())) { 14021 Diag(MemExpr->getBeginLoc(), 14022 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14023 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14024 << MD->getParent()->getDeclName(); 14025 14026 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14027 if (getLangOpts().AppleKext) 14028 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14029 << MD->getParent()->getDeclName() << MD->getDeclName(); 14030 } 14031 } 14032 14033 if (CXXDestructorDecl *DD = 14034 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14035 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14036 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14037 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14038 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14039 MemExpr->getMemberLoc()); 14040 } 14041 14042 return MaybeBindToTemporary(TheCall); 14043 } 14044 14045 /// BuildCallToObjectOfClassType - Build a call to an object of class 14046 /// type (C++ [over.call.object]), which can end up invoking an 14047 /// overloaded function call operator (@c operator()) or performing a 14048 /// user-defined conversion on the object argument. 14049 ExprResult 14050 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14051 SourceLocation LParenLoc, 14052 MultiExprArg Args, 14053 SourceLocation RParenLoc) { 14054 if (checkPlaceholderForOverload(*this, Obj)) 14055 return ExprError(); 14056 ExprResult Object = Obj; 14057 14058 UnbridgedCastsSet UnbridgedCasts; 14059 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14060 return ExprError(); 14061 14062 assert(Object.get()->getType()->isRecordType() && 14063 "Requires object type argument"); 14064 14065 // C++ [over.call.object]p1: 14066 // If the primary-expression E in the function call syntax 14067 // evaluates to a class object of type "cv T", then the set of 14068 // candidate functions includes at least the function call 14069 // operators of T. The function call operators of T are obtained by 14070 // ordinary lookup of the name operator() in the context of 14071 // (E).operator(). 14072 OverloadCandidateSet CandidateSet(LParenLoc, 14073 OverloadCandidateSet::CSK_Operator); 14074 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14075 14076 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14077 diag::err_incomplete_object_call, Object.get())) 14078 return true; 14079 14080 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14081 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14082 LookupQualifiedName(R, Record->getDecl()); 14083 R.suppressDiagnostics(); 14084 14085 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14086 Oper != OperEnd; ++Oper) { 14087 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14088 Object.get()->Classify(Context), Args, CandidateSet, 14089 /*SuppressUserConversion=*/false); 14090 } 14091 14092 // C++ [over.call.object]p2: 14093 // In addition, for each (non-explicit in C++0x) conversion function 14094 // declared in T of the form 14095 // 14096 // operator conversion-type-id () cv-qualifier; 14097 // 14098 // where cv-qualifier is the same cv-qualification as, or a 14099 // greater cv-qualification than, cv, and where conversion-type-id 14100 // denotes the type "pointer to function of (P1,...,Pn) returning 14101 // R", or the type "reference to pointer to function of 14102 // (P1,...,Pn) returning R", or the type "reference to function 14103 // of (P1,...,Pn) returning R", a surrogate call function [...] 14104 // is also considered as a candidate function. Similarly, 14105 // surrogate call functions are added to the set of candidate 14106 // functions for each conversion function declared in an 14107 // accessible base class provided the function is not hidden 14108 // within T by another intervening declaration. 14109 const auto &Conversions = 14110 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14111 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14112 NamedDecl *D = *I; 14113 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14114 if (isa<UsingShadowDecl>(D)) 14115 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14116 14117 // Skip over templated conversion functions; they aren't 14118 // surrogates. 14119 if (isa<FunctionTemplateDecl>(D)) 14120 continue; 14121 14122 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14123 if (!Conv->isExplicit()) { 14124 // Strip the reference type (if any) and then the pointer type (if 14125 // any) to get down to what might be a function type. 14126 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14127 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14128 ConvType = ConvPtrType->getPointeeType(); 14129 14130 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14131 { 14132 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14133 Object.get(), Args, CandidateSet); 14134 } 14135 } 14136 } 14137 14138 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14139 14140 // Perform overload resolution. 14141 OverloadCandidateSet::iterator Best; 14142 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14143 Best)) { 14144 case OR_Success: 14145 // Overload resolution succeeded; we'll build the appropriate call 14146 // below. 14147 break; 14148 14149 case OR_No_Viable_Function: { 14150 PartialDiagnostic PD = 14151 CandidateSet.empty() 14152 ? (PDiag(diag::err_ovl_no_oper) 14153 << Object.get()->getType() << /*call*/ 1 14154 << Object.get()->getSourceRange()) 14155 : (PDiag(diag::err_ovl_no_viable_object_call) 14156 << Object.get()->getType() << Object.get()->getSourceRange()); 14157 CandidateSet.NoteCandidates( 14158 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14159 OCD_AllCandidates, Args); 14160 break; 14161 } 14162 case OR_Ambiguous: 14163 CandidateSet.NoteCandidates( 14164 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14165 PDiag(diag::err_ovl_ambiguous_object_call) 14166 << Object.get()->getType() 14167 << Object.get()->getSourceRange()), 14168 *this, OCD_AmbiguousCandidates, Args); 14169 break; 14170 14171 case OR_Deleted: 14172 CandidateSet.NoteCandidates( 14173 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14174 PDiag(diag::err_ovl_deleted_object_call) 14175 << Object.get()->getType() 14176 << Object.get()->getSourceRange()), 14177 *this, OCD_AllCandidates, Args); 14178 break; 14179 } 14180 14181 if (Best == CandidateSet.end()) 14182 return true; 14183 14184 UnbridgedCasts.restore(); 14185 14186 if (Best->Function == nullptr) { 14187 // Since there is no function declaration, this is one of the 14188 // surrogate candidates. Dig out the conversion function. 14189 CXXConversionDecl *Conv 14190 = cast<CXXConversionDecl>( 14191 Best->Conversions[0].UserDefined.ConversionFunction); 14192 14193 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14194 Best->FoundDecl); 14195 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14196 return ExprError(); 14197 assert(Conv == Best->FoundDecl.getDecl() && 14198 "Found Decl & conversion-to-functionptr should be same, right?!"); 14199 // We selected one of the surrogate functions that converts the 14200 // object parameter to a function pointer. Perform the conversion 14201 // on the object argument, then let BuildCallExpr finish the job. 14202 14203 // Create an implicit member expr to refer to the conversion operator. 14204 // and then call it. 14205 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14206 Conv, HadMultipleCandidates); 14207 if (Call.isInvalid()) 14208 return ExprError(); 14209 // Record usage of conversion in an implicit cast. 14210 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 14211 CK_UserDefinedConversion, Call.get(), 14212 nullptr, VK_RValue); 14213 14214 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14215 } 14216 14217 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14218 14219 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14220 // that calls this method, using Object for the implicit object 14221 // parameter and passing along the remaining arguments. 14222 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14223 14224 // An error diagnostic has already been printed when parsing the declaration. 14225 if (Method->isInvalidDecl()) 14226 return ExprError(); 14227 14228 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14229 unsigned NumParams = Proto->getNumParams(); 14230 14231 DeclarationNameInfo OpLocInfo( 14232 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14233 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14234 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14235 Obj, HadMultipleCandidates, 14236 OpLocInfo.getLoc(), 14237 OpLocInfo.getInfo()); 14238 if (NewFn.isInvalid()) 14239 return true; 14240 14241 // The number of argument slots to allocate in the call. If we have default 14242 // arguments we need to allocate space for them as well. We additionally 14243 // need one more slot for the object parameter. 14244 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14245 14246 // Build the full argument list for the method call (the implicit object 14247 // parameter is placed at the beginning of the list). 14248 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14249 14250 bool IsError = false; 14251 14252 // Initialize the implicit object parameter. 14253 ExprResult ObjRes = 14254 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14255 Best->FoundDecl, Method); 14256 if (ObjRes.isInvalid()) 14257 IsError = true; 14258 else 14259 Object = ObjRes; 14260 MethodArgs[0] = Object.get(); 14261 14262 // Check the argument types. 14263 for (unsigned i = 0; i != NumParams; i++) { 14264 Expr *Arg; 14265 if (i < Args.size()) { 14266 Arg = Args[i]; 14267 14268 // Pass the argument. 14269 14270 ExprResult InputInit 14271 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14272 Context, 14273 Method->getParamDecl(i)), 14274 SourceLocation(), Arg); 14275 14276 IsError |= InputInit.isInvalid(); 14277 Arg = InputInit.getAs<Expr>(); 14278 } else { 14279 ExprResult DefArg 14280 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14281 if (DefArg.isInvalid()) { 14282 IsError = true; 14283 break; 14284 } 14285 14286 Arg = DefArg.getAs<Expr>(); 14287 } 14288 14289 MethodArgs[i + 1] = Arg; 14290 } 14291 14292 // If this is a variadic call, handle args passed through "...". 14293 if (Proto->isVariadic()) { 14294 // Promote the arguments (C99 6.5.2.2p7). 14295 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14296 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14297 nullptr); 14298 IsError |= Arg.isInvalid(); 14299 MethodArgs[i + 1] = Arg.get(); 14300 } 14301 } 14302 14303 if (IsError) 14304 return true; 14305 14306 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14307 14308 // Once we've built TheCall, all of the expressions are properly owned. 14309 QualType ResultTy = Method->getReturnType(); 14310 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14311 ResultTy = ResultTy.getNonLValueExprType(Context); 14312 14313 CXXOperatorCallExpr *TheCall = 14314 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 14315 ResultTy, VK, RParenLoc, FPOptions()); 14316 14317 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14318 return true; 14319 14320 if (CheckFunctionCall(Method, TheCall, Proto)) 14321 return true; 14322 14323 return MaybeBindToTemporary(TheCall); 14324 } 14325 14326 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14327 /// (if one exists), where @c Base is an expression of class type and 14328 /// @c Member is the name of the member we're trying to find. 14329 ExprResult 14330 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14331 bool *NoArrowOperatorFound) { 14332 assert(Base->getType()->isRecordType() && 14333 "left-hand side must have class type"); 14334 14335 if (checkPlaceholderForOverload(*this, Base)) 14336 return ExprError(); 14337 14338 SourceLocation Loc = Base->getExprLoc(); 14339 14340 // C++ [over.ref]p1: 14341 // 14342 // [...] An expression x->m is interpreted as (x.operator->())->m 14343 // for a class object x of type T if T::operator->() exists and if 14344 // the operator is selected as the best match function by the 14345 // overload resolution mechanism (13.3). 14346 DeclarationName OpName = 14347 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14348 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14349 14350 if (RequireCompleteType(Loc, Base->getType(), 14351 diag::err_typecheck_incomplete_tag, Base)) 14352 return ExprError(); 14353 14354 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14355 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14356 R.suppressDiagnostics(); 14357 14358 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14359 Oper != OperEnd; ++Oper) { 14360 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14361 None, CandidateSet, /*SuppressUserConversion=*/false); 14362 } 14363 14364 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14365 14366 // Perform overload resolution. 14367 OverloadCandidateSet::iterator Best; 14368 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14369 case OR_Success: 14370 // Overload resolution succeeded; we'll build the call below. 14371 break; 14372 14373 case OR_No_Viable_Function: { 14374 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14375 if (CandidateSet.empty()) { 14376 QualType BaseType = Base->getType(); 14377 if (NoArrowOperatorFound) { 14378 // Report this specific error to the caller instead of emitting a 14379 // diagnostic, as requested. 14380 *NoArrowOperatorFound = true; 14381 return ExprError(); 14382 } 14383 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14384 << BaseType << Base->getSourceRange(); 14385 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14386 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14387 << FixItHint::CreateReplacement(OpLoc, "."); 14388 } 14389 } else 14390 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14391 << "operator->" << Base->getSourceRange(); 14392 CandidateSet.NoteCandidates(*this, Base, Cands); 14393 return ExprError(); 14394 } 14395 case OR_Ambiguous: 14396 CandidateSet.NoteCandidates( 14397 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14398 << "->" << Base->getType() 14399 << Base->getSourceRange()), 14400 *this, OCD_AmbiguousCandidates, Base); 14401 return ExprError(); 14402 14403 case OR_Deleted: 14404 CandidateSet.NoteCandidates( 14405 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14406 << "->" << Base->getSourceRange()), 14407 *this, OCD_AllCandidates, Base); 14408 return ExprError(); 14409 } 14410 14411 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14412 14413 // Convert the object parameter. 14414 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14415 ExprResult BaseResult = 14416 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14417 Best->FoundDecl, Method); 14418 if (BaseResult.isInvalid()) 14419 return ExprError(); 14420 Base = BaseResult.get(); 14421 14422 // Build the operator call. 14423 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14424 Base, HadMultipleCandidates, OpLoc); 14425 if (FnExpr.isInvalid()) 14426 return ExprError(); 14427 14428 QualType ResultTy = Method->getReturnType(); 14429 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14430 ResultTy = ResultTy.getNonLValueExprType(Context); 14431 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14432 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 14433 14434 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14435 return ExprError(); 14436 14437 if (CheckFunctionCall(Method, TheCall, 14438 Method->getType()->castAs<FunctionProtoType>())) 14439 return ExprError(); 14440 14441 return MaybeBindToTemporary(TheCall); 14442 } 14443 14444 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14445 /// a literal operator described by the provided lookup results. 14446 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14447 DeclarationNameInfo &SuffixInfo, 14448 ArrayRef<Expr*> Args, 14449 SourceLocation LitEndLoc, 14450 TemplateArgumentListInfo *TemplateArgs) { 14451 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14452 14453 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14454 OverloadCandidateSet::CSK_Normal); 14455 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14456 TemplateArgs); 14457 14458 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14459 14460 // Perform overload resolution. This will usually be trivial, but might need 14461 // to perform substitutions for a literal operator template. 14462 OverloadCandidateSet::iterator Best; 14463 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14464 case OR_Success: 14465 case OR_Deleted: 14466 break; 14467 14468 case OR_No_Viable_Function: 14469 CandidateSet.NoteCandidates( 14470 PartialDiagnosticAt(UDSuffixLoc, 14471 PDiag(diag::err_ovl_no_viable_function_in_call) 14472 << R.getLookupName()), 14473 *this, OCD_AllCandidates, Args); 14474 return ExprError(); 14475 14476 case OR_Ambiguous: 14477 CandidateSet.NoteCandidates( 14478 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14479 << R.getLookupName()), 14480 *this, OCD_AmbiguousCandidates, Args); 14481 return ExprError(); 14482 } 14483 14484 FunctionDecl *FD = Best->Function; 14485 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14486 nullptr, HadMultipleCandidates, 14487 SuffixInfo.getLoc(), 14488 SuffixInfo.getInfo()); 14489 if (Fn.isInvalid()) 14490 return true; 14491 14492 // Check the argument types. This should almost always be a no-op, except 14493 // that array-to-pointer decay is applied to string literals. 14494 Expr *ConvArgs[2]; 14495 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14496 ExprResult InputInit = PerformCopyInitialization( 14497 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14498 SourceLocation(), Args[ArgIdx]); 14499 if (InputInit.isInvalid()) 14500 return true; 14501 ConvArgs[ArgIdx] = InputInit.get(); 14502 } 14503 14504 QualType ResultTy = FD->getReturnType(); 14505 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14506 ResultTy = ResultTy.getNonLValueExprType(Context); 14507 14508 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14509 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14510 VK, LitEndLoc, UDSuffixLoc); 14511 14512 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14513 return ExprError(); 14514 14515 if (CheckFunctionCall(FD, UDL, nullptr)) 14516 return ExprError(); 14517 14518 return MaybeBindToTemporary(UDL); 14519 } 14520 14521 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14522 /// given LookupResult is non-empty, it is assumed to describe a member which 14523 /// will be invoked. Otherwise, the function will be found via argument 14524 /// dependent lookup. 14525 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14526 /// otherwise CallExpr is set to ExprError() and some non-success value 14527 /// is returned. 14528 Sema::ForRangeStatus 14529 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14530 SourceLocation RangeLoc, 14531 const DeclarationNameInfo &NameInfo, 14532 LookupResult &MemberLookup, 14533 OverloadCandidateSet *CandidateSet, 14534 Expr *Range, ExprResult *CallExpr) { 14535 Scope *S = nullptr; 14536 14537 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14538 if (!MemberLookup.empty()) { 14539 ExprResult MemberRef = 14540 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14541 /*IsPtr=*/false, CXXScopeSpec(), 14542 /*TemplateKWLoc=*/SourceLocation(), 14543 /*FirstQualifierInScope=*/nullptr, 14544 MemberLookup, 14545 /*TemplateArgs=*/nullptr, S); 14546 if (MemberRef.isInvalid()) { 14547 *CallExpr = ExprError(); 14548 return FRS_DiagnosticIssued; 14549 } 14550 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14551 if (CallExpr->isInvalid()) { 14552 *CallExpr = ExprError(); 14553 return FRS_DiagnosticIssued; 14554 } 14555 } else { 14556 UnresolvedSet<0> FoundNames; 14557 UnresolvedLookupExpr *Fn = 14558 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 14559 NestedNameSpecifierLoc(), NameInfo, 14560 /*NeedsADL=*/true, /*Overloaded=*/false, 14561 FoundNames.begin(), FoundNames.end()); 14562 14563 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14564 CandidateSet, CallExpr); 14565 if (CandidateSet->empty() || CandidateSetError) { 14566 *CallExpr = ExprError(); 14567 return FRS_NoViableFunction; 14568 } 14569 OverloadCandidateSet::iterator Best; 14570 OverloadingResult OverloadResult = 14571 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14572 14573 if (OverloadResult == OR_No_Viable_Function) { 14574 *CallExpr = ExprError(); 14575 return FRS_NoViableFunction; 14576 } 14577 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14578 Loc, nullptr, CandidateSet, &Best, 14579 OverloadResult, 14580 /*AllowTypoCorrection=*/false); 14581 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14582 *CallExpr = ExprError(); 14583 return FRS_DiagnosticIssued; 14584 } 14585 } 14586 return FRS_Success; 14587 } 14588 14589 14590 /// FixOverloadedFunctionReference - E is an expression that refers to 14591 /// a C++ overloaded function (possibly with some parentheses and 14592 /// perhaps a '&' around it). We have resolved the overloaded function 14593 /// to the function declaration Fn, so patch up the expression E to 14594 /// refer (possibly indirectly) to Fn. Returns the new expr. 14595 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14596 FunctionDecl *Fn) { 14597 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14598 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14599 Found, Fn); 14600 if (SubExpr == PE->getSubExpr()) 14601 return PE; 14602 14603 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14604 } 14605 14606 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14607 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14608 Found, Fn); 14609 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 14610 SubExpr->getType()) && 14611 "Implicit cast type cannot be determined from overload"); 14612 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 14613 if (SubExpr == ICE->getSubExpr()) 14614 return ICE; 14615 14616 return ImplicitCastExpr::Create(Context, ICE->getType(), 14617 ICE->getCastKind(), 14618 SubExpr, nullptr, 14619 ICE->getValueKind()); 14620 } 14621 14622 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14623 if (!GSE->isResultDependent()) { 14624 Expr *SubExpr = 14625 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14626 if (SubExpr == GSE->getResultExpr()) 14627 return GSE; 14628 14629 // Replace the resulting type information before rebuilding the generic 14630 // selection expression. 14631 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14632 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14633 unsigned ResultIdx = GSE->getResultIndex(); 14634 AssocExprs[ResultIdx] = SubExpr; 14635 14636 return GenericSelectionExpr::Create( 14637 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14638 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14639 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14640 ResultIdx); 14641 } 14642 // Rather than fall through to the unreachable, return the original generic 14643 // selection expression. 14644 return GSE; 14645 } 14646 14647 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14648 assert(UnOp->getOpcode() == UO_AddrOf && 14649 "Can only take the address of an overloaded function"); 14650 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14651 if (Method->isStatic()) { 14652 // Do nothing: static member functions aren't any different 14653 // from non-member functions. 14654 } else { 14655 // Fix the subexpression, which really has to be an 14656 // UnresolvedLookupExpr holding an overloaded member function 14657 // or template. 14658 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14659 Found, Fn); 14660 if (SubExpr == UnOp->getSubExpr()) 14661 return UnOp; 14662 14663 assert(isa<DeclRefExpr>(SubExpr) 14664 && "fixed to something other than a decl ref"); 14665 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 14666 && "fixed to a member ref with no nested name qualifier"); 14667 14668 // We have taken the address of a pointer to member 14669 // function. Perform the computation here so that we get the 14670 // appropriate pointer to member type. 14671 QualType ClassType 14672 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14673 QualType MemPtrType 14674 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 14675 // Under the MS ABI, lock down the inheritance model now. 14676 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14677 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 14678 14679 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 14680 VK_RValue, OK_Ordinary, 14681 UnOp->getOperatorLoc(), false); 14682 } 14683 } 14684 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14685 Found, Fn); 14686 if (SubExpr == UnOp->getSubExpr()) 14687 return UnOp; 14688 14689 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 14690 Context.getPointerType(SubExpr->getType()), 14691 VK_RValue, OK_Ordinary, 14692 UnOp->getOperatorLoc(), false); 14693 } 14694 14695 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14696 // FIXME: avoid copy. 14697 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14698 if (ULE->hasExplicitTemplateArgs()) { 14699 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 14700 TemplateArgs = &TemplateArgsBuffer; 14701 } 14702 14703 DeclRefExpr *DRE = 14704 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 14705 ULE->getQualifierLoc(), Found.getDecl(), 14706 ULE->getTemplateKeywordLoc(), TemplateArgs); 14707 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 14708 return DRE; 14709 } 14710 14711 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 14712 // FIXME: avoid copy. 14713 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14714 if (MemExpr->hasExplicitTemplateArgs()) { 14715 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14716 TemplateArgs = &TemplateArgsBuffer; 14717 } 14718 14719 Expr *Base; 14720 14721 // If we're filling in a static method where we used to have an 14722 // implicit member access, rewrite to a simple decl ref. 14723 if (MemExpr->isImplicitAccess()) { 14724 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14725 DeclRefExpr *DRE = BuildDeclRefExpr( 14726 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 14727 MemExpr->getQualifierLoc(), Found.getDecl(), 14728 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 14729 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 14730 return DRE; 14731 } else { 14732 SourceLocation Loc = MemExpr->getMemberLoc(); 14733 if (MemExpr->getQualifier()) 14734 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 14735 Base = 14736 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 14737 } 14738 } else 14739 Base = MemExpr->getBase(); 14740 14741 ExprValueKind valueKind; 14742 QualType type; 14743 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14744 valueKind = VK_LValue; 14745 type = Fn->getType(); 14746 } else { 14747 valueKind = VK_RValue; 14748 type = Context.BoundMemberTy; 14749 } 14750 14751 return BuildMemberExpr( 14752 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 14753 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 14754 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 14755 type, valueKind, OK_Ordinary, TemplateArgs); 14756 } 14757 14758 llvm_unreachable("Invalid reference to overloaded function"); 14759 } 14760 14761 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 14762 DeclAccessPair Found, 14763 FunctionDecl *Fn) { 14764 return FixOverloadedFunctionReference(E.get(), Found, Fn); 14765 } 14766