1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides Sema routines for C++ overloading. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Sema/Overload.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/DeclObjC.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/TypeOrdering.h" 21 #include "clang/Basic/Diagnostic.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Basic/TargetInfo.h" 25 #include "clang/Sema/Initialization.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/SemaInternal.h" 28 #include "clang/Sema/Template.h" 29 #include "clang/Sema/TemplateDeduction.h" 30 #include "llvm/ADT/DenseSet.h" 31 #include "llvm/ADT/Optional.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 using AllowedExplicit = Sema::AllowedExplicit; 42 43 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 44 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 45 return P->hasAttr<PassObjectSizeAttr>(); 46 }); 47 } 48 49 /// A convenience routine for creating a decayed reference to a function. 50 static ExprResult 51 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 52 const Expr *Base, bool HadMultipleCandidates, 53 SourceLocation Loc = SourceLocation(), 54 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 55 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 56 return ExprError(); 57 // If FoundDecl is different from Fn (such as if one is a template 58 // and the other a specialization), make sure DiagnoseUseOfDecl is 59 // called on both. 60 // FIXME: This would be more comprehensively addressed by modifying 61 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 62 // being used. 63 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 64 return ExprError(); 65 DeclRefExpr *DRE = new (S.Context) 66 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 67 if (HadMultipleCandidates) 68 DRE->setHadMultipleCandidates(true); 69 70 S.MarkDeclRefReferenced(DRE, Base); 71 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 72 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 73 S.ResolveExceptionSpec(Loc, FPT); 74 DRE->setType(Fn->getType()); 75 } 76 } 77 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 78 CK_FunctionToPointerDecay); 79 } 80 81 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 82 bool InOverloadResolution, 83 StandardConversionSequence &SCS, 84 bool CStyle, 85 bool AllowObjCWritebackConversion); 86 87 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 88 QualType &ToType, 89 bool InOverloadResolution, 90 StandardConversionSequence &SCS, 91 bool CStyle); 92 static OverloadingResult 93 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 94 UserDefinedConversionSequence& User, 95 OverloadCandidateSet& Conversions, 96 AllowedExplicit AllowExplicit, 97 bool AllowObjCConversionOnExplicit); 98 99 static ImplicitConversionSequence::CompareKind 100 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 101 const StandardConversionSequence& SCS1, 102 const StandardConversionSequence& SCS2); 103 104 static ImplicitConversionSequence::CompareKind 105 CompareQualificationConversions(Sema &S, 106 const StandardConversionSequence& SCS1, 107 const StandardConversionSequence& SCS2); 108 109 static ImplicitConversionSequence::CompareKind 110 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 111 const StandardConversionSequence& SCS1, 112 const StandardConversionSequence& SCS2); 113 114 /// GetConversionRank - Retrieve the implicit conversion rank 115 /// corresponding to the given implicit conversion kind. 116 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 117 static const ImplicitConversionRank 118 Rank[(int)ICK_Num_Conversion_Kinds] = { 119 ICR_Exact_Match, 120 ICR_Exact_Match, 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Exact_Match, 125 ICR_Promotion, 126 ICR_Promotion, 127 ICR_Promotion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_OCL_Scalar_Widening, 139 ICR_Complex_Real_Conversion, 140 ICR_Conversion, 141 ICR_Conversion, 142 ICR_Writeback_Conversion, 143 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 144 // it was omitted by the patch that added 145 // ICK_Zero_Event_Conversion 146 ICR_C_Conversion, 147 ICR_C_Conversion_Extension 148 }; 149 return Rank[(int)Kind]; 150 } 151 152 /// GetImplicitConversionName - Return the name of this kind of 153 /// implicit conversion. 154 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 155 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 156 "No conversion", 157 "Lvalue-to-rvalue", 158 "Array-to-pointer", 159 "Function-to-pointer", 160 "Function pointer conversion", 161 "Qualification", 162 "Integral promotion", 163 "Floating point promotion", 164 "Complex promotion", 165 "Integral conversion", 166 "Floating conversion", 167 "Complex conversion", 168 "Floating-integral conversion", 169 "Pointer conversion", 170 "Pointer-to-member conversion", 171 "Boolean conversion", 172 "Compatible-types conversion", 173 "Derived-to-base conversion", 174 "Vector conversion", 175 "Vector splat", 176 "Complex-real conversion", 177 "Block Pointer conversion", 178 "Transparent Union Conversion", 179 "Writeback conversion", 180 "OpenCL Zero Event Conversion", 181 "C specific type conversion", 182 "Incompatible pointer conversion" 183 }; 184 return Name[Kind]; 185 } 186 187 /// StandardConversionSequence - Set the standard conversion 188 /// sequence to the identity conversion. 189 void StandardConversionSequence::setAsIdentityConversion() { 190 First = ICK_Identity; 191 Second = ICK_Identity; 192 Third = ICK_Identity; 193 DeprecatedStringLiteralToCharPtr = false; 194 QualificationIncludesObjCLifetime = false; 195 ReferenceBinding = false; 196 DirectBinding = false; 197 IsLvalueReference = true; 198 BindsToFunctionLvalue = false; 199 BindsToRvalue = false; 200 BindsImplicitObjectArgumentWithoutRefQualifier = false; 201 ObjCLifetimeConversionBinding = false; 202 CopyConstructor = nullptr; 203 } 204 205 /// getRank - Retrieve the rank of this standard conversion sequence 206 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 207 /// implicit conversions. 208 ImplicitConversionRank StandardConversionSequence::getRank() const { 209 ImplicitConversionRank Rank = ICR_Exact_Match; 210 if (GetConversionRank(First) > Rank) 211 Rank = GetConversionRank(First); 212 if (GetConversionRank(Second) > Rank) 213 Rank = GetConversionRank(Second); 214 if (GetConversionRank(Third) > Rank) 215 Rank = GetConversionRank(Third); 216 return Rank; 217 } 218 219 /// isPointerConversionToBool - Determines whether this conversion is 220 /// a conversion of a pointer or pointer-to-member to bool. This is 221 /// used as part of the ranking of standard conversion sequences 222 /// (C++ 13.3.3.2p4). 223 bool StandardConversionSequence::isPointerConversionToBool() const { 224 // Note that FromType has not necessarily been transformed by the 225 // array-to-pointer or function-to-pointer implicit conversions, so 226 // check for their presence as well as checking whether FromType is 227 // a pointer. 228 if (getToType(1)->isBooleanType() && 229 (getFromType()->isPointerType() || 230 getFromType()->isMemberPointerType() || 231 getFromType()->isObjCObjectPointerType() || 232 getFromType()->isBlockPointerType() || 233 getFromType()->isNullPtrType() || 234 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 235 return true; 236 237 return false; 238 } 239 240 /// isPointerConversionToVoidPointer - Determines whether this 241 /// conversion is a conversion of a pointer to a void pointer. This is 242 /// used as part of the ranking of standard conversion sequences (C++ 243 /// 13.3.3.2p4). 244 bool 245 StandardConversionSequence:: 246 isPointerConversionToVoidPointer(ASTContext& Context) const { 247 QualType FromType = getFromType(); 248 QualType ToType = getToType(1); 249 250 // Note that FromType has not necessarily been transformed by the 251 // array-to-pointer implicit conversion, so check for its presence 252 // and redo the conversion to get a pointer. 253 if (First == ICK_Array_To_Pointer) 254 FromType = Context.getArrayDecayedType(FromType); 255 256 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 257 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 258 return ToPtrType->getPointeeType()->isVoidType(); 259 260 return false; 261 } 262 263 /// Skip any implicit casts which could be either part of a narrowing conversion 264 /// or after one in an implicit conversion. 265 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 266 const Expr *Converted) { 267 // We can have cleanups wrapping the converted expression; these need to be 268 // preserved so that destructors run if necessary. 269 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 270 Expr *Inner = 271 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 272 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 273 EWC->getObjects()); 274 } 275 276 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 277 switch (ICE->getCastKind()) { 278 case CK_NoOp: 279 case CK_IntegralCast: 280 case CK_IntegralToBoolean: 281 case CK_IntegralToFloating: 282 case CK_BooleanToSignedIntegral: 283 case CK_FloatingToIntegral: 284 case CK_FloatingToBoolean: 285 case CK_FloatingCast: 286 Converted = ICE->getSubExpr(); 287 continue; 288 289 default: 290 return Converted; 291 } 292 } 293 294 return Converted; 295 } 296 297 /// Check if this standard conversion sequence represents a narrowing 298 /// conversion, according to C++11 [dcl.init.list]p7. 299 /// 300 /// \param Ctx The AST context. 301 /// \param Converted The result of applying this standard conversion sequence. 302 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 303 /// value of the expression prior to the narrowing conversion. 304 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 305 /// type of the expression prior to the narrowing conversion. 306 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 307 /// from floating point types to integral types should be ignored. 308 NarrowingKind StandardConversionSequence::getNarrowingKind( 309 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 310 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 311 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 312 313 // C++11 [dcl.init.list]p7: 314 // A narrowing conversion is an implicit conversion ... 315 QualType FromType = getToType(0); 316 QualType ToType = getToType(1); 317 318 // A conversion to an enumeration type is narrowing if the conversion to 319 // the underlying type is narrowing. This only arises for expressions of 320 // the form 'Enum{init}'. 321 if (auto *ET = ToType->getAs<EnumType>()) 322 ToType = ET->getDecl()->getIntegerType(); 323 324 switch (Second) { 325 // 'bool' is an integral type; dispatch to the right place to handle it. 326 case ICK_Boolean_Conversion: 327 if (FromType->isRealFloatingType()) 328 goto FloatingIntegralConversion; 329 if (FromType->isIntegralOrUnscopedEnumerationType()) 330 goto IntegralConversion; 331 // Boolean conversions can be from pointers and pointers to members 332 // [conv.bool], and those aren't considered narrowing conversions. 333 return NK_Not_Narrowing; 334 335 // -- from a floating-point type to an integer type, or 336 // 337 // -- from an integer type or unscoped enumeration type to a floating-point 338 // type, except where the source is a constant expression and the actual 339 // value after conversion will fit into the target type and will produce 340 // the original value when converted back to the original type, or 341 case ICK_Floating_Integral: 342 FloatingIntegralConversion: 343 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 344 return NK_Type_Narrowing; 345 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 346 ToType->isRealFloatingType()) { 347 if (IgnoreFloatToIntegralConversion) 348 return NK_Not_Narrowing; 349 llvm::APSInt IntConstantValue; 350 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 351 assert(Initializer && "Unknown conversion expression"); 352 353 // If it's value-dependent, we can't tell whether it's narrowing. 354 if (Initializer->isValueDependent()) 355 return NK_Dependent_Narrowing; 356 357 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 358 // Convert the integer to the floating type. 359 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 360 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 361 llvm::APFloat::rmNearestTiesToEven); 362 // And back. 363 llvm::APSInt ConvertedValue = IntConstantValue; 364 bool ignored; 365 Result.convertToInteger(ConvertedValue, 366 llvm::APFloat::rmTowardZero, &ignored); 367 // If the resulting value is different, this was a narrowing conversion. 368 if (IntConstantValue != ConvertedValue) { 369 ConstantValue = APValue(IntConstantValue); 370 ConstantType = Initializer->getType(); 371 return NK_Constant_Narrowing; 372 } 373 } else { 374 // Variables are always narrowings. 375 return NK_Variable_Narrowing; 376 } 377 } 378 return NK_Not_Narrowing; 379 380 // -- from long double to double or float, or from double to float, except 381 // where the source is a constant expression and the actual value after 382 // conversion is within the range of values that can be represented (even 383 // if it cannot be represented exactly), or 384 case ICK_Floating_Conversion: 385 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 386 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 387 // FromType is larger than ToType. 388 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 389 390 // If it's value-dependent, we can't tell whether it's narrowing. 391 if (Initializer->isValueDependent()) 392 return NK_Dependent_Narrowing; 393 394 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 395 // Constant! 396 assert(ConstantValue.isFloat()); 397 llvm::APFloat FloatVal = ConstantValue.getFloat(); 398 // Convert the source value into the target type. 399 bool ignored; 400 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 401 Ctx.getFloatTypeSemantics(ToType), 402 llvm::APFloat::rmNearestTiesToEven, &ignored); 403 // If there was no overflow, the source value is within the range of 404 // values that can be represented. 405 if (ConvertStatus & llvm::APFloat::opOverflow) { 406 ConstantType = Initializer->getType(); 407 return NK_Constant_Narrowing; 408 } 409 } else { 410 return NK_Variable_Narrowing; 411 } 412 } 413 return NK_Not_Narrowing; 414 415 // -- from an integer type or unscoped enumeration type to an integer type 416 // that cannot represent all the values of the original type, except where 417 // the source is a constant expression and the actual value after 418 // conversion will fit into the target type and will produce the original 419 // value when converted back to the original type. 420 case ICK_Integral_Conversion: 421 IntegralConversion: { 422 assert(FromType->isIntegralOrUnscopedEnumerationType()); 423 assert(ToType->isIntegralOrUnscopedEnumerationType()); 424 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 425 const unsigned FromWidth = Ctx.getIntWidth(FromType); 426 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 427 const unsigned ToWidth = Ctx.getIntWidth(ToType); 428 429 if (FromWidth > ToWidth || 430 (FromWidth == ToWidth && FromSigned != ToSigned) || 431 (FromSigned && !ToSigned)) { 432 // Not all values of FromType can be represented in ToType. 433 llvm::APSInt InitializerValue; 434 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 435 436 // If it's value-dependent, we can't tell whether it's narrowing. 437 if (Initializer->isValueDependent()) 438 return NK_Dependent_Narrowing; 439 440 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 441 // Such conversions on variables are always narrowing. 442 return NK_Variable_Narrowing; 443 } 444 bool Narrowing = false; 445 if (FromWidth < ToWidth) { 446 // Negative -> unsigned is narrowing. Otherwise, more bits is never 447 // narrowing. 448 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 449 Narrowing = true; 450 } else { 451 // Add a bit to the InitializerValue so we don't have to worry about 452 // signed vs. unsigned comparisons. 453 InitializerValue = InitializerValue.extend( 454 InitializerValue.getBitWidth() + 1); 455 // Convert the initializer to and from the target width and signed-ness. 456 llvm::APSInt ConvertedValue = InitializerValue; 457 ConvertedValue = ConvertedValue.trunc(ToWidth); 458 ConvertedValue.setIsSigned(ToSigned); 459 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 460 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 461 // If the result is different, this was a narrowing conversion. 462 if (ConvertedValue != InitializerValue) 463 Narrowing = true; 464 } 465 if (Narrowing) { 466 ConstantType = Initializer->getType(); 467 ConstantValue = APValue(InitializerValue); 468 return NK_Constant_Narrowing; 469 } 470 } 471 return NK_Not_Narrowing; 472 } 473 474 default: 475 // Other kinds of conversions are not narrowings. 476 return NK_Not_Narrowing; 477 } 478 } 479 480 /// dump - Print this standard conversion sequence to standard 481 /// error. Useful for debugging overloading issues. 482 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 483 raw_ostream &OS = llvm::errs(); 484 bool PrintedSomething = false; 485 if (First != ICK_Identity) { 486 OS << GetImplicitConversionName(First); 487 PrintedSomething = true; 488 } 489 490 if (Second != ICK_Identity) { 491 if (PrintedSomething) { 492 OS << " -> "; 493 } 494 OS << GetImplicitConversionName(Second); 495 496 if (CopyConstructor) { 497 OS << " (by copy constructor)"; 498 } else if (DirectBinding) { 499 OS << " (direct reference binding)"; 500 } else if (ReferenceBinding) { 501 OS << " (reference binding)"; 502 } 503 PrintedSomething = true; 504 } 505 506 if (Third != ICK_Identity) { 507 if (PrintedSomething) { 508 OS << " -> "; 509 } 510 OS << GetImplicitConversionName(Third); 511 PrintedSomething = true; 512 } 513 514 if (!PrintedSomething) { 515 OS << "No conversions required"; 516 } 517 } 518 519 /// dump - Print this user-defined conversion sequence to standard 520 /// error. Useful for debugging overloading issues. 521 void UserDefinedConversionSequence::dump() const { 522 raw_ostream &OS = llvm::errs(); 523 if (Before.First || Before.Second || Before.Third) { 524 Before.dump(); 525 OS << " -> "; 526 } 527 if (ConversionFunction) 528 OS << '\'' << *ConversionFunction << '\''; 529 else 530 OS << "aggregate initialization"; 531 if (After.First || After.Second || After.Third) { 532 OS << " -> "; 533 After.dump(); 534 } 535 } 536 537 /// dump - Print this implicit conversion sequence to standard 538 /// error. Useful for debugging overloading issues. 539 void ImplicitConversionSequence::dump() const { 540 raw_ostream &OS = llvm::errs(); 541 if (isStdInitializerListElement()) 542 OS << "Worst std::initializer_list element conversion: "; 543 switch (ConversionKind) { 544 case StandardConversion: 545 OS << "Standard conversion: "; 546 Standard.dump(); 547 break; 548 case UserDefinedConversion: 549 OS << "User-defined conversion: "; 550 UserDefined.dump(); 551 break; 552 case EllipsisConversion: 553 OS << "Ellipsis conversion"; 554 break; 555 case AmbiguousConversion: 556 OS << "Ambiguous conversion"; 557 break; 558 case BadConversion: 559 OS << "Bad conversion"; 560 break; 561 } 562 563 OS << "\n"; 564 } 565 566 void AmbiguousConversionSequence::construct() { 567 new (&conversions()) ConversionSet(); 568 } 569 570 void AmbiguousConversionSequence::destruct() { 571 conversions().~ConversionSet(); 572 } 573 574 void 575 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 576 FromTypePtr = O.FromTypePtr; 577 ToTypePtr = O.ToTypePtr; 578 new (&conversions()) ConversionSet(O.conversions()); 579 } 580 581 namespace { 582 // Structure used by DeductionFailureInfo to store 583 // template argument information. 584 struct DFIArguments { 585 TemplateArgument FirstArg; 586 TemplateArgument SecondArg; 587 }; 588 // Structure used by DeductionFailureInfo to store 589 // template parameter and template argument information. 590 struct DFIParamWithArguments : DFIArguments { 591 TemplateParameter Param; 592 }; 593 // Structure used by DeductionFailureInfo to store template argument 594 // information and the index of the problematic call argument. 595 struct DFIDeducedMismatchArgs : DFIArguments { 596 TemplateArgumentList *TemplateArgs; 597 unsigned CallArgIndex; 598 }; 599 // Structure used by DeductionFailureInfo to store information about 600 // unsatisfied constraints. 601 struct CNSInfo { 602 TemplateArgumentList *TemplateArgs; 603 ConstraintSatisfaction Satisfaction; 604 }; 605 } 606 607 /// Convert from Sema's representation of template deduction information 608 /// to the form used in overload-candidate information. 609 DeductionFailureInfo 610 clang::MakeDeductionFailureInfo(ASTContext &Context, 611 Sema::TemplateDeductionResult TDK, 612 TemplateDeductionInfo &Info) { 613 DeductionFailureInfo Result; 614 Result.Result = static_cast<unsigned>(TDK); 615 Result.HasDiagnostic = false; 616 switch (TDK) { 617 case Sema::TDK_Invalid: 618 case Sema::TDK_InstantiationDepth: 619 case Sema::TDK_TooManyArguments: 620 case Sema::TDK_TooFewArguments: 621 case Sema::TDK_MiscellaneousDeductionFailure: 622 case Sema::TDK_CUDATargetMismatch: 623 Result.Data = nullptr; 624 break; 625 626 case Sema::TDK_Incomplete: 627 case Sema::TDK_InvalidExplicitArguments: 628 Result.Data = Info.Param.getOpaqueValue(); 629 break; 630 631 case Sema::TDK_DeducedMismatch: 632 case Sema::TDK_DeducedMismatchNested: { 633 // FIXME: Should allocate from normal heap so that we can free this later. 634 auto *Saved = new (Context) DFIDeducedMismatchArgs; 635 Saved->FirstArg = Info.FirstArg; 636 Saved->SecondArg = Info.SecondArg; 637 Saved->TemplateArgs = Info.take(); 638 Saved->CallArgIndex = Info.CallArgIndex; 639 Result.Data = Saved; 640 break; 641 } 642 643 case Sema::TDK_NonDeducedMismatch: { 644 // FIXME: Should allocate from normal heap so that we can free this later. 645 DFIArguments *Saved = new (Context) DFIArguments; 646 Saved->FirstArg = Info.FirstArg; 647 Saved->SecondArg = Info.SecondArg; 648 Result.Data = Saved; 649 break; 650 } 651 652 case Sema::TDK_IncompletePack: 653 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 654 case Sema::TDK_Inconsistent: 655 case Sema::TDK_Underqualified: { 656 // FIXME: Should allocate from normal heap so that we can free this later. 657 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 658 Saved->Param = Info.Param; 659 Saved->FirstArg = Info.FirstArg; 660 Saved->SecondArg = Info.SecondArg; 661 Result.Data = Saved; 662 break; 663 } 664 665 case Sema::TDK_SubstitutionFailure: 666 Result.Data = Info.take(); 667 if (Info.hasSFINAEDiagnostic()) { 668 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 669 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 670 Info.takeSFINAEDiagnostic(*Diag); 671 Result.HasDiagnostic = true; 672 } 673 break; 674 675 case Sema::TDK_ConstraintsNotSatisfied: { 676 CNSInfo *Saved = new (Context) CNSInfo; 677 Saved->TemplateArgs = Info.take(); 678 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 679 Result.Data = Saved; 680 break; 681 } 682 683 case Sema::TDK_Success: 684 case Sema::TDK_NonDependentConversionFailure: 685 llvm_unreachable("not a deduction failure"); 686 } 687 688 return Result; 689 } 690 691 void DeductionFailureInfo::Destroy() { 692 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 693 case Sema::TDK_Success: 694 case Sema::TDK_Invalid: 695 case Sema::TDK_InstantiationDepth: 696 case Sema::TDK_Incomplete: 697 case Sema::TDK_TooManyArguments: 698 case Sema::TDK_TooFewArguments: 699 case Sema::TDK_InvalidExplicitArguments: 700 case Sema::TDK_CUDATargetMismatch: 701 case Sema::TDK_NonDependentConversionFailure: 702 break; 703 704 case Sema::TDK_IncompletePack: 705 case Sema::TDK_Inconsistent: 706 case Sema::TDK_Underqualified: 707 case Sema::TDK_DeducedMismatch: 708 case Sema::TDK_DeducedMismatchNested: 709 case Sema::TDK_NonDeducedMismatch: 710 // FIXME: Destroy the data? 711 Data = nullptr; 712 break; 713 714 case Sema::TDK_SubstitutionFailure: 715 // FIXME: Destroy the template argument list? 716 Data = nullptr; 717 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 718 Diag->~PartialDiagnosticAt(); 719 HasDiagnostic = false; 720 } 721 break; 722 723 case Sema::TDK_ConstraintsNotSatisfied: 724 // FIXME: Destroy the template argument list? 725 Data = nullptr; 726 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 727 Diag->~PartialDiagnosticAt(); 728 HasDiagnostic = false; 729 } 730 break; 731 732 // Unhandled 733 case Sema::TDK_MiscellaneousDeductionFailure: 734 break; 735 } 736 } 737 738 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 739 if (HasDiagnostic) 740 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 741 return nullptr; 742 } 743 744 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 745 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 746 case Sema::TDK_Success: 747 case Sema::TDK_Invalid: 748 case Sema::TDK_InstantiationDepth: 749 case Sema::TDK_TooManyArguments: 750 case Sema::TDK_TooFewArguments: 751 case Sema::TDK_SubstitutionFailure: 752 case Sema::TDK_DeducedMismatch: 753 case Sema::TDK_DeducedMismatchNested: 754 case Sema::TDK_NonDeducedMismatch: 755 case Sema::TDK_CUDATargetMismatch: 756 case Sema::TDK_NonDependentConversionFailure: 757 case Sema::TDK_ConstraintsNotSatisfied: 758 return TemplateParameter(); 759 760 case Sema::TDK_Incomplete: 761 case Sema::TDK_InvalidExplicitArguments: 762 return TemplateParameter::getFromOpaqueValue(Data); 763 764 case Sema::TDK_IncompletePack: 765 case Sema::TDK_Inconsistent: 766 case Sema::TDK_Underqualified: 767 return static_cast<DFIParamWithArguments*>(Data)->Param; 768 769 // Unhandled 770 case Sema::TDK_MiscellaneousDeductionFailure: 771 break; 772 } 773 774 return TemplateParameter(); 775 } 776 777 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 778 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 779 case Sema::TDK_Success: 780 case Sema::TDK_Invalid: 781 case Sema::TDK_InstantiationDepth: 782 case Sema::TDK_TooManyArguments: 783 case Sema::TDK_TooFewArguments: 784 case Sema::TDK_Incomplete: 785 case Sema::TDK_IncompletePack: 786 case Sema::TDK_InvalidExplicitArguments: 787 case Sema::TDK_Inconsistent: 788 case Sema::TDK_Underqualified: 789 case Sema::TDK_NonDeducedMismatch: 790 case Sema::TDK_CUDATargetMismatch: 791 case Sema::TDK_NonDependentConversionFailure: 792 return nullptr; 793 794 case Sema::TDK_DeducedMismatch: 795 case Sema::TDK_DeducedMismatchNested: 796 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 797 798 case Sema::TDK_SubstitutionFailure: 799 return static_cast<TemplateArgumentList*>(Data); 800 801 case Sema::TDK_ConstraintsNotSatisfied: 802 return static_cast<CNSInfo*>(Data)->TemplateArgs; 803 804 // Unhandled 805 case Sema::TDK_MiscellaneousDeductionFailure: 806 break; 807 } 808 809 return nullptr; 810 } 811 812 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 813 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 814 case Sema::TDK_Success: 815 case Sema::TDK_Invalid: 816 case Sema::TDK_InstantiationDepth: 817 case Sema::TDK_Incomplete: 818 case Sema::TDK_TooManyArguments: 819 case Sema::TDK_TooFewArguments: 820 case Sema::TDK_InvalidExplicitArguments: 821 case Sema::TDK_SubstitutionFailure: 822 case Sema::TDK_CUDATargetMismatch: 823 case Sema::TDK_NonDependentConversionFailure: 824 case Sema::TDK_ConstraintsNotSatisfied: 825 return nullptr; 826 827 case Sema::TDK_IncompletePack: 828 case Sema::TDK_Inconsistent: 829 case Sema::TDK_Underqualified: 830 case Sema::TDK_DeducedMismatch: 831 case Sema::TDK_DeducedMismatchNested: 832 case Sema::TDK_NonDeducedMismatch: 833 return &static_cast<DFIArguments*>(Data)->FirstArg; 834 835 // Unhandled 836 case Sema::TDK_MiscellaneousDeductionFailure: 837 break; 838 } 839 840 return nullptr; 841 } 842 843 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 844 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 845 case Sema::TDK_Success: 846 case Sema::TDK_Invalid: 847 case Sema::TDK_InstantiationDepth: 848 case Sema::TDK_Incomplete: 849 case Sema::TDK_IncompletePack: 850 case Sema::TDK_TooManyArguments: 851 case Sema::TDK_TooFewArguments: 852 case Sema::TDK_InvalidExplicitArguments: 853 case Sema::TDK_SubstitutionFailure: 854 case Sema::TDK_CUDATargetMismatch: 855 case Sema::TDK_NonDependentConversionFailure: 856 case Sema::TDK_ConstraintsNotSatisfied: 857 return nullptr; 858 859 case Sema::TDK_Inconsistent: 860 case Sema::TDK_Underqualified: 861 case Sema::TDK_DeducedMismatch: 862 case Sema::TDK_DeducedMismatchNested: 863 case Sema::TDK_NonDeducedMismatch: 864 return &static_cast<DFIArguments*>(Data)->SecondArg; 865 866 // Unhandled 867 case Sema::TDK_MiscellaneousDeductionFailure: 868 break; 869 } 870 871 return nullptr; 872 } 873 874 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 875 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 876 case Sema::TDK_DeducedMismatch: 877 case Sema::TDK_DeducedMismatchNested: 878 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 879 880 default: 881 return llvm::None; 882 } 883 } 884 885 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 886 OverloadedOperatorKind Op) { 887 if (!AllowRewrittenCandidates) 888 return false; 889 return Op == OO_EqualEqual || Op == OO_Spaceship; 890 } 891 892 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 893 ASTContext &Ctx, const FunctionDecl *FD) { 894 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 895 return false; 896 // Don't bother adding a reversed candidate that can never be a better 897 // match than the non-reversed version. 898 return FD->getNumParams() != 2 || 899 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 900 FD->getParamDecl(1)->getType()) || 901 FD->hasAttr<EnableIfAttr>(); 902 } 903 904 void OverloadCandidateSet::destroyCandidates() { 905 for (iterator i = begin(), e = end(); i != e; ++i) { 906 for (auto &C : i->Conversions) 907 C.~ImplicitConversionSequence(); 908 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 909 i->DeductionFailure.Destroy(); 910 } 911 } 912 913 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 914 destroyCandidates(); 915 SlabAllocator.Reset(); 916 NumInlineBytesUsed = 0; 917 Candidates.clear(); 918 Functions.clear(); 919 Kind = CSK; 920 } 921 922 namespace { 923 class UnbridgedCastsSet { 924 struct Entry { 925 Expr **Addr; 926 Expr *Saved; 927 }; 928 SmallVector<Entry, 2> Entries; 929 930 public: 931 void save(Sema &S, Expr *&E) { 932 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 933 Entry entry = { &E, E }; 934 Entries.push_back(entry); 935 E = S.stripARCUnbridgedCast(E); 936 } 937 938 void restore() { 939 for (SmallVectorImpl<Entry>::iterator 940 i = Entries.begin(), e = Entries.end(); i != e; ++i) 941 *i->Addr = i->Saved; 942 } 943 }; 944 } 945 946 /// checkPlaceholderForOverload - Do any interesting placeholder-like 947 /// preprocessing on the given expression. 948 /// 949 /// \param unbridgedCasts a collection to which to add unbridged casts; 950 /// without this, they will be immediately diagnosed as errors 951 /// 952 /// Return true on unrecoverable error. 953 static bool 954 checkPlaceholderForOverload(Sema &S, Expr *&E, 955 UnbridgedCastsSet *unbridgedCasts = nullptr) { 956 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 957 // We can't handle overloaded expressions here because overload 958 // resolution might reasonably tweak them. 959 if (placeholder->getKind() == BuiltinType::Overload) return false; 960 961 // If the context potentially accepts unbridged ARC casts, strip 962 // the unbridged cast and add it to the collection for later restoration. 963 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 964 unbridgedCasts) { 965 unbridgedCasts->save(S, E); 966 return false; 967 } 968 969 // Go ahead and check everything else. 970 ExprResult result = S.CheckPlaceholderExpr(E); 971 if (result.isInvalid()) 972 return true; 973 974 E = result.get(); 975 return false; 976 } 977 978 // Nothing to do. 979 return false; 980 } 981 982 /// checkArgPlaceholdersForOverload - Check a set of call operands for 983 /// placeholders. 984 static bool checkArgPlaceholdersForOverload(Sema &S, 985 MultiExprArg Args, 986 UnbridgedCastsSet &unbridged) { 987 for (unsigned i = 0, e = Args.size(); i != e; ++i) 988 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 989 return true; 990 991 return false; 992 } 993 994 /// Determine whether the given New declaration is an overload of the 995 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 996 /// New and Old cannot be overloaded, e.g., if New has the same signature as 997 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 998 /// functions (or function templates) at all. When it does return Ovl_Match or 999 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1000 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1001 /// declaration. 1002 /// 1003 /// Example: Given the following input: 1004 /// 1005 /// void f(int, float); // #1 1006 /// void f(int, int); // #2 1007 /// int f(int, int); // #3 1008 /// 1009 /// When we process #1, there is no previous declaration of "f", so IsOverload 1010 /// will not be used. 1011 /// 1012 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1013 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1014 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1015 /// unchanged. 1016 /// 1017 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1018 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1019 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1020 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1021 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1022 /// 1023 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1024 /// by a using declaration. The rules for whether to hide shadow declarations 1025 /// ignore some properties which otherwise figure into a function template's 1026 /// signature. 1027 Sema::OverloadKind 1028 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1029 NamedDecl *&Match, bool NewIsUsingDecl) { 1030 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1031 I != E; ++I) { 1032 NamedDecl *OldD = *I; 1033 1034 bool OldIsUsingDecl = false; 1035 if (isa<UsingShadowDecl>(OldD)) { 1036 OldIsUsingDecl = true; 1037 1038 // We can always introduce two using declarations into the same 1039 // context, even if they have identical signatures. 1040 if (NewIsUsingDecl) continue; 1041 1042 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1043 } 1044 1045 // A using-declaration does not conflict with another declaration 1046 // if one of them is hidden. 1047 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1048 continue; 1049 1050 // If either declaration was introduced by a using declaration, 1051 // we'll need to use slightly different rules for matching. 1052 // Essentially, these rules are the normal rules, except that 1053 // function templates hide function templates with different 1054 // return types or template parameter lists. 1055 bool UseMemberUsingDeclRules = 1056 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1057 !New->getFriendObjectKind(); 1058 1059 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1060 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1061 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1062 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1063 continue; 1064 } 1065 1066 if (!isa<FunctionTemplateDecl>(OldD) && 1067 !shouldLinkPossiblyHiddenDecl(*I, New)) 1068 continue; 1069 1070 Match = *I; 1071 return Ovl_Match; 1072 } 1073 1074 // Builtins that have custom typechecking or have a reference should 1075 // not be overloadable or redeclarable. 1076 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1077 Match = *I; 1078 return Ovl_NonFunction; 1079 } 1080 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1081 // We can overload with these, which can show up when doing 1082 // redeclaration checks for UsingDecls. 1083 assert(Old.getLookupKind() == LookupUsingDeclName); 1084 } else if (isa<TagDecl>(OldD)) { 1085 // We can always overload with tags by hiding them. 1086 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1087 // Optimistically assume that an unresolved using decl will 1088 // overload; if it doesn't, we'll have to diagnose during 1089 // template instantiation. 1090 // 1091 // Exception: if the scope is dependent and this is not a class 1092 // member, the using declaration can only introduce an enumerator. 1093 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1094 Match = *I; 1095 return Ovl_NonFunction; 1096 } 1097 } else { 1098 // (C++ 13p1): 1099 // Only function declarations can be overloaded; object and type 1100 // declarations cannot be overloaded. 1101 Match = *I; 1102 return Ovl_NonFunction; 1103 } 1104 } 1105 1106 // C++ [temp.friend]p1: 1107 // For a friend function declaration that is not a template declaration: 1108 // -- if the name of the friend is a qualified or unqualified template-id, 1109 // [...], otherwise 1110 // -- if the name of the friend is a qualified-id and a matching 1111 // non-template function is found in the specified class or namespace, 1112 // the friend declaration refers to that function, otherwise, 1113 // -- if the name of the friend is a qualified-id and a matching function 1114 // template is found in the specified class or namespace, the friend 1115 // declaration refers to the deduced specialization of that function 1116 // template, otherwise 1117 // -- the name shall be an unqualified-id [...] 1118 // If we get here for a qualified friend declaration, we've just reached the 1119 // third bullet. If the type of the friend is dependent, skip this lookup 1120 // until instantiation. 1121 if (New->getFriendObjectKind() && New->getQualifier() && 1122 !New->getDescribedFunctionTemplate() && 1123 !New->getDependentSpecializationInfo() && 1124 !New->getType()->isDependentType()) { 1125 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1126 TemplateSpecResult.addAllDecls(Old); 1127 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1128 /*QualifiedFriend*/true)) { 1129 New->setInvalidDecl(); 1130 return Ovl_Overload; 1131 } 1132 1133 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1134 return Ovl_Match; 1135 } 1136 1137 return Ovl_Overload; 1138 } 1139 1140 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1141 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1142 bool ConsiderRequiresClauses) { 1143 // C++ [basic.start.main]p2: This function shall not be overloaded. 1144 if (New->isMain()) 1145 return false; 1146 1147 // MSVCRT user defined entry points cannot be overloaded. 1148 if (New->isMSVCRTEntryPoint()) 1149 return false; 1150 1151 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1152 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1153 1154 // C++ [temp.fct]p2: 1155 // A function template can be overloaded with other function templates 1156 // and with normal (non-template) functions. 1157 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1158 return true; 1159 1160 // Is the function New an overload of the function Old? 1161 QualType OldQType = Context.getCanonicalType(Old->getType()); 1162 QualType NewQType = Context.getCanonicalType(New->getType()); 1163 1164 // Compare the signatures (C++ 1.3.10) of the two functions to 1165 // determine whether they are overloads. If we find any mismatch 1166 // in the signature, they are overloads. 1167 1168 // If either of these functions is a K&R-style function (no 1169 // prototype), then we consider them to have matching signatures. 1170 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1171 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1172 return false; 1173 1174 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1175 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1176 1177 // The signature of a function includes the types of its 1178 // parameters (C++ 1.3.10), which includes the presence or absence 1179 // of the ellipsis; see C++ DR 357). 1180 if (OldQType != NewQType && 1181 (OldType->getNumParams() != NewType->getNumParams() || 1182 OldType->isVariadic() != NewType->isVariadic() || 1183 !FunctionParamTypesAreEqual(OldType, NewType))) 1184 return true; 1185 1186 // C++ [temp.over.link]p4: 1187 // The signature of a function template consists of its function 1188 // signature, its return type and its template parameter list. The names 1189 // of the template parameters are significant only for establishing the 1190 // relationship between the template parameters and the rest of the 1191 // signature. 1192 // 1193 // We check the return type and template parameter lists for function 1194 // templates first; the remaining checks follow. 1195 // 1196 // However, we don't consider either of these when deciding whether 1197 // a member introduced by a shadow declaration is hidden. 1198 if (!UseMemberUsingDeclRules && NewTemplate && 1199 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1200 OldTemplate->getTemplateParameters(), 1201 false, TPL_TemplateMatch) || 1202 !Context.hasSameType(Old->getDeclaredReturnType(), 1203 New->getDeclaredReturnType()))) 1204 return true; 1205 1206 // If the function is a class member, its signature includes the 1207 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1208 // 1209 // As part of this, also check whether one of the member functions 1210 // is static, in which case they are not overloads (C++ 1211 // 13.1p2). While not part of the definition of the signature, 1212 // this check is important to determine whether these functions 1213 // can be overloaded. 1214 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1215 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1216 if (OldMethod && NewMethod && 1217 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1218 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1219 if (!UseMemberUsingDeclRules && 1220 (OldMethod->getRefQualifier() == RQ_None || 1221 NewMethod->getRefQualifier() == RQ_None)) { 1222 // C++0x [over.load]p2: 1223 // - Member function declarations with the same name and the same 1224 // parameter-type-list as well as member function template 1225 // declarations with the same name, the same parameter-type-list, and 1226 // the same template parameter lists cannot be overloaded if any of 1227 // them, but not all, have a ref-qualifier (8.3.5). 1228 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1229 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1230 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1231 } 1232 return true; 1233 } 1234 1235 // We may not have applied the implicit const for a constexpr member 1236 // function yet (because we haven't yet resolved whether this is a static 1237 // or non-static member function). Add it now, on the assumption that this 1238 // is a redeclaration of OldMethod. 1239 auto OldQuals = OldMethod->getMethodQualifiers(); 1240 auto NewQuals = NewMethod->getMethodQualifiers(); 1241 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1242 !isa<CXXConstructorDecl>(NewMethod)) 1243 NewQuals.addConst(); 1244 // We do not allow overloading based off of '__restrict'. 1245 OldQuals.removeRestrict(); 1246 NewQuals.removeRestrict(); 1247 if (OldQuals != NewQuals) 1248 return true; 1249 } 1250 1251 // Though pass_object_size is placed on parameters and takes an argument, we 1252 // consider it to be a function-level modifier for the sake of function 1253 // identity. Either the function has one or more parameters with 1254 // pass_object_size or it doesn't. 1255 if (functionHasPassObjectSizeParams(New) != 1256 functionHasPassObjectSizeParams(Old)) 1257 return true; 1258 1259 // enable_if attributes are an order-sensitive part of the signature. 1260 for (specific_attr_iterator<EnableIfAttr> 1261 NewI = New->specific_attr_begin<EnableIfAttr>(), 1262 NewE = New->specific_attr_end<EnableIfAttr>(), 1263 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1264 OldE = Old->specific_attr_end<EnableIfAttr>(); 1265 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1266 if (NewI == NewE || OldI == OldE) 1267 return true; 1268 llvm::FoldingSetNodeID NewID, OldID; 1269 NewI->getCond()->Profile(NewID, Context, true); 1270 OldI->getCond()->Profile(OldID, Context, true); 1271 if (NewID != OldID) 1272 return true; 1273 } 1274 1275 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1276 // Don't allow overloading of destructors. (In theory we could, but it 1277 // would be a giant change to clang.) 1278 if (!isa<CXXDestructorDecl>(New)) { 1279 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1280 OldTarget = IdentifyCUDATarget(Old); 1281 if (NewTarget != CFT_InvalidTarget) { 1282 assert((OldTarget != CFT_InvalidTarget) && 1283 "Unexpected invalid target."); 1284 1285 // Allow overloading of functions with same signature and different CUDA 1286 // target attributes. 1287 if (NewTarget != OldTarget) 1288 return true; 1289 } 1290 } 1291 } 1292 1293 if (ConsiderRequiresClauses) { 1294 Expr *NewRC = New->getTrailingRequiresClause(), 1295 *OldRC = Old->getTrailingRequiresClause(); 1296 if ((NewRC != nullptr) != (OldRC != nullptr)) 1297 // RC are most certainly different - these are overloads. 1298 return true; 1299 1300 if (NewRC) { 1301 llvm::FoldingSetNodeID NewID, OldID; 1302 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1303 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1304 if (NewID != OldID) 1305 // RCs are not equivalent - these are overloads. 1306 return true; 1307 } 1308 } 1309 1310 // The signatures match; this is not an overload. 1311 return false; 1312 } 1313 1314 /// Tries a user-defined conversion from From to ToType. 1315 /// 1316 /// Produces an implicit conversion sequence for when a standard conversion 1317 /// is not an option. See TryImplicitConversion for more information. 1318 static ImplicitConversionSequence 1319 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1320 bool SuppressUserConversions, 1321 AllowedExplicit AllowExplicit, 1322 bool InOverloadResolution, 1323 bool CStyle, 1324 bool AllowObjCWritebackConversion, 1325 bool AllowObjCConversionOnExplicit) { 1326 ImplicitConversionSequence ICS; 1327 1328 if (SuppressUserConversions) { 1329 // We're not in the case above, so there is no conversion that 1330 // we can perform. 1331 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1332 return ICS; 1333 } 1334 1335 // Attempt user-defined conversion. 1336 OverloadCandidateSet Conversions(From->getExprLoc(), 1337 OverloadCandidateSet::CSK_Normal); 1338 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1339 Conversions, AllowExplicit, 1340 AllowObjCConversionOnExplicit)) { 1341 case OR_Success: 1342 case OR_Deleted: 1343 ICS.setUserDefined(); 1344 // C++ [over.ics.user]p4: 1345 // A conversion of an expression of class type to the same class 1346 // type is given Exact Match rank, and a conversion of an 1347 // expression of class type to a base class of that type is 1348 // given Conversion rank, in spite of the fact that a copy 1349 // constructor (i.e., a user-defined conversion function) is 1350 // called for those cases. 1351 if (CXXConstructorDecl *Constructor 1352 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1353 QualType FromCanon 1354 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1355 QualType ToCanon 1356 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1357 if (Constructor->isCopyConstructor() && 1358 (FromCanon == ToCanon || 1359 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1360 // Turn this into a "standard" conversion sequence, so that it 1361 // gets ranked with standard conversion sequences. 1362 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1363 ICS.setStandard(); 1364 ICS.Standard.setAsIdentityConversion(); 1365 ICS.Standard.setFromType(From->getType()); 1366 ICS.Standard.setAllToTypes(ToType); 1367 ICS.Standard.CopyConstructor = Constructor; 1368 ICS.Standard.FoundCopyConstructor = Found; 1369 if (ToCanon != FromCanon) 1370 ICS.Standard.Second = ICK_Derived_To_Base; 1371 } 1372 } 1373 break; 1374 1375 case OR_Ambiguous: 1376 ICS.setAmbiguous(); 1377 ICS.Ambiguous.setFromType(From->getType()); 1378 ICS.Ambiguous.setToType(ToType); 1379 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1380 Cand != Conversions.end(); ++Cand) 1381 if (Cand->Best) 1382 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1383 break; 1384 1385 // Fall through. 1386 case OR_No_Viable_Function: 1387 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1388 break; 1389 } 1390 1391 return ICS; 1392 } 1393 1394 /// TryImplicitConversion - Attempt to perform an implicit conversion 1395 /// from the given expression (Expr) to the given type (ToType). This 1396 /// function returns an implicit conversion sequence that can be used 1397 /// to perform the initialization. Given 1398 /// 1399 /// void f(float f); 1400 /// void g(int i) { f(i); } 1401 /// 1402 /// this routine would produce an implicit conversion sequence to 1403 /// describe the initialization of f from i, which will be a standard 1404 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1405 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1406 // 1407 /// Note that this routine only determines how the conversion can be 1408 /// performed; it does not actually perform the conversion. As such, 1409 /// it will not produce any diagnostics if no conversion is available, 1410 /// but will instead return an implicit conversion sequence of kind 1411 /// "BadConversion". 1412 /// 1413 /// If @p SuppressUserConversions, then user-defined conversions are 1414 /// not permitted. 1415 /// If @p AllowExplicit, then explicit user-defined conversions are 1416 /// permitted. 1417 /// 1418 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1419 /// writeback conversion, which allows __autoreleasing id* parameters to 1420 /// be initialized with __strong id* or __weak id* arguments. 1421 static ImplicitConversionSequence 1422 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1423 bool SuppressUserConversions, 1424 AllowedExplicit AllowExplicit, 1425 bool InOverloadResolution, 1426 bool CStyle, 1427 bool AllowObjCWritebackConversion, 1428 bool AllowObjCConversionOnExplicit) { 1429 ImplicitConversionSequence ICS; 1430 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1431 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1432 ICS.setStandard(); 1433 return ICS; 1434 } 1435 1436 if (!S.getLangOpts().CPlusPlus) { 1437 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1438 return ICS; 1439 } 1440 1441 // C++ [over.ics.user]p4: 1442 // A conversion of an expression of class type to the same class 1443 // type is given Exact Match rank, and a conversion of an 1444 // expression of class type to a base class of that type is 1445 // given Conversion rank, in spite of the fact that a copy/move 1446 // constructor (i.e., a user-defined conversion function) is 1447 // called for those cases. 1448 QualType FromType = From->getType(); 1449 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1450 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1451 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1452 ICS.setStandard(); 1453 ICS.Standard.setAsIdentityConversion(); 1454 ICS.Standard.setFromType(FromType); 1455 ICS.Standard.setAllToTypes(ToType); 1456 1457 // We don't actually check at this point whether there is a valid 1458 // copy/move constructor, since overloading just assumes that it 1459 // exists. When we actually perform initialization, we'll find the 1460 // appropriate constructor to copy the returned object, if needed. 1461 ICS.Standard.CopyConstructor = nullptr; 1462 1463 // Determine whether this is considered a derived-to-base conversion. 1464 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1465 ICS.Standard.Second = ICK_Derived_To_Base; 1466 1467 return ICS; 1468 } 1469 1470 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1471 AllowExplicit, InOverloadResolution, CStyle, 1472 AllowObjCWritebackConversion, 1473 AllowObjCConversionOnExplicit); 1474 } 1475 1476 ImplicitConversionSequence 1477 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1478 bool SuppressUserConversions, 1479 AllowedExplicit AllowExplicit, 1480 bool InOverloadResolution, 1481 bool CStyle, 1482 bool AllowObjCWritebackConversion) { 1483 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1484 AllowExplicit, InOverloadResolution, CStyle, 1485 AllowObjCWritebackConversion, 1486 /*AllowObjCConversionOnExplicit=*/false); 1487 } 1488 1489 /// PerformImplicitConversion - Perform an implicit conversion of the 1490 /// expression From to the type ToType. Returns the 1491 /// converted expression. Flavor is the kind of conversion we're 1492 /// performing, used in the error message. If @p AllowExplicit, 1493 /// explicit user-defined conversions are permitted. 1494 ExprResult 1495 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1496 AssignmentAction Action, bool AllowExplicit) { 1497 ImplicitConversionSequence ICS; 1498 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1499 } 1500 1501 ExprResult 1502 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1503 AssignmentAction Action, bool AllowExplicit, 1504 ImplicitConversionSequence& ICS) { 1505 if (checkPlaceholderForOverload(*this, From)) 1506 return ExprError(); 1507 1508 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1509 bool AllowObjCWritebackConversion 1510 = getLangOpts().ObjCAutoRefCount && 1511 (Action == AA_Passing || Action == AA_Sending); 1512 if (getLangOpts().ObjC) 1513 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1514 From->getType(), From); 1515 ICS = ::TryImplicitConversion(*this, From, ToType, 1516 /*SuppressUserConversions=*/false, 1517 AllowExplicit ? AllowedExplicit::All 1518 : AllowedExplicit::None, 1519 /*InOverloadResolution=*/false, 1520 /*CStyle=*/false, AllowObjCWritebackConversion, 1521 /*AllowObjCConversionOnExplicit=*/false); 1522 return PerformImplicitConversion(From, ToType, ICS, Action); 1523 } 1524 1525 /// Determine whether the conversion from FromType to ToType is a valid 1526 /// conversion that strips "noexcept" or "noreturn" off the nested function 1527 /// type. 1528 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1529 QualType &ResultTy) { 1530 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1531 return false; 1532 1533 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1534 // or F(t noexcept) -> F(t) 1535 // where F adds one of the following at most once: 1536 // - a pointer 1537 // - a member pointer 1538 // - a block pointer 1539 // Changes here need matching changes in FindCompositePointerType. 1540 CanQualType CanTo = Context.getCanonicalType(ToType); 1541 CanQualType CanFrom = Context.getCanonicalType(FromType); 1542 Type::TypeClass TyClass = CanTo->getTypeClass(); 1543 if (TyClass != CanFrom->getTypeClass()) return false; 1544 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1545 if (TyClass == Type::Pointer) { 1546 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1547 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1548 } else if (TyClass == Type::BlockPointer) { 1549 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1550 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1551 } else if (TyClass == Type::MemberPointer) { 1552 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1553 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1554 // A function pointer conversion cannot change the class of the function. 1555 if (ToMPT->getClass() != FromMPT->getClass()) 1556 return false; 1557 CanTo = ToMPT->getPointeeType(); 1558 CanFrom = FromMPT->getPointeeType(); 1559 } else { 1560 return false; 1561 } 1562 1563 TyClass = CanTo->getTypeClass(); 1564 if (TyClass != CanFrom->getTypeClass()) return false; 1565 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1566 return false; 1567 } 1568 1569 const auto *FromFn = cast<FunctionType>(CanFrom); 1570 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1571 1572 const auto *ToFn = cast<FunctionType>(CanTo); 1573 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1574 1575 bool Changed = false; 1576 1577 // Drop 'noreturn' if not present in target type. 1578 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1579 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1580 Changed = true; 1581 } 1582 1583 // Drop 'noexcept' if not present in target type. 1584 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1585 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1586 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1587 FromFn = cast<FunctionType>( 1588 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1589 EST_None) 1590 .getTypePtr()); 1591 Changed = true; 1592 } 1593 1594 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1595 // only if the ExtParameterInfo lists of the two function prototypes can be 1596 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1597 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1598 bool CanUseToFPT, CanUseFromFPT; 1599 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1600 CanUseFromFPT, NewParamInfos) && 1601 CanUseToFPT && !CanUseFromFPT) { 1602 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1603 ExtInfo.ExtParameterInfos = 1604 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1605 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1606 FromFPT->getParamTypes(), ExtInfo); 1607 FromFn = QT->getAs<FunctionType>(); 1608 Changed = true; 1609 } 1610 } 1611 1612 if (!Changed) 1613 return false; 1614 1615 assert(QualType(FromFn, 0).isCanonical()); 1616 if (QualType(FromFn, 0) != CanTo) return false; 1617 1618 ResultTy = ToType; 1619 return true; 1620 } 1621 1622 /// Determine whether the conversion from FromType to ToType is a valid 1623 /// vector conversion. 1624 /// 1625 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1626 /// conversion. 1627 static bool IsVectorConversion(Sema &S, QualType FromType, 1628 QualType ToType, ImplicitConversionKind &ICK) { 1629 // We need at least one of these types to be a vector type to have a vector 1630 // conversion. 1631 if (!ToType->isVectorType() && !FromType->isVectorType()) 1632 return false; 1633 1634 // Identical types require no conversions. 1635 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1636 return false; 1637 1638 // There are no conversions between extended vector types, only identity. 1639 if (ToType->isExtVectorType()) { 1640 // There are no conversions between extended vector types other than the 1641 // identity conversion. 1642 if (FromType->isExtVectorType()) 1643 return false; 1644 1645 // Vector splat from any arithmetic type to a vector. 1646 if (FromType->isArithmeticType()) { 1647 ICK = ICK_Vector_Splat; 1648 return true; 1649 } 1650 } 1651 1652 // We can perform the conversion between vector types in the following cases: 1653 // 1)vector types are equivalent AltiVec and GCC vector types 1654 // 2)lax vector conversions are permitted and the vector types are of the 1655 // same size 1656 // 3)the destination type does not have the ARM MVE strict-polymorphism 1657 // attribute, which inhibits lax vector conversion for overload resolution 1658 // only 1659 if (ToType->isVectorType() && FromType->isVectorType()) { 1660 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1661 (S.isLaxVectorConversion(FromType, ToType) && 1662 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1663 ICK = ICK_Vector_Conversion; 1664 return true; 1665 } 1666 } 1667 1668 return false; 1669 } 1670 1671 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1672 bool InOverloadResolution, 1673 StandardConversionSequence &SCS, 1674 bool CStyle); 1675 1676 /// IsStandardConversion - Determines whether there is a standard 1677 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1678 /// expression From to the type ToType. Standard conversion sequences 1679 /// only consider non-class types; for conversions that involve class 1680 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1681 /// contain the standard conversion sequence required to perform this 1682 /// conversion and this routine will return true. Otherwise, this 1683 /// routine will return false and the value of SCS is unspecified. 1684 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1685 bool InOverloadResolution, 1686 StandardConversionSequence &SCS, 1687 bool CStyle, 1688 bool AllowObjCWritebackConversion) { 1689 QualType FromType = From->getType(); 1690 1691 // Standard conversions (C++ [conv]) 1692 SCS.setAsIdentityConversion(); 1693 SCS.IncompatibleObjC = false; 1694 SCS.setFromType(FromType); 1695 SCS.CopyConstructor = nullptr; 1696 1697 // There are no standard conversions for class types in C++, so 1698 // abort early. When overloading in C, however, we do permit them. 1699 if (S.getLangOpts().CPlusPlus && 1700 (FromType->isRecordType() || ToType->isRecordType())) 1701 return false; 1702 1703 // The first conversion can be an lvalue-to-rvalue conversion, 1704 // array-to-pointer conversion, or function-to-pointer conversion 1705 // (C++ 4p1). 1706 1707 if (FromType == S.Context.OverloadTy) { 1708 DeclAccessPair AccessPair; 1709 if (FunctionDecl *Fn 1710 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1711 AccessPair)) { 1712 // We were able to resolve the address of the overloaded function, 1713 // so we can convert to the type of that function. 1714 FromType = Fn->getType(); 1715 SCS.setFromType(FromType); 1716 1717 // we can sometimes resolve &foo<int> regardless of ToType, so check 1718 // if the type matches (identity) or we are converting to bool 1719 if (!S.Context.hasSameUnqualifiedType( 1720 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1721 QualType resultTy; 1722 // if the function type matches except for [[noreturn]], it's ok 1723 if (!S.IsFunctionConversion(FromType, 1724 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1725 // otherwise, only a boolean conversion is standard 1726 if (!ToType->isBooleanType()) 1727 return false; 1728 } 1729 1730 // Check if the "from" expression is taking the address of an overloaded 1731 // function and recompute the FromType accordingly. Take advantage of the 1732 // fact that non-static member functions *must* have such an address-of 1733 // expression. 1734 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1735 if (Method && !Method->isStatic()) { 1736 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1737 "Non-unary operator on non-static member address"); 1738 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1739 == UO_AddrOf && 1740 "Non-address-of operator on non-static member address"); 1741 const Type *ClassType 1742 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1743 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1744 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1745 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1746 UO_AddrOf && 1747 "Non-address-of operator for overloaded function expression"); 1748 FromType = S.Context.getPointerType(FromType); 1749 } 1750 1751 // Check that we've computed the proper type after overload resolution. 1752 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1753 // be calling it from within an NDEBUG block. 1754 assert(S.Context.hasSameType( 1755 FromType, 1756 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1757 } else { 1758 return false; 1759 } 1760 } 1761 // Lvalue-to-rvalue conversion (C++11 4.1): 1762 // A glvalue (3.10) of a non-function, non-array type T can 1763 // be converted to a prvalue. 1764 bool argIsLValue = From->isGLValue(); 1765 if (argIsLValue && 1766 !FromType->isFunctionType() && !FromType->isArrayType() && 1767 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1768 SCS.First = ICK_Lvalue_To_Rvalue; 1769 1770 // C11 6.3.2.1p2: 1771 // ... if the lvalue has atomic type, the value has the non-atomic version 1772 // of the type of the lvalue ... 1773 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1774 FromType = Atomic->getValueType(); 1775 1776 // If T is a non-class type, the type of the rvalue is the 1777 // cv-unqualified version of T. Otherwise, the type of the rvalue 1778 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1779 // just strip the qualifiers because they don't matter. 1780 FromType = FromType.getUnqualifiedType(); 1781 } else if (FromType->isArrayType()) { 1782 // Array-to-pointer conversion (C++ 4.2) 1783 SCS.First = ICK_Array_To_Pointer; 1784 1785 // An lvalue or rvalue of type "array of N T" or "array of unknown 1786 // bound of T" can be converted to an rvalue of type "pointer to 1787 // T" (C++ 4.2p1). 1788 FromType = S.Context.getArrayDecayedType(FromType); 1789 1790 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1791 // This conversion is deprecated in C++03 (D.4) 1792 SCS.DeprecatedStringLiteralToCharPtr = true; 1793 1794 // For the purpose of ranking in overload resolution 1795 // (13.3.3.1.1), this conversion is considered an 1796 // array-to-pointer conversion followed by a qualification 1797 // conversion (4.4). (C++ 4.2p2) 1798 SCS.Second = ICK_Identity; 1799 SCS.Third = ICK_Qualification; 1800 SCS.QualificationIncludesObjCLifetime = false; 1801 SCS.setAllToTypes(FromType); 1802 return true; 1803 } 1804 } else if (FromType->isFunctionType() && argIsLValue) { 1805 // Function-to-pointer conversion (C++ 4.3). 1806 SCS.First = ICK_Function_To_Pointer; 1807 1808 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1809 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1810 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1811 return false; 1812 1813 // An lvalue of function type T can be converted to an rvalue of 1814 // type "pointer to T." The result is a pointer to the 1815 // function. (C++ 4.3p1). 1816 FromType = S.Context.getPointerType(FromType); 1817 } else { 1818 // We don't require any conversions for the first step. 1819 SCS.First = ICK_Identity; 1820 } 1821 SCS.setToType(0, FromType); 1822 1823 // The second conversion can be an integral promotion, floating 1824 // point promotion, integral conversion, floating point conversion, 1825 // floating-integral conversion, pointer conversion, 1826 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1827 // For overloading in C, this can also be a "compatible-type" 1828 // conversion. 1829 bool IncompatibleObjC = false; 1830 ImplicitConversionKind SecondICK = ICK_Identity; 1831 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1832 // The unqualified versions of the types are the same: there's no 1833 // conversion to do. 1834 SCS.Second = ICK_Identity; 1835 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1836 // Integral promotion (C++ 4.5). 1837 SCS.Second = ICK_Integral_Promotion; 1838 FromType = ToType.getUnqualifiedType(); 1839 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1840 // Floating point promotion (C++ 4.6). 1841 SCS.Second = ICK_Floating_Promotion; 1842 FromType = ToType.getUnqualifiedType(); 1843 } else if (S.IsComplexPromotion(FromType, ToType)) { 1844 // Complex promotion (Clang extension) 1845 SCS.Second = ICK_Complex_Promotion; 1846 FromType = ToType.getUnqualifiedType(); 1847 } else if (ToType->isBooleanType() && 1848 (FromType->isArithmeticType() || 1849 FromType->isAnyPointerType() || 1850 FromType->isBlockPointerType() || 1851 FromType->isMemberPointerType() || 1852 FromType->isNullPtrType())) { 1853 // Boolean conversions (C++ 4.12). 1854 SCS.Second = ICK_Boolean_Conversion; 1855 FromType = S.Context.BoolTy; 1856 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1857 ToType->isIntegralType(S.Context)) { 1858 // Integral conversions (C++ 4.7). 1859 SCS.Second = ICK_Integral_Conversion; 1860 FromType = ToType.getUnqualifiedType(); 1861 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1862 // Complex conversions (C99 6.3.1.6) 1863 SCS.Second = ICK_Complex_Conversion; 1864 FromType = ToType.getUnqualifiedType(); 1865 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1866 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1867 // Complex-real conversions (C99 6.3.1.7) 1868 SCS.Second = ICK_Complex_Real; 1869 FromType = ToType.getUnqualifiedType(); 1870 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1871 // FIXME: disable conversions between long double and __float128 if 1872 // their representation is different until there is back end support 1873 // We of course allow this conversion if long double is really double. 1874 if (&S.Context.getFloatTypeSemantics(FromType) != 1875 &S.Context.getFloatTypeSemantics(ToType)) { 1876 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1877 ToType == S.Context.LongDoubleTy) || 1878 (FromType == S.Context.LongDoubleTy && 1879 ToType == S.Context.Float128Ty)); 1880 if (Float128AndLongDouble && 1881 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1882 &llvm::APFloat::PPCDoubleDouble())) 1883 return false; 1884 } 1885 // Floating point conversions (C++ 4.8). 1886 SCS.Second = ICK_Floating_Conversion; 1887 FromType = ToType.getUnqualifiedType(); 1888 } else if ((FromType->isRealFloatingType() && 1889 ToType->isIntegralType(S.Context)) || 1890 (FromType->isIntegralOrUnscopedEnumerationType() && 1891 ToType->isRealFloatingType())) { 1892 // Floating-integral conversions (C++ 4.9). 1893 SCS.Second = ICK_Floating_Integral; 1894 FromType = ToType.getUnqualifiedType(); 1895 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1896 SCS.Second = ICK_Block_Pointer_Conversion; 1897 } else if (AllowObjCWritebackConversion && 1898 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1899 SCS.Second = ICK_Writeback_Conversion; 1900 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1901 FromType, IncompatibleObjC)) { 1902 // Pointer conversions (C++ 4.10). 1903 SCS.Second = ICK_Pointer_Conversion; 1904 SCS.IncompatibleObjC = IncompatibleObjC; 1905 FromType = FromType.getUnqualifiedType(); 1906 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1907 InOverloadResolution, FromType)) { 1908 // Pointer to member conversions (4.11). 1909 SCS.Second = ICK_Pointer_Member; 1910 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1911 SCS.Second = SecondICK; 1912 FromType = ToType.getUnqualifiedType(); 1913 } else if (!S.getLangOpts().CPlusPlus && 1914 S.Context.typesAreCompatible(ToType, FromType)) { 1915 // Compatible conversions (Clang extension for C function overloading) 1916 SCS.Second = ICK_Compatible_Conversion; 1917 FromType = ToType.getUnqualifiedType(); 1918 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1919 InOverloadResolution, 1920 SCS, CStyle)) { 1921 SCS.Second = ICK_TransparentUnionConversion; 1922 FromType = ToType; 1923 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1924 CStyle)) { 1925 // tryAtomicConversion has updated the standard conversion sequence 1926 // appropriately. 1927 return true; 1928 } else if (ToType->isEventT() && 1929 From->isIntegerConstantExpr(S.getASTContext()) && 1930 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1931 SCS.Second = ICK_Zero_Event_Conversion; 1932 FromType = ToType; 1933 } else if (ToType->isQueueT() && 1934 From->isIntegerConstantExpr(S.getASTContext()) && 1935 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1936 SCS.Second = ICK_Zero_Queue_Conversion; 1937 FromType = ToType; 1938 } else if (ToType->isSamplerT() && 1939 From->isIntegerConstantExpr(S.getASTContext())) { 1940 SCS.Second = ICK_Compatible_Conversion; 1941 FromType = ToType; 1942 } else { 1943 // No second conversion required. 1944 SCS.Second = ICK_Identity; 1945 } 1946 SCS.setToType(1, FromType); 1947 1948 // The third conversion can be a function pointer conversion or a 1949 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1950 bool ObjCLifetimeConversion; 1951 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1952 // Function pointer conversions (removing 'noexcept') including removal of 1953 // 'noreturn' (Clang extension). 1954 SCS.Third = ICK_Function_Conversion; 1955 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1956 ObjCLifetimeConversion)) { 1957 SCS.Third = ICK_Qualification; 1958 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1959 FromType = ToType; 1960 } else { 1961 // No conversion required 1962 SCS.Third = ICK_Identity; 1963 } 1964 1965 // C++ [over.best.ics]p6: 1966 // [...] Any difference in top-level cv-qualification is 1967 // subsumed by the initialization itself and does not constitute 1968 // a conversion. [...] 1969 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1970 QualType CanonTo = S.Context.getCanonicalType(ToType); 1971 if (CanonFrom.getLocalUnqualifiedType() 1972 == CanonTo.getLocalUnqualifiedType() && 1973 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1974 FromType = ToType; 1975 CanonFrom = CanonTo; 1976 } 1977 1978 SCS.setToType(2, FromType); 1979 1980 if (CanonFrom == CanonTo) 1981 return true; 1982 1983 // If we have not converted the argument type to the parameter type, 1984 // this is a bad conversion sequence, unless we're resolving an overload in C. 1985 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1986 return false; 1987 1988 ExprResult ER = ExprResult{From}; 1989 Sema::AssignConvertType Conv = 1990 S.CheckSingleAssignmentConstraints(ToType, ER, 1991 /*Diagnose=*/false, 1992 /*DiagnoseCFAudited=*/false, 1993 /*ConvertRHS=*/false); 1994 ImplicitConversionKind SecondConv; 1995 switch (Conv) { 1996 case Sema::Compatible: 1997 SecondConv = ICK_C_Only_Conversion; 1998 break; 1999 // For our purposes, discarding qualifiers is just as bad as using an 2000 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2001 // qualifiers, as well. 2002 case Sema::CompatiblePointerDiscardsQualifiers: 2003 case Sema::IncompatiblePointer: 2004 case Sema::IncompatiblePointerSign: 2005 SecondConv = ICK_Incompatible_Pointer_Conversion; 2006 break; 2007 default: 2008 return false; 2009 } 2010 2011 // First can only be an lvalue conversion, so we pretend that this was the 2012 // second conversion. First should already be valid from earlier in the 2013 // function. 2014 SCS.Second = SecondConv; 2015 SCS.setToType(1, ToType); 2016 2017 // Third is Identity, because Second should rank us worse than any other 2018 // conversion. This could also be ICK_Qualification, but it's simpler to just 2019 // lump everything in with the second conversion, and we don't gain anything 2020 // from making this ICK_Qualification. 2021 SCS.Third = ICK_Identity; 2022 SCS.setToType(2, ToType); 2023 return true; 2024 } 2025 2026 static bool 2027 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2028 QualType &ToType, 2029 bool InOverloadResolution, 2030 StandardConversionSequence &SCS, 2031 bool CStyle) { 2032 2033 const RecordType *UT = ToType->getAsUnionType(); 2034 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2035 return false; 2036 // The field to initialize within the transparent union. 2037 RecordDecl *UD = UT->getDecl(); 2038 // It's compatible if the expression matches any of the fields. 2039 for (const auto *it : UD->fields()) { 2040 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2041 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2042 ToType = it->getType(); 2043 return true; 2044 } 2045 } 2046 return false; 2047 } 2048 2049 /// IsIntegralPromotion - Determines whether the conversion from the 2050 /// expression From (whose potentially-adjusted type is FromType) to 2051 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2052 /// sets PromotedType to the promoted type. 2053 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2054 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2055 // All integers are built-in. 2056 if (!To) { 2057 return false; 2058 } 2059 2060 // An rvalue of type char, signed char, unsigned char, short int, or 2061 // unsigned short int can be converted to an rvalue of type int if 2062 // int can represent all the values of the source type; otherwise, 2063 // the source rvalue can be converted to an rvalue of type unsigned 2064 // int (C++ 4.5p1). 2065 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2066 !FromType->isEnumeralType()) { 2067 if (// We can promote any signed, promotable integer type to an int 2068 (FromType->isSignedIntegerType() || 2069 // We can promote any unsigned integer type whose size is 2070 // less than int to an int. 2071 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2072 return To->getKind() == BuiltinType::Int; 2073 } 2074 2075 return To->getKind() == BuiltinType::UInt; 2076 } 2077 2078 // C++11 [conv.prom]p3: 2079 // A prvalue of an unscoped enumeration type whose underlying type is not 2080 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2081 // following types that can represent all the values of the enumeration 2082 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2083 // unsigned int, long int, unsigned long int, long long int, or unsigned 2084 // long long int. If none of the types in that list can represent all the 2085 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2086 // type can be converted to an rvalue a prvalue of the extended integer type 2087 // with lowest integer conversion rank (4.13) greater than the rank of long 2088 // long in which all the values of the enumeration can be represented. If 2089 // there are two such extended types, the signed one is chosen. 2090 // C++11 [conv.prom]p4: 2091 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2092 // can be converted to a prvalue of its underlying type. Moreover, if 2093 // integral promotion can be applied to its underlying type, a prvalue of an 2094 // unscoped enumeration type whose underlying type is fixed can also be 2095 // converted to a prvalue of the promoted underlying type. 2096 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2097 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2098 // provided for a scoped enumeration. 2099 if (FromEnumType->getDecl()->isScoped()) 2100 return false; 2101 2102 // We can perform an integral promotion to the underlying type of the enum, 2103 // even if that's not the promoted type. Note that the check for promoting 2104 // the underlying type is based on the type alone, and does not consider 2105 // the bitfield-ness of the actual source expression. 2106 if (FromEnumType->getDecl()->isFixed()) { 2107 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2108 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2109 IsIntegralPromotion(nullptr, Underlying, ToType); 2110 } 2111 2112 // We have already pre-calculated the promotion type, so this is trivial. 2113 if (ToType->isIntegerType() && 2114 isCompleteType(From->getBeginLoc(), FromType)) 2115 return Context.hasSameUnqualifiedType( 2116 ToType, FromEnumType->getDecl()->getPromotionType()); 2117 2118 // C++ [conv.prom]p5: 2119 // If the bit-field has an enumerated type, it is treated as any other 2120 // value of that type for promotion purposes. 2121 // 2122 // ... so do not fall through into the bit-field checks below in C++. 2123 if (getLangOpts().CPlusPlus) 2124 return false; 2125 } 2126 2127 // C++0x [conv.prom]p2: 2128 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2129 // to an rvalue a prvalue of the first of the following types that can 2130 // represent all the values of its underlying type: int, unsigned int, 2131 // long int, unsigned long int, long long int, or unsigned long long int. 2132 // If none of the types in that list can represent all the values of its 2133 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2134 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2135 // type. 2136 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2137 ToType->isIntegerType()) { 2138 // Determine whether the type we're converting from is signed or 2139 // unsigned. 2140 bool FromIsSigned = FromType->isSignedIntegerType(); 2141 uint64_t FromSize = Context.getTypeSize(FromType); 2142 2143 // The types we'll try to promote to, in the appropriate 2144 // order. Try each of these types. 2145 QualType PromoteTypes[6] = { 2146 Context.IntTy, Context.UnsignedIntTy, 2147 Context.LongTy, Context.UnsignedLongTy , 2148 Context.LongLongTy, Context.UnsignedLongLongTy 2149 }; 2150 for (int Idx = 0; Idx < 6; ++Idx) { 2151 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2152 if (FromSize < ToSize || 2153 (FromSize == ToSize && 2154 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2155 // We found the type that we can promote to. If this is the 2156 // type we wanted, we have a promotion. Otherwise, no 2157 // promotion. 2158 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2159 } 2160 } 2161 } 2162 2163 // An rvalue for an integral bit-field (9.6) can be converted to an 2164 // rvalue of type int if int can represent all the values of the 2165 // bit-field; otherwise, it can be converted to unsigned int if 2166 // unsigned int can represent all the values of the bit-field. If 2167 // the bit-field is larger yet, no integral promotion applies to 2168 // it. If the bit-field has an enumerated type, it is treated as any 2169 // other value of that type for promotion purposes (C++ 4.5p3). 2170 // FIXME: We should delay checking of bit-fields until we actually perform the 2171 // conversion. 2172 // 2173 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2174 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2175 // bit-fields and those whose underlying type is larger than int) for GCC 2176 // compatibility. 2177 if (From) { 2178 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2179 llvm::APSInt BitWidth; 2180 if (FromType->isIntegralType(Context) && 2181 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2182 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2183 ToSize = Context.getTypeSize(ToType); 2184 2185 // Are we promoting to an int from a bitfield that fits in an int? 2186 if (BitWidth < ToSize || 2187 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2188 return To->getKind() == BuiltinType::Int; 2189 } 2190 2191 // Are we promoting to an unsigned int from an unsigned bitfield 2192 // that fits into an unsigned int? 2193 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2194 return To->getKind() == BuiltinType::UInt; 2195 } 2196 2197 return false; 2198 } 2199 } 2200 } 2201 2202 // An rvalue of type bool can be converted to an rvalue of type int, 2203 // with false becoming zero and true becoming one (C++ 4.5p4). 2204 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2205 return true; 2206 } 2207 2208 return false; 2209 } 2210 2211 /// IsFloatingPointPromotion - Determines whether the conversion from 2212 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2213 /// returns true and sets PromotedType to the promoted type. 2214 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2215 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2216 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2217 /// An rvalue of type float can be converted to an rvalue of type 2218 /// double. (C++ 4.6p1). 2219 if (FromBuiltin->getKind() == BuiltinType::Float && 2220 ToBuiltin->getKind() == BuiltinType::Double) 2221 return true; 2222 2223 // C99 6.3.1.5p1: 2224 // When a float is promoted to double or long double, or a 2225 // double is promoted to long double [...]. 2226 if (!getLangOpts().CPlusPlus && 2227 (FromBuiltin->getKind() == BuiltinType::Float || 2228 FromBuiltin->getKind() == BuiltinType::Double) && 2229 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2230 ToBuiltin->getKind() == BuiltinType::Float128)) 2231 return true; 2232 2233 // Half can be promoted to float. 2234 if (!getLangOpts().NativeHalfType && 2235 FromBuiltin->getKind() == BuiltinType::Half && 2236 ToBuiltin->getKind() == BuiltinType::Float) 2237 return true; 2238 } 2239 2240 return false; 2241 } 2242 2243 /// Determine if a conversion is a complex promotion. 2244 /// 2245 /// A complex promotion is defined as a complex -> complex conversion 2246 /// where the conversion between the underlying real types is a 2247 /// floating-point or integral promotion. 2248 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2249 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2250 if (!FromComplex) 2251 return false; 2252 2253 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2254 if (!ToComplex) 2255 return false; 2256 2257 return IsFloatingPointPromotion(FromComplex->getElementType(), 2258 ToComplex->getElementType()) || 2259 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2260 ToComplex->getElementType()); 2261 } 2262 2263 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2264 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2265 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2266 /// if non-empty, will be a pointer to ToType that may or may not have 2267 /// the right set of qualifiers on its pointee. 2268 /// 2269 static QualType 2270 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2271 QualType ToPointee, QualType ToType, 2272 ASTContext &Context, 2273 bool StripObjCLifetime = false) { 2274 assert((FromPtr->getTypeClass() == Type::Pointer || 2275 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2276 "Invalid similarly-qualified pointer type"); 2277 2278 /// Conversions to 'id' subsume cv-qualifier conversions. 2279 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2280 return ToType.getUnqualifiedType(); 2281 2282 QualType CanonFromPointee 2283 = Context.getCanonicalType(FromPtr->getPointeeType()); 2284 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2285 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2286 2287 if (StripObjCLifetime) 2288 Quals.removeObjCLifetime(); 2289 2290 // Exact qualifier match -> return the pointer type we're converting to. 2291 if (CanonToPointee.getLocalQualifiers() == Quals) { 2292 // ToType is exactly what we need. Return it. 2293 if (!ToType.isNull()) 2294 return ToType.getUnqualifiedType(); 2295 2296 // Build a pointer to ToPointee. It has the right qualifiers 2297 // already. 2298 if (isa<ObjCObjectPointerType>(ToType)) 2299 return Context.getObjCObjectPointerType(ToPointee); 2300 return Context.getPointerType(ToPointee); 2301 } 2302 2303 // Just build a canonical type that has the right qualifiers. 2304 QualType QualifiedCanonToPointee 2305 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2306 2307 if (isa<ObjCObjectPointerType>(ToType)) 2308 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2309 return Context.getPointerType(QualifiedCanonToPointee); 2310 } 2311 2312 static bool isNullPointerConstantForConversion(Expr *Expr, 2313 bool InOverloadResolution, 2314 ASTContext &Context) { 2315 // Handle value-dependent integral null pointer constants correctly. 2316 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2317 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2318 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2319 return !InOverloadResolution; 2320 2321 return Expr->isNullPointerConstant(Context, 2322 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2323 : Expr::NPC_ValueDependentIsNull); 2324 } 2325 2326 /// IsPointerConversion - Determines whether the conversion of the 2327 /// expression From, which has the (possibly adjusted) type FromType, 2328 /// can be converted to the type ToType via a pointer conversion (C++ 2329 /// 4.10). If so, returns true and places the converted type (that 2330 /// might differ from ToType in its cv-qualifiers at some level) into 2331 /// ConvertedType. 2332 /// 2333 /// This routine also supports conversions to and from block pointers 2334 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2335 /// pointers to interfaces. FIXME: Once we've determined the 2336 /// appropriate overloading rules for Objective-C, we may want to 2337 /// split the Objective-C checks into a different routine; however, 2338 /// GCC seems to consider all of these conversions to be pointer 2339 /// conversions, so for now they live here. IncompatibleObjC will be 2340 /// set if the conversion is an allowed Objective-C conversion that 2341 /// should result in a warning. 2342 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2343 bool InOverloadResolution, 2344 QualType& ConvertedType, 2345 bool &IncompatibleObjC) { 2346 IncompatibleObjC = false; 2347 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2348 IncompatibleObjC)) 2349 return true; 2350 2351 // Conversion from a null pointer constant to any Objective-C pointer type. 2352 if (ToType->isObjCObjectPointerType() && 2353 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2354 ConvertedType = ToType; 2355 return true; 2356 } 2357 2358 // Blocks: Block pointers can be converted to void*. 2359 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2360 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2361 ConvertedType = ToType; 2362 return true; 2363 } 2364 // Blocks: A null pointer constant can be converted to a block 2365 // pointer type. 2366 if (ToType->isBlockPointerType() && 2367 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2368 ConvertedType = ToType; 2369 return true; 2370 } 2371 2372 // If the left-hand-side is nullptr_t, the right side can be a null 2373 // pointer constant. 2374 if (ToType->isNullPtrType() && 2375 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2376 ConvertedType = ToType; 2377 return true; 2378 } 2379 2380 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2381 if (!ToTypePtr) 2382 return false; 2383 2384 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2385 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2386 ConvertedType = ToType; 2387 return true; 2388 } 2389 2390 // Beyond this point, both types need to be pointers 2391 // , including objective-c pointers. 2392 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2393 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2394 !getLangOpts().ObjCAutoRefCount) { 2395 ConvertedType = BuildSimilarlyQualifiedPointerType( 2396 FromType->getAs<ObjCObjectPointerType>(), 2397 ToPointeeType, 2398 ToType, Context); 2399 return true; 2400 } 2401 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2402 if (!FromTypePtr) 2403 return false; 2404 2405 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2406 2407 // If the unqualified pointee types are the same, this can't be a 2408 // pointer conversion, so don't do all of the work below. 2409 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2410 return false; 2411 2412 // An rvalue of type "pointer to cv T," where T is an object type, 2413 // can be converted to an rvalue of type "pointer to cv void" (C++ 2414 // 4.10p2). 2415 if (FromPointeeType->isIncompleteOrObjectType() && 2416 ToPointeeType->isVoidType()) { 2417 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2418 ToPointeeType, 2419 ToType, Context, 2420 /*StripObjCLifetime=*/true); 2421 return true; 2422 } 2423 2424 // MSVC allows implicit function to void* type conversion. 2425 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2426 ToPointeeType->isVoidType()) { 2427 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2428 ToPointeeType, 2429 ToType, Context); 2430 return true; 2431 } 2432 2433 // When we're overloading in C, we allow a special kind of pointer 2434 // conversion for compatible-but-not-identical pointee types. 2435 if (!getLangOpts().CPlusPlus && 2436 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2437 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2438 ToPointeeType, 2439 ToType, Context); 2440 return true; 2441 } 2442 2443 // C++ [conv.ptr]p3: 2444 // 2445 // An rvalue of type "pointer to cv D," where D is a class type, 2446 // can be converted to an rvalue of type "pointer to cv B," where 2447 // B is a base class (clause 10) of D. If B is an inaccessible 2448 // (clause 11) or ambiguous (10.2) base class of D, a program that 2449 // necessitates this conversion is ill-formed. The result of the 2450 // conversion is a pointer to the base class sub-object of the 2451 // derived class object. The null pointer value is converted to 2452 // the null pointer value of the destination type. 2453 // 2454 // Note that we do not check for ambiguity or inaccessibility 2455 // here. That is handled by CheckPointerConversion. 2456 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2457 ToPointeeType->isRecordType() && 2458 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2459 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2460 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2461 ToPointeeType, 2462 ToType, Context); 2463 return true; 2464 } 2465 2466 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2467 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2468 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2469 ToPointeeType, 2470 ToType, Context); 2471 return true; 2472 } 2473 2474 return false; 2475 } 2476 2477 /// Adopt the given qualifiers for the given type. 2478 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2479 Qualifiers TQs = T.getQualifiers(); 2480 2481 // Check whether qualifiers already match. 2482 if (TQs == Qs) 2483 return T; 2484 2485 if (Qs.compatiblyIncludes(TQs)) 2486 return Context.getQualifiedType(T, Qs); 2487 2488 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2489 } 2490 2491 /// isObjCPointerConversion - Determines whether this is an 2492 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2493 /// with the same arguments and return values. 2494 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2495 QualType& ConvertedType, 2496 bool &IncompatibleObjC) { 2497 if (!getLangOpts().ObjC) 2498 return false; 2499 2500 // The set of qualifiers on the type we're converting from. 2501 Qualifiers FromQualifiers = FromType.getQualifiers(); 2502 2503 // First, we handle all conversions on ObjC object pointer types. 2504 const ObjCObjectPointerType* ToObjCPtr = 2505 ToType->getAs<ObjCObjectPointerType>(); 2506 const ObjCObjectPointerType *FromObjCPtr = 2507 FromType->getAs<ObjCObjectPointerType>(); 2508 2509 if (ToObjCPtr && FromObjCPtr) { 2510 // If the pointee types are the same (ignoring qualifications), 2511 // then this is not a pointer conversion. 2512 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2513 FromObjCPtr->getPointeeType())) 2514 return false; 2515 2516 // Conversion between Objective-C pointers. 2517 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2518 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2519 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2520 if (getLangOpts().CPlusPlus && LHS && RHS && 2521 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2522 FromObjCPtr->getPointeeType())) 2523 return false; 2524 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2525 ToObjCPtr->getPointeeType(), 2526 ToType, Context); 2527 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2528 return true; 2529 } 2530 2531 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2532 // Okay: this is some kind of implicit downcast of Objective-C 2533 // interfaces, which is permitted. However, we're going to 2534 // complain about it. 2535 IncompatibleObjC = true; 2536 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2537 ToObjCPtr->getPointeeType(), 2538 ToType, Context); 2539 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2540 return true; 2541 } 2542 } 2543 // Beyond this point, both types need to be C pointers or block pointers. 2544 QualType ToPointeeType; 2545 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2546 ToPointeeType = ToCPtr->getPointeeType(); 2547 else if (const BlockPointerType *ToBlockPtr = 2548 ToType->getAs<BlockPointerType>()) { 2549 // Objective C++: We're able to convert from a pointer to any object 2550 // to a block pointer type. 2551 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2552 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2553 return true; 2554 } 2555 ToPointeeType = ToBlockPtr->getPointeeType(); 2556 } 2557 else if (FromType->getAs<BlockPointerType>() && 2558 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2559 // Objective C++: We're able to convert from a block pointer type to a 2560 // pointer to any object. 2561 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2562 return true; 2563 } 2564 else 2565 return false; 2566 2567 QualType FromPointeeType; 2568 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2569 FromPointeeType = FromCPtr->getPointeeType(); 2570 else if (const BlockPointerType *FromBlockPtr = 2571 FromType->getAs<BlockPointerType>()) 2572 FromPointeeType = FromBlockPtr->getPointeeType(); 2573 else 2574 return false; 2575 2576 // If we have pointers to pointers, recursively check whether this 2577 // is an Objective-C conversion. 2578 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2579 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2580 IncompatibleObjC)) { 2581 // We always complain about this conversion. 2582 IncompatibleObjC = true; 2583 ConvertedType = Context.getPointerType(ConvertedType); 2584 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2585 return true; 2586 } 2587 // Allow conversion of pointee being objective-c pointer to another one; 2588 // as in I* to id. 2589 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2590 ToPointeeType->getAs<ObjCObjectPointerType>() && 2591 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2592 IncompatibleObjC)) { 2593 2594 ConvertedType = Context.getPointerType(ConvertedType); 2595 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2596 return true; 2597 } 2598 2599 // If we have pointers to functions or blocks, check whether the only 2600 // differences in the argument and result types are in Objective-C 2601 // pointer conversions. If so, we permit the conversion (but 2602 // complain about it). 2603 const FunctionProtoType *FromFunctionType 2604 = FromPointeeType->getAs<FunctionProtoType>(); 2605 const FunctionProtoType *ToFunctionType 2606 = ToPointeeType->getAs<FunctionProtoType>(); 2607 if (FromFunctionType && ToFunctionType) { 2608 // If the function types are exactly the same, this isn't an 2609 // Objective-C pointer conversion. 2610 if (Context.getCanonicalType(FromPointeeType) 2611 == Context.getCanonicalType(ToPointeeType)) 2612 return false; 2613 2614 // Perform the quick checks that will tell us whether these 2615 // function types are obviously different. 2616 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2617 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2618 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2619 return false; 2620 2621 bool HasObjCConversion = false; 2622 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2623 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2624 // Okay, the types match exactly. Nothing to do. 2625 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2626 ToFunctionType->getReturnType(), 2627 ConvertedType, IncompatibleObjC)) { 2628 // Okay, we have an Objective-C pointer conversion. 2629 HasObjCConversion = true; 2630 } else { 2631 // Function types are too different. Abort. 2632 return false; 2633 } 2634 2635 // Check argument types. 2636 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2637 ArgIdx != NumArgs; ++ArgIdx) { 2638 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2639 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2640 if (Context.getCanonicalType(FromArgType) 2641 == Context.getCanonicalType(ToArgType)) { 2642 // Okay, the types match exactly. Nothing to do. 2643 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2644 ConvertedType, IncompatibleObjC)) { 2645 // Okay, we have an Objective-C pointer conversion. 2646 HasObjCConversion = true; 2647 } else { 2648 // Argument types are too different. Abort. 2649 return false; 2650 } 2651 } 2652 2653 if (HasObjCConversion) { 2654 // We had an Objective-C conversion. Allow this pointer 2655 // conversion, but complain about it. 2656 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2657 IncompatibleObjC = true; 2658 return true; 2659 } 2660 } 2661 2662 return false; 2663 } 2664 2665 /// Determine whether this is an Objective-C writeback conversion, 2666 /// used for parameter passing when performing automatic reference counting. 2667 /// 2668 /// \param FromType The type we're converting form. 2669 /// 2670 /// \param ToType The type we're converting to. 2671 /// 2672 /// \param ConvertedType The type that will be produced after applying 2673 /// this conversion. 2674 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2675 QualType &ConvertedType) { 2676 if (!getLangOpts().ObjCAutoRefCount || 2677 Context.hasSameUnqualifiedType(FromType, ToType)) 2678 return false; 2679 2680 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2681 QualType ToPointee; 2682 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2683 ToPointee = ToPointer->getPointeeType(); 2684 else 2685 return false; 2686 2687 Qualifiers ToQuals = ToPointee.getQualifiers(); 2688 if (!ToPointee->isObjCLifetimeType() || 2689 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2690 !ToQuals.withoutObjCLifetime().empty()) 2691 return false; 2692 2693 // Argument must be a pointer to __strong to __weak. 2694 QualType FromPointee; 2695 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2696 FromPointee = FromPointer->getPointeeType(); 2697 else 2698 return false; 2699 2700 Qualifiers FromQuals = FromPointee.getQualifiers(); 2701 if (!FromPointee->isObjCLifetimeType() || 2702 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2703 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2704 return false; 2705 2706 // Make sure that we have compatible qualifiers. 2707 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2708 if (!ToQuals.compatiblyIncludes(FromQuals)) 2709 return false; 2710 2711 // Remove qualifiers from the pointee type we're converting from; they 2712 // aren't used in the compatibility check belong, and we'll be adding back 2713 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2714 FromPointee = FromPointee.getUnqualifiedType(); 2715 2716 // The unqualified form of the pointee types must be compatible. 2717 ToPointee = ToPointee.getUnqualifiedType(); 2718 bool IncompatibleObjC; 2719 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2720 FromPointee = ToPointee; 2721 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2722 IncompatibleObjC)) 2723 return false; 2724 2725 /// Construct the type we're converting to, which is a pointer to 2726 /// __autoreleasing pointee. 2727 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2728 ConvertedType = Context.getPointerType(FromPointee); 2729 return true; 2730 } 2731 2732 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2733 QualType& ConvertedType) { 2734 QualType ToPointeeType; 2735 if (const BlockPointerType *ToBlockPtr = 2736 ToType->getAs<BlockPointerType>()) 2737 ToPointeeType = ToBlockPtr->getPointeeType(); 2738 else 2739 return false; 2740 2741 QualType FromPointeeType; 2742 if (const BlockPointerType *FromBlockPtr = 2743 FromType->getAs<BlockPointerType>()) 2744 FromPointeeType = FromBlockPtr->getPointeeType(); 2745 else 2746 return false; 2747 // We have pointer to blocks, check whether the only 2748 // differences in the argument and result types are in Objective-C 2749 // pointer conversions. If so, we permit the conversion. 2750 2751 const FunctionProtoType *FromFunctionType 2752 = FromPointeeType->getAs<FunctionProtoType>(); 2753 const FunctionProtoType *ToFunctionType 2754 = ToPointeeType->getAs<FunctionProtoType>(); 2755 2756 if (!FromFunctionType || !ToFunctionType) 2757 return false; 2758 2759 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2760 return true; 2761 2762 // Perform the quick checks that will tell us whether these 2763 // function types are obviously different. 2764 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2765 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2766 return false; 2767 2768 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2769 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2770 if (FromEInfo != ToEInfo) 2771 return false; 2772 2773 bool IncompatibleObjC = false; 2774 if (Context.hasSameType(FromFunctionType->getReturnType(), 2775 ToFunctionType->getReturnType())) { 2776 // Okay, the types match exactly. Nothing to do. 2777 } else { 2778 QualType RHS = FromFunctionType->getReturnType(); 2779 QualType LHS = ToFunctionType->getReturnType(); 2780 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2781 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2782 LHS = LHS.getUnqualifiedType(); 2783 2784 if (Context.hasSameType(RHS,LHS)) { 2785 // OK exact match. 2786 } else if (isObjCPointerConversion(RHS, LHS, 2787 ConvertedType, IncompatibleObjC)) { 2788 if (IncompatibleObjC) 2789 return false; 2790 // Okay, we have an Objective-C pointer conversion. 2791 } 2792 else 2793 return false; 2794 } 2795 2796 // Check argument types. 2797 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2798 ArgIdx != NumArgs; ++ArgIdx) { 2799 IncompatibleObjC = false; 2800 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2801 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2802 if (Context.hasSameType(FromArgType, ToArgType)) { 2803 // Okay, the types match exactly. Nothing to do. 2804 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2805 ConvertedType, IncompatibleObjC)) { 2806 if (IncompatibleObjC) 2807 return false; 2808 // Okay, we have an Objective-C pointer conversion. 2809 } else 2810 // Argument types are too different. Abort. 2811 return false; 2812 } 2813 2814 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2815 bool CanUseToFPT, CanUseFromFPT; 2816 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2817 CanUseToFPT, CanUseFromFPT, 2818 NewParamInfos)) 2819 return false; 2820 2821 ConvertedType = ToType; 2822 return true; 2823 } 2824 2825 enum { 2826 ft_default, 2827 ft_different_class, 2828 ft_parameter_arity, 2829 ft_parameter_mismatch, 2830 ft_return_type, 2831 ft_qualifer_mismatch, 2832 ft_noexcept 2833 }; 2834 2835 /// Attempts to get the FunctionProtoType from a Type. Handles 2836 /// MemberFunctionPointers properly. 2837 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2838 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2839 return FPT; 2840 2841 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2842 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2843 2844 return nullptr; 2845 } 2846 2847 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2848 /// function types. Catches different number of parameter, mismatch in 2849 /// parameter types, and different return types. 2850 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2851 QualType FromType, QualType ToType) { 2852 // If either type is not valid, include no extra info. 2853 if (FromType.isNull() || ToType.isNull()) { 2854 PDiag << ft_default; 2855 return; 2856 } 2857 2858 // Get the function type from the pointers. 2859 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2860 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2861 *ToMember = ToType->castAs<MemberPointerType>(); 2862 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2863 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2864 << QualType(FromMember->getClass(), 0); 2865 return; 2866 } 2867 FromType = FromMember->getPointeeType(); 2868 ToType = ToMember->getPointeeType(); 2869 } 2870 2871 if (FromType->isPointerType()) 2872 FromType = FromType->getPointeeType(); 2873 if (ToType->isPointerType()) 2874 ToType = ToType->getPointeeType(); 2875 2876 // Remove references. 2877 FromType = FromType.getNonReferenceType(); 2878 ToType = ToType.getNonReferenceType(); 2879 2880 // Don't print extra info for non-specialized template functions. 2881 if (FromType->isInstantiationDependentType() && 2882 !FromType->getAs<TemplateSpecializationType>()) { 2883 PDiag << ft_default; 2884 return; 2885 } 2886 2887 // No extra info for same types. 2888 if (Context.hasSameType(FromType, ToType)) { 2889 PDiag << ft_default; 2890 return; 2891 } 2892 2893 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2894 *ToFunction = tryGetFunctionProtoType(ToType); 2895 2896 // Both types need to be function types. 2897 if (!FromFunction || !ToFunction) { 2898 PDiag << ft_default; 2899 return; 2900 } 2901 2902 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2903 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2904 << FromFunction->getNumParams(); 2905 return; 2906 } 2907 2908 // Handle different parameter types. 2909 unsigned ArgPos; 2910 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2911 PDiag << ft_parameter_mismatch << ArgPos + 1 2912 << ToFunction->getParamType(ArgPos) 2913 << FromFunction->getParamType(ArgPos); 2914 return; 2915 } 2916 2917 // Handle different return type. 2918 if (!Context.hasSameType(FromFunction->getReturnType(), 2919 ToFunction->getReturnType())) { 2920 PDiag << ft_return_type << ToFunction->getReturnType() 2921 << FromFunction->getReturnType(); 2922 return; 2923 } 2924 2925 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2926 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2927 << FromFunction->getMethodQuals(); 2928 return; 2929 } 2930 2931 // Handle exception specification differences on canonical type (in C++17 2932 // onwards). 2933 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2934 ->isNothrow() != 2935 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2936 ->isNothrow()) { 2937 PDiag << ft_noexcept; 2938 return; 2939 } 2940 2941 // Unable to find a difference, so add no extra info. 2942 PDiag << ft_default; 2943 } 2944 2945 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2946 /// for equality of their argument types. Caller has already checked that 2947 /// they have same number of arguments. If the parameters are different, 2948 /// ArgPos will have the parameter index of the first different parameter. 2949 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2950 const FunctionProtoType *NewType, 2951 unsigned *ArgPos) { 2952 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2953 N = NewType->param_type_begin(), 2954 E = OldType->param_type_end(); 2955 O && (O != E); ++O, ++N) { 2956 // Ignore address spaces in pointee type. This is to disallow overloading 2957 // on __ptr32/__ptr64 address spaces. 2958 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2959 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2960 2961 if (!Context.hasSameType(Old, New)) { 2962 if (ArgPos) 2963 *ArgPos = O - OldType->param_type_begin(); 2964 return false; 2965 } 2966 } 2967 return true; 2968 } 2969 2970 /// CheckPointerConversion - Check the pointer conversion from the 2971 /// expression From to the type ToType. This routine checks for 2972 /// ambiguous or inaccessible derived-to-base pointer 2973 /// conversions for which IsPointerConversion has already returned 2974 /// true. It returns true and produces a diagnostic if there was an 2975 /// error, or returns false otherwise. 2976 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2977 CastKind &Kind, 2978 CXXCastPath& BasePath, 2979 bool IgnoreBaseAccess, 2980 bool Diagnose) { 2981 QualType FromType = From->getType(); 2982 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2983 2984 Kind = CK_BitCast; 2985 2986 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2987 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2988 Expr::NPCK_ZeroExpression) { 2989 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2990 DiagRuntimeBehavior(From->getExprLoc(), From, 2991 PDiag(diag::warn_impcast_bool_to_null_pointer) 2992 << ToType << From->getSourceRange()); 2993 else if (!isUnevaluatedContext()) 2994 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2995 << ToType << From->getSourceRange(); 2996 } 2997 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2998 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2999 QualType FromPointeeType = FromPtrType->getPointeeType(), 3000 ToPointeeType = ToPtrType->getPointeeType(); 3001 3002 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3003 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3004 // We must have a derived-to-base conversion. Check an 3005 // ambiguous or inaccessible conversion. 3006 unsigned InaccessibleID = 0; 3007 unsigned AmbigiousID = 0; 3008 if (Diagnose) { 3009 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3010 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 3011 } 3012 if (CheckDerivedToBaseConversion( 3013 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 3014 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3015 &BasePath, IgnoreBaseAccess)) 3016 return true; 3017 3018 // The conversion was successful. 3019 Kind = CK_DerivedToBase; 3020 } 3021 3022 if (Diagnose && !IsCStyleOrFunctionalCast && 3023 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3024 assert(getLangOpts().MSVCCompat && 3025 "this should only be possible with MSVCCompat!"); 3026 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3027 << From->getSourceRange(); 3028 } 3029 } 3030 } else if (const ObjCObjectPointerType *ToPtrType = 3031 ToType->getAs<ObjCObjectPointerType>()) { 3032 if (const ObjCObjectPointerType *FromPtrType = 3033 FromType->getAs<ObjCObjectPointerType>()) { 3034 // Objective-C++ conversions are always okay. 3035 // FIXME: We should have a different class of conversions for the 3036 // Objective-C++ implicit conversions. 3037 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3038 return false; 3039 } else if (FromType->isBlockPointerType()) { 3040 Kind = CK_BlockPointerToObjCPointerCast; 3041 } else { 3042 Kind = CK_CPointerToObjCPointerCast; 3043 } 3044 } else if (ToType->isBlockPointerType()) { 3045 if (!FromType->isBlockPointerType()) 3046 Kind = CK_AnyPointerToBlockPointerCast; 3047 } 3048 3049 // We shouldn't fall into this case unless it's valid for other 3050 // reasons. 3051 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3052 Kind = CK_NullToPointer; 3053 3054 return false; 3055 } 3056 3057 /// IsMemberPointerConversion - Determines whether the conversion of the 3058 /// expression From, which has the (possibly adjusted) type FromType, can be 3059 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3060 /// If so, returns true and places the converted type (that might differ from 3061 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3062 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3063 QualType ToType, 3064 bool InOverloadResolution, 3065 QualType &ConvertedType) { 3066 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3067 if (!ToTypePtr) 3068 return false; 3069 3070 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3071 if (From->isNullPointerConstant(Context, 3072 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3073 : Expr::NPC_ValueDependentIsNull)) { 3074 ConvertedType = ToType; 3075 return true; 3076 } 3077 3078 // Otherwise, both types have to be member pointers. 3079 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3080 if (!FromTypePtr) 3081 return false; 3082 3083 // A pointer to member of B can be converted to a pointer to member of D, 3084 // where D is derived from B (C++ 4.11p2). 3085 QualType FromClass(FromTypePtr->getClass(), 0); 3086 QualType ToClass(ToTypePtr->getClass(), 0); 3087 3088 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3089 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3090 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3091 ToClass.getTypePtr()); 3092 return true; 3093 } 3094 3095 return false; 3096 } 3097 3098 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3099 /// expression From to the type ToType. This routine checks for ambiguous or 3100 /// virtual or inaccessible base-to-derived member pointer conversions 3101 /// for which IsMemberPointerConversion has already returned true. It returns 3102 /// true and produces a diagnostic if there was an error, or returns false 3103 /// otherwise. 3104 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3105 CastKind &Kind, 3106 CXXCastPath &BasePath, 3107 bool IgnoreBaseAccess) { 3108 QualType FromType = From->getType(); 3109 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3110 if (!FromPtrType) { 3111 // This must be a null pointer to member pointer conversion 3112 assert(From->isNullPointerConstant(Context, 3113 Expr::NPC_ValueDependentIsNull) && 3114 "Expr must be null pointer constant!"); 3115 Kind = CK_NullToMemberPointer; 3116 return false; 3117 } 3118 3119 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3120 assert(ToPtrType && "No member pointer cast has a target type " 3121 "that is not a member pointer."); 3122 3123 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3124 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3125 3126 // FIXME: What about dependent types? 3127 assert(FromClass->isRecordType() && "Pointer into non-class."); 3128 assert(ToClass->isRecordType() && "Pointer into non-class."); 3129 3130 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3131 /*DetectVirtual=*/true); 3132 bool DerivationOkay = 3133 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3134 assert(DerivationOkay && 3135 "Should not have been called if derivation isn't OK."); 3136 (void)DerivationOkay; 3137 3138 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3139 getUnqualifiedType())) { 3140 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3141 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3142 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3143 return true; 3144 } 3145 3146 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3147 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3148 << FromClass << ToClass << QualType(VBase, 0) 3149 << From->getSourceRange(); 3150 return true; 3151 } 3152 3153 if (!IgnoreBaseAccess) 3154 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3155 Paths.front(), 3156 diag::err_downcast_from_inaccessible_base); 3157 3158 // Must be a base to derived member conversion. 3159 BuildBasePathArray(Paths, BasePath); 3160 Kind = CK_BaseToDerivedMemberPointer; 3161 return false; 3162 } 3163 3164 /// Determine whether the lifetime conversion between the two given 3165 /// qualifiers sets is nontrivial. 3166 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3167 Qualifiers ToQuals) { 3168 // Converting anything to const __unsafe_unretained is trivial. 3169 if (ToQuals.hasConst() && 3170 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3171 return false; 3172 3173 return true; 3174 } 3175 3176 /// Perform a single iteration of the loop for checking if a qualification 3177 /// conversion is valid. 3178 /// 3179 /// Specifically, check whether any change between the qualifiers of \p 3180 /// FromType and \p ToType is permissible, given knowledge about whether every 3181 /// outer layer is const-qualified. 3182 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3183 bool CStyle, 3184 bool &PreviousToQualsIncludeConst, 3185 bool &ObjCLifetimeConversion) { 3186 Qualifiers FromQuals = FromType.getQualifiers(); 3187 Qualifiers ToQuals = ToType.getQualifiers(); 3188 3189 // Ignore __unaligned qualifier if this type is void. 3190 if (ToType.getUnqualifiedType()->isVoidType()) 3191 FromQuals.removeUnaligned(); 3192 3193 // Objective-C ARC: 3194 // Check Objective-C lifetime conversions. 3195 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3196 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3197 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3198 ObjCLifetimeConversion = true; 3199 FromQuals.removeObjCLifetime(); 3200 ToQuals.removeObjCLifetime(); 3201 } else { 3202 // Qualification conversions cannot cast between different 3203 // Objective-C lifetime qualifiers. 3204 return false; 3205 } 3206 } 3207 3208 // Allow addition/removal of GC attributes but not changing GC attributes. 3209 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3210 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3211 FromQuals.removeObjCGCAttr(); 3212 ToQuals.removeObjCGCAttr(); 3213 } 3214 3215 // -- for every j > 0, if const is in cv 1,j then const is in cv 3216 // 2,j, and similarly for volatile. 3217 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3218 return false; 3219 3220 // For a C-style cast, just require the address spaces to overlap. 3221 // FIXME: Does "superset" also imply the representation of a pointer is the 3222 // same? We're assuming that it does here and in compatiblyIncludes. 3223 if (CStyle && !ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3224 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) 3225 return false; 3226 3227 // -- if the cv 1,j and cv 2,j are different, then const is in 3228 // every cv for 0 < k < j. 3229 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3230 !PreviousToQualsIncludeConst) 3231 return false; 3232 3233 // Keep track of whether all prior cv-qualifiers in the "to" type 3234 // include const. 3235 PreviousToQualsIncludeConst = 3236 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3237 return true; 3238 } 3239 3240 /// IsQualificationConversion - Determines whether the conversion from 3241 /// an rvalue of type FromType to ToType is a qualification conversion 3242 /// (C++ 4.4). 3243 /// 3244 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3245 /// when the qualification conversion involves a change in the Objective-C 3246 /// object lifetime. 3247 bool 3248 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3249 bool CStyle, bool &ObjCLifetimeConversion) { 3250 FromType = Context.getCanonicalType(FromType); 3251 ToType = Context.getCanonicalType(ToType); 3252 ObjCLifetimeConversion = false; 3253 3254 // If FromType and ToType are the same type, this is not a 3255 // qualification conversion. 3256 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3257 return false; 3258 3259 // (C++ 4.4p4): 3260 // A conversion can add cv-qualifiers at levels other than the first 3261 // in multi-level pointers, subject to the following rules: [...] 3262 bool PreviousToQualsIncludeConst = true; 3263 bool UnwrappedAnyPointer = false; 3264 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3265 if (!isQualificationConversionStep(FromType, ToType, CStyle, 3266 PreviousToQualsIncludeConst, 3267 ObjCLifetimeConversion)) 3268 return false; 3269 UnwrappedAnyPointer = true; 3270 } 3271 3272 // We are left with FromType and ToType being the pointee types 3273 // after unwrapping the original FromType and ToType the same number 3274 // of times. If we unwrapped any pointers, and if FromType and 3275 // ToType have the same unqualified type (since we checked 3276 // qualifiers above), then this is a qualification conversion. 3277 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3278 } 3279 3280 /// - Determine whether this is a conversion from a scalar type to an 3281 /// atomic type. 3282 /// 3283 /// If successful, updates \c SCS's second and third steps in the conversion 3284 /// sequence to finish the conversion. 3285 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3286 bool InOverloadResolution, 3287 StandardConversionSequence &SCS, 3288 bool CStyle) { 3289 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3290 if (!ToAtomic) 3291 return false; 3292 3293 StandardConversionSequence InnerSCS; 3294 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3295 InOverloadResolution, InnerSCS, 3296 CStyle, /*AllowObjCWritebackConversion=*/false)) 3297 return false; 3298 3299 SCS.Second = InnerSCS.Second; 3300 SCS.setToType(1, InnerSCS.getToType(1)); 3301 SCS.Third = InnerSCS.Third; 3302 SCS.QualificationIncludesObjCLifetime 3303 = InnerSCS.QualificationIncludesObjCLifetime; 3304 SCS.setToType(2, InnerSCS.getToType(2)); 3305 return true; 3306 } 3307 3308 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3309 CXXConstructorDecl *Constructor, 3310 QualType Type) { 3311 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3312 if (CtorType->getNumParams() > 0) { 3313 QualType FirstArg = CtorType->getParamType(0); 3314 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3315 return true; 3316 } 3317 return false; 3318 } 3319 3320 static OverloadingResult 3321 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3322 CXXRecordDecl *To, 3323 UserDefinedConversionSequence &User, 3324 OverloadCandidateSet &CandidateSet, 3325 bool AllowExplicit) { 3326 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3327 for (auto *D : S.LookupConstructors(To)) { 3328 auto Info = getConstructorInfo(D); 3329 if (!Info) 3330 continue; 3331 3332 bool Usable = !Info.Constructor->isInvalidDecl() && 3333 S.isInitListConstructor(Info.Constructor); 3334 if (Usable) { 3335 // If the first argument is (a reference to) the target type, 3336 // suppress conversions. 3337 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3338 S.Context, Info.Constructor, ToType); 3339 if (Info.ConstructorTmpl) 3340 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3341 /*ExplicitArgs*/ nullptr, From, 3342 CandidateSet, SuppressUserConversions, 3343 /*PartialOverloading*/ false, 3344 AllowExplicit); 3345 else 3346 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3347 CandidateSet, SuppressUserConversions, 3348 /*PartialOverloading*/ false, AllowExplicit); 3349 } 3350 } 3351 3352 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3353 3354 OverloadCandidateSet::iterator Best; 3355 switch (auto Result = 3356 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3357 case OR_Deleted: 3358 case OR_Success: { 3359 // Record the standard conversion we used and the conversion function. 3360 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3361 QualType ThisType = Constructor->getThisType(); 3362 // Initializer lists don't have conversions as such. 3363 User.Before.setAsIdentityConversion(); 3364 User.HadMultipleCandidates = HadMultipleCandidates; 3365 User.ConversionFunction = Constructor; 3366 User.FoundConversionFunction = Best->FoundDecl; 3367 User.After.setAsIdentityConversion(); 3368 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3369 User.After.setAllToTypes(ToType); 3370 return Result; 3371 } 3372 3373 case OR_No_Viable_Function: 3374 return OR_No_Viable_Function; 3375 case OR_Ambiguous: 3376 return OR_Ambiguous; 3377 } 3378 3379 llvm_unreachable("Invalid OverloadResult!"); 3380 } 3381 3382 /// Determines whether there is a user-defined conversion sequence 3383 /// (C++ [over.ics.user]) that converts expression From to the type 3384 /// ToType. If such a conversion exists, User will contain the 3385 /// user-defined conversion sequence that performs such a conversion 3386 /// and this routine will return true. Otherwise, this routine returns 3387 /// false and User is unspecified. 3388 /// 3389 /// \param AllowExplicit true if the conversion should consider C++0x 3390 /// "explicit" conversion functions as well as non-explicit conversion 3391 /// functions (C++0x [class.conv.fct]p2). 3392 /// 3393 /// \param AllowObjCConversionOnExplicit true if the conversion should 3394 /// allow an extra Objective-C pointer conversion on uses of explicit 3395 /// constructors. Requires \c AllowExplicit to also be set. 3396 static OverloadingResult 3397 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3398 UserDefinedConversionSequence &User, 3399 OverloadCandidateSet &CandidateSet, 3400 AllowedExplicit AllowExplicit, 3401 bool AllowObjCConversionOnExplicit) { 3402 assert(AllowExplicit != AllowedExplicit::None || 3403 !AllowObjCConversionOnExplicit); 3404 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3405 3406 // Whether we will only visit constructors. 3407 bool ConstructorsOnly = false; 3408 3409 // If the type we are conversion to is a class type, enumerate its 3410 // constructors. 3411 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3412 // C++ [over.match.ctor]p1: 3413 // When objects of class type are direct-initialized (8.5), or 3414 // copy-initialized from an expression of the same or a 3415 // derived class type (8.5), overload resolution selects the 3416 // constructor. [...] For copy-initialization, the candidate 3417 // functions are all the converting constructors (12.3.1) of 3418 // that class. The argument list is the expression-list within 3419 // the parentheses of the initializer. 3420 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3421 (From->getType()->getAs<RecordType>() && 3422 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3423 ConstructorsOnly = true; 3424 3425 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3426 // We're not going to find any constructors. 3427 } else if (CXXRecordDecl *ToRecordDecl 3428 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3429 3430 Expr **Args = &From; 3431 unsigned NumArgs = 1; 3432 bool ListInitializing = false; 3433 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3434 // But first, see if there is an init-list-constructor that will work. 3435 OverloadingResult Result = IsInitializerListConstructorConversion( 3436 S, From, ToType, ToRecordDecl, User, CandidateSet, 3437 AllowExplicit == AllowedExplicit::All); 3438 if (Result != OR_No_Viable_Function) 3439 return Result; 3440 // Never mind. 3441 CandidateSet.clear( 3442 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3443 3444 // If we're list-initializing, we pass the individual elements as 3445 // arguments, not the entire list. 3446 Args = InitList->getInits(); 3447 NumArgs = InitList->getNumInits(); 3448 ListInitializing = true; 3449 } 3450 3451 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3452 auto Info = getConstructorInfo(D); 3453 if (!Info) 3454 continue; 3455 3456 bool Usable = !Info.Constructor->isInvalidDecl(); 3457 if (!ListInitializing) 3458 Usable = Usable && Info.Constructor->isConvertingConstructor( 3459 /*AllowExplicit*/ true); 3460 if (Usable) { 3461 bool SuppressUserConversions = !ConstructorsOnly; 3462 if (SuppressUserConversions && ListInitializing) { 3463 SuppressUserConversions = false; 3464 if (NumArgs == 1) { 3465 // If the first argument is (a reference to) the target type, 3466 // suppress conversions. 3467 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3468 S.Context, Info.Constructor, ToType); 3469 } 3470 } 3471 if (Info.ConstructorTmpl) 3472 S.AddTemplateOverloadCandidate( 3473 Info.ConstructorTmpl, Info.FoundDecl, 3474 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3475 CandidateSet, SuppressUserConversions, 3476 /*PartialOverloading*/ false, 3477 AllowExplicit == AllowedExplicit::All); 3478 else 3479 // Allow one user-defined conversion when user specifies a 3480 // From->ToType conversion via an static cast (c-style, etc). 3481 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3482 llvm::makeArrayRef(Args, NumArgs), 3483 CandidateSet, SuppressUserConversions, 3484 /*PartialOverloading*/ false, 3485 AllowExplicit == AllowedExplicit::All); 3486 } 3487 } 3488 } 3489 } 3490 3491 // Enumerate conversion functions, if we're allowed to. 3492 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3493 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3494 // No conversion functions from incomplete types. 3495 } else if (const RecordType *FromRecordType = 3496 From->getType()->getAs<RecordType>()) { 3497 if (CXXRecordDecl *FromRecordDecl 3498 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3499 // Add all of the conversion functions as candidates. 3500 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3501 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3502 DeclAccessPair FoundDecl = I.getPair(); 3503 NamedDecl *D = FoundDecl.getDecl(); 3504 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3505 if (isa<UsingShadowDecl>(D)) 3506 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3507 3508 CXXConversionDecl *Conv; 3509 FunctionTemplateDecl *ConvTemplate; 3510 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3511 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3512 else 3513 Conv = cast<CXXConversionDecl>(D); 3514 3515 if (ConvTemplate) 3516 S.AddTemplateConversionCandidate( 3517 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3518 CandidateSet, AllowObjCConversionOnExplicit, 3519 AllowExplicit != AllowedExplicit::None); 3520 else 3521 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3522 CandidateSet, AllowObjCConversionOnExplicit, 3523 AllowExplicit != AllowedExplicit::None); 3524 } 3525 } 3526 } 3527 3528 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3529 3530 OverloadCandidateSet::iterator Best; 3531 switch (auto Result = 3532 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3533 case OR_Success: 3534 case OR_Deleted: 3535 // Record the standard conversion we used and the conversion function. 3536 if (CXXConstructorDecl *Constructor 3537 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3538 // C++ [over.ics.user]p1: 3539 // If the user-defined conversion is specified by a 3540 // constructor (12.3.1), the initial standard conversion 3541 // sequence converts the source type to the type required by 3542 // the argument of the constructor. 3543 // 3544 QualType ThisType = Constructor->getThisType(); 3545 if (isa<InitListExpr>(From)) { 3546 // Initializer lists don't have conversions as such. 3547 User.Before.setAsIdentityConversion(); 3548 } else { 3549 if (Best->Conversions[0].isEllipsis()) 3550 User.EllipsisConversion = true; 3551 else { 3552 User.Before = Best->Conversions[0].Standard; 3553 User.EllipsisConversion = false; 3554 } 3555 } 3556 User.HadMultipleCandidates = HadMultipleCandidates; 3557 User.ConversionFunction = Constructor; 3558 User.FoundConversionFunction = Best->FoundDecl; 3559 User.After.setAsIdentityConversion(); 3560 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3561 User.After.setAllToTypes(ToType); 3562 return Result; 3563 } 3564 if (CXXConversionDecl *Conversion 3565 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3566 // C++ [over.ics.user]p1: 3567 // 3568 // [...] If the user-defined conversion is specified by a 3569 // conversion function (12.3.2), the initial standard 3570 // conversion sequence converts the source type to the 3571 // implicit object parameter of the conversion function. 3572 User.Before = Best->Conversions[0].Standard; 3573 User.HadMultipleCandidates = HadMultipleCandidates; 3574 User.ConversionFunction = Conversion; 3575 User.FoundConversionFunction = Best->FoundDecl; 3576 User.EllipsisConversion = false; 3577 3578 // C++ [over.ics.user]p2: 3579 // The second standard conversion sequence converts the 3580 // result of the user-defined conversion to the target type 3581 // for the sequence. Since an implicit conversion sequence 3582 // is an initialization, the special rules for 3583 // initialization by user-defined conversion apply when 3584 // selecting the best user-defined conversion for a 3585 // user-defined conversion sequence (see 13.3.3 and 3586 // 13.3.3.1). 3587 User.After = Best->FinalConversion; 3588 return Result; 3589 } 3590 llvm_unreachable("Not a constructor or conversion function?"); 3591 3592 case OR_No_Viable_Function: 3593 return OR_No_Viable_Function; 3594 3595 case OR_Ambiguous: 3596 return OR_Ambiguous; 3597 } 3598 3599 llvm_unreachable("Invalid OverloadResult!"); 3600 } 3601 3602 bool 3603 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3604 ImplicitConversionSequence ICS; 3605 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3606 OverloadCandidateSet::CSK_Normal); 3607 OverloadingResult OvResult = 3608 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3609 CandidateSet, AllowedExplicit::None, false); 3610 3611 if (!(OvResult == OR_Ambiguous || 3612 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3613 return false; 3614 3615 auto Cands = CandidateSet.CompleteCandidates( 3616 *this, 3617 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3618 From); 3619 if (OvResult == OR_Ambiguous) 3620 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3621 << From->getType() << ToType << From->getSourceRange(); 3622 else { // OR_No_Viable_Function && !CandidateSet.empty() 3623 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3624 diag::err_typecheck_nonviable_condition_incomplete, 3625 From->getType(), From->getSourceRange())) 3626 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3627 << false << From->getType() << From->getSourceRange() << ToType; 3628 } 3629 3630 CandidateSet.NoteCandidates( 3631 *this, From, Cands); 3632 return true; 3633 } 3634 3635 /// Compare the user-defined conversion functions or constructors 3636 /// of two user-defined conversion sequences to determine whether any ordering 3637 /// is possible. 3638 static ImplicitConversionSequence::CompareKind 3639 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3640 FunctionDecl *Function2) { 3641 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3642 return ImplicitConversionSequence::Indistinguishable; 3643 3644 // Objective-C++: 3645 // If both conversion functions are implicitly-declared conversions from 3646 // a lambda closure type to a function pointer and a block pointer, 3647 // respectively, always prefer the conversion to a function pointer, 3648 // because the function pointer is more lightweight and is more likely 3649 // to keep code working. 3650 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3651 if (!Conv1) 3652 return ImplicitConversionSequence::Indistinguishable; 3653 3654 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3655 if (!Conv2) 3656 return ImplicitConversionSequence::Indistinguishable; 3657 3658 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3659 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3660 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3661 if (Block1 != Block2) 3662 return Block1 ? ImplicitConversionSequence::Worse 3663 : ImplicitConversionSequence::Better; 3664 } 3665 3666 return ImplicitConversionSequence::Indistinguishable; 3667 } 3668 3669 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3670 const ImplicitConversionSequence &ICS) { 3671 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3672 (ICS.isUserDefined() && 3673 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3674 } 3675 3676 /// CompareImplicitConversionSequences - Compare two implicit 3677 /// conversion sequences to determine whether one is better than the 3678 /// other or if they are indistinguishable (C++ 13.3.3.2). 3679 static ImplicitConversionSequence::CompareKind 3680 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3681 const ImplicitConversionSequence& ICS1, 3682 const ImplicitConversionSequence& ICS2) 3683 { 3684 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3685 // conversion sequences (as defined in 13.3.3.1) 3686 // -- a standard conversion sequence (13.3.3.1.1) is a better 3687 // conversion sequence than a user-defined conversion sequence or 3688 // an ellipsis conversion sequence, and 3689 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3690 // conversion sequence than an ellipsis conversion sequence 3691 // (13.3.3.1.3). 3692 // 3693 // C++0x [over.best.ics]p10: 3694 // For the purpose of ranking implicit conversion sequences as 3695 // described in 13.3.3.2, the ambiguous conversion sequence is 3696 // treated as a user-defined sequence that is indistinguishable 3697 // from any other user-defined conversion sequence. 3698 3699 // String literal to 'char *' conversion has been deprecated in C++03. It has 3700 // been removed from C++11. We still accept this conversion, if it happens at 3701 // the best viable function. Otherwise, this conversion is considered worse 3702 // than ellipsis conversion. Consider this as an extension; this is not in the 3703 // standard. For example: 3704 // 3705 // int &f(...); // #1 3706 // void f(char*); // #2 3707 // void g() { int &r = f("foo"); } 3708 // 3709 // In C++03, we pick #2 as the best viable function. 3710 // In C++11, we pick #1 as the best viable function, because ellipsis 3711 // conversion is better than string-literal to char* conversion (since there 3712 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3713 // convert arguments, #2 would be the best viable function in C++11. 3714 // If the best viable function has this conversion, a warning will be issued 3715 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3716 3717 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3718 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3719 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3720 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3721 ? ImplicitConversionSequence::Worse 3722 : ImplicitConversionSequence::Better; 3723 3724 if (ICS1.getKindRank() < ICS2.getKindRank()) 3725 return ImplicitConversionSequence::Better; 3726 if (ICS2.getKindRank() < ICS1.getKindRank()) 3727 return ImplicitConversionSequence::Worse; 3728 3729 // The following checks require both conversion sequences to be of 3730 // the same kind. 3731 if (ICS1.getKind() != ICS2.getKind()) 3732 return ImplicitConversionSequence::Indistinguishable; 3733 3734 ImplicitConversionSequence::CompareKind Result = 3735 ImplicitConversionSequence::Indistinguishable; 3736 3737 // Two implicit conversion sequences of the same form are 3738 // indistinguishable conversion sequences unless one of the 3739 // following rules apply: (C++ 13.3.3.2p3): 3740 3741 // List-initialization sequence L1 is a better conversion sequence than 3742 // list-initialization sequence L2 if: 3743 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3744 // if not that, 3745 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3746 // and N1 is smaller than N2., 3747 // even if one of the other rules in this paragraph would otherwise apply. 3748 if (!ICS1.isBad()) { 3749 if (ICS1.isStdInitializerListElement() && 3750 !ICS2.isStdInitializerListElement()) 3751 return ImplicitConversionSequence::Better; 3752 if (!ICS1.isStdInitializerListElement() && 3753 ICS2.isStdInitializerListElement()) 3754 return ImplicitConversionSequence::Worse; 3755 } 3756 3757 if (ICS1.isStandard()) 3758 // Standard conversion sequence S1 is a better conversion sequence than 3759 // standard conversion sequence S2 if [...] 3760 Result = CompareStandardConversionSequences(S, Loc, 3761 ICS1.Standard, ICS2.Standard); 3762 else if (ICS1.isUserDefined()) { 3763 // User-defined conversion sequence U1 is a better conversion 3764 // sequence than another user-defined conversion sequence U2 if 3765 // they contain the same user-defined conversion function or 3766 // constructor and if the second standard conversion sequence of 3767 // U1 is better than the second standard conversion sequence of 3768 // U2 (C++ 13.3.3.2p3). 3769 if (ICS1.UserDefined.ConversionFunction == 3770 ICS2.UserDefined.ConversionFunction) 3771 Result = CompareStandardConversionSequences(S, Loc, 3772 ICS1.UserDefined.After, 3773 ICS2.UserDefined.After); 3774 else 3775 Result = compareConversionFunctions(S, 3776 ICS1.UserDefined.ConversionFunction, 3777 ICS2.UserDefined.ConversionFunction); 3778 } 3779 3780 return Result; 3781 } 3782 3783 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3784 // determine if one is a proper subset of the other. 3785 static ImplicitConversionSequence::CompareKind 3786 compareStandardConversionSubsets(ASTContext &Context, 3787 const StandardConversionSequence& SCS1, 3788 const StandardConversionSequence& SCS2) { 3789 ImplicitConversionSequence::CompareKind Result 3790 = ImplicitConversionSequence::Indistinguishable; 3791 3792 // the identity conversion sequence is considered to be a subsequence of 3793 // any non-identity conversion sequence 3794 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3795 return ImplicitConversionSequence::Better; 3796 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3797 return ImplicitConversionSequence::Worse; 3798 3799 if (SCS1.Second != SCS2.Second) { 3800 if (SCS1.Second == ICK_Identity) 3801 Result = ImplicitConversionSequence::Better; 3802 else if (SCS2.Second == ICK_Identity) 3803 Result = ImplicitConversionSequence::Worse; 3804 else 3805 return ImplicitConversionSequence::Indistinguishable; 3806 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3807 return ImplicitConversionSequence::Indistinguishable; 3808 3809 if (SCS1.Third == SCS2.Third) { 3810 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3811 : ImplicitConversionSequence::Indistinguishable; 3812 } 3813 3814 if (SCS1.Third == ICK_Identity) 3815 return Result == ImplicitConversionSequence::Worse 3816 ? ImplicitConversionSequence::Indistinguishable 3817 : ImplicitConversionSequence::Better; 3818 3819 if (SCS2.Third == ICK_Identity) 3820 return Result == ImplicitConversionSequence::Better 3821 ? ImplicitConversionSequence::Indistinguishable 3822 : ImplicitConversionSequence::Worse; 3823 3824 return ImplicitConversionSequence::Indistinguishable; 3825 } 3826 3827 /// Determine whether one of the given reference bindings is better 3828 /// than the other based on what kind of bindings they are. 3829 static bool 3830 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3831 const StandardConversionSequence &SCS2) { 3832 // C++0x [over.ics.rank]p3b4: 3833 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3834 // implicit object parameter of a non-static member function declared 3835 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3836 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3837 // lvalue reference to a function lvalue and S2 binds an rvalue 3838 // reference*. 3839 // 3840 // FIXME: Rvalue references. We're going rogue with the above edits, 3841 // because the semantics in the current C++0x working paper (N3225 at the 3842 // time of this writing) break the standard definition of std::forward 3843 // and std::reference_wrapper when dealing with references to functions. 3844 // Proposed wording changes submitted to CWG for consideration. 3845 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3846 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3847 return false; 3848 3849 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3850 SCS2.IsLvalueReference) || 3851 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3852 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3853 } 3854 3855 enum class FixedEnumPromotion { 3856 None, 3857 ToUnderlyingType, 3858 ToPromotedUnderlyingType 3859 }; 3860 3861 /// Returns kind of fixed enum promotion the \a SCS uses. 3862 static FixedEnumPromotion 3863 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3864 3865 if (SCS.Second != ICK_Integral_Promotion) 3866 return FixedEnumPromotion::None; 3867 3868 QualType FromType = SCS.getFromType(); 3869 if (!FromType->isEnumeralType()) 3870 return FixedEnumPromotion::None; 3871 3872 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3873 if (!Enum->isFixed()) 3874 return FixedEnumPromotion::None; 3875 3876 QualType UnderlyingType = Enum->getIntegerType(); 3877 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3878 return FixedEnumPromotion::ToUnderlyingType; 3879 3880 return FixedEnumPromotion::ToPromotedUnderlyingType; 3881 } 3882 3883 /// CompareStandardConversionSequences - Compare two standard 3884 /// conversion sequences to determine whether one is better than the 3885 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3886 static ImplicitConversionSequence::CompareKind 3887 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3888 const StandardConversionSequence& SCS1, 3889 const StandardConversionSequence& SCS2) 3890 { 3891 // Standard conversion sequence S1 is a better conversion sequence 3892 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3893 3894 // -- S1 is a proper subsequence of S2 (comparing the conversion 3895 // sequences in the canonical form defined by 13.3.3.1.1, 3896 // excluding any Lvalue Transformation; the identity conversion 3897 // sequence is considered to be a subsequence of any 3898 // non-identity conversion sequence) or, if not that, 3899 if (ImplicitConversionSequence::CompareKind CK 3900 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3901 return CK; 3902 3903 // -- the rank of S1 is better than the rank of S2 (by the rules 3904 // defined below), or, if not that, 3905 ImplicitConversionRank Rank1 = SCS1.getRank(); 3906 ImplicitConversionRank Rank2 = SCS2.getRank(); 3907 if (Rank1 < Rank2) 3908 return ImplicitConversionSequence::Better; 3909 else if (Rank2 < Rank1) 3910 return ImplicitConversionSequence::Worse; 3911 3912 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3913 // are indistinguishable unless one of the following rules 3914 // applies: 3915 3916 // A conversion that is not a conversion of a pointer, or 3917 // pointer to member, to bool is better than another conversion 3918 // that is such a conversion. 3919 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3920 return SCS2.isPointerConversionToBool() 3921 ? ImplicitConversionSequence::Better 3922 : ImplicitConversionSequence::Worse; 3923 3924 // C++14 [over.ics.rank]p4b2: 3925 // This is retroactively applied to C++11 by CWG 1601. 3926 // 3927 // A conversion that promotes an enumeration whose underlying type is fixed 3928 // to its underlying type is better than one that promotes to the promoted 3929 // underlying type, if the two are different. 3930 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3931 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3932 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3933 FEP1 != FEP2) 3934 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3935 ? ImplicitConversionSequence::Better 3936 : ImplicitConversionSequence::Worse; 3937 3938 // C++ [over.ics.rank]p4b2: 3939 // 3940 // If class B is derived directly or indirectly from class A, 3941 // conversion of B* to A* is better than conversion of B* to 3942 // void*, and conversion of A* to void* is better than conversion 3943 // of B* to void*. 3944 bool SCS1ConvertsToVoid 3945 = SCS1.isPointerConversionToVoidPointer(S.Context); 3946 bool SCS2ConvertsToVoid 3947 = SCS2.isPointerConversionToVoidPointer(S.Context); 3948 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3949 // Exactly one of the conversion sequences is a conversion to 3950 // a void pointer; it's the worse conversion. 3951 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3952 : ImplicitConversionSequence::Worse; 3953 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3954 // Neither conversion sequence converts to a void pointer; compare 3955 // their derived-to-base conversions. 3956 if (ImplicitConversionSequence::CompareKind DerivedCK 3957 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3958 return DerivedCK; 3959 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3960 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3961 // Both conversion sequences are conversions to void 3962 // pointers. Compare the source types to determine if there's an 3963 // inheritance relationship in their sources. 3964 QualType FromType1 = SCS1.getFromType(); 3965 QualType FromType2 = SCS2.getFromType(); 3966 3967 // Adjust the types we're converting from via the array-to-pointer 3968 // conversion, if we need to. 3969 if (SCS1.First == ICK_Array_To_Pointer) 3970 FromType1 = S.Context.getArrayDecayedType(FromType1); 3971 if (SCS2.First == ICK_Array_To_Pointer) 3972 FromType2 = S.Context.getArrayDecayedType(FromType2); 3973 3974 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3975 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3976 3977 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3978 return ImplicitConversionSequence::Better; 3979 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3980 return ImplicitConversionSequence::Worse; 3981 3982 // Objective-C++: If one interface is more specific than the 3983 // other, it is the better one. 3984 const ObjCObjectPointerType* FromObjCPtr1 3985 = FromType1->getAs<ObjCObjectPointerType>(); 3986 const ObjCObjectPointerType* FromObjCPtr2 3987 = FromType2->getAs<ObjCObjectPointerType>(); 3988 if (FromObjCPtr1 && FromObjCPtr2) { 3989 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3990 FromObjCPtr2); 3991 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3992 FromObjCPtr1); 3993 if (AssignLeft != AssignRight) { 3994 return AssignLeft? ImplicitConversionSequence::Better 3995 : ImplicitConversionSequence::Worse; 3996 } 3997 } 3998 } 3999 4000 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4001 // Check for a better reference binding based on the kind of bindings. 4002 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4003 return ImplicitConversionSequence::Better; 4004 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4005 return ImplicitConversionSequence::Worse; 4006 } 4007 4008 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4009 // bullet 3). 4010 if (ImplicitConversionSequence::CompareKind QualCK 4011 = CompareQualificationConversions(S, SCS1, SCS2)) 4012 return QualCK; 4013 4014 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4015 // C++ [over.ics.rank]p3b4: 4016 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4017 // which the references refer are the same type except for 4018 // top-level cv-qualifiers, and the type to which the reference 4019 // initialized by S2 refers is more cv-qualified than the type 4020 // to which the reference initialized by S1 refers. 4021 QualType T1 = SCS1.getToType(2); 4022 QualType T2 = SCS2.getToType(2); 4023 T1 = S.Context.getCanonicalType(T1); 4024 T2 = S.Context.getCanonicalType(T2); 4025 Qualifiers T1Quals, T2Quals; 4026 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4027 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4028 if (UnqualT1 == UnqualT2) { 4029 // Objective-C++ ARC: If the references refer to objects with different 4030 // lifetimes, prefer bindings that don't change lifetime. 4031 if (SCS1.ObjCLifetimeConversionBinding != 4032 SCS2.ObjCLifetimeConversionBinding) { 4033 return SCS1.ObjCLifetimeConversionBinding 4034 ? ImplicitConversionSequence::Worse 4035 : ImplicitConversionSequence::Better; 4036 } 4037 4038 // If the type is an array type, promote the element qualifiers to the 4039 // type for comparison. 4040 if (isa<ArrayType>(T1) && T1Quals) 4041 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4042 if (isa<ArrayType>(T2) && T2Quals) 4043 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4044 if (T2.isMoreQualifiedThan(T1)) 4045 return ImplicitConversionSequence::Better; 4046 if (T1.isMoreQualifiedThan(T2)) 4047 return ImplicitConversionSequence::Worse; 4048 } 4049 } 4050 4051 // In Microsoft mode, prefer an integral conversion to a 4052 // floating-to-integral conversion if the integral conversion 4053 // is between types of the same size. 4054 // For example: 4055 // void f(float); 4056 // void f(int); 4057 // int main { 4058 // long a; 4059 // f(a); 4060 // } 4061 // Here, MSVC will call f(int) instead of generating a compile error 4062 // as clang will do in standard mode. 4063 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 4064 SCS2.Second == ICK_Floating_Integral && 4065 S.Context.getTypeSize(SCS1.getFromType()) == 4066 S.Context.getTypeSize(SCS1.getToType(2))) 4067 return ImplicitConversionSequence::Better; 4068 4069 // Prefer a compatible vector conversion over a lax vector conversion 4070 // For example: 4071 // 4072 // typedef float __v4sf __attribute__((__vector_size__(16))); 4073 // void f(vector float); 4074 // void f(vector signed int); 4075 // int main() { 4076 // __v4sf a; 4077 // f(a); 4078 // } 4079 // Here, we'd like to choose f(vector float) and not 4080 // report an ambiguous call error 4081 if (SCS1.Second == ICK_Vector_Conversion && 4082 SCS2.Second == ICK_Vector_Conversion) { 4083 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4084 SCS1.getFromType(), SCS1.getToType(2)); 4085 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4086 SCS2.getFromType(), SCS2.getToType(2)); 4087 4088 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4089 return SCS1IsCompatibleVectorConversion 4090 ? ImplicitConversionSequence::Better 4091 : ImplicitConversionSequence::Worse; 4092 } 4093 4094 return ImplicitConversionSequence::Indistinguishable; 4095 } 4096 4097 /// CompareQualificationConversions - Compares two standard conversion 4098 /// sequences to determine whether they can be ranked based on their 4099 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4100 static ImplicitConversionSequence::CompareKind 4101 CompareQualificationConversions(Sema &S, 4102 const StandardConversionSequence& SCS1, 4103 const StandardConversionSequence& SCS2) { 4104 // C++ 13.3.3.2p3: 4105 // -- S1 and S2 differ only in their qualification conversion and 4106 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4107 // cv-qualification signature of type T1 is a proper subset of 4108 // the cv-qualification signature of type T2, and S1 is not the 4109 // deprecated string literal array-to-pointer conversion (4.2). 4110 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4111 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4112 return ImplicitConversionSequence::Indistinguishable; 4113 4114 // FIXME: the example in the standard doesn't use a qualification 4115 // conversion (!) 4116 QualType T1 = SCS1.getToType(2); 4117 QualType T2 = SCS2.getToType(2); 4118 T1 = S.Context.getCanonicalType(T1); 4119 T2 = S.Context.getCanonicalType(T2); 4120 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4121 Qualifiers T1Quals, T2Quals; 4122 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4123 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4124 4125 // If the types are the same, we won't learn anything by unwrapping 4126 // them. 4127 if (UnqualT1 == UnqualT2) 4128 return ImplicitConversionSequence::Indistinguishable; 4129 4130 ImplicitConversionSequence::CompareKind Result 4131 = ImplicitConversionSequence::Indistinguishable; 4132 4133 // Objective-C++ ARC: 4134 // Prefer qualification conversions not involving a change in lifetime 4135 // to qualification conversions that do not change lifetime. 4136 if (SCS1.QualificationIncludesObjCLifetime != 4137 SCS2.QualificationIncludesObjCLifetime) { 4138 Result = SCS1.QualificationIncludesObjCLifetime 4139 ? ImplicitConversionSequence::Worse 4140 : ImplicitConversionSequence::Better; 4141 } 4142 4143 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4144 // Within each iteration of the loop, we check the qualifiers to 4145 // determine if this still looks like a qualification 4146 // conversion. Then, if all is well, we unwrap one more level of 4147 // pointers or pointers-to-members and do it all again 4148 // until there are no more pointers or pointers-to-members left 4149 // to unwrap. This essentially mimics what 4150 // IsQualificationConversion does, but here we're checking for a 4151 // strict subset of qualifiers. 4152 if (T1.getQualifiers().withoutObjCLifetime() == 4153 T2.getQualifiers().withoutObjCLifetime()) 4154 // The qualifiers are the same, so this doesn't tell us anything 4155 // about how the sequences rank. 4156 // ObjC ownership quals are omitted above as they interfere with 4157 // the ARC overload rule. 4158 ; 4159 else if (T2.isMoreQualifiedThan(T1)) { 4160 // T1 has fewer qualifiers, so it could be the better sequence. 4161 if (Result == ImplicitConversionSequence::Worse) 4162 // Neither has qualifiers that are a subset of the other's 4163 // qualifiers. 4164 return ImplicitConversionSequence::Indistinguishable; 4165 4166 Result = ImplicitConversionSequence::Better; 4167 } else if (T1.isMoreQualifiedThan(T2)) { 4168 // T2 has fewer qualifiers, so it could be the better sequence. 4169 if (Result == ImplicitConversionSequence::Better) 4170 // Neither has qualifiers that are a subset of the other's 4171 // qualifiers. 4172 return ImplicitConversionSequence::Indistinguishable; 4173 4174 Result = ImplicitConversionSequence::Worse; 4175 } else { 4176 // Qualifiers are disjoint. 4177 return ImplicitConversionSequence::Indistinguishable; 4178 } 4179 4180 // If the types after this point are equivalent, we're done. 4181 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4182 break; 4183 } 4184 4185 // Check that the winning standard conversion sequence isn't using 4186 // the deprecated string literal array to pointer conversion. 4187 switch (Result) { 4188 case ImplicitConversionSequence::Better: 4189 if (SCS1.DeprecatedStringLiteralToCharPtr) 4190 Result = ImplicitConversionSequence::Indistinguishable; 4191 break; 4192 4193 case ImplicitConversionSequence::Indistinguishable: 4194 break; 4195 4196 case ImplicitConversionSequence::Worse: 4197 if (SCS2.DeprecatedStringLiteralToCharPtr) 4198 Result = ImplicitConversionSequence::Indistinguishable; 4199 break; 4200 } 4201 4202 return Result; 4203 } 4204 4205 /// CompareDerivedToBaseConversions - Compares two standard conversion 4206 /// sequences to determine whether they can be ranked based on their 4207 /// various kinds of derived-to-base conversions (C++ 4208 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4209 /// conversions between Objective-C interface types. 4210 static ImplicitConversionSequence::CompareKind 4211 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4212 const StandardConversionSequence& SCS1, 4213 const StandardConversionSequence& SCS2) { 4214 QualType FromType1 = SCS1.getFromType(); 4215 QualType ToType1 = SCS1.getToType(1); 4216 QualType FromType2 = SCS2.getFromType(); 4217 QualType ToType2 = SCS2.getToType(1); 4218 4219 // Adjust the types we're converting from via the array-to-pointer 4220 // conversion, if we need to. 4221 if (SCS1.First == ICK_Array_To_Pointer) 4222 FromType1 = S.Context.getArrayDecayedType(FromType1); 4223 if (SCS2.First == ICK_Array_To_Pointer) 4224 FromType2 = S.Context.getArrayDecayedType(FromType2); 4225 4226 // Canonicalize all of the types. 4227 FromType1 = S.Context.getCanonicalType(FromType1); 4228 ToType1 = S.Context.getCanonicalType(ToType1); 4229 FromType2 = S.Context.getCanonicalType(FromType2); 4230 ToType2 = S.Context.getCanonicalType(ToType2); 4231 4232 // C++ [over.ics.rank]p4b3: 4233 // 4234 // If class B is derived directly or indirectly from class A and 4235 // class C is derived directly or indirectly from B, 4236 // 4237 // Compare based on pointer conversions. 4238 if (SCS1.Second == ICK_Pointer_Conversion && 4239 SCS2.Second == ICK_Pointer_Conversion && 4240 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4241 FromType1->isPointerType() && FromType2->isPointerType() && 4242 ToType1->isPointerType() && ToType2->isPointerType()) { 4243 QualType FromPointee1 = 4244 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4245 QualType ToPointee1 = 4246 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4247 QualType FromPointee2 = 4248 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4249 QualType ToPointee2 = 4250 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4251 4252 // -- conversion of C* to B* is better than conversion of C* to A*, 4253 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4254 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4255 return ImplicitConversionSequence::Better; 4256 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4257 return ImplicitConversionSequence::Worse; 4258 } 4259 4260 // -- conversion of B* to A* is better than conversion of C* to A*, 4261 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4262 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4263 return ImplicitConversionSequence::Better; 4264 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4265 return ImplicitConversionSequence::Worse; 4266 } 4267 } else if (SCS1.Second == ICK_Pointer_Conversion && 4268 SCS2.Second == ICK_Pointer_Conversion) { 4269 const ObjCObjectPointerType *FromPtr1 4270 = FromType1->getAs<ObjCObjectPointerType>(); 4271 const ObjCObjectPointerType *FromPtr2 4272 = FromType2->getAs<ObjCObjectPointerType>(); 4273 const ObjCObjectPointerType *ToPtr1 4274 = ToType1->getAs<ObjCObjectPointerType>(); 4275 const ObjCObjectPointerType *ToPtr2 4276 = ToType2->getAs<ObjCObjectPointerType>(); 4277 4278 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4279 // Apply the same conversion ranking rules for Objective-C pointer types 4280 // that we do for C++ pointers to class types. However, we employ the 4281 // Objective-C pseudo-subtyping relationship used for assignment of 4282 // Objective-C pointer types. 4283 bool FromAssignLeft 4284 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4285 bool FromAssignRight 4286 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4287 bool ToAssignLeft 4288 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4289 bool ToAssignRight 4290 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4291 4292 // A conversion to an a non-id object pointer type or qualified 'id' 4293 // type is better than a conversion to 'id'. 4294 if (ToPtr1->isObjCIdType() && 4295 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4296 return ImplicitConversionSequence::Worse; 4297 if (ToPtr2->isObjCIdType() && 4298 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4299 return ImplicitConversionSequence::Better; 4300 4301 // A conversion to a non-id object pointer type is better than a 4302 // conversion to a qualified 'id' type 4303 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4304 return ImplicitConversionSequence::Worse; 4305 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4306 return ImplicitConversionSequence::Better; 4307 4308 // A conversion to an a non-Class object pointer type or qualified 'Class' 4309 // type is better than a conversion to 'Class'. 4310 if (ToPtr1->isObjCClassType() && 4311 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4312 return ImplicitConversionSequence::Worse; 4313 if (ToPtr2->isObjCClassType() && 4314 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4315 return ImplicitConversionSequence::Better; 4316 4317 // A conversion to a non-Class object pointer type is better than a 4318 // conversion to a qualified 'Class' type. 4319 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4320 return ImplicitConversionSequence::Worse; 4321 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4322 return ImplicitConversionSequence::Better; 4323 4324 // -- "conversion of C* to B* is better than conversion of C* to A*," 4325 if (S.Context.hasSameType(FromType1, FromType2) && 4326 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4327 (ToAssignLeft != ToAssignRight)) { 4328 if (FromPtr1->isSpecialized()) { 4329 // "conversion of B<A> * to B * is better than conversion of B * to 4330 // C *. 4331 bool IsFirstSame = 4332 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4333 bool IsSecondSame = 4334 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4335 if (IsFirstSame) { 4336 if (!IsSecondSame) 4337 return ImplicitConversionSequence::Better; 4338 } else if (IsSecondSame) 4339 return ImplicitConversionSequence::Worse; 4340 } 4341 return ToAssignLeft? ImplicitConversionSequence::Worse 4342 : ImplicitConversionSequence::Better; 4343 } 4344 4345 // -- "conversion of B* to A* is better than conversion of C* to A*," 4346 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4347 (FromAssignLeft != FromAssignRight)) 4348 return FromAssignLeft? ImplicitConversionSequence::Better 4349 : ImplicitConversionSequence::Worse; 4350 } 4351 } 4352 4353 // Ranking of member-pointer types. 4354 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4355 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4356 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4357 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4358 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4359 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4360 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4361 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4362 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4363 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4364 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4365 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4366 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4367 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4368 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4369 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4370 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4371 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4372 return ImplicitConversionSequence::Worse; 4373 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4374 return ImplicitConversionSequence::Better; 4375 } 4376 // conversion of B::* to C::* is better than conversion of A::* to C::* 4377 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4378 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4379 return ImplicitConversionSequence::Better; 4380 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4381 return ImplicitConversionSequence::Worse; 4382 } 4383 } 4384 4385 if (SCS1.Second == ICK_Derived_To_Base) { 4386 // -- conversion of C to B is better than conversion of C to A, 4387 // -- binding of an expression of type C to a reference of type 4388 // B& is better than binding an expression of type C to a 4389 // reference of type A&, 4390 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4391 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4392 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4393 return ImplicitConversionSequence::Better; 4394 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4395 return ImplicitConversionSequence::Worse; 4396 } 4397 4398 // -- conversion of B to A is better than conversion of C to A. 4399 // -- binding of an expression of type B to a reference of type 4400 // A& is better than binding an expression of type C to a 4401 // reference of type A&, 4402 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4403 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4404 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4405 return ImplicitConversionSequence::Better; 4406 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4407 return ImplicitConversionSequence::Worse; 4408 } 4409 } 4410 4411 return ImplicitConversionSequence::Indistinguishable; 4412 } 4413 4414 /// Determine whether the given type is valid, e.g., it is not an invalid 4415 /// C++ class. 4416 static bool isTypeValid(QualType T) { 4417 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4418 return !Record->isInvalidDecl(); 4419 4420 return true; 4421 } 4422 4423 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4424 if (!T.getQualifiers().hasUnaligned()) 4425 return T; 4426 4427 Qualifiers Q; 4428 T = Ctx.getUnqualifiedArrayType(T, Q); 4429 Q.removeUnaligned(); 4430 return Ctx.getQualifiedType(T, Q); 4431 } 4432 4433 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4434 /// determine whether they are reference-compatible, 4435 /// reference-related, or incompatible, for use in C++ initialization by 4436 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4437 /// type, and the first type (T1) is the pointee type of the reference 4438 /// type being initialized. 4439 Sema::ReferenceCompareResult 4440 Sema::CompareReferenceRelationship(SourceLocation Loc, 4441 QualType OrigT1, QualType OrigT2, 4442 ReferenceConversions *ConvOut) { 4443 assert(!OrigT1->isReferenceType() && 4444 "T1 must be the pointee type of the reference type"); 4445 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4446 4447 QualType T1 = Context.getCanonicalType(OrigT1); 4448 QualType T2 = Context.getCanonicalType(OrigT2); 4449 Qualifiers T1Quals, T2Quals; 4450 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4451 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4452 4453 ReferenceConversions ConvTmp; 4454 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4455 Conv = ReferenceConversions(); 4456 4457 // C++2a [dcl.init.ref]p4: 4458 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4459 // reference-related to "cv2 T2" if T1 is similar to T2, or 4460 // T1 is a base class of T2. 4461 // "cv1 T1" is reference-compatible with "cv2 T2" if 4462 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4463 // "pointer to cv1 T1" via a standard conversion sequence. 4464 4465 // Check for standard conversions we can apply to pointers: derived-to-base 4466 // conversions, ObjC pointer conversions, and function pointer conversions. 4467 // (Qualification conversions are checked last.) 4468 QualType ConvertedT2; 4469 if (UnqualT1 == UnqualT2) { 4470 // Nothing to do. 4471 } else if (isCompleteType(Loc, OrigT2) && 4472 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4473 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4474 Conv |= ReferenceConversions::DerivedToBase; 4475 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4476 UnqualT2->isObjCObjectOrInterfaceType() && 4477 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4478 Conv |= ReferenceConversions::ObjC; 4479 else if (UnqualT2->isFunctionType() && 4480 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4481 Conv |= ReferenceConversions::Function; 4482 // No need to check qualifiers; function types don't have them. 4483 return Ref_Compatible; 4484 } 4485 bool ConvertedReferent = Conv != 0; 4486 4487 // We can have a qualification conversion. Compute whether the types are 4488 // similar at the same time. 4489 bool PreviousToQualsIncludeConst = true; 4490 bool TopLevel = true; 4491 do { 4492 if (T1 == T2) 4493 break; 4494 4495 // We will need a qualification conversion. 4496 Conv |= ReferenceConversions::Qualification; 4497 4498 // Track whether we performed a qualification conversion anywhere other 4499 // than the top level. This matters for ranking reference bindings in 4500 // overload resolution. 4501 if (!TopLevel) 4502 Conv |= ReferenceConversions::NestedQualification; 4503 4504 // MS compiler ignores __unaligned qualifier for references; do the same. 4505 T1 = withoutUnaligned(Context, T1); 4506 T2 = withoutUnaligned(Context, T2); 4507 4508 // If we find a qualifier mismatch, the types are not reference-compatible, 4509 // but are still be reference-related if they're similar. 4510 bool ObjCLifetimeConversion = false; 4511 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, 4512 PreviousToQualsIncludeConst, 4513 ObjCLifetimeConversion)) 4514 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4515 ? Ref_Related 4516 : Ref_Incompatible; 4517 4518 // FIXME: Should we track this for any level other than the first? 4519 if (ObjCLifetimeConversion) 4520 Conv |= ReferenceConversions::ObjCLifetime; 4521 4522 TopLevel = false; 4523 } while (Context.UnwrapSimilarTypes(T1, T2)); 4524 4525 // At this point, if the types are reference-related, we must either have the 4526 // same inner type (ignoring qualifiers), or must have already worked out how 4527 // to convert the referent. 4528 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4529 ? Ref_Compatible 4530 : Ref_Incompatible; 4531 } 4532 4533 /// Look for a user-defined conversion to a value reference-compatible 4534 /// with DeclType. Return true if something definite is found. 4535 static bool 4536 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4537 QualType DeclType, SourceLocation DeclLoc, 4538 Expr *Init, QualType T2, bool AllowRvalues, 4539 bool AllowExplicit) { 4540 assert(T2->isRecordType() && "Can only find conversions of record types."); 4541 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4542 4543 OverloadCandidateSet CandidateSet( 4544 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4545 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4546 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4547 NamedDecl *D = *I; 4548 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4549 if (isa<UsingShadowDecl>(D)) 4550 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4551 4552 FunctionTemplateDecl *ConvTemplate 4553 = dyn_cast<FunctionTemplateDecl>(D); 4554 CXXConversionDecl *Conv; 4555 if (ConvTemplate) 4556 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4557 else 4558 Conv = cast<CXXConversionDecl>(D); 4559 4560 if (AllowRvalues) { 4561 // If we are initializing an rvalue reference, don't permit conversion 4562 // functions that return lvalues. 4563 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4564 const ReferenceType *RefType 4565 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4566 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4567 continue; 4568 } 4569 4570 if (!ConvTemplate && 4571 S.CompareReferenceRelationship( 4572 DeclLoc, 4573 Conv->getConversionType() 4574 .getNonReferenceType() 4575 .getUnqualifiedType(), 4576 DeclType.getNonReferenceType().getUnqualifiedType()) == 4577 Sema::Ref_Incompatible) 4578 continue; 4579 } else { 4580 // If the conversion function doesn't return a reference type, 4581 // it can't be considered for this conversion. An rvalue reference 4582 // is only acceptable if its referencee is a function type. 4583 4584 const ReferenceType *RefType = 4585 Conv->getConversionType()->getAs<ReferenceType>(); 4586 if (!RefType || 4587 (!RefType->isLValueReferenceType() && 4588 !RefType->getPointeeType()->isFunctionType())) 4589 continue; 4590 } 4591 4592 if (ConvTemplate) 4593 S.AddTemplateConversionCandidate( 4594 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4595 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4596 else 4597 S.AddConversionCandidate( 4598 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4599 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4600 } 4601 4602 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4603 4604 OverloadCandidateSet::iterator Best; 4605 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4606 case OR_Success: 4607 // C++ [over.ics.ref]p1: 4608 // 4609 // [...] If the parameter binds directly to the result of 4610 // applying a conversion function to the argument 4611 // expression, the implicit conversion sequence is a 4612 // user-defined conversion sequence (13.3.3.1.2), with the 4613 // second standard conversion sequence either an identity 4614 // conversion or, if the conversion function returns an 4615 // entity of a type that is a derived class of the parameter 4616 // type, a derived-to-base Conversion. 4617 if (!Best->FinalConversion.DirectBinding) 4618 return false; 4619 4620 ICS.setUserDefined(); 4621 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4622 ICS.UserDefined.After = Best->FinalConversion; 4623 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4624 ICS.UserDefined.ConversionFunction = Best->Function; 4625 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4626 ICS.UserDefined.EllipsisConversion = false; 4627 assert(ICS.UserDefined.After.ReferenceBinding && 4628 ICS.UserDefined.After.DirectBinding && 4629 "Expected a direct reference binding!"); 4630 return true; 4631 4632 case OR_Ambiguous: 4633 ICS.setAmbiguous(); 4634 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4635 Cand != CandidateSet.end(); ++Cand) 4636 if (Cand->Best) 4637 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4638 return true; 4639 4640 case OR_No_Viable_Function: 4641 case OR_Deleted: 4642 // There was no suitable conversion, or we found a deleted 4643 // conversion; continue with other checks. 4644 return false; 4645 } 4646 4647 llvm_unreachable("Invalid OverloadResult!"); 4648 } 4649 4650 /// Compute an implicit conversion sequence for reference 4651 /// initialization. 4652 static ImplicitConversionSequence 4653 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4654 SourceLocation DeclLoc, 4655 bool SuppressUserConversions, 4656 bool AllowExplicit) { 4657 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4658 4659 // Most paths end in a failed conversion. 4660 ImplicitConversionSequence ICS; 4661 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4662 4663 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4664 QualType T2 = Init->getType(); 4665 4666 // If the initializer is the address of an overloaded function, try 4667 // to resolve the overloaded function. If all goes well, T2 is the 4668 // type of the resulting function. 4669 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4670 DeclAccessPair Found; 4671 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4672 false, Found)) 4673 T2 = Fn->getType(); 4674 } 4675 4676 // Compute some basic properties of the types and the initializer. 4677 bool isRValRef = DeclType->isRValueReferenceType(); 4678 Expr::Classification InitCategory = Init->Classify(S.Context); 4679 4680 Sema::ReferenceConversions RefConv; 4681 Sema::ReferenceCompareResult RefRelationship = 4682 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4683 4684 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4685 ICS.setStandard(); 4686 ICS.Standard.First = ICK_Identity; 4687 // FIXME: A reference binding can be a function conversion too. We should 4688 // consider that when ordering reference-to-function bindings. 4689 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4690 ? ICK_Derived_To_Base 4691 : (RefConv & Sema::ReferenceConversions::ObjC) 4692 ? ICK_Compatible_Conversion 4693 : ICK_Identity; 4694 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4695 // a reference binding that performs a non-top-level qualification 4696 // conversion as a qualification conversion, not as an identity conversion. 4697 ICS.Standard.Third = (RefConv & 4698 Sema::ReferenceConversions::NestedQualification) 4699 ? ICK_Qualification 4700 : ICK_Identity; 4701 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4702 ICS.Standard.setToType(0, T2); 4703 ICS.Standard.setToType(1, T1); 4704 ICS.Standard.setToType(2, T1); 4705 ICS.Standard.ReferenceBinding = true; 4706 ICS.Standard.DirectBinding = BindsDirectly; 4707 ICS.Standard.IsLvalueReference = !isRValRef; 4708 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4709 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4710 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4711 ICS.Standard.ObjCLifetimeConversionBinding = 4712 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4713 ICS.Standard.CopyConstructor = nullptr; 4714 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4715 }; 4716 4717 // C++0x [dcl.init.ref]p5: 4718 // A reference to type "cv1 T1" is initialized by an expression 4719 // of type "cv2 T2" as follows: 4720 4721 // -- If reference is an lvalue reference and the initializer expression 4722 if (!isRValRef) { 4723 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4724 // reference-compatible with "cv2 T2," or 4725 // 4726 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4727 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4728 // C++ [over.ics.ref]p1: 4729 // When a parameter of reference type binds directly (8.5.3) 4730 // to an argument expression, the implicit conversion sequence 4731 // is the identity conversion, unless the argument expression 4732 // has a type that is a derived class of the parameter type, 4733 // in which case the implicit conversion sequence is a 4734 // derived-to-base Conversion (13.3.3.1). 4735 SetAsReferenceBinding(/*BindsDirectly=*/true); 4736 4737 // Nothing more to do: the inaccessibility/ambiguity check for 4738 // derived-to-base conversions is suppressed when we're 4739 // computing the implicit conversion sequence (C++ 4740 // [over.best.ics]p2). 4741 return ICS; 4742 } 4743 4744 // -- has a class type (i.e., T2 is a class type), where T1 is 4745 // not reference-related to T2, and can be implicitly 4746 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4747 // is reference-compatible with "cv3 T3" 92) (this 4748 // conversion is selected by enumerating the applicable 4749 // conversion functions (13.3.1.6) and choosing the best 4750 // one through overload resolution (13.3)), 4751 if (!SuppressUserConversions && T2->isRecordType() && 4752 S.isCompleteType(DeclLoc, T2) && 4753 RefRelationship == Sema::Ref_Incompatible) { 4754 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4755 Init, T2, /*AllowRvalues=*/false, 4756 AllowExplicit)) 4757 return ICS; 4758 } 4759 } 4760 4761 // -- Otherwise, the reference shall be an lvalue reference to a 4762 // non-volatile const type (i.e., cv1 shall be const), or the reference 4763 // shall be an rvalue reference. 4764 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4765 return ICS; 4766 4767 // -- If the initializer expression 4768 // 4769 // -- is an xvalue, class prvalue, array prvalue or function 4770 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4771 if (RefRelationship == Sema::Ref_Compatible && 4772 (InitCategory.isXValue() || 4773 (InitCategory.isPRValue() && 4774 (T2->isRecordType() || T2->isArrayType())) || 4775 (InitCategory.isLValue() && T2->isFunctionType()))) { 4776 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4777 // binding unless we're binding to a class prvalue. 4778 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4779 // allow the use of rvalue references in C++98/03 for the benefit of 4780 // standard library implementors; therefore, we need the xvalue check here. 4781 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4782 !(InitCategory.isPRValue() || T2->isRecordType())); 4783 return ICS; 4784 } 4785 4786 // -- has a class type (i.e., T2 is a class type), where T1 is not 4787 // reference-related to T2, and can be implicitly converted to 4788 // an xvalue, class prvalue, or function lvalue of type 4789 // "cv3 T3", where "cv1 T1" is reference-compatible with 4790 // "cv3 T3", 4791 // 4792 // then the reference is bound to the value of the initializer 4793 // expression in the first case and to the result of the conversion 4794 // in the second case (or, in either case, to an appropriate base 4795 // class subobject). 4796 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4797 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4798 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4799 Init, T2, /*AllowRvalues=*/true, 4800 AllowExplicit)) { 4801 // In the second case, if the reference is an rvalue reference 4802 // and the second standard conversion sequence of the 4803 // user-defined conversion sequence includes an lvalue-to-rvalue 4804 // conversion, the program is ill-formed. 4805 if (ICS.isUserDefined() && isRValRef && 4806 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4807 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4808 4809 return ICS; 4810 } 4811 4812 // A temporary of function type cannot be created; don't even try. 4813 if (T1->isFunctionType()) 4814 return ICS; 4815 4816 // -- Otherwise, a temporary of type "cv1 T1" is created and 4817 // initialized from the initializer expression using the 4818 // rules for a non-reference copy initialization (8.5). The 4819 // reference is then bound to the temporary. If T1 is 4820 // reference-related to T2, cv1 must be the same 4821 // cv-qualification as, or greater cv-qualification than, 4822 // cv2; otherwise, the program is ill-formed. 4823 if (RefRelationship == Sema::Ref_Related) { 4824 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4825 // we would be reference-compatible or reference-compatible with 4826 // added qualification. But that wasn't the case, so the reference 4827 // initialization fails. 4828 // 4829 // Note that we only want to check address spaces and cvr-qualifiers here. 4830 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4831 Qualifiers T1Quals = T1.getQualifiers(); 4832 Qualifiers T2Quals = T2.getQualifiers(); 4833 T1Quals.removeObjCGCAttr(); 4834 T1Quals.removeObjCLifetime(); 4835 T2Quals.removeObjCGCAttr(); 4836 T2Quals.removeObjCLifetime(); 4837 // MS compiler ignores __unaligned qualifier for references; do the same. 4838 T1Quals.removeUnaligned(); 4839 T2Quals.removeUnaligned(); 4840 if (!T1Quals.compatiblyIncludes(T2Quals)) 4841 return ICS; 4842 } 4843 4844 // If at least one of the types is a class type, the types are not 4845 // related, and we aren't allowed any user conversions, the 4846 // reference binding fails. This case is important for breaking 4847 // recursion, since TryImplicitConversion below will attempt to 4848 // create a temporary through the use of a copy constructor. 4849 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4850 (T1->isRecordType() || T2->isRecordType())) 4851 return ICS; 4852 4853 // If T1 is reference-related to T2 and the reference is an rvalue 4854 // reference, the initializer expression shall not be an lvalue. 4855 if (RefRelationship >= Sema::Ref_Related && 4856 isRValRef && Init->Classify(S.Context).isLValue()) 4857 return ICS; 4858 4859 // C++ [over.ics.ref]p2: 4860 // When a parameter of reference type is not bound directly to 4861 // an argument expression, the conversion sequence is the one 4862 // required to convert the argument expression to the 4863 // underlying type of the reference according to 4864 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4865 // to copy-initializing a temporary of the underlying type with 4866 // the argument expression. Any difference in top-level 4867 // cv-qualification is subsumed by the initialization itself 4868 // and does not constitute a conversion. 4869 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4870 AllowedExplicit::None, 4871 /*InOverloadResolution=*/false, 4872 /*CStyle=*/false, 4873 /*AllowObjCWritebackConversion=*/false, 4874 /*AllowObjCConversionOnExplicit=*/false); 4875 4876 // Of course, that's still a reference binding. 4877 if (ICS.isStandard()) { 4878 ICS.Standard.ReferenceBinding = true; 4879 ICS.Standard.IsLvalueReference = !isRValRef; 4880 ICS.Standard.BindsToFunctionLvalue = false; 4881 ICS.Standard.BindsToRvalue = true; 4882 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4883 ICS.Standard.ObjCLifetimeConversionBinding = false; 4884 } else if (ICS.isUserDefined()) { 4885 const ReferenceType *LValRefType = 4886 ICS.UserDefined.ConversionFunction->getReturnType() 4887 ->getAs<LValueReferenceType>(); 4888 4889 // C++ [over.ics.ref]p3: 4890 // Except for an implicit object parameter, for which see 13.3.1, a 4891 // standard conversion sequence cannot be formed if it requires [...] 4892 // binding an rvalue reference to an lvalue other than a function 4893 // lvalue. 4894 // Note that the function case is not possible here. 4895 if (DeclType->isRValueReferenceType() && LValRefType) { 4896 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4897 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4898 // reference to an rvalue! 4899 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4900 return ICS; 4901 } 4902 4903 ICS.UserDefined.After.ReferenceBinding = true; 4904 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4905 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4906 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4907 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4908 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4909 } 4910 4911 return ICS; 4912 } 4913 4914 static ImplicitConversionSequence 4915 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4916 bool SuppressUserConversions, 4917 bool InOverloadResolution, 4918 bool AllowObjCWritebackConversion, 4919 bool AllowExplicit = false); 4920 4921 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4922 /// initializer list From. 4923 static ImplicitConversionSequence 4924 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4925 bool SuppressUserConversions, 4926 bool InOverloadResolution, 4927 bool AllowObjCWritebackConversion) { 4928 // C++11 [over.ics.list]p1: 4929 // When an argument is an initializer list, it is not an expression and 4930 // special rules apply for converting it to a parameter type. 4931 4932 ImplicitConversionSequence Result; 4933 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4934 4935 // We need a complete type for what follows. Incomplete types can never be 4936 // initialized from init lists. 4937 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4938 return Result; 4939 4940 // Per DR1467: 4941 // If the parameter type is a class X and the initializer list has a single 4942 // element of type cv U, where U is X or a class derived from X, the 4943 // implicit conversion sequence is the one required to convert the element 4944 // to the parameter type. 4945 // 4946 // Otherwise, if the parameter type is a character array [... ] 4947 // and the initializer list has a single element that is an 4948 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4949 // implicit conversion sequence is the identity conversion. 4950 if (From->getNumInits() == 1) { 4951 if (ToType->isRecordType()) { 4952 QualType InitType = From->getInit(0)->getType(); 4953 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4954 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4955 return TryCopyInitialization(S, From->getInit(0), ToType, 4956 SuppressUserConversions, 4957 InOverloadResolution, 4958 AllowObjCWritebackConversion); 4959 } 4960 // FIXME: Check the other conditions here: array of character type, 4961 // initializer is a string literal. 4962 if (ToType->isArrayType()) { 4963 InitializedEntity Entity = 4964 InitializedEntity::InitializeParameter(S.Context, ToType, 4965 /*Consumed=*/false); 4966 if (S.CanPerformCopyInitialization(Entity, From)) { 4967 Result.setStandard(); 4968 Result.Standard.setAsIdentityConversion(); 4969 Result.Standard.setFromType(ToType); 4970 Result.Standard.setAllToTypes(ToType); 4971 return Result; 4972 } 4973 } 4974 } 4975 4976 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4977 // C++11 [over.ics.list]p2: 4978 // If the parameter type is std::initializer_list<X> or "array of X" and 4979 // all the elements can be implicitly converted to X, the implicit 4980 // conversion sequence is the worst conversion necessary to convert an 4981 // element of the list to X. 4982 // 4983 // C++14 [over.ics.list]p3: 4984 // Otherwise, if the parameter type is "array of N X", if the initializer 4985 // list has exactly N elements or if it has fewer than N elements and X is 4986 // default-constructible, and if all the elements of the initializer list 4987 // can be implicitly converted to X, the implicit conversion sequence is 4988 // the worst conversion necessary to convert an element of the list to X. 4989 // 4990 // FIXME: We're missing a lot of these checks. 4991 bool toStdInitializerList = false; 4992 QualType X; 4993 if (ToType->isArrayType()) 4994 X = S.Context.getAsArrayType(ToType)->getElementType(); 4995 else 4996 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4997 if (!X.isNull()) { 4998 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4999 Expr *Init = From->getInit(i); 5000 ImplicitConversionSequence ICS = 5001 TryCopyInitialization(S, Init, X, SuppressUserConversions, 5002 InOverloadResolution, 5003 AllowObjCWritebackConversion); 5004 // If a single element isn't convertible, fail. 5005 if (ICS.isBad()) { 5006 Result = ICS; 5007 break; 5008 } 5009 // Otherwise, look for the worst conversion. 5010 if (Result.isBad() || CompareImplicitConversionSequences( 5011 S, From->getBeginLoc(), ICS, Result) == 5012 ImplicitConversionSequence::Worse) 5013 Result = ICS; 5014 } 5015 5016 // For an empty list, we won't have computed any conversion sequence. 5017 // Introduce the identity conversion sequence. 5018 if (From->getNumInits() == 0) { 5019 Result.setStandard(); 5020 Result.Standard.setAsIdentityConversion(); 5021 Result.Standard.setFromType(ToType); 5022 Result.Standard.setAllToTypes(ToType); 5023 } 5024 5025 Result.setStdInitializerListElement(toStdInitializerList); 5026 return Result; 5027 } 5028 5029 // C++14 [over.ics.list]p4: 5030 // C++11 [over.ics.list]p3: 5031 // Otherwise, if the parameter is a non-aggregate class X and overload 5032 // resolution chooses a single best constructor [...] the implicit 5033 // conversion sequence is a user-defined conversion sequence. If multiple 5034 // constructors are viable but none is better than the others, the 5035 // implicit conversion sequence is a user-defined conversion sequence. 5036 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5037 // This function can deal with initializer lists. 5038 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5039 AllowedExplicit::None, 5040 InOverloadResolution, /*CStyle=*/false, 5041 AllowObjCWritebackConversion, 5042 /*AllowObjCConversionOnExplicit=*/false); 5043 } 5044 5045 // C++14 [over.ics.list]p5: 5046 // C++11 [over.ics.list]p4: 5047 // Otherwise, if the parameter has an aggregate type which can be 5048 // initialized from the initializer list [...] the implicit conversion 5049 // sequence is a user-defined conversion sequence. 5050 if (ToType->isAggregateType()) { 5051 // Type is an aggregate, argument is an init list. At this point it comes 5052 // down to checking whether the initialization works. 5053 // FIXME: Find out whether this parameter is consumed or not. 5054 InitializedEntity Entity = 5055 InitializedEntity::InitializeParameter(S.Context, ToType, 5056 /*Consumed=*/false); 5057 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5058 From)) { 5059 Result.setUserDefined(); 5060 Result.UserDefined.Before.setAsIdentityConversion(); 5061 // Initializer lists don't have a type. 5062 Result.UserDefined.Before.setFromType(QualType()); 5063 Result.UserDefined.Before.setAllToTypes(QualType()); 5064 5065 Result.UserDefined.After.setAsIdentityConversion(); 5066 Result.UserDefined.After.setFromType(ToType); 5067 Result.UserDefined.After.setAllToTypes(ToType); 5068 Result.UserDefined.ConversionFunction = nullptr; 5069 } 5070 return Result; 5071 } 5072 5073 // C++14 [over.ics.list]p6: 5074 // C++11 [over.ics.list]p5: 5075 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5076 if (ToType->isReferenceType()) { 5077 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5078 // mention initializer lists in any way. So we go by what list- 5079 // initialization would do and try to extrapolate from that. 5080 5081 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5082 5083 // If the initializer list has a single element that is reference-related 5084 // to the parameter type, we initialize the reference from that. 5085 if (From->getNumInits() == 1) { 5086 Expr *Init = From->getInit(0); 5087 5088 QualType T2 = Init->getType(); 5089 5090 // If the initializer is the address of an overloaded function, try 5091 // to resolve the overloaded function. If all goes well, T2 is the 5092 // type of the resulting function. 5093 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5094 DeclAccessPair Found; 5095 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5096 Init, ToType, false, Found)) 5097 T2 = Fn->getType(); 5098 } 5099 5100 // Compute some basic properties of the types and the initializer. 5101 Sema::ReferenceCompareResult RefRelationship = 5102 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5103 5104 if (RefRelationship >= Sema::Ref_Related) { 5105 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5106 SuppressUserConversions, 5107 /*AllowExplicit=*/false); 5108 } 5109 } 5110 5111 // Otherwise, we bind the reference to a temporary created from the 5112 // initializer list. 5113 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5114 InOverloadResolution, 5115 AllowObjCWritebackConversion); 5116 if (Result.isFailure()) 5117 return Result; 5118 assert(!Result.isEllipsis() && 5119 "Sub-initialization cannot result in ellipsis conversion."); 5120 5121 // Can we even bind to a temporary? 5122 if (ToType->isRValueReferenceType() || 5123 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5124 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5125 Result.UserDefined.After; 5126 SCS.ReferenceBinding = true; 5127 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5128 SCS.BindsToRvalue = true; 5129 SCS.BindsToFunctionLvalue = false; 5130 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5131 SCS.ObjCLifetimeConversionBinding = false; 5132 } else 5133 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5134 From, ToType); 5135 return Result; 5136 } 5137 5138 // C++14 [over.ics.list]p7: 5139 // C++11 [over.ics.list]p6: 5140 // Otherwise, if the parameter type is not a class: 5141 if (!ToType->isRecordType()) { 5142 // - if the initializer list has one element that is not itself an 5143 // initializer list, the implicit conversion sequence is the one 5144 // required to convert the element to the parameter type. 5145 unsigned NumInits = From->getNumInits(); 5146 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5147 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5148 SuppressUserConversions, 5149 InOverloadResolution, 5150 AllowObjCWritebackConversion); 5151 // - if the initializer list has no elements, the implicit conversion 5152 // sequence is the identity conversion. 5153 else if (NumInits == 0) { 5154 Result.setStandard(); 5155 Result.Standard.setAsIdentityConversion(); 5156 Result.Standard.setFromType(ToType); 5157 Result.Standard.setAllToTypes(ToType); 5158 } 5159 return Result; 5160 } 5161 5162 // C++14 [over.ics.list]p8: 5163 // C++11 [over.ics.list]p7: 5164 // In all cases other than those enumerated above, no conversion is possible 5165 return Result; 5166 } 5167 5168 /// TryCopyInitialization - Try to copy-initialize a value of type 5169 /// ToType from the expression From. Return the implicit conversion 5170 /// sequence required to pass this argument, which may be a bad 5171 /// conversion sequence (meaning that the argument cannot be passed to 5172 /// a parameter of this type). If @p SuppressUserConversions, then we 5173 /// do not permit any user-defined conversion sequences. 5174 static ImplicitConversionSequence 5175 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5176 bool SuppressUserConversions, 5177 bool InOverloadResolution, 5178 bool AllowObjCWritebackConversion, 5179 bool AllowExplicit) { 5180 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5181 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5182 InOverloadResolution,AllowObjCWritebackConversion); 5183 5184 if (ToType->isReferenceType()) 5185 return TryReferenceInit(S, From, ToType, 5186 /*FIXME:*/ From->getBeginLoc(), 5187 SuppressUserConversions, AllowExplicit); 5188 5189 return TryImplicitConversion(S, From, ToType, 5190 SuppressUserConversions, 5191 AllowedExplicit::None, 5192 InOverloadResolution, 5193 /*CStyle=*/false, 5194 AllowObjCWritebackConversion, 5195 /*AllowObjCConversionOnExplicit=*/false); 5196 } 5197 5198 static bool TryCopyInitialization(const CanQualType FromQTy, 5199 const CanQualType ToQTy, 5200 Sema &S, 5201 SourceLocation Loc, 5202 ExprValueKind FromVK) { 5203 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5204 ImplicitConversionSequence ICS = 5205 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5206 5207 return !ICS.isBad(); 5208 } 5209 5210 /// TryObjectArgumentInitialization - Try to initialize the object 5211 /// parameter of the given member function (@c Method) from the 5212 /// expression @p From. 5213 static ImplicitConversionSequence 5214 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5215 Expr::Classification FromClassification, 5216 CXXMethodDecl *Method, 5217 CXXRecordDecl *ActingContext) { 5218 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5219 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5220 // const volatile object. 5221 Qualifiers Quals = Method->getMethodQualifiers(); 5222 if (isa<CXXDestructorDecl>(Method)) { 5223 Quals.addConst(); 5224 Quals.addVolatile(); 5225 } 5226 5227 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5228 5229 // Set up the conversion sequence as a "bad" conversion, to allow us 5230 // to exit early. 5231 ImplicitConversionSequence ICS; 5232 5233 // We need to have an object of class type. 5234 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5235 FromType = PT->getPointeeType(); 5236 5237 // When we had a pointer, it's implicitly dereferenced, so we 5238 // better have an lvalue. 5239 assert(FromClassification.isLValue()); 5240 } 5241 5242 assert(FromType->isRecordType()); 5243 5244 // C++0x [over.match.funcs]p4: 5245 // For non-static member functions, the type of the implicit object 5246 // parameter is 5247 // 5248 // - "lvalue reference to cv X" for functions declared without a 5249 // ref-qualifier or with the & ref-qualifier 5250 // - "rvalue reference to cv X" for functions declared with the && 5251 // ref-qualifier 5252 // 5253 // where X is the class of which the function is a member and cv is the 5254 // cv-qualification on the member function declaration. 5255 // 5256 // However, when finding an implicit conversion sequence for the argument, we 5257 // are not allowed to perform user-defined conversions 5258 // (C++ [over.match.funcs]p5). We perform a simplified version of 5259 // reference binding here, that allows class rvalues to bind to 5260 // non-constant references. 5261 5262 // First check the qualifiers. 5263 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5264 if (ImplicitParamType.getCVRQualifiers() 5265 != FromTypeCanon.getLocalCVRQualifiers() && 5266 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5267 ICS.setBad(BadConversionSequence::bad_qualifiers, 5268 FromType, ImplicitParamType); 5269 return ICS; 5270 } 5271 5272 if (FromTypeCanon.hasAddressSpace()) { 5273 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5274 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5275 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5276 ICS.setBad(BadConversionSequence::bad_qualifiers, 5277 FromType, ImplicitParamType); 5278 return ICS; 5279 } 5280 } 5281 5282 // Check that we have either the same type or a derived type. It 5283 // affects the conversion rank. 5284 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5285 ImplicitConversionKind SecondKind; 5286 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5287 SecondKind = ICK_Identity; 5288 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5289 SecondKind = ICK_Derived_To_Base; 5290 else { 5291 ICS.setBad(BadConversionSequence::unrelated_class, 5292 FromType, ImplicitParamType); 5293 return ICS; 5294 } 5295 5296 // Check the ref-qualifier. 5297 switch (Method->getRefQualifier()) { 5298 case RQ_None: 5299 // Do nothing; we don't care about lvalueness or rvalueness. 5300 break; 5301 5302 case RQ_LValue: 5303 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5304 // non-const lvalue reference cannot bind to an rvalue 5305 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5306 ImplicitParamType); 5307 return ICS; 5308 } 5309 break; 5310 5311 case RQ_RValue: 5312 if (!FromClassification.isRValue()) { 5313 // rvalue reference cannot bind to an lvalue 5314 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5315 ImplicitParamType); 5316 return ICS; 5317 } 5318 break; 5319 } 5320 5321 // Success. Mark this as a reference binding. 5322 ICS.setStandard(); 5323 ICS.Standard.setAsIdentityConversion(); 5324 ICS.Standard.Second = SecondKind; 5325 ICS.Standard.setFromType(FromType); 5326 ICS.Standard.setAllToTypes(ImplicitParamType); 5327 ICS.Standard.ReferenceBinding = true; 5328 ICS.Standard.DirectBinding = true; 5329 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5330 ICS.Standard.BindsToFunctionLvalue = false; 5331 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5332 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5333 = (Method->getRefQualifier() == RQ_None); 5334 return ICS; 5335 } 5336 5337 /// PerformObjectArgumentInitialization - Perform initialization of 5338 /// the implicit object parameter for the given Method with the given 5339 /// expression. 5340 ExprResult 5341 Sema::PerformObjectArgumentInitialization(Expr *From, 5342 NestedNameSpecifier *Qualifier, 5343 NamedDecl *FoundDecl, 5344 CXXMethodDecl *Method) { 5345 QualType FromRecordType, DestType; 5346 QualType ImplicitParamRecordType = 5347 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5348 5349 Expr::Classification FromClassification; 5350 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5351 FromRecordType = PT->getPointeeType(); 5352 DestType = Method->getThisType(); 5353 FromClassification = Expr::Classification::makeSimpleLValue(); 5354 } else { 5355 FromRecordType = From->getType(); 5356 DestType = ImplicitParamRecordType; 5357 FromClassification = From->Classify(Context); 5358 5359 // When performing member access on an rvalue, materialize a temporary. 5360 if (From->isRValue()) { 5361 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5362 Method->getRefQualifier() != 5363 RefQualifierKind::RQ_RValue); 5364 } 5365 } 5366 5367 // Note that we always use the true parent context when performing 5368 // the actual argument initialization. 5369 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5370 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5371 Method->getParent()); 5372 if (ICS.isBad()) { 5373 switch (ICS.Bad.Kind) { 5374 case BadConversionSequence::bad_qualifiers: { 5375 Qualifiers FromQs = FromRecordType.getQualifiers(); 5376 Qualifiers ToQs = DestType.getQualifiers(); 5377 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5378 if (CVR) { 5379 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5380 << Method->getDeclName() << FromRecordType << (CVR - 1) 5381 << From->getSourceRange(); 5382 Diag(Method->getLocation(), diag::note_previous_decl) 5383 << Method->getDeclName(); 5384 return ExprError(); 5385 } 5386 break; 5387 } 5388 5389 case BadConversionSequence::lvalue_ref_to_rvalue: 5390 case BadConversionSequence::rvalue_ref_to_lvalue: { 5391 bool IsRValueQualified = 5392 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5393 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5394 << Method->getDeclName() << FromClassification.isRValue() 5395 << IsRValueQualified; 5396 Diag(Method->getLocation(), diag::note_previous_decl) 5397 << Method->getDeclName(); 5398 return ExprError(); 5399 } 5400 5401 case BadConversionSequence::no_conversion: 5402 case BadConversionSequence::unrelated_class: 5403 break; 5404 } 5405 5406 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5407 << ImplicitParamRecordType << FromRecordType 5408 << From->getSourceRange(); 5409 } 5410 5411 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5412 ExprResult FromRes = 5413 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5414 if (FromRes.isInvalid()) 5415 return ExprError(); 5416 From = FromRes.get(); 5417 } 5418 5419 if (!Context.hasSameType(From->getType(), DestType)) { 5420 CastKind CK; 5421 QualType PteeTy = DestType->getPointeeType(); 5422 LangAS DestAS = 5423 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5424 if (FromRecordType.getAddressSpace() != DestAS) 5425 CK = CK_AddressSpaceConversion; 5426 else 5427 CK = CK_NoOp; 5428 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5429 } 5430 return From; 5431 } 5432 5433 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5434 /// expression From to bool (C++0x [conv]p3). 5435 static ImplicitConversionSequence 5436 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5437 return TryImplicitConversion(S, From, S.Context.BoolTy, 5438 /*SuppressUserConversions=*/false, 5439 AllowedExplicit::Conversions, 5440 /*InOverloadResolution=*/false, 5441 /*CStyle=*/false, 5442 /*AllowObjCWritebackConversion=*/false, 5443 /*AllowObjCConversionOnExplicit=*/false); 5444 } 5445 5446 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5447 /// of the expression From to bool (C++0x [conv]p3). 5448 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5449 if (checkPlaceholderForOverload(*this, From)) 5450 return ExprError(); 5451 5452 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5453 if (!ICS.isBad()) 5454 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5455 5456 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5457 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5458 << From->getType() << From->getSourceRange(); 5459 return ExprError(); 5460 } 5461 5462 /// Check that the specified conversion is permitted in a converted constant 5463 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5464 /// is acceptable. 5465 static bool CheckConvertedConstantConversions(Sema &S, 5466 StandardConversionSequence &SCS) { 5467 // Since we know that the target type is an integral or unscoped enumeration 5468 // type, most conversion kinds are impossible. All possible First and Third 5469 // conversions are fine. 5470 switch (SCS.Second) { 5471 case ICK_Identity: 5472 case ICK_Function_Conversion: 5473 case ICK_Integral_Promotion: 5474 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5475 case ICK_Zero_Queue_Conversion: 5476 return true; 5477 5478 case ICK_Boolean_Conversion: 5479 // Conversion from an integral or unscoped enumeration type to bool is 5480 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5481 // conversion, so we allow it in a converted constant expression. 5482 // 5483 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5484 // a lot of popular code. We should at least add a warning for this 5485 // (non-conforming) extension. 5486 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5487 SCS.getToType(2)->isBooleanType(); 5488 5489 case ICK_Pointer_Conversion: 5490 case ICK_Pointer_Member: 5491 // C++1z: null pointer conversions and null member pointer conversions are 5492 // only permitted if the source type is std::nullptr_t. 5493 return SCS.getFromType()->isNullPtrType(); 5494 5495 case ICK_Floating_Promotion: 5496 case ICK_Complex_Promotion: 5497 case ICK_Floating_Conversion: 5498 case ICK_Complex_Conversion: 5499 case ICK_Floating_Integral: 5500 case ICK_Compatible_Conversion: 5501 case ICK_Derived_To_Base: 5502 case ICK_Vector_Conversion: 5503 case ICK_Vector_Splat: 5504 case ICK_Complex_Real: 5505 case ICK_Block_Pointer_Conversion: 5506 case ICK_TransparentUnionConversion: 5507 case ICK_Writeback_Conversion: 5508 case ICK_Zero_Event_Conversion: 5509 case ICK_C_Only_Conversion: 5510 case ICK_Incompatible_Pointer_Conversion: 5511 return false; 5512 5513 case ICK_Lvalue_To_Rvalue: 5514 case ICK_Array_To_Pointer: 5515 case ICK_Function_To_Pointer: 5516 llvm_unreachable("found a first conversion kind in Second"); 5517 5518 case ICK_Qualification: 5519 llvm_unreachable("found a third conversion kind in Second"); 5520 5521 case ICK_Num_Conversion_Kinds: 5522 break; 5523 } 5524 5525 llvm_unreachable("unknown conversion kind"); 5526 } 5527 5528 /// CheckConvertedConstantExpression - Check that the expression From is a 5529 /// converted constant expression of type T, perform the conversion and produce 5530 /// the converted expression, per C++11 [expr.const]p3. 5531 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5532 QualType T, APValue &Value, 5533 Sema::CCEKind CCE, 5534 bool RequireInt) { 5535 assert(S.getLangOpts().CPlusPlus11 && 5536 "converted constant expression outside C++11"); 5537 5538 if (checkPlaceholderForOverload(S, From)) 5539 return ExprError(); 5540 5541 // C++1z [expr.const]p3: 5542 // A converted constant expression of type T is an expression, 5543 // implicitly converted to type T, where the converted 5544 // expression is a constant expression and the implicit conversion 5545 // sequence contains only [... list of conversions ...]. 5546 // C++1z [stmt.if]p2: 5547 // If the if statement is of the form if constexpr, the value of the 5548 // condition shall be a contextually converted constant expression of type 5549 // bool. 5550 ImplicitConversionSequence ICS = 5551 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5552 ? TryContextuallyConvertToBool(S, From) 5553 : TryCopyInitialization(S, From, T, 5554 /*SuppressUserConversions=*/false, 5555 /*InOverloadResolution=*/false, 5556 /*AllowObjCWritebackConversion=*/false, 5557 /*AllowExplicit=*/false); 5558 StandardConversionSequence *SCS = nullptr; 5559 switch (ICS.getKind()) { 5560 case ImplicitConversionSequence::StandardConversion: 5561 SCS = &ICS.Standard; 5562 break; 5563 case ImplicitConversionSequence::UserDefinedConversion: 5564 // We are converting to a non-class type, so the Before sequence 5565 // must be trivial. 5566 SCS = &ICS.UserDefined.After; 5567 break; 5568 case ImplicitConversionSequence::AmbiguousConversion: 5569 case ImplicitConversionSequence::BadConversion: 5570 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5571 return S.Diag(From->getBeginLoc(), 5572 diag::err_typecheck_converted_constant_expression) 5573 << From->getType() << From->getSourceRange() << T; 5574 return ExprError(); 5575 5576 case ImplicitConversionSequence::EllipsisConversion: 5577 llvm_unreachable("ellipsis conversion in converted constant expression"); 5578 } 5579 5580 // Check that we would only use permitted conversions. 5581 if (!CheckConvertedConstantConversions(S, *SCS)) { 5582 return S.Diag(From->getBeginLoc(), 5583 diag::err_typecheck_converted_constant_expression_disallowed) 5584 << From->getType() << From->getSourceRange() << T; 5585 } 5586 // [...] and where the reference binding (if any) binds directly. 5587 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5588 return S.Diag(From->getBeginLoc(), 5589 diag::err_typecheck_converted_constant_expression_indirect) 5590 << From->getType() << From->getSourceRange() << T; 5591 } 5592 5593 ExprResult Result = 5594 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5595 if (Result.isInvalid()) 5596 return Result; 5597 5598 // C++2a [intro.execution]p5: 5599 // A full-expression is [...] a constant-expression [...] 5600 Result = 5601 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5602 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5603 if (Result.isInvalid()) 5604 return Result; 5605 5606 // Check for a narrowing implicit conversion. 5607 APValue PreNarrowingValue; 5608 QualType PreNarrowingType; 5609 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5610 PreNarrowingType)) { 5611 case NK_Dependent_Narrowing: 5612 // Implicit conversion to a narrower type, but the expression is 5613 // value-dependent so we can't tell whether it's actually narrowing. 5614 case NK_Variable_Narrowing: 5615 // Implicit conversion to a narrower type, and the value is not a constant 5616 // expression. We'll diagnose this in a moment. 5617 case NK_Not_Narrowing: 5618 break; 5619 5620 case NK_Constant_Narrowing: 5621 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5622 << CCE << /*Constant*/ 1 5623 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5624 break; 5625 5626 case NK_Type_Narrowing: 5627 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5628 << CCE << /*Constant*/ 0 << From->getType() << T; 5629 break; 5630 } 5631 5632 if (Result.get()->isValueDependent()) { 5633 Value = APValue(); 5634 return Result; 5635 } 5636 5637 // Check the expression is a constant expression. 5638 SmallVector<PartialDiagnosticAt, 8> Notes; 5639 Expr::EvalResult Eval; 5640 Eval.Diag = &Notes; 5641 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5642 ? Expr::EvaluateForMangling 5643 : Expr::EvaluateForCodeGen; 5644 5645 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5646 (RequireInt && !Eval.Val.isInt())) { 5647 // The expression can't be folded, so we can't keep it at this position in 5648 // the AST. 5649 Result = ExprError(); 5650 } else { 5651 Value = Eval.Val; 5652 5653 if (Notes.empty()) { 5654 // It's a constant expression. 5655 return ConstantExpr::Create(S.Context, Result.get(), Value); 5656 } 5657 } 5658 5659 // It's not a constant expression. Produce an appropriate diagnostic. 5660 if (Notes.size() == 1 && 5661 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5662 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5663 else { 5664 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5665 << CCE << From->getSourceRange(); 5666 for (unsigned I = 0; I < Notes.size(); ++I) 5667 S.Diag(Notes[I].first, Notes[I].second); 5668 } 5669 return ExprError(); 5670 } 5671 5672 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5673 APValue &Value, CCEKind CCE) { 5674 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5675 } 5676 5677 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5678 llvm::APSInt &Value, 5679 CCEKind CCE) { 5680 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5681 5682 APValue V; 5683 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5684 if (!R.isInvalid() && !R.get()->isValueDependent()) 5685 Value = V.getInt(); 5686 return R; 5687 } 5688 5689 5690 /// dropPointerConversions - If the given standard conversion sequence 5691 /// involves any pointer conversions, remove them. This may change 5692 /// the result type of the conversion sequence. 5693 static void dropPointerConversion(StandardConversionSequence &SCS) { 5694 if (SCS.Second == ICK_Pointer_Conversion) { 5695 SCS.Second = ICK_Identity; 5696 SCS.Third = ICK_Identity; 5697 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5698 } 5699 } 5700 5701 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5702 /// convert the expression From to an Objective-C pointer type. 5703 static ImplicitConversionSequence 5704 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5705 // Do an implicit conversion to 'id'. 5706 QualType Ty = S.Context.getObjCIdType(); 5707 ImplicitConversionSequence ICS 5708 = TryImplicitConversion(S, From, Ty, 5709 // FIXME: Are these flags correct? 5710 /*SuppressUserConversions=*/false, 5711 AllowedExplicit::Conversions, 5712 /*InOverloadResolution=*/false, 5713 /*CStyle=*/false, 5714 /*AllowObjCWritebackConversion=*/false, 5715 /*AllowObjCConversionOnExplicit=*/true); 5716 5717 // Strip off any final conversions to 'id'. 5718 switch (ICS.getKind()) { 5719 case ImplicitConversionSequence::BadConversion: 5720 case ImplicitConversionSequence::AmbiguousConversion: 5721 case ImplicitConversionSequence::EllipsisConversion: 5722 break; 5723 5724 case ImplicitConversionSequence::UserDefinedConversion: 5725 dropPointerConversion(ICS.UserDefined.After); 5726 break; 5727 5728 case ImplicitConversionSequence::StandardConversion: 5729 dropPointerConversion(ICS.Standard); 5730 break; 5731 } 5732 5733 return ICS; 5734 } 5735 5736 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5737 /// conversion of the expression From to an Objective-C pointer type. 5738 /// Returns a valid but null ExprResult if no conversion sequence exists. 5739 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5740 if (checkPlaceholderForOverload(*this, From)) 5741 return ExprError(); 5742 5743 QualType Ty = Context.getObjCIdType(); 5744 ImplicitConversionSequence ICS = 5745 TryContextuallyConvertToObjCPointer(*this, From); 5746 if (!ICS.isBad()) 5747 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5748 return ExprResult(); 5749 } 5750 5751 /// Determine whether the provided type is an integral type, or an enumeration 5752 /// type of a permitted flavor. 5753 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5754 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5755 : T->isIntegralOrUnscopedEnumerationType(); 5756 } 5757 5758 static ExprResult 5759 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5760 Sema::ContextualImplicitConverter &Converter, 5761 QualType T, UnresolvedSetImpl &ViableConversions) { 5762 5763 if (Converter.Suppress) 5764 return ExprError(); 5765 5766 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5767 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5768 CXXConversionDecl *Conv = 5769 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5770 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5771 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5772 } 5773 return From; 5774 } 5775 5776 static bool 5777 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5778 Sema::ContextualImplicitConverter &Converter, 5779 QualType T, bool HadMultipleCandidates, 5780 UnresolvedSetImpl &ExplicitConversions) { 5781 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5782 DeclAccessPair Found = ExplicitConversions[0]; 5783 CXXConversionDecl *Conversion = 5784 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5785 5786 // The user probably meant to invoke the given explicit 5787 // conversion; use it. 5788 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5789 std::string TypeStr; 5790 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5791 5792 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5793 << FixItHint::CreateInsertion(From->getBeginLoc(), 5794 "static_cast<" + TypeStr + ">(") 5795 << FixItHint::CreateInsertion( 5796 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5797 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5798 5799 // If we aren't in a SFINAE context, build a call to the 5800 // explicit conversion function. 5801 if (SemaRef.isSFINAEContext()) 5802 return true; 5803 5804 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5805 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5806 HadMultipleCandidates); 5807 if (Result.isInvalid()) 5808 return true; 5809 // Record usage of conversion in an implicit cast. 5810 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5811 CK_UserDefinedConversion, Result.get(), 5812 nullptr, Result.get()->getValueKind()); 5813 } 5814 return false; 5815 } 5816 5817 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5818 Sema::ContextualImplicitConverter &Converter, 5819 QualType T, bool HadMultipleCandidates, 5820 DeclAccessPair &Found) { 5821 CXXConversionDecl *Conversion = 5822 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5823 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5824 5825 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5826 if (!Converter.SuppressConversion) { 5827 if (SemaRef.isSFINAEContext()) 5828 return true; 5829 5830 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5831 << From->getSourceRange(); 5832 } 5833 5834 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5835 HadMultipleCandidates); 5836 if (Result.isInvalid()) 5837 return true; 5838 // Record usage of conversion in an implicit cast. 5839 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5840 CK_UserDefinedConversion, Result.get(), 5841 nullptr, Result.get()->getValueKind()); 5842 return false; 5843 } 5844 5845 static ExprResult finishContextualImplicitConversion( 5846 Sema &SemaRef, SourceLocation Loc, Expr *From, 5847 Sema::ContextualImplicitConverter &Converter) { 5848 if (!Converter.match(From->getType()) && !Converter.Suppress) 5849 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5850 << From->getSourceRange(); 5851 5852 return SemaRef.DefaultLvalueConversion(From); 5853 } 5854 5855 static void 5856 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5857 UnresolvedSetImpl &ViableConversions, 5858 OverloadCandidateSet &CandidateSet) { 5859 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5860 DeclAccessPair FoundDecl = ViableConversions[I]; 5861 NamedDecl *D = FoundDecl.getDecl(); 5862 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5863 if (isa<UsingShadowDecl>(D)) 5864 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5865 5866 CXXConversionDecl *Conv; 5867 FunctionTemplateDecl *ConvTemplate; 5868 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5869 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5870 else 5871 Conv = cast<CXXConversionDecl>(D); 5872 5873 if (ConvTemplate) 5874 SemaRef.AddTemplateConversionCandidate( 5875 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5876 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5877 else 5878 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5879 ToType, CandidateSet, 5880 /*AllowObjCConversionOnExplicit=*/false, 5881 /*AllowExplicit*/ true); 5882 } 5883 } 5884 5885 /// Attempt to convert the given expression to a type which is accepted 5886 /// by the given converter. 5887 /// 5888 /// This routine will attempt to convert an expression of class type to a 5889 /// type accepted by the specified converter. In C++11 and before, the class 5890 /// must have a single non-explicit conversion function converting to a matching 5891 /// type. In C++1y, there can be multiple such conversion functions, but only 5892 /// one target type. 5893 /// 5894 /// \param Loc The source location of the construct that requires the 5895 /// conversion. 5896 /// 5897 /// \param From The expression we're converting from. 5898 /// 5899 /// \param Converter Used to control and diagnose the conversion process. 5900 /// 5901 /// \returns The expression, converted to an integral or enumeration type if 5902 /// successful. 5903 ExprResult Sema::PerformContextualImplicitConversion( 5904 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5905 // We can't perform any more checking for type-dependent expressions. 5906 if (From->isTypeDependent()) 5907 return From; 5908 5909 // Process placeholders immediately. 5910 if (From->hasPlaceholderType()) { 5911 ExprResult result = CheckPlaceholderExpr(From); 5912 if (result.isInvalid()) 5913 return result; 5914 From = result.get(); 5915 } 5916 5917 // If the expression already has a matching type, we're golden. 5918 QualType T = From->getType(); 5919 if (Converter.match(T)) 5920 return DefaultLvalueConversion(From); 5921 5922 // FIXME: Check for missing '()' if T is a function type? 5923 5924 // We can only perform contextual implicit conversions on objects of class 5925 // type. 5926 const RecordType *RecordTy = T->getAs<RecordType>(); 5927 if (!RecordTy || !getLangOpts().CPlusPlus) { 5928 if (!Converter.Suppress) 5929 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5930 return From; 5931 } 5932 5933 // We must have a complete class type. 5934 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5935 ContextualImplicitConverter &Converter; 5936 Expr *From; 5937 5938 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5939 : Converter(Converter), From(From) {} 5940 5941 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5942 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5943 } 5944 } IncompleteDiagnoser(Converter, From); 5945 5946 if (Converter.Suppress ? !isCompleteType(Loc, T) 5947 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5948 return From; 5949 5950 // Look for a conversion to an integral or enumeration type. 5951 UnresolvedSet<4> 5952 ViableConversions; // These are *potentially* viable in C++1y. 5953 UnresolvedSet<4> ExplicitConversions; 5954 const auto &Conversions = 5955 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5956 5957 bool HadMultipleCandidates = 5958 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5959 5960 // To check that there is only one target type, in C++1y: 5961 QualType ToType; 5962 bool HasUniqueTargetType = true; 5963 5964 // Collect explicit or viable (potentially in C++1y) conversions. 5965 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5966 NamedDecl *D = (*I)->getUnderlyingDecl(); 5967 CXXConversionDecl *Conversion; 5968 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5969 if (ConvTemplate) { 5970 if (getLangOpts().CPlusPlus14) 5971 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5972 else 5973 continue; // C++11 does not consider conversion operator templates(?). 5974 } else 5975 Conversion = cast<CXXConversionDecl>(D); 5976 5977 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5978 "Conversion operator templates are considered potentially " 5979 "viable in C++1y"); 5980 5981 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5982 if (Converter.match(CurToType) || ConvTemplate) { 5983 5984 if (Conversion->isExplicit()) { 5985 // FIXME: For C++1y, do we need this restriction? 5986 // cf. diagnoseNoViableConversion() 5987 if (!ConvTemplate) 5988 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5989 } else { 5990 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5991 if (ToType.isNull()) 5992 ToType = CurToType.getUnqualifiedType(); 5993 else if (HasUniqueTargetType && 5994 (CurToType.getUnqualifiedType() != ToType)) 5995 HasUniqueTargetType = false; 5996 } 5997 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5998 } 5999 } 6000 } 6001 6002 if (getLangOpts().CPlusPlus14) { 6003 // C++1y [conv]p6: 6004 // ... An expression e of class type E appearing in such a context 6005 // is said to be contextually implicitly converted to a specified 6006 // type T and is well-formed if and only if e can be implicitly 6007 // converted to a type T that is determined as follows: E is searched 6008 // for conversion functions whose return type is cv T or reference to 6009 // cv T such that T is allowed by the context. There shall be 6010 // exactly one such T. 6011 6012 // If no unique T is found: 6013 if (ToType.isNull()) { 6014 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6015 HadMultipleCandidates, 6016 ExplicitConversions)) 6017 return ExprError(); 6018 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6019 } 6020 6021 // If more than one unique Ts are found: 6022 if (!HasUniqueTargetType) 6023 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6024 ViableConversions); 6025 6026 // If one unique T is found: 6027 // First, build a candidate set from the previously recorded 6028 // potentially viable conversions. 6029 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6030 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6031 CandidateSet); 6032 6033 // Then, perform overload resolution over the candidate set. 6034 OverloadCandidateSet::iterator Best; 6035 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6036 case OR_Success: { 6037 // Apply this conversion. 6038 DeclAccessPair Found = 6039 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6040 if (recordConversion(*this, Loc, From, Converter, T, 6041 HadMultipleCandidates, Found)) 6042 return ExprError(); 6043 break; 6044 } 6045 case OR_Ambiguous: 6046 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6047 ViableConversions); 6048 case OR_No_Viable_Function: 6049 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6050 HadMultipleCandidates, 6051 ExplicitConversions)) 6052 return ExprError(); 6053 LLVM_FALLTHROUGH; 6054 case OR_Deleted: 6055 // We'll complain below about a non-integral condition type. 6056 break; 6057 } 6058 } else { 6059 switch (ViableConversions.size()) { 6060 case 0: { 6061 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6062 HadMultipleCandidates, 6063 ExplicitConversions)) 6064 return ExprError(); 6065 6066 // We'll complain below about a non-integral condition type. 6067 break; 6068 } 6069 case 1: { 6070 // Apply this conversion. 6071 DeclAccessPair Found = ViableConversions[0]; 6072 if (recordConversion(*this, Loc, From, Converter, T, 6073 HadMultipleCandidates, Found)) 6074 return ExprError(); 6075 break; 6076 } 6077 default: 6078 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6079 ViableConversions); 6080 } 6081 } 6082 6083 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6084 } 6085 6086 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6087 /// an acceptable non-member overloaded operator for a call whose 6088 /// arguments have types T1 (and, if non-empty, T2). This routine 6089 /// implements the check in C++ [over.match.oper]p3b2 concerning 6090 /// enumeration types. 6091 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6092 FunctionDecl *Fn, 6093 ArrayRef<Expr *> Args) { 6094 QualType T1 = Args[0]->getType(); 6095 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6096 6097 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6098 return true; 6099 6100 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6101 return true; 6102 6103 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6104 if (Proto->getNumParams() < 1) 6105 return false; 6106 6107 if (T1->isEnumeralType()) { 6108 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6109 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6110 return true; 6111 } 6112 6113 if (Proto->getNumParams() < 2) 6114 return false; 6115 6116 if (!T2.isNull() && T2->isEnumeralType()) { 6117 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6118 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6119 return true; 6120 } 6121 6122 return false; 6123 } 6124 6125 /// AddOverloadCandidate - Adds the given function to the set of 6126 /// candidate functions, using the given function call arguments. If 6127 /// @p SuppressUserConversions, then don't allow user-defined 6128 /// conversions via constructors or conversion operators. 6129 /// 6130 /// \param PartialOverloading true if we are performing "partial" overloading 6131 /// based on an incomplete set of function arguments. This feature is used by 6132 /// code completion. 6133 void Sema::AddOverloadCandidate( 6134 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6135 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6136 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6137 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6138 OverloadCandidateParamOrder PO) { 6139 const FunctionProtoType *Proto 6140 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6141 assert(Proto && "Functions without a prototype cannot be overloaded"); 6142 assert(!Function->getDescribedFunctionTemplate() && 6143 "Use AddTemplateOverloadCandidate for function templates"); 6144 6145 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6146 if (!isa<CXXConstructorDecl>(Method)) { 6147 // If we get here, it's because we're calling a member function 6148 // that is named without a member access expression (e.g., 6149 // "this->f") that was either written explicitly or created 6150 // implicitly. This can happen with a qualified call to a member 6151 // function, e.g., X::f(). We use an empty type for the implied 6152 // object argument (C++ [over.call.func]p3), and the acting context 6153 // is irrelevant. 6154 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6155 Expr::Classification::makeSimpleLValue(), Args, 6156 CandidateSet, SuppressUserConversions, 6157 PartialOverloading, EarlyConversions, PO); 6158 return; 6159 } 6160 // We treat a constructor like a non-member function, since its object 6161 // argument doesn't participate in overload resolution. 6162 } 6163 6164 if (!CandidateSet.isNewCandidate(Function, PO)) 6165 return; 6166 6167 // C++11 [class.copy]p11: [DR1402] 6168 // A defaulted move constructor that is defined as deleted is ignored by 6169 // overload resolution. 6170 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6171 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6172 Constructor->isMoveConstructor()) 6173 return; 6174 6175 // Overload resolution is always an unevaluated context. 6176 EnterExpressionEvaluationContext Unevaluated( 6177 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6178 6179 // C++ [over.match.oper]p3: 6180 // if no operand has a class type, only those non-member functions in the 6181 // lookup set that have a first parameter of type T1 or "reference to 6182 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6183 // is a right operand) a second parameter of type T2 or "reference to 6184 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6185 // candidate functions. 6186 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6187 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6188 return; 6189 6190 // Add this candidate 6191 OverloadCandidate &Candidate = 6192 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6193 Candidate.FoundDecl = FoundDecl; 6194 Candidate.Function = Function; 6195 Candidate.Viable = true; 6196 Candidate.RewriteKind = 6197 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6198 Candidate.IsSurrogate = false; 6199 Candidate.IsADLCandidate = IsADLCandidate; 6200 Candidate.IgnoreObjectArgument = false; 6201 Candidate.ExplicitCallArguments = Args.size(); 6202 6203 // Explicit functions are not actually candidates at all if we're not 6204 // allowing them in this context, but keep them around so we can point 6205 // to them in diagnostics. 6206 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6207 Candidate.Viable = false; 6208 Candidate.FailureKind = ovl_fail_explicit; 6209 return; 6210 } 6211 6212 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6213 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6214 Candidate.Viable = false; 6215 Candidate.FailureKind = ovl_non_default_multiversion_function; 6216 return; 6217 } 6218 6219 if (Constructor) { 6220 // C++ [class.copy]p3: 6221 // A member function template is never instantiated to perform the copy 6222 // of a class object to an object of its class type. 6223 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6224 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6225 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6226 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6227 ClassType))) { 6228 Candidate.Viable = false; 6229 Candidate.FailureKind = ovl_fail_illegal_constructor; 6230 return; 6231 } 6232 6233 // C++ [over.match.funcs]p8: (proposed DR resolution) 6234 // A constructor inherited from class type C that has a first parameter 6235 // of type "reference to P" (including such a constructor instantiated 6236 // from a template) is excluded from the set of candidate functions when 6237 // constructing an object of type cv D if the argument list has exactly 6238 // one argument and D is reference-related to P and P is reference-related 6239 // to C. 6240 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6241 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6242 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6243 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6244 QualType C = Context.getRecordType(Constructor->getParent()); 6245 QualType D = Context.getRecordType(Shadow->getParent()); 6246 SourceLocation Loc = Args.front()->getExprLoc(); 6247 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6248 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6249 Candidate.Viable = false; 6250 Candidate.FailureKind = ovl_fail_inhctor_slice; 6251 return; 6252 } 6253 } 6254 6255 // Check that the constructor is capable of constructing an object in the 6256 // destination address space. 6257 if (!Qualifiers::isAddressSpaceSupersetOf( 6258 Constructor->getMethodQualifiers().getAddressSpace(), 6259 CandidateSet.getDestAS())) { 6260 Candidate.Viable = false; 6261 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6262 } 6263 } 6264 6265 unsigned NumParams = Proto->getNumParams(); 6266 6267 // (C++ 13.3.2p2): A candidate function having fewer than m 6268 // parameters is viable only if it has an ellipsis in its parameter 6269 // list (8.3.5). 6270 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6271 !Proto->isVariadic()) { 6272 Candidate.Viable = false; 6273 Candidate.FailureKind = ovl_fail_too_many_arguments; 6274 return; 6275 } 6276 6277 // (C++ 13.3.2p2): A candidate function having more than m parameters 6278 // is viable only if the (m+1)st parameter has a default argument 6279 // (8.3.6). For the purposes of overload resolution, the 6280 // parameter list is truncated on the right, so that there are 6281 // exactly m parameters. 6282 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6283 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6284 // Not enough arguments. 6285 Candidate.Viable = false; 6286 Candidate.FailureKind = ovl_fail_too_few_arguments; 6287 return; 6288 } 6289 6290 // (CUDA B.1): Check for invalid calls between targets. 6291 if (getLangOpts().CUDA) 6292 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6293 // Skip the check for callers that are implicit members, because in this 6294 // case we may not yet know what the member's target is; the target is 6295 // inferred for the member automatically, based on the bases and fields of 6296 // the class. 6297 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6298 Candidate.Viable = false; 6299 Candidate.FailureKind = ovl_fail_bad_target; 6300 return; 6301 } 6302 6303 if (Function->getTrailingRequiresClause()) { 6304 ConstraintSatisfaction Satisfaction; 6305 if (CheckFunctionConstraints(Function, Satisfaction) || 6306 !Satisfaction.IsSatisfied) { 6307 Candidate.Viable = false; 6308 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6309 return; 6310 } 6311 } 6312 6313 // Determine the implicit conversion sequences for each of the 6314 // arguments. 6315 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6316 unsigned ConvIdx = 6317 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6318 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6319 // We already formed a conversion sequence for this parameter during 6320 // template argument deduction. 6321 } else if (ArgIdx < NumParams) { 6322 // (C++ 13.3.2p3): for F to be a viable function, there shall 6323 // exist for each argument an implicit conversion sequence 6324 // (13.3.3.1) that converts that argument to the corresponding 6325 // parameter of F. 6326 QualType ParamType = Proto->getParamType(ArgIdx); 6327 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6328 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6329 /*InOverloadResolution=*/true, 6330 /*AllowObjCWritebackConversion=*/ 6331 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6332 if (Candidate.Conversions[ConvIdx].isBad()) { 6333 Candidate.Viable = false; 6334 Candidate.FailureKind = ovl_fail_bad_conversion; 6335 return; 6336 } 6337 } else { 6338 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6339 // argument for which there is no corresponding parameter is 6340 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6341 Candidate.Conversions[ConvIdx].setEllipsis(); 6342 } 6343 } 6344 6345 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6346 Candidate.Viable = false; 6347 Candidate.FailureKind = ovl_fail_enable_if; 6348 Candidate.DeductionFailure.Data = FailedAttr; 6349 return; 6350 } 6351 6352 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6353 Candidate.Viable = false; 6354 Candidate.FailureKind = ovl_fail_ext_disabled; 6355 return; 6356 } 6357 } 6358 6359 ObjCMethodDecl * 6360 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6361 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6362 if (Methods.size() <= 1) 6363 return nullptr; 6364 6365 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6366 bool Match = true; 6367 ObjCMethodDecl *Method = Methods[b]; 6368 unsigned NumNamedArgs = Sel.getNumArgs(); 6369 // Method might have more arguments than selector indicates. This is due 6370 // to addition of c-style arguments in method. 6371 if (Method->param_size() > NumNamedArgs) 6372 NumNamedArgs = Method->param_size(); 6373 if (Args.size() < NumNamedArgs) 6374 continue; 6375 6376 for (unsigned i = 0; i < NumNamedArgs; i++) { 6377 // We can't do any type-checking on a type-dependent argument. 6378 if (Args[i]->isTypeDependent()) { 6379 Match = false; 6380 break; 6381 } 6382 6383 ParmVarDecl *param = Method->parameters()[i]; 6384 Expr *argExpr = Args[i]; 6385 assert(argExpr && "SelectBestMethod(): missing expression"); 6386 6387 // Strip the unbridged-cast placeholder expression off unless it's 6388 // a consumed argument. 6389 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6390 !param->hasAttr<CFConsumedAttr>()) 6391 argExpr = stripARCUnbridgedCast(argExpr); 6392 6393 // If the parameter is __unknown_anytype, move on to the next method. 6394 if (param->getType() == Context.UnknownAnyTy) { 6395 Match = false; 6396 break; 6397 } 6398 6399 ImplicitConversionSequence ConversionState 6400 = TryCopyInitialization(*this, argExpr, param->getType(), 6401 /*SuppressUserConversions*/false, 6402 /*InOverloadResolution=*/true, 6403 /*AllowObjCWritebackConversion=*/ 6404 getLangOpts().ObjCAutoRefCount, 6405 /*AllowExplicit*/false); 6406 // This function looks for a reasonably-exact match, so we consider 6407 // incompatible pointer conversions to be a failure here. 6408 if (ConversionState.isBad() || 6409 (ConversionState.isStandard() && 6410 ConversionState.Standard.Second == 6411 ICK_Incompatible_Pointer_Conversion)) { 6412 Match = false; 6413 break; 6414 } 6415 } 6416 // Promote additional arguments to variadic methods. 6417 if (Match && Method->isVariadic()) { 6418 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6419 if (Args[i]->isTypeDependent()) { 6420 Match = false; 6421 break; 6422 } 6423 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6424 nullptr); 6425 if (Arg.isInvalid()) { 6426 Match = false; 6427 break; 6428 } 6429 } 6430 } else { 6431 // Check for extra arguments to non-variadic methods. 6432 if (Args.size() != NumNamedArgs) 6433 Match = false; 6434 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6435 // Special case when selectors have no argument. In this case, select 6436 // one with the most general result type of 'id'. 6437 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6438 QualType ReturnT = Methods[b]->getReturnType(); 6439 if (ReturnT->isObjCIdType()) 6440 return Methods[b]; 6441 } 6442 } 6443 } 6444 6445 if (Match) 6446 return Method; 6447 } 6448 return nullptr; 6449 } 6450 6451 static bool 6452 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6453 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6454 bool MissingImplicitThis, Expr *&ConvertedThis, 6455 SmallVectorImpl<Expr *> &ConvertedArgs) { 6456 if (ThisArg) { 6457 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6458 assert(!isa<CXXConstructorDecl>(Method) && 6459 "Shouldn't have `this` for ctors!"); 6460 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6461 ExprResult R = S.PerformObjectArgumentInitialization( 6462 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6463 if (R.isInvalid()) 6464 return false; 6465 ConvertedThis = R.get(); 6466 } else { 6467 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6468 (void)MD; 6469 assert((MissingImplicitThis || MD->isStatic() || 6470 isa<CXXConstructorDecl>(MD)) && 6471 "Expected `this` for non-ctor instance methods"); 6472 } 6473 ConvertedThis = nullptr; 6474 } 6475 6476 // Ignore any variadic arguments. Converting them is pointless, since the 6477 // user can't refer to them in the function condition. 6478 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6479 6480 // Convert the arguments. 6481 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6482 ExprResult R; 6483 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6484 S.Context, Function->getParamDecl(I)), 6485 SourceLocation(), Args[I]); 6486 6487 if (R.isInvalid()) 6488 return false; 6489 6490 ConvertedArgs.push_back(R.get()); 6491 } 6492 6493 if (Trap.hasErrorOccurred()) 6494 return false; 6495 6496 // Push default arguments if needed. 6497 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6498 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6499 ParmVarDecl *P = Function->getParamDecl(i); 6500 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6501 ? P->getUninstantiatedDefaultArg() 6502 : P->getDefaultArg(); 6503 // This can only happen in code completion, i.e. when PartialOverloading 6504 // is true. 6505 if (!DefArg) 6506 return false; 6507 ExprResult R = 6508 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6509 S.Context, Function->getParamDecl(i)), 6510 SourceLocation(), DefArg); 6511 if (R.isInvalid()) 6512 return false; 6513 ConvertedArgs.push_back(R.get()); 6514 } 6515 6516 if (Trap.hasErrorOccurred()) 6517 return false; 6518 } 6519 return true; 6520 } 6521 6522 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6523 bool MissingImplicitThis) { 6524 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6525 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6526 return nullptr; 6527 6528 SFINAETrap Trap(*this); 6529 SmallVector<Expr *, 16> ConvertedArgs; 6530 // FIXME: We should look into making enable_if late-parsed. 6531 Expr *DiscardedThis; 6532 if (!convertArgsForAvailabilityChecks( 6533 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6534 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6535 return *EnableIfAttrs.begin(); 6536 6537 for (auto *EIA : EnableIfAttrs) { 6538 APValue Result; 6539 // FIXME: This doesn't consider value-dependent cases, because doing so is 6540 // very difficult. Ideally, we should handle them more gracefully. 6541 if (EIA->getCond()->isValueDependent() || 6542 !EIA->getCond()->EvaluateWithSubstitution( 6543 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6544 return EIA; 6545 6546 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6547 return EIA; 6548 } 6549 return nullptr; 6550 } 6551 6552 template <typename CheckFn> 6553 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6554 bool ArgDependent, SourceLocation Loc, 6555 CheckFn &&IsSuccessful) { 6556 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6557 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6558 if (ArgDependent == DIA->getArgDependent()) 6559 Attrs.push_back(DIA); 6560 } 6561 6562 // Common case: No diagnose_if attributes, so we can quit early. 6563 if (Attrs.empty()) 6564 return false; 6565 6566 auto WarningBegin = std::stable_partition( 6567 Attrs.begin(), Attrs.end(), 6568 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6569 6570 // Note that diagnose_if attributes are late-parsed, so they appear in the 6571 // correct order (unlike enable_if attributes). 6572 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6573 IsSuccessful); 6574 if (ErrAttr != WarningBegin) { 6575 const DiagnoseIfAttr *DIA = *ErrAttr; 6576 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6577 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6578 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6579 return true; 6580 } 6581 6582 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6583 if (IsSuccessful(DIA)) { 6584 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6585 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6586 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6587 } 6588 6589 return false; 6590 } 6591 6592 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6593 const Expr *ThisArg, 6594 ArrayRef<const Expr *> Args, 6595 SourceLocation Loc) { 6596 return diagnoseDiagnoseIfAttrsWith( 6597 *this, Function, /*ArgDependent=*/true, Loc, 6598 [&](const DiagnoseIfAttr *DIA) { 6599 APValue Result; 6600 // It's sane to use the same Args for any redecl of this function, since 6601 // EvaluateWithSubstitution only cares about the position of each 6602 // argument in the arg list, not the ParmVarDecl* it maps to. 6603 if (!DIA->getCond()->EvaluateWithSubstitution( 6604 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6605 return false; 6606 return Result.isInt() && Result.getInt().getBoolValue(); 6607 }); 6608 } 6609 6610 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6611 SourceLocation Loc) { 6612 return diagnoseDiagnoseIfAttrsWith( 6613 *this, ND, /*ArgDependent=*/false, Loc, 6614 [&](const DiagnoseIfAttr *DIA) { 6615 bool Result; 6616 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6617 Result; 6618 }); 6619 } 6620 6621 /// Add all of the function declarations in the given function set to 6622 /// the overload candidate set. 6623 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6624 ArrayRef<Expr *> Args, 6625 OverloadCandidateSet &CandidateSet, 6626 TemplateArgumentListInfo *ExplicitTemplateArgs, 6627 bool SuppressUserConversions, 6628 bool PartialOverloading, 6629 bool FirstArgumentIsBase) { 6630 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6631 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6632 ArrayRef<Expr *> FunctionArgs = Args; 6633 6634 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6635 FunctionDecl *FD = 6636 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6637 6638 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6639 QualType ObjectType; 6640 Expr::Classification ObjectClassification; 6641 if (Args.size() > 0) { 6642 if (Expr *E = Args[0]) { 6643 // Use the explicit base to restrict the lookup: 6644 ObjectType = E->getType(); 6645 // Pointers in the object arguments are implicitly dereferenced, so we 6646 // always classify them as l-values. 6647 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6648 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6649 else 6650 ObjectClassification = E->Classify(Context); 6651 } // .. else there is an implicit base. 6652 FunctionArgs = Args.slice(1); 6653 } 6654 if (FunTmpl) { 6655 AddMethodTemplateCandidate( 6656 FunTmpl, F.getPair(), 6657 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6658 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6659 FunctionArgs, CandidateSet, SuppressUserConversions, 6660 PartialOverloading); 6661 } else { 6662 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6663 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6664 ObjectClassification, FunctionArgs, CandidateSet, 6665 SuppressUserConversions, PartialOverloading); 6666 } 6667 } else { 6668 // This branch handles both standalone functions and static methods. 6669 6670 // Slice the first argument (which is the base) when we access 6671 // static method as non-static. 6672 if (Args.size() > 0 && 6673 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6674 !isa<CXXConstructorDecl>(FD)))) { 6675 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6676 FunctionArgs = Args.slice(1); 6677 } 6678 if (FunTmpl) { 6679 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6680 ExplicitTemplateArgs, FunctionArgs, 6681 CandidateSet, SuppressUserConversions, 6682 PartialOverloading); 6683 } else { 6684 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6685 SuppressUserConversions, PartialOverloading); 6686 } 6687 } 6688 } 6689 } 6690 6691 /// AddMethodCandidate - Adds a named decl (which is some kind of 6692 /// method) as a method candidate to the given overload set. 6693 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6694 Expr::Classification ObjectClassification, 6695 ArrayRef<Expr *> Args, 6696 OverloadCandidateSet &CandidateSet, 6697 bool SuppressUserConversions, 6698 OverloadCandidateParamOrder PO) { 6699 NamedDecl *Decl = FoundDecl.getDecl(); 6700 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6701 6702 if (isa<UsingShadowDecl>(Decl)) 6703 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6704 6705 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6706 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6707 "Expected a member function template"); 6708 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6709 /*ExplicitArgs*/ nullptr, ObjectType, 6710 ObjectClassification, Args, CandidateSet, 6711 SuppressUserConversions, false, PO); 6712 } else { 6713 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6714 ObjectType, ObjectClassification, Args, CandidateSet, 6715 SuppressUserConversions, false, None, PO); 6716 } 6717 } 6718 6719 /// AddMethodCandidate - Adds the given C++ member function to the set 6720 /// of candidate functions, using the given function call arguments 6721 /// and the object argument (@c Object). For example, in a call 6722 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6723 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6724 /// allow user-defined conversions via constructors or conversion 6725 /// operators. 6726 void 6727 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6728 CXXRecordDecl *ActingContext, QualType ObjectType, 6729 Expr::Classification ObjectClassification, 6730 ArrayRef<Expr *> Args, 6731 OverloadCandidateSet &CandidateSet, 6732 bool SuppressUserConversions, 6733 bool PartialOverloading, 6734 ConversionSequenceList EarlyConversions, 6735 OverloadCandidateParamOrder PO) { 6736 const FunctionProtoType *Proto 6737 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6738 assert(Proto && "Methods without a prototype cannot be overloaded"); 6739 assert(!isa<CXXConstructorDecl>(Method) && 6740 "Use AddOverloadCandidate for constructors"); 6741 6742 if (!CandidateSet.isNewCandidate(Method, PO)) 6743 return; 6744 6745 // C++11 [class.copy]p23: [DR1402] 6746 // A defaulted move assignment operator that is defined as deleted is 6747 // ignored by overload resolution. 6748 if (Method->isDefaulted() && Method->isDeleted() && 6749 Method->isMoveAssignmentOperator()) 6750 return; 6751 6752 // Overload resolution is always an unevaluated context. 6753 EnterExpressionEvaluationContext Unevaluated( 6754 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6755 6756 // Add this candidate 6757 OverloadCandidate &Candidate = 6758 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6759 Candidate.FoundDecl = FoundDecl; 6760 Candidate.Function = Method; 6761 Candidate.RewriteKind = 6762 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6763 Candidate.IsSurrogate = false; 6764 Candidate.IgnoreObjectArgument = false; 6765 Candidate.ExplicitCallArguments = Args.size(); 6766 6767 unsigned NumParams = Proto->getNumParams(); 6768 6769 // (C++ 13.3.2p2): A candidate function having fewer than m 6770 // parameters is viable only if it has an ellipsis in its parameter 6771 // list (8.3.5). 6772 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6773 !Proto->isVariadic()) { 6774 Candidate.Viable = false; 6775 Candidate.FailureKind = ovl_fail_too_many_arguments; 6776 return; 6777 } 6778 6779 // (C++ 13.3.2p2): A candidate function having more than m parameters 6780 // is viable only if the (m+1)st parameter has a default argument 6781 // (8.3.6). For the purposes of overload resolution, the 6782 // parameter list is truncated on the right, so that there are 6783 // exactly m parameters. 6784 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6785 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6786 // Not enough arguments. 6787 Candidate.Viable = false; 6788 Candidate.FailureKind = ovl_fail_too_few_arguments; 6789 return; 6790 } 6791 6792 Candidate.Viable = true; 6793 6794 if (Method->isStatic() || ObjectType.isNull()) 6795 // The implicit object argument is ignored. 6796 Candidate.IgnoreObjectArgument = true; 6797 else { 6798 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6799 // Determine the implicit conversion sequence for the object 6800 // parameter. 6801 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6802 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6803 Method, ActingContext); 6804 if (Candidate.Conversions[ConvIdx].isBad()) { 6805 Candidate.Viable = false; 6806 Candidate.FailureKind = ovl_fail_bad_conversion; 6807 return; 6808 } 6809 } 6810 6811 // (CUDA B.1): Check for invalid calls between targets. 6812 if (getLangOpts().CUDA) 6813 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6814 if (!IsAllowedCUDACall(Caller, Method)) { 6815 Candidate.Viable = false; 6816 Candidate.FailureKind = ovl_fail_bad_target; 6817 return; 6818 } 6819 6820 if (Method->getTrailingRequiresClause()) { 6821 ConstraintSatisfaction Satisfaction; 6822 if (CheckFunctionConstraints(Method, Satisfaction) || 6823 !Satisfaction.IsSatisfied) { 6824 Candidate.Viable = false; 6825 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6826 return; 6827 } 6828 } 6829 6830 // Determine the implicit conversion sequences for each of the 6831 // arguments. 6832 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6833 unsigned ConvIdx = 6834 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6835 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6836 // We already formed a conversion sequence for this parameter during 6837 // template argument deduction. 6838 } else if (ArgIdx < NumParams) { 6839 // (C++ 13.3.2p3): for F to be a viable function, there shall 6840 // exist for each argument an implicit conversion sequence 6841 // (13.3.3.1) that converts that argument to the corresponding 6842 // parameter of F. 6843 QualType ParamType = Proto->getParamType(ArgIdx); 6844 Candidate.Conversions[ConvIdx] 6845 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6846 SuppressUserConversions, 6847 /*InOverloadResolution=*/true, 6848 /*AllowObjCWritebackConversion=*/ 6849 getLangOpts().ObjCAutoRefCount); 6850 if (Candidate.Conversions[ConvIdx].isBad()) { 6851 Candidate.Viable = false; 6852 Candidate.FailureKind = ovl_fail_bad_conversion; 6853 return; 6854 } 6855 } else { 6856 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6857 // argument for which there is no corresponding parameter is 6858 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6859 Candidate.Conversions[ConvIdx].setEllipsis(); 6860 } 6861 } 6862 6863 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6864 Candidate.Viable = false; 6865 Candidate.FailureKind = ovl_fail_enable_if; 6866 Candidate.DeductionFailure.Data = FailedAttr; 6867 return; 6868 } 6869 6870 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6871 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6872 Candidate.Viable = false; 6873 Candidate.FailureKind = ovl_non_default_multiversion_function; 6874 } 6875 } 6876 6877 /// Add a C++ member function template as a candidate to the candidate 6878 /// set, using template argument deduction to produce an appropriate member 6879 /// function template specialization. 6880 void Sema::AddMethodTemplateCandidate( 6881 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 6882 CXXRecordDecl *ActingContext, 6883 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 6884 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 6885 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6886 bool PartialOverloading, OverloadCandidateParamOrder PO) { 6887 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 6888 return; 6889 6890 // C++ [over.match.funcs]p7: 6891 // In each case where a candidate is a function template, candidate 6892 // function template specializations are generated using template argument 6893 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6894 // candidate functions in the usual way.113) A given name can refer to one 6895 // or more function templates and also to a set of overloaded non-template 6896 // functions. In such a case, the candidate functions generated from each 6897 // function template are combined with the set of non-template candidate 6898 // functions. 6899 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6900 FunctionDecl *Specialization = nullptr; 6901 ConversionSequenceList Conversions; 6902 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6903 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6904 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6905 return CheckNonDependentConversions( 6906 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6907 SuppressUserConversions, ActingContext, ObjectType, 6908 ObjectClassification, PO); 6909 })) { 6910 OverloadCandidate &Candidate = 6911 CandidateSet.addCandidate(Conversions.size(), Conversions); 6912 Candidate.FoundDecl = FoundDecl; 6913 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6914 Candidate.Viable = false; 6915 Candidate.RewriteKind = 6916 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6917 Candidate.IsSurrogate = false; 6918 Candidate.IgnoreObjectArgument = 6919 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6920 ObjectType.isNull(); 6921 Candidate.ExplicitCallArguments = Args.size(); 6922 if (Result == TDK_NonDependentConversionFailure) 6923 Candidate.FailureKind = ovl_fail_bad_conversion; 6924 else { 6925 Candidate.FailureKind = ovl_fail_bad_deduction; 6926 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6927 Info); 6928 } 6929 return; 6930 } 6931 6932 // Add the function template specialization produced by template argument 6933 // deduction as a candidate. 6934 assert(Specialization && "Missing member function template specialization?"); 6935 assert(isa<CXXMethodDecl>(Specialization) && 6936 "Specialization is not a member function?"); 6937 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6938 ActingContext, ObjectType, ObjectClassification, Args, 6939 CandidateSet, SuppressUserConversions, PartialOverloading, 6940 Conversions, PO); 6941 } 6942 6943 /// Determine whether a given function template has a simple explicit specifier 6944 /// or a non-value-dependent explicit-specification that evaluates to true. 6945 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 6946 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 6947 } 6948 6949 /// Add a C++ function template specialization as a candidate 6950 /// in the candidate set, using template argument deduction to produce 6951 /// an appropriate function template specialization. 6952 void Sema::AddTemplateOverloadCandidate( 6953 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6954 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6955 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6956 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 6957 OverloadCandidateParamOrder PO) { 6958 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 6959 return; 6960 6961 // If the function template has a non-dependent explicit specification, 6962 // exclude it now if appropriate; we are not permitted to perform deduction 6963 // and substitution in this case. 6964 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 6965 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6966 Candidate.FoundDecl = FoundDecl; 6967 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6968 Candidate.Viable = false; 6969 Candidate.FailureKind = ovl_fail_explicit; 6970 return; 6971 } 6972 6973 // C++ [over.match.funcs]p7: 6974 // In each case where a candidate is a function template, candidate 6975 // function template specializations are generated using template argument 6976 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6977 // candidate functions in the usual way.113) A given name can refer to one 6978 // or more function templates and also to a set of overloaded non-template 6979 // functions. In such a case, the candidate functions generated from each 6980 // function template are combined with the set of non-template candidate 6981 // functions. 6982 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6983 FunctionDecl *Specialization = nullptr; 6984 ConversionSequenceList Conversions; 6985 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6986 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6987 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6988 return CheckNonDependentConversions( 6989 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 6990 SuppressUserConversions, nullptr, QualType(), {}, PO); 6991 })) { 6992 OverloadCandidate &Candidate = 6993 CandidateSet.addCandidate(Conversions.size(), Conversions); 6994 Candidate.FoundDecl = FoundDecl; 6995 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6996 Candidate.Viable = false; 6997 Candidate.RewriteKind = 6998 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6999 Candidate.IsSurrogate = false; 7000 Candidate.IsADLCandidate = IsADLCandidate; 7001 // Ignore the object argument if there is one, since we don't have an object 7002 // type. 7003 Candidate.IgnoreObjectArgument = 7004 isa<CXXMethodDecl>(Candidate.Function) && 7005 !isa<CXXConstructorDecl>(Candidate.Function); 7006 Candidate.ExplicitCallArguments = Args.size(); 7007 if (Result == TDK_NonDependentConversionFailure) 7008 Candidate.FailureKind = ovl_fail_bad_conversion; 7009 else { 7010 Candidate.FailureKind = ovl_fail_bad_deduction; 7011 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7012 Info); 7013 } 7014 return; 7015 } 7016 7017 // Add the function template specialization produced by template argument 7018 // deduction as a candidate. 7019 assert(Specialization && "Missing function template specialization?"); 7020 AddOverloadCandidate( 7021 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7022 PartialOverloading, AllowExplicit, 7023 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7024 } 7025 7026 /// Check that implicit conversion sequences can be formed for each argument 7027 /// whose corresponding parameter has a non-dependent type, per DR1391's 7028 /// [temp.deduct.call]p10. 7029 bool Sema::CheckNonDependentConversions( 7030 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7031 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7032 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7033 CXXRecordDecl *ActingContext, QualType ObjectType, 7034 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7035 // FIXME: The cases in which we allow explicit conversions for constructor 7036 // arguments never consider calling a constructor template. It's not clear 7037 // that is correct. 7038 const bool AllowExplicit = false; 7039 7040 auto *FD = FunctionTemplate->getTemplatedDecl(); 7041 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7042 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7043 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7044 7045 Conversions = 7046 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7047 7048 // Overload resolution is always an unevaluated context. 7049 EnterExpressionEvaluationContext Unevaluated( 7050 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7051 7052 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7053 // require that, but this check should never result in a hard error, and 7054 // overload resolution is permitted to sidestep instantiations. 7055 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7056 !ObjectType.isNull()) { 7057 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7058 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7059 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7060 Method, ActingContext); 7061 if (Conversions[ConvIdx].isBad()) 7062 return true; 7063 } 7064 7065 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7066 ++I) { 7067 QualType ParamType = ParamTypes[I]; 7068 if (!ParamType->isDependentType()) { 7069 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7070 ? 0 7071 : (ThisConversions + I); 7072 Conversions[ConvIdx] 7073 = TryCopyInitialization(*this, Args[I], ParamType, 7074 SuppressUserConversions, 7075 /*InOverloadResolution=*/true, 7076 /*AllowObjCWritebackConversion=*/ 7077 getLangOpts().ObjCAutoRefCount, 7078 AllowExplicit); 7079 if (Conversions[ConvIdx].isBad()) 7080 return true; 7081 } 7082 } 7083 7084 return false; 7085 } 7086 7087 /// Determine whether this is an allowable conversion from the result 7088 /// of an explicit conversion operator to the expected type, per C++ 7089 /// [over.match.conv]p1 and [over.match.ref]p1. 7090 /// 7091 /// \param ConvType The return type of the conversion function. 7092 /// 7093 /// \param ToType The type we are converting to. 7094 /// 7095 /// \param AllowObjCPointerConversion Allow a conversion from one 7096 /// Objective-C pointer to another. 7097 /// 7098 /// \returns true if the conversion is allowable, false otherwise. 7099 static bool isAllowableExplicitConversion(Sema &S, 7100 QualType ConvType, QualType ToType, 7101 bool AllowObjCPointerConversion) { 7102 QualType ToNonRefType = ToType.getNonReferenceType(); 7103 7104 // Easy case: the types are the same. 7105 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7106 return true; 7107 7108 // Allow qualification conversions. 7109 bool ObjCLifetimeConversion; 7110 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7111 ObjCLifetimeConversion)) 7112 return true; 7113 7114 // If we're not allowed to consider Objective-C pointer conversions, 7115 // we're done. 7116 if (!AllowObjCPointerConversion) 7117 return false; 7118 7119 // Is this an Objective-C pointer conversion? 7120 bool IncompatibleObjC = false; 7121 QualType ConvertedType; 7122 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7123 IncompatibleObjC); 7124 } 7125 7126 /// AddConversionCandidate - Add a C++ conversion function as a 7127 /// candidate in the candidate set (C++ [over.match.conv], 7128 /// C++ [over.match.copy]). From is the expression we're converting from, 7129 /// and ToType is the type that we're eventually trying to convert to 7130 /// (which may or may not be the same type as the type that the 7131 /// conversion function produces). 7132 void Sema::AddConversionCandidate( 7133 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7134 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7135 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7136 bool AllowExplicit, bool AllowResultConversion) { 7137 assert(!Conversion->getDescribedFunctionTemplate() && 7138 "Conversion function templates use AddTemplateConversionCandidate"); 7139 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7140 if (!CandidateSet.isNewCandidate(Conversion)) 7141 return; 7142 7143 // If the conversion function has an undeduced return type, trigger its 7144 // deduction now. 7145 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7146 if (DeduceReturnType(Conversion, From->getExprLoc())) 7147 return; 7148 ConvType = Conversion->getConversionType().getNonReferenceType(); 7149 } 7150 7151 // If we don't allow any conversion of the result type, ignore conversion 7152 // functions that don't convert to exactly (possibly cv-qualified) T. 7153 if (!AllowResultConversion && 7154 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7155 return; 7156 7157 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7158 // operator is only a candidate if its return type is the target type or 7159 // can be converted to the target type with a qualification conversion. 7160 // 7161 // FIXME: Include such functions in the candidate list and explain why we 7162 // can't select them. 7163 if (Conversion->isExplicit() && 7164 !isAllowableExplicitConversion(*this, ConvType, ToType, 7165 AllowObjCConversionOnExplicit)) 7166 return; 7167 7168 // Overload resolution is always an unevaluated context. 7169 EnterExpressionEvaluationContext Unevaluated( 7170 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7171 7172 // Add this candidate 7173 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7174 Candidate.FoundDecl = FoundDecl; 7175 Candidate.Function = Conversion; 7176 Candidate.IsSurrogate = false; 7177 Candidate.IgnoreObjectArgument = false; 7178 Candidate.FinalConversion.setAsIdentityConversion(); 7179 Candidate.FinalConversion.setFromType(ConvType); 7180 Candidate.FinalConversion.setAllToTypes(ToType); 7181 Candidate.Viable = true; 7182 Candidate.ExplicitCallArguments = 1; 7183 7184 // Explicit functions are not actually candidates at all if we're not 7185 // allowing them in this context, but keep them around so we can point 7186 // to them in diagnostics. 7187 if (!AllowExplicit && Conversion->isExplicit()) { 7188 Candidate.Viable = false; 7189 Candidate.FailureKind = ovl_fail_explicit; 7190 return; 7191 } 7192 7193 // C++ [over.match.funcs]p4: 7194 // For conversion functions, the function is considered to be a member of 7195 // the class of the implicit implied object argument for the purpose of 7196 // defining the type of the implicit object parameter. 7197 // 7198 // Determine the implicit conversion sequence for the implicit 7199 // object parameter. 7200 QualType ImplicitParamType = From->getType(); 7201 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7202 ImplicitParamType = FromPtrType->getPointeeType(); 7203 CXXRecordDecl *ConversionContext 7204 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7205 7206 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7207 *this, CandidateSet.getLocation(), From->getType(), 7208 From->Classify(Context), Conversion, ConversionContext); 7209 7210 if (Candidate.Conversions[0].isBad()) { 7211 Candidate.Viable = false; 7212 Candidate.FailureKind = ovl_fail_bad_conversion; 7213 return; 7214 } 7215 7216 if (Conversion->getTrailingRequiresClause()) { 7217 ConstraintSatisfaction Satisfaction; 7218 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7219 !Satisfaction.IsSatisfied) { 7220 Candidate.Viable = false; 7221 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7222 return; 7223 } 7224 } 7225 7226 // We won't go through a user-defined type conversion function to convert a 7227 // derived to base as such conversions are given Conversion Rank. They only 7228 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7229 QualType FromCanon 7230 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7231 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7232 if (FromCanon == ToCanon || 7233 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7234 Candidate.Viable = false; 7235 Candidate.FailureKind = ovl_fail_trivial_conversion; 7236 return; 7237 } 7238 7239 // To determine what the conversion from the result of calling the 7240 // conversion function to the type we're eventually trying to 7241 // convert to (ToType), we need to synthesize a call to the 7242 // conversion function and attempt copy initialization from it. This 7243 // makes sure that we get the right semantics with respect to 7244 // lvalues/rvalues and the type. Fortunately, we can allocate this 7245 // call on the stack and we don't need its arguments to be 7246 // well-formed. 7247 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7248 VK_LValue, From->getBeginLoc()); 7249 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7250 Context.getPointerType(Conversion->getType()), 7251 CK_FunctionToPointerDecay, 7252 &ConversionRef, VK_RValue); 7253 7254 QualType ConversionType = Conversion->getConversionType(); 7255 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7256 Candidate.Viable = false; 7257 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7258 return; 7259 } 7260 7261 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7262 7263 // Note that it is safe to allocate CallExpr on the stack here because 7264 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7265 // allocator). 7266 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7267 7268 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7269 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7270 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7271 7272 ImplicitConversionSequence ICS = 7273 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7274 /*SuppressUserConversions=*/true, 7275 /*InOverloadResolution=*/false, 7276 /*AllowObjCWritebackConversion=*/false); 7277 7278 switch (ICS.getKind()) { 7279 case ImplicitConversionSequence::StandardConversion: 7280 Candidate.FinalConversion = ICS.Standard; 7281 7282 // C++ [over.ics.user]p3: 7283 // If the user-defined conversion is specified by a specialization of a 7284 // conversion function template, the second standard conversion sequence 7285 // shall have exact match rank. 7286 if (Conversion->getPrimaryTemplate() && 7287 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7288 Candidate.Viable = false; 7289 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7290 return; 7291 } 7292 7293 // C++0x [dcl.init.ref]p5: 7294 // In the second case, if the reference is an rvalue reference and 7295 // the second standard conversion sequence of the user-defined 7296 // conversion sequence includes an lvalue-to-rvalue conversion, the 7297 // program is ill-formed. 7298 if (ToType->isRValueReferenceType() && 7299 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7300 Candidate.Viable = false; 7301 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7302 return; 7303 } 7304 break; 7305 7306 case ImplicitConversionSequence::BadConversion: 7307 Candidate.Viable = false; 7308 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7309 return; 7310 7311 default: 7312 llvm_unreachable( 7313 "Can only end up with a standard conversion sequence or failure"); 7314 } 7315 7316 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7317 Candidate.Viable = false; 7318 Candidate.FailureKind = ovl_fail_enable_if; 7319 Candidate.DeductionFailure.Data = FailedAttr; 7320 return; 7321 } 7322 7323 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7324 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7325 Candidate.Viable = false; 7326 Candidate.FailureKind = ovl_non_default_multiversion_function; 7327 } 7328 } 7329 7330 /// Adds a conversion function template specialization 7331 /// candidate to the overload set, using template argument deduction 7332 /// to deduce the template arguments of the conversion function 7333 /// template from the type that we are converting to (C++ 7334 /// [temp.deduct.conv]). 7335 void Sema::AddTemplateConversionCandidate( 7336 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7337 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7338 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7339 bool AllowExplicit, bool AllowResultConversion) { 7340 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7341 "Only conversion function templates permitted here"); 7342 7343 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7344 return; 7345 7346 // If the function template has a non-dependent explicit specification, 7347 // exclude it now if appropriate; we are not permitted to perform deduction 7348 // and substitution in this case. 7349 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7350 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7351 Candidate.FoundDecl = FoundDecl; 7352 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7353 Candidate.Viable = false; 7354 Candidate.FailureKind = ovl_fail_explicit; 7355 return; 7356 } 7357 7358 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7359 CXXConversionDecl *Specialization = nullptr; 7360 if (TemplateDeductionResult Result 7361 = DeduceTemplateArguments(FunctionTemplate, ToType, 7362 Specialization, Info)) { 7363 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7364 Candidate.FoundDecl = FoundDecl; 7365 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7366 Candidate.Viable = false; 7367 Candidate.FailureKind = ovl_fail_bad_deduction; 7368 Candidate.IsSurrogate = false; 7369 Candidate.IgnoreObjectArgument = false; 7370 Candidate.ExplicitCallArguments = 1; 7371 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7372 Info); 7373 return; 7374 } 7375 7376 // Add the conversion function template specialization produced by 7377 // template argument deduction as a candidate. 7378 assert(Specialization && "Missing function template specialization?"); 7379 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7380 CandidateSet, AllowObjCConversionOnExplicit, 7381 AllowExplicit, AllowResultConversion); 7382 } 7383 7384 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7385 /// converts the given @c Object to a function pointer via the 7386 /// conversion function @c Conversion, and then attempts to call it 7387 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7388 /// the type of function that we'll eventually be calling. 7389 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7390 DeclAccessPair FoundDecl, 7391 CXXRecordDecl *ActingContext, 7392 const FunctionProtoType *Proto, 7393 Expr *Object, 7394 ArrayRef<Expr *> Args, 7395 OverloadCandidateSet& CandidateSet) { 7396 if (!CandidateSet.isNewCandidate(Conversion)) 7397 return; 7398 7399 // Overload resolution is always an unevaluated context. 7400 EnterExpressionEvaluationContext Unevaluated( 7401 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7402 7403 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7404 Candidate.FoundDecl = FoundDecl; 7405 Candidate.Function = nullptr; 7406 Candidate.Surrogate = Conversion; 7407 Candidate.Viable = true; 7408 Candidate.IsSurrogate = true; 7409 Candidate.IgnoreObjectArgument = false; 7410 Candidate.ExplicitCallArguments = Args.size(); 7411 7412 // Determine the implicit conversion sequence for the implicit 7413 // object parameter. 7414 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7415 *this, CandidateSet.getLocation(), Object->getType(), 7416 Object->Classify(Context), Conversion, ActingContext); 7417 if (ObjectInit.isBad()) { 7418 Candidate.Viable = false; 7419 Candidate.FailureKind = ovl_fail_bad_conversion; 7420 Candidate.Conversions[0] = ObjectInit; 7421 return; 7422 } 7423 7424 // The first conversion is actually a user-defined conversion whose 7425 // first conversion is ObjectInit's standard conversion (which is 7426 // effectively a reference binding). Record it as such. 7427 Candidate.Conversions[0].setUserDefined(); 7428 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7429 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7430 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7431 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7432 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7433 Candidate.Conversions[0].UserDefined.After 7434 = Candidate.Conversions[0].UserDefined.Before; 7435 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7436 7437 // Find the 7438 unsigned NumParams = Proto->getNumParams(); 7439 7440 // (C++ 13.3.2p2): A candidate function having fewer than m 7441 // parameters is viable only if it has an ellipsis in its parameter 7442 // list (8.3.5). 7443 if (Args.size() > NumParams && !Proto->isVariadic()) { 7444 Candidate.Viable = false; 7445 Candidate.FailureKind = ovl_fail_too_many_arguments; 7446 return; 7447 } 7448 7449 // Function types don't have any default arguments, so just check if 7450 // we have enough arguments. 7451 if (Args.size() < NumParams) { 7452 // Not enough arguments. 7453 Candidate.Viable = false; 7454 Candidate.FailureKind = ovl_fail_too_few_arguments; 7455 return; 7456 } 7457 7458 // Determine the implicit conversion sequences for each of the 7459 // arguments. 7460 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7461 if (ArgIdx < NumParams) { 7462 // (C++ 13.3.2p3): for F to be a viable function, there shall 7463 // exist for each argument an implicit conversion sequence 7464 // (13.3.3.1) that converts that argument to the corresponding 7465 // parameter of F. 7466 QualType ParamType = Proto->getParamType(ArgIdx); 7467 Candidate.Conversions[ArgIdx + 1] 7468 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7469 /*SuppressUserConversions=*/false, 7470 /*InOverloadResolution=*/false, 7471 /*AllowObjCWritebackConversion=*/ 7472 getLangOpts().ObjCAutoRefCount); 7473 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7474 Candidate.Viable = false; 7475 Candidate.FailureKind = ovl_fail_bad_conversion; 7476 return; 7477 } 7478 } else { 7479 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7480 // argument for which there is no corresponding parameter is 7481 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7482 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7483 } 7484 } 7485 7486 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7487 Candidate.Viable = false; 7488 Candidate.FailureKind = ovl_fail_enable_if; 7489 Candidate.DeductionFailure.Data = FailedAttr; 7490 return; 7491 } 7492 } 7493 7494 /// Add all of the non-member operator function declarations in the given 7495 /// function set to the overload candidate set. 7496 void Sema::AddNonMemberOperatorCandidates( 7497 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7498 OverloadCandidateSet &CandidateSet, 7499 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7500 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7501 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7502 ArrayRef<Expr *> FunctionArgs = Args; 7503 7504 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7505 FunctionDecl *FD = 7506 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7507 7508 // Don't consider rewritten functions if we're not rewriting. 7509 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7510 continue; 7511 7512 assert(!isa<CXXMethodDecl>(FD) && 7513 "unqualified operator lookup found a member function"); 7514 7515 if (FunTmpl) { 7516 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7517 FunctionArgs, CandidateSet); 7518 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7519 AddTemplateOverloadCandidate( 7520 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7521 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7522 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7523 } else { 7524 if (ExplicitTemplateArgs) 7525 continue; 7526 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7527 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7528 AddOverloadCandidate(FD, F.getPair(), 7529 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7530 false, false, true, false, ADLCallKind::NotADL, 7531 None, OverloadCandidateParamOrder::Reversed); 7532 } 7533 } 7534 } 7535 7536 /// Add overload candidates for overloaded operators that are 7537 /// member functions. 7538 /// 7539 /// Add the overloaded operator candidates that are member functions 7540 /// for the operator Op that was used in an operator expression such 7541 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7542 /// CandidateSet will store the added overload candidates. (C++ 7543 /// [over.match.oper]). 7544 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7545 SourceLocation OpLoc, 7546 ArrayRef<Expr *> Args, 7547 OverloadCandidateSet &CandidateSet, 7548 OverloadCandidateParamOrder PO) { 7549 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7550 7551 // C++ [over.match.oper]p3: 7552 // For a unary operator @ with an operand of a type whose 7553 // cv-unqualified version is T1, and for a binary operator @ with 7554 // a left operand of a type whose cv-unqualified version is T1 and 7555 // a right operand of a type whose cv-unqualified version is T2, 7556 // three sets of candidate functions, designated member 7557 // candidates, non-member candidates and built-in candidates, are 7558 // constructed as follows: 7559 QualType T1 = Args[0]->getType(); 7560 7561 // -- If T1 is a complete class type or a class currently being 7562 // defined, the set of member candidates is the result of the 7563 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7564 // the set of member candidates is empty. 7565 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7566 // Complete the type if it can be completed. 7567 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7568 return; 7569 // If the type is neither complete nor being defined, bail out now. 7570 if (!T1Rec->getDecl()->getDefinition()) 7571 return; 7572 7573 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7574 LookupQualifiedName(Operators, T1Rec->getDecl()); 7575 Operators.suppressDiagnostics(); 7576 7577 for (LookupResult::iterator Oper = Operators.begin(), 7578 OperEnd = Operators.end(); 7579 Oper != OperEnd; 7580 ++Oper) 7581 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7582 Args[0]->Classify(Context), Args.slice(1), 7583 CandidateSet, /*SuppressUserConversion=*/false, PO); 7584 } 7585 } 7586 7587 /// AddBuiltinCandidate - Add a candidate for a built-in 7588 /// operator. ResultTy and ParamTys are the result and parameter types 7589 /// of the built-in candidate, respectively. Args and NumArgs are the 7590 /// arguments being passed to the candidate. IsAssignmentOperator 7591 /// should be true when this built-in candidate is an assignment 7592 /// operator. NumContextualBoolArguments is the number of arguments 7593 /// (at the beginning of the argument list) that will be contextually 7594 /// converted to bool. 7595 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7596 OverloadCandidateSet& CandidateSet, 7597 bool IsAssignmentOperator, 7598 unsigned NumContextualBoolArguments) { 7599 // Overload resolution is always an unevaluated context. 7600 EnterExpressionEvaluationContext Unevaluated( 7601 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7602 7603 // Add this candidate 7604 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7605 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7606 Candidate.Function = nullptr; 7607 Candidate.IsSurrogate = false; 7608 Candidate.IgnoreObjectArgument = false; 7609 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7610 7611 // Determine the implicit conversion sequences for each of the 7612 // arguments. 7613 Candidate.Viable = true; 7614 Candidate.ExplicitCallArguments = Args.size(); 7615 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7616 // C++ [over.match.oper]p4: 7617 // For the built-in assignment operators, conversions of the 7618 // left operand are restricted as follows: 7619 // -- no temporaries are introduced to hold the left operand, and 7620 // -- no user-defined conversions are applied to the left 7621 // operand to achieve a type match with the left-most 7622 // parameter of a built-in candidate. 7623 // 7624 // We block these conversions by turning off user-defined 7625 // conversions, since that is the only way that initialization of 7626 // a reference to a non-class type can occur from something that 7627 // is not of the same type. 7628 if (ArgIdx < NumContextualBoolArguments) { 7629 assert(ParamTys[ArgIdx] == Context.BoolTy && 7630 "Contextual conversion to bool requires bool type"); 7631 Candidate.Conversions[ArgIdx] 7632 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7633 } else { 7634 Candidate.Conversions[ArgIdx] 7635 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7636 ArgIdx == 0 && IsAssignmentOperator, 7637 /*InOverloadResolution=*/false, 7638 /*AllowObjCWritebackConversion=*/ 7639 getLangOpts().ObjCAutoRefCount); 7640 } 7641 if (Candidate.Conversions[ArgIdx].isBad()) { 7642 Candidate.Viable = false; 7643 Candidate.FailureKind = ovl_fail_bad_conversion; 7644 break; 7645 } 7646 } 7647 } 7648 7649 namespace { 7650 7651 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7652 /// candidate operator functions for built-in operators (C++ 7653 /// [over.built]). The types are separated into pointer types and 7654 /// enumeration types. 7655 class BuiltinCandidateTypeSet { 7656 /// TypeSet - A set of types. 7657 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7658 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7659 7660 /// PointerTypes - The set of pointer types that will be used in the 7661 /// built-in candidates. 7662 TypeSet PointerTypes; 7663 7664 /// MemberPointerTypes - The set of member pointer types that will be 7665 /// used in the built-in candidates. 7666 TypeSet MemberPointerTypes; 7667 7668 /// EnumerationTypes - The set of enumeration types that will be 7669 /// used in the built-in candidates. 7670 TypeSet EnumerationTypes; 7671 7672 /// The set of vector types that will be used in the built-in 7673 /// candidates. 7674 TypeSet VectorTypes; 7675 7676 /// A flag indicating non-record types are viable candidates 7677 bool HasNonRecordTypes; 7678 7679 /// A flag indicating whether either arithmetic or enumeration types 7680 /// were present in the candidate set. 7681 bool HasArithmeticOrEnumeralTypes; 7682 7683 /// A flag indicating whether the nullptr type was present in the 7684 /// candidate set. 7685 bool HasNullPtrType; 7686 7687 /// Sema - The semantic analysis instance where we are building the 7688 /// candidate type set. 7689 Sema &SemaRef; 7690 7691 /// Context - The AST context in which we will build the type sets. 7692 ASTContext &Context; 7693 7694 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7695 const Qualifiers &VisibleQuals); 7696 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7697 7698 public: 7699 /// iterator - Iterates through the types that are part of the set. 7700 typedef TypeSet::iterator iterator; 7701 7702 BuiltinCandidateTypeSet(Sema &SemaRef) 7703 : HasNonRecordTypes(false), 7704 HasArithmeticOrEnumeralTypes(false), 7705 HasNullPtrType(false), 7706 SemaRef(SemaRef), 7707 Context(SemaRef.Context) { } 7708 7709 void AddTypesConvertedFrom(QualType Ty, 7710 SourceLocation Loc, 7711 bool AllowUserConversions, 7712 bool AllowExplicitConversions, 7713 const Qualifiers &VisibleTypeConversionsQuals); 7714 7715 /// pointer_begin - First pointer type found; 7716 iterator pointer_begin() { return PointerTypes.begin(); } 7717 7718 /// pointer_end - Past the last pointer type found; 7719 iterator pointer_end() { return PointerTypes.end(); } 7720 7721 /// member_pointer_begin - First member pointer type found; 7722 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7723 7724 /// member_pointer_end - Past the last member pointer type found; 7725 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7726 7727 /// enumeration_begin - First enumeration type found; 7728 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7729 7730 /// enumeration_end - Past the last enumeration type found; 7731 iterator enumeration_end() { return EnumerationTypes.end(); } 7732 7733 iterator vector_begin() { return VectorTypes.begin(); } 7734 iterator vector_end() { return VectorTypes.end(); } 7735 7736 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7737 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7738 bool hasNullPtrType() const { return HasNullPtrType; } 7739 }; 7740 7741 } // end anonymous namespace 7742 7743 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7744 /// the set of pointer types along with any more-qualified variants of 7745 /// that type. For example, if @p Ty is "int const *", this routine 7746 /// will add "int const *", "int const volatile *", "int const 7747 /// restrict *", and "int const volatile restrict *" to the set of 7748 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7749 /// false otherwise. 7750 /// 7751 /// FIXME: what to do about extended qualifiers? 7752 bool 7753 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7754 const Qualifiers &VisibleQuals) { 7755 7756 // Insert this type. 7757 if (!PointerTypes.insert(Ty)) 7758 return false; 7759 7760 QualType PointeeTy; 7761 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7762 bool buildObjCPtr = false; 7763 if (!PointerTy) { 7764 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7765 PointeeTy = PTy->getPointeeType(); 7766 buildObjCPtr = true; 7767 } else { 7768 PointeeTy = PointerTy->getPointeeType(); 7769 } 7770 7771 // Don't add qualified variants of arrays. For one, they're not allowed 7772 // (the qualifier would sink to the element type), and for another, the 7773 // only overload situation where it matters is subscript or pointer +- int, 7774 // and those shouldn't have qualifier variants anyway. 7775 if (PointeeTy->isArrayType()) 7776 return true; 7777 7778 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7779 bool hasVolatile = VisibleQuals.hasVolatile(); 7780 bool hasRestrict = VisibleQuals.hasRestrict(); 7781 7782 // Iterate through all strict supersets of BaseCVR. 7783 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7784 if ((CVR | BaseCVR) != CVR) continue; 7785 // Skip over volatile if no volatile found anywhere in the types. 7786 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7787 7788 // Skip over restrict if no restrict found anywhere in the types, or if 7789 // the type cannot be restrict-qualified. 7790 if ((CVR & Qualifiers::Restrict) && 7791 (!hasRestrict || 7792 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7793 continue; 7794 7795 // Build qualified pointee type. 7796 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7797 7798 // Build qualified pointer type. 7799 QualType QPointerTy; 7800 if (!buildObjCPtr) 7801 QPointerTy = Context.getPointerType(QPointeeTy); 7802 else 7803 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7804 7805 // Insert qualified pointer type. 7806 PointerTypes.insert(QPointerTy); 7807 } 7808 7809 return true; 7810 } 7811 7812 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7813 /// to the set of pointer types along with any more-qualified variants of 7814 /// that type. For example, if @p Ty is "int const *", this routine 7815 /// will add "int const *", "int const volatile *", "int const 7816 /// restrict *", and "int const volatile restrict *" to the set of 7817 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7818 /// false otherwise. 7819 /// 7820 /// FIXME: what to do about extended qualifiers? 7821 bool 7822 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7823 QualType Ty) { 7824 // Insert this type. 7825 if (!MemberPointerTypes.insert(Ty)) 7826 return false; 7827 7828 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7829 assert(PointerTy && "type was not a member pointer type!"); 7830 7831 QualType PointeeTy = PointerTy->getPointeeType(); 7832 // Don't add qualified variants of arrays. For one, they're not allowed 7833 // (the qualifier would sink to the element type), and for another, the 7834 // only overload situation where it matters is subscript or pointer +- int, 7835 // and those shouldn't have qualifier variants anyway. 7836 if (PointeeTy->isArrayType()) 7837 return true; 7838 const Type *ClassTy = PointerTy->getClass(); 7839 7840 // Iterate through all strict supersets of the pointee type's CVR 7841 // qualifiers. 7842 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7843 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7844 if ((CVR | BaseCVR) != CVR) continue; 7845 7846 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7847 MemberPointerTypes.insert( 7848 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7849 } 7850 7851 return true; 7852 } 7853 7854 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7855 /// Ty can be implicit converted to the given set of @p Types. We're 7856 /// primarily interested in pointer types and enumeration types. We also 7857 /// take member pointer types, for the conditional operator. 7858 /// AllowUserConversions is true if we should look at the conversion 7859 /// functions of a class type, and AllowExplicitConversions if we 7860 /// should also include the explicit conversion functions of a class 7861 /// type. 7862 void 7863 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7864 SourceLocation Loc, 7865 bool AllowUserConversions, 7866 bool AllowExplicitConversions, 7867 const Qualifiers &VisibleQuals) { 7868 // Only deal with canonical types. 7869 Ty = Context.getCanonicalType(Ty); 7870 7871 // Look through reference types; they aren't part of the type of an 7872 // expression for the purposes of conversions. 7873 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7874 Ty = RefTy->getPointeeType(); 7875 7876 // If we're dealing with an array type, decay to the pointer. 7877 if (Ty->isArrayType()) 7878 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7879 7880 // Otherwise, we don't care about qualifiers on the type. 7881 Ty = Ty.getLocalUnqualifiedType(); 7882 7883 // Flag if we ever add a non-record type. 7884 const RecordType *TyRec = Ty->getAs<RecordType>(); 7885 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7886 7887 // Flag if we encounter an arithmetic type. 7888 HasArithmeticOrEnumeralTypes = 7889 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7890 7891 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7892 PointerTypes.insert(Ty); 7893 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7894 // Insert our type, and its more-qualified variants, into the set 7895 // of types. 7896 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7897 return; 7898 } else if (Ty->isMemberPointerType()) { 7899 // Member pointers are far easier, since the pointee can't be converted. 7900 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7901 return; 7902 } else if (Ty->isEnumeralType()) { 7903 HasArithmeticOrEnumeralTypes = true; 7904 EnumerationTypes.insert(Ty); 7905 } else if (Ty->isVectorType()) { 7906 // We treat vector types as arithmetic types in many contexts as an 7907 // extension. 7908 HasArithmeticOrEnumeralTypes = true; 7909 VectorTypes.insert(Ty); 7910 } else if (Ty->isNullPtrType()) { 7911 HasNullPtrType = true; 7912 } else if (AllowUserConversions && TyRec) { 7913 // No conversion functions in incomplete types. 7914 if (!SemaRef.isCompleteType(Loc, Ty)) 7915 return; 7916 7917 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7918 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7919 if (isa<UsingShadowDecl>(D)) 7920 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7921 7922 // Skip conversion function templates; they don't tell us anything 7923 // about which builtin types we can convert to. 7924 if (isa<FunctionTemplateDecl>(D)) 7925 continue; 7926 7927 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7928 if (AllowExplicitConversions || !Conv->isExplicit()) { 7929 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7930 VisibleQuals); 7931 } 7932 } 7933 } 7934 } 7935 /// Helper function for adjusting address spaces for the pointer or reference 7936 /// operands of builtin operators depending on the argument. 7937 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7938 Expr *Arg) { 7939 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7940 } 7941 7942 /// Helper function for AddBuiltinOperatorCandidates() that adds 7943 /// the volatile- and non-volatile-qualified assignment operators for the 7944 /// given type to the candidate set. 7945 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7946 QualType T, 7947 ArrayRef<Expr *> Args, 7948 OverloadCandidateSet &CandidateSet) { 7949 QualType ParamTypes[2]; 7950 7951 // T& operator=(T&, T) 7952 ParamTypes[0] = S.Context.getLValueReferenceType( 7953 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7954 ParamTypes[1] = T; 7955 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7956 /*IsAssignmentOperator=*/true); 7957 7958 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7959 // volatile T& operator=(volatile T&, T) 7960 ParamTypes[0] = S.Context.getLValueReferenceType( 7961 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7962 Args[0])); 7963 ParamTypes[1] = T; 7964 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7965 /*IsAssignmentOperator=*/true); 7966 } 7967 } 7968 7969 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7970 /// if any, found in visible type conversion functions found in ArgExpr's type. 7971 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7972 Qualifiers VRQuals; 7973 const RecordType *TyRec; 7974 if (const MemberPointerType *RHSMPType = 7975 ArgExpr->getType()->getAs<MemberPointerType>()) 7976 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7977 else 7978 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7979 if (!TyRec) { 7980 // Just to be safe, assume the worst case. 7981 VRQuals.addVolatile(); 7982 VRQuals.addRestrict(); 7983 return VRQuals; 7984 } 7985 7986 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7987 if (!ClassDecl->hasDefinition()) 7988 return VRQuals; 7989 7990 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7991 if (isa<UsingShadowDecl>(D)) 7992 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7993 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7994 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7995 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7996 CanTy = ResTypeRef->getPointeeType(); 7997 // Need to go down the pointer/mempointer chain and add qualifiers 7998 // as see them. 7999 bool done = false; 8000 while (!done) { 8001 if (CanTy.isRestrictQualified()) 8002 VRQuals.addRestrict(); 8003 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8004 CanTy = ResTypePtr->getPointeeType(); 8005 else if (const MemberPointerType *ResTypeMPtr = 8006 CanTy->getAs<MemberPointerType>()) 8007 CanTy = ResTypeMPtr->getPointeeType(); 8008 else 8009 done = true; 8010 if (CanTy.isVolatileQualified()) 8011 VRQuals.addVolatile(); 8012 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8013 return VRQuals; 8014 } 8015 } 8016 } 8017 return VRQuals; 8018 } 8019 8020 namespace { 8021 8022 /// Helper class to manage the addition of builtin operator overload 8023 /// candidates. It provides shared state and utility methods used throughout 8024 /// the process, as well as a helper method to add each group of builtin 8025 /// operator overloads from the standard to a candidate set. 8026 class BuiltinOperatorOverloadBuilder { 8027 // Common instance state available to all overload candidate addition methods. 8028 Sema &S; 8029 ArrayRef<Expr *> Args; 8030 Qualifiers VisibleTypeConversionsQuals; 8031 bool HasArithmeticOrEnumeralCandidateType; 8032 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8033 OverloadCandidateSet &CandidateSet; 8034 8035 static constexpr int ArithmeticTypesCap = 24; 8036 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8037 8038 // Define some indices used to iterate over the arithmetic types in 8039 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8040 // types are that preserved by promotion (C++ [over.built]p2). 8041 unsigned FirstIntegralType, 8042 LastIntegralType; 8043 unsigned FirstPromotedIntegralType, 8044 LastPromotedIntegralType; 8045 unsigned FirstPromotedArithmeticType, 8046 LastPromotedArithmeticType; 8047 unsigned NumArithmeticTypes; 8048 8049 void InitArithmeticTypes() { 8050 // Start of promoted types. 8051 FirstPromotedArithmeticType = 0; 8052 ArithmeticTypes.push_back(S.Context.FloatTy); 8053 ArithmeticTypes.push_back(S.Context.DoubleTy); 8054 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8055 if (S.Context.getTargetInfo().hasFloat128Type()) 8056 ArithmeticTypes.push_back(S.Context.Float128Ty); 8057 8058 // Start of integral types. 8059 FirstIntegralType = ArithmeticTypes.size(); 8060 FirstPromotedIntegralType = ArithmeticTypes.size(); 8061 ArithmeticTypes.push_back(S.Context.IntTy); 8062 ArithmeticTypes.push_back(S.Context.LongTy); 8063 ArithmeticTypes.push_back(S.Context.LongLongTy); 8064 if (S.Context.getTargetInfo().hasInt128Type()) 8065 ArithmeticTypes.push_back(S.Context.Int128Ty); 8066 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8067 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8068 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8069 if (S.Context.getTargetInfo().hasInt128Type()) 8070 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8071 LastPromotedIntegralType = ArithmeticTypes.size(); 8072 LastPromotedArithmeticType = ArithmeticTypes.size(); 8073 // End of promoted types. 8074 8075 ArithmeticTypes.push_back(S.Context.BoolTy); 8076 ArithmeticTypes.push_back(S.Context.CharTy); 8077 ArithmeticTypes.push_back(S.Context.WCharTy); 8078 if (S.Context.getLangOpts().Char8) 8079 ArithmeticTypes.push_back(S.Context.Char8Ty); 8080 ArithmeticTypes.push_back(S.Context.Char16Ty); 8081 ArithmeticTypes.push_back(S.Context.Char32Ty); 8082 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8083 ArithmeticTypes.push_back(S.Context.ShortTy); 8084 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8085 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8086 LastIntegralType = ArithmeticTypes.size(); 8087 NumArithmeticTypes = ArithmeticTypes.size(); 8088 // End of integral types. 8089 // FIXME: What about complex? What about half? 8090 8091 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8092 "Enough inline storage for all arithmetic types."); 8093 } 8094 8095 /// Helper method to factor out the common pattern of adding overloads 8096 /// for '++' and '--' builtin operators. 8097 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8098 bool HasVolatile, 8099 bool HasRestrict) { 8100 QualType ParamTypes[2] = { 8101 S.Context.getLValueReferenceType(CandidateTy), 8102 S.Context.IntTy 8103 }; 8104 8105 // Non-volatile version. 8106 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8107 8108 // Use a heuristic to reduce number of builtin candidates in the set: 8109 // add volatile version only if there are conversions to a volatile type. 8110 if (HasVolatile) { 8111 ParamTypes[0] = 8112 S.Context.getLValueReferenceType( 8113 S.Context.getVolatileType(CandidateTy)); 8114 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8115 } 8116 8117 // Add restrict version only if there are conversions to a restrict type 8118 // and our candidate type is a non-restrict-qualified pointer. 8119 if (HasRestrict && CandidateTy->isAnyPointerType() && 8120 !CandidateTy.isRestrictQualified()) { 8121 ParamTypes[0] 8122 = S.Context.getLValueReferenceType( 8123 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8124 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8125 8126 if (HasVolatile) { 8127 ParamTypes[0] 8128 = S.Context.getLValueReferenceType( 8129 S.Context.getCVRQualifiedType(CandidateTy, 8130 (Qualifiers::Volatile | 8131 Qualifiers::Restrict))); 8132 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8133 } 8134 } 8135 8136 } 8137 8138 public: 8139 BuiltinOperatorOverloadBuilder( 8140 Sema &S, ArrayRef<Expr *> Args, 8141 Qualifiers VisibleTypeConversionsQuals, 8142 bool HasArithmeticOrEnumeralCandidateType, 8143 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8144 OverloadCandidateSet &CandidateSet) 8145 : S(S), Args(Args), 8146 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8147 HasArithmeticOrEnumeralCandidateType( 8148 HasArithmeticOrEnumeralCandidateType), 8149 CandidateTypes(CandidateTypes), 8150 CandidateSet(CandidateSet) { 8151 8152 InitArithmeticTypes(); 8153 } 8154 8155 // Increment is deprecated for bool since C++17. 8156 // 8157 // C++ [over.built]p3: 8158 // 8159 // For every pair (T, VQ), where T is an arithmetic type other 8160 // than bool, and VQ is either volatile or empty, there exist 8161 // candidate operator functions of the form 8162 // 8163 // VQ T& operator++(VQ T&); 8164 // T operator++(VQ T&, int); 8165 // 8166 // C++ [over.built]p4: 8167 // 8168 // For every pair (T, VQ), where T is an arithmetic type other 8169 // than bool, and VQ is either volatile or empty, there exist 8170 // candidate operator functions of the form 8171 // 8172 // VQ T& operator--(VQ T&); 8173 // T operator--(VQ T&, int); 8174 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8175 if (!HasArithmeticOrEnumeralCandidateType) 8176 return; 8177 8178 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8179 const auto TypeOfT = ArithmeticTypes[Arith]; 8180 if (TypeOfT == S.Context.BoolTy) { 8181 if (Op == OO_MinusMinus) 8182 continue; 8183 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8184 continue; 8185 } 8186 addPlusPlusMinusMinusStyleOverloads( 8187 TypeOfT, 8188 VisibleTypeConversionsQuals.hasVolatile(), 8189 VisibleTypeConversionsQuals.hasRestrict()); 8190 } 8191 } 8192 8193 // C++ [over.built]p5: 8194 // 8195 // For every pair (T, VQ), where T is a cv-qualified or 8196 // cv-unqualified object type, and VQ is either volatile or 8197 // empty, there exist candidate operator functions of the form 8198 // 8199 // T*VQ& operator++(T*VQ&); 8200 // T*VQ& operator--(T*VQ&); 8201 // T* operator++(T*VQ&, int); 8202 // T* operator--(T*VQ&, int); 8203 void addPlusPlusMinusMinusPointerOverloads() { 8204 for (BuiltinCandidateTypeSet::iterator 8205 Ptr = CandidateTypes[0].pointer_begin(), 8206 PtrEnd = CandidateTypes[0].pointer_end(); 8207 Ptr != PtrEnd; ++Ptr) { 8208 // Skip pointer types that aren't pointers to object types. 8209 if (!(*Ptr)->getPointeeType()->isObjectType()) 8210 continue; 8211 8212 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8213 (!(*Ptr).isVolatileQualified() && 8214 VisibleTypeConversionsQuals.hasVolatile()), 8215 (!(*Ptr).isRestrictQualified() && 8216 VisibleTypeConversionsQuals.hasRestrict())); 8217 } 8218 } 8219 8220 // C++ [over.built]p6: 8221 // For every cv-qualified or cv-unqualified object type T, there 8222 // exist candidate operator functions of the form 8223 // 8224 // T& operator*(T*); 8225 // 8226 // C++ [over.built]p7: 8227 // For every function type T that does not have cv-qualifiers or a 8228 // ref-qualifier, there exist candidate operator functions of the form 8229 // T& operator*(T*); 8230 void addUnaryStarPointerOverloads() { 8231 for (BuiltinCandidateTypeSet::iterator 8232 Ptr = CandidateTypes[0].pointer_begin(), 8233 PtrEnd = CandidateTypes[0].pointer_end(); 8234 Ptr != PtrEnd; ++Ptr) { 8235 QualType ParamTy = *Ptr; 8236 QualType PointeeTy = ParamTy->getPointeeType(); 8237 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8238 continue; 8239 8240 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8241 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8242 continue; 8243 8244 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8245 } 8246 } 8247 8248 // C++ [over.built]p9: 8249 // For every promoted arithmetic type T, there exist candidate 8250 // operator functions of the form 8251 // 8252 // T operator+(T); 8253 // T operator-(T); 8254 void addUnaryPlusOrMinusArithmeticOverloads() { 8255 if (!HasArithmeticOrEnumeralCandidateType) 8256 return; 8257 8258 for (unsigned Arith = FirstPromotedArithmeticType; 8259 Arith < LastPromotedArithmeticType; ++Arith) { 8260 QualType ArithTy = ArithmeticTypes[Arith]; 8261 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8262 } 8263 8264 // Extension: We also add these operators for vector types. 8265 for (BuiltinCandidateTypeSet::iterator 8266 Vec = CandidateTypes[0].vector_begin(), 8267 VecEnd = CandidateTypes[0].vector_end(); 8268 Vec != VecEnd; ++Vec) { 8269 QualType VecTy = *Vec; 8270 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8271 } 8272 } 8273 8274 // C++ [over.built]p8: 8275 // For every type T, there exist candidate operator functions of 8276 // the form 8277 // 8278 // T* operator+(T*); 8279 void addUnaryPlusPointerOverloads() { 8280 for (BuiltinCandidateTypeSet::iterator 8281 Ptr = CandidateTypes[0].pointer_begin(), 8282 PtrEnd = CandidateTypes[0].pointer_end(); 8283 Ptr != PtrEnd; ++Ptr) { 8284 QualType ParamTy = *Ptr; 8285 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8286 } 8287 } 8288 8289 // C++ [over.built]p10: 8290 // For every promoted integral type T, there exist candidate 8291 // operator functions of the form 8292 // 8293 // T operator~(T); 8294 void addUnaryTildePromotedIntegralOverloads() { 8295 if (!HasArithmeticOrEnumeralCandidateType) 8296 return; 8297 8298 for (unsigned Int = FirstPromotedIntegralType; 8299 Int < LastPromotedIntegralType; ++Int) { 8300 QualType IntTy = ArithmeticTypes[Int]; 8301 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8302 } 8303 8304 // Extension: We also add this operator for vector types. 8305 for (BuiltinCandidateTypeSet::iterator 8306 Vec = CandidateTypes[0].vector_begin(), 8307 VecEnd = CandidateTypes[0].vector_end(); 8308 Vec != VecEnd; ++Vec) { 8309 QualType VecTy = *Vec; 8310 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8311 } 8312 } 8313 8314 // C++ [over.match.oper]p16: 8315 // For every pointer to member type T or type std::nullptr_t, there 8316 // exist candidate operator functions of the form 8317 // 8318 // bool operator==(T,T); 8319 // bool operator!=(T,T); 8320 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8321 /// Set of (canonical) types that we've already handled. 8322 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8323 8324 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8325 for (BuiltinCandidateTypeSet::iterator 8326 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8327 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8328 MemPtr != MemPtrEnd; 8329 ++MemPtr) { 8330 // Don't add the same builtin candidate twice. 8331 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8332 continue; 8333 8334 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8335 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8336 } 8337 8338 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8339 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8340 if (AddedTypes.insert(NullPtrTy).second) { 8341 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8342 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8343 } 8344 } 8345 } 8346 } 8347 8348 // C++ [over.built]p15: 8349 // 8350 // For every T, where T is an enumeration type or a pointer type, 8351 // there exist candidate operator functions of the form 8352 // 8353 // bool operator<(T, T); 8354 // bool operator>(T, T); 8355 // bool operator<=(T, T); 8356 // bool operator>=(T, T); 8357 // bool operator==(T, T); 8358 // bool operator!=(T, T); 8359 // R operator<=>(T, T) 8360 void addGenericBinaryPointerOrEnumeralOverloads() { 8361 // C++ [over.match.oper]p3: 8362 // [...]the built-in candidates include all of the candidate operator 8363 // functions defined in 13.6 that, compared to the given operator, [...] 8364 // do not have the same parameter-type-list as any non-template non-member 8365 // candidate. 8366 // 8367 // Note that in practice, this only affects enumeration types because there 8368 // aren't any built-in candidates of record type, and a user-defined operator 8369 // must have an operand of record or enumeration type. Also, the only other 8370 // overloaded operator with enumeration arguments, operator=, 8371 // cannot be overloaded for enumeration types, so this is the only place 8372 // where we must suppress candidates like this. 8373 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8374 UserDefinedBinaryOperators; 8375 8376 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8377 if (CandidateTypes[ArgIdx].enumeration_begin() != 8378 CandidateTypes[ArgIdx].enumeration_end()) { 8379 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8380 CEnd = CandidateSet.end(); 8381 C != CEnd; ++C) { 8382 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8383 continue; 8384 8385 if (C->Function->isFunctionTemplateSpecialization()) 8386 continue; 8387 8388 // We interpret "same parameter-type-list" as applying to the 8389 // "synthesized candidate, with the order of the two parameters 8390 // reversed", not to the original function. 8391 bool Reversed = C->RewriteKind & CRK_Reversed; 8392 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8393 ->getType() 8394 .getUnqualifiedType(); 8395 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8396 ->getType() 8397 .getUnqualifiedType(); 8398 8399 // Skip if either parameter isn't of enumeral type. 8400 if (!FirstParamType->isEnumeralType() || 8401 !SecondParamType->isEnumeralType()) 8402 continue; 8403 8404 // Add this operator to the set of known user-defined operators. 8405 UserDefinedBinaryOperators.insert( 8406 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8407 S.Context.getCanonicalType(SecondParamType))); 8408 } 8409 } 8410 } 8411 8412 /// Set of (canonical) types that we've already handled. 8413 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8414 8415 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8416 for (BuiltinCandidateTypeSet::iterator 8417 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8418 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8419 Ptr != PtrEnd; ++Ptr) { 8420 // Don't add the same builtin candidate twice. 8421 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8422 continue; 8423 8424 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8425 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8426 } 8427 for (BuiltinCandidateTypeSet::iterator 8428 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8429 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8430 Enum != EnumEnd; ++Enum) { 8431 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8432 8433 // Don't add the same builtin candidate twice, or if a user defined 8434 // candidate exists. 8435 if (!AddedTypes.insert(CanonType).second || 8436 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8437 CanonType))) 8438 continue; 8439 QualType ParamTypes[2] = { *Enum, *Enum }; 8440 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8441 } 8442 } 8443 } 8444 8445 // C++ [over.built]p13: 8446 // 8447 // For every cv-qualified or cv-unqualified object type T 8448 // there exist candidate operator functions of the form 8449 // 8450 // T* operator+(T*, ptrdiff_t); 8451 // T& operator[](T*, ptrdiff_t); [BELOW] 8452 // T* operator-(T*, ptrdiff_t); 8453 // T* operator+(ptrdiff_t, T*); 8454 // T& operator[](ptrdiff_t, T*); [BELOW] 8455 // 8456 // C++ [over.built]p14: 8457 // 8458 // For every T, where T is a pointer to object type, there 8459 // exist candidate operator functions of the form 8460 // 8461 // ptrdiff_t operator-(T, T); 8462 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8463 /// Set of (canonical) types that we've already handled. 8464 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8465 8466 for (int Arg = 0; Arg < 2; ++Arg) { 8467 QualType AsymmetricParamTypes[2] = { 8468 S.Context.getPointerDiffType(), 8469 S.Context.getPointerDiffType(), 8470 }; 8471 for (BuiltinCandidateTypeSet::iterator 8472 Ptr = CandidateTypes[Arg].pointer_begin(), 8473 PtrEnd = CandidateTypes[Arg].pointer_end(); 8474 Ptr != PtrEnd; ++Ptr) { 8475 QualType PointeeTy = (*Ptr)->getPointeeType(); 8476 if (!PointeeTy->isObjectType()) 8477 continue; 8478 8479 AsymmetricParamTypes[Arg] = *Ptr; 8480 if (Arg == 0 || Op == OO_Plus) { 8481 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8482 // T* operator+(ptrdiff_t, T*); 8483 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8484 } 8485 if (Op == OO_Minus) { 8486 // ptrdiff_t operator-(T, T); 8487 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8488 continue; 8489 8490 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8491 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8492 } 8493 } 8494 } 8495 } 8496 8497 // C++ [over.built]p12: 8498 // 8499 // For every pair of promoted arithmetic types L and R, there 8500 // exist candidate operator functions of the form 8501 // 8502 // LR operator*(L, R); 8503 // LR operator/(L, R); 8504 // LR operator+(L, R); 8505 // LR operator-(L, R); 8506 // bool operator<(L, R); 8507 // bool operator>(L, R); 8508 // bool operator<=(L, R); 8509 // bool operator>=(L, R); 8510 // bool operator==(L, R); 8511 // bool operator!=(L, R); 8512 // 8513 // where LR is the result of the usual arithmetic conversions 8514 // between types L and R. 8515 // 8516 // C++ [over.built]p24: 8517 // 8518 // For every pair of promoted arithmetic types L and R, there exist 8519 // candidate operator functions of the form 8520 // 8521 // LR operator?(bool, L, R); 8522 // 8523 // where LR is the result of the usual arithmetic conversions 8524 // between types L and R. 8525 // Our candidates ignore the first parameter. 8526 void addGenericBinaryArithmeticOverloads() { 8527 if (!HasArithmeticOrEnumeralCandidateType) 8528 return; 8529 8530 for (unsigned Left = FirstPromotedArithmeticType; 8531 Left < LastPromotedArithmeticType; ++Left) { 8532 for (unsigned Right = FirstPromotedArithmeticType; 8533 Right < LastPromotedArithmeticType; ++Right) { 8534 QualType LandR[2] = { ArithmeticTypes[Left], 8535 ArithmeticTypes[Right] }; 8536 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8537 } 8538 } 8539 8540 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8541 // conditional operator for vector types. 8542 for (BuiltinCandidateTypeSet::iterator 8543 Vec1 = CandidateTypes[0].vector_begin(), 8544 Vec1End = CandidateTypes[0].vector_end(); 8545 Vec1 != Vec1End; ++Vec1) { 8546 for (BuiltinCandidateTypeSet::iterator 8547 Vec2 = CandidateTypes[1].vector_begin(), 8548 Vec2End = CandidateTypes[1].vector_end(); 8549 Vec2 != Vec2End; ++Vec2) { 8550 QualType LandR[2] = { *Vec1, *Vec2 }; 8551 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8552 } 8553 } 8554 } 8555 8556 // C++2a [over.built]p14: 8557 // 8558 // For every integral type T there exists a candidate operator function 8559 // of the form 8560 // 8561 // std::strong_ordering operator<=>(T, T) 8562 // 8563 // C++2a [over.built]p15: 8564 // 8565 // For every pair of floating-point types L and R, there exists a candidate 8566 // operator function of the form 8567 // 8568 // std::partial_ordering operator<=>(L, R); 8569 // 8570 // FIXME: The current specification for integral types doesn't play nice with 8571 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8572 // comparisons. Under the current spec this can lead to ambiguity during 8573 // overload resolution. For example: 8574 // 8575 // enum A : int {a}; 8576 // auto x = (a <=> (long)42); 8577 // 8578 // error: call is ambiguous for arguments 'A' and 'long'. 8579 // note: candidate operator<=>(int, int) 8580 // note: candidate operator<=>(long, long) 8581 // 8582 // To avoid this error, this function deviates from the specification and adds 8583 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8584 // arithmetic types (the same as the generic relational overloads). 8585 // 8586 // For now this function acts as a placeholder. 8587 void addThreeWayArithmeticOverloads() { 8588 addGenericBinaryArithmeticOverloads(); 8589 } 8590 8591 // C++ [over.built]p17: 8592 // 8593 // For every pair of promoted integral types L and R, there 8594 // exist candidate operator functions of the form 8595 // 8596 // LR operator%(L, R); 8597 // LR operator&(L, R); 8598 // LR operator^(L, R); 8599 // LR operator|(L, R); 8600 // L operator<<(L, R); 8601 // L operator>>(L, R); 8602 // 8603 // where LR is the result of the usual arithmetic conversions 8604 // between types L and R. 8605 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8606 if (!HasArithmeticOrEnumeralCandidateType) 8607 return; 8608 8609 for (unsigned Left = FirstPromotedIntegralType; 8610 Left < LastPromotedIntegralType; ++Left) { 8611 for (unsigned Right = FirstPromotedIntegralType; 8612 Right < LastPromotedIntegralType; ++Right) { 8613 QualType LandR[2] = { ArithmeticTypes[Left], 8614 ArithmeticTypes[Right] }; 8615 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8616 } 8617 } 8618 } 8619 8620 // C++ [over.built]p20: 8621 // 8622 // For every pair (T, VQ), where T is an enumeration or 8623 // pointer to member type and VQ is either volatile or 8624 // empty, there exist candidate operator functions of the form 8625 // 8626 // VQ T& operator=(VQ T&, T); 8627 void addAssignmentMemberPointerOrEnumeralOverloads() { 8628 /// Set of (canonical) types that we've already handled. 8629 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8630 8631 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8632 for (BuiltinCandidateTypeSet::iterator 8633 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8634 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8635 Enum != EnumEnd; ++Enum) { 8636 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8637 continue; 8638 8639 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8640 } 8641 8642 for (BuiltinCandidateTypeSet::iterator 8643 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8644 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8645 MemPtr != MemPtrEnd; ++MemPtr) { 8646 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8647 continue; 8648 8649 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8650 } 8651 } 8652 } 8653 8654 // C++ [over.built]p19: 8655 // 8656 // For every pair (T, VQ), where T is any type and VQ is either 8657 // volatile or empty, there exist candidate operator functions 8658 // of the form 8659 // 8660 // T*VQ& operator=(T*VQ&, T*); 8661 // 8662 // C++ [over.built]p21: 8663 // 8664 // For every pair (T, VQ), where T is a cv-qualified or 8665 // cv-unqualified object type and VQ is either volatile or 8666 // empty, there exist candidate operator functions of the form 8667 // 8668 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8669 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8670 void addAssignmentPointerOverloads(bool isEqualOp) { 8671 /// Set of (canonical) types that we've already handled. 8672 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8673 8674 for (BuiltinCandidateTypeSet::iterator 8675 Ptr = CandidateTypes[0].pointer_begin(), 8676 PtrEnd = CandidateTypes[0].pointer_end(); 8677 Ptr != PtrEnd; ++Ptr) { 8678 // If this is operator=, keep track of the builtin candidates we added. 8679 if (isEqualOp) 8680 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8681 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8682 continue; 8683 8684 // non-volatile version 8685 QualType ParamTypes[2] = { 8686 S.Context.getLValueReferenceType(*Ptr), 8687 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8688 }; 8689 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8690 /*IsAssignmentOperator=*/ isEqualOp); 8691 8692 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8693 VisibleTypeConversionsQuals.hasVolatile(); 8694 if (NeedVolatile) { 8695 // volatile version 8696 ParamTypes[0] = 8697 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8698 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8699 /*IsAssignmentOperator=*/isEqualOp); 8700 } 8701 8702 if (!(*Ptr).isRestrictQualified() && 8703 VisibleTypeConversionsQuals.hasRestrict()) { 8704 // restrict version 8705 ParamTypes[0] 8706 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8707 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8708 /*IsAssignmentOperator=*/isEqualOp); 8709 8710 if (NeedVolatile) { 8711 // volatile restrict version 8712 ParamTypes[0] 8713 = S.Context.getLValueReferenceType( 8714 S.Context.getCVRQualifiedType(*Ptr, 8715 (Qualifiers::Volatile | 8716 Qualifiers::Restrict))); 8717 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8718 /*IsAssignmentOperator=*/isEqualOp); 8719 } 8720 } 8721 } 8722 8723 if (isEqualOp) { 8724 for (BuiltinCandidateTypeSet::iterator 8725 Ptr = CandidateTypes[1].pointer_begin(), 8726 PtrEnd = CandidateTypes[1].pointer_end(); 8727 Ptr != PtrEnd; ++Ptr) { 8728 // Make sure we don't add the same candidate twice. 8729 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8730 continue; 8731 8732 QualType ParamTypes[2] = { 8733 S.Context.getLValueReferenceType(*Ptr), 8734 *Ptr, 8735 }; 8736 8737 // non-volatile version 8738 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8739 /*IsAssignmentOperator=*/true); 8740 8741 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8742 VisibleTypeConversionsQuals.hasVolatile(); 8743 if (NeedVolatile) { 8744 // volatile version 8745 ParamTypes[0] = 8746 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8747 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8748 /*IsAssignmentOperator=*/true); 8749 } 8750 8751 if (!(*Ptr).isRestrictQualified() && 8752 VisibleTypeConversionsQuals.hasRestrict()) { 8753 // restrict version 8754 ParamTypes[0] 8755 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8756 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8757 /*IsAssignmentOperator=*/true); 8758 8759 if (NeedVolatile) { 8760 // volatile restrict version 8761 ParamTypes[0] 8762 = S.Context.getLValueReferenceType( 8763 S.Context.getCVRQualifiedType(*Ptr, 8764 (Qualifiers::Volatile | 8765 Qualifiers::Restrict))); 8766 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8767 /*IsAssignmentOperator=*/true); 8768 } 8769 } 8770 } 8771 } 8772 } 8773 8774 // C++ [over.built]p18: 8775 // 8776 // For every triple (L, VQ, R), where L is an arithmetic type, 8777 // VQ is either volatile or empty, and R is a promoted 8778 // arithmetic type, there exist candidate operator functions of 8779 // the form 8780 // 8781 // VQ L& operator=(VQ L&, R); 8782 // VQ L& operator*=(VQ L&, R); 8783 // VQ L& operator/=(VQ L&, R); 8784 // VQ L& operator+=(VQ L&, R); 8785 // VQ L& operator-=(VQ L&, R); 8786 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8787 if (!HasArithmeticOrEnumeralCandidateType) 8788 return; 8789 8790 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8791 for (unsigned Right = FirstPromotedArithmeticType; 8792 Right < LastPromotedArithmeticType; ++Right) { 8793 QualType ParamTypes[2]; 8794 ParamTypes[1] = ArithmeticTypes[Right]; 8795 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8796 S, ArithmeticTypes[Left], Args[0]); 8797 // Add this built-in operator as a candidate (VQ is empty). 8798 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8799 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8800 /*IsAssignmentOperator=*/isEqualOp); 8801 8802 // Add this built-in operator as a candidate (VQ is 'volatile'). 8803 if (VisibleTypeConversionsQuals.hasVolatile()) { 8804 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8805 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8806 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8807 /*IsAssignmentOperator=*/isEqualOp); 8808 } 8809 } 8810 } 8811 8812 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8813 for (BuiltinCandidateTypeSet::iterator 8814 Vec1 = CandidateTypes[0].vector_begin(), 8815 Vec1End = CandidateTypes[0].vector_end(); 8816 Vec1 != Vec1End; ++Vec1) { 8817 for (BuiltinCandidateTypeSet::iterator 8818 Vec2 = CandidateTypes[1].vector_begin(), 8819 Vec2End = CandidateTypes[1].vector_end(); 8820 Vec2 != Vec2End; ++Vec2) { 8821 QualType ParamTypes[2]; 8822 ParamTypes[1] = *Vec2; 8823 // Add this built-in operator as a candidate (VQ is empty). 8824 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8825 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8826 /*IsAssignmentOperator=*/isEqualOp); 8827 8828 // Add this built-in operator as a candidate (VQ is 'volatile'). 8829 if (VisibleTypeConversionsQuals.hasVolatile()) { 8830 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8831 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8832 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8833 /*IsAssignmentOperator=*/isEqualOp); 8834 } 8835 } 8836 } 8837 } 8838 8839 // C++ [over.built]p22: 8840 // 8841 // For every triple (L, VQ, R), where L is an integral type, VQ 8842 // is either volatile or empty, and R is a promoted integral 8843 // type, there exist candidate operator functions of the form 8844 // 8845 // VQ L& operator%=(VQ L&, R); 8846 // VQ L& operator<<=(VQ L&, R); 8847 // VQ L& operator>>=(VQ L&, R); 8848 // VQ L& operator&=(VQ L&, R); 8849 // VQ L& operator^=(VQ L&, R); 8850 // VQ L& operator|=(VQ L&, R); 8851 void addAssignmentIntegralOverloads() { 8852 if (!HasArithmeticOrEnumeralCandidateType) 8853 return; 8854 8855 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8856 for (unsigned Right = FirstPromotedIntegralType; 8857 Right < LastPromotedIntegralType; ++Right) { 8858 QualType ParamTypes[2]; 8859 ParamTypes[1] = ArithmeticTypes[Right]; 8860 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8861 S, ArithmeticTypes[Left], Args[0]); 8862 // Add this built-in operator as a candidate (VQ is empty). 8863 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8864 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8865 if (VisibleTypeConversionsQuals.hasVolatile()) { 8866 // Add this built-in operator as a candidate (VQ is 'volatile'). 8867 ParamTypes[0] = LeftBaseTy; 8868 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8869 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8870 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8871 } 8872 } 8873 } 8874 } 8875 8876 // C++ [over.operator]p23: 8877 // 8878 // There also exist candidate operator functions of the form 8879 // 8880 // bool operator!(bool); 8881 // bool operator&&(bool, bool); 8882 // bool operator||(bool, bool); 8883 void addExclaimOverload() { 8884 QualType ParamTy = S.Context.BoolTy; 8885 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8886 /*IsAssignmentOperator=*/false, 8887 /*NumContextualBoolArguments=*/1); 8888 } 8889 void addAmpAmpOrPipePipeOverload() { 8890 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8891 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8892 /*IsAssignmentOperator=*/false, 8893 /*NumContextualBoolArguments=*/2); 8894 } 8895 8896 // C++ [over.built]p13: 8897 // 8898 // For every cv-qualified or cv-unqualified object type T there 8899 // exist candidate operator functions of the form 8900 // 8901 // T* operator+(T*, ptrdiff_t); [ABOVE] 8902 // T& operator[](T*, ptrdiff_t); 8903 // T* operator-(T*, ptrdiff_t); [ABOVE] 8904 // T* operator+(ptrdiff_t, T*); [ABOVE] 8905 // T& operator[](ptrdiff_t, T*); 8906 void addSubscriptOverloads() { 8907 for (BuiltinCandidateTypeSet::iterator 8908 Ptr = CandidateTypes[0].pointer_begin(), 8909 PtrEnd = CandidateTypes[0].pointer_end(); 8910 Ptr != PtrEnd; ++Ptr) { 8911 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8912 QualType PointeeType = (*Ptr)->getPointeeType(); 8913 if (!PointeeType->isObjectType()) 8914 continue; 8915 8916 // T& operator[](T*, ptrdiff_t) 8917 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8918 } 8919 8920 for (BuiltinCandidateTypeSet::iterator 8921 Ptr = CandidateTypes[1].pointer_begin(), 8922 PtrEnd = CandidateTypes[1].pointer_end(); 8923 Ptr != PtrEnd; ++Ptr) { 8924 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8925 QualType PointeeType = (*Ptr)->getPointeeType(); 8926 if (!PointeeType->isObjectType()) 8927 continue; 8928 8929 // T& operator[](ptrdiff_t, T*) 8930 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8931 } 8932 } 8933 8934 // C++ [over.built]p11: 8935 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8936 // C1 is the same type as C2 or is a derived class of C2, T is an object 8937 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8938 // there exist candidate operator functions of the form 8939 // 8940 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8941 // 8942 // where CV12 is the union of CV1 and CV2. 8943 void addArrowStarOverloads() { 8944 for (BuiltinCandidateTypeSet::iterator 8945 Ptr = CandidateTypes[0].pointer_begin(), 8946 PtrEnd = CandidateTypes[0].pointer_end(); 8947 Ptr != PtrEnd; ++Ptr) { 8948 QualType C1Ty = (*Ptr); 8949 QualType C1; 8950 QualifierCollector Q1; 8951 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8952 if (!isa<RecordType>(C1)) 8953 continue; 8954 // heuristic to reduce number of builtin candidates in the set. 8955 // Add volatile/restrict version only if there are conversions to a 8956 // volatile/restrict type. 8957 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8958 continue; 8959 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8960 continue; 8961 for (BuiltinCandidateTypeSet::iterator 8962 MemPtr = CandidateTypes[1].member_pointer_begin(), 8963 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8964 MemPtr != MemPtrEnd; ++MemPtr) { 8965 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8966 QualType C2 = QualType(mptr->getClass(), 0); 8967 C2 = C2.getUnqualifiedType(); 8968 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8969 break; 8970 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8971 // build CV12 T& 8972 QualType T = mptr->getPointeeType(); 8973 if (!VisibleTypeConversionsQuals.hasVolatile() && 8974 T.isVolatileQualified()) 8975 continue; 8976 if (!VisibleTypeConversionsQuals.hasRestrict() && 8977 T.isRestrictQualified()) 8978 continue; 8979 T = Q1.apply(S.Context, T); 8980 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8981 } 8982 } 8983 } 8984 8985 // Note that we don't consider the first argument, since it has been 8986 // contextually converted to bool long ago. The candidates below are 8987 // therefore added as binary. 8988 // 8989 // C++ [over.built]p25: 8990 // For every type T, where T is a pointer, pointer-to-member, or scoped 8991 // enumeration type, there exist candidate operator functions of the form 8992 // 8993 // T operator?(bool, T, T); 8994 // 8995 void addConditionalOperatorOverloads() { 8996 /// Set of (canonical) types that we've already handled. 8997 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8998 8999 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9000 for (BuiltinCandidateTypeSet::iterator 9001 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 9002 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 9003 Ptr != PtrEnd; ++Ptr) { 9004 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 9005 continue; 9006 9007 QualType ParamTypes[2] = { *Ptr, *Ptr }; 9008 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9009 } 9010 9011 for (BuiltinCandidateTypeSet::iterator 9012 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 9013 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 9014 MemPtr != MemPtrEnd; ++MemPtr) { 9015 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 9016 continue; 9017 9018 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 9019 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9020 } 9021 9022 if (S.getLangOpts().CPlusPlus11) { 9023 for (BuiltinCandidateTypeSet::iterator 9024 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 9025 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 9026 Enum != EnumEnd; ++Enum) { 9027 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 9028 continue; 9029 9030 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 9031 continue; 9032 9033 QualType ParamTypes[2] = { *Enum, *Enum }; 9034 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9035 } 9036 } 9037 } 9038 } 9039 }; 9040 9041 } // end anonymous namespace 9042 9043 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9044 /// operator overloads to the candidate set (C++ [over.built]), based 9045 /// on the operator @p Op and the arguments given. For example, if the 9046 /// operator is a binary '+', this routine might add "int 9047 /// operator+(int, int)" to cover integer addition. 9048 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9049 SourceLocation OpLoc, 9050 ArrayRef<Expr *> Args, 9051 OverloadCandidateSet &CandidateSet) { 9052 // Find all of the types that the arguments can convert to, but only 9053 // if the operator we're looking at has built-in operator candidates 9054 // that make use of these types. Also record whether we encounter non-record 9055 // candidate types or either arithmetic or enumeral candidate types. 9056 Qualifiers VisibleTypeConversionsQuals; 9057 VisibleTypeConversionsQuals.addConst(); 9058 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9059 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9060 9061 bool HasNonRecordCandidateType = false; 9062 bool HasArithmeticOrEnumeralCandidateType = false; 9063 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9064 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9065 CandidateTypes.emplace_back(*this); 9066 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9067 OpLoc, 9068 true, 9069 (Op == OO_Exclaim || 9070 Op == OO_AmpAmp || 9071 Op == OO_PipePipe), 9072 VisibleTypeConversionsQuals); 9073 HasNonRecordCandidateType = HasNonRecordCandidateType || 9074 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9075 HasArithmeticOrEnumeralCandidateType = 9076 HasArithmeticOrEnumeralCandidateType || 9077 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9078 } 9079 9080 // Exit early when no non-record types have been added to the candidate set 9081 // for any of the arguments to the operator. 9082 // 9083 // We can't exit early for !, ||, or &&, since there we have always have 9084 // 'bool' overloads. 9085 if (!HasNonRecordCandidateType && 9086 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9087 return; 9088 9089 // Setup an object to manage the common state for building overloads. 9090 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9091 VisibleTypeConversionsQuals, 9092 HasArithmeticOrEnumeralCandidateType, 9093 CandidateTypes, CandidateSet); 9094 9095 // Dispatch over the operation to add in only those overloads which apply. 9096 switch (Op) { 9097 case OO_None: 9098 case NUM_OVERLOADED_OPERATORS: 9099 llvm_unreachable("Expected an overloaded operator"); 9100 9101 case OO_New: 9102 case OO_Delete: 9103 case OO_Array_New: 9104 case OO_Array_Delete: 9105 case OO_Call: 9106 llvm_unreachable( 9107 "Special operators don't use AddBuiltinOperatorCandidates"); 9108 9109 case OO_Comma: 9110 case OO_Arrow: 9111 case OO_Coawait: 9112 // C++ [over.match.oper]p3: 9113 // -- For the operator ',', the unary operator '&', the 9114 // operator '->', or the operator 'co_await', the 9115 // built-in candidates set is empty. 9116 break; 9117 9118 case OO_Plus: // '+' is either unary or binary 9119 if (Args.size() == 1) 9120 OpBuilder.addUnaryPlusPointerOverloads(); 9121 LLVM_FALLTHROUGH; 9122 9123 case OO_Minus: // '-' is either unary or binary 9124 if (Args.size() == 1) { 9125 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9126 } else { 9127 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9128 OpBuilder.addGenericBinaryArithmeticOverloads(); 9129 } 9130 break; 9131 9132 case OO_Star: // '*' is either unary or binary 9133 if (Args.size() == 1) 9134 OpBuilder.addUnaryStarPointerOverloads(); 9135 else 9136 OpBuilder.addGenericBinaryArithmeticOverloads(); 9137 break; 9138 9139 case OO_Slash: 9140 OpBuilder.addGenericBinaryArithmeticOverloads(); 9141 break; 9142 9143 case OO_PlusPlus: 9144 case OO_MinusMinus: 9145 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9146 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9147 break; 9148 9149 case OO_EqualEqual: 9150 case OO_ExclaimEqual: 9151 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9152 LLVM_FALLTHROUGH; 9153 9154 case OO_Less: 9155 case OO_Greater: 9156 case OO_LessEqual: 9157 case OO_GreaterEqual: 9158 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9159 OpBuilder.addGenericBinaryArithmeticOverloads(); 9160 break; 9161 9162 case OO_Spaceship: 9163 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9164 OpBuilder.addThreeWayArithmeticOverloads(); 9165 break; 9166 9167 case OO_Percent: 9168 case OO_Caret: 9169 case OO_Pipe: 9170 case OO_LessLess: 9171 case OO_GreaterGreater: 9172 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9173 break; 9174 9175 case OO_Amp: // '&' is either unary or binary 9176 if (Args.size() == 1) 9177 // C++ [over.match.oper]p3: 9178 // -- For the operator ',', the unary operator '&', or the 9179 // operator '->', the built-in candidates set is empty. 9180 break; 9181 9182 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9183 break; 9184 9185 case OO_Tilde: 9186 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9187 break; 9188 9189 case OO_Equal: 9190 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9191 LLVM_FALLTHROUGH; 9192 9193 case OO_PlusEqual: 9194 case OO_MinusEqual: 9195 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9196 LLVM_FALLTHROUGH; 9197 9198 case OO_StarEqual: 9199 case OO_SlashEqual: 9200 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9201 break; 9202 9203 case OO_PercentEqual: 9204 case OO_LessLessEqual: 9205 case OO_GreaterGreaterEqual: 9206 case OO_AmpEqual: 9207 case OO_CaretEqual: 9208 case OO_PipeEqual: 9209 OpBuilder.addAssignmentIntegralOverloads(); 9210 break; 9211 9212 case OO_Exclaim: 9213 OpBuilder.addExclaimOverload(); 9214 break; 9215 9216 case OO_AmpAmp: 9217 case OO_PipePipe: 9218 OpBuilder.addAmpAmpOrPipePipeOverload(); 9219 break; 9220 9221 case OO_Subscript: 9222 OpBuilder.addSubscriptOverloads(); 9223 break; 9224 9225 case OO_ArrowStar: 9226 OpBuilder.addArrowStarOverloads(); 9227 break; 9228 9229 case OO_Conditional: 9230 OpBuilder.addConditionalOperatorOverloads(); 9231 OpBuilder.addGenericBinaryArithmeticOverloads(); 9232 break; 9233 } 9234 } 9235 9236 /// Add function candidates found via argument-dependent lookup 9237 /// to the set of overloading candidates. 9238 /// 9239 /// This routine performs argument-dependent name lookup based on the 9240 /// given function name (which may also be an operator name) and adds 9241 /// all of the overload candidates found by ADL to the overload 9242 /// candidate set (C++ [basic.lookup.argdep]). 9243 void 9244 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9245 SourceLocation Loc, 9246 ArrayRef<Expr *> Args, 9247 TemplateArgumentListInfo *ExplicitTemplateArgs, 9248 OverloadCandidateSet& CandidateSet, 9249 bool PartialOverloading) { 9250 ADLResult Fns; 9251 9252 // FIXME: This approach for uniquing ADL results (and removing 9253 // redundant candidates from the set) relies on pointer-equality, 9254 // which means we need to key off the canonical decl. However, 9255 // always going back to the canonical decl might not get us the 9256 // right set of default arguments. What default arguments are 9257 // we supposed to consider on ADL candidates, anyway? 9258 9259 // FIXME: Pass in the explicit template arguments? 9260 ArgumentDependentLookup(Name, Loc, Args, Fns); 9261 9262 // Erase all of the candidates we already knew about. 9263 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9264 CandEnd = CandidateSet.end(); 9265 Cand != CandEnd; ++Cand) 9266 if (Cand->Function) { 9267 Fns.erase(Cand->Function); 9268 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9269 Fns.erase(FunTmpl); 9270 } 9271 9272 // For each of the ADL candidates we found, add it to the overload 9273 // set. 9274 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9275 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9276 9277 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9278 if (ExplicitTemplateArgs) 9279 continue; 9280 9281 AddOverloadCandidate( 9282 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9283 PartialOverloading, /*AllowExplicit=*/true, 9284 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL); 9285 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9286 AddOverloadCandidate( 9287 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9288 /*SuppressUserConversions=*/false, PartialOverloading, 9289 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false, 9290 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9291 } 9292 } else { 9293 auto *FTD = cast<FunctionTemplateDecl>(*I); 9294 AddTemplateOverloadCandidate( 9295 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9296 /*SuppressUserConversions=*/false, PartialOverloading, 9297 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9298 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9299 Context, FTD->getTemplatedDecl())) { 9300 AddTemplateOverloadCandidate( 9301 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9302 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9303 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9304 OverloadCandidateParamOrder::Reversed); 9305 } 9306 } 9307 } 9308 } 9309 9310 namespace { 9311 enum class Comparison { Equal, Better, Worse }; 9312 } 9313 9314 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9315 /// overload resolution. 9316 /// 9317 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9318 /// Cand1's first N enable_if attributes have precisely the same conditions as 9319 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9320 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9321 /// 9322 /// Note that you can have a pair of candidates such that Cand1's enable_if 9323 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9324 /// worse than Cand1's. 9325 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9326 const FunctionDecl *Cand2) { 9327 // Common case: One (or both) decls don't have enable_if attrs. 9328 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9329 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9330 if (!Cand1Attr || !Cand2Attr) { 9331 if (Cand1Attr == Cand2Attr) 9332 return Comparison::Equal; 9333 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9334 } 9335 9336 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9337 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9338 9339 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9340 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9341 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9342 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9343 9344 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9345 // has fewer enable_if attributes than Cand2, and vice versa. 9346 if (!Cand1A) 9347 return Comparison::Worse; 9348 if (!Cand2A) 9349 return Comparison::Better; 9350 9351 Cand1ID.clear(); 9352 Cand2ID.clear(); 9353 9354 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9355 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9356 if (Cand1ID != Cand2ID) 9357 return Comparison::Worse; 9358 } 9359 9360 return Comparison::Equal; 9361 } 9362 9363 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9364 const OverloadCandidate &Cand2) { 9365 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9366 !Cand2.Function->isMultiVersion()) 9367 return false; 9368 9369 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9370 // is obviously better. 9371 if (Cand1.Function->isInvalidDecl()) return false; 9372 if (Cand2.Function->isInvalidDecl()) return true; 9373 9374 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9375 // cpu_dispatch, else arbitrarily based on the identifiers. 9376 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9377 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9378 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9379 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9380 9381 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9382 return false; 9383 9384 if (Cand1CPUDisp && !Cand2CPUDisp) 9385 return true; 9386 if (Cand2CPUDisp && !Cand1CPUDisp) 9387 return false; 9388 9389 if (Cand1CPUSpec && Cand2CPUSpec) { 9390 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9391 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9392 9393 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9394 FirstDiff = std::mismatch( 9395 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9396 Cand2CPUSpec->cpus_begin(), 9397 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9398 return LHS->getName() == RHS->getName(); 9399 }); 9400 9401 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9402 "Two different cpu-specific versions should not have the same " 9403 "identifier list, otherwise they'd be the same decl!"); 9404 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9405 } 9406 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9407 } 9408 9409 /// isBetterOverloadCandidate - Determines whether the first overload 9410 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9411 bool clang::isBetterOverloadCandidate( 9412 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9413 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9414 // Define viable functions to be better candidates than non-viable 9415 // functions. 9416 if (!Cand2.Viable) 9417 return Cand1.Viable; 9418 else if (!Cand1.Viable) 9419 return false; 9420 9421 // C++ [over.match.best]p1: 9422 // 9423 // -- if F is a static member function, ICS1(F) is defined such 9424 // that ICS1(F) is neither better nor worse than ICS1(G) for 9425 // any function G, and, symmetrically, ICS1(G) is neither 9426 // better nor worse than ICS1(F). 9427 unsigned StartArg = 0; 9428 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9429 StartArg = 1; 9430 9431 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9432 // We don't allow incompatible pointer conversions in C++. 9433 if (!S.getLangOpts().CPlusPlus) 9434 return ICS.isStandard() && 9435 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9436 9437 // The only ill-formed conversion we allow in C++ is the string literal to 9438 // char* conversion, which is only considered ill-formed after C++11. 9439 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9440 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9441 }; 9442 9443 // Define functions that don't require ill-formed conversions for a given 9444 // argument to be better candidates than functions that do. 9445 unsigned NumArgs = Cand1.Conversions.size(); 9446 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9447 bool HasBetterConversion = false; 9448 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9449 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9450 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9451 if (Cand1Bad != Cand2Bad) { 9452 if (Cand1Bad) 9453 return false; 9454 HasBetterConversion = true; 9455 } 9456 } 9457 9458 if (HasBetterConversion) 9459 return true; 9460 9461 // C++ [over.match.best]p1: 9462 // A viable function F1 is defined to be a better function than another 9463 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9464 // conversion sequence than ICSi(F2), and then... 9465 bool HasWorseConversion = false; 9466 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9467 switch (CompareImplicitConversionSequences(S, Loc, 9468 Cand1.Conversions[ArgIdx], 9469 Cand2.Conversions[ArgIdx])) { 9470 case ImplicitConversionSequence::Better: 9471 // Cand1 has a better conversion sequence. 9472 HasBetterConversion = true; 9473 break; 9474 9475 case ImplicitConversionSequence::Worse: 9476 if (Cand1.Function && Cand1.Function == Cand2.Function && 9477 (Cand2.RewriteKind & CRK_Reversed) != 0) { 9478 // Work around large-scale breakage caused by considering reversed 9479 // forms of operator== in C++20: 9480 // 9481 // When comparing a function against its reversed form, if we have a 9482 // better conversion for one argument and a worse conversion for the 9483 // other, we prefer the non-reversed form. 9484 // 9485 // This prevents a conversion function from being considered ambiguous 9486 // with its own reversed form in various where it's only incidentally 9487 // heterogeneous. 9488 // 9489 // We diagnose this as an extension from CreateOverloadedBinOp. 9490 HasWorseConversion = true; 9491 break; 9492 } 9493 9494 // Cand1 can't be better than Cand2. 9495 return false; 9496 9497 case ImplicitConversionSequence::Indistinguishable: 9498 // Do nothing. 9499 break; 9500 } 9501 } 9502 9503 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9504 // ICSj(F2), or, if not that, 9505 if (HasBetterConversion) 9506 return true; 9507 if (HasWorseConversion) 9508 return false; 9509 9510 // -- the context is an initialization by user-defined conversion 9511 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9512 // from the return type of F1 to the destination type (i.e., 9513 // the type of the entity being initialized) is a better 9514 // conversion sequence than the standard conversion sequence 9515 // from the return type of F2 to the destination type. 9516 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9517 Cand1.Function && Cand2.Function && 9518 isa<CXXConversionDecl>(Cand1.Function) && 9519 isa<CXXConversionDecl>(Cand2.Function)) { 9520 // First check whether we prefer one of the conversion functions over the 9521 // other. This only distinguishes the results in non-standard, extension 9522 // cases such as the conversion from a lambda closure type to a function 9523 // pointer or block. 9524 ImplicitConversionSequence::CompareKind Result = 9525 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9526 if (Result == ImplicitConversionSequence::Indistinguishable) 9527 Result = CompareStandardConversionSequences(S, Loc, 9528 Cand1.FinalConversion, 9529 Cand2.FinalConversion); 9530 9531 if (Result != ImplicitConversionSequence::Indistinguishable) 9532 return Result == ImplicitConversionSequence::Better; 9533 9534 // FIXME: Compare kind of reference binding if conversion functions 9535 // convert to a reference type used in direct reference binding, per 9536 // C++14 [over.match.best]p1 section 2 bullet 3. 9537 } 9538 9539 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9540 // as combined with the resolution to CWG issue 243. 9541 // 9542 // When the context is initialization by constructor ([over.match.ctor] or 9543 // either phase of [over.match.list]), a constructor is preferred over 9544 // a conversion function. 9545 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9546 Cand1.Function && Cand2.Function && 9547 isa<CXXConstructorDecl>(Cand1.Function) != 9548 isa<CXXConstructorDecl>(Cand2.Function)) 9549 return isa<CXXConstructorDecl>(Cand1.Function); 9550 9551 // -- F1 is a non-template function and F2 is a function template 9552 // specialization, or, if not that, 9553 bool Cand1IsSpecialization = Cand1.Function && 9554 Cand1.Function->getPrimaryTemplate(); 9555 bool Cand2IsSpecialization = Cand2.Function && 9556 Cand2.Function->getPrimaryTemplate(); 9557 if (Cand1IsSpecialization != Cand2IsSpecialization) 9558 return Cand2IsSpecialization; 9559 9560 // -- F1 and F2 are function template specializations, and the function 9561 // template for F1 is more specialized than the template for F2 9562 // according to the partial ordering rules described in 14.5.5.2, or, 9563 // if not that, 9564 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9565 if (FunctionTemplateDecl *BetterTemplate 9566 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9567 Cand2.Function->getPrimaryTemplate(), 9568 Loc, 9569 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9570 : TPOC_Call, 9571 Cand1.ExplicitCallArguments, 9572 Cand2.ExplicitCallArguments)) 9573 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9574 } 9575 9576 // -— F1 and F2 are non-template functions with the same 9577 // parameter-type-lists, and F1 is more constrained than F2 [...], 9578 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9579 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9580 Cand2.Function->hasPrototype()) { 9581 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9582 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9583 if (PT1->getNumParams() == PT2->getNumParams() && 9584 PT1->isVariadic() == PT2->isVariadic() && 9585 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9586 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9587 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9588 if (RC1 && RC2) { 9589 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9590 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9591 {RC2}, AtLeastAsConstrained1)) 9592 return false; 9593 if (!AtLeastAsConstrained1) 9594 return false; 9595 if (S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9596 {RC1}, AtLeastAsConstrained2)) 9597 return false; 9598 if (!AtLeastAsConstrained2) 9599 return true; 9600 } else if (RC1 || RC2) 9601 return RC1 != nullptr; 9602 } 9603 } 9604 9605 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9606 // class B of D, and for all arguments the corresponding parameters of 9607 // F1 and F2 have the same type. 9608 // FIXME: Implement the "all parameters have the same type" check. 9609 bool Cand1IsInherited = 9610 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9611 bool Cand2IsInherited = 9612 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9613 if (Cand1IsInherited != Cand2IsInherited) 9614 return Cand2IsInherited; 9615 else if (Cand1IsInherited) { 9616 assert(Cand2IsInherited); 9617 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9618 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9619 if (Cand1Class->isDerivedFrom(Cand2Class)) 9620 return true; 9621 if (Cand2Class->isDerivedFrom(Cand1Class)) 9622 return false; 9623 // Inherited from sibling base classes: still ambiguous. 9624 } 9625 9626 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9627 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9628 // with reversed order of parameters and F1 is not 9629 // 9630 // We rank reversed + different operator as worse than just reversed, but 9631 // that comparison can never happen, because we only consider reversing for 9632 // the maximally-rewritten operator (== or <=>). 9633 if (Cand1.RewriteKind != Cand2.RewriteKind) 9634 return Cand1.RewriteKind < Cand2.RewriteKind; 9635 9636 // Check C++17 tie-breakers for deduction guides. 9637 { 9638 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9639 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9640 if (Guide1 && Guide2) { 9641 // -- F1 is generated from a deduction-guide and F2 is not 9642 if (Guide1->isImplicit() != Guide2->isImplicit()) 9643 return Guide2->isImplicit(); 9644 9645 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9646 if (Guide1->isCopyDeductionCandidate()) 9647 return true; 9648 } 9649 } 9650 9651 // Check for enable_if value-based overload resolution. 9652 if (Cand1.Function && Cand2.Function) { 9653 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9654 if (Cmp != Comparison::Equal) 9655 return Cmp == Comparison::Better; 9656 } 9657 9658 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9659 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9660 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9661 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9662 } 9663 9664 bool HasPS1 = Cand1.Function != nullptr && 9665 functionHasPassObjectSizeParams(Cand1.Function); 9666 bool HasPS2 = Cand2.Function != nullptr && 9667 functionHasPassObjectSizeParams(Cand2.Function); 9668 if (HasPS1 != HasPS2 && HasPS1) 9669 return true; 9670 9671 return isBetterMultiversionCandidate(Cand1, Cand2); 9672 } 9673 9674 /// Determine whether two declarations are "equivalent" for the purposes of 9675 /// name lookup and overload resolution. This applies when the same internal/no 9676 /// linkage entity is defined by two modules (probably by textually including 9677 /// the same header). In such a case, we don't consider the declarations to 9678 /// declare the same entity, but we also don't want lookups with both 9679 /// declarations visible to be ambiguous in some cases (this happens when using 9680 /// a modularized libstdc++). 9681 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9682 const NamedDecl *B) { 9683 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9684 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9685 if (!VA || !VB) 9686 return false; 9687 9688 // The declarations must be declaring the same name as an internal linkage 9689 // entity in different modules. 9690 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9691 VB->getDeclContext()->getRedeclContext()) || 9692 getOwningModule(VA) == getOwningModule(VB) || 9693 VA->isExternallyVisible() || VB->isExternallyVisible()) 9694 return false; 9695 9696 // Check that the declarations appear to be equivalent. 9697 // 9698 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9699 // For constants and functions, we should check the initializer or body is 9700 // the same. For non-constant variables, we shouldn't allow it at all. 9701 if (Context.hasSameType(VA->getType(), VB->getType())) 9702 return true; 9703 9704 // Enum constants within unnamed enumerations will have different types, but 9705 // may still be similar enough to be interchangeable for our purposes. 9706 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9707 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9708 // Only handle anonymous enums. If the enumerations were named and 9709 // equivalent, they would have been merged to the same type. 9710 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9711 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9712 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9713 !Context.hasSameType(EnumA->getIntegerType(), 9714 EnumB->getIntegerType())) 9715 return false; 9716 // Allow this only if the value is the same for both enumerators. 9717 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9718 } 9719 } 9720 9721 // Nothing else is sufficiently similar. 9722 return false; 9723 } 9724 9725 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9726 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9727 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9728 9729 Module *M = getOwningModule(D); 9730 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9731 << !M << (M ? M->getFullModuleName() : ""); 9732 9733 for (auto *E : Equiv) { 9734 Module *M = getOwningModule(E); 9735 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9736 << !M << (M ? M->getFullModuleName() : ""); 9737 } 9738 } 9739 9740 /// Computes the best viable function (C++ 13.3.3) 9741 /// within an overload candidate set. 9742 /// 9743 /// \param Loc The location of the function name (or operator symbol) for 9744 /// which overload resolution occurs. 9745 /// 9746 /// \param Best If overload resolution was successful or found a deleted 9747 /// function, \p Best points to the candidate function found. 9748 /// 9749 /// \returns The result of overload resolution. 9750 OverloadingResult 9751 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9752 iterator &Best) { 9753 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9754 std::transform(begin(), end(), std::back_inserter(Candidates), 9755 [](OverloadCandidate &Cand) { return &Cand; }); 9756 9757 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9758 // are accepted by both clang and NVCC. However, during a particular 9759 // compilation mode only one call variant is viable. We need to 9760 // exclude non-viable overload candidates from consideration based 9761 // only on their host/device attributes. Specifically, if one 9762 // candidate call is WrongSide and the other is SameSide, we ignore 9763 // the WrongSide candidate. 9764 if (S.getLangOpts().CUDA) { 9765 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9766 bool ContainsSameSideCandidate = 9767 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9768 // Check viable function only. 9769 return Cand->Viable && Cand->Function && 9770 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9771 Sema::CFP_SameSide; 9772 }); 9773 if (ContainsSameSideCandidate) { 9774 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9775 // Check viable function only to avoid unnecessary data copying/moving. 9776 return Cand->Viable && Cand->Function && 9777 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9778 Sema::CFP_WrongSide; 9779 }; 9780 llvm::erase_if(Candidates, IsWrongSideCandidate); 9781 } 9782 } 9783 9784 // Find the best viable function. 9785 Best = end(); 9786 for (auto *Cand : Candidates) { 9787 Cand->Best = false; 9788 if (Cand->Viable) 9789 if (Best == end() || 9790 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9791 Best = Cand; 9792 } 9793 9794 // If we didn't find any viable functions, abort. 9795 if (Best == end()) 9796 return OR_No_Viable_Function; 9797 9798 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9799 9800 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 9801 PendingBest.push_back(&*Best); 9802 Best->Best = true; 9803 9804 // Make sure that this function is better than every other viable 9805 // function. If not, we have an ambiguity. 9806 while (!PendingBest.empty()) { 9807 auto *Curr = PendingBest.pop_back_val(); 9808 for (auto *Cand : Candidates) { 9809 if (Cand->Viable && !Cand->Best && 9810 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 9811 PendingBest.push_back(Cand); 9812 Cand->Best = true; 9813 9814 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 9815 Curr->Function)) 9816 EquivalentCands.push_back(Cand->Function); 9817 else 9818 Best = end(); 9819 } 9820 } 9821 } 9822 9823 // If we found more than one best candidate, this is ambiguous. 9824 if (Best == end()) 9825 return OR_Ambiguous; 9826 9827 // Best is the best viable function. 9828 if (Best->Function && Best->Function->isDeleted()) 9829 return OR_Deleted; 9830 9831 if (!EquivalentCands.empty()) 9832 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9833 EquivalentCands); 9834 9835 return OR_Success; 9836 } 9837 9838 namespace { 9839 9840 enum OverloadCandidateKind { 9841 oc_function, 9842 oc_method, 9843 oc_reversed_binary_operator, 9844 oc_constructor, 9845 oc_implicit_default_constructor, 9846 oc_implicit_copy_constructor, 9847 oc_implicit_move_constructor, 9848 oc_implicit_copy_assignment, 9849 oc_implicit_move_assignment, 9850 oc_implicit_equality_comparison, 9851 oc_inherited_constructor 9852 }; 9853 9854 enum OverloadCandidateSelect { 9855 ocs_non_template, 9856 ocs_template, 9857 ocs_described_template, 9858 }; 9859 9860 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9861 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9862 OverloadCandidateRewriteKind CRK, 9863 std::string &Description) { 9864 9865 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9866 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9867 isTemplate = true; 9868 Description = S.getTemplateArgumentBindingsText( 9869 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9870 } 9871 9872 OverloadCandidateSelect Select = [&]() { 9873 if (!Description.empty()) 9874 return ocs_described_template; 9875 return isTemplate ? ocs_template : ocs_non_template; 9876 }(); 9877 9878 OverloadCandidateKind Kind = [&]() { 9879 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 9880 return oc_implicit_equality_comparison; 9881 9882 if (CRK & CRK_Reversed) 9883 return oc_reversed_binary_operator; 9884 9885 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9886 if (!Ctor->isImplicit()) { 9887 if (isa<ConstructorUsingShadowDecl>(Found)) 9888 return oc_inherited_constructor; 9889 else 9890 return oc_constructor; 9891 } 9892 9893 if (Ctor->isDefaultConstructor()) 9894 return oc_implicit_default_constructor; 9895 9896 if (Ctor->isMoveConstructor()) 9897 return oc_implicit_move_constructor; 9898 9899 assert(Ctor->isCopyConstructor() && 9900 "unexpected sort of implicit constructor"); 9901 return oc_implicit_copy_constructor; 9902 } 9903 9904 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9905 // This actually gets spelled 'candidate function' for now, but 9906 // it doesn't hurt to split it out. 9907 if (!Meth->isImplicit()) 9908 return oc_method; 9909 9910 if (Meth->isMoveAssignmentOperator()) 9911 return oc_implicit_move_assignment; 9912 9913 if (Meth->isCopyAssignmentOperator()) 9914 return oc_implicit_copy_assignment; 9915 9916 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9917 return oc_method; 9918 } 9919 9920 return oc_function; 9921 }(); 9922 9923 return std::make_pair(Kind, Select); 9924 } 9925 9926 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9927 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9928 // set. 9929 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9930 S.Diag(FoundDecl->getLocation(), 9931 diag::note_ovl_candidate_inherited_constructor) 9932 << Shadow->getNominatedBaseClass(); 9933 } 9934 9935 } // end anonymous namespace 9936 9937 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9938 const FunctionDecl *FD) { 9939 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9940 bool AlwaysTrue; 9941 if (EnableIf->getCond()->isValueDependent() || 9942 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9943 return false; 9944 if (!AlwaysTrue) 9945 return false; 9946 } 9947 return true; 9948 } 9949 9950 /// Returns true if we can take the address of the function. 9951 /// 9952 /// \param Complain - If true, we'll emit a diagnostic 9953 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9954 /// we in overload resolution? 9955 /// \param Loc - The location of the statement we're complaining about. Ignored 9956 /// if we're not complaining, or if we're in overload resolution. 9957 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9958 bool Complain, 9959 bool InOverloadResolution, 9960 SourceLocation Loc) { 9961 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9962 if (Complain) { 9963 if (InOverloadResolution) 9964 S.Diag(FD->getBeginLoc(), 9965 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9966 else 9967 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9968 } 9969 return false; 9970 } 9971 9972 if (FD->getTrailingRequiresClause()) { 9973 ConstraintSatisfaction Satisfaction; 9974 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 9975 return false; 9976 if (!Satisfaction.IsSatisfied) { 9977 if (Complain) { 9978 if (InOverloadResolution) 9979 S.Diag(FD->getBeginLoc(), 9980 diag::note_ovl_candidate_unsatisfied_constraints); 9981 else 9982 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 9983 << FD; 9984 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 9985 } 9986 return false; 9987 } 9988 } 9989 9990 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9991 return P->hasAttr<PassObjectSizeAttr>(); 9992 }); 9993 if (I == FD->param_end()) 9994 return true; 9995 9996 if (Complain) { 9997 // Add one to ParamNo because it's user-facing 9998 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9999 if (InOverloadResolution) 10000 S.Diag(FD->getLocation(), 10001 diag::note_ovl_candidate_has_pass_object_size_params) 10002 << ParamNo; 10003 else 10004 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10005 << FD << ParamNo; 10006 } 10007 return false; 10008 } 10009 10010 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10011 const FunctionDecl *FD) { 10012 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10013 /*InOverloadResolution=*/true, 10014 /*Loc=*/SourceLocation()); 10015 } 10016 10017 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10018 bool Complain, 10019 SourceLocation Loc) { 10020 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10021 /*InOverloadResolution=*/false, 10022 Loc); 10023 } 10024 10025 // Notes the location of an overload candidate. 10026 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10027 OverloadCandidateRewriteKind RewriteKind, 10028 QualType DestType, bool TakingAddress) { 10029 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10030 return; 10031 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10032 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10033 return; 10034 10035 std::string FnDesc; 10036 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10037 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10038 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10039 << (unsigned)KSPair.first << (unsigned)KSPair.second 10040 << Fn << FnDesc; 10041 10042 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10043 Diag(Fn->getLocation(), PD); 10044 MaybeEmitInheritedConstructorNote(*this, Found); 10045 } 10046 10047 static void 10048 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10049 // Perhaps the ambiguity was caused by two atomic constraints that are 10050 // 'identical' but not equivalent: 10051 // 10052 // void foo() requires (sizeof(T) > 4) { } // #1 10053 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10054 // 10055 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10056 // #2 to subsume #1, but these constraint are not considered equivalent 10057 // according to the subsumption rules because they are not the same 10058 // source-level construct. This behavior is quite confusing and we should try 10059 // to help the user figure out what happened. 10060 10061 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10062 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10063 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10064 if (!I->Function) 10065 continue; 10066 SmallVector<const Expr *, 3> AC; 10067 if (auto *Template = I->Function->getPrimaryTemplate()) 10068 Template->getAssociatedConstraints(AC); 10069 else 10070 I->Function->getAssociatedConstraints(AC); 10071 if (AC.empty()) 10072 continue; 10073 if (FirstCand == nullptr) { 10074 FirstCand = I->Function; 10075 FirstAC = AC; 10076 } else if (SecondCand == nullptr) { 10077 SecondCand = I->Function; 10078 SecondAC = AC; 10079 } else { 10080 // We have more than one pair of constrained functions - this check is 10081 // expensive and we'd rather not try to diagnose it. 10082 return; 10083 } 10084 } 10085 if (!SecondCand) 10086 return; 10087 // The diagnostic can only happen if there are associated constraints on 10088 // both sides (there needs to be some identical atomic constraint). 10089 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10090 SecondCand, SecondAC)) 10091 // Just show the user one diagnostic, they'll probably figure it out 10092 // from here. 10093 return; 10094 } 10095 10096 // Notes the location of all overload candidates designated through 10097 // OverloadedExpr 10098 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10099 bool TakingAddress) { 10100 assert(OverloadedExpr->getType() == Context.OverloadTy); 10101 10102 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10103 OverloadExpr *OvlExpr = Ovl.Expression; 10104 10105 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10106 IEnd = OvlExpr->decls_end(); 10107 I != IEnd; ++I) { 10108 if (FunctionTemplateDecl *FunTmpl = 10109 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10110 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10111 TakingAddress); 10112 } else if (FunctionDecl *Fun 10113 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10114 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10115 } 10116 } 10117 } 10118 10119 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10120 /// "lead" diagnostic; it will be given two arguments, the source and 10121 /// target types of the conversion. 10122 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10123 Sema &S, 10124 SourceLocation CaretLoc, 10125 const PartialDiagnostic &PDiag) const { 10126 S.Diag(CaretLoc, PDiag) 10127 << Ambiguous.getFromType() << Ambiguous.getToType(); 10128 // FIXME: The note limiting machinery is borrowed from 10129 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 10130 // refactoring here. 10131 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10132 unsigned CandsShown = 0; 10133 AmbiguousConversionSequence::const_iterator I, E; 10134 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10135 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10136 break; 10137 ++CandsShown; 10138 S.NoteOverloadCandidate(I->first, I->second); 10139 } 10140 if (I != E) 10141 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10142 } 10143 10144 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10145 unsigned I, bool TakingCandidateAddress) { 10146 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10147 assert(Conv.isBad()); 10148 assert(Cand->Function && "for now, candidate must be a function"); 10149 FunctionDecl *Fn = Cand->Function; 10150 10151 // There's a conversion slot for the object argument if this is a 10152 // non-constructor method. Note that 'I' corresponds the 10153 // conversion-slot index. 10154 bool isObjectArgument = false; 10155 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10156 if (I == 0) 10157 isObjectArgument = true; 10158 else 10159 I--; 10160 } 10161 10162 std::string FnDesc; 10163 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10164 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10165 FnDesc); 10166 10167 Expr *FromExpr = Conv.Bad.FromExpr; 10168 QualType FromTy = Conv.Bad.getFromType(); 10169 QualType ToTy = Conv.Bad.getToType(); 10170 10171 if (FromTy == S.Context.OverloadTy) { 10172 assert(FromExpr && "overload set argument came from implicit argument?"); 10173 Expr *E = FromExpr->IgnoreParens(); 10174 if (isa<UnaryOperator>(E)) 10175 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10176 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10177 10178 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10179 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10180 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10181 << Name << I + 1; 10182 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10183 return; 10184 } 10185 10186 // Do some hand-waving analysis to see if the non-viability is due 10187 // to a qualifier mismatch. 10188 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10189 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10190 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10191 CToTy = RT->getPointeeType(); 10192 else { 10193 // TODO: detect and diagnose the full richness of const mismatches. 10194 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10195 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10196 CFromTy = FromPT->getPointeeType(); 10197 CToTy = ToPT->getPointeeType(); 10198 } 10199 } 10200 10201 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10202 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10203 Qualifiers FromQs = CFromTy.getQualifiers(); 10204 Qualifiers ToQs = CToTy.getQualifiers(); 10205 10206 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10207 if (isObjectArgument) 10208 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10209 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10210 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10211 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10212 else 10213 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10214 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10215 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10216 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10217 << ToTy->isReferenceType() << I + 1; 10218 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10219 return; 10220 } 10221 10222 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10223 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10224 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10225 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10226 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10227 << (unsigned)isObjectArgument << I + 1; 10228 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10229 return; 10230 } 10231 10232 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10233 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10234 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10235 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10236 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10237 << (unsigned)isObjectArgument << I + 1; 10238 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10239 return; 10240 } 10241 10242 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10243 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10244 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10245 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10246 << FromQs.hasUnaligned() << I + 1; 10247 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10248 return; 10249 } 10250 10251 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10252 assert(CVR && "unexpected qualifiers mismatch"); 10253 10254 if (isObjectArgument) { 10255 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10256 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10257 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10258 << (CVR - 1); 10259 } else { 10260 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10261 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10262 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10263 << (CVR - 1) << I + 1; 10264 } 10265 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10266 return; 10267 } 10268 10269 // Special diagnostic for failure to convert an initializer list, since 10270 // telling the user that it has type void is not useful. 10271 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10272 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10273 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10274 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10275 << ToTy << (unsigned)isObjectArgument << I + 1; 10276 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10277 return; 10278 } 10279 10280 // Diagnose references or pointers to incomplete types differently, 10281 // since it's far from impossible that the incompleteness triggered 10282 // the failure. 10283 QualType TempFromTy = FromTy.getNonReferenceType(); 10284 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10285 TempFromTy = PTy->getPointeeType(); 10286 if (TempFromTy->isIncompleteType()) { 10287 // Emit the generic diagnostic and, optionally, add the hints to it. 10288 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10289 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10290 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10291 << ToTy << (unsigned)isObjectArgument << I + 1 10292 << (unsigned)(Cand->Fix.Kind); 10293 10294 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10295 return; 10296 } 10297 10298 // Diagnose base -> derived pointer conversions. 10299 unsigned BaseToDerivedConversion = 0; 10300 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10301 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10302 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10303 FromPtrTy->getPointeeType()) && 10304 !FromPtrTy->getPointeeType()->isIncompleteType() && 10305 !ToPtrTy->getPointeeType()->isIncompleteType() && 10306 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10307 FromPtrTy->getPointeeType())) 10308 BaseToDerivedConversion = 1; 10309 } 10310 } else if (const ObjCObjectPointerType *FromPtrTy 10311 = FromTy->getAs<ObjCObjectPointerType>()) { 10312 if (const ObjCObjectPointerType *ToPtrTy 10313 = ToTy->getAs<ObjCObjectPointerType>()) 10314 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10315 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10316 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10317 FromPtrTy->getPointeeType()) && 10318 FromIface->isSuperClassOf(ToIface)) 10319 BaseToDerivedConversion = 2; 10320 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10321 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10322 !FromTy->isIncompleteType() && 10323 !ToRefTy->getPointeeType()->isIncompleteType() && 10324 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10325 BaseToDerivedConversion = 3; 10326 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 10327 ToTy.getNonReferenceType().getCanonicalType() == 10328 FromTy.getNonReferenceType().getCanonicalType()) { 10329 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10330 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10331 << (unsigned)isObjectArgument << I + 1 10332 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10333 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10334 return; 10335 } 10336 } 10337 10338 if (BaseToDerivedConversion) { 10339 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10340 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10341 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10342 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10343 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10344 return; 10345 } 10346 10347 if (isa<ObjCObjectPointerType>(CFromTy) && 10348 isa<PointerType>(CToTy)) { 10349 Qualifiers FromQs = CFromTy.getQualifiers(); 10350 Qualifiers ToQs = CToTy.getQualifiers(); 10351 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10352 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10353 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10354 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10355 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10356 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10357 return; 10358 } 10359 } 10360 10361 if (TakingCandidateAddress && 10362 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10363 return; 10364 10365 // Emit the generic diagnostic and, optionally, add the hints to it. 10366 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10367 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10368 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10369 << ToTy << (unsigned)isObjectArgument << I + 1 10370 << (unsigned)(Cand->Fix.Kind); 10371 10372 // If we can fix the conversion, suggest the FixIts. 10373 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10374 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10375 FDiag << *HI; 10376 S.Diag(Fn->getLocation(), FDiag); 10377 10378 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10379 } 10380 10381 /// Additional arity mismatch diagnosis specific to a function overload 10382 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10383 /// over a candidate in any candidate set. 10384 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10385 unsigned NumArgs) { 10386 FunctionDecl *Fn = Cand->Function; 10387 unsigned MinParams = Fn->getMinRequiredArguments(); 10388 10389 // With invalid overloaded operators, it's possible that we think we 10390 // have an arity mismatch when in fact it looks like we have the 10391 // right number of arguments, because only overloaded operators have 10392 // the weird behavior of overloading member and non-member functions. 10393 // Just don't report anything. 10394 if (Fn->isInvalidDecl() && 10395 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10396 return true; 10397 10398 if (NumArgs < MinParams) { 10399 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10400 (Cand->FailureKind == ovl_fail_bad_deduction && 10401 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10402 } else { 10403 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10404 (Cand->FailureKind == ovl_fail_bad_deduction && 10405 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10406 } 10407 10408 return false; 10409 } 10410 10411 /// General arity mismatch diagnosis over a candidate in a candidate set. 10412 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10413 unsigned NumFormalArgs) { 10414 assert(isa<FunctionDecl>(D) && 10415 "The templated declaration should at least be a function" 10416 " when diagnosing bad template argument deduction due to too many" 10417 " or too few arguments"); 10418 10419 FunctionDecl *Fn = cast<FunctionDecl>(D); 10420 10421 // TODO: treat calls to a missing default constructor as a special case 10422 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10423 unsigned MinParams = Fn->getMinRequiredArguments(); 10424 10425 // at least / at most / exactly 10426 unsigned mode, modeCount; 10427 if (NumFormalArgs < MinParams) { 10428 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10429 FnTy->isTemplateVariadic()) 10430 mode = 0; // "at least" 10431 else 10432 mode = 2; // "exactly" 10433 modeCount = MinParams; 10434 } else { 10435 if (MinParams != FnTy->getNumParams()) 10436 mode = 1; // "at most" 10437 else 10438 mode = 2; // "exactly" 10439 modeCount = FnTy->getNumParams(); 10440 } 10441 10442 std::string Description; 10443 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10444 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10445 10446 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10447 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10448 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10449 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10450 else 10451 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10452 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10453 << Description << mode << modeCount << NumFormalArgs; 10454 10455 MaybeEmitInheritedConstructorNote(S, Found); 10456 } 10457 10458 /// Arity mismatch diagnosis specific to a function overload candidate. 10459 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10460 unsigned NumFormalArgs) { 10461 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10462 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10463 } 10464 10465 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10466 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10467 return TD; 10468 llvm_unreachable("Unsupported: Getting the described template declaration" 10469 " for bad deduction diagnosis"); 10470 } 10471 10472 /// Diagnose a failed template-argument deduction. 10473 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10474 DeductionFailureInfo &DeductionFailure, 10475 unsigned NumArgs, 10476 bool TakingCandidateAddress) { 10477 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10478 NamedDecl *ParamD; 10479 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10480 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10481 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10482 switch (DeductionFailure.Result) { 10483 case Sema::TDK_Success: 10484 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10485 10486 case Sema::TDK_Incomplete: { 10487 assert(ParamD && "no parameter found for incomplete deduction result"); 10488 S.Diag(Templated->getLocation(), 10489 diag::note_ovl_candidate_incomplete_deduction) 10490 << ParamD->getDeclName(); 10491 MaybeEmitInheritedConstructorNote(S, Found); 10492 return; 10493 } 10494 10495 case Sema::TDK_IncompletePack: { 10496 assert(ParamD && "no parameter found for incomplete deduction result"); 10497 S.Diag(Templated->getLocation(), 10498 diag::note_ovl_candidate_incomplete_deduction_pack) 10499 << ParamD->getDeclName() 10500 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10501 << *DeductionFailure.getFirstArg(); 10502 MaybeEmitInheritedConstructorNote(S, Found); 10503 return; 10504 } 10505 10506 case Sema::TDK_Underqualified: { 10507 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10508 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10509 10510 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10511 10512 // Param will have been canonicalized, but it should just be a 10513 // qualified version of ParamD, so move the qualifiers to that. 10514 QualifierCollector Qs; 10515 Qs.strip(Param); 10516 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10517 assert(S.Context.hasSameType(Param, NonCanonParam)); 10518 10519 // Arg has also been canonicalized, but there's nothing we can do 10520 // about that. It also doesn't matter as much, because it won't 10521 // have any template parameters in it (because deduction isn't 10522 // done on dependent types). 10523 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10524 10525 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10526 << ParamD->getDeclName() << Arg << NonCanonParam; 10527 MaybeEmitInheritedConstructorNote(S, Found); 10528 return; 10529 } 10530 10531 case Sema::TDK_Inconsistent: { 10532 assert(ParamD && "no parameter found for inconsistent deduction result"); 10533 int which = 0; 10534 if (isa<TemplateTypeParmDecl>(ParamD)) 10535 which = 0; 10536 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10537 // Deduction might have failed because we deduced arguments of two 10538 // different types for a non-type template parameter. 10539 // FIXME: Use a different TDK value for this. 10540 QualType T1 = 10541 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10542 QualType T2 = 10543 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10544 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10545 S.Diag(Templated->getLocation(), 10546 diag::note_ovl_candidate_inconsistent_deduction_types) 10547 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10548 << *DeductionFailure.getSecondArg() << T2; 10549 MaybeEmitInheritedConstructorNote(S, Found); 10550 return; 10551 } 10552 10553 which = 1; 10554 } else { 10555 which = 2; 10556 } 10557 10558 // Tweak the diagnostic if the problem is that we deduced packs of 10559 // different arities. We'll print the actual packs anyway in case that 10560 // includes additional useful information. 10561 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10562 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10563 DeductionFailure.getFirstArg()->pack_size() != 10564 DeductionFailure.getSecondArg()->pack_size()) { 10565 which = 3; 10566 } 10567 10568 S.Diag(Templated->getLocation(), 10569 diag::note_ovl_candidate_inconsistent_deduction) 10570 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10571 << *DeductionFailure.getSecondArg(); 10572 MaybeEmitInheritedConstructorNote(S, Found); 10573 return; 10574 } 10575 10576 case Sema::TDK_InvalidExplicitArguments: 10577 assert(ParamD && "no parameter found for invalid explicit arguments"); 10578 if (ParamD->getDeclName()) 10579 S.Diag(Templated->getLocation(), 10580 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10581 << ParamD->getDeclName(); 10582 else { 10583 int index = 0; 10584 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10585 index = TTP->getIndex(); 10586 else if (NonTypeTemplateParmDecl *NTTP 10587 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10588 index = NTTP->getIndex(); 10589 else 10590 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10591 S.Diag(Templated->getLocation(), 10592 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10593 << (index + 1); 10594 } 10595 MaybeEmitInheritedConstructorNote(S, Found); 10596 return; 10597 10598 case Sema::TDK_ConstraintsNotSatisfied: { 10599 // Format the template argument list into the argument string. 10600 SmallString<128> TemplateArgString; 10601 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10602 TemplateArgString = " "; 10603 TemplateArgString += S.getTemplateArgumentBindingsText( 10604 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10605 if (TemplateArgString.size() == 1) 10606 TemplateArgString.clear(); 10607 S.Diag(Templated->getLocation(), 10608 diag::note_ovl_candidate_unsatisfied_constraints) 10609 << TemplateArgString; 10610 10611 S.DiagnoseUnsatisfiedConstraint( 10612 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10613 return; 10614 } 10615 case Sema::TDK_TooManyArguments: 10616 case Sema::TDK_TooFewArguments: 10617 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10618 return; 10619 10620 case Sema::TDK_InstantiationDepth: 10621 S.Diag(Templated->getLocation(), 10622 diag::note_ovl_candidate_instantiation_depth); 10623 MaybeEmitInheritedConstructorNote(S, Found); 10624 return; 10625 10626 case Sema::TDK_SubstitutionFailure: { 10627 // Format the template argument list into the argument string. 10628 SmallString<128> TemplateArgString; 10629 if (TemplateArgumentList *Args = 10630 DeductionFailure.getTemplateArgumentList()) { 10631 TemplateArgString = " "; 10632 TemplateArgString += S.getTemplateArgumentBindingsText( 10633 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10634 if (TemplateArgString.size() == 1) 10635 TemplateArgString.clear(); 10636 } 10637 10638 // If this candidate was disabled by enable_if, say so. 10639 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10640 if (PDiag && PDiag->second.getDiagID() == 10641 diag::err_typename_nested_not_found_enable_if) { 10642 // FIXME: Use the source range of the condition, and the fully-qualified 10643 // name of the enable_if template. These are both present in PDiag. 10644 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10645 << "'enable_if'" << TemplateArgString; 10646 return; 10647 } 10648 10649 // We found a specific requirement that disabled the enable_if. 10650 if (PDiag && PDiag->second.getDiagID() == 10651 diag::err_typename_nested_not_found_requirement) { 10652 S.Diag(Templated->getLocation(), 10653 diag::note_ovl_candidate_disabled_by_requirement) 10654 << PDiag->second.getStringArg(0) << TemplateArgString; 10655 return; 10656 } 10657 10658 // Format the SFINAE diagnostic into the argument string. 10659 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10660 // formatted message in another diagnostic. 10661 SmallString<128> SFINAEArgString; 10662 SourceRange R; 10663 if (PDiag) { 10664 SFINAEArgString = ": "; 10665 R = SourceRange(PDiag->first, PDiag->first); 10666 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10667 } 10668 10669 S.Diag(Templated->getLocation(), 10670 diag::note_ovl_candidate_substitution_failure) 10671 << TemplateArgString << SFINAEArgString << R; 10672 MaybeEmitInheritedConstructorNote(S, Found); 10673 return; 10674 } 10675 10676 case Sema::TDK_DeducedMismatch: 10677 case Sema::TDK_DeducedMismatchNested: { 10678 // Format the template argument list into the argument string. 10679 SmallString<128> TemplateArgString; 10680 if (TemplateArgumentList *Args = 10681 DeductionFailure.getTemplateArgumentList()) { 10682 TemplateArgString = " "; 10683 TemplateArgString += S.getTemplateArgumentBindingsText( 10684 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10685 if (TemplateArgString.size() == 1) 10686 TemplateArgString.clear(); 10687 } 10688 10689 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10690 << (*DeductionFailure.getCallArgIndex() + 1) 10691 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10692 << TemplateArgString 10693 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10694 break; 10695 } 10696 10697 case Sema::TDK_NonDeducedMismatch: { 10698 // FIXME: Provide a source location to indicate what we couldn't match. 10699 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10700 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10701 if (FirstTA.getKind() == TemplateArgument::Template && 10702 SecondTA.getKind() == TemplateArgument::Template) { 10703 TemplateName FirstTN = FirstTA.getAsTemplate(); 10704 TemplateName SecondTN = SecondTA.getAsTemplate(); 10705 if (FirstTN.getKind() == TemplateName::Template && 10706 SecondTN.getKind() == TemplateName::Template) { 10707 if (FirstTN.getAsTemplateDecl()->getName() == 10708 SecondTN.getAsTemplateDecl()->getName()) { 10709 // FIXME: This fixes a bad diagnostic where both templates are named 10710 // the same. This particular case is a bit difficult since: 10711 // 1) It is passed as a string to the diagnostic printer. 10712 // 2) The diagnostic printer only attempts to find a better 10713 // name for types, not decls. 10714 // Ideally, this should folded into the diagnostic printer. 10715 S.Diag(Templated->getLocation(), 10716 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10717 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10718 return; 10719 } 10720 } 10721 } 10722 10723 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10724 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10725 return; 10726 10727 // FIXME: For generic lambda parameters, check if the function is a lambda 10728 // call operator, and if so, emit a prettier and more informative 10729 // diagnostic that mentions 'auto' and lambda in addition to 10730 // (or instead of?) the canonical template type parameters. 10731 S.Diag(Templated->getLocation(), 10732 diag::note_ovl_candidate_non_deduced_mismatch) 10733 << FirstTA << SecondTA; 10734 return; 10735 } 10736 // TODO: diagnose these individually, then kill off 10737 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10738 case Sema::TDK_MiscellaneousDeductionFailure: 10739 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10740 MaybeEmitInheritedConstructorNote(S, Found); 10741 return; 10742 case Sema::TDK_CUDATargetMismatch: 10743 S.Diag(Templated->getLocation(), 10744 diag::note_cuda_ovl_candidate_target_mismatch); 10745 return; 10746 } 10747 } 10748 10749 /// Diagnose a failed template-argument deduction, for function calls. 10750 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10751 unsigned NumArgs, 10752 bool TakingCandidateAddress) { 10753 unsigned TDK = Cand->DeductionFailure.Result; 10754 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10755 if (CheckArityMismatch(S, Cand, NumArgs)) 10756 return; 10757 } 10758 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10759 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10760 } 10761 10762 /// CUDA: diagnose an invalid call across targets. 10763 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10764 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10765 FunctionDecl *Callee = Cand->Function; 10766 10767 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10768 CalleeTarget = S.IdentifyCUDATarget(Callee); 10769 10770 std::string FnDesc; 10771 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10772 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 10773 Cand->getRewriteKind(), FnDesc); 10774 10775 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10776 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10777 << FnDesc /* Ignored */ 10778 << CalleeTarget << CallerTarget; 10779 10780 // This could be an implicit constructor for which we could not infer the 10781 // target due to a collsion. Diagnose that case. 10782 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10783 if (Meth != nullptr && Meth->isImplicit()) { 10784 CXXRecordDecl *ParentClass = Meth->getParent(); 10785 Sema::CXXSpecialMember CSM; 10786 10787 switch (FnKindPair.first) { 10788 default: 10789 return; 10790 case oc_implicit_default_constructor: 10791 CSM = Sema::CXXDefaultConstructor; 10792 break; 10793 case oc_implicit_copy_constructor: 10794 CSM = Sema::CXXCopyConstructor; 10795 break; 10796 case oc_implicit_move_constructor: 10797 CSM = Sema::CXXMoveConstructor; 10798 break; 10799 case oc_implicit_copy_assignment: 10800 CSM = Sema::CXXCopyAssignment; 10801 break; 10802 case oc_implicit_move_assignment: 10803 CSM = Sema::CXXMoveAssignment; 10804 break; 10805 }; 10806 10807 bool ConstRHS = false; 10808 if (Meth->getNumParams()) { 10809 if (const ReferenceType *RT = 10810 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10811 ConstRHS = RT->getPointeeType().isConstQualified(); 10812 } 10813 } 10814 10815 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10816 /* ConstRHS */ ConstRHS, 10817 /* Diagnose */ true); 10818 } 10819 } 10820 10821 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10822 FunctionDecl *Callee = Cand->Function; 10823 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10824 10825 S.Diag(Callee->getLocation(), 10826 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10827 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10828 } 10829 10830 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10831 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 10832 assert(ES.isExplicit() && "not an explicit candidate"); 10833 10834 unsigned Kind; 10835 switch (Cand->Function->getDeclKind()) { 10836 case Decl::Kind::CXXConstructor: 10837 Kind = 0; 10838 break; 10839 case Decl::Kind::CXXConversion: 10840 Kind = 1; 10841 break; 10842 case Decl::Kind::CXXDeductionGuide: 10843 Kind = Cand->Function->isImplicit() ? 0 : 2; 10844 break; 10845 default: 10846 llvm_unreachable("invalid Decl"); 10847 } 10848 10849 // Note the location of the first (in-class) declaration; a redeclaration 10850 // (particularly an out-of-class definition) will typically lack the 10851 // 'explicit' specifier. 10852 // FIXME: This is probably a good thing to do for all 'candidate' notes. 10853 FunctionDecl *First = Cand->Function->getFirstDecl(); 10854 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 10855 First = Pattern->getFirstDecl(); 10856 10857 S.Diag(First->getLocation(), 10858 diag::note_ovl_candidate_explicit) 10859 << Kind << (ES.getExpr() ? 1 : 0) 10860 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 10861 } 10862 10863 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10864 FunctionDecl *Callee = Cand->Function; 10865 10866 S.Diag(Callee->getLocation(), 10867 diag::note_ovl_candidate_disabled_by_extension) 10868 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10869 } 10870 10871 /// Generates a 'note' diagnostic for an overload candidate. We've 10872 /// already generated a primary error at the call site. 10873 /// 10874 /// It really does need to be a single diagnostic with its caret 10875 /// pointed at the candidate declaration. Yes, this creates some 10876 /// major challenges of technical writing. Yes, this makes pointing 10877 /// out problems with specific arguments quite awkward. It's still 10878 /// better than generating twenty screens of text for every failed 10879 /// overload. 10880 /// 10881 /// It would be great to be able to express per-candidate problems 10882 /// more richly for those diagnostic clients that cared, but we'd 10883 /// still have to be just as careful with the default diagnostics. 10884 /// \param CtorDestAS Addr space of object being constructed (for ctor 10885 /// candidates only). 10886 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10887 unsigned NumArgs, 10888 bool TakingCandidateAddress, 10889 LangAS CtorDestAS = LangAS::Default) { 10890 FunctionDecl *Fn = Cand->Function; 10891 10892 // Note deleted candidates, but only if they're viable. 10893 if (Cand->Viable) { 10894 if (Fn->isDeleted()) { 10895 std::string FnDesc; 10896 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10897 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 10898 Cand->getRewriteKind(), FnDesc); 10899 10900 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10901 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10902 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10903 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10904 return; 10905 } 10906 10907 // We don't really have anything else to say about viable candidates. 10908 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10909 return; 10910 } 10911 10912 switch (Cand->FailureKind) { 10913 case ovl_fail_too_many_arguments: 10914 case ovl_fail_too_few_arguments: 10915 return DiagnoseArityMismatch(S, Cand, NumArgs); 10916 10917 case ovl_fail_bad_deduction: 10918 return DiagnoseBadDeduction(S, Cand, NumArgs, 10919 TakingCandidateAddress); 10920 10921 case ovl_fail_illegal_constructor: { 10922 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10923 << (Fn->getPrimaryTemplate() ? 1 : 0); 10924 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10925 return; 10926 } 10927 10928 case ovl_fail_object_addrspace_mismatch: { 10929 Qualifiers QualsForPrinting; 10930 QualsForPrinting.setAddressSpace(CtorDestAS); 10931 S.Diag(Fn->getLocation(), 10932 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 10933 << QualsForPrinting; 10934 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10935 return; 10936 } 10937 10938 case ovl_fail_trivial_conversion: 10939 case ovl_fail_bad_final_conversion: 10940 case ovl_fail_final_conversion_not_exact: 10941 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10942 10943 case ovl_fail_bad_conversion: { 10944 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10945 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10946 if (Cand->Conversions[I].isBad()) 10947 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10948 10949 // FIXME: this currently happens when we're called from SemaInit 10950 // when user-conversion overload fails. Figure out how to handle 10951 // those conditions and diagnose them well. 10952 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 10953 } 10954 10955 case ovl_fail_bad_target: 10956 return DiagnoseBadTarget(S, Cand); 10957 10958 case ovl_fail_enable_if: 10959 return DiagnoseFailedEnableIfAttr(S, Cand); 10960 10961 case ovl_fail_explicit: 10962 return DiagnoseFailedExplicitSpec(S, Cand); 10963 10964 case ovl_fail_ext_disabled: 10965 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10966 10967 case ovl_fail_inhctor_slice: 10968 // It's generally not interesting to note copy/move constructors here. 10969 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10970 return; 10971 S.Diag(Fn->getLocation(), 10972 diag::note_ovl_candidate_inherited_constructor_slice) 10973 << (Fn->getPrimaryTemplate() ? 1 : 0) 10974 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10975 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10976 return; 10977 10978 case ovl_fail_addr_not_available: { 10979 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10980 (void)Available; 10981 assert(!Available); 10982 break; 10983 } 10984 case ovl_non_default_multiversion_function: 10985 // Do nothing, these should simply be ignored. 10986 break; 10987 10988 case ovl_fail_constraints_not_satisfied: { 10989 std::string FnDesc; 10990 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10991 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 10992 Cand->getRewriteKind(), FnDesc); 10993 10994 S.Diag(Fn->getLocation(), 10995 diag::note_ovl_candidate_constraints_not_satisfied) 10996 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10997 << FnDesc /* Ignored */; 10998 ConstraintSatisfaction Satisfaction; 10999 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11000 break; 11001 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11002 } 11003 } 11004 } 11005 11006 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11007 // Desugar the type of the surrogate down to a function type, 11008 // retaining as many typedefs as possible while still showing 11009 // the function type (and, therefore, its parameter types). 11010 QualType FnType = Cand->Surrogate->getConversionType(); 11011 bool isLValueReference = false; 11012 bool isRValueReference = false; 11013 bool isPointer = false; 11014 if (const LValueReferenceType *FnTypeRef = 11015 FnType->getAs<LValueReferenceType>()) { 11016 FnType = FnTypeRef->getPointeeType(); 11017 isLValueReference = true; 11018 } else if (const RValueReferenceType *FnTypeRef = 11019 FnType->getAs<RValueReferenceType>()) { 11020 FnType = FnTypeRef->getPointeeType(); 11021 isRValueReference = true; 11022 } 11023 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11024 FnType = FnTypePtr->getPointeeType(); 11025 isPointer = true; 11026 } 11027 // Desugar down to a function type. 11028 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11029 // Reconstruct the pointer/reference as appropriate. 11030 if (isPointer) FnType = S.Context.getPointerType(FnType); 11031 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11032 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11033 11034 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11035 << FnType; 11036 } 11037 11038 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11039 SourceLocation OpLoc, 11040 OverloadCandidate *Cand) { 11041 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11042 std::string TypeStr("operator"); 11043 TypeStr += Opc; 11044 TypeStr += "("; 11045 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11046 if (Cand->Conversions.size() == 1) { 11047 TypeStr += ")"; 11048 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11049 } else { 11050 TypeStr += ", "; 11051 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11052 TypeStr += ")"; 11053 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11054 } 11055 } 11056 11057 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11058 OverloadCandidate *Cand) { 11059 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11060 if (ICS.isBad()) break; // all meaningless after first invalid 11061 if (!ICS.isAmbiguous()) continue; 11062 11063 ICS.DiagnoseAmbiguousConversion( 11064 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11065 } 11066 } 11067 11068 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11069 if (Cand->Function) 11070 return Cand->Function->getLocation(); 11071 if (Cand->IsSurrogate) 11072 return Cand->Surrogate->getLocation(); 11073 return SourceLocation(); 11074 } 11075 11076 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11077 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11078 case Sema::TDK_Success: 11079 case Sema::TDK_NonDependentConversionFailure: 11080 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11081 11082 case Sema::TDK_Invalid: 11083 case Sema::TDK_Incomplete: 11084 case Sema::TDK_IncompletePack: 11085 return 1; 11086 11087 case Sema::TDK_Underqualified: 11088 case Sema::TDK_Inconsistent: 11089 return 2; 11090 11091 case Sema::TDK_SubstitutionFailure: 11092 case Sema::TDK_DeducedMismatch: 11093 case Sema::TDK_ConstraintsNotSatisfied: 11094 case Sema::TDK_DeducedMismatchNested: 11095 case Sema::TDK_NonDeducedMismatch: 11096 case Sema::TDK_MiscellaneousDeductionFailure: 11097 case Sema::TDK_CUDATargetMismatch: 11098 return 3; 11099 11100 case Sema::TDK_InstantiationDepth: 11101 return 4; 11102 11103 case Sema::TDK_InvalidExplicitArguments: 11104 return 5; 11105 11106 case Sema::TDK_TooManyArguments: 11107 case Sema::TDK_TooFewArguments: 11108 return 6; 11109 } 11110 llvm_unreachable("Unhandled deduction result"); 11111 } 11112 11113 namespace { 11114 struct CompareOverloadCandidatesForDisplay { 11115 Sema &S; 11116 SourceLocation Loc; 11117 size_t NumArgs; 11118 OverloadCandidateSet::CandidateSetKind CSK; 11119 11120 CompareOverloadCandidatesForDisplay( 11121 Sema &S, SourceLocation Loc, size_t NArgs, 11122 OverloadCandidateSet::CandidateSetKind CSK) 11123 : S(S), NumArgs(NArgs), CSK(CSK) {} 11124 11125 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11126 // If there are too many or too few arguments, that's the high-order bit we 11127 // want to sort by, even if the immediate failure kind was something else. 11128 if (C->FailureKind == ovl_fail_too_many_arguments || 11129 C->FailureKind == ovl_fail_too_few_arguments) 11130 return static_cast<OverloadFailureKind>(C->FailureKind); 11131 11132 if (C->Function) { 11133 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11134 return ovl_fail_too_many_arguments; 11135 if (NumArgs < C->Function->getMinRequiredArguments()) 11136 return ovl_fail_too_few_arguments; 11137 } 11138 11139 return static_cast<OverloadFailureKind>(C->FailureKind); 11140 } 11141 11142 bool operator()(const OverloadCandidate *L, 11143 const OverloadCandidate *R) { 11144 // Fast-path this check. 11145 if (L == R) return false; 11146 11147 // Order first by viability. 11148 if (L->Viable) { 11149 if (!R->Viable) return true; 11150 11151 // TODO: introduce a tri-valued comparison for overload 11152 // candidates. Would be more worthwhile if we had a sort 11153 // that could exploit it. 11154 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11155 return true; 11156 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11157 return false; 11158 } else if (R->Viable) 11159 return false; 11160 11161 assert(L->Viable == R->Viable); 11162 11163 // Criteria by which we can sort non-viable candidates: 11164 if (!L->Viable) { 11165 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11166 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11167 11168 // 1. Arity mismatches come after other candidates. 11169 if (LFailureKind == ovl_fail_too_many_arguments || 11170 LFailureKind == ovl_fail_too_few_arguments) { 11171 if (RFailureKind == ovl_fail_too_many_arguments || 11172 RFailureKind == ovl_fail_too_few_arguments) { 11173 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11174 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11175 if (LDist == RDist) { 11176 if (LFailureKind == RFailureKind) 11177 // Sort non-surrogates before surrogates. 11178 return !L->IsSurrogate && R->IsSurrogate; 11179 // Sort candidates requiring fewer parameters than there were 11180 // arguments given after candidates requiring more parameters 11181 // than there were arguments given. 11182 return LFailureKind == ovl_fail_too_many_arguments; 11183 } 11184 return LDist < RDist; 11185 } 11186 return false; 11187 } 11188 if (RFailureKind == ovl_fail_too_many_arguments || 11189 RFailureKind == ovl_fail_too_few_arguments) 11190 return true; 11191 11192 // 2. Bad conversions come first and are ordered by the number 11193 // of bad conversions and quality of good conversions. 11194 if (LFailureKind == ovl_fail_bad_conversion) { 11195 if (RFailureKind != ovl_fail_bad_conversion) 11196 return true; 11197 11198 // The conversion that can be fixed with a smaller number of changes, 11199 // comes first. 11200 unsigned numLFixes = L->Fix.NumConversionsFixed; 11201 unsigned numRFixes = R->Fix.NumConversionsFixed; 11202 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11203 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11204 if (numLFixes != numRFixes) { 11205 return numLFixes < numRFixes; 11206 } 11207 11208 // If there's any ordering between the defined conversions... 11209 // FIXME: this might not be transitive. 11210 assert(L->Conversions.size() == R->Conversions.size()); 11211 11212 int leftBetter = 0; 11213 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11214 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11215 switch (CompareImplicitConversionSequences(S, Loc, 11216 L->Conversions[I], 11217 R->Conversions[I])) { 11218 case ImplicitConversionSequence::Better: 11219 leftBetter++; 11220 break; 11221 11222 case ImplicitConversionSequence::Worse: 11223 leftBetter--; 11224 break; 11225 11226 case ImplicitConversionSequence::Indistinguishable: 11227 break; 11228 } 11229 } 11230 if (leftBetter > 0) return true; 11231 if (leftBetter < 0) return false; 11232 11233 } else if (RFailureKind == ovl_fail_bad_conversion) 11234 return false; 11235 11236 if (LFailureKind == ovl_fail_bad_deduction) { 11237 if (RFailureKind != ovl_fail_bad_deduction) 11238 return true; 11239 11240 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11241 return RankDeductionFailure(L->DeductionFailure) 11242 < RankDeductionFailure(R->DeductionFailure); 11243 } else if (RFailureKind == ovl_fail_bad_deduction) 11244 return false; 11245 11246 // TODO: others? 11247 } 11248 11249 // Sort everything else by location. 11250 SourceLocation LLoc = GetLocationForCandidate(L); 11251 SourceLocation RLoc = GetLocationForCandidate(R); 11252 11253 // Put candidates without locations (e.g. builtins) at the end. 11254 if (LLoc.isInvalid()) return false; 11255 if (RLoc.isInvalid()) return true; 11256 11257 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11258 } 11259 }; 11260 } 11261 11262 /// CompleteNonViableCandidate - Normally, overload resolution only 11263 /// computes up to the first bad conversion. Produces the FixIt set if 11264 /// possible. 11265 static void 11266 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11267 ArrayRef<Expr *> Args, 11268 OverloadCandidateSet::CandidateSetKind CSK) { 11269 assert(!Cand->Viable); 11270 11271 // Don't do anything on failures other than bad conversion. 11272 if (Cand->FailureKind != ovl_fail_bad_conversion) 11273 return; 11274 11275 // We only want the FixIts if all the arguments can be corrected. 11276 bool Unfixable = false; 11277 // Use a implicit copy initialization to check conversion fixes. 11278 Cand->Fix.setConversionChecker(TryCopyInitialization); 11279 11280 // Attempt to fix the bad conversion. 11281 unsigned ConvCount = Cand->Conversions.size(); 11282 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11283 ++ConvIdx) { 11284 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11285 if (Cand->Conversions[ConvIdx].isInitialized() && 11286 Cand->Conversions[ConvIdx].isBad()) { 11287 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11288 break; 11289 } 11290 } 11291 11292 // FIXME: this should probably be preserved from the overload 11293 // operation somehow. 11294 bool SuppressUserConversions = false; 11295 11296 unsigned ConvIdx = 0; 11297 unsigned ArgIdx = 0; 11298 ArrayRef<QualType> ParamTypes; 11299 bool Reversed = Cand->RewriteKind & CRK_Reversed; 11300 11301 if (Cand->IsSurrogate) { 11302 QualType ConvType 11303 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11304 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11305 ConvType = ConvPtrType->getPointeeType(); 11306 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11307 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11308 ConvIdx = 1; 11309 } else if (Cand->Function) { 11310 ParamTypes = 11311 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11312 if (isa<CXXMethodDecl>(Cand->Function) && 11313 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11314 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11315 ConvIdx = 1; 11316 if (CSK == OverloadCandidateSet::CSK_Operator && 11317 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11318 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11319 ArgIdx = 1; 11320 } 11321 } else { 11322 // Builtin operator. 11323 assert(ConvCount <= 3); 11324 ParamTypes = Cand->BuiltinParamTypes; 11325 } 11326 11327 // Fill in the rest of the conversions. 11328 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11329 ConvIdx != ConvCount; 11330 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11331 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11332 if (Cand->Conversions[ConvIdx].isInitialized()) { 11333 // We've already checked this conversion. 11334 } else if (ParamIdx < ParamTypes.size()) { 11335 if (ParamTypes[ParamIdx]->isDependentType()) 11336 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11337 Args[ArgIdx]->getType()); 11338 else { 11339 Cand->Conversions[ConvIdx] = 11340 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11341 SuppressUserConversions, 11342 /*InOverloadResolution=*/true, 11343 /*AllowObjCWritebackConversion=*/ 11344 S.getLangOpts().ObjCAutoRefCount); 11345 // Store the FixIt in the candidate if it exists. 11346 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11347 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11348 } 11349 } else 11350 Cand->Conversions[ConvIdx].setEllipsis(); 11351 } 11352 } 11353 11354 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11355 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11356 SourceLocation OpLoc, 11357 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11358 // Sort the candidates by viability and position. Sorting directly would 11359 // be prohibitive, so we make a set of pointers and sort those. 11360 SmallVector<OverloadCandidate*, 32> Cands; 11361 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11362 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11363 if (!Filter(*Cand)) 11364 continue; 11365 switch (OCD) { 11366 case OCD_AllCandidates: 11367 if (!Cand->Viable) { 11368 if (!Cand->Function && !Cand->IsSurrogate) { 11369 // This a non-viable builtin candidate. We do not, in general, 11370 // want to list every possible builtin candidate. 11371 continue; 11372 } 11373 CompleteNonViableCandidate(S, Cand, Args, Kind); 11374 } 11375 break; 11376 11377 case OCD_ViableCandidates: 11378 if (!Cand->Viable) 11379 continue; 11380 break; 11381 11382 case OCD_AmbiguousCandidates: 11383 if (!Cand->Best) 11384 continue; 11385 break; 11386 } 11387 11388 Cands.push_back(Cand); 11389 } 11390 11391 llvm::stable_sort( 11392 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11393 11394 return Cands; 11395 } 11396 11397 /// When overload resolution fails, prints diagnostic messages containing the 11398 /// candidates in the candidate set. 11399 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11400 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11401 StringRef Opc, SourceLocation OpLoc, 11402 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11403 11404 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11405 11406 S.Diag(PD.first, PD.second); 11407 11408 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11409 11410 if (OCD == OCD_AmbiguousCandidates) 11411 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11412 } 11413 11414 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11415 ArrayRef<OverloadCandidate *> Cands, 11416 StringRef Opc, SourceLocation OpLoc) { 11417 bool ReportedAmbiguousConversions = false; 11418 11419 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11420 unsigned CandsShown = 0; 11421 auto I = Cands.begin(), E = Cands.end(); 11422 for (; I != E; ++I) { 11423 OverloadCandidate *Cand = *I; 11424 11425 // Set an arbitrary limit on the number of candidate functions we'll spam 11426 // the user with. FIXME: This limit should depend on details of the 11427 // candidate list. 11428 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11429 break; 11430 } 11431 ++CandsShown; 11432 11433 if (Cand->Function) 11434 NoteFunctionCandidate(S, Cand, Args.size(), 11435 /*TakingCandidateAddress=*/false, DestAS); 11436 else if (Cand->IsSurrogate) 11437 NoteSurrogateCandidate(S, Cand); 11438 else { 11439 assert(Cand->Viable && 11440 "Non-viable built-in candidates are not added to Cands."); 11441 // Generally we only see ambiguities including viable builtin 11442 // operators if overload resolution got screwed up by an 11443 // ambiguous user-defined conversion. 11444 // 11445 // FIXME: It's quite possible for different conversions to see 11446 // different ambiguities, though. 11447 if (!ReportedAmbiguousConversions) { 11448 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11449 ReportedAmbiguousConversions = true; 11450 } 11451 11452 // If this is a viable builtin, print it. 11453 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11454 } 11455 } 11456 11457 if (I != E) 11458 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11459 } 11460 11461 static SourceLocation 11462 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11463 return Cand->Specialization ? Cand->Specialization->getLocation() 11464 : SourceLocation(); 11465 } 11466 11467 namespace { 11468 struct CompareTemplateSpecCandidatesForDisplay { 11469 Sema &S; 11470 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11471 11472 bool operator()(const TemplateSpecCandidate *L, 11473 const TemplateSpecCandidate *R) { 11474 // Fast-path this check. 11475 if (L == R) 11476 return false; 11477 11478 // Assuming that both candidates are not matches... 11479 11480 // Sort by the ranking of deduction failures. 11481 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11482 return RankDeductionFailure(L->DeductionFailure) < 11483 RankDeductionFailure(R->DeductionFailure); 11484 11485 // Sort everything else by location. 11486 SourceLocation LLoc = GetLocationForCandidate(L); 11487 SourceLocation RLoc = GetLocationForCandidate(R); 11488 11489 // Put candidates without locations (e.g. builtins) at the end. 11490 if (LLoc.isInvalid()) 11491 return false; 11492 if (RLoc.isInvalid()) 11493 return true; 11494 11495 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11496 } 11497 }; 11498 } 11499 11500 /// Diagnose a template argument deduction failure. 11501 /// We are treating these failures as overload failures due to bad 11502 /// deductions. 11503 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11504 bool ForTakingAddress) { 11505 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11506 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11507 } 11508 11509 void TemplateSpecCandidateSet::destroyCandidates() { 11510 for (iterator i = begin(), e = end(); i != e; ++i) { 11511 i->DeductionFailure.Destroy(); 11512 } 11513 } 11514 11515 void TemplateSpecCandidateSet::clear() { 11516 destroyCandidates(); 11517 Candidates.clear(); 11518 } 11519 11520 /// NoteCandidates - When no template specialization match is found, prints 11521 /// diagnostic messages containing the non-matching specializations that form 11522 /// the candidate set. 11523 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11524 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11525 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11526 // Sort the candidates by position (assuming no candidate is a match). 11527 // Sorting directly would be prohibitive, so we make a set of pointers 11528 // and sort those. 11529 SmallVector<TemplateSpecCandidate *, 32> Cands; 11530 Cands.reserve(size()); 11531 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11532 if (Cand->Specialization) 11533 Cands.push_back(Cand); 11534 // Otherwise, this is a non-matching builtin candidate. We do not, 11535 // in general, want to list every possible builtin candidate. 11536 } 11537 11538 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11539 11540 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11541 // for generalization purposes (?). 11542 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11543 11544 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11545 unsigned CandsShown = 0; 11546 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11547 TemplateSpecCandidate *Cand = *I; 11548 11549 // Set an arbitrary limit on the number of candidates we'll spam 11550 // the user with. FIXME: This limit should depend on details of the 11551 // candidate list. 11552 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11553 break; 11554 ++CandsShown; 11555 11556 assert(Cand->Specialization && 11557 "Non-matching built-in candidates are not added to Cands."); 11558 Cand->NoteDeductionFailure(S, ForTakingAddress); 11559 } 11560 11561 if (I != E) 11562 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11563 } 11564 11565 // [PossiblyAFunctionType] --> [Return] 11566 // NonFunctionType --> NonFunctionType 11567 // R (A) --> R(A) 11568 // R (*)(A) --> R (A) 11569 // R (&)(A) --> R (A) 11570 // R (S::*)(A) --> R (A) 11571 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11572 QualType Ret = PossiblyAFunctionType; 11573 if (const PointerType *ToTypePtr = 11574 PossiblyAFunctionType->getAs<PointerType>()) 11575 Ret = ToTypePtr->getPointeeType(); 11576 else if (const ReferenceType *ToTypeRef = 11577 PossiblyAFunctionType->getAs<ReferenceType>()) 11578 Ret = ToTypeRef->getPointeeType(); 11579 else if (const MemberPointerType *MemTypePtr = 11580 PossiblyAFunctionType->getAs<MemberPointerType>()) 11581 Ret = MemTypePtr->getPointeeType(); 11582 Ret = 11583 Context.getCanonicalType(Ret).getUnqualifiedType(); 11584 return Ret; 11585 } 11586 11587 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11588 bool Complain = true) { 11589 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11590 S.DeduceReturnType(FD, Loc, Complain)) 11591 return true; 11592 11593 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11594 if (S.getLangOpts().CPlusPlus17 && 11595 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11596 !S.ResolveExceptionSpec(Loc, FPT)) 11597 return true; 11598 11599 return false; 11600 } 11601 11602 namespace { 11603 // A helper class to help with address of function resolution 11604 // - allows us to avoid passing around all those ugly parameters 11605 class AddressOfFunctionResolver { 11606 Sema& S; 11607 Expr* SourceExpr; 11608 const QualType& TargetType; 11609 QualType TargetFunctionType; // Extracted function type from target type 11610 11611 bool Complain; 11612 //DeclAccessPair& ResultFunctionAccessPair; 11613 ASTContext& Context; 11614 11615 bool TargetTypeIsNonStaticMemberFunction; 11616 bool FoundNonTemplateFunction; 11617 bool StaticMemberFunctionFromBoundPointer; 11618 bool HasComplained; 11619 11620 OverloadExpr::FindResult OvlExprInfo; 11621 OverloadExpr *OvlExpr; 11622 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11623 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11624 TemplateSpecCandidateSet FailedCandidates; 11625 11626 public: 11627 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11628 const QualType &TargetType, bool Complain) 11629 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11630 Complain(Complain), Context(S.getASTContext()), 11631 TargetTypeIsNonStaticMemberFunction( 11632 !!TargetType->getAs<MemberPointerType>()), 11633 FoundNonTemplateFunction(false), 11634 StaticMemberFunctionFromBoundPointer(false), 11635 HasComplained(false), 11636 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11637 OvlExpr(OvlExprInfo.Expression), 11638 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11639 ExtractUnqualifiedFunctionTypeFromTargetType(); 11640 11641 if (TargetFunctionType->isFunctionType()) { 11642 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11643 if (!UME->isImplicitAccess() && 11644 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11645 StaticMemberFunctionFromBoundPointer = true; 11646 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11647 DeclAccessPair dap; 11648 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11649 OvlExpr, false, &dap)) { 11650 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11651 if (!Method->isStatic()) { 11652 // If the target type is a non-function type and the function found 11653 // is a non-static member function, pretend as if that was the 11654 // target, it's the only possible type to end up with. 11655 TargetTypeIsNonStaticMemberFunction = true; 11656 11657 // And skip adding the function if its not in the proper form. 11658 // We'll diagnose this due to an empty set of functions. 11659 if (!OvlExprInfo.HasFormOfMemberPointer) 11660 return; 11661 } 11662 11663 Matches.push_back(std::make_pair(dap, Fn)); 11664 } 11665 return; 11666 } 11667 11668 if (OvlExpr->hasExplicitTemplateArgs()) 11669 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11670 11671 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11672 // C++ [over.over]p4: 11673 // If more than one function is selected, [...] 11674 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11675 if (FoundNonTemplateFunction) 11676 EliminateAllTemplateMatches(); 11677 else 11678 EliminateAllExceptMostSpecializedTemplate(); 11679 } 11680 } 11681 11682 if (S.getLangOpts().CUDA && Matches.size() > 1) 11683 EliminateSuboptimalCudaMatches(); 11684 } 11685 11686 bool hasComplained() const { return HasComplained; } 11687 11688 private: 11689 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11690 QualType Discard; 11691 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11692 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11693 } 11694 11695 /// \return true if A is considered a better overload candidate for the 11696 /// desired type than B. 11697 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11698 // If A doesn't have exactly the correct type, we don't want to classify it 11699 // as "better" than anything else. This way, the user is required to 11700 // disambiguate for us if there are multiple candidates and no exact match. 11701 return candidateHasExactlyCorrectType(A) && 11702 (!candidateHasExactlyCorrectType(B) || 11703 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11704 } 11705 11706 /// \return true if we were able to eliminate all but one overload candidate, 11707 /// false otherwise. 11708 bool eliminiateSuboptimalOverloadCandidates() { 11709 // Same algorithm as overload resolution -- one pass to pick the "best", 11710 // another pass to be sure that nothing is better than the best. 11711 auto Best = Matches.begin(); 11712 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11713 if (isBetterCandidate(I->second, Best->second)) 11714 Best = I; 11715 11716 const FunctionDecl *BestFn = Best->second; 11717 auto IsBestOrInferiorToBest = [this, BestFn]( 11718 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11719 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11720 }; 11721 11722 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11723 // option, so we can potentially give the user a better error 11724 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11725 return false; 11726 Matches[0] = *Best; 11727 Matches.resize(1); 11728 return true; 11729 } 11730 11731 bool isTargetTypeAFunction() const { 11732 return TargetFunctionType->isFunctionType(); 11733 } 11734 11735 // [ToType] [Return] 11736 11737 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11738 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11739 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11740 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11741 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11742 } 11743 11744 // return true if any matching specializations were found 11745 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11746 const DeclAccessPair& CurAccessFunPair) { 11747 if (CXXMethodDecl *Method 11748 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11749 // Skip non-static function templates when converting to pointer, and 11750 // static when converting to member pointer. 11751 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11752 return false; 11753 } 11754 else if (TargetTypeIsNonStaticMemberFunction) 11755 return false; 11756 11757 // C++ [over.over]p2: 11758 // If the name is a function template, template argument deduction is 11759 // done (14.8.2.2), and if the argument deduction succeeds, the 11760 // resulting template argument list is used to generate a single 11761 // function template specialization, which is added to the set of 11762 // overloaded functions considered. 11763 FunctionDecl *Specialization = nullptr; 11764 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11765 if (Sema::TemplateDeductionResult Result 11766 = S.DeduceTemplateArguments(FunctionTemplate, 11767 &OvlExplicitTemplateArgs, 11768 TargetFunctionType, Specialization, 11769 Info, /*IsAddressOfFunction*/true)) { 11770 // Make a note of the failed deduction for diagnostics. 11771 FailedCandidates.addCandidate() 11772 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11773 MakeDeductionFailureInfo(Context, Result, Info)); 11774 return false; 11775 } 11776 11777 // Template argument deduction ensures that we have an exact match or 11778 // compatible pointer-to-function arguments that would be adjusted by ICS. 11779 // This function template specicalization works. 11780 assert(S.isSameOrCompatibleFunctionType( 11781 Context.getCanonicalType(Specialization->getType()), 11782 Context.getCanonicalType(TargetFunctionType))); 11783 11784 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11785 return false; 11786 11787 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11788 return true; 11789 } 11790 11791 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11792 const DeclAccessPair& CurAccessFunPair) { 11793 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11794 // Skip non-static functions when converting to pointer, and static 11795 // when converting to member pointer. 11796 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11797 return false; 11798 } 11799 else if (TargetTypeIsNonStaticMemberFunction) 11800 return false; 11801 11802 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11803 if (S.getLangOpts().CUDA) 11804 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11805 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11806 return false; 11807 if (FunDecl->isMultiVersion()) { 11808 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11809 if (TA && !TA->isDefaultVersion()) 11810 return false; 11811 } 11812 11813 // If any candidate has a placeholder return type, trigger its deduction 11814 // now. 11815 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11816 Complain)) { 11817 HasComplained |= Complain; 11818 return false; 11819 } 11820 11821 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11822 return false; 11823 11824 // If we're in C, we need to support types that aren't exactly identical. 11825 if (!S.getLangOpts().CPlusPlus || 11826 candidateHasExactlyCorrectType(FunDecl)) { 11827 Matches.push_back(std::make_pair( 11828 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11829 FoundNonTemplateFunction = true; 11830 return true; 11831 } 11832 } 11833 11834 return false; 11835 } 11836 11837 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11838 bool Ret = false; 11839 11840 // If the overload expression doesn't have the form of a pointer to 11841 // member, don't try to convert it to a pointer-to-member type. 11842 if (IsInvalidFormOfPointerToMemberFunction()) 11843 return false; 11844 11845 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11846 E = OvlExpr->decls_end(); 11847 I != E; ++I) { 11848 // Look through any using declarations to find the underlying function. 11849 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11850 11851 // C++ [over.over]p3: 11852 // Non-member functions and static member functions match 11853 // targets of type "pointer-to-function" or "reference-to-function." 11854 // Nonstatic member functions match targets of 11855 // type "pointer-to-member-function." 11856 // Note that according to DR 247, the containing class does not matter. 11857 if (FunctionTemplateDecl *FunctionTemplate 11858 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11859 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11860 Ret = true; 11861 } 11862 // If we have explicit template arguments supplied, skip non-templates. 11863 else if (!OvlExpr->hasExplicitTemplateArgs() && 11864 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11865 Ret = true; 11866 } 11867 assert(Ret || Matches.empty()); 11868 return Ret; 11869 } 11870 11871 void EliminateAllExceptMostSpecializedTemplate() { 11872 // [...] and any given function template specialization F1 is 11873 // eliminated if the set contains a second function template 11874 // specialization whose function template is more specialized 11875 // than the function template of F1 according to the partial 11876 // ordering rules of 14.5.5.2. 11877 11878 // The algorithm specified above is quadratic. We instead use a 11879 // two-pass algorithm (similar to the one used to identify the 11880 // best viable function in an overload set) that identifies the 11881 // best function template (if it exists). 11882 11883 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11884 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11885 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11886 11887 // TODO: It looks like FailedCandidates does not serve much purpose 11888 // here, since the no_viable diagnostic has index 0. 11889 UnresolvedSetIterator Result = S.getMostSpecialized( 11890 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11891 SourceExpr->getBeginLoc(), S.PDiag(), 11892 S.PDiag(diag::err_addr_ovl_ambiguous) 11893 << Matches[0].second->getDeclName(), 11894 S.PDiag(diag::note_ovl_candidate) 11895 << (unsigned)oc_function << (unsigned)ocs_described_template, 11896 Complain, TargetFunctionType); 11897 11898 if (Result != MatchesCopy.end()) { 11899 // Make it the first and only element 11900 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11901 Matches[0].second = cast<FunctionDecl>(*Result); 11902 Matches.resize(1); 11903 } else 11904 HasComplained |= Complain; 11905 } 11906 11907 void EliminateAllTemplateMatches() { 11908 // [...] any function template specializations in the set are 11909 // eliminated if the set also contains a non-template function, [...] 11910 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11911 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11912 ++I; 11913 else { 11914 Matches[I] = Matches[--N]; 11915 Matches.resize(N); 11916 } 11917 } 11918 } 11919 11920 void EliminateSuboptimalCudaMatches() { 11921 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11922 } 11923 11924 public: 11925 void ComplainNoMatchesFound() const { 11926 assert(Matches.empty()); 11927 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11928 << OvlExpr->getName() << TargetFunctionType 11929 << OvlExpr->getSourceRange(); 11930 if (FailedCandidates.empty()) 11931 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11932 /*TakingAddress=*/true); 11933 else { 11934 // We have some deduction failure messages. Use them to diagnose 11935 // the function templates, and diagnose the non-template candidates 11936 // normally. 11937 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11938 IEnd = OvlExpr->decls_end(); 11939 I != IEnd; ++I) 11940 if (FunctionDecl *Fun = 11941 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11942 if (!functionHasPassObjectSizeParams(Fun)) 11943 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 11944 /*TakingAddress=*/true); 11945 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11946 } 11947 } 11948 11949 bool IsInvalidFormOfPointerToMemberFunction() const { 11950 return TargetTypeIsNonStaticMemberFunction && 11951 !OvlExprInfo.HasFormOfMemberPointer; 11952 } 11953 11954 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11955 // TODO: Should we condition this on whether any functions might 11956 // have matched, or is it more appropriate to do that in callers? 11957 // TODO: a fixit wouldn't hurt. 11958 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11959 << TargetType << OvlExpr->getSourceRange(); 11960 } 11961 11962 bool IsStaticMemberFunctionFromBoundPointer() const { 11963 return StaticMemberFunctionFromBoundPointer; 11964 } 11965 11966 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11967 S.Diag(OvlExpr->getBeginLoc(), 11968 diag::err_invalid_form_pointer_member_function) 11969 << OvlExpr->getSourceRange(); 11970 } 11971 11972 void ComplainOfInvalidConversion() const { 11973 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11974 << OvlExpr->getName() << TargetType; 11975 } 11976 11977 void ComplainMultipleMatchesFound() const { 11978 assert(Matches.size() > 1); 11979 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11980 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11981 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11982 /*TakingAddress=*/true); 11983 } 11984 11985 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11986 11987 int getNumMatches() const { return Matches.size(); } 11988 11989 FunctionDecl* getMatchingFunctionDecl() const { 11990 if (Matches.size() != 1) return nullptr; 11991 return Matches[0].second; 11992 } 11993 11994 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11995 if (Matches.size() != 1) return nullptr; 11996 return &Matches[0].first; 11997 } 11998 }; 11999 } 12000 12001 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12002 /// an overloaded function (C++ [over.over]), where @p From is an 12003 /// expression with overloaded function type and @p ToType is the type 12004 /// we're trying to resolve to. For example: 12005 /// 12006 /// @code 12007 /// int f(double); 12008 /// int f(int); 12009 /// 12010 /// int (*pfd)(double) = f; // selects f(double) 12011 /// @endcode 12012 /// 12013 /// This routine returns the resulting FunctionDecl if it could be 12014 /// resolved, and NULL otherwise. When @p Complain is true, this 12015 /// routine will emit diagnostics if there is an error. 12016 FunctionDecl * 12017 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12018 QualType TargetType, 12019 bool Complain, 12020 DeclAccessPair &FoundResult, 12021 bool *pHadMultipleCandidates) { 12022 assert(AddressOfExpr->getType() == Context.OverloadTy); 12023 12024 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12025 Complain); 12026 int NumMatches = Resolver.getNumMatches(); 12027 FunctionDecl *Fn = nullptr; 12028 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12029 if (NumMatches == 0 && ShouldComplain) { 12030 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12031 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12032 else 12033 Resolver.ComplainNoMatchesFound(); 12034 } 12035 else if (NumMatches > 1 && ShouldComplain) 12036 Resolver.ComplainMultipleMatchesFound(); 12037 else if (NumMatches == 1) { 12038 Fn = Resolver.getMatchingFunctionDecl(); 12039 assert(Fn); 12040 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12041 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12042 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12043 if (Complain) { 12044 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12045 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12046 else 12047 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12048 } 12049 } 12050 12051 if (pHadMultipleCandidates) 12052 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12053 return Fn; 12054 } 12055 12056 /// Given an expression that refers to an overloaded function, try to 12057 /// resolve that function to a single function that can have its address taken. 12058 /// This will modify `Pair` iff it returns non-null. 12059 /// 12060 /// This routine can only succeed if from all of the candidates in the overload 12061 /// set for SrcExpr that can have their addresses taken, there is one candidate 12062 /// that is more constrained than the rest. 12063 FunctionDecl * 12064 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12065 OverloadExpr::FindResult R = OverloadExpr::find(E); 12066 OverloadExpr *Ovl = R.Expression; 12067 bool IsResultAmbiguous = false; 12068 FunctionDecl *Result = nullptr; 12069 DeclAccessPair DAP; 12070 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12071 12072 auto CheckMoreConstrained = 12073 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12074 SmallVector<const Expr *, 1> AC1, AC2; 12075 FD1->getAssociatedConstraints(AC1); 12076 FD2->getAssociatedConstraints(AC2); 12077 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12078 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12079 return None; 12080 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12081 return None; 12082 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12083 return None; 12084 return AtLeastAsConstrained1; 12085 }; 12086 12087 // Don't use the AddressOfResolver because we're specifically looking for 12088 // cases where we have one overload candidate that lacks 12089 // enable_if/pass_object_size/... 12090 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12091 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12092 if (!FD) 12093 return nullptr; 12094 12095 if (!checkAddressOfFunctionIsAvailable(FD)) 12096 continue; 12097 12098 // We have more than one result - see if it is more constrained than the 12099 // previous one. 12100 if (Result) { 12101 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12102 Result); 12103 if (!MoreConstrainedThanPrevious) { 12104 IsResultAmbiguous = true; 12105 AmbiguousDecls.push_back(FD); 12106 continue; 12107 } 12108 if (!*MoreConstrainedThanPrevious) 12109 continue; 12110 // FD is more constrained - replace Result with it. 12111 } 12112 IsResultAmbiguous = false; 12113 DAP = I.getPair(); 12114 Result = FD; 12115 } 12116 12117 if (IsResultAmbiguous) 12118 return nullptr; 12119 12120 if (Result) { 12121 SmallVector<const Expr *, 1> ResultAC; 12122 // We skipped over some ambiguous declarations which might be ambiguous with 12123 // the selected result. 12124 for (FunctionDecl *Skipped : AmbiguousDecls) 12125 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12126 return nullptr; 12127 Pair = DAP; 12128 } 12129 return Result; 12130 } 12131 12132 /// Given an overloaded function, tries to turn it into a non-overloaded 12133 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12134 /// will perform access checks, diagnose the use of the resultant decl, and, if 12135 /// requested, potentially perform a function-to-pointer decay. 12136 /// 12137 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12138 /// Otherwise, returns true. This may emit diagnostics and return true. 12139 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12140 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12141 Expr *E = SrcExpr.get(); 12142 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12143 12144 DeclAccessPair DAP; 12145 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12146 if (!Found || Found->isCPUDispatchMultiVersion() || 12147 Found->isCPUSpecificMultiVersion()) 12148 return false; 12149 12150 // Emitting multiple diagnostics for a function that is both inaccessible and 12151 // unavailable is consistent with our behavior elsewhere. So, always check 12152 // for both. 12153 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12154 CheckAddressOfMemberAccess(E, DAP); 12155 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12156 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12157 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12158 else 12159 SrcExpr = Fixed; 12160 return true; 12161 } 12162 12163 /// Given an expression that refers to an overloaded function, try to 12164 /// resolve that overloaded function expression down to a single function. 12165 /// 12166 /// This routine can only resolve template-ids that refer to a single function 12167 /// template, where that template-id refers to a single template whose template 12168 /// arguments are either provided by the template-id or have defaults, 12169 /// as described in C++0x [temp.arg.explicit]p3. 12170 /// 12171 /// If no template-ids are found, no diagnostics are emitted and NULL is 12172 /// returned. 12173 FunctionDecl * 12174 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12175 bool Complain, 12176 DeclAccessPair *FoundResult) { 12177 // C++ [over.over]p1: 12178 // [...] [Note: any redundant set of parentheses surrounding the 12179 // overloaded function name is ignored (5.1). ] 12180 // C++ [over.over]p1: 12181 // [...] The overloaded function name can be preceded by the & 12182 // operator. 12183 12184 // If we didn't actually find any template-ids, we're done. 12185 if (!ovl->hasExplicitTemplateArgs()) 12186 return nullptr; 12187 12188 TemplateArgumentListInfo ExplicitTemplateArgs; 12189 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12190 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12191 12192 // Look through all of the overloaded functions, searching for one 12193 // whose type matches exactly. 12194 FunctionDecl *Matched = nullptr; 12195 for (UnresolvedSetIterator I = ovl->decls_begin(), 12196 E = ovl->decls_end(); I != E; ++I) { 12197 // C++0x [temp.arg.explicit]p3: 12198 // [...] In contexts where deduction is done and fails, or in contexts 12199 // where deduction is not done, if a template argument list is 12200 // specified and it, along with any default template arguments, 12201 // identifies a single function template specialization, then the 12202 // template-id is an lvalue for the function template specialization. 12203 FunctionTemplateDecl *FunctionTemplate 12204 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12205 12206 // C++ [over.over]p2: 12207 // If the name is a function template, template argument deduction is 12208 // done (14.8.2.2), and if the argument deduction succeeds, the 12209 // resulting template argument list is used to generate a single 12210 // function template specialization, which is added to the set of 12211 // overloaded functions considered. 12212 FunctionDecl *Specialization = nullptr; 12213 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12214 if (TemplateDeductionResult Result 12215 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12216 Specialization, Info, 12217 /*IsAddressOfFunction*/true)) { 12218 // Make a note of the failed deduction for diagnostics. 12219 // TODO: Actually use the failed-deduction info? 12220 FailedCandidates.addCandidate() 12221 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12222 MakeDeductionFailureInfo(Context, Result, Info)); 12223 continue; 12224 } 12225 12226 assert(Specialization && "no specialization and no error?"); 12227 12228 // Multiple matches; we can't resolve to a single declaration. 12229 if (Matched) { 12230 if (Complain) { 12231 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12232 << ovl->getName(); 12233 NoteAllOverloadCandidates(ovl); 12234 } 12235 return nullptr; 12236 } 12237 12238 Matched = Specialization; 12239 if (FoundResult) *FoundResult = I.getPair(); 12240 } 12241 12242 if (Matched && 12243 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12244 return nullptr; 12245 12246 return Matched; 12247 } 12248 12249 // Resolve and fix an overloaded expression that can be resolved 12250 // because it identifies a single function template specialization. 12251 // 12252 // Last three arguments should only be supplied if Complain = true 12253 // 12254 // Return true if it was logically possible to so resolve the 12255 // expression, regardless of whether or not it succeeded. Always 12256 // returns true if 'complain' is set. 12257 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12258 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12259 bool complain, SourceRange OpRangeForComplaining, 12260 QualType DestTypeForComplaining, 12261 unsigned DiagIDForComplaining) { 12262 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12263 12264 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12265 12266 DeclAccessPair found; 12267 ExprResult SingleFunctionExpression; 12268 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12269 ovl.Expression, /*complain*/ false, &found)) { 12270 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12271 SrcExpr = ExprError(); 12272 return true; 12273 } 12274 12275 // It is only correct to resolve to an instance method if we're 12276 // resolving a form that's permitted to be a pointer to member. 12277 // Otherwise we'll end up making a bound member expression, which 12278 // is illegal in all the contexts we resolve like this. 12279 if (!ovl.HasFormOfMemberPointer && 12280 isa<CXXMethodDecl>(fn) && 12281 cast<CXXMethodDecl>(fn)->isInstance()) { 12282 if (!complain) return false; 12283 12284 Diag(ovl.Expression->getExprLoc(), 12285 diag::err_bound_member_function) 12286 << 0 << ovl.Expression->getSourceRange(); 12287 12288 // TODO: I believe we only end up here if there's a mix of 12289 // static and non-static candidates (otherwise the expression 12290 // would have 'bound member' type, not 'overload' type). 12291 // Ideally we would note which candidate was chosen and why 12292 // the static candidates were rejected. 12293 SrcExpr = ExprError(); 12294 return true; 12295 } 12296 12297 // Fix the expression to refer to 'fn'. 12298 SingleFunctionExpression = 12299 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12300 12301 // If desired, do function-to-pointer decay. 12302 if (doFunctionPointerConverion) { 12303 SingleFunctionExpression = 12304 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12305 if (SingleFunctionExpression.isInvalid()) { 12306 SrcExpr = ExprError(); 12307 return true; 12308 } 12309 } 12310 } 12311 12312 if (!SingleFunctionExpression.isUsable()) { 12313 if (complain) { 12314 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12315 << ovl.Expression->getName() 12316 << DestTypeForComplaining 12317 << OpRangeForComplaining 12318 << ovl.Expression->getQualifierLoc().getSourceRange(); 12319 NoteAllOverloadCandidates(SrcExpr.get()); 12320 12321 SrcExpr = ExprError(); 12322 return true; 12323 } 12324 12325 return false; 12326 } 12327 12328 SrcExpr = SingleFunctionExpression; 12329 return true; 12330 } 12331 12332 /// Add a single candidate to the overload set. 12333 static void AddOverloadedCallCandidate(Sema &S, 12334 DeclAccessPair FoundDecl, 12335 TemplateArgumentListInfo *ExplicitTemplateArgs, 12336 ArrayRef<Expr *> Args, 12337 OverloadCandidateSet &CandidateSet, 12338 bool PartialOverloading, 12339 bool KnownValid) { 12340 NamedDecl *Callee = FoundDecl.getDecl(); 12341 if (isa<UsingShadowDecl>(Callee)) 12342 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12343 12344 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12345 if (ExplicitTemplateArgs) { 12346 assert(!KnownValid && "Explicit template arguments?"); 12347 return; 12348 } 12349 // Prevent ill-formed function decls to be added as overload candidates. 12350 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12351 return; 12352 12353 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12354 /*SuppressUserConversions=*/false, 12355 PartialOverloading); 12356 return; 12357 } 12358 12359 if (FunctionTemplateDecl *FuncTemplate 12360 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12361 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12362 ExplicitTemplateArgs, Args, CandidateSet, 12363 /*SuppressUserConversions=*/false, 12364 PartialOverloading); 12365 return; 12366 } 12367 12368 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12369 } 12370 12371 /// Add the overload candidates named by callee and/or found by argument 12372 /// dependent lookup to the given overload set. 12373 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12374 ArrayRef<Expr *> Args, 12375 OverloadCandidateSet &CandidateSet, 12376 bool PartialOverloading) { 12377 12378 #ifndef NDEBUG 12379 // Verify that ArgumentDependentLookup is consistent with the rules 12380 // in C++0x [basic.lookup.argdep]p3: 12381 // 12382 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12383 // and let Y be the lookup set produced by argument dependent 12384 // lookup (defined as follows). If X contains 12385 // 12386 // -- a declaration of a class member, or 12387 // 12388 // -- a block-scope function declaration that is not a 12389 // using-declaration, or 12390 // 12391 // -- a declaration that is neither a function or a function 12392 // template 12393 // 12394 // then Y is empty. 12395 12396 if (ULE->requiresADL()) { 12397 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12398 E = ULE->decls_end(); I != E; ++I) { 12399 assert(!(*I)->getDeclContext()->isRecord()); 12400 assert(isa<UsingShadowDecl>(*I) || 12401 !(*I)->getDeclContext()->isFunctionOrMethod()); 12402 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12403 } 12404 } 12405 #endif 12406 12407 // It would be nice to avoid this copy. 12408 TemplateArgumentListInfo TABuffer; 12409 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12410 if (ULE->hasExplicitTemplateArgs()) { 12411 ULE->copyTemplateArgumentsInto(TABuffer); 12412 ExplicitTemplateArgs = &TABuffer; 12413 } 12414 12415 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12416 E = ULE->decls_end(); I != E; ++I) 12417 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12418 CandidateSet, PartialOverloading, 12419 /*KnownValid*/ true); 12420 12421 if (ULE->requiresADL()) 12422 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12423 Args, ExplicitTemplateArgs, 12424 CandidateSet, PartialOverloading); 12425 } 12426 12427 /// Determine whether a declaration with the specified name could be moved into 12428 /// a different namespace. 12429 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12430 switch (Name.getCXXOverloadedOperator()) { 12431 case OO_New: case OO_Array_New: 12432 case OO_Delete: case OO_Array_Delete: 12433 return false; 12434 12435 default: 12436 return true; 12437 } 12438 } 12439 12440 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12441 /// template, where the non-dependent name was declared after the template 12442 /// was defined. This is common in code written for a compilers which do not 12443 /// correctly implement two-stage name lookup. 12444 /// 12445 /// Returns true if a viable candidate was found and a diagnostic was issued. 12446 static bool 12447 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12448 const CXXScopeSpec &SS, LookupResult &R, 12449 OverloadCandidateSet::CandidateSetKind CSK, 12450 TemplateArgumentListInfo *ExplicitTemplateArgs, 12451 ArrayRef<Expr *> Args, 12452 bool *DoDiagnoseEmptyLookup = nullptr) { 12453 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12454 return false; 12455 12456 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12457 if (DC->isTransparentContext()) 12458 continue; 12459 12460 SemaRef.LookupQualifiedName(R, DC); 12461 12462 if (!R.empty()) { 12463 R.suppressDiagnostics(); 12464 12465 if (isa<CXXRecordDecl>(DC)) { 12466 // Don't diagnose names we find in classes; we get much better 12467 // diagnostics for these from DiagnoseEmptyLookup. 12468 R.clear(); 12469 if (DoDiagnoseEmptyLookup) 12470 *DoDiagnoseEmptyLookup = true; 12471 return false; 12472 } 12473 12474 OverloadCandidateSet Candidates(FnLoc, CSK); 12475 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12476 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12477 ExplicitTemplateArgs, Args, 12478 Candidates, false, /*KnownValid*/ false); 12479 12480 OverloadCandidateSet::iterator Best; 12481 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12482 // No viable functions. Don't bother the user with notes for functions 12483 // which don't work and shouldn't be found anyway. 12484 R.clear(); 12485 return false; 12486 } 12487 12488 // Find the namespaces where ADL would have looked, and suggest 12489 // declaring the function there instead. 12490 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12491 Sema::AssociatedClassSet AssociatedClasses; 12492 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12493 AssociatedNamespaces, 12494 AssociatedClasses); 12495 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12496 if (canBeDeclaredInNamespace(R.getLookupName())) { 12497 DeclContext *Std = SemaRef.getStdNamespace(); 12498 for (Sema::AssociatedNamespaceSet::iterator 12499 it = AssociatedNamespaces.begin(), 12500 end = AssociatedNamespaces.end(); it != end; ++it) { 12501 // Never suggest declaring a function within namespace 'std'. 12502 if (Std && Std->Encloses(*it)) 12503 continue; 12504 12505 // Never suggest declaring a function within a namespace with a 12506 // reserved name, like __gnu_cxx. 12507 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12508 if (NS && 12509 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12510 continue; 12511 12512 SuggestedNamespaces.insert(*it); 12513 } 12514 } 12515 12516 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12517 << R.getLookupName(); 12518 if (SuggestedNamespaces.empty()) { 12519 SemaRef.Diag(Best->Function->getLocation(), 12520 diag::note_not_found_by_two_phase_lookup) 12521 << R.getLookupName() << 0; 12522 } else if (SuggestedNamespaces.size() == 1) { 12523 SemaRef.Diag(Best->Function->getLocation(), 12524 diag::note_not_found_by_two_phase_lookup) 12525 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12526 } else { 12527 // FIXME: It would be useful to list the associated namespaces here, 12528 // but the diagnostics infrastructure doesn't provide a way to produce 12529 // a localized representation of a list of items. 12530 SemaRef.Diag(Best->Function->getLocation(), 12531 diag::note_not_found_by_two_phase_lookup) 12532 << R.getLookupName() << 2; 12533 } 12534 12535 // Try to recover by calling this function. 12536 return true; 12537 } 12538 12539 R.clear(); 12540 } 12541 12542 return false; 12543 } 12544 12545 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12546 /// template, where the non-dependent operator was declared after the template 12547 /// was defined. 12548 /// 12549 /// Returns true if a viable candidate was found and a diagnostic was issued. 12550 static bool 12551 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12552 SourceLocation OpLoc, 12553 ArrayRef<Expr *> Args) { 12554 DeclarationName OpName = 12555 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12556 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12557 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12558 OverloadCandidateSet::CSK_Operator, 12559 /*ExplicitTemplateArgs=*/nullptr, Args); 12560 } 12561 12562 namespace { 12563 class BuildRecoveryCallExprRAII { 12564 Sema &SemaRef; 12565 public: 12566 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12567 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12568 SemaRef.IsBuildingRecoveryCallExpr = true; 12569 } 12570 12571 ~BuildRecoveryCallExprRAII() { 12572 SemaRef.IsBuildingRecoveryCallExpr = false; 12573 } 12574 }; 12575 12576 } 12577 12578 /// Attempts to recover from a call where no functions were found. 12579 /// 12580 /// Returns true if new candidates were found. 12581 static ExprResult 12582 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12583 UnresolvedLookupExpr *ULE, 12584 SourceLocation LParenLoc, 12585 MutableArrayRef<Expr *> Args, 12586 SourceLocation RParenLoc, 12587 bool EmptyLookup, bool AllowTypoCorrection) { 12588 // Do not try to recover if it is already building a recovery call. 12589 // This stops infinite loops for template instantiations like 12590 // 12591 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12592 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12593 // 12594 if (SemaRef.IsBuildingRecoveryCallExpr) 12595 return ExprError(); 12596 BuildRecoveryCallExprRAII RCE(SemaRef); 12597 12598 CXXScopeSpec SS; 12599 SS.Adopt(ULE->getQualifierLoc()); 12600 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12601 12602 TemplateArgumentListInfo TABuffer; 12603 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12604 if (ULE->hasExplicitTemplateArgs()) { 12605 ULE->copyTemplateArgumentsInto(TABuffer); 12606 ExplicitTemplateArgs = &TABuffer; 12607 } 12608 12609 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12610 Sema::LookupOrdinaryName); 12611 bool DoDiagnoseEmptyLookup = EmptyLookup; 12612 if (!DiagnoseTwoPhaseLookup( 12613 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12614 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12615 NoTypoCorrectionCCC NoTypoValidator{}; 12616 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12617 ExplicitTemplateArgs != nullptr, 12618 dyn_cast<MemberExpr>(Fn)); 12619 CorrectionCandidateCallback &Validator = 12620 AllowTypoCorrection 12621 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12622 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12623 if (!DoDiagnoseEmptyLookup || 12624 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12625 Args)) 12626 return ExprError(); 12627 } 12628 12629 assert(!R.empty() && "lookup results empty despite recovery"); 12630 12631 // If recovery created an ambiguity, just bail out. 12632 if (R.isAmbiguous()) { 12633 R.suppressDiagnostics(); 12634 return ExprError(); 12635 } 12636 12637 // Build an implicit member call if appropriate. Just drop the 12638 // casts and such from the call, we don't really care. 12639 ExprResult NewFn = ExprError(); 12640 if ((*R.begin())->isCXXClassMember()) 12641 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12642 ExplicitTemplateArgs, S); 12643 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12644 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12645 ExplicitTemplateArgs); 12646 else 12647 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12648 12649 if (NewFn.isInvalid()) 12650 return ExprError(); 12651 12652 // This shouldn't cause an infinite loop because we're giving it 12653 // an expression with viable lookup results, which should never 12654 // end up here. 12655 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12656 MultiExprArg(Args.data(), Args.size()), 12657 RParenLoc); 12658 } 12659 12660 /// Constructs and populates an OverloadedCandidateSet from 12661 /// the given function. 12662 /// \returns true when an the ExprResult output parameter has been set. 12663 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12664 UnresolvedLookupExpr *ULE, 12665 MultiExprArg Args, 12666 SourceLocation RParenLoc, 12667 OverloadCandidateSet *CandidateSet, 12668 ExprResult *Result) { 12669 #ifndef NDEBUG 12670 if (ULE->requiresADL()) { 12671 // To do ADL, we must have found an unqualified name. 12672 assert(!ULE->getQualifier() && "qualified name with ADL"); 12673 12674 // We don't perform ADL for implicit declarations of builtins. 12675 // Verify that this was correctly set up. 12676 FunctionDecl *F; 12677 if (ULE->decls_begin() != ULE->decls_end() && 12678 ULE->decls_begin() + 1 == ULE->decls_end() && 12679 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12680 F->getBuiltinID() && F->isImplicit()) 12681 llvm_unreachable("performing ADL for builtin"); 12682 12683 // We don't perform ADL in C. 12684 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12685 } 12686 #endif 12687 12688 UnbridgedCastsSet UnbridgedCasts; 12689 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12690 *Result = ExprError(); 12691 return true; 12692 } 12693 12694 // Add the functions denoted by the callee to the set of candidate 12695 // functions, including those from argument-dependent lookup. 12696 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12697 12698 if (getLangOpts().MSVCCompat && 12699 CurContext->isDependentContext() && !isSFINAEContext() && 12700 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12701 12702 OverloadCandidateSet::iterator Best; 12703 if (CandidateSet->empty() || 12704 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12705 OR_No_Viable_Function) { 12706 // In Microsoft mode, if we are inside a template class member function 12707 // then create a type dependent CallExpr. The goal is to postpone name 12708 // lookup to instantiation time to be able to search into type dependent 12709 // base classes. 12710 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12711 VK_RValue, RParenLoc); 12712 CE->setTypeDependent(true); 12713 CE->setValueDependent(true); 12714 CE->setInstantiationDependent(true); 12715 *Result = CE; 12716 return true; 12717 } 12718 } 12719 12720 if (CandidateSet->empty()) 12721 return false; 12722 12723 UnbridgedCasts.restore(); 12724 return false; 12725 } 12726 12727 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12728 /// the completed call expression. If overload resolution fails, emits 12729 /// diagnostics and returns ExprError() 12730 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12731 UnresolvedLookupExpr *ULE, 12732 SourceLocation LParenLoc, 12733 MultiExprArg Args, 12734 SourceLocation RParenLoc, 12735 Expr *ExecConfig, 12736 OverloadCandidateSet *CandidateSet, 12737 OverloadCandidateSet::iterator *Best, 12738 OverloadingResult OverloadResult, 12739 bool AllowTypoCorrection) { 12740 if (CandidateSet->empty()) 12741 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12742 RParenLoc, /*EmptyLookup=*/true, 12743 AllowTypoCorrection); 12744 12745 switch (OverloadResult) { 12746 case OR_Success: { 12747 FunctionDecl *FDecl = (*Best)->Function; 12748 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12749 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12750 return ExprError(); 12751 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12752 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12753 ExecConfig, /*IsExecConfig=*/false, 12754 (*Best)->IsADLCandidate); 12755 } 12756 12757 case OR_No_Viable_Function: { 12758 // Try to recover by looking for viable functions which the user might 12759 // have meant to call. 12760 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12761 Args, RParenLoc, 12762 /*EmptyLookup=*/false, 12763 AllowTypoCorrection); 12764 if (!Recovery.isInvalid()) 12765 return Recovery; 12766 12767 // If the user passes in a function that we can't take the address of, we 12768 // generally end up emitting really bad error messages. Here, we attempt to 12769 // emit better ones. 12770 for (const Expr *Arg : Args) { 12771 if (!Arg->getType()->isFunctionType()) 12772 continue; 12773 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12774 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12775 if (FD && 12776 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12777 Arg->getExprLoc())) 12778 return ExprError(); 12779 } 12780 } 12781 12782 CandidateSet->NoteCandidates( 12783 PartialDiagnosticAt( 12784 Fn->getBeginLoc(), 12785 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12786 << ULE->getName() << Fn->getSourceRange()), 12787 SemaRef, OCD_AllCandidates, Args); 12788 break; 12789 } 12790 12791 case OR_Ambiguous: 12792 CandidateSet->NoteCandidates( 12793 PartialDiagnosticAt(Fn->getBeginLoc(), 12794 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12795 << ULE->getName() << Fn->getSourceRange()), 12796 SemaRef, OCD_AmbiguousCandidates, Args); 12797 break; 12798 12799 case OR_Deleted: { 12800 CandidateSet->NoteCandidates( 12801 PartialDiagnosticAt(Fn->getBeginLoc(), 12802 SemaRef.PDiag(diag::err_ovl_deleted_call) 12803 << ULE->getName() << Fn->getSourceRange()), 12804 SemaRef, OCD_AllCandidates, Args); 12805 12806 // We emitted an error for the unavailable/deleted function call but keep 12807 // the call in the AST. 12808 FunctionDecl *FDecl = (*Best)->Function; 12809 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12810 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12811 ExecConfig, /*IsExecConfig=*/false, 12812 (*Best)->IsADLCandidate); 12813 } 12814 } 12815 12816 // Overload resolution failed. 12817 return ExprError(); 12818 } 12819 12820 static void markUnaddressableCandidatesUnviable(Sema &S, 12821 OverloadCandidateSet &CS) { 12822 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12823 if (I->Viable && 12824 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12825 I->Viable = false; 12826 I->FailureKind = ovl_fail_addr_not_available; 12827 } 12828 } 12829 } 12830 12831 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12832 /// (which eventually refers to the declaration Func) and the call 12833 /// arguments Args/NumArgs, attempt to resolve the function call down 12834 /// to a specific function. If overload resolution succeeds, returns 12835 /// the call expression produced by overload resolution. 12836 /// Otherwise, emits diagnostics and returns ExprError. 12837 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12838 UnresolvedLookupExpr *ULE, 12839 SourceLocation LParenLoc, 12840 MultiExprArg Args, 12841 SourceLocation RParenLoc, 12842 Expr *ExecConfig, 12843 bool AllowTypoCorrection, 12844 bool CalleesAddressIsTaken) { 12845 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12846 OverloadCandidateSet::CSK_Normal); 12847 ExprResult result; 12848 12849 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12850 &result)) 12851 return result; 12852 12853 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12854 // functions that aren't addressible are considered unviable. 12855 if (CalleesAddressIsTaken) 12856 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12857 12858 OverloadCandidateSet::iterator Best; 12859 OverloadingResult OverloadResult = 12860 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12861 12862 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 12863 ExecConfig, &CandidateSet, &Best, 12864 OverloadResult, AllowTypoCorrection); 12865 } 12866 12867 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12868 return Functions.size() > 1 || 12869 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12870 } 12871 12872 /// Create a unary operation that may resolve to an overloaded 12873 /// operator. 12874 /// 12875 /// \param OpLoc The location of the operator itself (e.g., '*'). 12876 /// 12877 /// \param Opc The UnaryOperatorKind that describes this operator. 12878 /// 12879 /// \param Fns The set of non-member functions that will be 12880 /// considered by overload resolution. The caller needs to build this 12881 /// set based on the context using, e.g., 12882 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12883 /// set should not contain any member functions; those will be added 12884 /// by CreateOverloadedUnaryOp(). 12885 /// 12886 /// \param Input The input argument. 12887 ExprResult 12888 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12889 const UnresolvedSetImpl &Fns, 12890 Expr *Input, bool PerformADL) { 12891 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12892 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12893 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12894 // TODO: provide better source location info. 12895 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12896 12897 if (checkPlaceholderForOverload(*this, Input)) 12898 return ExprError(); 12899 12900 Expr *Args[2] = { Input, nullptr }; 12901 unsigned NumArgs = 1; 12902 12903 // For post-increment and post-decrement, add the implicit '0' as 12904 // the second argument, so that we know this is a post-increment or 12905 // post-decrement. 12906 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12907 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12908 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12909 SourceLocation()); 12910 NumArgs = 2; 12911 } 12912 12913 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12914 12915 if (Input->isTypeDependent()) { 12916 if (Fns.empty()) 12917 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12918 VK_RValue, OK_Ordinary, OpLoc, false); 12919 12920 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12921 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12922 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12923 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12924 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12925 Context.DependentTy, VK_RValue, OpLoc, 12926 FPOptions()); 12927 } 12928 12929 // Build an empty overload set. 12930 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12931 12932 // Add the candidates from the given function set. 12933 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 12934 12935 // Add operator candidates that are member functions. 12936 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12937 12938 // Add candidates from ADL. 12939 if (PerformADL) { 12940 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12941 /*ExplicitTemplateArgs*/nullptr, 12942 CandidateSet); 12943 } 12944 12945 // Add builtin operator candidates. 12946 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12947 12948 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12949 12950 // Perform overload resolution. 12951 OverloadCandidateSet::iterator Best; 12952 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12953 case OR_Success: { 12954 // We found a built-in operator or an overloaded operator. 12955 FunctionDecl *FnDecl = Best->Function; 12956 12957 if (FnDecl) { 12958 Expr *Base = nullptr; 12959 // We matched an overloaded operator. Build a call to that 12960 // operator. 12961 12962 // Convert the arguments. 12963 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12964 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12965 12966 ExprResult InputRes = 12967 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12968 Best->FoundDecl, Method); 12969 if (InputRes.isInvalid()) 12970 return ExprError(); 12971 Base = Input = InputRes.get(); 12972 } else { 12973 // Convert the arguments. 12974 ExprResult InputInit 12975 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12976 Context, 12977 FnDecl->getParamDecl(0)), 12978 SourceLocation(), 12979 Input); 12980 if (InputInit.isInvalid()) 12981 return ExprError(); 12982 Input = InputInit.get(); 12983 } 12984 12985 // Build the actual expression node. 12986 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12987 Base, HadMultipleCandidates, 12988 OpLoc); 12989 if (FnExpr.isInvalid()) 12990 return ExprError(); 12991 12992 // Determine the result type. 12993 QualType ResultTy = FnDecl->getReturnType(); 12994 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12995 ResultTy = ResultTy.getNonLValueExprType(Context); 12996 12997 Args[0] = Input; 12998 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12999 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13000 FPOptions(), Best->IsADLCandidate); 13001 13002 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13003 return ExprError(); 13004 13005 if (CheckFunctionCall(FnDecl, TheCall, 13006 FnDecl->getType()->castAs<FunctionProtoType>())) 13007 return ExprError(); 13008 13009 return MaybeBindToTemporary(TheCall); 13010 } else { 13011 // We matched a built-in operator. Convert the arguments, then 13012 // break out so that we will build the appropriate built-in 13013 // operator node. 13014 ExprResult InputRes = PerformImplicitConversion( 13015 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13016 CCK_ForBuiltinOverloadedOp); 13017 if (InputRes.isInvalid()) 13018 return ExprError(); 13019 Input = InputRes.get(); 13020 break; 13021 } 13022 } 13023 13024 case OR_No_Viable_Function: 13025 // This is an erroneous use of an operator which can be overloaded by 13026 // a non-member function. Check for non-member operators which were 13027 // defined too late to be candidates. 13028 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13029 // FIXME: Recover by calling the found function. 13030 return ExprError(); 13031 13032 // No viable function; fall through to handling this as a 13033 // built-in operator, which will produce an error message for us. 13034 break; 13035 13036 case OR_Ambiguous: 13037 CandidateSet.NoteCandidates( 13038 PartialDiagnosticAt(OpLoc, 13039 PDiag(diag::err_ovl_ambiguous_oper_unary) 13040 << UnaryOperator::getOpcodeStr(Opc) 13041 << Input->getType() << Input->getSourceRange()), 13042 *this, OCD_AmbiguousCandidates, ArgsArray, 13043 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13044 return ExprError(); 13045 13046 case OR_Deleted: 13047 CandidateSet.NoteCandidates( 13048 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13049 << UnaryOperator::getOpcodeStr(Opc) 13050 << Input->getSourceRange()), 13051 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13052 OpLoc); 13053 return ExprError(); 13054 } 13055 13056 // Either we found no viable overloaded operator or we matched a 13057 // built-in operator. In either case, fall through to trying to 13058 // build a built-in operation. 13059 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13060 } 13061 13062 /// Perform lookup for an overloaded binary operator. 13063 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13064 OverloadedOperatorKind Op, 13065 const UnresolvedSetImpl &Fns, 13066 ArrayRef<Expr *> Args, bool PerformADL) { 13067 SourceLocation OpLoc = CandidateSet.getLocation(); 13068 13069 OverloadedOperatorKind ExtraOp = 13070 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13071 ? getRewrittenOverloadedOperator(Op) 13072 : OO_None; 13073 13074 // Add the candidates from the given function set. This also adds the 13075 // rewritten candidates using these functions if necessary. 13076 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13077 13078 // Add operator candidates that are member functions. 13079 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13080 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13081 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13082 OverloadCandidateParamOrder::Reversed); 13083 13084 // In C++20, also add any rewritten member candidates. 13085 if (ExtraOp) { 13086 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13087 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13088 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13089 CandidateSet, 13090 OverloadCandidateParamOrder::Reversed); 13091 } 13092 13093 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13094 // performed for an assignment operator (nor for operator[] nor operator->, 13095 // which don't get here). 13096 if (Op != OO_Equal && PerformADL) { 13097 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13098 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13099 /*ExplicitTemplateArgs*/ nullptr, 13100 CandidateSet); 13101 if (ExtraOp) { 13102 DeclarationName ExtraOpName = 13103 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13104 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13105 /*ExplicitTemplateArgs*/ nullptr, 13106 CandidateSet); 13107 } 13108 } 13109 13110 // Add builtin operator candidates. 13111 // 13112 // FIXME: We don't add any rewritten candidates here. This is strictly 13113 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13114 // resulting in our selecting a rewritten builtin candidate. For example: 13115 // 13116 // enum class E { e }; 13117 // bool operator!=(E, E) requires false; 13118 // bool k = E::e != E::e; 13119 // 13120 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13121 // it seems unreasonable to consider rewritten builtin candidates. A core 13122 // issue has been filed proposing to removed this requirement. 13123 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13124 } 13125 13126 /// Create a binary operation that may resolve to an overloaded 13127 /// operator. 13128 /// 13129 /// \param OpLoc The location of the operator itself (e.g., '+'). 13130 /// 13131 /// \param Opc The BinaryOperatorKind that describes this operator. 13132 /// 13133 /// \param Fns The set of non-member functions that will be 13134 /// considered by overload resolution. The caller needs to build this 13135 /// set based on the context using, e.g., 13136 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13137 /// set should not contain any member functions; those will be added 13138 /// by CreateOverloadedBinOp(). 13139 /// 13140 /// \param LHS Left-hand argument. 13141 /// \param RHS Right-hand argument. 13142 /// \param PerformADL Whether to consider operator candidates found by ADL. 13143 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13144 /// C++20 operator rewrites. 13145 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13146 /// the function in question. Such a function is never a candidate in 13147 /// our overload resolution. This also enables synthesizing a three-way 13148 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13149 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13150 BinaryOperatorKind Opc, 13151 const UnresolvedSetImpl &Fns, Expr *LHS, 13152 Expr *RHS, bool PerformADL, 13153 bool AllowRewrittenCandidates, 13154 FunctionDecl *DefaultedFn) { 13155 Expr *Args[2] = { LHS, RHS }; 13156 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13157 13158 if (!getLangOpts().CPlusPlus2a) 13159 AllowRewrittenCandidates = false; 13160 13161 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13162 13163 // If either side is type-dependent, create an appropriate dependent 13164 // expression. 13165 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13166 if (Fns.empty()) { 13167 // If there are no functions to store, just build a dependent 13168 // BinaryOperator or CompoundAssignment. 13169 if (Opc <= BO_Assign || Opc > BO_OrAssign) 13170 return new (Context) BinaryOperator( 13171 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 13172 OpLoc, FPFeatures); 13173 13174 return new (Context) CompoundAssignOperator( 13175 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 13176 Context.DependentTy, Context.DependentTy, OpLoc, 13177 FPFeatures); 13178 } 13179 13180 // FIXME: save results of ADL from here? 13181 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13182 // TODO: provide better source location info in DNLoc component. 13183 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13184 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13185 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 13186 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 13187 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 13188 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 13189 Context.DependentTy, VK_RValue, OpLoc, 13190 FPFeatures); 13191 } 13192 13193 // Always do placeholder-like conversions on the RHS. 13194 if (checkPlaceholderForOverload(*this, Args[1])) 13195 return ExprError(); 13196 13197 // Do placeholder-like conversion on the LHS; note that we should 13198 // not get here with a PseudoObject LHS. 13199 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13200 if (checkPlaceholderForOverload(*this, Args[0])) 13201 return ExprError(); 13202 13203 // If this is the assignment operator, we only perform overload resolution 13204 // if the left-hand side is a class or enumeration type. This is actually 13205 // a hack. The standard requires that we do overload resolution between the 13206 // various built-in candidates, but as DR507 points out, this can lead to 13207 // problems. So we do it this way, which pretty much follows what GCC does. 13208 // Note that we go the traditional code path for compound assignment forms. 13209 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13210 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13211 13212 // If this is the .* operator, which is not overloadable, just 13213 // create a built-in binary operator. 13214 if (Opc == BO_PtrMemD) 13215 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13216 13217 // Build the overload set. 13218 OverloadCandidateSet CandidateSet( 13219 OpLoc, OverloadCandidateSet::CSK_Operator, 13220 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13221 if (DefaultedFn) 13222 CandidateSet.exclude(DefaultedFn); 13223 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13224 13225 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13226 13227 // Perform overload resolution. 13228 OverloadCandidateSet::iterator Best; 13229 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13230 case OR_Success: { 13231 // We found a built-in operator or an overloaded operator. 13232 FunctionDecl *FnDecl = Best->Function; 13233 13234 bool IsReversed = (Best->RewriteKind & CRK_Reversed); 13235 if (IsReversed) 13236 std::swap(Args[0], Args[1]); 13237 13238 if (FnDecl) { 13239 Expr *Base = nullptr; 13240 // We matched an overloaded operator. Build a call to that 13241 // operator. 13242 13243 OverloadedOperatorKind ChosenOp = 13244 FnDecl->getDeclName().getCXXOverloadedOperator(); 13245 13246 // C++2a [over.match.oper]p9: 13247 // If a rewritten operator== candidate is selected by overload 13248 // resolution for an operator@, its return type shall be cv bool 13249 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13250 !FnDecl->getReturnType()->isBooleanType()) { 13251 Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool) 13252 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13253 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13254 Diag(FnDecl->getLocation(), diag::note_declared_at); 13255 return ExprError(); 13256 } 13257 13258 if (AllowRewrittenCandidates && !IsReversed && 13259 CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) { 13260 // We could have reversed this operator, but didn't. Check if the 13261 // reversed form was a viable candidate, and if so, if it had a 13262 // better conversion for either parameter. If so, this call is 13263 // formally ambiguous, and allowing it is an extension. 13264 for (OverloadCandidate &Cand : CandidateSet) { 13265 if (Cand.Viable && Cand.Function == FnDecl && 13266 Cand.RewriteKind & CRK_Reversed) { 13267 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13268 if (CompareImplicitConversionSequences( 13269 *this, OpLoc, Cand.Conversions[ArgIdx], 13270 Best->Conversions[ArgIdx]) == 13271 ImplicitConversionSequence::Better) { 13272 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13273 << BinaryOperator::getOpcodeStr(Opc) 13274 << Args[0]->getType() << Args[1]->getType() 13275 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13276 Diag(FnDecl->getLocation(), 13277 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13278 } 13279 } 13280 break; 13281 } 13282 } 13283 } 13284 13285 // Convert the arguments. 13286 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13287 // Best->Access is only meaningful for class members. 13288 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13289 13290 ExprResult Arg1 = 13291 PerformCopyInitialization( 13292 InitializedEntity::InitializeParameter(Context, 13293 FnDecl->getParamDecl(0)), 13294 SourceLocation(), Args[1]); 13295 if (Arg1.isInvalid()) 13296 return ExprError(); 13297 13298 ExprResult Arg0 = 13299 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13300 Best->FoundDecl, Method); 13301 if (Arg0.isInvalid()) 13302 return ExprError(); 13303 Base = Args[0] = Arg0.getAs<Expr>(); 13304 Args[1] = RHS = Arg1.getAs<Expr>(); 13305 } else { 13306 // Convert the arguments. 13307 ExprResult Arg0 = PerformCopyInitialization( 13308 InitializedEntity::InitializeParameter(Context, 13309 FnDecl->getParamDecl(0)), 13310 SourceLocation(), Args[0]); 13311 if (Arg0.isInvalid()) 13312 return ExprError(); 13313 13314 ExprResult Arg1 = 13315 PerformCopyInitialization( 13316 InitializedEntity::InitializeParameter(Context, 13317 FnDecl->getParamDecl(1)), 13318 SourceLocation(), Args[1]); 13319 if (Arg1.isInvalid()) 13320 return ExprError(); 13321 Args[0] = LHS = Arg0.getAs<Expr>(); 13322 Args[1] = RHS = Arg1.getAs<Expr>(); 13323 } 13324 13325 // Build the actual expression node. 13326 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13327 Best->FoundDecl, Base, 13328 HadMultipleCandidates, OpLoc); 13329 if (FnExpr.isInvalid()) 13330 return ExprError(); 13331 13332 // Determine the result type. 13333 QualType ResultTy = FnDecl->getReturnType(); 13334 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13335 ResultTy = ResultTy.getNonLValueExprType(Context); 13336 13337 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13338 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13339 FPFeatures, Best->IsADLCandidate); 13340 13341 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13342 FnDecl)) 13343 return ExprError(); 13344 13345 ArrayRef<const Expr *> ArgsArray(Args, 2); 13346 const Expr *ImplicitThis = nullptr; 13347 // Cut off the implicit 'this'. 13348 if (isa<CXXMethodDecl>(FnDecl)) { 13349 ImplicitThis = ArgsArray[0]; 13350 ArgsArray = ArgsArray.slice(1); 13351 } 13352 13353 // Check for a self move. 13354 if (Op == OO_Equal) 13355 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13356 13357 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13358 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13359 VariadicDoesNotApply); 13360 13361 ExprResult R = MaybeBindToTemporary(TheCall); 13362 if (R.isInvalid()) 13363 return ExprError(); 13364 13365 // For a rewritten candidate, we've already reversed the arguments 13366 // if needed. Perform the rest of the rewrite now. 13367 if ((Best->RewriteKind & CRK_DifferentOperator) || 13368 (Op == OO_Spaceship && IsReversed)) { 13369 if (Op == OO_ExclaimEqual) { 13370 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13371 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13372 } else { 13373 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13374 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13375 Expr *ZeroLiteral = 13376 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13377 13378 Sema::CodeSynthesisContext Ctx; 13379 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13380 Ctx.Entity = FnDecl; 13381 pushCodeSynthesisContext(Ctx); 13382 13383 R = CreateOverloadedBinOp( 13384 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13385 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13386 /*AllowRewrittenCandidates=*/false); 13387 13388 popCodeSynthesisContext(); 13389 } 13390 if (R.isInvalid()) 13391 return ExprError(); 13392 } else { 13393 assert(ChosenOp == Op && "unexpected operator name"); 13394 } 13395 13396 // Make a note in the AST if we did any rewriting. 13397 if (Best->RewriteKind != CRK_None) 13398 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13399 13400 return R; 13401 } else { 13402 // We matched a built-in operator. Convert the arguments, then 13403 // break out so that we will build the appropriate built-in 13404 // operator node. 13405 ExprResult ArgsRes0 = PerformImplicitConversion( 13406 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13407 AA_Passing, CCK_ForBuiltinOverloadedOp); 13408 if (ArgsRes0.isInvalid()) 13409 return ExprError(); 13410 Args[0] = ArgsRes0.get(); 13411 13412 ExprResult ArgsRes1 = PerformImplicitConversion( 13413 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13414 AA_Passing, CCK_ForBuiltinOverloadedOp); 13415 if (ArgsRes1.isInvalid()) 13416 return ExprError(); 13417 Args[1] = ArgsRes1.get(); 13418 break; 13419 } 13420 } 13421 13422 case OR_No_Viable_Function: { 13423 // C++ [over.match.oper]p9: 13424 // If the operator is the operator , [...] and there are no 13425 // viable functions, then the operator is assumed to be the 13426 // built-in operator and interpreted according to clause 5. 13427 if (Opc == BO_Comma) 13428 break; 13429 13430 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13431 // compare result using '==' and '<'. 13432 if (DefaultedFn && Opc == BO_Cmp) { 13433 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13434 Args[1], DefaultedFn); 13435 if (E.isInvalid() || E.isUsable()) 13436 return E; 13437 } 13438 13439 // For class as left operand for assignment or compound assignment 13440 // operator do not fall through to handling in built-in, but report that 13441 // no overloaded assignment operator found 13442 ExprResult Result = ExprError(); 13443 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13444 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13445 Args, OpLoc); 13446 if (Args[0]->getType()->isRecordType() && 13447 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13448 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13449 << BinaryOperator::getOpcodeStr(Opc) 13450 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13451 if (Args[0]->getType()->isIncompleteType()) { 13452 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13453 << Args[0]->getType() 13454 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13455 } 13456 } else { 13457 // This is an erroneous use of an operator which can be overloaded by 13458 // a non-member function. Check for non-member operators which were 13459 // defined too late to be candidates. 13460 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13461 // FIXME: Recover by calling the found function. 13462 return ExprError(); 13463 13464 // No viable function; try to create a built-in operation, which will 13465 // produce an error. Then, show the non-viable candidates. 13466 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13467 } 13468 assert(Result.isInvalid() && 13469 "C++ binary operator overloading is missing candidates!"); 13470 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13471 return Result; 13472 } 13473 13474 case OR_Ambiguous: 13475 CandidateSet.NoteCandidates( 13476 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13477 << BinaryOperator::getOpcodeStr(Opc) 13478 << Args[0]->getType() 13479 << Args[1]->getType() 13480 << Args[0]->getSourceRange() 13481 << Args[1]->getSourceRange()), 13482 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13483 OpLoc); 13484 return ExprError(); 13485 13486 case OR_Deleted: 13487 if (isImplicitlyDeleted(Best->Function)) { 13488 FunctionDecl *DeletedFD = Best->Function; 13489 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13490 if (DFK.isSpecialMember()) { 13491 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13492 << Args[0]->getType() << DFK.asSpecialMember(); 13493 } else { 13494 assert(DFK.isComparison()); 13495 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13496 << Args[0]->getType() << DeletedFD; 13497 } 13498 13499 // The user probably meant to call this special member. Just 13500 // explain why it's deleted. 13501 NoteDeletedFunction(DeletedFD); 13502 return ExprError(); 13503 } 13504 CandidateSet.NoteCandidates( 13505 PartialDiagnosticAt( 13506 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13507 << getOperatorSpelling(Best->Function->getDeclName() 13508 .getCXXOverloadedOperator()) 13509 << Args[0]->getSourceRange() 13510 << Args[1]->getSourceRange()), 13511 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13512 OpLoc); 13513 return ExprError(); 13514 } 13515 13516 // We matched a built-in operator; build it. 13517 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13518 } 13519 13520 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13521 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13522 FunctionDecl *DefaultedFn) { 13523 const ComparisonCategoryInfo *Info = 13524 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13525 // If we're not producing a known comparison category type, we can't 13526 // synthesize a three-way comparison. Let the caller diagnose this. 13527 if (!Info) 13528 return ExprResult((Expr*)nullptr); 13529 13530 // If we ever want to perform this synthesis more generally, we will need to 13531 // apply the temporary materialization conversion to the operands. 13532 assert(LHS->isGLValue() && RHS->isGLValue() && 13533 "cannot use prvalue expressions more than once"); 13534 Expr *OrigLHS = LHS; 13535 Expr *OrigRHS = RHS; 13536 13537 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13538 // each of them multiple times below. 13539 LHS = new (Context) 13540 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13541 LHS->getObjectKind(), LHS); 13542 RHS = new (Context) 13543 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13544 RHS->getObjectKind(), RHS); 13545 13546 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13547 DefaultedFn); 13548 if (Eq.isInvalid()) 13549 return ExprError(); 13550 13551 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13552 true, DefaultedFn); 13553 if (Less.isInvalid()) 13554 return ExprError(); 13555 13556 ExprResult Greater; 13557 if (Info->isPartial()) { 13558 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13559 DefaultedFn); 13560 if (Greater.isInvalid()) 13561 return ExprError(); 13562 } 13563 13564 // Form the list of comparisons we're going to perform. 13565 struct Comparison { 13566 ExprResult Cmp; 13567 ComparisonCategoryResult Result; 13568 } Comparisons[4] = 13569 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13570 : ComparisonCategoryResult::Equivalent}, 13571 {Less, ComparisonCategoryResult::Less}, 13572 {Greater, ComparisonCategoryResult::Greater}, 13573 {ExprResult(), ComparisonCategoryResult::Unordered}, 13574 }; 13575 13576 int I = Info->isPartial() ? 3 : 2; 13577 13578 // Combine the comparisons with suitable conditional expressions. 13579 ExprResult Result; 13580 for (; I >= 0; --I) { 13581 // Build a reference to the comparison category constant. 13582 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13583 // FIXME: Missing a constant for a comparison category. Diagnose this? 13584 if (!VI) 13585 return ExprResult((Expr*)nullptr); 13586 ExprResult ThisResult = 13587 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13588 if (ThisResult.isInvalid()) 13589 return ExprError(); 13590 13591 // Build a conditional unless this is the final case. 13592 if (Result.get()) { 13593 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13594 ThisResult.get(), Result.get()); 13595 if (Result.isInvalid()) 13596 return ExprError(); 13597 } else { 13598 Result = ThisResult; 13599 } 13600 } 13601 13602 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13603 // bind the OpaqueValueExprs before they're (repeatedly) used. 13604 Expr *SyntacticForm = new (Context) 13605 BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13606 Result.get()->getValueKind(), 13607 Result.get()->getObjectKind(), OpLoc, FPFeatures); 13608 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13609 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13610 } 13611 13612 ExprResult 13613 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13614 SourceLocation RLoc, 13615 Expr *Base, Expr *Idx) { 13616 Expr *Args[2] = { Base, Idx }; 13617 DeclarationName OpName = 13618 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13619 13620 // If either side is type-dependent, create an appropriate dependent 13621 // expression. 13622 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13623 13624 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13625 // CHECKME: no 'operator' keyword? 13626 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13627 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13628 UnresolvedLookupExpr *Fn 13629 = UnresolvedLookupExpr::Create(Context, NamingClass, 13630 NestedNameSpecifierLoc(), OpNameInfo, 13631 /*ADL*/ true, /*Overloaded*/ false, 13632 UnresolvedSetIterator(), 13633 UnresolvedSetIterator()); 13634 // Can't add any actual overloads yet 13635 13636 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 13637 Context.DependentTy, VK_RValue, RLoc, 13638 FPOptions()); 13639 } 13640 13641 // Handle placeholders on both operands. 13642 if (checkPlaceholderForOverload(*this, Args[0])) 13643 return ExprError(); 13644 if (checkPlaceholderForOverload(*this, Args[1])) 13645 return ExprError(); 13646 13647 // Build an empty overload set. 13648 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13649 13650 // Subscript can only be overloaded as a member function. 13651 13652 // Add operator candidates that are member functions. 13653 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13654 13655 // Add builtin operator candidates. 13656 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13657 13658 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13659 13660 // Perform overload resolution. 13661 OverloadCandidateSet::iterator Best; 13662 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13663 case OR_Success: { 13664 // We found a built-in operator or an overloaded operator. 13665 FunctionDecl *FnDecl = Best->Function; 13666 13667 if (FnDecl) { 13668 // We matched an overloaded operator. Build a call to that 13669 // operator. 13670 13671 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13672 13673 // Convert the arguments. 13674 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13675 ExprResult Arg0 = 13676 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13677 Best->FoundDecl, Method); 13678 if (Arg0.isInvalid()) 13679 return ExprError(); 13680 Args[0] = Arg0.get(); 13681 13682 // Convert the arguments. 13683 ExprResult InputInit 13684 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13685 Context, 13686 FnDecl->getParamDecl(0)), 13687 SourceLocation(), 13688 Args[1]); 13689 if (InputInit.isInvalid()) 13690 return ExprError(); 13691 13692 Args[1] = InputInit.getAs<Expr>(); 13693 13694 // Build the actual expression node. 13695 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13696 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13697 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13698 Best->FoundDecl, 13699 Base, 13700 HadMultipleCandidates, 13701 OpLocInfo.getLoc(), 13702 OpLocInfo.getInfo()); 13703 if (FnExpr.isInvalid()) 13704 return ExprError(); 13705 13706 // Determine the result type 13707 QualType ResultTy = FnDecl->getReturnType(); 13708 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13709 ResultTy = ResultTy.getNonLValueExprType(Context); 13710 13711 CXXOperatorCallExpr *TheCall = 13712 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 13713 Args, ResultTy, VK, RLoc, FPOptions()); 13714 13715 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 13716 return ExprError(); 13717 13718 if (CheckFunctionCall(Method, TheCall, 13719 Method->getType()->castAs<FunctionProtoType>())) 13720 return ExprError(); 13721 13722 return MaybeBindToTemporary(TheCall); 13723 } else { 13724 // We matched a built-in operator. Convert the arguments, then 13725 // break out so that we will build the appropriate built-in 13726 // operator node. 13727 ExprResult ArgsRes0 = PerformImplicitConversion( 13728 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13729 AA_Passing, CCK_ForBuiltinOverloadedOp); 13730 if (ArgsRes0.isInvalid()) 13731 return ExprError(); 13732 Args[0] = ArgsRes0.get(); 13733 13734 ExprResult ArgsRes1 = PerformImplicitConversion( 13735 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13736 AA_Passing, CCK_ForBuiltinOverloadedOp); 13737 if (ArgsRes1.isInvalid()) 13738 return ExprError(); 13739 Args[1] = ArgsRes1.get(); 13740 13741 break; 13742 } 13743 } 13744 13745 case OR_No_Viable_Function: { 13746 PartialDiagnostic PD = CandidateSet.empty() 13747 ? (PDiag(diag::err_ovl_no_oper) 13748 << Args[0]->getType() << /*subscript*/ 0 13749 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 13750 : (PDiag(diag::err_ovl_no_viable_subscript) 13751 << Args[0]->getType() << Args[0]->getSourceRange() 13752 << Args[1]->getSourceRange()); 13753 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 13754 OCD_AllCandidates, Args, "[]", LLoc); 13755 return ExprError(); 13756 } 13757 13758 case OR_Ambiguous: 13759 CandidateSet.NoteCandidates( 13760 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13761 << "[]" << Args[0]->getType() 13762 << Args[1]->getType() 13763 << Args[0]->getSourceRange() 13764 << Args[1]->getSourceRange()), 13765 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 13766 return ExprError(); 13767 13768 case OR_Deleted: 13769 CandidateSet.NoteCandidates( 13770 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 13771 << "[]" << Args[0]->getSourceRange() 13772 << Args[1]->getSourceRange()), 13773 *this, OCD_AllCandidates, Args, "[]", LLoc); 13774 return ExprError(); 13775 } 13776 13777 // We matched a built-in operator; build it. 13778 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 13779 } 13780 13781 /// BuildCallToMemberFunction - Build a call to a member 13782 /// function. MemExpr is the expression that refers to the member 13783 /// function (and includes the object parameter), Args/NumArgs are the 13784 /// arguments to the function call (not including the object 13785 /// parameter). The caller needs to validate that the member 13786 /// expression refers to a non-static member function or an overloaded 13787 /// member function. 13788 ExprResult 13789 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 13790 SourceLocation LParenLoc, 13791 MultiExprArg Args, 13792 SourceLocation RParenLoc) { 13793 assert(MemExprE->getType() == Context.BoundMemberTy || 13794 MemExprE->getType() == Context.OverloadTy); 13795 13796 // Dig out the member expression. This holds both the object 13797 // argument and the member function we're referring to. 13798 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 13799 13800 // Determine whether this is a call to a pointer-to-member function. 13801 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 13802 assert(op->getType() == Context.BoundMemberTy); 13803 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 13804 13805 QualType fnType = 13806 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 13807 13808 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 13809 QualType resultType = proto->getCallResultType(Context); 13810 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 13811 13812 // Check that the object type isn't more qualified than the 13813 // member function we're calling. 13814 Qualifiers funcQuals = proto->getMethodQuals(); 13815 13816 QualType objectType = op->getLHS()->getType(); 13817 if (op->getOpcode() == BO_PtrMemI) 13818 objectType = objectType->castAs<PointerType>()->getPointeeType(); 13819 Qualifiers objectQuals = objectType.getQualifiers(); 13820 13821 Qualifiers difference = objectQuals - funcQuals; 13822 difference.removeObjCGCAttr(); 13823 difference.removeAddressSpace(); 13824 if (difference) { 13825 std::string qualsString = difference.getAsString(); 13826 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 13827 << fnType.getUnqualifiedType() 13828 << qualsString 13829 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 13830 } 13831 13832 CXXMemberCallExpr *call = 13833 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 13834 valueKind, RParenLoc, proto->getNumParams()); 13835 13836 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 13837 call, nullptr)) 13838 return ExprError(); 13839 13840 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 13841 return ExprError(); 13842 13843 if (CheckOtherCall(call, proto)) 13844 return ExprError(); 13845 13846 return MaybeBindToTemporary(call); 13847 } 13848 13849 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 13850 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 13851 RParenLoc); 13852 13853 UnbridgedCastsSet UnbridgedCasts; 13854 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13855 return ExprError(); 13856 13857 MemberExpr *MemExpr; 13858 CXXMethodDecl *Method = nullptr; 13859 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 13860 NestedNameSpecifier *Qualifier = nullptr; 13861 if (isa<MemberExpr>(NakedMemExpr)) { 13862 MemExpr = cast<MemberExpr>(NakedMemExpr); 13863 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 13864 FoundDecl = MemExpr->getFoundDecl(); 13865 Qualifier = MemExpr->getQualifier(); 13866 UnbridgedCasts.restore(); 13867 } else { 13868 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 13869 Qualifier = UnresExpr->getQualifier(); 13870 13871 QualType ObjectType = UnresExpr->getBaseType(); 13872 Expr::Classification ObjectClassification 13873 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 13874 : UnresExpr->getBase()->Classify(Context); 13875 13876 // Add overload candidates 13877 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 13878 OverloadCandidateSet::CSK_Normal); 13879 13880 // FIXME: avoid copy. 13881 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13882 if (UnresExpr->hasExplicitTemplateArgs()) { 13883 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13884 TemplateArgs = &TemplateArgsBuffer; 13885 } 13886 13887 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 13888 E = UnresExpr->decls_end(); I != E; ++I) { 13889 13890 NamedDecl *Func = *I; 13891 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 13892 if (isa<UsingShadowDecl>(Func)) 13893 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 13894 13895 13896 // Microsoft supports direct constructor calls. 13897 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 13898 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 13899 CandidateSet, 13900 /*SuppressUserConversions*/ false); 13901 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 13902 // If explicit template arguments were provided, we can't call a 13903 // non-template member function. 13904 if (TemplateArgs) 13905 continue; 13906 13907 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 13908 ObjectClassification, Args, CandidateSet, 13909 /*SuppressUserConversions=*/false); 13910 } else { 13911 AddMethodTemplateCandidate( 13912 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 13913 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 13914 /*SuppressUserConversions=*/false); 13915 } 13916 } 13917 13918 DeclarationName DeclName = UnresExpr->getMemberName(); 13919 13920 UnbridgedCasts.restore(); 13921 13922 OverloadCandidateSet::iterator Best; 13923 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 13924 Best)) { 13925 case OR_Success: 13926 Method = cast<CXXMethodDecl>(Best->Function); 13927 FoundDecl = Best->FoundDecl; 13928 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13929 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13930 return ExprError(); 13931 // If FoundDecl is different from Method (such as if one is a template 13932 // and the other a specialization), make sure DiagnoseUseOfDecl is 13933 // called on both. 13934 // FIXME: This would be more comprehensively addressed by modifying 13935 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13936 // being used. 13937 if (Method != FoundDecl.getDecl() && 13938 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13939 return ExprError(); 13940 break; 13941 13942 case OR_No_Viable_Function: 13943 CandidateSet.NoteCandidates( 13944 PartialDiagnosticAt( 13945 UnresExpr->getMemberLoc(), 13946 PDiag(diag::err_ovl_no_viable_member_function_in_call) 13947 << DeclName << MemExprE->getSourceRange()), 13948 *this, OCD_AllCandidates, Args); 13949 // FIXME: Leaking incoming expressions! 13950 return ExprError(); 13951 13952 case OR_Ambiguous: 13953 CandidateSet.NoteCandidates( 13954 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13955 PDiag(diag::err_ovl_ambiguous_member_call) 13956 << DeclName << MemExprE->getSourceRange()), 13957 *this, OCD_AmbiguousCandidates, Args); 13958 // FIXME: Leaking incoming expressions! 13959 return ExprError(); 13960 13961 case OR_Deleted: 13962 CandidateSet.NoteCandidates( 13963 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13964 PDiag(diag::err_ovl_deleted_member_call) 13965 << DeclName << MemExprE->getSourceRange()), 13966 *this, OCD_AllCandidates, Args); 13967 // FIXME: Leaking incoming expressions! 13968 return ExprError(); 13969 } 13970 13971 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13972 13973 // If overload resolution picked a static member, build a 13974 // non-member call based on that function. 13975 if (Method->isStatic()) { 13976 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13977 RParenLoc); 13978 } 13979 13980 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13981 } 13982 13983 QualType ResultType = Method->getReturnType(); 13984 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13985 ResultType = ResultType.getNonLValueExprType(Context); 13986 13987 assert(Method && "Member call to something that isn't a method?"); 13988 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 13989 CXXMemberCallExpr *TheCall = 13990 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13991 RParenLoc, Proto->getNumParams()); 13992 13993 // Check for a valid return type. 13994 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13995 TheCall, Method)) 13996 return ExprError(); 13997 13998 // Convert the object argument (for a non-static member function call). 13999 // We only need to do this if there was actually an overload; otherwise 14000 // it was done at lookup. 14001 if (!Method->isStatic()) { 14002 ExprResult ObjectArg = 14003 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14004 FoundDecl, Method); 14005 if (ObjectArg.isInvalid()) 14006 return ExprError(); 14007 MemExpr->setBase(ObjectArg.get()); 14008 } 14009 14010 // Convert the rest of the arguments 14011 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14012 RParenLoc)) 14013 return ExprError(); 14014 14015 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14016 14017 if (CheckFunctionCall(Method, TheCall, Proto)) 14018 return ExprError(); 14019 14020 // In the case the method to call was not selected by the overloading 14021 // resolution process, we still need to handle the enable_if attribute. Do 14022 // that here, so it will not hide previous -- and more relevant -- errors. 14023 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14024 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 14025 Diag(MemE->getMemberLoc(), 14026 diag::err_ovl_no_viable_member_function_in_call) 14027 << Method << Method->getSourceRange(); 14028 Diag(Method->getLocation(), 14029 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14030 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14031 return ExprError(); 14032 } 14033 } 14034 14035 if ((isa<CXXConstructorDecl>(CurContext) || 14036 isa<CXXDestructorDecl>(CurContext)) && 14037 TheCall->getMethodDecl()->isPure()) { 14038 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14039 14040 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14041 MemExpr->performsVirtualDispatch(getLangOpts())) { 14042 Diag(MemExpr->getBeginLoc(), 14043 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14044 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14045 << MD->getParent()->getDeclName(); 14046 14047 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14048 if (getLangOpts().AppleKext) 14049 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14050 << MD->getParent()->getDeclName() << MD->getDeclName(); 14051 } 14052 } 14053 14054 if (CXXDestructorDecl *DD = 14055 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14056 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14057 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14058 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14059 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14060 MemExpr->getMemberLoc()); 14061 } 14062 14063 return MaybeBindToTemporary(TheCall); 14064 } 14065 14066 /// BuildCallToObjectOfClassType - Build a call to an object of class 14067 /// type (C++ [over.call.object]), which can end up invoking an 14068 /// overloaded function call operator (@c operator()) or performing a 14069 /// user-defined conversion on the object argument. 14070 ExprResult 14071 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14072 SourceLocation LParenLoc, 14073 MultiExprArg Args, 14074 SourceLocation RParenLoc) { 14075 if (checkPlaceholderForOverload(*this, Obj)) 14076 return ExprError(); 14077 ExprResult Object = Obj; 14078 14079 UnbridgedCastsSet UnbridgedCasts; 14080 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14081 return ExprError(); 14082 14083 assert(Object.get()->getType()->isRecordType() && 14084 "Requires object type argument"); 14085 14086 // C++ [over.call.object]p1: 14087 // If the primary-expression E in the function call syntax 14088 // evaluates to a class object of type "cv T", then the set of 14089 // candidate functions includes at least the function call 14090 // operators of T. The function call operators of T are obtained by 14091 // ordinary lookup of the name operator() in the context of 14092 // (E).operator(). 14093 OverloadCandidateSet CandidateSet(LParenLoc, 14094 OverloadCandidateSet::CSK_Operator); 14095 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14096 14097 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14098 diag::err_incomplete_object_call, Object.get())) 14099 return true; 14100 14101 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14102 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14103 LookupQualifiedName(R, Record->getDecl()); 14104 R.suppressDiagnostics(); 14105 14106 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14107 Oper != OperEnd; ++Oper) { 14108 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14109 Object.get()->Classify(Context), Args, CandidateSet, 14110 /*SuppressUserConversion=*/false); 14111 } 14112 14113 // C++ [over.call.object]p2: 14114 // In addition, for each (non-explicit in C++0x) conversion function 14115 // declared in T of the form 14116 // 14117 // operator conversion-type-id () cv-qualifier; 14118 // 14119 // where cv-qualifier is the same cv-qualification as, or a 14120 // greater cv-qualification than, cv, and where conversion-type-id 14121 // denotes the type "pointer to function of (P1,...,Pn) returning 14122 // R", or the type "reference to pointer to function of 14123 // (P1,...,Pn) returning R", or the type "reference to function 14124 // of (P1,...,Pn) returning R", a surrogate call function [...] 14125 // is also considered as a candidate function. Similarly, 14126 // surrogate call functions are added to the set of candidate 14127 // functions for each conversion function declared in an 14128 // accessible base class provided the function is not hidden 14129 // within T by another intervening declaration. 14130 const auto &Conversions = 14131 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14132 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14133 NamedDecl *D = *I; 14134 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14135 if (isa<UsingShadowDecl>(D)) 14136 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14137 14138 // Skip over templated conversion functions; they aren't 14139 // surrogates. 14140 if (isa<FunctionTemplateDecl>(D)) 14141 continue; 14142 14143 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14144 if (!Conv->isExplicit()) { 14145 // Strip the reference type (if any) and then the pointer type (if 14146 // any) to get down to what might be a function type. 14147 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14148 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14149 ConvType = ConvPtrType->getPointeeType(); 14150 14151 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14152 { 14153 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14154 Object.get(), Args, CandidateSet); 14155 } 14156 } 14157 } 14158 14159 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14160 14161 // Perform overload resolution. 14162 OverloadCandidateSet::iterator Best; 14163 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14164 Best)) { 14165 case OR_Success: 14166 // Overload resolution succeeded; we'll build the appropriate call 14167 // below. 14168 break; 14169 14170 case OR_No_Viable_Function: { 14171 PartialDiagnostic PD = 14172 CandidateSet.empty() 14173 ? (PDiag(diag::err_ovl_no_oper) 14174 << Object.get()->getType() << /*call*/ 1 14175 << Object.get()->getSourceRange()) 14176 : (PDiag(diag::err_ovl_no_viable_object_call) 14177 << Object.get()->getType() << Object.get()->getSourceRange()); 14178 CandidateSet.NoteCandidates( 14179 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14180 OCD_AllCandidates, Args); 14181 break; 14182 } 14183 case OR_Ambiguous: 14184 CandidateSet.NoteCandidates( 14185 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14186 PDiag(diag::err_ovl_ambiguous_object_call) 14187 << Object.get()->getType() 14188 << Object.get()->getSourceRange()), 14189 *this, OCD_AmbiguousCandidates, Args); 14190 break; 14191 14192 case OR_Deleted: 14193 CandidateSet.NoteCandidates( 14194 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14195 PDiag(diag::err_ovl_deleted_object_call) 14196 << Object.get()->getType() 14197 << Object.get()->getSourceRange()), 14198 *this, OCD_AllCandidates, Args); 14199 break; 14200 } 14201 14202 if (Best == CandidateSet.end()) 14203 return true; 14204 14205 UnbridgedCasts.restore(); 14206 14207 if (Best->Function == nullptr) { 14208 // Since there is no function declaration, this is one of the 14209 // surrogate candidates. Dig out the conversion function. 14210 CXXConversionDecl *Conv 14211 = cast<CXXConversionDecl>( 14212 Best->Conversions[0].UserDefined.ConversionFunction); 14213 14214 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14215 Best->FoundDecl); 14216 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14217 return ExprError(); 14218 assert(Conv == Best->FoundDecl.getDecl() && 14219 "Found Decl & conversion-to-functionptr should be same, right?!"); 14220 // We selected one of the surrogate functions that converts the 14221 // object parameter to a function pointer. Perform the conversion 14222 // on the object argument, then let BuildCallExpr finish the job. 14223 14224 // Create an implicit member expr to refer to the conversion operator. 14225 // and then call it. 14226 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14227 Conv, HadMultipleCandidates); 14228 if (Call.isInvalid()) 14229 return ExprError(); 14230 // Record usage of conversion in an implicit cast. 14231 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 14232 CK_UserDefinedConversion, Call.get(), 14233 nullptr, VK_RValue); 14234 14235 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14236 } 14237 14238 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14239 14240 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14241 // that calls this method, using Object for the implicit object 14242 // parameter and passing along the remaining arguments. 14243 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14244 14245 // An error diagnostic has already been printed when parsing the declaration. 14246 if (Method->isInvalidDecl()) 14247 return ExprError(); 14248 14249 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14250 unsigned NumParams = Proto->getNumParams(); 14251 14252 DeclarationNameInfo OpLocInfo( 14253 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14254 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14255 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14256 Obj, HadMultipleCandidates, 14257 OpLocInfo.getLoc(), 14258 OpLocInfo.getInfo()); 14259 if (NewFn.isInvalid()) 14260 return true; 14261 14262 // The number of argument slots to allocate in the call. If we have default 14263 // arguments we need to allocate space for them as well. We additionally 14264 // need one more slot for the object parameter. 14265 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14266 14267 // Build the full argument list for the method call (the implicit object 14268 // parameter is placed at the beginning of the list). 14269 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14270 14271 bool IsError = false; 14272 14273 // Initialize the implicit object parameter. 14274 ExprResult ObjRes = 14275 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14276 Best->FoundDecl, Method); 14277 if (ObjRes.isInvalid()) 14278 IsError = true; 14279 else 14280 Object = ObjRes; 14281 MethodArgs[0] = Object.get(); 14282 14283 // Check the argument types. 14284 for (unsigned i = 0; i != NumParams; i++) { 14285 Expr *Arg; 14286 if (i < Args.size()) { 14287 Arg = Args[i]; 14288 14289 // Pass the argument. 14290 14291 ExprResult InputInit 14292 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14293 Context, 14294 Method->getParamDecl(i)), 14295 SourceLocation(), Arg); 14296 14297 IsError |= InputInit.isInvalid(); 14298 Arg = InputInit.getAs<Expr>(); 14299 } else { 14300 ExprResult DefArg 14301 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14302 if (DefArg.isInvalid()) { 14303 IsError = true; 14304 break; 14305 } 14306 14307 Arg = DefArg.getAs<Expr>(); 14308 } 14309 14310 MethodArgs[i + 1] = Arg; 14311 } 14312 14313 // If this is a variadic call, handle args passed through "...". 14314 if (Proto->isVariadic()) { 14315 // Promote the arguments (C99 6.5.2.2p7). 14316 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14317 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14318 nullptr); 14319 IsError |= Arg.isInvalid(); 14320 MethodArgs[i + 1] = Arg.get(); 14321 } 14322 } 14323 14324 if (IsError) 14325 return true; 14326 14327 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14328 14329 // Once we've built TheCall, all of the expressions are properly owned. 14330 QualType ResultTy = Method->getReturnType(); 14331 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14332 ResultTy = ResultTy.getNonLValueExprType(Context); 14333 14334 CXXOperatorCallExpr *TheCall = 14335 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 14336 ResultTy, VK, RParenLoc, FPOptions()); 14337 14338 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14339 return true; 14340 14341 if (CheckFunctionCall(Method, TheCall, Proto)) 14342 return true; 14343 14344 return MaybeBindToTemporary(TheCall); 14345 } 14346 14347 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14348 /// (if one exists), where @c Base is an expression of class type and 14349 /// @c Member is the name of the member we're trying to find. 14350 ExprResult 14351 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14352 bool *NoArrowOperatorFound) { 14353 assert(Base->getType()->isRecordType() && 14354 "left-hand side must have class type"); 14355 14356 if (checkPlaceholderForOverload(*this, Base)) 14357 return ExprError(); 14358 14359 SourceLocation Loc = Base->getExprLoc(); 14360 14361 // C++ [over.ref]p1: 14362 // 14363 // [...] An expression x->m is interpreted as (x.operator->())->m 14364 // for a class object x of type T if T::operator->() exists and if 14365 // the operator is selected as the best match function by the 14366 // overload resolution mechanism (13.3). 14367 DeclarationName OpName = 14368 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14369 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14370 14371 if (RequireCompleteType(Loc, Base->getType(), 14372 diag::err_typecheck_incomplete_tag, Base)) 14373 return ExprError(); 14374 14375 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14376 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14377 R.suppressDiagnostics(); 14378 14379 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14380 Oper != OperEnd; ++Oper) { 14381 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14382 None, CandidateSet, /*SuppressUserConversion=*/false); 14383 } 14384 14385 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14386 14387 // Perform overload resolution. 14388 OverloadCandidateSet::iterator Best; 14389 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14390 case OR_Success: 14391 // Overload resolution succeeded; we'll build the call below. 14392 break; 14393 14394 case OR_No_Viable_Function: { 14395 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14396 if (CandidateSet.empty()) { 14397 QualType BaseType = Base->getType(); 14398 if (NoArrowOperatorFound) { 14399 // Report this specific error to the caller instead of emitting a 14400 // diagnostic, as requested. 14401 *NoArrowOperatorFound = true; 14402 return ExprError(); 14403 } 14404 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14405 << BaseType << Base->getSourceRange(); 14406 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14407 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14408 << FixItHint::CreateReplacement(OpLoc, "."); 14409 } 14410 } else 14411 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14412 << "operator->" << Base->getSourceRange(); 14413 CandidateSet.NoteCandidates(*this, Base, Cands); 14414 return ExprError(); 14415 } 14416 case OR_Ambiguous: 14417 CandidateSet.NoteCandidates( 14418 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14419 << "->" << Base->getType() 14420 << Base->getSourceRange()), 14421 *this, OCD_AmbiguousCandidates, Base); 14422 return ExprError(); 14423 14424 case OR_Deleted: 14425 CandidateSet.NoteCandidates( 14426 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14427 << "->" << Base->getSourceRange()), 14428 *this, OCD_AllCandidates, Base); 14429 return ExprError(); 14430 } 14431 14432 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14433 14434 // Convert the object parameter. 14435 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14436 ExprResult BaseResult = 14437 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14438 Best->FoundDecl, Method); 14439 if (BaseResult.isInvalid()) 14440 return ExprError(); 14441 Base = BaseResult.get(); 14442 14443 // Build the operator call. 14444 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14445 Base, HadMultipleCandidates, OpLoc); 14446 if (FnExpr.isInvalid()) 14447 return ExprError(); 14448 14449 QualType ResultTy = Method->getReturnType(); 14450 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14451 ResultTy = ResultTy.getNonLValueExprType(Context); 14452 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14453 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 14454 14455 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14456 return ExprError(); 14457 14458 if (CheckFunctionCall(Method, TheCall, 14459 Method->getType()->castAs<FunctionProtoType>())) 14460 return ExprError(); 14461 14462 return MaybeBindToTemporary(TheCall); 14463 } 14464 14465 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14466 /// a literal operator described by the provided lookup results. 14467 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14468 DeclarationNameInfo &SuffixInfo, 14469 ArrayRef<Expr*> Args, 14470 SourceLocation LitEndLoc, 14471 TemplateArgumentListInfo *TemplateArgs) { 14472 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14473 14474 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14475 OverloadCandidateSet::CSK_Normal); 14476 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14477 TemplateArgs); 14478 14479 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14480 14481 // Perform overload resolution. This will usually be trivial, but might need 14482 // to perform substitutions for a literal operator template. 14483 OverloadCandidateSet::iterator Best; 14484 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14485 case OR_Success: 14486 case OR_Deleted: 14487 break; 14488 14489 case OR_No_Viable_Function: 14490 CandidateSet.NoteCandidates( 14491 PartialDiagnosticAt(UDSuffixLoc, 14492 PDiag(diag::err_ovl_no_viable_function_in_call) 14493 << R.getLookupName()), 14494 *this, OCD_AllCandidates, Args); 14495 return ExprError(); 14496 14497 case OR_Ambiguous: 14498 CandidateSet.NoteCandidates( 14499 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14500 << R.getLookupName()), 14501 *this, OCD_AmbiguousCandidates, Args); 14502 return ExprError(); 14503 } 14504 14505 FunctionDecl *FD = Best->Function; 14506 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14507 nullptr, HadMultipleCandidates, 14508 SuffixInfo.getLoc(), 14509 SuffixInfo.getInfo()); 14510 if (Fn.isInvalid()) 14511 return true; 14512 14513 // Check the argument types. This should almost always be a no-op, except 14514 // that array-to-pointer decay is applied to string literals. 14515 Expr *ConvArgs[2]; 14516 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14517 ExprResult InputInit = PerformCopyInitialization( 14518 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14519 SourceLocation(), Args[ArgIdx]); 14520 if (InputInit.isInvalid()) 14521 return true; 14522 ConvArgs[ArgIdx] = InputInit.get(); 14523 } 14524 14525 QualType ResultTy = FD->getReturnType(); 14526 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14527 ResultTy = ResultTy.getNonLValueExprType(Context); 14528 14529 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14530 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14531 VK, LitEndLoc, UDSuffixLoc); 14532 14533 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14534 return ExprError(); 14535 14536 if (CheckFunctionCall(FD, UDL, nullptr)) 14537 return ExprError(); 14538 14539 return MaybeBindToTemporary(UDL); 14540 } 14541 14542 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14543 /// given LookupResult is non-empty, it is assumed to describe a member which 14544 /// will be invoked. Otherwise, the function will be found via argument 14545 /// dependent lookup. 14546 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14547 /// otherwise CallExpr is set to ExprError() and some non-success value 14548 /// is returned. 14549 Sema::ForRangeStatus 14550 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14551 SourceLocation RangeLoc, 14552 const DeclarationNameInfo &NameInfo, 14553 LookupResult &MemberLookup, 14554 OverloadCandidateSet *CandidateSet, 14555 Expr *Range, ExprResult *CallExpr) { 14556 Scope *S = nullptr; 14557 14558 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14559 if (!MemberLookup.empty()) { 14560 ExprResult MemberRef = 14561 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14562 /*IsPtr=*/false, CXXScopeSpec(), 14563 /*TemplateKWLoc=*/SourceLocation(), 14564 /*FirstQualifierInScope=*/nullptr, 14565 MemberLookup, 14566 /*TemplateArgs=*/nullptr, S); 14567 if (MemberRef.isInvalid()) { 14568 *CallExpr = ExprError(); 14569 return FRS_DiagnosticIssued; 14570 } 14571 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14572 if (CallExpr->isInvalid()) { 14573 *CallExpr = ExprError(); 14574 return FRS_DiagnosticIssued; 14575 } 14576 } else { 14577 UnresolvedSet<0> FoundNames; 14578 UnresolvedLookupExpr *Fn = 14579 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 14580 NestedNameSpecifierLoc(), NameInfo, 14581 /*NeedsADL=*/true, /*Overloaded=*/false, 14582 FoundNames.begin(), FoundNames.end()); 14583 14584 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14585 CandidateSet, CallExpr); 14586 if (CandidateSet->empty() || CandidateSetError) { 14587 *CallExpr = ExprError(); 14588 return FRS_NoViableFunction; 14589 } 14590 OverloadCandidateSet::iterator Best; 14591 OverloadingResult OverloadResult = 14592 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14593 14594 if (OverloadResult == OR_No_Viable_Function) { 14595 *CallExpr = ExprError(); 14596 return FRS_NoViableFunction; 14597 } 14598 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14599 Loc, nullptr, CandidateSet, &Best, 14600 OverloadResult, 14601 /*AllowTypoCorrection=*/false); 14602 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14603 *CallExpr = ExprError(); 14604 return FRS_DiagnosticIssued; 14605 } 14606 } 14607 return FRS_Success; 14608 } 14609 14610 14611 /// FixOverloadedFunctionReference - E is an expression that refers to 14612 /// a C++ overloaded function (possibly with some parentheses and 14613 /// perhaps a '&' around it). We have resolved the overloaded function 14614 /// to the function declaration Fn, so patch up the expression E to 14615 /// refer (possibly indirectly) to Fn. Returns the new expr. 14616 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14617 FunctionDecl *Fn) { 14618 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14619 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14620 Found, Fn); 14621 if (SubExpr == PE->getSubExpr()) 14622 return PE; 14623 14624 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14625 } 14626 14627 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14628 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14629 Found, Fn); 14630 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 14631 SubExpr->getType()) && 14632 "Implicit cast type cannot be determined from overload"); 14633 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 14634 if (SubExpr == ICE->getSubExpr()) 14635 return ICE; 14636 14637 return ImplicitCastExpr::Create(Context, ICE->getType(), 14638 ICE->getCastKind(), 14639 SubExpr, nullptr, 14640 ICE->getValueKind()); 14641 } 14642 14643 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14644 if (!GSE->isResultDependent()) { 14645 Expr *SubExpr = 14646 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14647 if (SubExpr == GSE->getResultExpr()) 14648 return GSE; 14649 14650 // Replace the resulting type information before rebuilding the generic 14651 // selection expression. 14652 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14653 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14654 unsigned ResultIdx = GSE->getResultIndex(); 14655 AssocExprs[ResultIdx] = SubExpr; 14656 14657 return GenericSelectionExpr::Create( 14658 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14659 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14660 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14661 ResultIdx); 14662 } 14663 // Rather than fall through to the unreachable, return the original generic 14664 // selection expression. 14665 return GSE; 14666 } 14667 14668 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14669 assert(UnOp->getOpcode() == UO_AddrOf && 14670 "Can only take the address of an overloaded function"); 14671 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14672 if (Method->isStatic()) { 14673 // Do nothing: static member functions aren't any different 14674 // from non-member functions. 14675 } else { 14676 // Fix the subexpression, which really has to be an 14677 // UnresolvedLookupExpr holding an overloaded member function 14678 // or template. 14679 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14680 Found, Fn); 14681 if (SubExpr == UnOp->getSubExpr()) 14682 return UnOp; 14683 14684 assert(isa<DeclRefExpr>(SubExpr) 14685 && "fixed to something other than a decl ref"); 14686 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 14687 && "fixed to a member ref with no nested name qualifier"); 14688 14689 // We have taken the address of a pointer to member 14690 // function. Perform the computation here so that we get the 14691 // appropriate pointer to member type. 14692 QualType ClassType 14693 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14694 QualType MemPtrType 14695 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 14696 // Under the MS ABI, lock down the inheritance model now. 14697 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14698 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 14699 14700 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 14701 VK_RValue, OK_Ordinary, 14702 UnOp->getOperatorLoc(), false); 14703 } 14704 } 14705 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14706 Found, Fn); 14707 if (SubExpr == UnOp->getSubExpr()) 14708 return UnOp; 14709 14710 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 14711 Context.getPointerType(SubExpr->getType()), 14712 VK_RValue, OK_Ordinary, 14713 UnOp->getOperatorLoc(), false); 14714 } 14715 14716 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14717 // FIXME: avoid copy. 14718 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14719 if (ULE->hasExplicitTemplateArgs()) { 14720 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 14721 TemplateArgs = &TemplateArgsBuffer; 14722 } 14723 14724 DeclRefExpr *DRE = 14725 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 14726 ULE->getQualifierLoc(), Found.getDecl(), 14727 ULE->getTemplateKeywordLoc(), TemplateArgs); 14728 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 14729 return DRE; 14730 } 14731 14732 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 14733 // FIXME: avoid copy. 14734 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14735 if (MemExpr->hasExplicitTemplateArgs()) { 14736 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14737 TemplateArgs = &TemplateArgsBuffer; 14738 } 14739 14740 Expr *Base; 14741 14742 // If we're filling in a static method where we used to have an 14743 // implicit member access, rewrite to a simple decl ref. 14744 if (MemExpr->isImplicitAccess()) { 14745 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14746 DeclRefExpr *DRE = BuildDeclRefExpr( 14747 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 14748 MemExpr->getQualifierLoc(), Found.getDecl(), 14749 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 14750 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 14751 return DRE; 14752 } else { 14753 SourceLocation Loc = MemExpr->getMemberLoc(); 14754 if (MemExpr->getQualifier()) 14755 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 14756 Base = 14757 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 14758 } 14759 } else 14760 Base = MemExpr->getBase(); 14761 14762 ExprValueKind valueKind; 14763 QualType type; 14764 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14765 valueKind = VK_LValue; 14766 type = Fn->getType(); 14767 } else { 14768 valueKind = VK_RValue; 14769 type = Context.BoundMemberTy; 14770 } 14771 14772 return BuildMemberExpr( 14773 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 14774 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 14775 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 14776 type, valueKind, OK_Ordinary, TemplateArgs); 14777 } 14778 14779 llvm_unreachable("Invalid reference to overloaded function"); 14780 } 14781 14782 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 14783 DeclAccessPair Found, 14784 FunctionDecl *Fn) { 14785 return FixOverloadedFunctionReference(E.get(), Found, Fn); 14786 } 14787