1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/ADT/Optional.h" 33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/SmallString.h" 36 #include <algorithm> 37 #include <cstdlib> 38 39 using namespace clang; 40 using namespace sema; 41 42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 43 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 44 return P->hasAttr<PassObjectSizeAttr>(); 45 }); 46 } 47 48 /// A convenience routine for creating a decayed reference to a function. 49 static ExprResult 50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 51 const Expr *Base, bool HadMultipleCandidates, 52 SourceLocation Loc = SourceLocation(), 53 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 54 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 55 return ExprError(); 56 // If FoundDecl is different from Fn (such as if one is a template 57 // and the other a specialization), make sure DiagnoseUseOfDecl is 58 // called on both. 59 // FIXME: This would be more comprehensively addressed by modifying 60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 61 // being used. 62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 63 return ExprError(); 64 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 65 S.ResolveExceptionSpec(Loc, FPT); 66 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 67 VK_LValue, Loc, LocInfo); 68 if (HadMultipleCandidates) 69 DRE->setHadMultipleCandidates(true); 70 71 S.MarkDeclRefReferenced(DRE, Base); 72 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 73 CK_FunctionToPointerDecay); 74 } 75 76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 77 bool InOverloadResolution, 78 StandardConversionSequence &SCS, 79 bool CStyle, 80 bool AllowObjCWritebackConversion); 81 82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 83 QualType &ToType, 84 bool InOverloadResolution, 85 StandardConversionSequence &SCS, 86 bool CStyle); 87 static OverloadingResult 88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 89 UserDefinedConversionSequence& User, 90 OverloadCandidateSet& Conversions, 91 bool AllowExplicit, 92 bool AllowObjCConversionOnExplicit); 93 94 95 static ImplicitConversionSequence::CompareKind 96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 97 const StandardConversionSequence& SCS1, 98 const StandardConversionSequence& SCS2); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareQualificationConversions(Sema &S, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 static ImplicitConversionSequence::CompareKind 106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 107 const StandardConversionSequence& SCS1, 108 const StandardConversionSequence& SCS2); 109 110 /// GetConversionRank - Retrieve the implicit conversion rank 111 /// corresponding to the given implicit conversion kind. 112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 113 static const ImplicitConversionRank 114 Rank[(int)ICK_Num_Conversion_Kinds] = { 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Exact_Match, 121 ICR_Promotion, 122 ICR_Promotion, 123 ICR_Promotion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_OCL_Scalar_Widening, 135 ICR_Complex_Real_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Writeback_Conversion, 139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 140 // it was omitted by the patch that added 141 // ICK_Zero_Event_Conversion 142 ICR_C_Conversion, 143 ICR_C_Conversion_Extension 144 }; 145 return Rank[(int)Kind]; 146 } 147 148 /// GetImplicitConversionName - Return the name of this kind of 149 /// implicit conversion. 150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 152 "No conversion", 153 "Lvalue-to-rvalue", 154 "Array-to-pointer", 155 "Function-to-pointer", 156 "Function pointer conversion", 157 "Qualification", 158 "Integral promotion", 159 "Floating point promotion", 160 "Complex promotion", 161 "Integral conversion", 162 "Floating conversion", 163 "Complex conversion", 164 "Floating-integral conversion", 165 "Pointer conversion", 166 "Pointer-to-member conversion", 167 "Boolean conversion", 168 "Compatible-types conversion", 169 "Derived-to-base conversion", 170 "Vector conversion", 171 "Vector splat", 172 "Complex-real conversion", 173 "Block Pointer conversion", 174 "Transparent Union Conversion", 175 "Writeback conversion", 176 "OpenCL Zero Event Conversion", 177 "C specific type conversion", 178 "Incompatible pointer conversion" 179 }; 180 return Name[Kind]; 181 } 182 183 /// StandardConversionSequence - Set the standard conversion 184 /// sequence to the identity conversion. 185 void StandardConversionSequence::setAsIdentityConversion() { 186 First = ICK_Identity; 187 Second = ICK_Identity; 188 Third = ICK_Identity; 189 DeprecatedStringLiteralToCharPtr = false; 190 QualificationIncludesObjCLifetime = false; 191 ReferenceBinding = false; 192 DirectBinding = false; 193 IsLvalueReference = true; 194 BindsToFunctionLvalue = false; 195 BindsToRvalue = false; 196 BindsImplicitObjectArgumentWithoutRefQualifier = false; 197 ObjCLifetimeConversionBinding = false; 198 CopyConstructor = nullptr; 199 } 200 201 /// getRank - Retrieve the rank of this standard conversion sequence 202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 203 /// implicit conversions. 204 ImplicitConversionRank StandardConversionSequence::getRank() const { 205 ImplicitConversionRank Rank = ICR_Exact_Match; 206 if (GetConversionRank(First) > Rank) 207 Rank = GetConversionRank(First); 208 if (GetConversionRank(Second) > Rank) 209 Rank = GetConversionRank(Second); 210 if (GetConversionRank(Third) > Rank) 211 Rank = GetConversionRank(Third); 212 return Rank; 213 } 214 215 /// isPointerConversionToBool - Determines whether this conversion is 216 /// a conversion of a pointer or pointer-to-member to bool. This is 217 /// used as part of the ranking of standard conversion sequences 218 /// (C++ 13.3.3.2p4). 219 bool StandardConversionSequence::isPointerConversionToBool() const { 220 // Note that FromType has not necessarily been transformed by the 221 // array-to-pointer or function-to-pointer implicit conversions, so 222 // check for their presence as well as checking whether FromType is 223 // a pointer. 224 if (getToType(1)->isBooleanType() && 225 (getFromType()->isPointerType() || 226 getFromType()->isMemberPointerType() || 227 getFromType()->isObjCObjectPointerType() || 228 getFromType()->isBlockPointerType() || 229 getFromType()->isNullPtrType() || 230 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 231 return true; 232 233 return false; 234 } 235 236 /// isPointerConversionToVoidPointer - Determines whether this 237 /// conversion is a conversion of a pointer to a void pointer. This is 238 /// used as part of the ranking of standard conversion sequences (C++ 239 /// 13.3.3.2p4). 240 bool 241 StandardConversionSequence:: 242 isPointerConversionToVoidPointer(ASTContext& Context) const { 243 QualType FromType = getFromType(); 244 QualType ToType = getToType(1); 245 246 // Note that FromType has not necessarily been transformed by the 247 // array-to-pointer implicit conversion, so check for its presence 248 // and redo the conversion to get a pointer. 249 if (First == ICK_Array_To_Pointer) 250 FromType = Context.getArrayDecayedType(FromType); 251 252 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 253 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 254 return ToPtrType->getPointeeType()->isVoidType(); 255 256 return false; 257 } 258 259 /// Skip any implicit casts which could be either part of a narrowing conversion 260 /// or after one in an implicit conversion. 261 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 262 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 263 switch (ICE->getCastKind()) { 264 case CK_NoOp: 265 case CK_IntegralCast: 266 case CK_IntegralToBoolean: 267 case CK_IntegralToFloating: 268 case CK_BooleanToSignedIntegral: 269 case CK_FloatingToIntegral: 270 case CK_FloatingToBoolean: 271 case CK_FloatingCast: 272 Converted = ICE->getSubExpr(); 273 continue; 274 275 default: 276 return Converted; 277 } 278 } 279 280 return Converted; 281 } 282 283 /// Check if this standard conversion sequence represents a narrowing 284 /// conversion, according to C++11 [dcl.init.list]p7. 285 /// 286 /// \param Ctx The AST context. 287 /// \param Converted The result of applying this standard conversion sequence. 288 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 289 /// value of the expression prior to the narrowing conversion. 290 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 291 /// type of the expression prior to the narrowing conversion. 292 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 293 /// from floating point types to integral types should be ignored. 294 NarrowingKind StandardConversionSequence::getNarrowingKind( 295 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 296 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 297 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 298 299 // C++11 [dcl.init.list]p7: 300 // A narrowing conversion is an implicit conversion ... 301 QualType FromType = getToType(0); 302 QualType ToType = getToType(1); 303 304 // A conversion to an enumeration type is narrowing if the conversion to 305 // the underlying type is narrowing. This only arises for expressions of 306 // the form 'Enum{init}'. 307 if (auto *ET = ToType->getAs<EnumType>()) 308 ToType = ET->getDecl()->getIntegerType(); 309 310 switch (Second) { 311 // 'bool' is an integral type; dispatch to the right place to handle it. 312 case ICK_Boolean_Conversion: 313 if (FromType->isRealFloatingType()) 314 goto FloatingIntegralConversion; 315 if (FromType->isIntegralOrUnscopedEnumerationType()) 316 goto IntegralConversion; 317 // Boolean conversions can be from pointers and pointers to members 318 // [conv.bool], and those aren't considered narrowing conversions. 319 return NK_Not_Narrowing; 320 321 // -- from a floating-point type to an integer type, or 322 // 323 // -- from an integer type or unscoped enumeration type to a floating-point 324 // type, except where the source is a constant expression and the actual 325 // value after conversion will fit into the target type and will produce 326 // the original value when converted back to the original type, or 327 case ICK_Floating_Integral: 328 FloatingIntegralConversion: 329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 330 return NK_Type_Narrowing; 331 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 332 ToType->isRealFloatingType()) { 333 if (IgnoreFloatToIntegralConversion) 334 return NK_Not_Narrowing; 335 llvm::APSInt IntConstantValue; 336 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 337 assert(Initializer && "Unknown conversion expression"); 338 339 // If it's value-dependent, we can't tell whether it's narrowing. 340 if (Initializer->isValueDependent()) 341 return NK_Dependent_Narrowing; 342 343 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 344 // Convert the integer to the floating type. 345 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 346 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 347 llvm::APFloat::rmNearestTiesToEven); 348 // And back. 349 llvm::APSInt ConvertedValue = IntConstantValue; 350 bool ignored; 351 Result.convertToInteger(ConvertedValue, 352 llvm::APFloat::rmTowardZero, &ignored); 353 // If the resulting value is different, this was a narrowing conversion. 354 if (IntConstantValue != ConvertedValue) { 355 ConstantValue = APValue(IntConstantValue); 356 ConstantType = Initializer->getType(); 357 return NK_Constant_Narrowing; 358 } 359 } else { 360 // Variables are always narrowings. 361 return NK_Variable_Narrowing; 362 } 363 } 364 return NK_Not_Narrowing; 365 366 // -- from long double to double or float, or from double to float, except 367 // where the source is a constant expression and the actual value after 368 // conversion is within the range of values that can be represented (even 369 // if it cannot be represented exactly), or 370 case ICK_Floating_Conversion: 371 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 372 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 373 // FromType is larger than ToType. 374 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 375 376 // If it's value-dependent, we can't tell whether it's narrowing. 377 if (Initializer->isValueDependent()) 378 return NK_Dependent_Narrowing; 379 380 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 381 // Constant! 382 assert(ConstantValue.isFloat()); 383 llvm::APFloat FloatVal = ConstantValue.getFloat(); 384 // Convert the source value into the target type. 385 bool ignored; 386 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 387 Ctx.getFloatTypeSemantics(ToType), 388 llvm::APFloat::rmNearestTiesToEven, &ignored); 389 // If there was no overflow, the source value is within the range of 390 // values that can be represented. 391 if (ConvertStatus & llvm::APFloat::opOverflow) { 392 ConstantType = Initializer->getType(); 393 return NK_Constant_Narrowing; 394 } 395 } else { 396 return NK_Variable_Narrowing; 397 } 398 } 399 return NK_Not_Narrowing; 400 401 // -- from an integer type or unscoped enumeration type to an integer type 402 // that cannot represent all the values of the original type, except where 403 // the source is a constant expression and the actual value after 404 // conversion will fit into the target type and will produce the original 405 // value when converted back to the original type. 406 case ICK_Integral_Conversion: 407 IntegralConversion: { 408 assert(FromType->isIntegralOrUnscopedEnumerationType()); 409 assert(ToType->isIntegralOrUnscopedEnumerationType()); 410 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 411 const unsigned FromWidth = Ctx.getIntWidth(FromType); 412 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 413 const unsigned ToWidth = Ctx.getIntWidth(ToType); 414 415 if (FromWidth > ToWidth || 416 (FromWidth == ToWidth && FromSigned != ToSigned) || 417 (FromSigned && !ToSigned)) { 418 // Not all values of FromType can be represented in ToType. 419 llvm::APSInt InitializerValue; 420 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 421 422 // If it's value-dependent, we can't tell whether it's narrowing. 423 if (Initializer->isValueDependent()) 424 return NK_Dependent_Narrowing; 425 426 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 427 // Such conversions on variables are always narrowing. 428 return NK_Variable_Narrowing; 429 } 430 bool Narrowing = false; 431 if (FromWidth < ToWidth) { 432 // Negative -> unsigned is narrowing. Otherwise, more bits is never 433 // narrowing. 434 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 435 Narrowing = true; 436 } else { 437 // Add a bit to the InitializerValue so we don't have to worry about 438 // signed vs. unsigned comparisons. 439 InitializerValue = InitializerValue.extend( 440 InitializerValue.getBitWidth() + 1); 441 // Convert the initializer to and from the target width and signed-ness. 442 llvm::APSInt ConvertedValue = InitializerValue; 443 ConvertedValue = ConvertedValue.trunc(ToWidth); 444 ConvertedValue.setIsSigned(ToSigned); 445 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 446 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 447 // If the result is different, this was a narrowing conversion. 448 if (ConvertedValue != InitializerValue) 449 Narrowing = true; 450 } 451 if (Narrowing) { 452 ConstantType = Initializer->getType(); 453 ConstantValue = APValue(InitializerValue); 454 return NK_Constant_Narrowing; 455 } 456 } 457 return NK_Not_Narrowing; 458 } 459 460 default: 461 // Other kinds of conversions are not narrowings. 462 return NK_Not_Narrowing; 463 } 464 } 465 466 /// dump - Print this standard conversion sequence to standard 467 /// error. Useful for debugging overloading issues. 468 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 469 raw_ostream &OS = llvm::errs(); 470 bool PrintedSomething = false; 471 if (First != ICK_Identity) { 472 OS << GetImplicitConversionName(First); 473 PrintedSomething = true; 474 } 475 476 if (Second != ICK_Identity) { 477 if (PrintedSomething) { 478 OS << " -> "; 479 } 480 OS << GetImplicitConversionName(Second); 481 482 if (CopyConstructor) { 483 OS << " (by copy constructor)"; 484 } else if (DirectBinding) { 485 OS << " (direct reference binding)"; 486 } else if (ReferenceBinding) { 487 OS << " (reference binding)"; 488 } 489 PrintedSomething = true; 490 } 491 492 if (Third != ICK_Identity) { 493 if (PrintedSomething) { 494 OS << " -> "; 495 } 496 OS << GetImplicitConversionName(Third); 497 PrintedSomething = true; 498 } 499 500 if (!PrintedSomething) { 501 OS << "No conversions required"; 502 } 503 } 504 505 /// dump - Print this user-defined conversion sequence to standard 506 /// error. Useful for debugging overloading issues. 507 void UserDefinedConversionSequence::dump() const { 508 raw_ostream &OS = llvm::errs(); 509 if (Before.First || Before.Second || Before.Third) { 510 Before.dump(); 511 OS << " -> "; 512 } 513 if (ConversionFunction) 514 OS << '\'' << *ConversionFunction << '\''; 515 else 516 OS << "aggregate initialization"; 517 if (After.First || After.Second || After.Third) { 518 OS << " -> "; 519 After.dump(); 520 } 521 } 522 523 /// dump - Print this implicit conversion sequence to standard 524 /// error. Useful for debugging overloading issues. 525 void ImplicitConversionSequence::dump() const { 526 raw_ostream &OS = llvm::errs(); 527 if (isStdInitializerListElement()) 528 OS << "Worst std::initializer_list element conversion: "; 529 switch (ConversionKind) { 530 case StandardConversion: 531 OS << "Standard conversion: "; 532 Standard.dump(); 533 break; 534 case UserDefinedConversion: 535 OS << "User-defined conversion: "; 536 UserDefined.dump(); 537 break; 538 case EllipsisConversion: 539 OS << "Ellipsis conversion"; 540 break; 541 case AmbiguousConversion: 542 OS << "Ambiguous conversion"; 543 break; 544 case BadConversion: 545 OS << "Bad conversion"; 546 break; 547 } 548 549 OS << "\n"; 550 } 551 552 void AmbiguousConversionSequence::construct() { 553 new (&conversions()) ConversionSet(); 554 } 555 556 void AmbiguousConversionSequence::destruct() { 557 conversions().~ConversionSet(); 558 } 559 560 void 561 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 562 FromTypePtr = O.FromTypePtr; 563 ToTypePtr = O.ToTypePtr; 564 new (&conversions()) ConversionSet(O.conversions()); 565 } 566 567 namespace { 568 // Structure used by DeductionFailureInfo to store 569 // template argument information. 570 struct DFIArguments { 571 TemplateArgument FirstArg; 572 TemplateArgument SecondArg; 573 }; 574 // Structure used by DeductionFailureInfo to store 575 // template parameter and template argument information. 576 struct DFIParamWithArguments : DFIArguments { 577 TemplateParameter Param; 578 }; 579 // Structure used by DeductionFailureInfo to store template argument 580 // information and the index of the problematic call argument. 581 struct DFIDeducedMismatchArgs : DFIArguments { 582 TemplateArgumentList *TemplateArgs; 583 unsigned CallArgIndex; 584 }; 585 } 586 587 /// Convert from Sema's representation of template deduction information 588 /// to the form used in overload-candidate information. 589 DeductionFailureInfo 590 clang::MakeDeductionFailureInfo(ASTContext &Context, 591 Sema::TemplateDeductionResult TDK, 592 TemplateDeductionInfo &Info) { 593 DeductionFailureInfo Result; 594 Result.Result = static_cast<unsigned>(TDK); 595 Result.HasDiagnostic = false; 596 switch (TDK) { 597 case Sema::TDK_Invalid: 598 case Sema::TDK_InstantiationDepth: 599 case Sema::TDK_TooManyArguments: 600 case Sema::TDK_TooFewArguments: 601 case Sema::TDK_MiscellaneousDeductionFailure: 602 case Sema::TDK_CUDATargetMismatch: 603 Result.Data = nullptr; 604 break; 605 606 case Sema::TDK_Incomplete: 607 case Sema::TDK_InvalidExplicitArguments: 608 Result.Data = Info.Param.getOpaqueValue(); 609 break; 610 611 case Sema::TDK_DeducedMismatch: 612 case Sema::TDK_DeducedMismatchNested: { 613 // FIXME: Should allocate from normal heap so that we can free this later. 614 auto *Saved = new (Context) DFIDeducedMismatchArgs; 615 Saved->FirstArg = Info.FirstArg; 616 Saved->SecondArg = Info.SecondArg; 617 Saved->TemplateArgs = Info.take(); 618 Saved->CallArgIndex = Info.CallArgIndex; 619 Result.Data = Saved; 620 break; 621 } 622 623 case Sema::TDK_NonDeducedMismatch: { 624 // FIXME: Should allocate from normal heap so that we can free this later. 625 DFIArguments *Saved = new (Context) DFIArguments; 626 Saved->FirstArg = Info.FirstArg; 627 Saved->SecondArg = Info.SecondArg; 628 Result.Data = Saved; 629 break; 630 } 631 632 case Sema::TDK_IncompletePack: 633 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 634 case Sema::TDK_Inconsistent: 635 case Sema::TDK_Underqualified: { 636 // FIXME: Should allocate from normal heap so that we can free this later. 637 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 638 Saved->Param = Info.Param; 639 Saved->FirstArg = Info.FirstArg; 640 Saved->SecondArg = Info.SecondArg; 641 Result.Data = Saved; 642 break; 643 } 644 645 case Sema::TDK_SubstitutionFailure: 646 Result.Data = Info.take(); 647 if (Info.hasSFINAEDiagnostic()) { 648 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 649 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 650 Info.takeSFINAEDiagnostic(*Diag); 651 Result.HasDiagnostic = true; 652 } 653 break; 654 655 case Sema::TDK_Success: 656 case Sema::TDK_NonDependentConversionFailure: 657 llvm_unreachable("not a deduction failure"); 658 } 659 660 return Result; 661 } 662 663 void DeductionFailureInfo::Destroy() { 664 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 665 case Sema::TDK_Success: 666 case Sema::TDK_Invalid: 667 case Sema::TDK_InstantiationDepth: 668 case Sema::TDK_Incomplete: 669 case Sema::TDK_TooManyArguments: 670 case Sema::TDK_TooFewArguments: 671 case Sema::TDK_InvalidExplicitArguments: 672 case Sema::TDK_CUDATargetMismatch: 673 case Sema::TDK_NonDependentConversionFailure: 674 break; 675 676 case Sema::TDK_IncompletePack: 677 case Sema::TDK_Inconsistent: 678 case Sema::TDK_Underqualified: 679 case Sema::TDK_DeducedMismatch: 680 case Sema::TDK_DeducedMismatchNested: 681 case Sema::TDK_NonDeducedMismatch: 682 // FIXME: Destroy the data? 683 Data = nullptr; 684 break; 685 686 case Sema::TDK_SubstitutionFailure: 687 // FIXME: Destroy the template argument list? 688 Data = nullptr; 689 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 690 Diag->~PartialDiagnosticAt(); 691 HasDiagnostic = false; 692 } 693 break; 694 695 // Unhandled 696 case Sema::TDK_MiscellaneousDeductionFailure: 697 break; 698 } 699 } 700 701 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 702 if (HasDiagnostic) 703 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 704 return nullptr; 705 } 706 707 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 708 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 709 case Sema::TDK_Success: 710 case Sema::TDK_Invalid: 711 case Sema::TDK_InstantiationDepth: 712 case Sema::TDK_TooManyArguments: 713 case Sema::TDK_TooFewArguments: 714 case Sema::TDK_SubstitutionFailure: 715 case Sema::TDK_DeducedMismatch: 716 case Sema::TDK_DeducedMismatchNested: 717 case Sema::TDK_NonDeducedMismatch: 718 case Sema::TDK_CUDATargetMismatch: 719 case Sema::TDK_NonDependentConversionFailure: 720 return TemplateParameter(); 721 722 case Sema::TDK_Incomplete: 723 case Sema::TDK_InvalidExplicitArguments: 724 return TemplateParameter::getFromOpaqueValue(Data); 725 726 case Sema::TDK_IncompletePack: 727 case Sema::TDK_Inconsistent: 728 case Sema::TDK_Underqualified: 729 return static_cast<DFIParamWithArguments*>(Data)->Param; 730 731 // Unhandled 732 case Sema::TDK_MiscellaneousDeductionFailure: 733 break; 734 } 735 736 return TemplateParameter(); 737 } 738 739 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 740 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 741 case Sema::TDK_Success: 742 case Sema::TDK_Invalid: 743 case Sema::TDK_InstantiationDepth: 744 case Sema::TDK_TooManyArguments: 745 case Sema::TDK_TooFewArguments: 746 case Sema::TDK_Incomplete: 747 case Sema::TDK_IncompletePack: 748 case Sema::TDK_InvalidExplicitArguments: 749 case Sema::TDK_Inconsistent: 750 case Sema::TDK_Underqualified: 751 case Sema::TDK_NonDeducedMismatch: 752 case Sema::TDK_CUDATargetMismatch: 753 case Sema::TDK_NonDependentConversionFailure: 754 return nullptr; 755 756 case Sema::TDK_DeducedMismatch: 757 case Sema::TDK_DeducedMismatchNested: 758 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 759 760 case Sema::TDK_SubstitutionFailure: 761 return static_cast<TemplateArgumentList*>(Data); 762 763 // Unhandled 764 case Sema::TDK_MiscellaneousDeductionFailure: 765 break; 766 } 767 768 return nullptr; 769 } 770 771 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 772 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 773 case Sema::TDK_Success: 774 case Sema::TDK_Invalid: 775 case Sema::TDK_InstantiationDepth: 776 case Sema::TDK_Incomplete: 777 case Sema::TDK_TooManyArguments: 778 case Sema::TDK_TooFewArguments: 779 case Sema::TDK_InvalidExplicitArguments: 780 case Sema::TDK_SubstitutionFailure: 781 case Sema::TDK_CUDATargetMismatch: 782 case Sema::TDK_NonDependentConversionFailure: 783 return nullptr; 784 785 case Sema::TDK_IncompletePack: 786 case Sema::TDK_Inconsistent: 787 case Sema::TDK_Underqualified: 788 case Sema::TDK_DeducedMismatch: 789 case Sema::TDK_DeducedMismatchNested: 790 case Sema::TDK_NonDeducedMismatch: 791 return &static_cast<DFIArguments*>(Data)->FirstArg; 792 793 // Unhandled 794 case Sema::TDK_MiscellaneousDeductionFailure: 795 break; 796 } 797 798 return nullptr; 799 } 800 801 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 802 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 803 case Sema::TDK_Success: 804 case Sema::TDK_Invalid: 805 case Sema::TDK_InstantiationDepth: 806 case Sema::TDK_Incomplete: 807 case Sema::TDK_IncompletePack: 808 case Sema::TDK_TooManyArguments: 809 case Sema::TDK_TooFewArguments: 810 case Sema::TDK_InvalidExplicitArguments: 811 case Sema::TDK_SubstitutionFailure: 812 case Sema::TDK_CUDATargetMismatch: 813 case Sema::TDK_NonDependentConversionFailure: 814 return nullptr; 815 816 case Sema::TDK_Inconsistent: 817 case Sema::TDK_Underqualified: 818 case Sema::TDK_DeducedMismatch: 819 case Sema::TDK_DeducedMismatchNested: 820 case Sema::TDK_NonDeducedMismatch: 821 return &static_cast<DFIArguments*>(Data)->SecondArg; 822 823 // Unhandled 824 case Sema::TDK_MiscellaneousDeductionFailure: 825 break; 826 } 827 828 return nullptr; 829 } 830 831 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 832 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 833 case Sema::TDK_DeducedMismatch: 834 case Sema::TDK_DeducedMismatchNested: 835 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 836 837 default: 838 return llvm::None; 839 } 840 } 841 842 void OverloadCandidateSet::destroyCandidates() { 843 for (iterator i = begin(), e = end(); i != e; ++i) { 844 for (auto &C : i->Conversions) 845 C.~ImplicitConversionSequence(); 846 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 847 i->DeductionFailure.Destroy(); 848 } 849 } 850 851 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 852 destroyCandidates(); 853 SlabAllocator.Reset(); 854 NumInlineBytesUsed = 0; 855 Candidates.clear(); 856 Functions.clear(); 857 Kind = CSK; 858 } 859 860 namespace { 861 class UnbridgedCastsSet { 862 struct Entry { 863 Expr **Addr; 864 Expr *Saved; 865 }; 866 SmallVector<Entry, 2> Entries; 867 868 public: 869 void save(Sema &S, Expr *&E) { 870 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 871 Entry entry = { &E, E }; 872 Entries.push_back(entry); 873 E = S.stripARCUnbridgedCast(E); 874 } 875 876 void restore() { 877 for (SmallVectorImpl<Entry>::iterator 878 i = Entries.begin(), e = Entries.end(); i != e; ++i) 879 *i->Addr = i->Saved; 880 } 881 }; 882 } 883 884 /// checkPlaceholderForOverload - Do any interesting placeholder-like 885 /// preprocessing on the given expression. 886 /// 887 /// \param unbridgedCasts a collection to which to add unbridged casts; 888 /// without this, they will be immediately diagnosed as errors 889 /// 890 /// Return true on unrecoverable error. 891 static bool 892 checkPlaceholderForOverload(Sema &S, Expr *&E, 893 UnbridgedCastsSet *unbridgedCasts = nullptr) { 894 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 895 // We can't handle overloaded expressions here because overload 896 // resolution might reasonably tweak them. 897 if (placeholder->getKind() == BuiltinType::Overload) return false; 898 899 // If the context potentially accepts unbridged ARC casts, strip 900 // the unbridged cast and add it to the collection for later restoration. 901 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 902 unbridgedCasts) { 903 unbridgedCasts->save(S, E); 904 return false; 905 } 906 907 // Go ahead and check everything else. 908 ExprResult result = S.CheckPlaceholderExpr(E); 909 if (result.isInvalid()) 910 return true; 911 912 E = result.get(); 913 return false; 914 } 915 916 // Nothing to do. 917 return false; 918 } 919 920 /// checkArgPlaceholdersForOverload - Check a set of call operands for 921 /// placeholders. 922 static bool checkArgPlaceholdersForOverload(Sema &S, 923 MultiExprArg Args, 924 UnbridgedCastsSet &unbridged) { 925 for (unsigned i = 0, e = Args.size(); i != e; ++i) 926 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 927 return true; 928 929 return false; 930 } 931 932 /// Determine whether the given New declaration is an overload of the 933 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 934 /// New and Old cannot be overloaded, e.g., if New has the same signature as 935 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 936 /// functions (or function templates) at all. When it does return Ovl_Match or 937 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 938 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 939 /// declaration. 940 /// 941 /// Example: Given the following input: 942 /// 943 /// void f(int, float); // #1 944 /// void f(int, int); // #2 945 /// int f(int, int); // #3 946 /// 947 /// When we process #1, there is no previous declaration of "f", so IsOverload 948 /// will not be used. 949 /// 950 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 951 /// the parameter types, we see that #1 and #2 are overloaded (since they have 952 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 953 /// unchanged. 954 /// 955 /// When we process #3, Old is an overload set containing #1 and #2. We compare 956 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 957 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 958 /// functions are not part of the signature), IsOverload returns Ovl_Match and 959 /// MatchedDecl will be set to point to the FunctionDecl for #2. 960 /// 961 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 962 /// by a using declaration. The rules for whether to hide shadow declarations 963 /// ignore some properties which otherwise figure into a function template's 964 /// signature. 965 Sema::OverloadKind 966 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 967 NamedDecl *&Match, bool NewIsUsingDecl) { 968 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 969 I != E; ++I) { 970 NamedDecl *OldD = *I; 971 972 bool OldIsUsingDecl = false; 973 if (isa<UsingShadowDecl>(OldD)) { 974 OldIsUsingDecl = true; 975 976 // We can always introduce two using declarations into the same 977 // context, even if they have identical signatures. 978 if (NewIsUsingDecl) continue; 979 980 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 981 } 982 983 // A using-declaration does not conflict with another declaration 984 // if one of them is hidden. 985 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 986 continue; 987 988 // If either declaration was introduced by a using declaration, 989 // we'll need to use slightly different rules for matching. 990 // Essentially, these rules are the normal rules, except that 991 // function templates hide function templates with different 992 // return types or template parameter lists. 993 bool UseMemberUsingDeclRules = 994 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 995 !New->getFriendObjectKind(); 996 997 if (FunctionDecl *OldF = OldD->getAsFunction()) { 998 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 999 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1000 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1001 continue; 1002 } 1003 1004 if (!isa<FunctionTemplateDecl>(OldD) && 1005 !shouldLinkPossiblyHiddenDecl(*I, New)) 1006 continue; 1007 1008 Match = *I; 1009 return Ovl_Match; 1010 } 1011 1012 // Builtins that have custom typechecking or have a reference should 1013 // not be overloadable or redeclarable. 1014 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1015 Match = *I; 1016 return Ovl_NonFunction; 1017 } 1018 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1019 // We can overload with these, which can show up when doing 1020 // redeclaration checks for UsingDecls. 1021 assert(Old.getLookupKind() == LookupUsingDeclName); 1022 } else if (isa<TagDecl>(OldD)) { 1023 // We can always overload with tags by hiding them. 1024 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1025 // Optimistically assume that an unresolved using decl will 1026 // overload; if it doesn't, we'll have to diagnose during 1027 // template instantiation. 1028 // 1029 // Exception: if the scope is dependent and this is not a class 1030 // member, the using declaration can only introduce an enumerator. 1031 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1032 Match = *I; 1033 return Ovl_NonFunction; 1034 } 1035 } else { 1036 // (C++ 13p1): 1037 // Only function declarations can be overloaded; object and type 1038 // declarations cannot be overloaded. 1039 Match = *I; 1040 return Ovl_NonFunction; 1041 } 1042 } 1043 1044 return Ovl_Overload; 1045 } 1046 1047 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1048 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1049 // C++ [basic.start.main]p2: This function shall not be overloaded. 1050 if (New->isMain()) 1051 return false; 1052 1053 // MSVCRT user defined entry points cannot be overloaded. 1054 if (New->isMSVCRTEntryPoint()) 1055 return false; 1056 1057 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1058 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1059 1060 // C++ [temp.fct]p2: 1061 // A function template can be overloaded with other function templates 1062 // and with normal (non-template) functions. 1063 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1064 return true; 1065 1066 // Is the function New an overload of the function Old? 1067 QualType OldQType = Context.getCanonicalType(Old->getType()); 1068 QualType NewQType = Context.getCanonicalType(New->getType()); 1069 1070 // Compare the signatures (C++ 1.3.10) of the two functions to 1071 // determine whether they are overloads. If we find any mismatch 1072 // in the signature, they are overloads. 1073 1074 // If either of these functions is a K&R-style function (no 1075 // prototype), then we consider them to have matching signatures. 1076 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1077 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1078 return false; 1079 1080 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1081 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1082 1083 // The signature of a function includes the types of its 1084 // parameters (C++ 1.3.10), which includes the presence or absence 1085 // of the ellipsis; see C++ DR 357). 1086 if (OldQType != NewQType && 1087 (OldType->getNumParams() != NewType->getNumParams() || 1088 OldType->isVariadic() != NewType->isVariadic() || 1089 !FunctionParamTypesAreEqual(OldType, NewType))) 1090 return true; 1091 1092 // C++ [temp.over.link]p4: 1093 // The signature of a function template consists of its function 1094 // signature, its return type and its template parameter list. The names 1095 // of the template parameters are significant only for establishing the 1096 // relationship between the template parameters and the rest of the 1097 // signature. 1098 // 1099 // We check the return type and template parameter lists for function 1100 // templates first; the remaining checks follow. 1101 // 1102 // However, we don't consider either of these when deciding whether 1103 // a member introduced by a shadow declaration is hidden. 1104 if (!UseMemberUsingDeclRules && NewTemplate && 1105 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1106 OldTemplate->getTemplateParameters(), 1107 false, TPL_TemplateMatch) || 1108 !Context.hasSameType(Old->getDeclaredReturnType(), 1109 New->getDeclaredReturnType()))) 1110 return true; 1111 1112 // If the function is a class member, its signature includes the 1113 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1114 // 1115 // As part of this, also check whether one of the member functions 1116 // is static, in which case they are not overloads (C++ 1117 // 13.1p2). While not part of the definition of the signature, 1118 // this check is important to determine whether these functions 1119 // can be overloaded. 1120 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1121 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1122 if (OldMethod && NewMethod && 1123 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1124 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1125 if (!UseMemberUsingDeclRules && 1126 (OldMethod->getRefQualifier() == RQ_None || 1127 NewMethod->getRefQualifier() == RQ_None)) { 1128 // C++0x [over.load]p2: 1129 // - Member function declarations with the same name and the same 1130 // parameter-type-list as well as member function template 1131 // declarations with the same name, the same parameter-type-list, and 1132 // the same template parameter lists cannot be overloaded if any of 1133 // them, but not all, have a ref-qualifier (8.3.5). 1134 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1135 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1136 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1137 } 1138 return true; 1139 } 1140 1141 // We may not have applied the implicit const for a constexpr member 1142 // function yet (because we haven't yet resolved whether this is a static 1143 // or non-static member function). Add it now, on the assumption that this 1144 // is a redeclaration of OldMethod. 1145 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1146 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1147 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1148 !isa<CXXConstructorDecl>(NewMethod)) 1149 NewQuals |= Qualifiers::Const; 1150 1151 // We do not allow overloading based off of '__restrict'. 1152 OldQuals &= ~Qualifiers::Restrict; 1153 NewQuals &= ~Qualifiers::Restrict; 1154 if (OldQuals != NewQuals) 1155 return true; 1156 } 1157 1158 // Though pass_object_size is placed on parameters and takes an argument, we 1159 // consider it to be a function-level modifier for the sake of function 1160 // identity. Either the function has one or more parameters with 1161 // pass_object_size or it doesn't. 1162 if (functionHasPassObjectSizeParams(New) != 1163 functionHasPassObjectSizeParams(Old)) 1164 return true; 1165 1166 // enable_if attributes are an order-sensitive part of the signature. 1167 for (specific_attr_iterator<EnableIfAttr> 1168 NewI = New->specific_attr_begin<EnableIfAttr>(), 1169 NewE = New->specific_attr_end<EnableIfAttr>(), 1170 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1171 OldE = Old->specific_attr_end<EnableIfAttr>(); 1172 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1173 if (NewI == NewE || OldI == OldE) 1174 return true; 1175 llvm::FoldingSetNodeID NewID, OldID; 1176 NewI->getCond()->Profile(NewID, Context, true); 1177 OldI->getCond()->Profile(OldID, Context, true); 1178 if (NewID != OldID) 1179 return true; 1180 } 1181 1182 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1183 // Don't allow overloading of destructors. (In theory we could, but it 1184 // would be a giant change to clang.) 1185 if (isa<CXXDestructorDecl>(New)) 1186 return false; 1187 1188 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1189 OldTarget = IdentifyCUDATarget(Old); 1190 if (NewTarget == CFT_InvalidTarget) 1191 return false; 1192 1193 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1194 1195 // Allow overloading of functions with same signature and different CUDA 1196 // target attributes. 1197 return NewTarget != OldTarget; 1198 } 1199 1200 // The signatures match; this is not an overload. 1201 return false; 1202 } 1203 1204 /// Checks availability of the function depending on the current 1205 /// function context. Inside an unavailable function, unavailability is ignored. 1206 /// 1207 /// \returns true if \arg FD is unavailable and current context is inside 1208 /// an available function, false otherwise. 1209 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1210 if (!FD->isUnavailable()) 1211 return false; 1212 1213 // Walk up the context of the caller. 1214 Decl *C = cast<Decl>(CurContext); 1215 do { 1216 if (C->isUnavailable()) 1217 return false; 1218 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1219 return true; 1220 } 1221 1222 /// Tries a user-defined conversion from From to ToType. 1223 /// 1224 /// Produces an implicit conversion sequence for when a standard conversion 1225 /// is not an option. See TryImplicitConversion for more information. 1226 static ImplicitConversionSequence 1227 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1228 bool SuppressUserConversions, 1229 bool AllowExplicit, 1230 bool InOverloadResolution, 1231 bool CStyle, 1232 bool AllowObjCWritebackConversion, 1233 bool AllowObjCConversionOnExplicit) { 1234 ImplicitConversionSequence ICS; 1235 1236 if (SuppressUserConversions) { 1237 // We're not in the case above, so there is no conversion that 1238 // we can perform. 1239 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1240 return ICS; 1241 } 1242 1243 // Attempt user-defined conversion. 1244 OverloadCandidateSet Conversions(From->getExprLoc(), 1245 OverloadCandidateSet::CSK_Normal); 1246 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1247 Conversions, AllowExplicit, 1248 AllowObjCConversionOnExplicit)) { 1249 case OR_Success: 1250 case OR_Deleted: 1251 ICS.setUserDefined(); 1252 // C++ [over.ics.user]p4: 1253 // A conversion of an expression of class type to the same class 1254 // type is given Exact Match rank, and a conversion of an 1255 // expression of class type to a base class of that type is 1256 // given Conversion rank, in spite of the fact that a copy 1257 // constructor (i.e., a user-defined conversion function) is 1258 // called for those cases. 1259 if (CXXConstructorDecl *Constructor 1260 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1261 QualType FromCanon 1262 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1263 QualType ToCanon 1264 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1265 if (Constructor->isCopyConstructor() && 1266 (FromCanon == ToCanon || 1267 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1268 // Turn this into a "standard" conversion sequence, so that it 1269 // gets ranked with standard conversion sequences. 1270 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1271 ICS.setStandard(); 1272 ICS.Standard.setAsIdentityConversion(); 1273 ICS.Standard.setFromType(From->getType()); 1274 ICS.Standard.setAllToTypes(ToType); 1275 ICS.Standard.CopyConstructor = Constructor; 1276 ICS.Standard.FoundCopyConstructor = Found; 1277 if (ToCanon != FromCanon) 1278 ICS.Standard.Second = ICK_Derived_To_Base; 1279 } 1280 } 1281 break; 1282 1283 case OR_Ambiguous: 1284 ICS.setAmbiguous(); 1285 ICS.Ambiguous.setFromType(From->getType()); 1286 ICS.Ambiguous.setToType(ToType); 1287 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1288 Cand != Conversions.end(); ++Cand) 1289 if (Cand->Viable) 1290 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1291 break; 1292 1293 // Fall through. 1294 case OR_No_Viable_Function: 1295 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1296 break; 1297 } 1298 1299 return ICS; 1300 } 1301 1302 /// TryImplicitConversion - Attempt to perform an implicit conversion 1303 /// from the given expression (Expr) to the given type (ToType). This 1304 /// function returns an implicit conversion sequence that can be used 1305 /// to perform the initialization. Given 1306 /// 1307 /// void f(float f); 1308 /// void g(int i) { f(i); } 1309 /// 1310 /// this routine would produce an implicit conversion sequence to 1311 /// describe the initialization of f from i, which will be a standard 1312 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1313 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1314 // 1315 /// Note that this routine only determines how the conversion can be 1316 /// performed; it does not actually perform the conversion. As such, 1317 /// it will not produce any diagnostics if no conversion is available, 1318 /// but will instead return an implicit conversion sequence of kind 1319 /// "BadConversion". 1320 /// 1321 /// If @p SuppressUserConversions, then user-defined conversions are 1322 /// not permitted. 1323 /// If @p AllowExplicit, then explicit user-defined conversions are 1324 /// permitted. 1325 /// 1326 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1327 /// writeback conversion, which allows __autoreleasing id* parameters to 1328 /// be initialized with __strong id* or __weak id* arguments. 1329 static ImplicitConversionSequence 1330 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1331 bool SuppressUserConversions, 1332 bool AllowExplicit, 1333 bool InOverloadResolution, 1334 bool CStyle, 1335 bool AllowObjCWritebackConversion, 1336 bool AllowObjCConversionOnExplicit) { 1337 ImplicitConversionSequence ICS; 1338 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1339 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1340 ICS.setStandard(); 1341 return ICS; 1342 } 1343 1344 if (!S.getLangOpts().CPlusPlus) { 1345 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1346 return ICS; 1347 } 1348 1349 // C++ [over.ics.user]p4: 1350 // A conversion of an expression of class type to the same class 1351 // type is given Exact Match rank, and a conversion of an 1352 // expression of class type to a base class of that type is 1353 // given Conversion rank, in spite of the fact that a copy/move 1354 // constructor (i.e., a user-defined conversion function) is 1355 // called for those cases. 1356 QualType FromType = From->getType(); 1357 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1358 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1359 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1360 ICS.setStandard(); 1361 ICS.Standard.setAsIdentityConversion(); 1362 ICS.Standard.setFromType(FromType); 1363 ICS.Standard.setAllToTypes(ToType); 1364 1365 // We don't actually check at this point whether there is a valid 1366 // copy/move constructor, since overloading just assumes that it 1367 // exists. When we actually perform initialization, we'll find the 1368 // appropriate constructor to copy the returned object, if needed. 1369 ICS.Standard.CopyConstructor = nullptr; 1370 1371 // Determine whether this is considered a derived-to-base conversion. 1372 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1373 ICS.Standard.Second = ICK_Derived_To_Base; 1374 1375 return ICS; 1376 } 1377 1378 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1379 AllowExplicit, InOverloadResolution, CStyle, 1380 AllowObjCWritebackConversion, 1381 AllowObjCConversionOnExplicit); 1382 } 1383 1384 ImplicitConversionSequence 1385 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1386 bool SuppressUserConversions, 1387 bool AllowExplicit, 1388 bool InOverloadResolution, 1389 bool CStyle, 1390 bool AllowObjCWritebackConversion) { 1391 return ::TryImplicitConversion(*this, From, ToType, 1392 SuppressUserConversions, AllowExplicit, 1393 InOverloadResolution, CStyle, 1394 AllowObjCWritebackConversion, 1395 /*AllowObjCConversionOnExplicit=*/false); 1396 } 1397 1398 /// PerformImplicitConversion - Perform an implicit conversion of the 1399 /// expression From to the type ToType. Returns the 1400 /// converted expression. Flavor is the kind of conversion we're 1401 /// performing, used in the error message. If @p AllowExplicit, 1402 /// explicit user-defined conversions are permitted. 1403 ExprResult 1404 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1405 AssignmentAction Action, bool AllowExplicit) { 1406 ImplicitConversionSequence ICS; 1407 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1408 } 1409 1410 ExprResult 1411 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1412 AssignmentAction Action, bool AllowExplicit, 1413 ImplicitConversionSequence& ICS) { 1414 if (checkPlaceholderForOverload(*this, From)) 1415 return ExprError(); 1416 1417 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1418 bool AllowObjCWritebackConversion 1419 = getLangOpts().ObjCAutoRefCount && 1420 (Action == AA_Passing || Action == AA_Sending); 1421 if (getLangOpts().ObjC) 1422 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1423 From->getType(), From); 1424 ICS = ::TryImplicitConversion(*this, From, ToType, 1425 /*SuppressUserConversions=*/false, 1426 AllowExplicit, 1427 /*InOverloadResolution=*/false, 1428 /*CStyle=*/false, 1429 AllowObjCWritebackConversion, 1430 /*AllowObjCConversionOnExplicit=*/false); 1431 return PerformImplicitConversion(From, ToType, ICS, Action); 1432 } 1433 1434 /// Determine whether the conversion from FromType to ToType is a valid 1435 /// conversion that strips "noexcept" or "noreturn" off the nested function 1436 /// type. 1437 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1438 QualType &ResultTy) { 1439 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1440 return false; 1441 1442 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1443 // or F(t noexcept) -> F(t) 1444 // where F adds one of the following at most once: 1445 // - a pointer 1446 // - a member pointer 1447 // - a block pointer 1448 // Changes here need matching changes in FindCompositePointerType. 1449 CanQualType CanTo = Context.getCanonicalType(ToType); 1450 CanQualType CanFrom = Context.getCanonicalType(FromType); 1451 Type::TypeClass TyClass = CanTo->getTypeClass(); 1452 if (TyClass != CanFrom->getTypeClass()) return false; 1453 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1454 if (TyClass == Type::Pointer) { 1455 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1456 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1457 } else if (TyClass == Type::BlockPointer) { 1458 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1459 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1460 } else if (TyClass == Type::MemberPointer) { 1461 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1462 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1463 // A function pointer conversion cannot change the class of the function. 1464 if (ToMPT->getClass() != FromMPT->getClass()) 1465 return false; 1466 CanTo = ToMPT->getPointeeType(); 1467 CanFrom = FromMPT->getPointeeType(); 1468 } else { 1469 return false; 1470 } 1471 1472 TyClass = CanTo->getTypeClass(); 1473 if (TyClass != CanFrom->getTypeClass()) return false; 1474 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1475 return false; 1476 } 1477 1478 const auto *FromFn = cast<FunctionType>(CanFrom); 1479 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1480 1481 const auto *ToFn = cast<FunctionType>(CanTo); 1482 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1483 1484 bool Changed = false; 1485 1486 // Drop 'noreturn' if not present in target type. 1487 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1488 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1489 Changed = true; 1490 } 1491 1492 // Drop 'noexcept' if not present in target type. 1493 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1494 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1495 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1496 FromFn = cast<FunctionType>( 1497 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1498 EST_None) 1499 .getTypePtr()); 1500 Changed = true; 1501 } 1502 1503 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1504 // only if the ExtParameterInfo lists of the two function prototypes can be 1505 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1506 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1507 bool CanUseToFPT, CanUseFromFPT; 1508 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1509 CanUseFromFPT, NewParamInfos) && 1510 CanUseToFPT && !CanUseFromFPT) { 1511 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1512 ExtInfo.ExtParameterInfos = 1513 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1514 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1515 FromFPT->getParamTypes(), ExtInfo); 1516 FromFn = QT->getAs<FunctionType>(); 1517 Changed = true; 1518 } 1519 } 1520 1521 if (!Changed) 1522 return false; 1523 1524 assert(QualType(FromFn, 0).isCanonical()); 1525 if (QualType(FromFn, 0) != CanTo) return false; 1526 1527 ResultTy = ToType; 1528 return true; 1529 } 1530 1531 /// Determine whether the conversion from FromType to ToType is a valid 1532 /// vector conversion. 1533 /// 1534 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1535 /// conversion. 1536 static bool IsVectorConversion(Sema &S, QualType FromType, 1537 QualType ToType, ImplicitConversionKind &ICK) { 1538 // We need at least one of these types to be a vector type to have a vector 1539 // conversion. 1540 if (!ToType->isVectorType() && !FromType->isVectorType()) 1541 return false; 1542 1543 // Identical types require no conversions. 1544 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1545 return false; 1546 1547 // There are no conversions between extended vector types, only identity. 1548 if (ToType->isExtVectorType()) { 1549 // There are no conversions between extended vector types other than the 1550 // identity conversion. 1551 if (FromType->isExtVectorType()) 1552 return false; 1553 1554 // Vector splat from any arithmetic type to a vector. 1555 if (FromType->isArithmeticType()) { 1556 ICK = ICK_Vector_Splat; 1557 return true; 1558 } 1559 } 1560 1561 // We can perform the conversion between vector types in the following cases: 1562 // 1)vector types are equivalent AltiVec and GCC vector types 1563 // 2)lax vector conversions are permitted and the vector types are of the 1564 // same size 1565 if (ToType->isVectorType() && FromType->isVectorType()) { 1566 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1567 S.isLaxVectorConversion(FromType, ToType)) { 1568 ICK = ICK_Vector_Conversion; 1569 return true; 1570 } 1571 } 1572 1573 return false; 1574 } 1575 1576 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1577 bool InOverloadResolution, 1578 StandardConversionSequence &SCS, 1579 bool CStyle); 1580 1581 /// IsStandardConversion - Determines whether there is a standard 1582 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1583 /// expression From to the type ToType. Standard conversion sequences 1584 /// only consider non-class types; for conversions that involve class 1585 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1586 /// contain the standard conversion sequence required to perform this 1587 /// conversion and this routine will return true. Otherwise, this 1588 /// routine will return false and the value of SCS is unspecified. 1589 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1590 bool InOverloadResolution, 1591 StandardConversionSequence &SCS, 1592 bool CStyle, 1593 bool AllowObjCWritebackConversion) { 1594 QualType FromType = From->getType(); 1595 1596 // Standard conversions (C++ [conv]) 1597 SCS.setAsIdentityConversion(); 1598 SCS.IncompatibleObjC = false; 1599 SCS.setFromType(FromType); 1600 SCS.CopyConstructor = nullptr; 1601 1602 // There are no standard conversions for class types in C++, so 1603 // abort early. When overloading in C, however, we do permit them. 1604 if (S.getLangOpts().CPlusPlus && 1605 (FromType->isRecordType() || ToType->isRecordType())) 1606 return false; 1607 1608 // The first conversion can be an lvalue-to-rvalue conversion, 1609 // array-to-pointer conversion, or function-to-pointer conversion 1610 // (C++ 4p1). 1611 1612 if (FromType == S.Context.OverloadTy) { 1613 DeclAccessPair AccessPair; 1614 if (FunctionDecl *Fn 1615 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1616 AccessPair)) { 1617 // We were able to resolve the address of the overloaded function, 1618 // so we can convert to the type of that function. 1619 FromType = Fn->getType(); 1620 SCS.setFromType(FromType); 1621 1622 // we can sometimes resolve &foo<int> regardless of ToType, so check 1623 // if the type matches (identity) or we are converting to bool 1624 if (!S.Context.hasSameUnqualifiedType( 1625 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1626 QualType resultTy; 1627 // if the function type matches except for [[noreturn]], it's ok 1628 if (!S.IsFunctionConversion(FromType, 1629 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1630 // otherwise, only a boolean conversion is standard 1631 if (!ToType->isBooleanType()) 1632 return false; 1633 } 1634 1635 // Check if the "from" expression is taking the address of an overloaded 1636 // function and recompute the FromType accordingly. Take advantage of the 1637 // fact that non-static member functions *must* have such an address-of 1638 // expression. 1639 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1640 if (Method && !Method->isStatic()) { 1641 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1642 "Non-unary operator on non-static member address"); 1643 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1644 == UO_AddrOf && 1645 "Non-address-of operator on non-static member address"); 1646 const Type *ClassType 1647 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1648 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1649 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1650 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1651 UO_AddrOf && 1652 "Non-address-of operator for overloaded function expression"); 1653 FromType = S.Context.getPointerType(FromType); 1654 } 1655 1656 // Check that we've computed the proper type after overload resolution. 1657 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1658 // be calling it from within an NDEBUG block. 1659 assert(S.Context.hasSameType( 1660 FromType, 1661 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1662 } else { 1663 return false; 1664 } 1665 } 1666 // Lvalue-to-rvalue conversion (C++11 4.1): 1667 // A glvalue (3.10) of a non-function, non-array type T can 1668 // be converted to a prvalue. 1669 bool argIsLValue = From->isGLValue(); 1670 if (argIsLValue && 1671 !FromType->isFunctionType() && !FromType->isArrayType() && 1672 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1673 SCS.First = ICK_Lvalue_To_Rvalue; 1674 1675 // C11 6.3.2.1p2: 1676 // ... if the lvalue has atomic type, the value has the non-atomic version 1677 // of the type of the lvalue ... 1678 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1679 FromType = Atomic->getValueType(); 1680 1681 // If T is a non-class type, the type of the rvalue is the 1682 // cv-unqualified version of T. Otherwise, the type of the rvalue 1683 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1684 // just strip the qualifiers because they don't matter. 1685 FromType = FromType.getUnqualifiedType(); 1686 } else if (FromType->isArrayType()) { 1687 // Array-to-pointer conversion (C++ 4.2) 1688 SCS.First = ICK_Array_To_Pointer; 1689 1690 // An lvalue or rvalue of type "array of N T" or "array of unknown 1691 // bound of T" can be converted to an rvalue of type "pointer to 1692 // T" (C++ 4.2p1). 1693 FromType = S.Context.getArrayDecayedType(FromType); 1694 1695 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1696 // This conversion is deprecated in C++03 (D.4) 1697 SCS.DeprecatedStringLiteralToCharPtr = true; 1698 1699 // For the purpose of ranking in overload resolution 1700 // (13.3.3.1.1), this conversion is considered an 1701 // array-to-pointer conversion followed by a qualification 1702 // conversion (4.4). (C++ 4.2p2) 1703 SCS.Second = ICK_Identity; 1704 SCS.Third = ICK_Qualification; 1705 SCS.QualificationIncludesObjCLifetime = false; 1706 SCS.setAllToTypes(FromType); 1707 return true; 1708 } 1709 } else if (FromType->isFunctionType() && argIsLValue) { 1710 // Function-to-pointer conversion (C++ 4.3). 1711 SCS.First = ICK_Function_To_Pointer; 1712 1713 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1714 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1715 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1716 return false; 1717 1718 // An lvalue of function type T can be converted to an rvalue of 1719 // type "pointer to T." The result is a pointer to the 1720 // function. (C++ 4.3p1). 1721 FromType = S.Context.getPointerType(FromType); 1722 } else { 1723 // We don't require any conversions for the first step. 1724 SCS.First = ICK_Identity; 1725 } 1726 SCS.setToType(0, FromType); 1727 1728 // The second conversion can be an integral promotion, floating 1729 // point promotion, integral conversion, floating point conversion, 1730 // floating-integral conversion, pointer conversion, 1731 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1732 // For overloading in C, this can also be a "compatible-type" 1733 // conversion. 1734 bool IncompatibleObjC = false; 1735 ImplicitConversionKind SecondICK = ICK_Identity; 1736 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1737 // The unqualified versions of the types are the same: there's no 1738 // conversion to do. 1739 SCS.Second = ICK_Identity; 1740 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1741 // Integral promotion (C++ 4.5). 1742 SCS.Second = ICK_Integral_Promotion; 1743 FromType = ToType.getUnqualifiedType(); 1744 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1745 // Floating point promotion (C++ 4.6). 1746 SCS.Second = ICK_Floating_Promotion; 1747 FromType = ToType.getUnqualifiedType(); 1748 } else if (S.IsComplexPromotion(FromType, ToType)) { 1749 // Complex promotion (Clang extension) 1750 SCS.Second = ICK_Complex_Promotion; 1751 FromType = ToType.getUnqualifiedType(); 1752 } else if (ToType->isBooleanType() && 1753 (FromType->isArithmeticType() || 1754 FromType->isAnyPointerType() || 1755 FromType->isBlockPointerType() || 1756 FromType->isMemberPointerType() || 1757 FromType->isNullPtrType())) { 1758 // Boolean conversions (C++ 4.12). 1759 SCS.Second = ICK_Boolean_Conversion; 1760 FromType = S.Context.BoolTy; 1761 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1762 ToType->isIntegralType(S.Context)) { 1763 // Integral conversions (C++ 4.7). 1764 SCS.Second = ICK_Integral_Conversion; 1765 FromType = ToType.getUnqualifiedType(); 1766 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1767 // Complex conversions (C99 6.3.1.6) 1768 SCS.Second = ICK_Complex_Conversion; 1769 FromType = ToType.getUnqualifiedType(); 1770 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1771 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1772 // Complex-real conversions (C99 6.3.1.7) 1773 SCS.Second = ICK_Complex_Real; 1774 FromType = ToType.getUnqualifiedType(); 1775 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1776 // FIXME: disable conversions between long double and __float128 if 1777 // their representation is different until there is back end support 1778 // We of course allow this conversion if long double is really double. 1779 if (&S.Context.getFloatTypeSemantics(FromType) != 1780 &S.Context.getFloatTypeSemantics(ToType)) { 1781 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1782 ToType == S.Context.LongDoubleTy) || 1783 (FromType == S.Context.LongDoubleTy && 1784 ToType == S.Context.Float128Ty)); 1785 if (Float128AndLongDouble && 1786 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1787 &llvm::APFloat::PPCDoubleDouble())) 1788 return false; 1789 } 1790 // Floating point conversions (C++ 4.8). 1791 SCS.Second = ICK_Floating_Conversion; 1792 FromType = ToType.getUnqualifiedType(); 1793 } else if ((FromType->isRealFloatingType() && 1794 ToType->isIntegralType(S.Context)) || 1795 (FromType->isIntegralOrUnscopedEnumerationType() && 1796 ToType->isRealFloatingType())) { 1797 // Floating-integral conversions (C++ 4.9). 1798 SCS.Second = ICK_Floating_Integral; 1799 FromType = ToType.getUnqualifiedType(); 1800 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1801 SCS.Second = ICK_Block_Pointer_Conversion; 1802 } else if (AllowObjCWritebackConversion && 1803 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1804 SCS.Second = ICK_Writeback_Conversion; 1805 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1806 FromType, IncompatibleObjC)) { 1807 // Pointer conversions (C++ 4.10). 1808 SCS.Second = ICK_Pointer_Conversion; 1809 SCS.IncompatibleObjC = IncompatibleObjC; 1810 FromType = FromType.getUnqualifiedType(); 1811 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1812 InOverloadResolution, FromType)) { 1813 // Pointer to member conversions (4.11). 1814 SCS.Second = ICK_Pointer_Member; 1815 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1816 SCS.Second = SecondICK; 1817 FromType = ToType.getUnqualifiedType(); 1818 } else if (!S.getLangOpts().CPlusPlus && 1819 S.Context.typesAreCompatible(ToType, FromType)) { 1820 // Compatible conversions (Clang extension for C function overloading) 1821 SCS.Second = ICK_Compatible_Conversion; 1822 FromType = ToType.getUnqualifiedType(); 1823 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1824 InOverloadResolution, 1825 SCS, CStyle)) { 1826 SCS.Second = ICK_TransparentUnionConversion; 1827 FromType = ToType; 1828 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1829 CStyle)) { 1830 // tryAtomicConversion has updated the standard conversion sequence 1831 // appropriately. 1832 return true; 1833 } else if (ToType->isEventT() && 1834 From->isIntegerConstantExpr(S.getASTContext()) && 1835 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1836 SCS.Second = ICK_Zero_Event_Conversion; 1837 FromType = ToType; 1838 } else if (ToType->isQueueT() && 1839 From->isIntegerConstantExpr(S.getASTContext()) && 1840 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1841 SCS.Second = ICK_Zero_Queue_Conversion; 1842 FromType = ToType; 1843 } else { 1844 // No second conversion required. 1845 SCS.Second = ICK_Identity; 1846 } 1847 SCS.setToType(1, FromType); 1848 1849 // The third conversion can be a function pointer conversion or a 1850 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1851 bool ObjCLifetimeConversion; 1852 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1853 // Function pointer conversions (removing 'noexcept') including removal of 1854 // 'noreturn' (Clang extension). 1855 SCS.Third = ICK_Function_Conversion; 1856 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1857 ObjCLifetimeConversion)) { 1858 SCS.Third = ICK_Qualification; 1859 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1860 FromType = ToType; 1861 } else { 1862 // No conversion required 1863 SCS.Third = ICK_Identity; 1864 } 1865 1866 // C++ [over.best.ics]p6: 1867 // [...] Any difference in top-level cv-qualification is 1868 // subsumed by the initialization itself and does not constitute 1869 // a conversion. [...] 1870 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1871 QualType CanonTo = S.Context.getCanonicalType(ToType); 1872 if (CanonFrom.getLocalUnqualifiedType() 1873 == CanonTo.getLocalUnqualifiedType() && 1874 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1875 FromType = ToType; 1876 CanonFrom = CanonTo; 1877 } 1878 1879 SCS.setToType(2, FromType); 1880 1881 if (CanonFrom == CanonTo) 1882 return true; 1883 1884 // If we have not converted the argument type to the parameter type, 1885 // this is a bad conversion sequence, unless we're resolving an overload in C. 1886 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1887 return false; 1888 1889 ExprResult ER = ExprResult{From}; 1890 Sema::AssignConvertType Conv = 1891 S.CheckSingleAssignmentConstraints(ToType, ER, 1892 /*Diagnose=*/false, 1893 /*DiagnoseCFAudited=*/false, 1894 /*ConvertRHS=*/false); 1895 ImplicitConversionKind SecondConv; 1896 switch (Conv) { 1897 case Sema::Compatible: 1898 SecondConv = ICK_C_Only_Conversion; 1899 break; 1900 // For our purposes, discarding qualifiers is just as bad as using an 1901 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1902 // qualifiers, as well. 1903 case Sema::CompatiblePointerDiscardsQualifiers: 1904 case Sema::IncompatiblePointer: 1905 case Sema::IncompatiblePointerSign: 1906 SecondConv = ICK_Incompatible_Pointer_Conversion; 1907 break; 1908 default: 1909 return false; 1910 } 1911 1912 // First can only be an lvalue conversion, so we pretend that this was the 1913 // second conversion. First should already be valid from earlier in the 1914 // function. 1915 SCS.Second = SecondConv; 1916 SCS.setToType(1, ToType); 1917 1918 // Third is Identity, because Second should rank us worse than any other 1919 // conversion. This could also be ICK_Qualification, but it's simpler to just 1920 // lump everything in with the second conversion, and we don't gain anything 1921 // from making this ICK_Qualification. 1922 SCS.Third = ICK_Identity; 1923 SCS.setToType(2, ToType); 1924 return true; 1925 } 1926 1927 static bool 1928 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1929 QualType &ToType, 1930 bool InOverloadResolution, 1931 StandardConversionSequence &SCS, 1932 bool CStyle) { 1933 1934 const RecordType *UT = ToType->getAsUnionType(); 1935 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1936 return false; 1937 // The field to initialize within the transparent union. 1938 RecordDecl *UD = UT->getDecl(); 1939 // It's compatible if the expression matches any of the fields. 1940 for (const auto *it : UD->fields()) { 1941 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1942 CStyle, /*ObjCWritebackConversion=*/false)) { 1943 ToType = it->getType(); 1944 return true; 1945 } 1946 } 1947 return false; 1948 } 1949 1950 /// IsIntegralPromotion - Determines whether the conversion from the 1951 /// expression From (whose potentially-adjusted type is FromType) to 1952 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1953 /// sets PromotedType to the promoted type. 1954 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1955 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1956 // All integers are built-in. 1957 if (!To) { 1958 return false; 1959 } 1960 1961 // An rvalue of type char, signed char, unsigned char, short int, or 1962 // unsigned short int can be converted to an rvalue of type int if 1963 // int can represent all the values of the source type; otherwise, 1964 // the source rvalue can be converted to an rvalue of type unsigned 1965 // int (C++ 4.5p1). 1966 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1967 !FromType->isEnumeralType()) { 1968 if (// We can promote any signed, promotable integer type to an int 1969 (FromType->isSignedIntegerType() || 1970 // We can promote any unsigned integer type whose size is 1971 // less than int to an int. 1972 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1973 return To->getKind() == BuiltinType::Int; 1974 } 1975 1976 return To->getKind() == BuiltinType::UInt; 1977 } 1978 1979 // C++11 [conv.prom]p3: 1980 // A prvalue of an unscoped enumeration type whose underlying type is not 1981 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1982 // following types that can represent all the values of the enumeration 1983 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1984 // unsigned int, long int, unsigned long int, long long int, or unsigned 1985 // long long int. If none of the types in that list can represent all the 1986 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1987 // type can be converted to an rvalue a prvalue of the extended integer type 1988 // with lowest integer conversion rank (4.13) greater than the rank of long 1989 // long in which all the values of the enumeration can be represented. If 1990 // there are two such extended types, the signed one is chosen. 1991 // C++11 [conv.prom]p4: 1992 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1993 // can be converted to a prvalue of its underlying type. Moreover, if 1994 // integral promotion can be applied to its underlying type, a prvalue of an 1995 // unscoped enumeration type whose underlying type is fixed can also be 1996 // converted to a prvalue of the promoted underlying type. 1997 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1998 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1999 // provided for a scoped enumeration. 2000 if (FromEnumType->getDecl()->isScoped()) 2001 return false; 2002 2003 // We can perform an integral promotion to the underlying type of the enum, 2004 // even if that's not the promoted type. Note that the check for promoting 2005 // the underlying type is based on the type alone, and does not consider 2006 // the bitfield-ness of the actual source expression. 2007 if (FromEnumType->getDecl()->isFixed()) { 2008 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2009 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2010 IsIntegralPromotion(nullptr, Underlying, ToType); 2011 } 2012 2013 // We have already pre-calculated the promotion type, so this is trivial. 2014 if (ToType->isIntegerType() && 2015 isCompleteType(From->getBeginLoc(), FromType)) 2016 return Context.hasSameUnqualifiedType( 2017 ToType, FromEnumType->getDecl()->getPromotionType()); 2018 2019 // C++ [conv.prom]p5: 2020 // If the bit-field has an enumerated type, it is treated as any other 2021 // value of that type for promotion purposes. 2022 // 2023 // ... so do not fall through into the bit-field checks below in C++. 2024 if (getLangOpts().CPlusPlus) 2025 return false; 2026 } 2027 2028 // C++0x [conv.prom]p2: 2029 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2030 // to an rvalue a prvalue of the first of the following types that can 2031 // represent all the values of its underlying type: int, unsigned int, 2032 // long int, unsigned long int, long long int, or unsigned long long int. 2033 // If none of the types in that list can represent all the values of its 2034 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2035 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2036 // type. 2037 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2038 ToType->isIntegerType()) { 2039 // Determine whether the type we're converting from is signed or 2040 // unsigned. 2041 bool FromIsSigned = FromType->isSignedIntegerType(); 2042 uint64_t FromSize = Context.getTypeSize(FromType); 2043 2044 // The types we'll try to promote to, in the appropriate 2045 // order. Try each of these types. 2046 QualType PromoteTypes[6] = { 2047 Context.IntTy, Context.UnsignedIntTy, 2048 Context.LongTy, Context.UnsignedLongTy , 2049 Context.LongLongTy, Context.UnsignedLongLongTy 2050 }; 2051 for (int Idx = 0; Idx < 6; ++Idx) { 2052 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2053 if (FromSize < ToSize || 2054 (FromSize == ToSize && 2055 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2056 // We found the type that we can promote to. If this is the 2057 // type we wanted, we have a promotion. Otherwise, no 2058 // promotion. 2059 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2060 } 2061 } 2062 } 2063 2064 // An rvalue for an integral bit-field (9.6) can be converted to an 2065 // rvalue of type int if int can represent all the values of the 2066 // bit-field; otherwise, it can be converted to unsigned int if 2067 // unsigned int can represent all the values of the bit-field. If 2068 // the bit-field is larger yet, no integral promotion applies to 2069 // it. If the bit-field has an enumerated type, it is treated as any 2070 // other value of that type for promotion purposes (C++ 4.5p3). 2071 // FIXME: We should delay checking of bit-fields until we actually perform the 2072 // conversion. 2073 // 2074 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2075 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2076 // bit-fields and those whose underlying type is larger than int) for GCC 2077 // compatibility. 2078 if (From) { 2079 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2080 llvm::APSInt BitWidth; 2081 if (FromType->isIntegralType(Context) && 2082 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2083 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2084 ToSize = Context.getTypeSize(ToType); 2085 2086 // Are we promoting to an int from a bitfield that fits in an int? 2087 if (BitWidth < ToSize || 2088 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2089 return To->getKind() == BuiltinType::Int; 2090 } 2091 2092 // Are we promoting to an unsigned int from an unsigned bitfield 2093 // that fits into an unsigned int? 2094 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2095 return To->getKind() == BuiltinType::UInt; 2096 } 2097 2098 return false; 2099 } 2100 } 2101 } 2102 2103 // An rvalue of type bool can be converted to an rvalue of type int, 2104 // with false becoming zero and true becoming one (C++ 4.5p4). 2105 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2106 return true; 2107 } 2108 2109 return false; 2110 } 2111 2112 /// IsFloatingPointPromotion - Determines whether the conversion from 2113 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2114 /// returns true and sets PromotedType to the promoted type. 2115 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2116 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2117 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2118 /// An rvalue of type float can be converted to an rvalue of type 2119 /// double. (C++ 4.6p1). 2120 if (FromBuiltin->getKind() == BuiltinType::Float && 2121 ToBuiltin->getKind() == BuiltinType::Double) 2122 return true; 2123 2124 // C99 6.3.1.5p1: 2125 // When a float is promoted to double or long double, or a 2126 // double is promoted to long double [...]. 2127 if (!getLangOpts().CPlusPlus && 2128 (FromBuiltin->getKind() == BuiltinType::Float || 2129 FromBuiltin->getKind() == BuiltinType::Double) && 2130 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2131 ToBuiltin->getKind() == BuiltinType::Float128)) 2132 return true; 2133 2134 // Half can be promoted to float. 2135 if (!getLangOpts().NativeHalfType && 2136 FromBuiltin->getKind() == BuiltinType::Half && 2137 ToBuiltin->getKind() == BuiltinType::Float) 2138 return true; 2139 } 2140 2141 return false; 2142 } 2143 2144 /// Determine if a conversion is a complex promotion. 2145 /// 2146 /// A complex promotion is defined as a complex -> complex conversion 2147 /// where the conversion between the underlying real types is a 2148 /// floating-point or integral promotion. 2149 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2150 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2151 if (!FromComplex) 2152 return false; 2153 2154 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2155 if (!ToComplex) 2156 return false; 2157 2158 return IsFloatingPointPromotion(FromComplex->getElementType(), 2159 ToComplex->getElementType()) || 2160 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2161 ToComplex->getElementType()); 2162 } 2163 2164 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2165 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2166 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2167 /// if non-empty, will be a pointer to ToType that may or may not have 2168 /// the right set of qualifiers on its pointee. 2169 /// 2170 static QualType 2171 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2172 QualType ToPointee, QualType ToType, 2173 ASTContext &Context, 2174 bool StripObjCLifetime = false) { 2175 assert((FromPtr->getTypeClass() == Type::Pointer || 2176 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2177 "Invalid similarly-qualified pointer type"); 2178 2179 /// Conversions to 'id' subsume cv-qualifier conversions. 2180 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2181 return ToType.getUnqualifiedType(); 2182 2183 QualType CanonFromPointee 2184 = Context.getCanonicalType(FromPtr->getPointeeType()); 2185 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2186 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2187 2188 if (StripObjCLifetime) 2189 Quals.removeObjCLifetime(); 2190 2191 // Exact qualifier match -> return the pointer type we're converting to. 2192 if (CanonToPointee.getLocalQualifiers() == Quals) { 2193 // ToType is exactly what we need. Return it. 2194 if (!ToType.isNull()) 2195 return ToType.getUnqualifiedType(); 2196 2197 // Build a pointer to ToPointee. It has the right qualifiers 2198 // already. 2199 if (isa<ObjCObjectPointerType>(ToType)) 2200 return Context.getObjCObjectPointerType(ToPointee); 2201 return Context.getPointerType(ToPointee); 2202 } 2203 2204 // Just build a canonical type that has the right qualifiers. 2205 QualType QualifiedCanonToPointee 2206 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2207 2208 if (isa<ObjCObjectPointerType>(ToType)) 2209 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2210 return Context.getPointerType(QualifiedCanonToPointee); 2211 } 2212 2213 static bool isNullPointerConstantForConversion(Expr *Expr, 2214 bool InOverloadResolution, 2215 ASTContext &Context) { 2216 // Handle value-dependent integral null pointer constants correctly. 2217 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2218 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2219 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2220 return !InOverloadResolution; 2221 2222 return Expr->isNullPointerConstant(Context, 2223 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2224 : Expr::NPC_ValueDependentIsNull); 2225 } 2226 2227 /// IsPointerConversion - Determines whether the conversion of the 2228 /// expression From, which has the (possibly adjusted) type FromType, 2229 /// can be converted to the type ToType via a pointer conversion (C++ 2230 /// 4.10). If so, returns true and places the converted type (that 2231 /// might differ from ToType in its cv-qualifiers at some level) into 2232 /// ConvertedType. 2233 /// 2234 /// This routine also supports conversions to and from block pointers 2235 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2236 /// pointers to interfaces. FIXME: Once we've determined the 2237 /// appropriate overloading rules for Objective-C, we may want to 2238 /// split the Objective-C checks into a different routine; however, 2239 /// GCC seems to consider all of these conversions to be pointer 2240 /// conversions, so for now they live here. IncompatibleObjC will be 2241 /// set if the conversion is an allowed Objective-C conversion that 2242 /// should result in a warning. 2243 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2244 bool InOverloadResolution, 2245 QualType& ConvertedType, 2246 bool &IncompatibleObjC) { 2247 IncompatibleObjC = false; 2248 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2249 IncompatibleObjC)) 2250 return true; 2251 2252 // Conversion from a null pointer constant to any Objective-C pointer type. 2253 if (ToType->isObjCObjectPointerType() && 2254 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2255 ConvertedType = ToType; 2256 return true; 2257 } 2258 2259 // Blocks: Block pointers can be converted to void*. 2260 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2261 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2262 ConvertedType = ToType; 2263 return true; 2264 } 2265 // Blocks: A null pointer constant can be converted to a block 2266 // pointer type. 2267 if (ToType->isBlockPointerType() && 2268 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2269 ConvertedType = ToType; 2270 return true; 2271 } 2272 2273 // If the left-hand-side is nullptr_t, the right side can be a null 2274 // pointer constant. 2275 if (ToType->isNullPtrType() && 2276 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2277 ConvertedType = ToType; 2278 return true; 2279 } 2280 2281 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2282 if (!ToTypePtr) 2283 return false; 2284 2285 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2286 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2287 ConvertedType = ToType; 2288 return true; 2289 } 2290 2291 // Beyond this point, both types need to be pointers 2292 // , including objective-c pointers. 2293 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2294 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2295 !getLangOpts().ObjCAutoRefCount) { 2296 ConvertedType = BuildSimilarlyQualifiedPointerType( 2297 FromType->getAs<ObjCObjectPointerType>(), 2298 ToPointeeType, 2299 ToType, Context); 2300 return true; 2301 } 2302 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2303 if (!FromTypePtr) 2304 return false; 2305 2306 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2307 2308 // If the unqualified pointee types are the same, this can't be a 2309 // pointer conversion, so don't do all of the work below. 2310 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2311 return false; 2312 2313 // An rvalue of type "pointer to cv T," where T is an object type, 2314 // can be converted to an rvalue of type "pointer to cv void" (C++ 2315 // 4.10p2). 2316 if (FromPointeeType->isIncompleteOrObjectType() && 2317 ToPointeeType->isVoidType()) { 2318 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2319 ToPointeeType, 2320 ToType, Context, 2321 /*StripObjCLifetime=*/true); 2322 return true; 2323 } 2324 2325 // MSVC allows implicit function to void* type conversion. 2326 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2327 ToPointeeType->isVoidType()) { 2328 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2329 ToPointeeType, 2330 ToType, Context); 2331 return true; 2332 } 2333 2334 // When we're overloading in C, we allow a special kind of pointer 2335 // conversion for compatible-but-not-identical pointee types. 2336 if (!getLangOpts().CPlusPlus && 2337 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2338 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2339 ToPointeeType, 2340 ToType, Context); 2341 return true; 2342 } 2343 2344 // C++ [conv.ptr]p3: 2345 // 2346 // An rvalue of type "pointer to cv D," where D is a class type, 2347 // can be converted to an rvalue of type "pointer to cv B," where 2348 // B is a base class (clause 10) of D. If B is an inaccessible 2349 // (clause 11) or ambiguous (10.2) base class of D, a program that 2350 // necessitates this conversion is ill-formed. The result of the 2351 // conversion is a pointer to the base class sub-object of the 2352 // derived class object. The null pointer value is converted to 2353 // the null pointer value of the destination type. 2354 // 2355 // Note that we do not check for ambiguity or inaccessibility 2356 // here. That is handled by CheckPointerConversion. 2357 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2358 ToPointeeType->isRecordType() && 2359 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2360 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2361 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2362 ToPointeeType, 2363 ToType, Context); 2364 return true; 2365 } 2366 2367 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2368 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2369 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2370 ToPointeeType, 2371 ToType, Context); 2372 return true; 2373 } 2374 2375 return false; 2376 } 2377 2378 /// Adopt the given qualifiers for the given type. 2379 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2380 Qualifiers TQs = T.getQualifiers(); 2381 2382 // Check whether qualifiers already match. 2383 if (TQs == Qs) 2384 return T; 2385 2386 if (Qs.compatiblyIncludes(TQs)) 2387 return Context.getQualifiedType(T, Qs); 2388 2389 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2390 } 2391 2392 /// isObjCPointerConversion - Determines whether this is an 2393 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2394 /// with the same arguments and return values. 2395 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2396 QualType& ConvertedType, 2397 bool &IncompatibleObjC) { 2398 if (!getLangOpts().ObjC) 2399 return false; 2400 2401 // The set of qualifiers on the type we're converting from. 2402 Qualifiers FromQualifiers = FromType.getQualifiers(); 2403 2404 // First, we handle all conversions on ObjC object pointer types. 2405 const ObjCObjectPointerType* ToObjCPtr = 2406 ToType->getAs<ObjCObjectPointerType>(); 2407 const ObjCObjectPointerType *FromObjCPtr = 2408 FromType->getAs<ObjCObjectPointerType>(); 2409 2410 if (ToObjCPtr && FromObjCPtr) { 2411 // If the pointee types are the same (ignoring qualifications), 2412 // then this is not a pointer conversion. 2413 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2414 FromObjCPtr->getPointeeType())) 2415 return false; 2416 2417 // Conversion between Objective-C pointers. 2418 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2419 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2420 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2421 if (getLangOpts().CPlusPlus && LHS && RHS && 2422 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2423 FromObjCPtr->getPointeeType())) 2424 return false; 2425 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2426 ToObjCPtr->getPointeeType(), 2427 ToType, Context); 2428 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2429 return true; 2430 } 2431 2432 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2433 // Okay: this is some kind of implicit downcast of Objective-C 2434 // interfaces, which is permitted. However, we're going to 2435 // complain about it. 2436 IncompatibleObjC = true; 2437 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2438 ToObjCPtr->getPointeeType(), 2439 ToType, Context); 2440 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2441 return true; 2442 } 2443 } 2444 // Beyond this point, both types need to be C pointers or block pointers. 2445 QualType ToPointeeType; 2446 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2447 ToPointeeType = ToCPtr->getPointeeType(); 2448 else if (const BlockPointerType *ToBlockPtr = 2449 ToType->getAs<BlockPointerType>()) { 2450 // Objective C++: We're able to convert from a pointer to any object 2451 // to a block pointer type. 2452 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2453 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2454 return true; 2455 } 2456 ToPointeeType = ToBlockPtr->getPointeeType(); 2457 } 2458 else if (FromType->getAs<BlockPointerType>() && 2459 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2460 // Objective C++: We're able to convert from a block pointer type to a 2461 // pointer to any object. 2462 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2463 return true; 2464 } 2465 else 2466 return false; 2467 2468 QualType FromPointeeType; 2469 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2470 FromPointeeType = FromCPtr->getPointeeType(); 2471 else if (const BlockPointerType *FromBlockPtr = 2472 FromType->getAs<BlockPointerType>()) 2473 FromPointeeType = FromBlockPtr->getPointeeType(); 2474 else 2475 return false; 2476 2477 // If we have pointers to pointers, recursively check whether this 2478 // is an Objective-C conversion. 2479 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2480 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2481 IncompatibleObjC)) { 2482 // We always complain about this conversion. 2483 IncompatibleObjC = true; 2484 ConvertedType = Context.getPointerType(ConvertedType); 2485 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2486 return true; 2487 } 2488 // Allow conversion of pointee being objective-c pointer to another one; 2489 // as in I* to id. 2490 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2491 ToPointeeType->getAs<ObjCObjectPointerType>() && 2492 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2493 IncompatibleObjC)) { 2494 2495 ConvertedType = Context.getPointerType(ConvertedType); 2496 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2497 return true; 2498 } 2499 2500 // If we have pointers to functions or blocks, check whether the only 2501 // differences in the argument and result types are in Objective-C 2502 // pointer conversions. If so, we permit the conversion (but 2503 // complain about it). 2504 const FunctionProtoType *FromFunctionType 2505 = FromPointeeType->getAs<FunctionProtoType>(); 2506 const FunctionProtoType *ToFunctionType 2507 = ToPointeeType->getAs<FunctionProtoType>(); 2508 if (FromFunctionType && ToFunctionType) { 2509 // If the function types are exactly the same, this isn't an 2510 // Objective-C pointer conversion. 2511 if (Context.getCanonicalType(FromPointeeType) 2512 == Context.getCanonicalType(ToPointeeType)) 2513 return false; 2514 2515 // Perform the quick checks that will tell us whether these 2516 // function types are obviously different. 2517 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2518 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2519 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2520 return false; 2521 2522 bool HasObjCConversion = false; 2523 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2524 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2525 // Okay, the types match exactly. Nothing to do. 2526 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2527 ToFunctionType->getReturnType(), 2528 ConvertedType, IncompatibleObjC)) { 2529 // Okay, we have an Objective-C pointer conversion. 2530 HasObjCConversion = true; 2531 } else { 2532 // Function types are too different. Abort. 2533 return false; 2534 } 2535 2536 // Check argument types. 2537 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2538 ArgIdx != NumArgs; ++ArgIdx) { 2539 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2540 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2541 if (Context.getCanonicalType(FromArgType) 2542 == Context.getCanonicalType(ToArgType)) { 2543 // Okay, the types match exactly. Nothing to do. 2544 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2545 ConvertedType, IncompatibleObjC)) { 2546 // Okay, we have an Objective-C pointer conversion. 2547 HasObjCConversion = true; 2548 } else { 2549 // Argument types are too different. Abort. 2550 return false; 2551 } 2552 } 2553 2554 if (HasObjCConversion) { 2555 // We had an Objective-C conversion. Allow this pointer 2556 // conversion, but complain about it. 2557 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2558 IncompatibleObjC = true; 2559 return true; 2560 } 2561 } 2562 2563 return false; 2564 } 2565 2566 /// Determine whether this is an Objective-C writeback conversion, 2567 /// used for parameter passing when performing automatic reference counting. 2568 /// 2569 /// \param FromType The type we're converting form. 2570 /// 2571 /// \param ToType The type we're converting to. 2572 /// 2573 /// \param ConvertedType The type that will be produced after applying 2574 /// this conversion. 2575 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2576 QualType &ConvertedType) { 2577 if (!getLangOpts().ObjCAutoRefCount || 2578 Context.hasSameUnqualifiedType(FromType, ToType)) 2579 return false; 2580 2581 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2582 QualType ToPointee; 2583 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2584 ToPointee = ToPointer->getPointeeType(); 2585 else 2586 return false; 2587 2588 Qualifiers ToQuals = ToPointee.getQualifiers(); 2589 if (!ToPointee->isObjCLifetimeType() || 2590 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2591 !ToQuals.withoutObjCLifetime().empty()) 2592 return false; 2593 2594 // Argument must be a pointer to __strong to __weak. 2595 QualType FromPointee; 2596 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2597 FromPointee = FromPointer->getPointeeType(); 2598 else 2599 return false; 2600 2601 Qualifiers FromQuals = FromPointee.getQualifiers(); 2602 if (!FromPointee->isObjCLifetimeType() || 2603 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2604 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2605 return false; 2606 2607 // Make sure that we have compatible qualifiers. 2608 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2609 if (!ToQuals.compatiblyIncludes(FromQuals)) 2610 return false; 2611 2612 // Remove qualifiers from the pointee type we're converting from; they 2613 // aren't used in the compatibility check belong, and we'll be adding back 2614 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2615 FromPointee = FromPointee.getUnqualifiedType(); 2616 2617 // The unqualified form of the pointee types must be compatible. 2618 ToPointee = ToPointee.getUnqualifiedType(); 2619 bool IncompatibleObjC; 2620 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2621 FromPointee = ToPointee; 2622 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2623 IncompatibleObjC)) 2624 return false; 2625 2626 /// Construct the type we're converting to, which is a pointer to 2627 /// __autoreleasing pointee. 2628 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2629 ConvertedType = Context.getPointerType(FromPointee); 2630 return true; 2631 } 2632 2633 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2634 QualType& ConvertedType) { 2635 QualType ToPointeeType; 2636 if (const BlockPointerType *ToBlockPtr = 2637 ToType->getAs<BlockPointerType>()) 2638 ToPointeeType = ToBlockPtr->getPointeeType(); 2639 else 2640 return false; 2641 2642 QualType FromPointeeType; 2643 if (const BlockPointerType *FromBlockPtr = 2644 FromType->getAs<BlockPointerType>()) 2645 FromPointeeType = FromBlockPtr->getPointeeType(); 2646 else 2647 return false; 2648 // We have pointer to blocks, check whether the only 2649 // differences in the argument and result types are in Objective-C 2650 // pointer conversions. If so, we permit the conversion. 2651 2652 const FunctionProtoType *FromFunctionType 2653 = FromPointeeType->getAs<FunctionProtoType>(); 2654 const FunctionProtoType *ToFunctionType 2655 = ToPointeeType->getAs<FunctionProtoType>(); 2656 2657 if (!FromFunctionType || !ToFunctionType) 2658 return false; 2659 2660 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2661 return true; 2662 2663 // Perform the quick checks that will tell us whether these 2664 // function types are obviously different. 2665 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2666 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2667 return false; 2668 2669 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2670 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2671 if (FromEInfo != ToEInfo) 2672 return false; 2673 2674 bool IncompatibleObjC = false; 2675 if (Context.hasSameType(FromFunctionType->getReturnType(), 2676 ToFunctionType->getReturnType())) { 2677 // Okay, the types match exactly. Nothing to do. 2678 } else { 2679 QualType RHS = FromFunctionType->getReturnType(); 2680 QualType LHS = ToFunctionType->getReturnType(); 2681 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2682 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2683 LHS = LHS.getUnqualifiedType(); 2684 2685 if (Context.hasSameType(RHS,LHS)) { 2686 // OK exact match. 2687 } else if (isObjCPointerConversion(RHS, LHS, 2688 ConvertedType, IncompatibleObjC)) { 2689 if (IncompatibleObjC) 2690 return false; 2691 // Okay, we have an Objective-C pointer conversion. 2692 } 2693 else 2694 return false; 2695 } 2696 2697 // Check argument types. 2698 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2699 ArgIdx != NumArgs; ++ArgIdx) { 2700 IncompatibleObjC = false; 2701 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2702 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2703 if (Context.hasSameType(FromArgType, ToArgType)) { 2704 // Okay, the types match exactly. Nothing to do. 2705 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2706 ConvertedType, IncompatibleObjC)) { 2707 if (IncompatibleObjC) 2708 return false; 2709 // Okay, we have an Objective-C pointer conversion. 2710 } else 2711 // Argument types are too different. Abort. 2712 return false; 2713 } 2714 2715 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2716 bool CanUseToFPT, CanUseFromFPT; 2717 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2718 CanUseToFPT, CanUseFromFPT, 2719 NewParamInfos)) 2720 return false; 2721 2722 ConvertedType = ToType; 2723 return true; 2724 } 2725 2726 enum { 2727 ft_default, 2728 ft_different_class, 2729 ft_parameter_arity, 2730 ft_parameter_mismatch, 2731 ft_return_type, 2732 ft_qualifer_mismatch, 2733 ft_noexcept 2734 }; 2735 2736 /// Attempts to get the FunctionProtoType from a Type. Handles 2737 /// MemberFunctionPointers properly. 2738 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2739 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2740 return FPT; 2741 2742 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2743 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2744 2745 return nullptr; 2746 } 2747 2748 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2749 /// function types. Catches different number of parameter, mismatch in 2750 /// parameter types, and different return types. 2751 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2752 QualType FromType, QualType ToType) { 2753 // If either type is not valid, include no extra info. 2754 if (FromType.isNull() || ToType.isNull()) { 2755 PDiag << ft_default; 2756 return; 2757 } 2758 2759 // Get the function type from the pointers. 2760 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2761 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2762 *ToMember = ToType->getAs<MemberPointerType>(); 2763 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2764 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2765 << QualType(FromMember->getClass(), 0); 2766 return; 2767 } 2768 FromType = FromMember->getPointeeType(); 2769 ToType = ToMember->getPointeeType(); 2770 } 2771 2772 if (FromType->isPointerType()) 2773 FromType = FromType->getPointeeType(); 2774 if (ToType->isPointerType()) 2775 ToType = ToType->getPointeeType(); 2776 2777 // Remove references. 2778 FromType = FromType.getNonReferenceType(); 2779 ToType = ToType.getNonReferenceType(); 2780 2781 // Don't print extra info for non-specialized template functions. 2782 if (FromType->isInstantiationDependentType() && 2783 !FromType->getAs<TemplateSpecializationType>()) { 2784 PDiag << ft_default; 2785 return; 2786 } 2787 2788 // No extra info for same types. 2789 if (Context.hasSameType(FromType, ToType)) { 2790 PDiag << ft_default; 2791 return; 2792 } 2793 2794 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2795 *ToFunction = tryGetFunctionProtoType(ToType); 2796 2797 // Both types need to be function types. 2798 if (!FromFunction || !ToFunction) { 2799 PDiag << ft_default; 2800 return; 2801 } 2802 2803 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2804 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2805 << FromFunction->getNumParams(); 2806 return; 2807 } 2808 2809 // Handle different parameter types. 2810 unsigned ArgPos; 2811 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2812 PDiag << ft_parameter_mismatch << ArgPos + 1 2813 << ToFunction->getParamType(ArgPos) 2814 << FromFunction->getParamType(ArgPos); 2815 return; 2816 } 2817 2818 // Handle different return type. 2819 if (!Context.hasSameType(FromFunction->getReturnType(), 2820 ToFunction->getReturnType())) { 2821 PDiag << ft_return_type << ToFunction->getReturnType() 2822 << FromFunction->getReturnType(); 2823 return; 2824 } 2825 2826 unsigned FromQuals = FromFunction->getTypeQuals(), 2827 ToQuals = ToFunction->getTypeQuals(); 2828 if (FromQuals != ToQuals) { 2829 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2830 return; 2831 } 2832 2833 // Handle exception specification differences on canonical type (in C++17 2834 // onwards). 2835 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2836 ->isNothrow() != 2837 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2838 ->isNothrow()) { 2839 PDiag << ft_noexcept; 2840 return; 2841 } 2842 2843 // Unable to find a difference, so add no extra info. 2844 PDiag << ft_default; 2845 } 2846 2847 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2848 /// for equality of their argument types. Caller has already checked that 2849 /// they have same number of arguments. If the parameters are different, 2850 /// ArgPos will have the parameter index of the first different parameter. 2851 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2852 const FunctionProtoType *NewType, 2853 unsigned *ArgPos) { 2854 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2855 N = NewType->param_type_begin(), 2856 E = OldType->param_type_end(); 2857 O && (O != E); ++O, ++N) { 2858 if (!Context.hasSameType(O->getUnqualifiedType(), 2859 N->getUnqualifiedType())) { 2860 if (ArgPos) 2861 *ArgPos = O - OldType->param_type_begin(); 2862 return false; 2863 } 2864 } 2865 return true; 2866 } 2867 2868 /// CheckPointerConversion - Check the pointer conversion from the 2869 /// expression From to the type ToType. This routine checks for 2870 /// ambiguous or inaccessible derived-to-base pointer 2871 /// conversions for which IsPointerConversion has already returned 2872 /// true. It returns true and produces a diagnostic if there was an 2873 /// error, or returns false otherwise. 2874 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2875 CastKind &Kind, 2876 CXXCastPath& BasePath, 2877 bool IgnoreBaseAccess, 2878 bool Diagnose) { 2879 QualType FromType = From->getType(); 2880 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2881 2882 Kind = CK_BitCast; 2883 2884 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2885 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2886 Expr::NPCK_ZeroExpression) { 2887 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2888 DiagRuntimeBehavior(From->getExprLoc(), From, 2889 PDiag(diag::warn_impcast_bool_to_null_pointer) 2890 << ToType << From->getSourceRange()); 2891 else if (!isUnevaluatedContext()) 2892 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2893 << ToType << From->getSourceRange(); 2894 } 2895 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2896 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2897 QualType FromPointeeType = FromPtrType->getPointeeType(), 2898 ToPointeeType = ToPtrType->getPointeeType(); 2899 2900 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2901 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2902 // We must have a derived-to-base conversion. Check an 2903 // ambiguous or inaccessible conversion. 2904 unsigned InaccessibleID = 0; 2905 unsigned AmbigiousID = 0; 2906 if (Diagnose) { 2907 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2908 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2909 } 2910 if (CheckDerivedToBaseConversion( 2911 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2912 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2913 &BasePath, IgnoreBaseAccess)) 2914 return true; 2915 2916 // The conversion was successful. 2917 Kind = CK_DerivedToBase; 2918 } 2919 2920 if (Diagnose && !IsCStyleOrFunctionalCast && 2921 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2922 assert(getLangOpts().MSVCCompat && 2923 "this should only be possible with MSVCCompat!"); 2924 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2925 << From->getSourceRange(); 2926 } 2927 } 2928 } else if (const ObjCObjectPointerType *ToPtrType = 2929 ToType->getAs<ObjCObjectPointerType>()) { 2930 if (const ObjCObjectPointerType *FromPtrType = 2931 FromType->getAs<ObjCObjectPointerType>()) { 2932 // Objective-C++ conversions are always okay. 2933 // FIXME: We should have a different class of conversions for the 2934 // Objective-C++ implicit conversions. 2935 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2936 return false; 2937 } else if (FromType->isBlockPointerType()) { 2938 Kind = CK_BlockPointerToObjCPointerCast; 2939 } else { 2940 Kind = CK_CPointerToObjCPointerCast; 2941 } 2942 } else if (ToType->isBlockPointerType()) { 2943 if (!FromType->isBlockPointerType()) 2944 Kind = CK_AnyPointerToBlockPointerCast; 2945 } 2946 2947 // We shouldn't fall into this case unless it's valid for other 2948 // reasons. 2949 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2950 Kind = CK_NullToPointer; 2951 2952 return false; 2953 } 2954 2955 /// IsMemberPointerConversion - Determines whether the conversion of the 2956 /// expression From, which has the (possibly adjusted) type FromType, can be 2957 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2958 /// If so, returns true and places the converted type (that might differ from 2959 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2960 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2961 QualType ToType, 2962 bool InOverloadResolution, 2963 QualType &ConvertedType) { 2964 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2965 if (!ToTypePtr) 2966 return false; 2967 2968 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2969 if (From->isNullPointerConstant(Context, 2970 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2971 : Expr::NPC_ValueDependentIsNull)) { 2972 ConvertedType = ToType; 2973 return true; 2974 } 2975 2976 // Otherwise, both types have to be member pointers. 2977 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2978 if (!FromTypePtr) 2979 return false; 2980 2981 // A pointer to member of B can be converted to a pointer to member of D, 2982 // where D is derived from B (C++ 4.11p2). 2983 QualType FromClass(FromTypePtr->getClass(), 0); 2984 QualType ToClass(ToTypePtr->getClass(), 0); 2985 2986 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2987 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 2988 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2989 ToClass.getTypePtr()); 2990 return true; 2991 } 2992 2993 return false; 2994 } 2995 2996 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2997 /// expression From to the type ToType. This routine checks for ambiguous or 2998 /// virtual or inaccessible base-to-derived member pointer conversions 2999 /// for which IsMemberPointerConversion has already returned true. It returns 3000 /// true and produces a diagnostic if there was an error, or returns false 3001 /// otherwise. 3002 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3003 CastKind &Kind, 3004 CXXCastPath &BasePath, 3005 bool IgnoreBaseAccess) { 3006 QualType FromType = From->getType(); 3007 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3008 if (!FromPtrType) { 3009 // This must be a null pointer to member pointer conversion 3010 assert(From->isNullPointerConstant(Context, 3011 Expr::NPC_ValueDependentIsNull) && 3012 "Expr must be null pointer constant!"); 3013 Kind = CK_NullToMemberPointer; 3014 return false; 3015 } 3016 3017 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3018 assert(ToPtrType && "No member pointer cast has a target type " 3019 "that is not a member pointer."); 3020 3021 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3022 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3023 3024 // FIXME: What about dependent types? 3025 assert(FromClass->isRecordType() && "Pointer into non-class."); 3026 assert(ToClass->isRecordType() && "Pointer into non-class."); 3027 3028 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3029 /*DetectVirtual=*/true); 3030 bool DerivationOkay = 3031 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3032 assert(DerivationOkay && 3033 "Should not have been called if derivation isn't OK."); 3034 (void)DerivationOkay; 3035 3036 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3037 getUnqualifiedType())) { 3038 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3039 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3040 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3041 return true; 3042 } 3043 3044 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3045 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3046 << FromClass << ToClass << QualType(VBase, 0) 3047 << From->getSourceRange(); 3048 return true; 3049 } 3050 3051 if (!IgnoreBaseAccess) 3052 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3053 Paths.front(), 3054 diag::err_downcast_from_inaccessible_base); 3055 3056 // Must be a base to derived member conversion. 3057 BuildBasePathArray(Paths, BasePath); 3058 Kind = CK_BaseToDerivedMemberPointer; 3059 return false; 3060 } 3061 3062 /// Determine whether the lifetime conversion between the two given 3063 /// qualifiers sets is nontrivial. 3064 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3065 Qualifiers ToQuals) { 3066 // Converting anything to const __unsafe_unretained is trivial. 3067 if (ToQuals.hasConst() && 3068 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3069 return false; 3070 3071 return true; 3072 } 3073 3074 /// IsQualificationConversion - Determines whether the conversion from 3075 /// an rvalue of type FromType to ToType is a qualification conversion 3076 /// (C++ 4.4). 3077 /// 3078 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3079 /// when the qualification conversion involves a change in the Objective-C 3080 /// object lifetime. 3081 bool 3082 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3083 bool CStyle, bool &ObjCLifetimeConversion) { 3084 FromType = Context.getCanonicalType(FromType); 3085 ToType = Context.getCanonicalType(ToType); 3086 ObjCLifetimeConversion = false; 3087 3088 // If FromType and ToType are the same type, this is not a 3089 // qualification conversion. 3090 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3091 return false; 3092 3093 // (C++ 4.4p4): 3094 // A conversion can add cv-qualifiers at levels other than the first 3095 // in multi-level pointers, subject to the following rules: [...] 3096 bool PreviousToQualsIncludeConst = true; 3097 bool UnwrappedAnyPointer = false; 3098 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3099 // Within each iteration of the loop, we check the qualifiers to 3100 // determine if this still looks like a qualification 3101 // conversion. Then, if all is well, we unwrap one more level of 3102 // pointers or pointers-to-members and do it all again 3103 // until there are no more pointers or pointers-to-members left to 3104 // unwrap. 3105 UnwrappedAnyPointer = true; 3106 3107 Qualifiers FromQuals = FromType.getQualifiers(); 3108 Qualifiers ToQuals = ToType.getQualifiers(); 3109 3110 // Ignore __unaligned qualifier if this type is void. 3111 if (ToType.getUnqualifiedType()->isVoidType()) 3112 FromQuals.removeUnaligned(); 3113 3114 // Objective-C ARC: 3115 // Check Objective-C lifetime conversions. 3116 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3117 UnwrappedAnyPointer) { 3118 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3119 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3120 ObjCLifetimeConversion = true; 3121 FromQuals.removeObjCLifetime(); 3122 ToQuals.removeObjCLifetime(); 3123 } else { 3124 // Qualification conversions cannot cast between different 3125 // Objective-C lifetime qualifiers. 3126 return false; 3127 } 3128 } 3129 3130 // Allow addition/removal of GC attributes but not changing GC attributes. 3131 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3132 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3133 FromQuals.removeObjCGCAttr(); 3134 ToQuals.removeObjCGCAttr(); 3135 } 3136 3137 // -- for every j > 0, if const is in cv 1,j then const is in cv 3138 // 2,j, and similarly for volatile. 3139 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3140 return false; 3141 3142 // -- if the cv 1,j and cv 2,j are different, then const is in 3143 // every cv for 0 < k < j. 3144 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3145 && !PreviousToQualsIncludeConst) 3146 return false; 3147 3148 // Keep track of whether all prior cv-qualifiers in the "to" type 3149 // include const. 3150 PreviousToQualsIncludeConst 3151 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3152 } 3153 3154 // Allows address space promotion by language rules implemented in 3155 // Type::Qualifiers::isAddressSpaceSupersetOf. 3156 Qualifiers FromQuals = FromType.getQualifiers(); 3157 Qualifiers ToQuals = ToType.getQualifiers(); 3158 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3159 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3160 return false; 3161 } 3162 3163 // We are left with FromType and ToType being the pointee types 3164 // after unwrapping the original FromType and ToType the same number 3165 // of types. If we unwrapped any pointers, and if FromType and 3166 // ToType have the same unqualified type (since we checked 3167 // qualifiers above), then this is a qualification conversion. 3168 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3169 } 3170 3171 /// - Determine whether this is a conversion from a scalar type to an 3172 /// atomic type. 3173 /// 3174 /// If successful, updates \c SCS's second and third steps in the conversion 3175 /// sequence to finish the conversion. 3176 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3177 bool InOverloadResolution, 3178 StandardConversionSequence &SCS, 3179 bool CStyle) { 3180 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3181 if (!ToAtomic) 3182 return false; 3183 3184 StandardConversionSequence InnerSCS; 3185 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3186 InOverloadResolution, InnerSCS, 3187 CStyle, /*AllowObjCWritebackConversion=*/false)) 3188 return false; 3189 3190 SCS.Second = InnerSCS.Second; 3191 SCS.setToType(1, InnerSCS.getToType(1)); 3192 SCS.Third = InnerSCS.Third; 3193 SCS.QualificationIncludesObjCLifetime 3194 = InnerSCS.QualificationIncludesObjCLifetime; 3195 SCS.setToType(2, InnerSCS.getToType(2)); 3196 return true; 3197 } 3198 3199 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3200 CXXConstructorDecl *Constructor, 3201 QualType Type) { 3202 const FunctionProtoType *CtorType = 3203 Constructor->getType()->getAs<FunctionProtoType>(); 3204 if (CtorType->getNumParams() > 0) { 3205 QualType FirstArg = CtorType->getParamType(0); 3206 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3207 return true; 3208 } 3209 return false; 3210 } 3211 3212 static OverloadingResult 3213 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3214 CXXRecordDecl *To, 3215 UserDefinedConversionSequence &User, 3216 OverloadCandidateSet &CandidateSet, 3217 bool AllowExplicit) { 3218 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3219 for (auto *D : S.LookupConstructors(To)) { 3220 auto Info = getConstructorInfo(D); 3221 if (!Info) 3222 continue; 3223 3224 bool Usable = !Info.Constructor->isInvalidDecl() && 3225 S.isInitListConstructor(Info.Constructor) && 3226 (AllowExplicit || !Info.Constructor->isExplicit()); 3227 if (Usable) { 3228 // If the first argument is (a reference to) the target type, 3229 // suppress conversions. 3230 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3231 S.Context, Info.Constructor, ToType); 3232 if (Info.ConstructorTmpl) 3233 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3234 /*ExplicitArgs*/ nullptr, From, 3235 CandidateSet, SuppressUserConversions); 3236 else 3237 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3238 CandidateSet, SuppressUserConversions); 3239 } 3240 } 3241 3242 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3243 3244 OverloadCandidateSet::iterator Best; 3245 switch (auto Result = 3246 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3247 case OR_Deleted: 3248 case OR_Success: { 3249 // Record the standard conversion we used and the conversion function. 3250 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3251 QualType ThisType = Constructor->getThisType(S.Context); 3252 // Initializer lists don't have conversions as such. 3253 User.Before.setAsIdentityConversion(); 3254 User.HadMultipleCandidates = HadMultipleCandidates; 3255 User.ConversionFunction = Constructor; 3256 User.FoundConversionFunction = Best->FoundDecl; 3257 User.After.setAsIdentityConversion(); 3258 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3259 User.After.setAllToTypes(ToType); 3260 return Result; 3261 } 3262 3263 case OR_No_Viable_Function: 3264 return OR_No_Viable_Function; 3265 case OR_Ambiguous: 3266 return OR_Ambiguous; 3267 } 3268 3269 llvm_unreachable("Invalid OverloadResult!"); 3270 } 3271 3272 /// Determines whether there is a user-defined conversion sequence 3273 /// (C++ [over.ics.user]) that converts expression From to the type 3274 /// ToType. If such a conversion exists, User will contain the 3275 /// user-defined conversion sequence that performs such a conversion 3276 /// and this routine will return true. Otherwise, this routine returns 3277 /// false and User is unspecified. 3278 /// 3279 /// \param AllowExplicit true if the conversion should consider C++0x 3280 /// "explicit" conversion functions as well as non-explicit conversion 3281 /// functions (C++0x [class.conv.fct]p2). 3282 /// 3283 /// \param AllowObjCConversionOnExplicit true if the conversion should 3284 /// allow an extra Objective-C pointer conversion on uses of explicit 3285 /// constructors. Requires \c AllowExplicit to also be set. 3286 static OverloadingResult 3287 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3288 UserDefinedConversionSequence &User, 3289 OverloadCandidateSet &CandidateSet, 3290 bool AllowExplicit, 3291 bool AllowObjCConversionOnExplicit) { 3292 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3293 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3294 3295 // Whether we will only visit constructors. 3296 bool ConstructorsOnly = false; 3297 3298 // If the type we are conversion to is a class type, enumerate its 3299 // constructors. 3300 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3301 // C++ [over.match.ctor]p1: 3302 // When objects of class type are direct-initialized (8.5), or 3303 // copy-initialized from an expression of the same or a 3304 // derived class type (8.5), overload resolution selects the 3305 // constructor. [...] For copy-initialization, the candidate 3306 // functions are all the converting constructors (12.3.1) of 3307 // that class. The argument list is the expression-list within 3308 // the parentheses of the initializer. 3309 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3310 (From->getType()->getAs<RecordType>() && 3311 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3312 ConstructorsOnly = true; 3313 3314 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3315 // We're not going to find any constructors. 3316 } else if (CXXRecordDecl *ToRecordDecl 3317 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3318 3319 Expr **Args = &From; 3320 unsigned NumArgs = 1; 3321 bool ListInitializing = false; 3322 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3323 // But first, see if there is an init-list-constructor that will work. 3324 OverloadingResult Result = IsInitializerListConstructorConversion( 3325 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3326 if (Result != OR_No_Viable_Function) 3327 return Result; 3328 // Never mind. 3329 CandidateSet.clear( 3330 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3331 3332 // If we're list-initializing, we pass the individual elements as 3333 // arguments, not the entire list. 3334 Args = InitList->getInits(); 3335 NumArgs = InitList->getNumInits(); 3336 ListInitializing = true; 3337 } 3338 3339 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3340 auto Info = getConstructorInfo(D); 3341 if (!Info) 3342 continue; 3343 3344 bool Usable = !Info.Constructor->isInvalidDecl(); 3345 if (ListInitializing) 3346 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3347 else 3348 Usable = Usable && 3349 Info.Constructor->isConvertingConstructor(AllowExplicit); 3350 if (Usable) { 3351 bool SuppressUserConversions = !ConstructorsOnly; 3352 if (SuppressUserConversions && ListInitializing) { 3353 SuppressUserConversions = false; 3354 if (NumArgs == 1) { 3355 // If the first argument is (a reference to) the target type, 3356 // suppress conversions. 3357 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3358 S.Context, Info.Constructor, ToType); 3359 } 3360 } 3361 if (Info.ConstructorTmpl) 3362 S.AddTemplateOverloadCandidate( 3363 Info.ConstructorTmpl, Info.FoundDecl, 3364 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3365 CandidateSet, SuppressUserConversions); 3366 else 3367 // Allow one user-defined conversion when user specifies a 3368 // From->ToType conversion via an static cast (c-style, etc). 3369 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3370 llvm::makeArrayRef(Args, NumArgs), 3371 CandidateSet, SuppressUserConversions); 3372 } 3373 } 3374 } 3375 } 3376 3377 // Enumerate conversion functions, if we're allowed to. 3378 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3379 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3380 // No conversion functions from incomplete types. 3381 } else if (const RecordType *FromRecordType = 3382 From->getType()->getAs<RecordType>()) { 3383 if (CXXRecordDecl *FromRecordDecl 3384 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3385 // Add all of the conversion functions as candidates. 3386 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3387 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3388 DeclAccessPair FoundDecl = I.getPair(); 3389 NamedDecl *D = FoundDecl.getDecl(); 3390 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3391 if (isa<UsingShadowDecl>(D)) 3392 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3393 3394 CXXConversionDecl *Conv; 3395 FunctionTemplateDecl *ConvTemplate; 3396 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3397 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3398 else 3399 Conv = cast<CXXConversionDecl>(D); 3400 3401 if (AllowExplicit || !Conv->isExplicit()) { 3402 if (ConvTemplate) 3403 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3404 ActingContext, From, ToType, 3405 CandidateSet, 3406 AllowObjCConversionOnExplicit); 3407 else 3408 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3409 From, ToType, CandidateSet, 3410 AllowObjCConversionOnExplicit); 3411 } 3412 } 3413 } 3414 } 3415 3416 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3417 3418 OverloadCandidateSet::iterator Best; 3419 switch (auto Result = 3420 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3421 case OR_Success: 3422 case OR_Deleted: 3423 // Record the standard conversion we used and the conversion function. 3424 if (CXXConstructorDecl *Constructor 3425 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3426 // C++ [over.ics.user]p1: 3427 // If the user-defined conversion is specified by a 3428 // constructor (12.3.1), the initial standard conversion 3429 // sequence converts the source type to the type required by 3430 // the argument of the constructor. 3431 // 3432 QualType ThisType = Constructor->getThisType(S.Context); 3433 if (isa<InitListExpr>(From)) { 3434 // Initializer lists don't have conversions as such. 3435 User.Before.setAsIdentityConversion(); 3436 } else { 3437 if (Best->Conversions[0].isEllipsis()) 3438 User.EllipsisConversion = true; 3439 else { 3440 User.Before = Best->Conversions[0].Standard; 3441 User.EllipsisConversion = false; 3442 } 3443 } 3444 User.HadMultipleCandidates = HadMultipleCandidates; 3445 User.ConversionFunction = Constructor; 3446 User.FoundConversionFunction = Best->FoundDecl; 3447 User.After.setAsIdentityConversion(); 3448 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3449 User.After.setAllToTypes(ToType); 3450 return Result; 3451 } 3452 if (CXXConversionDecl *Conversion 3453 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3454 // C++ [over.ics.user]p1: 3455 // 3456 // [...] If the user-defined conversion is specified by a 3457 // conversion function (12.3.2), the initial standard 3458 // conversion sequence converts the source type to the 3459 // implicit object parameter of the conversion function. 3460 User.Before = Best->Conversions[0].Standard; 3461 User.HadMultipleCandidates = HadMultipleCandidates; 3462 User.ConversionFunction = Conversion; 3463 User.FoundConversionFunction = Best->FoundDecl; 3464 User.EllipsisConversion = false; 3465 3466 // C++ [over.ics.user]p2: 3467 // The second standard conversion sequence converts the 3468 // result of the user-defined conversion to the target type 3469 // for the sequence. Since an implicit conversion sequence 3470 // is an initialization, the special rules for 3471 // initialization by user-defined conversion apply when 3472 // selecting the best user-defined conversion for a 3473 // user-defined conversion sequence (see 13.3.3 and 3474 // 13.3.3.1). 3475 User.After = Best->FinalConversion; 3476 return Result; 3477 } 3478 llvm_unreachable("Not a constructor or conversion function?"); 3479 3480 case OR_No_Viable_Function: 3481 return OR_No_Viable_Function; 3482 3483 case OR_Ambiguous: 3484 return OR_Ambiguous; 3485 } 3486 3487 llvm_unreachable("Invalid OverloadResult!"); 3488 } 3489 3490 bool 3491 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3492 ImplicitConversionSequence ICS; 3493 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3494 OverloadCandidateSet::CSK_Normal); 3495 OverloadingResult OvResult = 3496 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3497 CandidateSet, false, false); 3498 if (OvResult == OR_Ambiguous) 3499 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3500 << From->getType() << ToType << From->getSourceRange(); 3501 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3502 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3503 diag::err_typecheck_nonviable_condition_incomplete, 3504 From->getType(), From->getSourceRange())) 3505 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3506 << false << From->getType() << From->getSourceRange() << ToType; 3507 } else 3508 return false; 3509 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3510 return true; 3511 } 3512 3513 /// Compare the user-defined conversion functions or constructors 3514 /// of two user-defined conversion sequences to determine whether any ordering 3515 /// is possible. 3516 static ImplicitConversionSequence::CompareKind 3517 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3518 FunctionDecl *Function2) { 3519 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3520 return ImplicitConversionSequence::Indistinguishable; 3521 3522 // Objective-C++: 3523 // If both conversion functions are implicitly-declared conversions from 3524 // a lambda closure type to a function pointer and a block pointer, 3525 // respectively, always prefer the conversion to a function pointer, 3526 // because the function pointer is more lightweight and is more likely 3527 // to keep code working. 3528 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3529 if (!Conv1) 3530 return ImplicitConversionSequence::Indistinguishable; 3531 3532 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3533 if (!Conv2) 3534 return ImplicitConversionSequence::Indistinguishable; 3535 3536 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3537 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3538 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3539 if (Block1 != Block2) 3540 return Block1 ? ImplicitConversionSequence::Worse 3541 : ImplicitConversionSequence::Better; 3542 } 3543 3544 return ImplicitConversionSequence::Indistinguishable; 3545 } 3546 3547 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3548 const ImplicitConversionSequence &ICS) { 3549 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3550 (ICS.isUserDefined() && 3551 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3552 } 3553 3554 /// CompareImplicitConversionSequences - Compare two implicit 3555 /// conversion sequences to determine whether one is better than the 3556 /// other or if they are indistinguishable (C++ 13.3.3.2). 3557 static ImplicitConversionSequence::CompareKind 3558 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3559 const ImplicitConversionSequence& ICS1, 3560 const ImplicitConversionSequence& ICS2) 3561 { 3562 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3563 // conversion sequences (as defined in 13.3.3.1) 3564 // -- a standard conversion sequence (13.3.3.1.1) is a better 3565 // conversion sequence than a user-defined conversion sequence or 3566 // an ellipsis conversion sequence, and 3567 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3568 // conversion sequence than an ellipsis conversion sequence 3569 // (13.3.3.1.3). 3570 // 3571 // C++0x [over.best.ics]p10: 3572 // For the purpose of ranking implicit conversion sequences as 3573 // described in 13.3.3.2, the ambiguous conversion sequence is 3574 // treated as a user-defined sequence that is indistinguishable 3575 // from any other user-defined conversion sequence. 3576 3577 // String literal to 'char *' conversion has been deprecated in C++03. It has 3578 // been removed from C++11. We still accept this conversion, if it happens at 3579 // the best viable function. Otherwise, this conversion is considered worse 3580 // than ellipsis conversion. Consider this as an extension; this is not in the 3581 // standard. For example: 3582 // 3583 // int &f(...); // #1 3584 // void f(char*); // #2 3585 // void g() { int &r = f("foo"); } 3586 // 3587 // In C++03, we pick #2 as the best viable function. 3588 // In C++11, we pick #1 as the best viable function, because ellipsis 3589 // conversion is better than string-literal to char* conversion (since there 3590 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3591 // convert arguments, #2 would be the best viable function in C++11. 3592 // If the best viable function has this conversion, a warning will be issued 3593 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3594 3595 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3596 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3597 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3598 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3599 ? ImplicitConversionSequence::Worse 3600 : ImplicitConversionSequence::Better; 3601 3602 if (ICS1.getKindRank() < ICS2.getKindRank()) 3603 return ImplicitConversionSequence::Better; 3604 if (ICS2.getKindRank() < ICS1.getKindRank()) 3605 return ImplicitConversionSequence::Worse; 3606 3607 // The following checks require both conversion sequences to be of 3608 // the same kind. 3609 if (ICS1.getKind() != ICS2.getKind()) 3610 return ImplicitConversionSequence::Indistinguishable; 3611 3612 ImplicitConversionSequence::CompareKind Result = 3613 ImplicitConversionSequence::Indistinguishable; 3614 3615 // Two implicit conversion sequences of the same form are 3616 // indistinguishable conversion sequences unless one of the 3617 // following rules apply: (C++ 13.3.3.2p3): 3618 3619 // List-initialization sequence L1 is a better conversion sequence than 3620 // list-initialization sequence L2 if: 3621 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3622 // if not that, 3623 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3624 // and N1 is smaller than N2., 3625 // even if one of the other rules in this paragraph would otherwise apply. 3626 if (!ICS1.isBad()) { 3627 if (ICS1.isStdInitializerListElement() && 3628 !ICS2.isStdInitializerListElement()) 3629 return ImplicitConversionSequence::Better; 3630 if (!ICS1.isStdInitializerListElement() && 3631 ICS2.isStdInitializerListElement()) 3632 return ImplicitConversionSequence::Worse; 3633 } 3634 3635 if (ICS1.isStandard()) 3636 // Standard conversion sequence S1 is a better conversion sequence than 3637 // standard conversion sequence S2 if [...] 3638 Result = CompareStandardConversionSequences(S, Loc, 3639 ICS1.Standard, ICS2.Standard); 3640 else if (ICS1.isUserDefined()) { 3641 // User-defined conversion sequence U1 is a better conversion 3642 // sequence than another user-defined conversion sequence U2 if 3643 // they contain the same user-defined conversion function or 3644 // constructor and if the second standard conversion sequence of 3645 // U1 is better than the second standard conversion sequence of 3646 // U2 (C++ 13.3.3.2p3). 3647 if (ICS1.UserDefined.ConversionFunction == 3648 ICS2.UserDefined.ConversionFunction) 3649 Result = CompareStandardConversionSequences(S, Loc, 3650 ICS1.UserDefined.After, 3651 ICS2.UserDefined.After); 3652 else 3653 Result = compareConversionFunctions(S, 3654 ICS1.UserDefined.ConversionFunction, 3655 ICS2.UserDefined.ConversionFunction); 3656 } 3657 3658 return Result; 3659 } 3660 3661 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3662 // determine if one is a proper subset of the other. 3663 static ImplicitConversionSequence::CompareKind 3664 compareStandardConversionSubsets(ASTContext &Context, 3665 const StandardConversionSequence& SCS1, 3666 const StandardConversionSequence& SCS2) { 3667 ImplicitConversionSequence::CompareKind Result 3668 = ImplicitConversionSequence::Indistinguishable; 3669 3670 // the identity conversion sequence is considered to be a subsequence of 3671 // any non-identity conversion sequence 3672 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3673 return ImplicitConversionSequence::Better; 3674 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3675 return ImplicitConversionSequence::Worse; 3676 3677 if (SCS1.Second != SCS2.Second) { 3678 if (SCS1.Second == ICK_Identity) 3679 Result = ImplicitConversionSequence::Better; 3680 else if (SCS2.Second == ICK_Identity) 3681 Result = ImplicitConversionSequence::Worse; 3682 else 3683 return ImplicitConversionSequence::Indistinguishable; 3684 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3685 return ImplicitConversionSequence::Indistinguishable; 3686 3687 if (SCS1.Third == SCS2.Third) { 3688 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3689 : ImplicitConversionSequence::Indistinguishable; 3690 } 3691 3692 if (SCS1.Third == ICK_Identity) 3693 return Result == ImplicitConversionSequence::Worse 3694 ? ImplicitConversionSequence::Indistinguishable 3695 : ImplicitConversionSequence::Better; 3696 3697 if (SCS2.Third == ICK_Identity) 3698 return Result == ImplicitConversionSequence::Better 3699 ? ImplicitConversionSequence::Indistinguishable 3700 : ImplicitConversionSequence::Worse; 3701 3702 return ImplicitConversionSequence::Indistinguishable; 3703 } 3704 3705 /// Determine whether one of the given reference bindings is better 3706 /// than the other based on what kind of bindings they are. 3707 static bool 3708 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3709 const StandardConversionSequence &SCS2) { 3710 // C++0x [over.ics.rank]p3b4: 3711 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3712 // implicit object parameter of a non-static member function declared 3713 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3714 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3715 // lvalue reference to a function lvalue and S2 binds an rvalue 3716 // reference*. 3717 // 3718 // FIXME: Rvalue references. We're going rogue with the above edits, 3719 // because the semantics in the current C++0x working paper (N3225 at the 3720 // time of this writing) break the standard definition of std::forward 3721 // and std::reference_wrapper when dealing with references to functions. 3722 // Proposed wording changes submitted to CWG for consideration. 3723 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3724 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3725 return false; 3726 3727 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3728 SCS2.IsLvalueReference) || 3729 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3730 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3731 } 3732 3733 /// CompareStandardConversionSequences - Compare two standard 3734 /// conversion sequences to determine whether one is better than the 3735 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3736 static ImplicitConversionSequence::CompareKind 3737 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3738 const StandardConversionSequence& SCS1, 3739 const StandardConversionSequence& SCS2) 3740 { 3741 // Standard conversion sequence S1 is a better conversion sequence 3742 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3743 3744 // -- S1 is a proper subsequence of S2 (comparing the conversion 3745 // sequences in the canonical form defined by 13.3.3.1.1, 3746 // excluding any Lvalue Transformation; the identity conversion 3747 // sequence is considered to be a subsequence of any 3748 // non-identity conversion sequence) or, if not that, 3749 if (ImplicitConversionSequence::CompareKind CK 3750 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3751 return CK; 3752 3753 // -- the rank of S1 is better than the rank of S2 (by the rules 3754 // defined below), or, if not that, 3755 ImplicitConversionRank Rank1 = SCS1.getRank(); 3756 ImplicitConversionRank Rank2 = SCS2.getRank(); 3757 if (Rank1 < Rank2) 3758 return ImplicitConversionSequence::Better; 3759 else if (Rank2 < Rank1) 3760 return ImplicitConversionSequence::Worse; 3761 3762 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3763 // are indistinguishable unless one of the following rules 3764 // applies: 3765 3766 // A conversion that is not a conversion of a pointer, or 3767 // pointer to member, to bool is better than another conversion 3768 // that is such a conversion. 3769 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3770 return SCS2.isPointerConversionToBool() 3771 ? ImplicitConversionSequence::Better 3772 : ImplicitConversionSequence::Worse; 3773 3774 // C++ [over.ics.rank]p4b2: 3775 // 3776 // If class B is derived directly or indirectly from class A, 3777 // conversion of B* to A* is better than conversion of B* to 3778 // void*, and conversion of A* to void* is better than conversion 3779 // of B* to void*. 3780 bool SCS1ConvertsToVoid 3781 = SCS1.isPointerConversionToVoidPointer(S.Context); 3782 bool SCS2ConvertsToVoid 3783 = SCS2.isPointerConversionToVoidPointer(S.Context); 3784 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3785 // Exactly one of the conversion sequences is a conversion to 3786 // a void pointer; it's the worse conversion. 3787 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3788 : ImplicitConversionSequence::Worse; 3789 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3790 // Neither conversion sequence converts to a void pointer; compare 3791 // their derived-to-base conversions. 3792 if (ImplicitConversionSequence::CompareKind DerivedCK 3793 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3794 return DerivedCK; 3795 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3796 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3797 // Both conversion sequences are conversions to void 3798 // pointers. Compare the source types to determine if there's an 3799 // inheritance relationship in their sources. 3800 QualType FromType1 = SCS1.getFromType(); 3801 QualType FromType2 = SCS2.getFromType(); 3802 3803 // Adjust the types we're converting from via the array-to-pointer 3804 // conversion, if we need to. 3805 if (SCS1.First == ICK_Array_To_Pointer) 3806 FromType1 = S.Context.getArrayDecayedType(FromType1); 3807 if (SCS2.First == ICK_Array_To_Pointer) 3808 FromType2 = S.Context.getArrayDecayedType(FromType2); 3809 3810 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3811 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3812 3813 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3814 return ImplicitConversionSequence::Better; 3815 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3816 return ImplicitConversionSequence::Worse; 3817 3818 // Objective-C++: If one interface is more specific than the 3819 // other, it is the better one. 3820 const ObjCObjectPointerType* FromObjCPtr1 3821 = FromType1->getAs<ObjCObjectPointerType>(); 3822 const ObjCObjectPointerType* FromObjCPtr2 3823 = FromType2->getAs<ObjCObjectPointerType>(); 3824 if (FromObjCPtr1 && FromObjCPtr2) { 3825 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3826 FromObjCPtr2); 3827 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3828 FromObjCPtr1); 3829 if (AssignLeft != AssignRight) { 3830 return AssignLeft? ImplicitConversionSequence::Better 3831 : ImplicitConversionSequence::Worse; 3832 } 3833 } 3834 } 3835 3836 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3837 // bullet 3). 3838 if (ImplicitConversionSequence::CompareKind QualCK 3839 = CompareQualificationConversions(S, SCS1, SCS2)) 3840 return QualCK; 3841 3842 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3843 // Check for a better reference binding based on the kind of bindings. 3844 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3845 return ImplicitConversionSequence::Better; 3846 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3847 return ImplicitConversionSequence::Worse; 3848 3849 // C++ [over.ics.rank]p3b4: 3850 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3851 // which the references refer are the same type except for 3852 // top-level cv-qualifiers, and the type to which the reference 3853 // initialized by S2 refers is more cv-qualified than the type 3854 // to which the reference initialized by S1 refers. 3855 QualType T1 = SCS1.getToType(2); 3856 QualType T2 = SCS2.getToType(2); 3857 T1 = S.Context.getCanonicalType(T1); 3858 T2 = S.Context.getCanonicalType(T2); 3859 Qualifiers T1Quals, T2Quals; 3860 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3861 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3862 if (UnqualT1 == UnqualT2) { 3863 // Objective-C++ ARC: If the references refer to objects with different 3864 // lifetimes, prefer bindings that don't change lifetime. 3865 if (SCS1.ObjCLifetimeConversionBinding != 3866 SCS2.ObjCLifetimeConversionBinding) { 3867 return SCS1.ObjCLifetimeConversionBinding 3868 ? ImplicitConversionSequence::Worse 3869 : ImplicitConversionSequence::Better; 3870 } 3871 3872 // If the type is an array type, promote the element qualifiers to the 3873 // type for comparison. 3874 if (isa<ArrayType>(T1) && T1Quals) 3875 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3876 if (isa<ArrayType>(T2) && T2Quals) 3877 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3878 if (T2.isMoreQualifiedThan(T1)) 3879 return ImplicitConversionSequence::Better; 3880 else if (T1.isMoreQualifiedThan(T2)) 3881 return ImplicitConversionSequence::Worse; 3882 } 3883 } 3884 3885 // In Microsoft mode, prefer an integral conversion to a 3886 // floating-to-integral conversion if the integral conversion 3887 // is between types of the same size. 3888 // For example: 3889 // void f(float); 3890 // void f(int); 3891 // int main { 3892 // long a; 3893 // f(a); 3894 // } 3895 // Here, MSVC will call f(int) instead of generating a compile error 3896 // as clang will do in standard mode. 3897 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3898 SCS2.Second == ICK_Floating_Integral && 3899 S.Context.getTypeSize(SCS1.getFromType()) == 3900 S.Context.getTypeSize(SCS1.getToType(2))) 3901 return ImplicitConversionSequence::Better; 3902 3903 return ImplicitConversionSequence::Indistinguishable; 3904 } 3905 3906 /// CompareQualificationConversions - Compares two standard conversion 3907 /// sequences to determine whether they can be ranked based on their 3908 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3909 static ImplicitConversionSequence::CompareKind 3910 CompareQualificationConversions(Sema &S, 3911 const StandardConversionSequence& SCS1, 3912 const StandardConversionSequence& SCS2) { 3913 // C++ 13.3.3.2p3: 3914 // -- S1 and S2 differ only in their qualification conversion and 3915 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3916 // cv-qualification signature of type T1 is a proper subset of 3917 // the cv-qualification signature of type T2, and S1 is not the 3918 // deprecated string literal array-to-pointer conversion (4.2). 3919 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3920 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3921 return ImplicitConversionSequence::Indistinguishable; 3922 3923 // FIXME: the example in the standard doesn't use a qualification 3924 // conversion (!) 3925 QualType T1 = SCS1.getToType(2); 3926 QualType T2 = SCS2.getToType(2); 3927 T1 = S.Context.getCanonicalType(T1); 3928 T2 = S.Context.getCanonicalType(T2); 3929 Qualifiers T1Quals, T2Quals; 3930 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3931 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3932 3933 // If the types are the same, we won't learn anything by unwrapped 3934 // them. 3935 if (UnqualT1 == UnqualT2) 3936 return ImplicitConversionSequence::Indistinguishable; 3937 3938 // If the type is an array type, promote the element qualifiers to the type 3939 // for comparison. 3940 if (isa<ArrayType>(T1) && T1Quals) 3941 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3942 if (isa<ArrayType>(T2) && T2Quals) 3943 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3944 3945 ImplicitConversionSequence::CompareKind Result 3946 = ImplicitConversionSequence::Indistinguishable; 3947 3948 // Objective-C++ ARC: 3949 // Prefer qualification conversions not involving a change in lifetime 3950 // to qualification conversions that do not change lifetime. 3951 if (SCS1.QualificationIncludesObjCLifetime != 3952 SCS2.QualificationIncludesObjCLifetime) { 3953 Result = SCS1.QualificationIncludesObjCLifetime 3954 ? ImplicitConversionSequence::Worse 3955 : ImplicitConversionSequence::Better; 3956 } 3957 3958 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 3959 // Within each iteration of the loop, we check the qualifiers to 3960 // determine if this still looks like a qualification 3961 // conversion. Then, if all is well, we unwrap one more level of 3962 // pointers or pointers-to-members and do it all again 3963 // until there are no more pointers or pointers-to-members left 3964 // to unwrap. This essentially mimics what 3965 // IsQualificationConversion does, but here we're checking for a 3966 // strict subset of qualifiers. 3967 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3968 // The qualifiers are the same, so this doesn't tell us anything 3969 // about how the sequences rank. 3970 ; 3971 else if (T2.isMoreQualifiedThan(T1)) { 3972 // T1 has fewer qualifiers, so it could be the better sequence. 3973 if (Result == ImplicitConversionSequence::Worse) 3974 // Neither has qualifiers that are a subset of the other's 3975 // qualifiers. 3976 return ImplicitConversionSequence::Indistinguishable; 3977 3978 Result = ImplicitConversionSequence::Better; 3979 } else if (T1.isMoreQualifiedThan(T2)) { 3980 // T2 has fewer qualifiers, so it could be the better sequence. 3981 if (Result == ImplicitConversionSequence::Better) 3982 // Neither has qualifiers that are a subset of the other's 3983 // qualifiers. 3984 return ImplicitConversionSequence::Indistinguishable; 3985 3986 Result = ImplicitConversionSequence::Worse; 3987 } else { 3988 // Qualifiers are disjoint. 3989 return ImplicitConversionSequence::Indistinguishable; 3990 } 3991 3992 // If the types after this point are equivalent, we're done. 3993 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3994 break; 3995 } 3996 3997 // Check that the winning standard conversion sequence isn't using 3998 // the deprecated string literal array to pointer conversion. 3999 switch (Result) { 4000 case ImplicitConversionSequence::Better: 4001 if (SCS1.DeprecatedStringLiteralToCharPtr) 4002 Result = ImplicitConversionSequence::Indistinguishable; 4003 break; 4004 4005 case ImplicitConversionSequence::Indistinguishable: 4006 break; 4007 4008 case ImplicitConversionSequence::Worse: 4009 if (SCS2.DeprecatedStringLiteralToCharPtr) 4010 Result = ImplicitConversionSequence::Indistinguishable; 4011 break; 4012 } 4013 4014 return Result; 4015 } 4016 4017 /// CompareDerivedToBaseConversions - Compares two standard conversion 4018 /// sequences to determine whether they can be ranked based on their 4019 /// various kinds of derived-to-base conversions (C++ 4020 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4021 /// conversions between Objective-C interface types. 4022 static ImplicitConversionSequence::CompareKind 4023 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4024 const StandardConversionSequence& SCS1, 4025 const StandardConversionSequence& SCS2) { 4026 QualType FromType1 = SCS1.getFromType(); 4027 QualType ToType1 = SCS1.getToType(1); 4028 QualType FromType2 = SCS2.getFromType(); 4029 QualType ToType2 = SCS2.getToType(1); 4030 4031 // Adjust the types we're converting from via the array-to-pointer 4032 // conversion, if we need to. 4033 if (SCS1.First == ICK_Array_To_Pointer) 4034 FromType1 = S.Context.getArrayDecayedType(FromType1); 4035 if (SCS2.First == ICK_Array_To_Pointer) 4036 FromType2 = S.Context.getArrayDecayedType(FromType2); 4037 4038 // Canonicalize all of the types. 4039 FromType1 = S.Context.getCanonicalType(FromType1); 4040 ToType1 = S.Context.getCanonicalType(ToType1); 4041 FromType2 = S.Context.getCanonicalType(FromType2); 4042 ToType2 = S.Context.getCanonicalType(ToType2); 4043 4044 // C++ [over.ics.rank]p4b3: 4045 // 4046 // If class B is derived directly or indirectly from class A and 4047 // class C is derived directly or indirectly from B, 4048 // 4049 // Compare based on pointer conversions. 4050 if (SCS1.Second == ICK_Pointer_Conversion && 4051 SCS2.Second == ICK_Pointer_Conversion && 4052 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4053 FromType1->isPointerType() && FromType2->isPointerType() && 4054 ToType1->isPointerType() && ToType2->isPointerType()) { 4055 QualType FromPointee1 4056 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4057 QualType ToPointee1 4058 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4059 QualType FromPointee2 4060 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4061 QualType ToPointee2 4062 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4063 4064 // -- conversion of C* to B* is better than conversion of C* to A*, 4065 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4066 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4067 return ImplicitConversionSequence::Better; 4068 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4069 return ImplicitConversionSequence::Worse; 4070 } 4071 4072 // -- conversion of B* to A* is better than conversion of C* to A*, 4073 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4074 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4075 return ImplicitConversionSequence::Better; 4076 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4077 return ImplicitConversionSequence::Worse; 4078 } 4079 } else if (SCS1.Second == ICK_Pointer_Conversion && 4080 SCS2.Second == ICK_Pointer_Conversion) { 4081 const ObjCObjectPointerType *FromPtr1 4082 = FromType1->getAs<ObjCObjectPointerType>(); 4083 const ObjCObjectPointerType *FromPtr2 4084 = FromType2->getAs<ObjCObjectPointerType>(); 4085 const ObjCObjectPointerType *ToPtr1 4086 = ToType1->getAs<ObjCObjectPointerType>(); 4087 const ObjCObjectPointerType *ToPtr2 4088 = ToType2->getAs<ObjCObjectPointerType>(); 4089 4090 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4091 // Apply the same conversion ranking rules for Objective-C pointer types 4092 // that we do for C++ pointers to class types. However, we employ the 4093 // Objective-C pseudo-subtyping relationship used for assignment of 4094 // Objective-C pointer types. 4095 bool FromAssignLeft 4096 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4097 bool FromAssignRight 4098 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4099 bool ToAssignLeft 4100 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4101 bool ToAssignRight 4102 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4103 4104 // A conversion to an a non-id object pointer type or qualified 'id' 4105 // type is better than a conversion to 'id'. 4106 if (ToPtr1->isObjCIdType() && 4107 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4108 return ImplicitConversionSequence::Worse; 4109 if (ToPtr2->isObjCIdType() && 4110 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4111 return ImplicitConversionSequence::Better; 4112 4113 // A conversion to a non-id object pointer type is better than a 4114 // conversion to a qualified 'id' type 4115 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4116 return ImplicitConversionSequence::Worse; 4117 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4118 return ImplicitConversionSequence::Better; 4119 4120 // A conversion to an a non-Class object pointer type or qualified 'Class' 4121 // type is better than a conversion to 'Class'. 4122 if (ToPtr1->isObjCClassType() && 4123 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4124 return ImplicitConversionSequence::Worse; 4125 if (ToPtr2->isObjCClassType() && 4126 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4127 return ImplicitConversionSequence::Better; 4128 4129 // A conversion to a non-Class object pointer type is better than a 4130 // conversion to a qualified 'Class' type. 4131 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4132 return ImplicitConversionSequence::Worse; 4133 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4134 return ImplicitConversionSequence::Better; 4135 4136 // -- "conversion of C* to B* is better than conversion of C* to A*," 4137 if (S.Context.hasSameType(FromType1, FromType2) && 4138 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4139 (ToAssignLeft != ToAssignRight)) { 4140 if (FromPtr1->isSpecialized()) { 4141 // "conversion of B<A> * to B * is better than conversion of B * to 4142 // C *. 4143 bool IsFirstSame = 4144 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4145 bool IsSecondSame = 4146 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4147 if (IsFirstSame) { 4148 if (!IsSecondSame) 4149 return ImplicitConversionSequence::Better; 4150 } else if (IsSecondSame) 4151 return ImplicitConversionSequence::Worse; 4152 } 4153 return ToAssignLeft? ImplicitConversionSequence::Worse 4154 : ImplicitConversionSequence::Better; 4155 } 4156 4157 // -- "conversion of B* to A* is better than conversion of C* to A*," 4158 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4159 (FromAssignLeft != FromAssignRight)) 4160 return FromAssignLeft? ImplicitConversionSequence::Better 4161 : ImplicitConversionSequence::Worse; 4162 } 4163 } 4164 4165 // Ranking of member-pointer types. 4166 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4167 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4168 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4169 const MemberPointerType * FromMemPointer1 = 4170 FromType1->getAs<MemberPointerType>(); 4171 const MemberPointerType * ToMemPointer1 = 4172 ToType1->getAs<MemberPointerType>(); 4173 const MemberPointerType * FromMemPointer2 = 4174 FromType2->getAs<MemberPointerType>(); 4175 const MemberPointerType * ToMemPointer2 = 4176 ToType2->getAs<MemberPointerType>(); 4177 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4178 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4179 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4180 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4181 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4182 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4183 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4184 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4185 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4186 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4187 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4188 return ImplicitConversionSequence::Worse; 4189 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4190 return ImplicitConversionSequence::Better; 4191 } 4192 // conversion of B::* to C::* is better than conversion of A::* to C::* 4193 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4194 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4195 return ImplicitConversionSequence::Better; 4196 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4197 return ImplicitConversionSequence::Worse; 4198 } 4199 } 4200 4201 if (SCS1.Second == ICK_Derived_To_Base) { 4202 // -- conversion of C to B is better than conversion of C to A, 4203 // -- binding of an expression of type C to a reference of type 4204 // B& is better than binding an expression of type C to a 4205 // reference of type A&, 4206 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4207 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4208 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4209 return ImplicitConversionSequence::Better; 4210 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4211 return ImplicitConversionSequence::Worse; 4212 } 4213 4214 // -- conversion of B to A is better than conversion of C to A. 4215 // -- binding of an expression of type B to a reference of type 4216 // A& is better than binding an expression of type C to a 4217 // reference of type A&, 4218 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4219 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4220 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4221 return ImplicitConversionSequence::Better; 4222 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4223 return ImplicitConversionSequence::Worse; 4224 } 4225 } 4226 4227 return ImplicitConversionSequence::Indistinguishable; 4228 } 4229 4230 /// Determine whether the given type is valid, e.g., it is not an invalid 4231 /// C++ class. 4232 static bool isTypeValid(QualType T) { 4233 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4234 return !Record->isInvalidDecl(); 4235 4236 return true; 4237 } 4238 4239 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4240 /// determine whether they are reference-related, 4241 /// reference-compatible, reference-compatible with added 4242 /// qualification, or incompatible, for use in C++ initialization by 4243 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4244 /// type, and the first type (T1) is the pointee type of the reference 4245 /// type being initialized. 4246 Sema::ReferenceCompareResult 4247 Sema::CompareReferenceRelationship(SourceLocation Loc, 4248 QualType OrigT1, QualType OrigT2, 4249 bool &DerivedToBase, 4250 bool &ObjCConversion, 4251 bool &ObjCLifetimeConversion) { 4252 assert(!OrigT1->isReferenceType() && 4253 "T1 must be the pointee type of the reference type"); 4254 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4255 4256 QualType T1 = Context.getCanonicalType(OrigT1); 4257 QualType T2 = Context.getCanonicalType(OrigT2); 4258 Qualifiers T1Quals, T2Quals; 4259 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4260 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4261 4262 // C++ [dcl.init.ref]p4: 4263 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4264 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4265 // T1 is a base class of T2. 4266 DerivedToBase = false; 4267 ObjCConversion = false; 4268 ObjCLifetimeConversion = false; 4269 QualType ConvertedT2; 4270 if (UnqualT1 == UnqualT2) { 4271 // Nothing to do. 4272 } else if (isCompleteType(Loc, OrigT2) && 4273 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4274 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4275 DerivedToBase = true; 4276 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4277 UnqualT2->isObjCObjectOrInterfaceType() && 4278 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4279 ObjCConversion = true; 4280 else if (UnqualT2->isFunctionType() && 4281 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4282 // C++1z [dcl.init.ref]p4: 4283 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4284 // function" and T1 is "function" 4285 // 4286 // We extend this to also apply to 'noreturn', so allow any function 4287 // conversion between function types. 4288 return Ref_Compatible; 4289 else 4290 return Ref_Incompatible; 4291 4292 // At this point, we know that T1 and T2 are reference-related (at 4293 // least). 4294 4295 // If the type is an array type, promote the element qualifiers to the type 4296 // for comparison. 4297 if (isa<ArrayType>(T1) && T1Quals) 4298 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4299 if (isa<ArrayType>(T2) && T2Quals) 4300 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4301 4302 // C++ [dcl.init.ref]p4: 4303 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4304 // reference-related to T2 and cv1 is the same cv-qualification 4305 // as, or greater cv-qualification than, cv2. For purposes of 4306 // overload resolution, cases for which cv1 is greater 4307 // cv-qualification than cv2 are identified as 4308 // reference-compatible with added qualification (see 13.3.3.2). 4309 // 4310 // Note that we also require equivalence of Objective-C GC and address-space 4311 // qualifiers when performing these computations, so that e.g., an int in 4312 // address space 1 is not reference-compatible with an int in address 4313 // space 2. 4314 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4315 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4316 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4317 ObjCLifetimeConversion = true; 4318 4319 T1Quals.removeObjCLifetime(); 4320 T2Quals.removeObjCLifetime(); 4321 } 4322 4323 // MS compiler ignores __unaligned qualifier for references; do the same. 4324 T1Quals.removeUnaligned(); 4325 T2Quals.removeUnaligned(); 4326 4327 if (T1Quals.compatiblyIncludes(T2Quals)) 4328 return Ref_Compatible; 4329 else 4330 return Ref_Related; 4331 } 4332 4333 /// Look for a user-defined conversion to a value reference-compatible 4334 /// with DeclType. Return true if something definite is found. 4335 static bool 4336 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4337 QualType DeclType, SourceLocation DeclLoc, 4338 Expr *Init, QualType T2, bool AllowRvalues, 4339 bool AllowExplicit) { 4340 assert(T2->isRecordType() && "Can only find conversions of record types."); 4341 CXXRecordDecl *T2RecordDecl 4342 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4343 4344 OverloadCandidateSet CandidateSet( 4345 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4346 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4347 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4348 NamedDecl *D = *I; 4349 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4350 if (isa<UsingShadowDecl>(D)) 4351 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4352 4353 FunctionTemplateDecl *ConvTemplate 4354 = dyn_cast<FunctionTemplateDecl>(D); 4355 CXXConversionDecl *Conv; 4356 if (ConvTemplate) 4357 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4358 else 4359 Conv = cast<CXXConversionDecl>(D); 4360 4361 // If this is an explicit conversion, and we're not allowed to consider 4362 // explicit conversions, skip it. 4363 if (!AllowExplicit && Conv->isExplicit()) 4364 continue; 4365 4366 if (AllowRvalues) { 4367 bool DerivedToBase = false; 4368 bool ObjCConversion = false; 4369 bool ObjCLifetimeConversion = false; 4370 4371 // If we are initializing an rvalue reference, don't permit conversion 4372 // functions that return lvalues. 4373 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4374 const ReferenceType *RefType 4375 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4376 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4377 continue; 4378 } 4379 4380 if (!ConvTemplate && 4381 S.CompareReferenceRelationship( 4382 DeclLoc, 4383 Conv->getConversionType().getNonReferenceType() 4384 .getUnqualifiedType(), 4385 DeclType.getNonReferenceType().getUnqualifiedType(), 4386 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4387 Sema::Ref_Incompatible) 4388 continue; 4389 } else { 4390 // If the conversion function doesn't return a reference type, 4391 // it can't be considered for this conversion. An rvalue reference 4392 // is only acceptable if its referencee is a function type. 4393 4394 const ReferenceType *RefType = 4395 Conv->getConversionType()->getAs<ReferenceType>(); 4396 if (!RefType || 4397 (!RefType->isLValueReferenceType() && 4398 !RefType->getPointeeType()->isFunctionType())) 4399 continue; 4400 } 4401 4402 if (ConvTemplate) 4403 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4404 Init, DeclType, CandidateSet, 4405 /*AllowObjCConversionOnExplicit=*/false); 4406 else 4407 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4408 DeclType, CandidateSet, 4409 /*AllowObjCConversionOnExplicit=*/false); 4410 } 4411 4412 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4413 4414 OverloadCandidateSet::iterator Best; 4415 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4416 case OR_Success: 4417 // C++ [over.ics.ref]p1: 4418 // 4419 // [...] If the parameter binds directly to the result of 4420 // applying a conversion function to the argument 4421 // expression, the implicit conversion sequence is a 4422 // user-defined conversion sequence (13.3.3.1.2), with the 4423 // second standard conversion sequence either an identity 4424 // conversion or, if the conversion function returns an 4425 // entity of a type that is a derived class of the parameter 4426 // type, a derived-to-base Conversion. 4427 if (!Best->FinalConversion.DirectBinding) 4428 return false; 4429 4430 ICS.setUserDefined(); 4431 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4432 ICS.UserDefined.After = Best->FinalConversion; 4433 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4434 ICS.UserDefined.ConversionFunction = Best->Function; 4435 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4436 ICS.UserDefined.EllipsisConversion = false; 4437 assert(ICS.UserDefined.After.ReferenceBinding && 4438 ICS.UserDefined.After.DirectBinding && 4439 "Expected a direct reference binding!"); 4440 return true; 4441 4442 case OR_Ambiguous: 4443 ICS.setAmbiguous(); 4444 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4445 Cand != CandidateSet.end(); ++Cand) 4446 if (Cand->Viable) 4447 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4448 return true; 4449 4450 case OR_No_Viable_Function: 4451 case OR_Deleted: 4452 // There was no suitable conversion, or we found a deleted 4453 // conversion; continue with other checks. 4454 return false; 4455 } 4456 4457 llvm_unreachable("Invalid OverloadResult!"); 4458 } 4459 4460 /// Compute an implicit conversion sequence for reference 4461 /// initialization. 4462 static ImplicitConversionSequence 4463 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4464 SourceLocation DeclLoc, 4465 bool SuppressUserConversions, 4466 bool AllowExplicit) { 4467 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4468 4469 // Most paths end in a failed conversion. 4470 ImplicitConversionSequence ICS; 4471 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4472 4473 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4474 QualType T2 = Init->getType(); 4475 4476 // If the initializer is the address of an overloaded function, try 4477 // to resolve the overloaded function. If all goes well, T2 is the 4478 // type of the resulting function. 4479 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4480 DeclAccessPair Found; 4481 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4482 false, Found)) 4483 T2 = Fn->getType(); 4484 } 4485 4486 // Compute some basic properties of the types and the initializer. 4487 bool isRValRef = DeclType->isRValueReferenceType(); 4488 bool DerivedToBase = false; 4489 bool ObjCConversion = false; 4490 bool ObjCLifetimeConversion = false; 4491 Expr::Classification InitCategory = Init->Classify(S.Context); 4492 Sema::ReferenceCompareResult RefRelationship 4493 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4494 ObjCConversion, ObjCLifetimeConversion); 4495 4496 4497 // C++0x [dcl.init.ref]p5: 4498 // A reference to type "cv1 T1" is initialized by an expression 4499 // of type "cv2 T2" as follows: 4500 4501 // -- If reference is an lvalue reference and the initializer expression 4502 if (!isRValRef) { 4503 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4504 // reference-compatible with "cv2 T2," or 4505 // 4506 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4507 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4508 // C++ [over.ics.ref]p1: 4509 // When a parameter of reference type binds directly (8.5.3) 4510 // to an argument expression, the implicit conversion sequence 4511 // is the identity conversion, unless the argument expression 4512 // has a type that is a derived class of the parameter type, 4513 // in which case the implicit conversion sequence is a 4514 // derived-to-base Conversion (13.3.3.1). 4515 ICS.setStandard(); 4516 ICS.Standard.First = ICK_Identity; 4517 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4518 : ObjCConversion? ICK_Compatible_Conversion 4519 : ICK_Identity; 4520 ICS.Standard.Third = ICK_Identity; 4521 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4522 ICS.Standard.setToType(0, T2); 4523 ICS.Standard.setToType(1, T1); 4524 ICS.Standard.setToType(2, T1); 4525 ICS.Standard.ReferenceBinding = true; 4526 ICS.Standard.DirectBinding = true; 4527 ICS.Standard.IsLvalueReference = !isRValRef; 4528 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4529 ICS.Standard.BindsToRvalue = false; 4530 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4531 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4532 ICS.Standard.CopyConstructor = nullptr; 4533 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4534 4535 // Nothing more to do: the inaccessibility/ambiguity check for 4536 // derived-to-base conversions is suppressed when we're 4537 // computing the implicit conversion sequence (C++ 4538 // [over.best.ics]p2). 4539 return ICS; 4540 } 4541 4542 // -- has a class type (i.e., T2 is a class type), where T1 is 4543 // not reference-related to T2, and can be implicitly 4544 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4545 // is reference-compatible with "cv3 T3" 92) (this 4546 // conversion is selected by enumerating the applicable 4547 // conversion functions (13.3.1.6) and choosing the best 4548 // one through overload resolution (13.3)), 4549 if (!SuppressUserConversions && T2->isRecordType() && 4550 S.isCompleteType(DeclLoc, T2) && 4551 RefRelationship == Sema::Ref_Incompatible) { 4552 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4553 Init, T2, /*AllowRvalues=*/false, 4554 AllowExplicit)) 4555 return ICS; 4556 } 4557 } 4558 4559 // -- Otherwise, the reference shall be an lvalue reference to a 4560 // non-volatile const type (i.e., cv1 shall be const), or the reference 4561 // shall be an rvalue reference. 4562 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4563 return ICS; 4564 4565 // -- If the initializer expression 4566 // 4567 // -- is an xvalue, class prvalue, array prvalue or function 4568 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4569 if (RefRelationship == Sema::Ref_Compatible && 4570 (InitCategory.isXValue() || 4571 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4572 (InitCategory.isLValue() && T2->isFunctionType()))) { 4573 ICS.setStandard(); 4574 ICS.Standard.First = ICK_Identity; 4575 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4576 : ObjCConversion? ICK_Compatible_Conversion 4577 : ICK_Identity; 4578 ICS.Standard.Third = ICK_Identity; 4579 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4580 ICS.Standard.setToType(0, T2); 4581 ICS.Standard.setToType(1, T1); 4582 ICS.Standard.setToType(2, T1); 4583 ICS.Standard.ReferenceBinding = true; 4584 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4585 // binding unless we're binding to a class prvalue. 4586 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4587 // allow the use of rvalue references in C++98/03 for the benefit of 4588 // standard library implementors; therefore, we need the xvalue check here. 4589 ICS.Standard.DirectBinding = 4590 S.getLangOpts().CPlusPlus11 || 4591 !(InitCategory.isPRValue() || T2->isRecordType()); 4592 ICS.Standard.IsLvalueReference = !isRValRef; 4593 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4594 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4595 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4596 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4597 ICS.Standard.CopyConstructor = nullptr; 4598 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4599 return ICS; 4600 } 4601 4602 // -- has a class type (i.e., T2 is a class type), where T1 is not 4603 // reference-related to T2, and can be implicitly converted to 4604 // an xvalue, class prvalue, or function lvalue of type 4605 // "cv3 T3", where "cv1 T1" is reference-compatible with 4606 // "cv3 T3", 4607 // 4608 // then the reference is bound to the value of the initializer 4609 // expression in the first case and to the result of the conversion 4610 // in the second case (or, in either case, to an appropriate base 4611 // class subobject). 4612 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4613 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4614 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4615 Init, T2, /*AllowRvalues=*/true, 4616 AllowExplicit)) { 4617 // In the second case, if the reference is an rvalue reference 4618 // and the second standard conversion sequence of the 4619 // user-defined conversion sequence includes an lvalue-to-rvalue 4620 // conversion, the program is ill-formed. 4621 if (ICS.isUserDefined() && isRValRef && 4622 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4623 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4624 4625 return ICS; 4626 } 4627 4628 // A temporary of function type cannot be created; don't even try. 4629 if (T1->isFunctionType()) 4630 return ICS; 4631 4632 // -- Otherwise, a temporary of type "cv1 T1" is created and 4633 // initialized from the initializer expression using the 4634 // rules for a non-reference copy initialization (8.5). The 4635 // reference is then bound to the temporary. If T1 is 4636 // reference-related to T2, cv1 must be the same 4637 // cv-qualification as, or greater cv-qualification than, 4638 // cv2; otherwise, the program is ill-formed. 4639 if (RefRelationship == Sema::Ref_Related) { 4640 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4641 // we would be reference-compatible or reference-compatible with 4642 // added qualification. But that wasn't the case, so the reference 4643 // initialization fails. 4644 // 4645 // Note that we only want to check address spaces and cvr-qualifiers here. 4646 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4647 Qualifiers T1Quals = T1.getQualifiers(); 4648 Qualifiers T2Quals = T2.getQualifiers(); 4649 T1Quals.removeObjCGCAttr(); 4650 T1Quals.removeObjCLifetime(); 4651 T2Quals.removeObjCGCAttr(); 4652 T2Quals.removeObjCLifetime(); 4653 // MS compiler ignores __unaligned qualifier for references; do the same. 4654 T1Quals.removeUnaligned(); 4655 T2Quals.removeUnaligned(); 4656 if (!T1Quals.compatiblyIncludes(T2Quals)) 4657 return ICS; 4658 } 4659 4660 // If at least one of the types is a class type, the types are not 4661 // related, and we aren't allowed any user conversions, the 4662 // reference binding fails. This case is important for breaking 4663 // recursion, since TryImplicitConversion below will attempt to 4664 // create a temporary through the use of a copy constructor. 4665 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4666 (T1->isRecordType() || T2->isRecordType())) 4667 return ICS; 4668 4669 // If T1 is reference-related to T2 and the reference is an rvalue 4670 // reference, the initializer expression shall not be an lvalue. 4671 if (RefRelationship >= Sema::Ref_Related && 4672 isRValRef && Init->Classify(S.Context).isLValue()) 4673 return ICS; 4674 4675 // C++ [over.ics.ref]p2: 4676 // When a parameter of reference type is not bound directly to 4677 // an argument expression, the conversion sequence is the one 4678 // required to convert the argument expression to the 4679 // underlying type of the reference according to 4680 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4681 // to copy-initializing a temporary of the underlying type with 4682 // the argument expression. Any difference in top-level 4683 // cv-qualification is subsumed by the initialization itself 4684 // and does not constitute a conversion. 4685 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4686 /*AllowExplicit=*/false, 4687 /*InOverloadResolution=*/false, 4688 /*CStyle=*/false, 4689 /*AllowObjCWritebackConversion=*/false, 4690 /*AllowObjCConversionOnExplicit=*/false); 4691 4692 // Of course, that's still a reference binding. 4693 if (ICS.isStandard()) { 4694 ICS.Standard.ReferenceBinding = true; 4695 ICS.Standard.IsLvalueReference = !isRValRef; 4696 ICS.Standard.BindsToFunctionLvalue = false; 4697 ICS.Standard.BindsToRvalue = true; 4698 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4699 ICS.Standard.ObjCLifetimeConversionBinding = false; 4700 } else if (ICS.isUserDefined()) { 4701 const ReferenceType *LValRefType = 4702 ICS.UserDefined.ConversionFunction->getReturnType() 4703 ->getAs<LValueReferenceType>(); 4704 4705 // C++ [over.ics.ref]p3: 4706 // Except for an implicit object parameter, for which see 13.3.1, a 4707 // standard conversion sequence cannot be formed if it requires [...] 4708 // binding an rvalue reference to an lvalue other than a function 4709 // lvalue. 4710 // Note that the function case is not possible here. 4711 if (DeclType->isRValueReferenceType() && LValRefType) { 4712 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4713 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4714 // reference to an rvalue! 4715 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4716 return ICS; 4717 } 4718 4719 ICS.UserDefined.After.ReferenceBinding = true; 4720 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4721 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4722 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4723 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4724 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4725 } 4726 4727 return ICS; 4728 } 4729 4730 static ImplicitConversionSequence 4731 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4732 bool SuppressUserConversions, 4733 bool InOverloadResolution, 4734 bool AllowObjCWritebackConversion, 4735 bool AllowExplicit = false); 4736 4737 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4738 /// initializer list From. 4739 static ImplicitConversionSequence 4740 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4741 bool SuppressUserConversions, 4742 bool InOverloadResolution, 4743 bool AllowObjCWritebackConversion) { 4744 // C++11 [over.ics.list]p1: 4745 // When an argument is an initializer list, it is not an expression and 4746 // special rules apply for converting it to a parameter type. 4747 4748 ImplicitConversionSequence Result; 4749 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4750 4751 // We need a complete type for what follows. Incomplete types can never be 4752 // initialized from init lists. 4753 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4754 return Result; 4755 4756 // Per DR1467: 4757 // If the parameter type is a class X and the initializer list has a single 4758 // element of type cv U, where U is X or a class derived from X, the 4759 // implicit conversion sequence is the one required to convert the element 4760 // to the parameter type. 4761 // 4762 // Otherwise, if the parameter type is a character array [... ] 4763 // and the initializer list has a single element that is an 4764 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4765 // implicit conversion sequence is the identity conversion. 4766 if (From->getNumInits() == 1) { 4767 if (ToType->isRecordType()) { 4768 QualType InitType = From->getInit(0)->getType(); 4769 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4770 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4771 return TryCopyInitialization(S, From->getInit(0), ToType, 4772 SuppressUserConversions, 4773 InOverloadResolution, 4774 AllowObjCWritebackConversion); 4775 } 4776 // FIXME: Check the other conditions here: array of character type, 4777 // initializer is a string literal. 4778 if (ToType->isArrayType()) { 4779 InitializedEntity Entity = 4780 InitializedEntity::InitializeParameter(S.Context, ToType, 4781 /*Consumed=*/false); 4782 if (S.CanPerformCopyInitialization(Entity, From)) { 4783 Result.setStandard(); 4784 Result.Standard.setAsIdentityConversion(); 4785 Result.Standard.setFromType(ToType); 4786 Result.Standard.setAllToTypes(ToType); 4787 return Result; 4788 } 4789 } 4790 } 4791 4792 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4793 // C++11 [over.ics.list]p2: 4794 // If the parameter type is std::initializer_list<X> or "array of X" and 4795 // all the elements can be implicitly converted to X, the implicit 4796 // conversion sequence is the worst conversion necessary to convert an 4797 // element of the list to X. 4798 // 4799 // C++14 [over.ics.list]p3: 4800 // Otherwise, if the parameter type is "array of N X", if the initializer 4801 // list has exactly N elements or if it has fewer than N elements and X is 4802 // default-constructible, and if all the elements of the initializer list 4803 // can be implicitly converted to X, the implicit conversion sequence is 4804 // the worst conversion necessary to convert an element of the list to X. 4805 // 4806 // FIXME: We're missing a lot of these checks. 4807 bool toStdInitializerList = false; 4808 QualType X; 4809 if (ToType->isArrayType()) 4810 X = S.Context.getAsArrayType(ToType)->getElementType(); 4811 else 4812 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4813 if (!X.isNull()) { 4814 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4815 Expr *Init = From->getInit(i); 4816 ImplicitConversionSequence ICS = 4817 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4818 InOverloadResolution, 4819 AllowObjCWritebackConversion); 4820 // If a single element isn't convertible, fail. 4821 if (ICS.isBad()) { 4822 Result = ICS; 4823 break; 4824 } 4825 // Otherwise, look for the worst conversion. 4826 if (Result.isBad() || CompareImplicitConversionSequences( 4827 S, From->getBeginLoc(), ICS, Result) == 4828 ImplicitConversionSequence::Worse) 4829 Result = ICS; 4830 } 4831 4832 // For an empty list, we won't have computed any conversion sequence. 4833 // Introduce the identity conversion sequence. 4834 if (From->getNumInits() == 0) { 4835 Result.setStandard(); 4836 Result.Standard.setAsIdentityConversion(); 4837 Result.Standard.setFromType(ToType); 4838 Result.Standard.setAllToTypes(ToType); 4839 } 4840 4841 Result.setStdInitializerListElement(toStdInitializerList); 4842 return Result; 4843 } 4844 4845 // C++14 [over.ics.list]p4: 4846 // C++11 [over.ics.list]p3: 4847 // Otherwise, if the parameter is a non-aggregate class X and overload 4848 // resolution chooses a single best constructor [...] the implicit 4849 // conversion sequence is a user-defined conversion sequence. If multiple 4850 // constructors are viable but none is better than the others, the 4851 // implicit conversion sequence is a user-defined conversion sequence. 4852 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4853 // This function can deal with initializer lists. 4854 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4855 /*AllowExplicit=*/false, 4856 InOverloadResolution, /*CStyle=*/false, 4857 AllowObjCWritebackConversion, 4858 /*AllowObjCConversionOnExplicit=*/false); 4859 } 4860 4861 // C++14 [over.ics.list]p5: 4862 // C++11 [over.ics.list]p4: 4863 // Otherwise, if the parameter has an aggregate type which can be 4864 // initialized from the initializer list [...] the implicit conversion 4865 // sequence is a user-defined conversion sequence. 4866 if (ToType->isAggregateType()) { 4867 // Type is an aggregate, argument is an init list. At this point it comes 4868 // down to checking whether the initialization works. 4869 // FIXME: Find out whether this parameter is consumed or not. 4870 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4871 // need to call into the initialization code here; overload resolution 4872 // should not be doing that. 4873 InitializedEntity Entity = 4874 InitializedEntity::InitializeParameter(S.Context, ToType, 4875 /*Consumed=*/false); 4876 if (S.CanPerformCopyInitialization(Entity, From)) { 4877 Result.setUserDefined(); 4878 Result.UserDefined.Before.setAsIdentityConversion(); 4879 // Initializer lists don't have a type. 4880 Result.UserDefined.Before.setFromType(QualType()); 4881 Result.UserDefined.Before.setAllToTypes(QualType()); 4882 4883 Result.UserDefined.After.setAsIdentityConversion(); 4884 Result.UserDefined.After.setFromType(ToType); 4885 Result.UserDefined.After.setAllToTypes(ToType); 4886 Result.UserDefined.ConversionFunction = nullptr; 4887 } 4888 return Result; 4889 } 4890 4891 // C++14 [over.ics.list]p6: 4892 // C++11 [over.ics.list]p5: 4893 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4894 if (ToType->isReferenceType()) { 4895 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4896 // mention initializer lists in any way. So we go by what list- 4897 // initialization would do and try to extrapolate from that. 4898 4899 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4900 4901 // If the initializer list has a single element that is reference-related 4902 // to the parameter type, we initialize the reference from that. 4903 if (From->getNumInits() == 1) { 4904 Expr *Init = From->getInit(0); 4905 4906 QualType T2 = Init->getType(); 4907 4908 // If the initializer is the address of an overloaded function, try 4909 // to resolve the overloaded function. If all goes well, T2 is the 4910 // type of the resulting function. 4911 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4912 DeclAccessPair Found; 4913 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4914 Init, ToType, false, Found)) 4915 T2 = Fn->getType(); 4916 } 4917 4918 // Compute some basic properties of the types and the initializer. 4919 bool dummy1 = false; 4920 bool dummy2 = false; 4921 bool dummy3 = false; 4922 Sema::ReferenceCompareResult RefRelationship = 4923 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, 4924 dummy2, dummy3); 4925 4926 if (RefRelationship >= Sema::Ref_Related) { 4927 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 4928 SuppressUserConversions, 4929 /*AllowExplicit=*/false); 4930 } 4931 } 4932 4933 // Otherwise, we bind the reference to a temporary created from the 4934 // initializer list. 4935 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4936 InOverloadResolution, 4937 AllowObjCWritebackConversion); 4938 if (Result.isFailure()) 4939 return Result; 4940 assert(!Result.isEllipsis() && 4941 "Sub-initialization cannot result in ellipsis conversion."); 4942 4943 // Can we even bind to a temporary? 4944 if (ToType->isRValueReferenceType() || 4945 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4946 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4947 Result.UserDefined.After; 4948 SCS.ReferenceBinding = true; 4949 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4950 SCS.BindsToRvalue = true; 4951 SCS.BindsToFunctionLvalue = false; 4952 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4953 SCS.ObjCLifetimeConversionBinding = false; 4954 } else 4955 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4956 From, ToType); 4957 return Result; 4958 } 4959 4960 // C++14 [over.ics.list]p7: 4961 // C++11 [over.ics.list]p6: 4962 // Otherwise, if the parameter type is not a class: 4963 if (!ToType->isRecordType()) { 4964 // - if the initializer list has one element that is not itself an 4965 // initializer list, the implicit conversion sequence is the one 4966 // required to convert the element to the parameter type. 4967 unsigned NumInits = From->getNumInits(); 4968 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4969 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4970 SuppressUserConversions, 4971 InOverloadResolution, 4972 AllowObjCWritebackConversion); 4973 // - if the initializer list has no elements, the implicit conversion 4974 // sequence is the identity conversion. 4975 else if (NumInits == 0) { 4976 Result.setStandard(); 4977 Result.Standard.setAsIdentityConversion(); 4978 Result.Standard.setFromType(ToType); 4979 Result.Standard.setAllToTypes(ToType); 4980 } 4981 return Result; 4982 } 4983 4984 // C++14 [over.ics.list]p8: 4985 // C++11 [over.ics.list]p7: 4986 // In all cases other than those enumerated above, no conversion is possible 4987 return Result; 4988 } 4989 4990 /// TryCopyInitialization - Try to copy-initialize a value of type 4991 /// ToType from the expression From. Return the implicit conversion 4992 /// sequence required to pass this argument, which may be a bad 4993 /// conversion sequence (meaning that the argument cannot be passed to 4994 /// a parameter of this type). If @p SuppressUserConversions, then we 4995 /// do not permit any user-defined conversion sequences. 4996 static ImplicitConversionSequence 4997 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4998 bool SuppressUserConversions, 4999 bool InOverloadResolution, 5000 bool AllowObjCWritebackConversion, 5001 bool AllowExplicit) { 5002 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5003 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5004 InOverloadResolution,AllowObjCWritebackConversion); 5005 5006 if (ToType->isReferenceType()) 5007 return TryReferenceInit(S, From, ToType, 5008 /*FIXME:*/ From->getBeginLoc(), 5009 SuppressUserConversions, AllowExplicit); 5010 5011 return TryImplicitConversion(S, From, ToType, 5012 SuppressUserConversions, 5013 /*AllowExplicit=*/false, 5014 InOverloadResolution, 5015 /*CStyle=*/false, 5016 AllowObjCWritebackConversion, 5017 /*AllowObjCConversionOnExplicit=*/false); 5018 } 5019 5020 static bool TryCopyInitialization(const CanQualType FromQTy, 5021 const CanQualType ToQTy, 5022 Sema &S, 5023 SourceLocation Loc, 5024 ExprValueKind FromVK) { 5025 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5026 ImplicitConversionSequence ICS = 5027 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5028 5029 return !ICS.isBad(); 5030 } 5031 5032 /// TryObjectArgumentInitialization - Try to initialize the object 5033 /// parameter of the given member function (@c Method) from the 5034 /// expression @p From. 5035 static ImplicitConversionSequence 5036 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5037 Expr::Classification FromClassification, 5038 CXXMethodDecl *Method, 5039 CXXRecordDecl *ActingContext) { 5040 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5041 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5042 // const volatile object. 5043 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 5044 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 5045 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 5046 5047 // Set up the conversion sequence as a "bad" conversion, to allow us 5048 // to exit early. 5049 ImplicitConversionSequence ICS; 5050 5051 // We need to have an object of class type. 5052 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5053 FromType = PT->getPointeeType(); 5054 5055 // When we had a pointer, it's implicitly dereferenced, so we 5056 // better have an lvalue. 5057 assert(FromClassification.isLValue()); 5058 } 5059 5060 assert(FromType->isRecordType()); 5061 5062 // C++0x [over.match.funcs]p4: 5063 // For non-static member functions, the type of the implicit object 5064 // parameter is 5065 // 5066 // - "lvalue reference to cv X" for functions declared without a 5067 // ref-qualifier or with the & ref-qualifier 5068 // - "rvalue reference to cv X" for functions declared with the && 5069 // ref-qualifier 5070 // 5071 // where X is the class of which the function is a member and cv is the 5072 // cv-qualification on the member function declaration. 5073 // 5074 // However, when finding an implicit conversion sequence for the argument, we 5075 // are not allowed to perform user-defined conversions 5076 // (C++ [over.match.funcs]p5). We perform a simplified version of 5077 // reference binding here, that allows class rvalues to bind to 5078 // non-constant references. 5079 5080 // First check the qualifiers. 5081 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5082 if (ImplicitParamType.getCVRQualifiers() 5083 != FromTypeCanon.getLocalCVRQualifiers() && 5084 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5085 ICS.setBad(BadConversionSequence::bad_qualifiers, 5086 FromType, ImplicitParamType); 5087 return ICS; 5088 } 5089 5090 // Check that we have either the same type or a derived type. It 5091 // affects the conversion rank. 5092 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5093 ImplicitConversionKind SecondKind; 5094 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5095 SecondKind = ICK_Identity; 5096 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5097 SecondKind = ICK_Derived_To_Base; 5098 else { 5099 ICS.setBad(BadConversionSequence::unrelated_class, 5100 FromType, ImplicitParamType); 5101 return ICS; 5102 } 5103 5104 // Check the ref-qualifier. 5105 switch (Method->getRefQualifier()) { 5106 case RQ_None: 5107 // Do nothing; we don't care about lvalueness or rvalueness. 5108 break; 5109 5110 case RQ_LValue: 5111 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 5112 // non-const lvalue reference cannot bind to an rvalue 5113 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5114 ImplicitParamType); 5115 return ICS; 5116 } 5117 break; 5118 5119 case RQ_RValue: 5120 if (!FromClassification.isRValue()) { 5121 // rvalue reference cannot bind to an lvalue 5122 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5123 ImplicitParamType); 5124 return ICS; 5125 } 5126 break; 5127 } 5128 5129 // Success. Mark this as a reference binding. 5130 ICS.setStandard(); 5131 ICS.Standard.setAsIdentityConversion(); 5132 ICS.Standard.Second = SecondKind; 5133 ICS.Standard.setFromType(FromType); 5134 ICS.Standard.setAllToTypes(ImplicitParamType); 5135 ICS.Standard.ReferenceBinding = true; 5136 ICS.Standard.DirectBinding = true; 5137 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5138 ICS.Standard.BindsToFunctionLvalue = false; 5139 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5140 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5141 = (Method->getRefQualifier() == RQ_None); 5142 return ICS; 5143 } 5144 5145 /// PerformObjectArgumentInitialization - Perform initialization of 5146 /// the implicit object parameter for the given Method with the given 5147 /// expression. 5148 ExprResult 5149 Sema::PerformObjectArgumentInitialization(Expr *From, 5150 NestedNameSpecifier *Qualifier, 5151 NamedDecl *FoundDecl, 5152 CXXMethodDecl *Method) { 5153 QualType FromRecordType, DestType; 5154 QualType ImplicitParamRecordType = 5155 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5156 5157 Expr::Classification FromClassification; 5158 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5159 FromRecordType = PT->getPointeeType(); 5160 DestType = Method->getThisType(Context); 5161 FromClassification = Expr::Classification::makeSimpleLValue(); 5162 } else { 5163 FromRecordType = From->getType(); 5164 DestType = ImplicitParamRecordType; 5165 FromClassification = From->Classify(Context); 5166 5167 // When performing member access on an rvalue, materialize a temporary. 5168 if (From->isRValue()) { 5169 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5170 Method->getRefQualifier() != 5171 RefQualifierKind::RQ_RValue); 5172 } 5173 } 5174 5175 // Note that we always use the true parent context when performing 5176 // the actual argument initialization. 5177 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5178 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5179 Method->getParent()); 5180 if (ICS.isBad()) { 5181 switch (ICS.Bad.Kind) { 5182 case BadConversionSequence::bad_qualifiers: { 5183 Qualifiers FromQs = FromRecordType.getQualifiers(); 5184 Qualifiers ToQs = DestType.getQualifiers(); 5185 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5186 if (CVR) { 5187 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5188 << Method->getDeclName() << FromRecordType << (CVR - 1) 5189 << From->getSourceRange(); 5190 Diag(Method->getLocation(), diag::note_previous_decl) 5191 << Method->getDeclName(); 5192 return ExprError(); 5193 } 5194 break; 5195 } 5196 5197 case BadConversionSequence::lvalue_ref_to_rvalue: 5198 case BadConversionSequence::rvalue_ref_to_lvalue: { 5199 bool IsRValueQualified = 5200 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5201 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5202 << Method->getDeclName() << FromClassification.isRValue() 5203 << IsRValueQualified; 5204 Diag(Method->getLocation(), diag::note_previous_decl) 5205 << Method->getDeclName(); 5206 return ExprError(); 5207 } 5208 5209 case BadConversionSequence::no_conversion: 5210 case BadConversionSequence::unrelated_class: 5211 break; 5212 } 5213 5214 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5215 << ImplicitParamRecordType << FromRecordType 5216 << From->getSourceRange(); 5217 } 5218 5219 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5220 ExprResult FromRes = 5221 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5222 if (FromRes.isInvalid()) 5223 return ExprError(); 5224 From = FromRes.get(); 5225 } 5226 5227 if (!Context.hasSameType(From->getType(), DestType)) 5228 From = ImpCastExprToType(From, DestType, CK_NoOp, 5229 From->getValueKind()).get(); 5230 return From; 5231 } 5232 5233 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5234 /// expression From to bool (C++0x [conv]p3). 5235 static ImplicitConversionSequence 5236 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5237 return TryImplicitConversion(S, From, S.Context.BoolTy, 5238 /*SuppressUserConversions=*/false, 5239 /*AllowExplicit=*/true, 5240 /*InOverloadResolution=*/false, 5241 /*CStyle=*/false, 5242 /*AllowObjCWritebackConversion=*/false, 5243 /*AllowObjCConversionOnExplicit=*/false); 5244 } 5245 5246 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5247 /// of the expression From to bool (C++0x [conv]p3). 5248 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5249 if (checkPlaceholderForOverload(*this, From)) 5250 return ExprError(); 5251 5252 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5253 if (!ICS.isBad()) 5254 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5255 5256 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5257 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5258 << From->getType() << From->getSourceRange(); 5259 return ExprError(); 5260 } 5261 5262 /// Check that the specified conversion is permitted in a converted constant 5263 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5264 /// is acceptable. 5265 static bool CheckConvertedConstantConversions(Sema &S, 5266 StandardConversionSequence &SCS) { 5267 // Since we know that the target type is an integral or unscoped enumeration 5268 // type, most conversion kinds are impossible. All possible First and Third 5269 // conversions are fine. 5270 switch (SCS.Second) { 5271 case ICK_Identity: 5272 case ICK_Function_Conversion: 5273 case ICK_Integral_Promotion: 5274 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5275 case ICK_Zero_Queue_Conversion: 5276 return true; 5277 5278 case ICK_Boolean_Conversion: 5279 // Conversion from an integral or unscoped enumeration type to bool is 5280 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5281 // conversion, so we allow it in a converted constant expression. 5282 // 5283 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5284 // a lot of popular code. We should at least add a warning for this 5285 // (non-conforming) extension. 5286 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5287 SCS.getToType(2)->isBooleanType(); 5288 5289 case ICK_Pointer_Conversion: 5290 case ICK_Pointer_Member: 5291 // C++1z: null pointer conversions and null member pointer conversions are 5292 // only permitted if the source type is std::nullptr_t. 5293 return SCS.getFromType()->isNullPtrType(); 5294 5295 case ICK_Floating_Promotion: 5296 case ICK_Complex_Promotion: 5297 case ICK_Floating_Conversion: 5298 case ICK_Complex_Conversion: 5299 case ICK_Floating_Integral: 5300 case ICK_Compatible_Conversion: 5301 case ICK_Derived_To_Base: 5302 case ICK_Vector_Conversion: 5303 case ICK_Vector_Splat: 5304 case ICK_Complex_Real: 5305 case ICK_Block_Pointer_Conversion: 5306 case ICK_TransparentUnionConversion: 5307 case ICK_Writeback_Conversion: 5308 case ICK_Zero_Event_Conversion: 5309 case ICK_C_Only_Conversion: 5310 case ICK_Incompatible_Pointer_Conversion: 5311 return false; 5312 5313 case ICK_Lvalue_To_Rvalue: 5314 case ICK_Array_To_Pointer: 5315 case ICK_Function_To_Pointer: 5316 llvm_unreachable("found a first conversion kind in Second"); 5317 5318 case ICK_Qualification: 5319 llvm_unreachable("found a third conversion kind in Second"); 5320 5321 case ICK_Num_Conversion_Kinds: 5322 break; 5323 } 5324 5325 llvm_unreachable("unknown conversion kind"); 5326 } 5327 5328 /// CheckConvertedConstantExpression - Check that the expression From is a 5329 /// converted constant expression of type T, perform the conversion and produce 5330 /// the converted expression, per C++11 [expr.const]p3. 5331 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5332 QualType T, APValue &Value, 5333 Sema::CCEKind CCE, 5334 bool RequireInt) { 5335 assert(S.getLangOpts().CPlusPlus11 && 5336 "converted constant expression outside C++11"); 5337 5338 if (checkPlaceholderForOverload(S, From)) 5339 return ExprError(); 5340 5341 // C++1z [expr.const]p3: 5342 // A converted constant expression of type T is an expression, 5343 // implicitly converted to type T, where the converted 5344 // expression is a constant expression and the implicit conversion 5345 // sequence contains only [... list of conversions ...]. 5346 // C++1z [stmt.if]p2: 5347 // If the if statement is of the form if constexpr, the value of the 5348 // condition shall be a contextually converted constant expression of type 5349 // bool. 5350 ImplicitConversionSequence ICS = 5351 CCE == Sema::CCEK_ConstexprIf 5352 ? TryContextuallyConvertToBool(S, From) 5353 : TryCopyInitialization(S, From, T, 5354 /*SuppressUserConversions=*/false, 5355 /*InOverloadResolution=*/false, 5356 /*AllowObjcWritebackConversion=*/false, 5357 /*AllowExplicit=*/false); 5358 StandardConversionSequence *SCS = nullptr; 5359 switch (ICS.getKind()) { 5360 case ImplicitConversionSequence::StandardConversion: 5361 SCS = &ICS.Standard; 5362 break; 5363 case ImplicitConversionSequence::UserDefinedConversion: 5364 // We are converting to a non-class type, so the Before sequence 5365 // must be trivial. 5366 SCS = &ICS.UserDefined.After; 5367 break; 5368 case ImplicitConversionSequence::AmbiguousConversion: 5369 case ImplicitConversionSequence::BadConversion: 5370 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5371 return S.Diag(From->getBeginLoc(), 5372 diag::err_typecheck_converted_constant_expression) 5373 << From->getType() << From->getSourceRange() << T; 5374 return ExprError(); 5375 5376 case ImplicitConversionSequence::EllipsisConversion: 5377 llvm_unreachable("ellipsis conversion in converted constant expression"); 5378 } 5379 5380 // Check that we would only use permitted conversions. 5381 if (!CheckConvertedConstantConversions(S, *SCS)) { 5382 return S.Diag(From->getBeginLoc(), 5383 diag::err_typecheck_converted_constant_expression_disallowed) 5384 << From->getType() << From->getSourceRange() << T; 5385 } 5386 // [...] and where the reference binding (if any) binds directly. 5387 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5388 return S.Diag(From->getBeginLoc(), 5389 diag::err_typecheck_converted_constant_expression_indirect) 5390 << From->getType() << From->getSourceRange() << T; 5391 } 5392 5393 ExprResult Result = 5394 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5395 if (Result.isInvalid()) 5396 return Result; 5397 5398 // Check for a narrowing implicit conversion. 5399 APValue PreNarrowingValue; 5400 QualType PreNarrowingType; 5401 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5402 PreNarrowingType)) { 5403 case NK_Dependent_Narrowing: 5404 // Implicit conversion to a narrower type, but the expression is 5405 // value-dependent so we can't tell whether it's actually narrowing. 5406 case NK_Variable_Narrowing: 5407 // Implicit conversion to a narrower type, and the value is not a constant 5408 // expression. We'll diagnose this in a moment. 5409 case NK_Not_Narrowing: 5410 break; 5411 5412 case NK_Constant_Narrowing: 5413 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5414 << CCE << /*Constant*/ 1 5415 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5416 break; 5417 5418 case NK_Type_Narrowing: 5419 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5420 << CCE << /*Constant*/ 0 << From->getType() << T; 5421 break; 5422 } 5423 5424 if (Result.get()->isValueDependent()) { 5425 Value = APValue(); 5426 return Result; 5427 } 5428 5429 // Check the expression is a constant expression. 5430 SmallVector<PartialDiagnosticAt, 8> Notes; 5431 Expr::EvalResult Eval; 5432 Eval.Diag = &Notes; 5433 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5434 ? Expr::EvaluateForMangling 5435 : Expr::EvaluateForCodeGen; 5436 5437 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5438 (RequireInt && !Eval.Val.isInt())) { 5439 // The expression can't be folded, so we can't keep it at this position in 5440 // the AST. 5441 Result = ExprError(); 5442 } else { 5443 Value = Eval.Val; 5444 5445 if (Notes.empty()) { 5446 // It's a constant expression. 5447 return new (S.Context) ConstantExpr(Result.get()); 5448 } 5449 } 5450 5451 // It's not a constant expression. Produce an appropriate diagnostic. 5452 if (Notes.size() == 1 && 5453 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5454 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5455 else { 5456 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5457 << CCE << From->getSourceRange(); 5458 for (unsigned I = 0; I < Notes.size(); ++I) 5459 S.Diag(Notes[I].first, Notes[I].second); 5460 } 5461 return ExprError(); 5462 } 5463 5464 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5465 APValue &Value, CCEKind CCE) { 5466 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5467 } 5468 5469 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5470 llvm::APSInt &Value, 5471 CCEKind CCE) { 5472 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5473 5474 APValue V; 5475 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5476 if (!R.isInvalid() && !R.get()->isValueDependent()) 5477 Value = V.getInt(); 5478 return R; 5479 } 5480 5481 5482 /// dropPointerConversions - If the given standard conversion sequence 5483 /// involves any pointer conversions, remove them. This may change 5484 /// the result type of the conversion sequence. 5485 static void dropPointerConversion(StandardConversionSequence &SCS) { 5486 if (SCS.Second == ICK_Pointer_Conversion) { 5487 SCS.Second = ICK_Identity; 5488 SCS.Third = ICK_Identity; 5489 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5490 } 5491 } 5492 5493 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5494 /// convert the expression From to an Objective-C pointer type. 5495 static ImplicitConversionSequence 5496 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5497 // Do an implicit conversion to 'id'. 5498 QualType Ty = S.Context.getObjCIdType(); 5499 ImplicitConversionSequence ICS 5500 = TryImplicitConversion(S, From, Ty, 5501 // FIXME: Are these flags correct? 5502 /*SuppressUserConversions=*/false, 5503 /*AllowExplicit=*/true, 5504 /*InOverloadResolution=*/false, 5505 /*CStyle=*/false, 5506 /*AllowObjCWritebackConversion=*/false, 5507 /*AllowObjCConversionOnExplicit=*/true); 5508 5509 // Strip off any final conversions to 'id'. 5510 switch (ICS.getKind()) { 5511 case ImplicitConversionSequence::BadConversion: 5512 case ImplicitConversionSequence::AmbiguousConversion: 5513 case ImplicitConversionSequence::EllipsisConversion: 5514 break; 5515 5516 case ImplicitConversionSequence::UserDefinedConversion: 5517 dropPointerConversion(ICS.UserDefined.After); 5518 break; 5519 5520 case ImplicitConversionSequence::StandardConversion: 5521 dropPointerConversion(ICS.Standard); 5522 break; 5523 } 5524 5525 return ICS; 5526 } 5527 5528 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5529 /// conversion of the expression From to an Objective-C pointer type. 5530 /// Returns a valid but null ExprResult if no conversion sequence exists. 5531 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5532 if (checkPlaceholderForOverload(*this, From)) 5533 return ExprError(); 5534 5535 QualType Ty = Context.getObjCIdType(); 5536 ImplicitConversionSequence ICS = 5537 TryContextuallyConvertToObjCPointer(*this, From); 5538 if (!ICS.isBad()) 5539 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5540 return ExprResult(); 5541 } 5542 5543 /// Determine whether the provided type is an integral type, or an enumeration 5544 /// type of a permitted flavor. 5545 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5546 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5547 : T->isIntegralOrUnscopedEnumerationType(); 5548 } 5549 5550 static ExprResult 5551 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5552 Sema::ContextualImplicitConverter &Converter, 5553 QualType T, UnresolvedSetImpl &ViableConversions) { 5554 5555 if (Converter.Suppress) 5556 return ExprError(); 5557 5558 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5559 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5560 CXXConversionDecl *Conv = 5561 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5562 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5563 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5564 } 5565 return From; 5566 } 5567 5568 static bool 5569 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5570 Sema::ContextualImplicitConverter &Converter, 5571 QualType T, bool HadMultipleCandidates, 5572 UnresolvedSetImpl &ExplicitConversions) { 5573 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5574 DeclAccessPair Found = ExplicitConversions[0]; 5575 CXXConversionDecl *Conversion = 5576 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5577 5578 // The user probably meant to invoke the given explicit 5579 // conversion; use it. 5580 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5581 std::string TypeStr; 5582 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5583 5584 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5585 << FixItHint::CreateInsertion(From->getBeginLoc(), 5586 "static_cast<" + TypeStr + ">(") 5587 << FixItHint::CreateInsertion( 5588 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5589 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5590 5591 // If we aren't in a SFINAE context, build a call to the 5592 // explicit conversion function. 5593 if (SemaRef.isSFINAEContext()) 5594 return true; 5595 5596 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5597 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5598 HadMultipleCandidates); 5599 if (Result.isInvalid()) 5600 return true; 5601 // Record usage of conversion in an implicit cast. 5602 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5603 CK_UserDefinedConversion, Result.get(), 5604 nullptr, Result.get()->getValueKind()); 5605 } 5606 return false; 5607 } 5608 5609 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5610 Sema::ContextualImplicitConverter &Converter, 5611 QualType T, bool HadMultipleCandidates, 5612 DeclAccessPair &Found) { 5613 CXXConversionDecl *Conversion = 5614 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5615 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5616 5617 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5618 if (!Converter.SuppressConversion) { 5619 if (SemaRef.isSFINAEContext()) 5620 return true; 5621 5622 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5623 << From->getSourceRange(); 5624 } 5625 5626 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5627 HadMultipleCandidates); 5628 if (Result.isInvalid()) 5629 return true; 5630 // Record usage of conversion in an implicit cast. 5631 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5632 CK_UserDefinedConversion, Result.get(), 5633 nullptr, Result.get()->getValueKind()); 5634 return false; 5635 } 5636 5637 static ExprResult finishContextualImplicitConversion( 5638 Sema &SemaRef, SourceLocation Loc, Expr *From, 5639 Sema::ContextualImplicitConverter &Converter) { 5640 if (!Converter.match(From->getType()) && !Converter.Suppress) 5641 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5642 << From->getSourceRange(); 5643 5644 return SemaRef.DefaultLvalueConversion(From); 5645 } 5646 5647 static void 5648 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5649 UnresolvedSetImpl &ViableConversions, 5650 OverloadCandidateSet &CandidateSet) { 5651 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5652 DeclAccessPair FoundDecl = ViableConversions[I]; 5653 NamedDecl *D = FoundDecl.getDecl(); 5654 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5655 if (isa<UsingShadowDecl>(D)) 5656 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5657 5658 CXXConversionDecl *Conv; 5659 FunctionTemplateDecl *ConvTemplate; 5660 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5661 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5662 else 5663 Conv = cast<CXXConversionDecl>(D); 5664 5665 if (ConvTemplate) 5666 SemaRef.AddTemplateConversionCandidate( 5667 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5668 /*AllowObjCConversionOnExplicit=*/false); 5669 else 5670 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5671 ToType, CandidateSet, 5672 /*AllowObjCConversionOnExplicit=*/false); 5673 } 5674 } 5675 5676 /// Attempt to convert the given expression to a type which is accepted 5677 /// by the given converter. 5678 /// 5679 /// This routine will attempt to convert an expression of class type to a 5680 /// type accepted by the specified converter. In C++11 and before, the class 5681 /// must have a single non-explicit conversion function converting to a matching 5682 /// type. In C++1y, there can be multiple such conversion functions, but only 5683 /// one target type. 5684 /// 5685 /// \param Loc The source location of the construct that requires the 5686 /// conversion. 5687 /// 5688 /// \param From The expression we're converting from. 5689 /// 5690 /// \param Converter Used to control and diagnose the conversion process. 5691 /// 5692 /// \returns The expression, converted to an integral or enumeration type if 5693 /// successful. 5694 ExprResult Sema::PerformContextualImplicitConversion( 5695 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5696 // We can't perform any more checking for type-dependent expressions. 5697 if (From->isTypeDependent()) 5698 return From; 5699 5700 // Process placeholders immediately. 5701 if (From->hasPlaceholderType()) { 5702 ExprResult result = CheckPlaceholderExpr(From); 5703 if (result.isInvalid()) 5704 return result; 5705 From = result.get(); 5706 } 5707 5708 // If the expression already has a matching type, we're golden. 5709 QualType T = From->getType(); 5710 if (Converter.match(T)) 5711 return DefaultLvalueConversion(From); 5712 5713 // FIXME: Check for missing '()' if T is a function type? 5714 5715 // We can only perform contextual implicit conversions on objects of class 5716 // type. 5717 const RecordType *RecordTy = T->getAs<RecordType>(); 5718 if (!RecordTy || !getLangOpts().CPlusPlus) { 5719 if (!Converter.Suppress) 5720 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5721 return From; 5722 } 5723 5724 // We must have a complete class type. 5725 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5726 ContextualImplicitConverter &Converter; 5727 Expr *From; 5728 5729 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5730 : Converter(Converter), From(From) {} 5731 5732 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5733 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5734 } 5735 } IncompleteDiagnoser(Converter, From); 5736 5737 if (Converter.Suppress ? !isCompleteType(Loc, T) 5738 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5739 return From; 5740 5741 // Look for a conversion to an integral or enumeration type. 5742 UnresolvedSet<4> 5743 ViableConversions; // These are *potentially* viable in C++1y. 5744 UnresolvedSet<4> ExplicitConversions; 5745 const auto &Conversions = 5746 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5747 5748 bool HadMultipleCandidates = 5749 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5750 5751 // To check that there is only one target type, in C++1y: 5752 QualType ToType; 5753 bool HasUniqueTargetType = true; 5754 5755 // Collect explicit or viable (potentially in C++1y) conversions. 5756 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5757 NamedDecl *D = (*I)->getUnderlyingDecl(); 5758 CXXConversionDecl *Conversion; 5759 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5760 if (ConvTemplate) { 5761 if (getLangOpts().CPlusPlus14) 5762 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5763 else 5764 continue; // C++11 does not consider conversion operator templates(?). 5765 } else 5766 Conversion = cast<CXXConversionDecl>(D); 5767 5768 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5769 "Conversion operator templates are considered potentially " 5770 "viable in C++1y"); 5771 5772 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5773 if (Converter.match(CurToType) || ConvTemplate) { 5774 5775 if (Conversion->isExplicit()) { 5776 // FIXME: For C++1y, do we need this restriction? 5777 // cf. diagnoseNoViableConversion() 5778 if (!ConvTemplate) 5779 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5780 } else { 5781 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5782 if (ToType.isNull()) 5783 ToType = CurToType.getUnqualifiedType(); 5784 else if (HasUniqueTargetType && 5785 (CurToType.getUnqualifiedType() != ToType)) 5786 HasUniqueTargetType = false; 5787 } 5788 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5789 } 5790 } 5791 } 5792 5793 if (getLangOpts().CPlusPlus14) { 5794 // C++1y [conv]p6: 5795 // ... An expression e of class type E appearing in such a context 5796 // is said to be contextually implicitly converted to a specified 5797 // type T and is well-formed if and only if e can be implicitly 5798 // converted to a type T that is determined as follows: E is searched 5799 // for conversion functions whose return type is cv T or reference to 5800 // cv T such that T is allowed by the context. There shall be 5801 // exactly one such T. 5802 5803 // If no unique T is found: 5804 if (ToType.isNull()) { 5805 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5806 HadMultipleCandidates, 5807 ExplicitConversions)) 5808 return ExprError(); 5809 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5810 } 5811 5812 // If more than one unique Ts are found: 5813 if (!HasUniqueTargetType) 5814 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5815 ViableConversions); 5816 5817 // If one unique T is found: 5818 // First, build a candidate set from the previously recorded 5819 // potentially viable conversions. 5820 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5821 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5822 CandidateSet); 5823 5824 // Then, perform overload resolution over the candidate set. 5825 OverloadCandidateSet::iterator Best; 5826 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5827 case OR_Success: { 5828 // Apply this conversion. 5829 DeclAccessPair Found = 5830 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5831 if (recordConversion(*this, Loc, From, Converter, T, 5832 HadMultipleCandidates, Found)) 5833 return ExprError(); 5834 break; 5835 } 5836 case OR_Ambiguous: 5837 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5838 ViableConversions); 5839 case OR_No_Viable_Function: 5840 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5841 HadMultipleCandidates, 5842 ExplicitConversions)) 5843 return ExprError(); 5844 LLVM_FALLTHROUGH; 5845 case OR_Deleted: 5846 // We'll complain below about a non-integral condition type. 5847 break; 5848 } 5849 } else { 5850 switch (ViableConversions.size()) { 5851 case 0: { 5852 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5853 HadMultipleCandidates, 5854 ExplicitConversions)) 5855 return ExprError(); 5856 5857 // We'll complain below about a non-integral condition type. 5858 break; 5859 } 5860 case 1: { 5861 // Apply this conversion. 5862 DeclAccessPair Found = ViableConversions[0]; 5863 if (recordConversion(*this, Loc, From, Converter, T, 5864 HadMultipleCandidates, Found)) 5865 return ExprError(); 5866 break; 5867 } 5868 default: 5869 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5870 ViableConversions); 5871 } 5872 } 5873 5874 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5875 } 5876 5877 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5878 /// an acceptable non-member overloaded operator for a call whose 5879 /// arguments have types T1 (and, if non-empty, T2). This routine 5880 /// implements the check in C++ [over.match.oper]p3b2 concerning 5881 /// enumeration types. 5882 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5883 FunctionDecl *Fn, 5884 ArrayRef<Expr *> Args) { 5885 QualType T1 = Args[0]->getType(); 5886 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5887 5888 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5889 return true; 5890 5891 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5892 return true; 5893 5894 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5895 if (Proto->getNumParams() < 1) 5896 return false; 5897 5898 if (T1->isEnumeralType()) { 5899 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5900 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5901 return true; 5902 } 5903 5904 if (Proto->getNumParams() < 2) 5905 return false; 5906 5907 if (!T2.isNull() && T2->isEnumeralType()) { 5908 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5909 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5910 return true; 5911 } 5912 5913 return false; 5914 } 5915 5916 /// AddOverloadCandidate - Adds the given function to the set of 5917 /// candidate functions, using the given function call arguments. If 5918 /// @p SuppressUserConversions, then don't allow user-defined 5919 /// conversions via constructors or conversion operators. 5920 /// 5921 /// \param PartialOverloading true if we are performing "partial" overloading 5922 /// based on an incomplete set of function arguments. This feature is used by 5923 /// code completion. 5924 void 5925 Sema::AddOverloadCandidate(FunctionDecl *Function, 5926 DeclAccessPair FoundDecl, 5927 ArrayRef<Expr *> Args, 5928 OverloadCandidateSet &CandidateSet, 5929 bool SuppressUserConversions, 5930 bool PartialOverloading, 5931 bool AllowExplicit, 5932 ConversionSequenceList EarlyConversions) { 5933 const FunctionProtoType *Proto 5934 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5935 assert(Proto && "Functions without a prototype cannot be overloaded"); 5936 assert(!Function->getDescribedFunctionTemplate() && 5937 "Use AddTemplateOverloadCandidate for function templates"); 5938 5939 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5940 if (!isa<CXXConstructorDecl>(Method)) { 5941 // If we get here, it's because we're calling a member function 5942 // that is named without a member access expression (e.g., 5943 // "this->f") that was either written explicitly or created 5944 // implicitly. This can happen with a qualified call to a member 5945 // function, e.g., X::f(). We use an empty type for the implied 5946 // object argument (C++ [over.call.func]p3), and the acting context 5947 // is irrelevant. 5948 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 5949 Expr::Classification::makeSimpleLValue(), Args, 5950 CandidateSet, SuppressUserConversions, 5951 PartialOverloading, EarlyConversions); 5952 return; 5953 } 5954 // We treat a constructor like a non-member function, since its object 5955 // argument doesn't participate in overload resolution. 5956 } 5957 5958 if (!CandidateSet.isNewCandidate(Function)) 5959 return; 5960 5961 // C++ [over.match.oper]p3: 5962 // if no operand has a class type, only those non-member functions in the 5963 // lookup set that have a first parameter of type T1 or "reference to 5964 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5965 // is a right operand) a second parameter of type T2 or "reference to 5966 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5967 // candidate functions. 5968 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5969 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5970 return; 5971 5972 // C++11 [class.copy]p11: [DR1402] 5973 // A defaulted move constructor that is defined as deleted is ignored by 5974 // overload resolution. 5975 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5976 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5977 Constructor->isMoveConstructor()) 5978 return; 5979 5980 // Overload resolution is always an unevaluated context. 5981 EnterExpressionEvaluationContext Unevaluated( 5982 *this, Sema::ExpressionEvaluationContext::Unevaluated); 5983 5984 // Add this candidate 5985 OverloadCandidate &Candidate = 5986 CandidateSet.addCandidate(Args.size(), EarlyConversions); 5987 Candidate.FoundDecl = FoundDecl; 5988 Candidate.Function = Function; 5989 Candidate.Viable = true; 5990 Candidate.IsSurrogate = false; 5991 Candidate.IgnoreObjectArgument = false; 5992 Candidate.ExplicitCallArguments = Args.size(); 5993 5994 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 5995 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 5996 Candidate.Viable = false; 5997 Candidate.FailureKind = ovl_non_default_multiversion_function; 5998 return; 5999 } 6000 6001 if (Constructor) { 6002 // C++ [class.copy]p3: 6003 // A member function template is never instantiated to perform the copy 6004 // of a class object to an object of its class type. 6005 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6006 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6007 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6008 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6009 ClassType))) { 6010 Candidate.Viable = false; 6011 Candidate.FailureKind = ovl_fail_illegal_constructor; 6012 return; 6013 } 6014 6015 // C++ [over.match.funcs]p8: (proposed DR resolution) 6016 // A constructor inherited from class type C that has a first parameter 6017 // of type "reference to P" (including such a constructor instantiated 6018 // from a template) is excluded from the set of candidate functions when 6019 // constructing an object of type cv D if the argument list has exactly 6020 // one argument and D is reference-related to P and P is reference-related 6021 // to C. 6022 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6023 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6024 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6025 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6026 QualType C = Context.getRecordType(Constructor->getParent()); 6027 QualType D = Context.getRecordType(Shadow->getParent()); 6028 SourceLocation Loc = Args.front()->getExprLoc(); 6029 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6030 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6031 Candidate.Viable = false; 6032 Candidate.FailureKind = ovl_fail_inhctor_slice; 6033 return; 6034 } 6035 } 6036 } 6037 6038 unsigned NumParams = Proto->getNumParams(); 6039 6040 // (C++ 13.3.2p2): A candidate function having fewer than m 6041 // parameters is viable only if it has an ellipsis in its parameter 6042 // list (8.3.5). 6043 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6044 !Proto->isVariadic()) { 6045 Candidate.Viable = false; 6046 Candidate.FailureKind = ovl_fail_too_many_arguments; 6047 return; 6048 } 6049 6050 // (C++ 13.3.2p2): A candidate function having more than m parameters 6051 // is viable only if the (m+1)st parameter has a default argument 6052 // (8.3.6). For the purposes of overload resolution, the 6053 // parameter list is truncated on the right, so that there are 6054 // exactly m parameters. 6055 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6056 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6057 // Not enough arguments. 6058 Candidate.Viable = false; 6059 Candidate.FailureKind = ovl_fail_too_few_arguments; 6060 return; 6061 } 6062 6063 // (CUDA B.1): Check for invalid calls between targets. 6064 if (getLangOpts().CUDA) 6065 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6066 // Skip the check for callers that are implicit members, because in this 6067 // case we may not yet know what the member's target is; the target is 6068 // inferred for the member automatically, based on the bases and fields of 6069 // the class. 6070 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6071 Candidate.Viable = false; 6072 Candidate.FailureKind = ovl_fail_bad_target; 6073 return; 6074 } 6075 6076 // Determine the implicit conversion sequences for each of the 6077 // arguments. 6078 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6079 if (Candidate.Conversions[ArgIdx].isInitialized()) { 6080 // We already formed a conversion sequence for this parameter during 6081 // template argument deduction. 6082 } else if (ArgIdx < NumParams) { 6083 // (C++ 13.3.2p3): for F to be a viable function, there shall 6084 // exist for each argument an implicit conversion sequence 6085 // (13.3.3.1) that converts that argument to the corresponding 6086 // parameter of F. 6087 QualType ParamType = Proto->getParamType(ArgIdx); 6088 Candidate.Conversions[ArgIdx] 6089 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6090 SuppressUserConversions, 6091 /*InOverloadResolution=*/true, 6092 /*AllowObjCWritebackConversion=*/ 6093 getLangOpts().ObjCAutoRefCount, 6094 AllowExplicit); 6095 if (Candidate.Conversions[ArgIdx].isBad()) { 6096 Candidate.Viable = false; 6097 Candidate.FailureKind = ovl_fail_bad_conversion; 6098 return; 6099 } 6100 } else { 6101 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6102 // argument for which there is no corresponding parameter is 6103 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6104 Candidate.Conversions[ArgIdx].setEllipsis(); 6105 } 6106 } 6107 6108 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6109 Candidate.Viable = false; 6110 Candidate.FailureKind = ovl_fail_enable_if; 6111 Candidate.DeductionFailure.Data = FailedAttr; 6112 return; 6113 } 6114 6115 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6116 Candidate.Viable = false; 6117 Candidate.FailureKind = ovl_fail_ext_disabled; 6118 return; 6119 } 6120 } 6121 6122 ObjCMethodDecl * 6123 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6124 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6125 if (Methods.size() <= 1) 6126 return nullptr; 6127 6128 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6129 bool Match = true; 6130 ObjCMethodDecl *Method = Methods[b]; 6131 unsigned NumNamedArgs = Sel.getNumArgs(); 6132 // Method might have more arguments than selector indicates. This is due 6133 // to addition of c-style arguments in method. 6134 if (Method->param_size() > NumNamedArgs) 6135 NumNamedArgs = Method->param_size(); 6136 if (Args.size() < NumNamedArgs) 6137 continue; 6138 6139 for (unsigned i = 0; i < NumNamedArgs; i++) { 6140 // We can't do any type-checking on a type-dependent argument. 6141 if (Args[i]->isTypeDependent()) { 6142 Match = false; 6143 break; 6144 } 6145 6146 ParmVarDecl *param = Method->parameters()[i]; 6147 Expr *argExpr = Args[i]; 6148 assert(argExpr && "SelectBestMethod(): missing expression"); 6149 6150 // Strip the unbridged-cast placeholder expression off unless it's 6151 // a consumed argument. 6152 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6153 !param->hasAttr<CFConsumedAttr>()) 6154 argExpr = stripARCUnbridgedCast(argExpr); 6155 6156 // If the parameter is __unknown_anytype, move on to the next method. 6157 if (param->getType() == Context.UnknownAnyTy) { 6158 Match = false; 6159 break; 6160 } 6161 6162 ImplicitConversionSequence ConversionState 6163 = TryCopyInitialization(*this, argExpr, param->getType(), 6164 /*SuppressUserConversions*/false, 6165 /*InOverloadResolution=*/true, 6166 /*AllowObjCWritebackConversion=*/ 6167 getLangOpts().ObjCAutoRefCount, 6168 /*AllowExplicit*/false); 6169 // This function looks for a reasonably-exact match, so we consider 6170 // incompatible pointer conversions to be a failure here. 6171 if (ConversionState.isBad() || 6172 (ConversionState.isStandard() && 6173 ConversionState.Standard.Second == 6174 ICK_Incompatible_Pointer_Conversion)) { 6175 Match = false; 6176 break; 6177 } 6178 } 6179 // Promote additional arguments to variadic methods. 6180 if (Match && Method->isVariadic()) { 6181 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6182 if (Args[i]->isTypeDependent()) { 6183 Match = false; 6184 break; 6185 } 6186 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6187 nullptr); 6188 if (Arg.isInvalid()) { 6189 Match = false; 6190 break; 6191 } 6192 } 6193 } else { 6194 // Check for extra arguments to non-variadic methods. 6195 if (Args.size() != NumNamedArgs) 6196 Match = false; 6197 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6198 // Special case when selectors have no argument. In this case, select 6199 // one with the most general result type of 'id'. 6200 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6201 QualType ReturnT = Methods[b]->getReturnType(); 6202 if (ReturnT->isObjCIdType()) 6203 return Methods[b]; 6204 } 6205 } 6206 } 6207 6208 if (Match) 6209 return Method; 6210 } 6211 return nullptr; 6212 } 6213 6214 static bool 6215 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6216 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6217 bool MissingImplicitThis, Expr *&ConvertedThis, 6218 SmallVectorImpl<Expr *> &ConvertedArgs) { 6219 if (ThisArg) { 6220 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6221 assert(!isa<CXXConstructorDecl>(Method) && 6222 "Shouldn't have `this` for ctors!"); 6223 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6224 ExprResult R = S.PerformObjectArgumentInitialization( 6225 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6226 if (R.isInvalid()) 6227 return false; 6228 ConvertedThis = R.get(); 6229 } else { 6230 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6231 (void)MD; 6232 assert((MissingImplicitThis || MD->isStatic() || 6233 isa<CXXConstructorDecl>(MD)) && 6234 "Expected `this` for non-ctor instance methods"); 6235 } 6236 ConvertedThis = nullptr; 6237 } 6238 6239 // Ignore any variadic arguments. Converting them is pointless, since the 6240 // user can't refer to them in the function condition. 6241 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6242 6243 // Convert the arguments. 6244 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6245 ExprResult R; 6246 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6247 S.Context, Function->getParamDecl(I)), 6248 SourceLocation(), Args[I]); 6249 6250 if (R.isInvalid()) 6251 return false; 6252 6253 ConvertedArgs.push_back(R.get()); 6254 } 6255 6256 if (Trap.hasErrorOccurred()) 6257 return false; 6258 6259 // Push default arguments if needed. 6260 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6261 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6262 ParmVarDecl *P = Function->getParamDecl(i); 6263 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6264 ? P->getUninstantiatedDefaultArg() 6265 : P->getDefaultArg(); 6266 // This can only happen in code completion, i.e. when PartialOverloading 6267 // is true. 6268 if (!DefArg) 6269 return false; 6270 ExprResult R = 6271 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6272 S.Context, Function->getParamDecl(i)), 6273 SourceLocation(), DefArg); 6274 if (R.isInvalid()) 6275 return false; 6276 ConvertedArgs.push_back(R.get()); 6277 } 6278 6279 if (Trap.hasErrorOccurred()) 6280 return false; 6281 } 6282 return true; 6283 } 6284 6285 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6286 bool MissingImplicitThis) { 6287 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6288 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6289 return nullptr; 6290 6291 SFINAETrap Trap(*this); 6292 SmallVector<Expr *, 16> ConvertedArgs; 6293 // FIXME: We should look into making enable_if late-parsed. 6294 Expr *DiscardedThis; 6295 if (!convertArgsForAvailabilityChecks( 6296 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6297 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6298 return *EnableIfAttrs.begin(); 6299 6300 for (auto *EIA : EnableIfAttrs) { 6301 APValue Result; 6302 // FIXME: This doesn't consider value-dependent cases, because doing so is 6303 // very difficult. Ideally, we should handle them more gracefully. 6304 if (!EIA->getCond()->EvaluateWithSubstitution( 6305 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6306 return EIA; 6307 6308 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6309 return EIA; 6310 } 6311 return nullptr; 6312 } 6313 6314 template <typename CheckFn> 6315 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6316 bool ArgDependent, SourceLocation Loc, 6317 CheckFn &&IsSuccessful) { 6318 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6319 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6320 if (ArgDependent == DIA->getArgDependent()) 6321 Attrs.push_back(DIA); 6322 } 6323 6324 // Common case: No diagnose_if attributes, so we can quit early. 6325 if (Attrs.empty()) 6326 return false; 6327 6328 auto WarningBegin = std::stable_partition( 6329 Attrs.begin(), Attrs.end(), 6330 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6331 6332 // Note that diagnose_if attributes are late-parsed, so they appear in the 6333 // correct order (unlike enable_if attributes). 6334 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6335 IsSuccessful); 6336 if (ErrAttr != WarningBegin) { 6337 const DiagnoseIfAttr *DIA = *ErrAttr; 6338 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6339 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6340 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6341 return true; 6342 } 6343 6344 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6345 if (IsSuccessful(DIA)) { 6346 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6347 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6348 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6349 } 6350 6351 return false; 6352 } 6353 6354 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6355 const Expr *ThisArg, 6356 ArrayRef<const Expr *> Args, 6357 SourceLocation Loc) { 6358 return diagnoseDiagnoseIfAttrsWith( 6359 *this, Function, /*ArgDependent=*/true, Loc, 6360 [&](const DiagnoseIfAttr *DIA) { 6361 APValue Result; 6362 // It's sane to use the same Args for any redecl of this function, since 6363 // EvaluateWithSubstitution only cares about the position of each 6364 // argument in the arg list, not the ParmVarDecl* it maps to. 6365 if (!DIA->getCond()->EvaluateWithSubstitution( 6366 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6367 return false; 6368 return Result.isInt() && Result.getInt().getBoolValue(); 6369 }); 6370 } 6371 6372 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6373 SourceLocation Loc) { 6374 return diagnoseDiagnoseIfAttrsWith( 6375 *this, ND, /*ArgDependent=*/false, Loc, 6376 [&](const DiagnoseIfAttr *DIA) { 6377 bool Result; 6378 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6379 Result; 6380 }); 6381 } 6382 6383 /// Add all of the function declarations in the given function set to 6384 /// the overload candidate set. 6385 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6386 ArrayRef<Expr *> Args, 6387 OverloadCandidateSet &CandidateSet, 6388 TemplateArgumentListInfo *ExplicitTemplateArgs, 6389 bool SuppressUserConversions, 6390 bool PartialOverloading, 6391 bool FirstArgumentIsBase) { 6392 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6393 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6394 ArrayRef<Expr *> FunctionArgs = Args; 6395 6396 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6397 FunctionDecl *FD = 6398 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6399 6400 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6401 QualType ObjectType; 6402 Expr::Classification ObjectClassification; 6403 if (Args.size() > 0) { 6404 if (Expr *E = Args[0]) { 6405 // Use the explicit base to restrict the lookup: 6406 ObjectType = E->getType(); 6407 ObjectClassification = E->Classify(Context); 6408 } // .. else there is an implicit base. 6409 FunctionArgs = Args.slice(1); 6410 } 6411 if (FunTmpl) { 6412 AddMethodTemplateCandidate( 6413 FunTmpl, F.getPair(), 6414 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6415 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6416 FunctionArgs, CandidateSet, SuppressUserConversions, 6417 PartialOverloading); 6418 } else { 6419 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6420 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6421 ObjectClassification, FunctionArgs, CandidateSet, 6422 SuppressUserConversions, PartialOverloading); 6423 } 6424 } else { 6425 // This branch handles both standalone functions and static methods. 6426 6427 // Slice the first argument (which is the base) when we access 6428 // static method as non-static. 6429 if (Args.size() > 0 && 6430 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6431 !isa<CXXConstructorDecl>(FD)))) { 6432 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6433 FunctionArgs = Args.slice(1); 6434 } 6435 if (FunTmpl) { 6436 AddTemplateOverloadCandidate( 6437 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs, 6438 CandidateSet, SuppressUserConversions, PartialOverloading); 6439 } else { 6440 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6441 SuppressUserConversions, PartialOverloading); 6442 } 6443 } 6444 } 6445 } 6446 6447 /// AddMethodCandidate - Adds a named decl (which is some kind of 6448 /// method) as a method candidate to the given overload set. 6449 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6450 QualType ObjectType, 6451 Expr::Classification ObjectClassification, 6452 ArrayRef<Expr *> Args, 6453 OverloadCandidateSet& CandidateSet, 6454 bool SuppressUserConversions) { 6455 NamedDecl *Decl = FoundDecl.getDecl(); 6456 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6457 6458 if (isa<UsingShadowDecl>(Decl)) 6459 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6460 6461 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6462 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6463 "Expected a member function template"); 6464 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6465 /*ExplicitArgs*/ nullptr, ObjectType, 6466 ObjectClassification, Args, CandidateSet, 6467 SuppressUserConversions); 6468 } else { 6469 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6470 ObjectType, ObjectClassification, Args, CandidateSet, 6471 SuppressUserConversions); 6472 } 6473 } 6474 6475 /// AddMethodCandidate - Adds the given C++ member function to the set 6476 /// of candidate functions, using the given function call arguments 6477 /// and the object argument (@c Object). For example, in a call 6478 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6479 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6480 /// allow user-defined conversions via constructors or conversion 6481 /// operators. 6482 void 6483 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6484 CXXRecordDecl *ActingContext, QualType ObjectType, 6485 Expr::Classification ObjectClassification, 6486 ArrayRef<Expr *> Args, 6487 OverloadCandidateSet &CandidateSet, 6488 bool SuppressUserConversions, 6489 bool PartialOverloading, 6490 ConversionSequenceList EarlyConversions) { 6491 const FunctionProtoType *Proto 6492 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6493 assert(Proto && "Methods without a prototype cannot be overloaded"); 6494 assert(!isa<CXXConstructorDecl>(Method) && 6495 "Use AddOverloadCandidate for constructors"); 6496 6497 if (!CandidateSet.isNewCandidate(Method)) 6498 return; 6499 6500 // C++11 [class.copy]p23: [DR1402] 6501 // A defaulted move assignment operator that is defined as deleted is 6502 // ignored by overload resolution. 6503 if (Method->isDefaulted() && Method->isDeleted() && 6504 Method->isMoveAssignmentOperator()) 6505 return; 6506 6507 // Overload resolution is always an unevaluated context. 6508 EnterExpressionEvaluationContext Unevaluated( 6509 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6510 6511 // Add this candidate 6512 OverloadCandidate &Candidate = 6513 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6514 Candidate.FoundDecl = FoundDecl; 6515 Candidate.Function = Method; 6516 Candidate.IsSurrogate = false; 6517 Candidate.IgnoreObjectArgument = false; 6518 Candidate.ExplicitCallArguments = Args.size(); 6519 6520 unsigned NumParams = Proto->getNumParams(); 6521 6522 // (C++ 13.3.2p2): A candidate function having fewer than m 6523 // parameters is viable only if it has an ellipsis in its parameter 6524 // list (8.3.5). 6525 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6526 !Proto->isVariadic()) { 6527 Candidate.Viable = false; 6528 Candidate.FailureKind = ovl_fail_too_many_arguments; 6529 return; 6530 } 6531 6532 // (C++ 13.3.2p2): A candidate function having more than m parameters 6533 // is viable only if the (m+1)st parameter has a default argument 6534 // (8.3.6). For the purposes of overload resolution, the 6535 // parameter list is truncated on the right, so that there are 6536 // exactly m parameters. 6537 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6538 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6539 // Not enough arguments. 6540 Candidate.Viable = false; 6541 Candidate.FailureKind = ovl_fail_too_few_arguments; 6542 return; 6543 } 6544 6545 Candidate.Viable = true; 6546 6547 if (Method->isStatic() || ObjectType.isNull()) 6548 // The implicit object argument is ignored. 6549 Candidate.IgnoreObjectArgument = true; 6550 else { 6551 // Determine the implicit conversion sequence for the object 6552 // parameter. 6553 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6554 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6555 Method, ActingContext); 6556 if (Candidate.Conversions[0].isBad()) { 6557 Candidate.Viable = false; 6558 Candidate.FailureKind = ovl_fail_bad_conversion; 6559 return; 6560 } 6561 } 6562 6563 // (CUDA B.1): Check for invalid calls between targets. 6564 if (getLangOpts().CUDA) 6565 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6566 if (!IsAllowedCUDACall(Caller, Method)) { 6567 Candidate.Viable = false; 6568 Candidate.FailureKind = ovl_fail_bad_target; 6569 return; 6570 } 6571 6572 // Determine the implicit conversion sequences for each of the 6573 // arguments. 6574 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6575 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6576 // We already formed a conversion sequence for this parameter during 6577 // template argument deduction. 6578 } else if (ArgIdx < NumParams) { 6579 // (C++ 13.3.2p3): for F to be a viable function, there shall 6580 // exist for each argument an implicit conversion sequence 6581 // (13.3.3.1) that converts that argument to the corresponding 6582 // parameter of F. 6583 QualType ParamType = Proto->getParamType(ArgIdx); 6584 Candidate.Conversions[ArgIdx + 1] 6585 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6586 SuppressUserConversions, 6587 /*InOverloadResolution=*/true, 6588 /*AllowObjCWritebackConversion=*/ 6589 getLangOpts().ObjCAutoRefCount); 6590 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6591 Candidate.Viable = false; 6592 Candidate.FailureKind = ovl_fail_bad_conversion; 6593 return; 6594 } 6595 } else { 6596 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6597 // argument for which there is no corresponding parameter is 6598 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6599 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6600 } 6601 } 6602 6603 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6604 Candidate.Viable = false; 6605 Candidate.FailureKind = ovl_fail_enable_if; 6606 Candidate.DeductionFailure.Data = FailedAttr; 6607 return; 6608 } 6609 6610 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6611 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6612 Candidate.Viable = false; 6613 Candidate.FailureKind = ovl_non_default_multiversion_function; 6614 } 6615 } 6616 6617 /// Add a C++ member function template as a candidate to the candidate 6618 /// set, using template argument deduction to produce an appropriate member 6619 /// function template specialization. 6620 void 6621 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6622 DeclAccessPair FoundDecl, 6623 CXXRecordDecl *ActingContext, 6624 TemplateArgumentListInfo *ExplicitTemplateArgs, 6625 QualType ObjectType, 6626 Expr::Classification ObjectClassification, 6627 ArrayRef<Expr *> Args, 6628 OverloadCandidateSet& CandidateSet, 6629 bool SuppressUserConversions, 6630 bool PartialOverloading) { 6631 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6632 return; 6633 6634 // C++ [over.match.funcs]p7: 6635 // In each case where a candidate is a function template, candidate 6636 // function template specializations are generated using template argument 6637 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6638 // candidate functions in the usual way.113) A given name can refer to one 6639 // or more function templates and also to a set of overloaded non-template 6640 // functions. In such a case, the candidate functions generated from each 6641 // function template are combined with the set of non-template candidate 6642 // functions. 6643 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6644 FunctionDecl *Specialization = nullptr; 6645 ConversionSequenceList Conversions; 6646 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6647 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6648 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6649 return CheckNonDependentConversions( 6650 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6651 SuppressUserConversions, ActingContext, ObjectType, 6652 ObjectClassification); 6653 })) { 6654 OverloadCandidate &Candidate = 6655 CandidateSet.addCandidate(Conversions.size(), Conversions); 6656 Candidate.FoundDecl = FoundDecl; 6657 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6658 Candidate.Viable = false; 6659 Candidate.IsSurrogate = false; 6660 Candidate.IgnoreObjectArgument = 6661 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6662 ObjectType.isNull(); 6663 Candidate.ExplicitCallArguments = Args.size(); 6664 if (Result == TDK_NonDependentConversionFailure) 6665 Candidate.FailureKind = ovl_fail_bad_conversion; 6666 else { 6667 Candidate.FailureKind = ovl_fail_bad_deduction; 6668 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6669 Info); 6670 } 6671 return; 6672 } 6673 6674 // Add the function template specialization produced by template argument 6675 // deduction as a candidate. 6676 assert(Specialization && "Missing member function template specialization?"); 6677 assert(isa<CXXMethodDecl>(Specialization) && 6678 "Specialization is not a member function?"); 6679 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6680 ActingContext, ObjectType, ObjectClassification, Args, 6681 CandidateSet, SuppressUserConversions, PartialOverloading, 6682 Conversions); 6683 } 6684 6685 /// Add a C++ function template specialization as a candidate 6686 /// in the candidate set, using template argument deduction to produce 6687 /// an appropriate function template specialization. 6688 void 6689 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6690 DeclAccessPair FoundDecl, 6691 TemplateArgumentListInfo *ExplicitTemplateArgs, 6692 ArrayRef<Expr *> Args, 6693 OverloadCandidateSet& CandidateSet, 6694 bool SuppressUserConversions, 6695 bool PartialOverloading) { 6696 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6697 return; 6698 6699 // C++ [over.match.funcs]p7: 6700 // In each case where a candidate is a function template, candidate 6701 // function template specializations are generated using template argument 6702 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6703 // candidate functions in the usual way.113) A given name can refer to one 6704 // or more function templates and also to a set of overloaded non-template 6705 // functions. In such a case, the candidate functions generated from each 6706 // function template are combined with the set of non-template candidate 6707 // functions. 6708 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6709 FunctionDecl *Specialization = nullptr; 6710 ConversionSequenceList Conversions; 6711 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6712 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6713 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6714 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6715 Args, CandidateSet, Conversions, 6716 SuppressUserConversions); 6717 })) { 6718 OverloadCandidate &Candidate = 6719 CandidateSet.addCandidate(Conversions.size(), Conversions); 6720 Candidate.FoundDecl = FoundDecl; 6721 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6722 Candidate.Viable = false; 6723 Candidate.IsSurrogate = false; 6724 // Ignore the object argument if there is one, since we don't have an object 6725 // type. 6726 Candidate.IgnoreObjectArgument = 6727 isa<CXXMethodDecl>(Candidate.Function) && 6728 !isa<CXXConstructorDecl>(Candidate.Function); 6729 Candidate.ExplicitCallArguments = Args.size(); 6730 if (Result == TDK_NonDependentConversionFailure) 6731 Candidate.FailureKind = ovl_fail_bad_conversion; 6732 else { 6733 Candidate.FailureKind = ovl_fail_bad_deduction; 6734 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6735 Info); 6736 } 6737 return; 6738 } 6739 6740 // Add the function template specialization produced by template argument 6741 // deduction as a candidate. 6742 assert(Specialization && "Missing function template specialization?"); 6743 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6744 SuppressUserConversions, PartialOverloading, 6745 /*AllowExplicit*/false, Conversions); 6746 } 6747 6748 /// Check that implicit conversion sequences can be formed for each argument 6749 /// whose corresponding parameter has a non-dependent type, per DR1391's 6750 /// [temp.deduct.call]p10. 6751 bool Sema::CheckNonDependentConversions( 6752 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6753 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6754 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6755 CXXRecordDecl *ActingContext, QualType ObjectType, 6756 Expr::Classification ObjectClassification) { 6757 // FIXME: The cases in which we allow explicit conversions for constructor 6758 // arguments never consider calling a constructor template. It's not clear 6759 // that is correct. 6760 const bool AllowExplicit = false; 6761 6762 auto *FD = FunctionTemplate->getTemplatedDecl(); 6763 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6764 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6765 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6766 6767 Conversions = 6768 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6769 6770 // Overload resolution is always an unevaluated context. 6771 EnterExpressionEvaluationContext Unevaluated( 6772 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6773 6774 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6775 // require that, but this check should never result in a hard error, and 6776 // overload resolution is permitted to sidestep instantiations. 6777 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6778 !ObjectType.isNull()) { 6779 Conversions[0] = TryObjectArgumentInitialization( 6780 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6781 Method, ActingContext); 6782 if (Conversions[0].isBad()) 6783 return true; 6784 } 6785 6786 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6787 ++I) { 6788 QualType ParamType = ParamTypes[I]; 6789 if (!ParamType->isDependentType()) { 6790 Conversions[ThisConversions + I] 6791 = TryCopyInitialization(*this, Args[I], ParamType, 6792 SuppressUserConversions, 6793 /*InOverloadResolution=*/true, 6794 /*AllowObjCWritebackConversion=*/ 6795 getLangOpts().ObjCAutoRefCount, 6796 AllowExplicit); 6797 if (Conversions[ThisConversions + I].isBad()) 6798 return true; 6799 } 6800 } 6801 6802 return false; 6803 } 6804 6805 /// Determine whether this is an allowable conversion from the result 6806 /// of an explicit conversion operator to the expected type, per C++ 6807 /// [over.match.conv]p1 and [over.match.ref]p1. 6808 /// 6809 /// \param ConvType The return type of the conversion function. 6810 /// 6811 /// \param ToType The type we are converting to. 6812 /// 6813 /// \param AllowObjCPointerConversion Allow a conversion from one 6814 /// Objective-C pointer to another. 6815 /// 6816 /// \returns true if the conversion is allowable, false otherwise. 6817 static bool isAllowableExplicitConversion(Sema &S, 6818 QualType ConvType, QualType ToType, 6819 bool AllowObjCPointerConversion) { 6820 QualType ToNonRefType = ToType.getNonReferenceType(); 6821 6822 // Easy case: the types are the same. 6823 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6824 return true; 6825 6826 // Allow qualification conversions. 6827 bool ObjCLifetimeConversion; 6828 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6829 ObjCLifetimeConversion)) 6830 return true; 6831 6832 // If we're not allowed to consider Objective-C pointer conversions, 6833 // we're done. 6834 if (!AllowObjCPointerConversion) 6835 return false; 6836 6837 // Is this an Objective-C pointer conversion? 6838 bool IncompatibleObjC = false; 6839 QualType ConvertedType; 6840 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6841 IncompatibleObjC); 6842 } 6843 6844 /// AddConversionCandidate - Add a C++ conversion function as a 6845 /// candidate in the candidate set (C++ [over.match.conv], 6846 /// C++ [over.match.copy]). From is the expression we're converting from, 6847 /// and ToType is the type that we're eventually trying to convert to 6848 /// (which may or may not be the same type as the type that the 6849 /// conversion function produces). 6850 void 6851 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6852 DeclAccessPair FoundDecl, 6853 CXXRecordDecl *ActingContext, 6854 Expr *From, QualType ToType, 6855 OverloadCandidateSet& CandidateSet, 6856 bool AllowObjCConversionOnExplicit, 6857 bool AllowResultConversion) { 6858 assert(!Conversion->getDescribedFunctionTemplate() && 6859 "Conversion function templates use AddTemplateConversionCandidate"); 6860 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6861 if (!CandidateSet.isNewCandidate(Conversion)) 6862 return; 6863 6864 // If the conversion function has an undeduced return type, trigger its 6865 // deduction now. 6866 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6867 if (DeduceReturnType(Conversion, From->getExprLoc())) 6868 return; 6869 ConvType = Conversion->getConversionType().getNonReferenceType(); 6870 } 6871 6872 // If we don't allow any conversion of the result type, ignore conversion 6873 // functions that don't convert to exactly (possibly cv-qualified) T. 6874 if (!AllowResultConversion && 6875 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 6876 return; 6877 6878 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6879 // operator is only a candidate if its return type is the target type or 6880 // can be converted to the target type with a qualification conversion. 6881 if (Conversion->isExplicit() && 6882 !isAllowableExplicitConversion(*this, ConvType, ToType, 6883 AllowObjCConversionOnExplicit)) 6884 return; 6885 6886 // Overload resolution is always an unevaluated context. 6887 EnterExpressionEvaluationContext Unevaluated( 6888 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6889 6890 // Add this candidate 6891 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6892 Candidate.FoundDecl = FoundDecl; 6893 Candidate.Function = Conversion; 6894 Candidate.IsSurrogate = false; 6895 Candidate.IgnoreObjectArgument = false; 6896 Candidate.FinalConversion.setAsIdentityConversion(); 6897 Candidate.FinalConversion.setFromType(ConvType); 6898 Candidate.FinalConversion.setAllToTypes(ToType); 6899 Candidate.Viable = true; 6900 Candidate.ExplicitCallArguments = 1; 6901 6902 // C++ [over.match.funcs]p4: 6903 // For conversion functions, the function is considered to be a member of 6904 // the class of the implicit implied object argument for the purpose of 6905 // defining the type of the implicit object parameter. 6906 // 6907 // Determine the implicit conversion sequence for the implicit 6908 // object parameter. 6909 QualType ImplicitParamType = From->getType(); 6910 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6911 ImplicitParamType = FromPtrType->getPointeeType(); 6912 CXXRecordDecl *ConversionContext 6913 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6914 6915 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6916 *this, CandidateSet.getLocation(), From->getType(), 6917 From->Classify(Context), Conversion, ConversionContext); 6918 6919 if (Candidate.Conversions[0].isBad()) { 6920 Candidate.Viable = false; 6921 Candidate.FailureKind = ovl_fail_bad_conversion; 6922 return; 6923 } 6924 6925 // We won't go through a user-defined type conversion function to convert a 6926 // derived to base as such conversions are given Conversion Rank. They only 6927 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6928 QualType FromCanon 6929 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6930 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6931 if (FromCanon == ToCanon || 6932 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6933 Candidate.Viable = false; 6934 Candidate.FailureKind = ovl_fail_trivial_conversion; 6935 return; 6936 } 6937 6938 // To determine what the conversion from the result of calling the 6939 // conversion function to the type we're eventually trying to 6940 // convert to (ToType), we need to synthesize a call to the 6941 // conversion function and attempt copy initialization from it. This 6942 // makes sure that we get the right semantics with respect to 6943 // lvalues/rvalues and the type. Fortunately, we can allocate this 6944 // call on the stack and we don't need its arguments to be 6945 // well-formed. 6946 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), VK_LValue, 6947 From->getBeginLoc()); 6948 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6949 Context.getPointerType(Conversion->getType()), 6950 CK_FunctionToPointerDecay, 6951 &ConversionRef, VK_RValue); 6952 6953 QualType ConversionType = Conversion->getConversionType(); 6954 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 6955 Candidate.Viable = false; 6956 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6957 return; 6958 } 6959 6960 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6961 6962 // Note that it is safe to allocate CallExpr on the stack here because 6963 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6964 // allocator). 6965 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6966 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6967 From->getBeginLoc()); 6968 ImplicitConversionSequence ICS = 6969 TryCopyInitialization(*this, &Call, ToType, 6970 /*SuppressUserConversions=*/true, 6971 /*InOverloadResolution=*/false, 6972 /*AllowObjCWritebackConversion=*/false); 6973 6974 switch (ICS.getKind()) { 6975 case ImplicitConversionSequence::StandardConversion: 6976 Candidate.FinalConversion = ICS.Standard; 6977 6978 // C++ [over.ics.user]p3: 6979 // If the user-defined conversion is specified by a specialization of a 6980 // conversion function template, the second standard conversion sequence 6981 // shall have exact match rank. 6982 if (Conversion->getPrimaryTemplate() && 6983 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6984 Candidate.Viable = false; 6985 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6986 return; 6987 } 6988 6989 // C++0x [dcl.init.ref]p5: 6990 // In the second case, if the reference is an rvalue reference and 6991 // the second standard conversion sequence of the user-defined 6992 // conversion sequence includes an lvalue-to-rvalue conversion, the 6993 // program is ill-formed. 6994 if (ToType->isRValueReferenceType() && 6995 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6996 Candidate.Viable = false; 6997 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6998 return; 6999 } 7000 break; 7001 7002 case ImplicitConversionSequence::BadConversion: 7003 Candidate.Viable = false; 7004 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7005 return; 7006 7007 default: 7008 llvm_unreachable( 7009 "Can only end up with a standard conversion sequence or failure"); 7010 } 7011 7012 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7013 Candidate.Viable = false; 7014 Candidate.FailureKind = ovl_fail_enable_if; 7015 Candidate.DeductionFailure.Data = FailedAttr; 7016 return; 7017 } 7018 7019 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7020 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7021 Candidate.Viable = false; 7022 Candidate.FailureKind = ovl_non_default_multiversion_function; 7023 } 7024 } 7025 7026 /// Adds a conversion function template specialization 7027 /// candidate to the overload set, using template argument deduction 7028 /// to deduce the template arguments of the conversion function 7029 /// template from the type that we are converting to (C++ 7030 /// [temp.deduct.conv]). 7031 void 7032 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 7033 DeclAccessPair FoundDecl, 7034 CXXRecordDecl *ActingDC, 7035 Expr *From, QualType ToType, 7036 OverloadCandidateSet &CandidateSet, 7037 bool AllowObjCConversionOnExplicit, 7038 bool AllowResultConversion) { 7039 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7040 "Only conversion function templates permitted here"); 7041 7042 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7043 return; 7044 7045 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7046 CXXConversionDecl *Specialization = nullptr; 7047 if (TemplateDeductionResult Result 7048 = DeduceTemplateArguments(FunctionTemplate, ToType, 7049 Specialization, Info)) { 7050 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7051 Candidate.FoundDecl = FoundDecl; 7052 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7053 Candidate.Viable = false; 7054 Candidate.FailureKind = ovl_fail_bad_deduction; 7055 Candidate.IsSurrogate = false; 7056 Candidate.IgnoreObjectArgument = false; 7057 Candidate.ExplicitCallArguments = 1; 7058 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7059 Info); 7060 return; 7061 } 7062 7063 // Add the conversion function template specialization produced by 7064 // template argument deduction as a candidate. 7065 assert(Specialization && "Missing function template specialization?"); 7066 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7067 CandidateSet, AllowObjCConversionOnExplicit, 7068 AllowResultConversion); 7069 } 7070 7071 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7072 /// converts the given @c Object to a function pointer via the 7073 /// conversion function @c Conversion, and then attempts to call it 7074 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7075 /// the type of function that we'll eventually be calling. 7076 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7077 DeclAccessPair FoundDecl, 7078 CXXRecordDecl *ActingContext, 7079 const FunctionProtoType *Proto, 7080 Expr *Object, 7081 ArrayRef<Expr *> Args, 7082 OverloadCandidateSet& CandidateSet) { 7083 if (!CandidateSet.isNewCandidate(Conversion)) 7084 return; 7085 7086 // Overload resolution is always an unevaluated context. 7087 EnterExpressionEvaluationContext Unevaluated( 7088 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7089 7090 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7091 Candidate.FoundDecl = FoundDecl; 7092 Candidate.Function = nullptr; 7093 Candidate.Surrogate = Conversion; 7094 Candidate.Viable = true; 7095 Candidate.IsSurrogate = true; 7096 Candidate.IgnoreObjectArgument = false; 7097 Candidate.ExplicitCallArguments = Args.size(); 7098 7099 // Determine the implicit conversion sequence for the implicit 7100 // object parameter. 7101 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7102 *this, CandidateSet.getLocation(), Object->getType(), 7103 Object->Classify(Context), Conversion, ActingContext); 7104 if (ObjectInit.isBad()) { 7105 Candidate.Viable = false; 7106 Candidate.FailureKind = ovl_fail_bad_conversion; 7107 Candidate.Conversions[0] = ObjectInit; 7108 return; 7109 } 7110 7111 // The first conversion is actually a user-defined conversion whose 7112 // first conversion is ObjectInit's standard conversion (which is 7113 // effectively a reference binding). Record it as such. 7114 Candidate.Conversions[0].setUserDefined(); 7115 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7116 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7117 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7118 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7119 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7120 Candidate.Conversions[0].UserDefined.After 7121 = Candidate.Conversions[0].UserDefined.Before; 7122 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7123 7124 // Find the 7125 unsigned NumParams = Proto->getNumParams(); 7126 7127 // (C++ 13.3.2p2): A candidate function having fewer than m 7128 // parameters is viable only if it has an ellipsis in its parameter 7129 // list (8.3.5). 7130 if (Args.size() > NumParams && !Proto->isVariadic()) { 7131 Candidate.Viable = false; 7132 Candidate.FailureKind = ovl_fail_too_many_arguments; 7133 return; 7134 } 7135 7136 // Function types don't have any default arguments, so just check if 7137 // we have enough arguments. 7138 if (Args.size() < NumParams) { 7139 // Not enough arguments. 7140 Candidate.Viable = false; 7141 Candidate.FailureKind = ovl_fail_too_few_arguments; 7142 return; 7143 } 7144 7145 // Determine the implicit conversion sequences for each of the 7146 // arguments. 7147 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7148 if (ArgIdx < NumParams) { 7149 // (C++ 13.3.2p3): for F to be a viable function, there shall 7150 // exist for each argument an implicit conversion sequence 7151 // (13.3.3.1) that converts that argument to the corresponding 7152 // parameter of F. 7153 QualType ParamType = Proto->getParamType(ArgIdx); 7154 Candidate.Conversions[ArgIdx + 1] 7155 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7156 /*SuppressUserConversions=*/false, 7157 /*InOverloadResolution=*/false, 7158 /*AllowObjCWritebackConversion=*/ 7159 getLangOpts().ObjCAutoRefCount); 7160 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7161 Candidate.Viable = false; 7162 Candidate.FailureKind = ovl_fail_bad_conversion; 7163 return; 7164 } 7165 } else { 7166 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7167 // argument for which there is no corresponding parameter is 7168 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7169 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7170 } 7171 } 7172 7173 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7174 Candidate.Viable = false; 7175 Candidate.FailureKind = ovl_fail_enable_if; 7176 Candidate.DeductionFailure.Data = FailedAttr; 7177 return; 7178 } 7179 } 7180 7181 /// Add overload candidates for overloaded operators that are 7182 /// member functions. 7183 /// 7184 /// Add the overloaded operator candidates that are member functions 7185 /// for the operator Op that was used in an operator expression such 7186 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7187 /// CandidateSet will store the added overload candidates. (C++ 7188 /// [over.match.oper]). 7189 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7190 SourceLocation OpLoc, 7191 ArrayRef<Expr *> Args, 7192 OverloadCandidateSet& CandidateSet, 7193 SourceRange OpRange) { 7194 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7195 7196 // C++ [over.match.oper]p3: 7197 // For a unary operator @ with an operand of a type whose 7198 // cv-unqualified version is T1, and for a binary operator @ with 7199 // a left operand of a type whose cv-unqualified version is T1 and 7200 // a right operand of a type whose cv-unqualified version is T2, 7201 // three sets of candidate functions, designated member 7202 // candidates, non-member candidates and built-in candidates, are 7203 // constructed as follows: 7204 QualType T1 = Args[0]->getType(); 7205 7206 // -- If T1 is a complete class type or a class currently being 7207 // defined, the set of member candidates is the result of the 7208 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7209 // the set of member candidates is empty. 7210 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7211 // Complete the type if it can be completed. 7212 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7213 return; 7214 // If the type is neither complete nor being defined, bail out now. 7215 if (!T1Rec->getDecl()->getDefinition()) 7216 return; 7217 7218 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7219 LookupQualifiedName(Operators, T1Rec->getDecl()); 7220 Operators.suppressDiagnostics(); 7221 7222 for (LookupResult::iterator Oper = Operators.begin(), 7223 OperEnd = Operators.end(); 7224 Oper != OperEnd; 7225 ++Oper) 7226 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7227 Args[0]->Classify(Context), Args.slice(1), 7228 CandidateSet, /*SuppressUserConversions=*/false); 7229 } 7230 } 7231 7232 /// AddBuiltinCandidate - Add a candidate for a built-in 7233 /// operator. ResultTy and ParamTys are the result and parameter types 7234 /// of the built-in candidate, respectively. Args and NumArgs are the 7235 /// arguments being passed to the candidate. IsAssignmentOperator 7236 /// should be true when this built-in candidate is an assignment 7237 /// operator. NumContextualBoolArguments is the number of arguments 7238 /// (at the beginning of the argument list) that will be contextually 7239 /// converted to bool. 7240 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7241 OverloadCandidateSet& CandidateSet, 7242 bool IsAssignmentOperator, 7243 unsigned NumContextualBoolArguments) { 7244 // Overload resolution is always an unevaluated context. 7245 EnterExpressionEvaluationContext Unevaluated( 7246 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7247 7248 // Add this candidate 7249 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7250 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7251 Candidate.Function = nullptr; 7252 Candidate.IsSurrogate = false; 7253 Candidate.IgnoreObjectArgument = false; 7254 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7255 7256 // Determine the implicit conversion sequences for each of the 7257 // arguments. 7258 Candidate.Viable = true; 7259 Candidate.ExplicitCallArguments = Args.size(); 7260 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7261 // C++ [over.match.oper]p4: 7262 // For the built-in assignment operators, conversions of the 7263 // left operand are restricted as follows: 7264 // -- no temporaries are introduced to hold the left operand, and 7265 // -- no user-defined conversions are applied to the left 7266 // operand to achieve a type match with the left-most 7267 // parameter of a built-in candidate. 7268 // 7269 // We block these conversions by turning off user-defined 7270 // conversions, since that is the only way that initialization of 7271 // a reference to a non-class type can occur from something that 7272 // is not of the same type. 7273 if (ArgIdx < NumContextualBoolArguments) { 7274 assert(ParamTys[ArgIdx] == Context.BoolTy && 7275 "Contextual conversion to bool requires bool type"); 7276 Candidate.Conversions[ArgIdx] 7277 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7278 } else { 7279 Candidate.Conversions[ArgIdx] 7280 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7281 ArgIdx == 0 && IsAssignmentOperator, 7282 /*InOverloadResolution=*/false, 7283 /*AllowObjCWritebackConversion=*/ 7284 getLangOpts().ObjCAutoRefCount); 7285 } 7286 if (Candidate.Conversions[ArgIdx].isBad()) { 7287 Candidate.Viable = false; 7288 Candidate.FailureKind = ovl_fail_bad_conversion; 7289 break; 7290 } 7291 } 7292 } 7293 7294 namespace { 7295 7296 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7297 /// candidate operator functions for built-in operators (C++ 7298 /// [over.built]). The types are separated into pointer types and 7299 /// enumeration types. 7300 class BuiltinCandidateTypeSet { 7301 /// TypeSet - A set of types. 7302 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7303 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7304 7305 /// PointerTypes - The set of pointer types that will be used in the 7306 /// built-in candidates. 7307 TypeSet PointerTypes; 7308 7309 /// MemberPointerTypes - The set of member pointer types that will be 7310 /// used in the built-in candidates. 7311 TypeSet MemberPointerTypes; 7312 7313 /// EnumerationTypes - The set of enumeration types that will be 7314 /// used in the built-in candidates. 7315 TypeSet EnumerationTypes; 7316 7317 /// The set of vector types that will be used in the built-in 7318 /// candidates. 7319 TypeSet VectorTypes; 7320 7321 /// A flag indicating non-record types are viable candidates 7322 bool HasNonRecordTypes; 7323 7324 /// A flag indicating whether either arithmetic or enumeration types 7325 /// were present in the candidate set. 7326 bool HasArithmeticOrEnumeralTypes; 7327 7328 /// A flag indicating whether the nullptr type was present in the 7329 /// candidate set. 7330 bool HasNullPtrType; 7331 7332 /// Sema - The semantic analysis instance where we are building the 7333 /// candidate type set. 7334 Sema &SemaRef; 7335 7336 /// Context - The AST context in which we will build the type sets. 7337 ASTContext &Context; 7338 7339 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7340 const Qualifiers &VisibleQuals); 7341 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7342 7343 public: 7344 /// iterator - Iterates through the types that are part of the set. 7345 typedef TypeSet::iterator iterator; 7346 7347 BuiltinCandidateTypeSet(Sema &SemaRef) 7348 : HasNonRecordTypes(false), 7349 HasArithmeticOrEnumeralTypes(false), 7350 HasNullPtrType(false), 7351 SemaRef(SemaRef), 7352 Context(SemaRef.Context) { } 7353 7354 void AddTypesConvertedFrom(QualType Ty, 7355 SourceLocation Loc, 7356 bool AllowUserConversions, 7357 bool AllowExplicitConversions, 7358 const Qualifiers &VisibleTypeConversionsQuals); 7359 7360 /// pointer_begin - First pointer type found; 7361 iterator pointer_begin() { return PointerTypes.begin(); } 7362 7363 /// pointer_end - Past the last pointer type found; 7364 iterator pointer_end() { return PointerTypes.end(); } 7365 7366 /// member_pointer_begin - First member pointer type found; 7367 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7368 7369 /// member_pointer_end - Past the last member pointer type found; 7370 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7371 7372 /// enumeration_begin - First enumeration type found; 7373 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7374 7375 /// enumeration_end - Past the last enumeration type found; 7376 iterator enumeration_end() { return EnumerationTypes.end(); } 7377 7378 iterator vector_begin() { return VectorTypes.begin(); } 7379 iterator vector_end() { return VectorTypes.end(); } 7380 7381 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7382 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7383 bool hasNullPtrType() const { return HasNullPtrType; } 7384 }; 7385 7386 } // end anonymous namespace 7387 7388 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7389 /// the set of pointer types along with any more-qualified variants of 7390 /// that type. For example, if @p Ty is "int const *", this routine 7391 /// will add "int const *", "int const volatile *", "int const 7392 /// restrict *", and "int const volatile restrict *" to the set of 7393 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7394 /// false otherwise. 7395 /// 7396 /// FIXME: what to do about extended qualifiers? 7397 bool 7398 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7399 const Qualifiers &VisibleQuals) { 7400 7401 // Insert this type. 7402 if (!PointerTypes.insert(Ty)) 7403 return false; 7404 7405 QualType PointeeTy; 7406 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7407 bool buildObjCPtr = false; 7408 if (!PointerTy) { 7409 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7410 PointeeTy = PTy->getPointeeType(); 7411 buildObjCPtr = true; 7412 } else { 7413 PointeeTy = PointerTy->getPointeeType(); 7414 } 7415 7416 // Don't add qualified variants of arrays. For one, they're not allowed 7417 // (the qualifier would sink to the element type), and for another, the 7418 // only overload situation where it matters is subscript or pointer +- int, 7419 // and those shouldn't have qualifier variants anyway. 7420 if (PointeeTy->isArrayType()) 7421 return true; 7422 7423 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7424 bool hasVolatile = VisibleQuals.hasVolatile(); 7425 bool hasRestrict = VisibleQuals.hasRestrict(); 7426 7427 // Iterate through all strict supersets of BaseCVR. 7428 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7429 if ((CVR | BaseCVR) != CVR) continue; 7430 // Skip over volatile if no volatile found anywhere in the types. 7431 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7432 7433 // Skip over restrict if no restrict found anywhere in the types, or if 7434 // the type cannot be restrict-qualified. 7435 if ((CVR & Qualifiers::Restrict) && 7436 (!hasRestrict || 7437 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7438 continue; 7439 7440 // Build qualified pointee type. 7441 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7442 7443 // Build qualified pointer type. 7444 QualType QPointerTy; 7445 if (!buildObjCPtr) 7446 QPointerTy = Context.getPointerType(QPointeeTy); 7447 else 7448 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7449 7450 // Insert qualified pointer type. 7451 PointerTypes.insert(QPointerTy); 7452 } 7453 7454 return true; 7455 } 7456 7457 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7458 /// to the set of pointer types along with any more-qualified variants of 7459 /// that type. For example, if @p Ty is "int const *", this routine 7460 /// will add "int const *", "int const volatile *", "int const 7461 /// restrict *", and "int const volatile restrict *" to the set of 7462 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7463 /// false otherwise. 7464 /// 7465 /// FIXME: what to do about extended qualifiers? 7466 bool 7467 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7468 QualType Ty) { 7469 // Insert this type. 7470 if (!MemberPointerTypes.insert(Ty)) 7471 return false; 7472 7473 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7474 assert(PointerTy && "type was not a member pointer type!"); 7475 7476 QualType PointeeTy = PointerTy->getPointeeType(); 7477 // Don't add qualified variants of arrays. For one, they're not allowed 7478 // (the qualifier would sink to the element type), and for another, the 7479 // only overload situation where it matters is subscript or pointer +- int, 7480 // and those shouldn't have qualifier variants anyway. 7481 if (PointeeTy->isArrayType()) 7482 return true; 7483 const Type *ClassTy = PointerTy->getClass(); 7484 7485 // Iterate through all strict supersets of the pointee type's CVR 7486 // qualifiers. 7487 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7488 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7489 if ((CVR | BaseCVR) != CVR) continue; 7490 7491 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7492 MemberPointerTypes.insert( 7493 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7494 } 7495 7496 return true; 7497 } 7498 7499 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7500 /// Ty can be implicit converted to the given set of @p Types. We're 7501 /// primarily interested in pointer types and enumeration types. We also 7502 /// take member pointer types, for the conditional operator. 7503 /// AllowUserConversions is true if we should look at the conversion 7504 /// functions of a class type, and AllowExplicitConversions if we 7505 /// should also include the explicit conversion functions of a class 7506 /// type. 7507 void 7508 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7509 SourceLocation Loc, 7510 bool AllowUserConversions, 7511 bool AllowExplicitConversions, 7512 const Qualifiers &VisibleQuals) { 7513 // Only deal with canonical types. 7514 Ty = Context.getCanonicalType(Ty); 7515 7516 // Look through reference types; they aren't part of the type of an 7517 // expression for the purposes of conversions. 7518 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7519 Ty = RefTy->getPointeeType(); 7520 7521 // If we're dealing with an array type, decay to the pointer. 7522 if (Ty->isArrayType()) 7523 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7524 7525 // Otherwise, we don't care about qualifiers on the type. 7526 Ty = Ty.getLocalUnqualifiedType(); 7527 7528 // Flag if we ever add a non-record type. 7529 const RecordType *TyRec = Ty->getAs<RecordType>(); 7530 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7531 7532 // Flag if we encounter an arithmetic type. 7533 HasArithmeticOrEnumeralTypes = 7534 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7535 7536 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7537 PointerTypes.insert(Ty); 7538 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7539 // Insert our type, and its more-qualified variants, into the set 7540 // of types. 7541 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7542 return; 7543 } else if (Ty->isMemberPointerType()) { 7544 // Member pointers are far easier, since the pointee can't be converted. 7545 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7546 return; 7547 } else if (Ty->isEnumeralType()) { 7548 HasArithmeticOrEnumeralTypes = true; 7549 EnumerationTypes.insert(Ty); 7550 } else if (Ty->isVectorType()) { 7551 // We treat vector types as arithmetic types in many contexts as an 7552 // extension. 7553 HasArithmeticOrEnumeralTypes = true; 7554 VectorTypes.insert(Ty); 7555 } else if (Ty->isNullPtrType()) { 7556 HasNullPtrType = true; 7557 } else if (AllowUserConversions && TyRec) { 7558 // No conversion functions in incomplete types. 7559 if (!SemaRef.isCompleteType(Loc, Ty)) 7560 return; 7561 7562 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7563 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7564 if (isa<UsingShadowDecl>(D)) 7565 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7566 7567 // Skip conversion function templates; they don't tell us anything 7568 // about which builtin types we can convert to. 7569 if (isa<FunctionTemplateDecl>(D)) 7570 continue; 7571 7572 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7573 if (AllowExplicitConversions || !Conv->isExplicit()) { 7574 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7575 VisibleQuals); 7576 } 7577 } 7578 } 7579 } 7580 7581 /// Helper function for AddBuiltinOperatorCandidates() that adds 7582 /// the volatile- and non-volatile-qualified assignment operators for the 7583 /// given type to the candidate set. 7584 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7585 QualType T, 7586 ArrayRef<Expr *> Args, 7587 OverloadCandidateSet &CandidateSet) { 7588 QualType ParamTypes[2]; 7589 7590 // T& operator=(T&, T) 7591 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7592 ParamTypes[1] = T; 7593 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7594 /*IsAssignmentOperator=*/true); 7595 7596 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7597 // volatile T& operator=(volatile T&, T) 7598 ParamTypes[0] 7599 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7600 ParamTypes[1] = T; 7601 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7602 /*IsAssignmentOperator=*/true); 7603 } 7604 } 7605 7606 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7607 /// if any, found in visible type conversion functions found in ArgExpr's type. 7608 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7609 Qualifiers VRQuals; 7610 const RecordType *TyRec; 7611 if (const MemberPointerType *RHSMPType = 7612 ArgExpr->getType()->getAs<MemberPointerType>()) 7613 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7614 else 7615 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7616 if (!TyRec) { 7617 // Just to be safe, assume the worst case. 7618 VRQuals.addVolatile(); 7619 VRQuals.addRestrict(); 7620 return VRQuals; 7621 } 7622 7623 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7624 if (!ClassDecl->hasDefinition()) 7625 return VRQuals; 7626 7627 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7628 if (isa<UsingShadowDecl>(D)) 7629 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7630 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7631 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7632 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7633 CanTy = ResTypeRef->getPointeeType(); 7634 // Need to go down the pointer/mempointer chain and add qualifiers 7635 // as see them. 7636 bool done = false; 7637 while (!done) { 7638 if (CanTy.isRestrictQualified()) 7639 VRQuals.addRestrict(); 7640 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7641 CanTy = ResTypePtr->getPointeeType(); 7642 else if (const MemberPointerType *ResTypeMPtr = 7643 CanTy->getAs<MemberPointerType>()) 7644 CanTy = ResTypeMPtr->getPointeeType(); 7645 else 7646 done = true; 7647 if (CanTy.isVolatileQualified()) 7648 VRQuals.addVolatile(); 7649 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7650 return VRQuals; 7651 } 7652 } 7653 } 7654 return VRQuals; 7655 } 7656 7657 namespace { 7658 7659 /// Helper class to manage the addition of builtin operator overload 7660 /// candidates. It provides shared state and utility methods used throughout 7661 /// the process, as well as a helper method to add each group of builtin 7662 /// operator overloads from the standard to a candidate set. 7663 class BuiltinOperatorOverloadBuilder { 7664 // Common instance state available to all overload candidate addition methods. 7665 Sema &S; 7666 ArrayRef<Expr *> Args; 7667 Qualifiers VisibleTypeConversionsQuals; 7668 bool HasArithmeticOrEnumeralCandidateType; 7669 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7670 OverloadCandidateSet &CandidateSet; 7671 7672 static constexpr int ArithmeticTypesCap = 24; 7673 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7674 7675 // Define some indices used to iterate over the arithemetic types in 7676 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7677 // types are that preserved by promotion (C++ [over.built]p2). 7678 unsigned FirstIntegralType, 7679 LastIntegralType; 7680 unsigned FirstPromotedIntegralType, 7681 LastPromotedIntegralType; 7682 unsigned FirstPromotedArithmeticType, 7683 LastPromotedArithmeticType; 7684 unsigned NumArithmeticTypes; 7685 7686 void InitArithmeticTypes() { 7687 // Start of promoted types. 7688 FirstPromotedArithmeticType = 0; 7689 ArithmeticTypes.push_back(S.Context.FloatTy); 7690 ArithmeticTypes.push_back(S.Context.DoubleTy); 7691 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7692 if (S.Context.getTargetInfo().hasFloat128Type()) 7693 ArithmeticTypes.push_back(S.Context.Float128Ty); 7694 7695 // Start of integral types. 7696 FirstIntegralType = ArithmeticTypes.size(); 7697 FirstPromotedIntegralType = ArithmeticTypes.size(); 7698 ArithmeticTypes.push_back(S.Context.IntTy); 7699 ArithmeticTypes.push_back(S.Context.LongTy); 7700 ArithmeticTypes.push_back(S.Context.LongLongTy); 7701 if (S.Context.getTargetInfo().hasInt128Type()) 7702 ArithmeticTypes.push_back(S.Context.Int128Ty); 7703 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7704 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7705 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7706 if (S.Context.getTargetInfo().hasInt128Type()) 7707 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7708 LastPromotedIntegralType = ArithmeticTypes.size(); 7709 LastPromotedArithmeticType = ArithmeticTypes.size(); 7710 // End of promoted types. 7711 7712 ArithmeticTypes.push_back(S.Context.BoolTy); 7713 ArithmeticTypes.push_back(S.Context.CharTy); 7714 ArithmeticTypes.push_back(S.Context.WCharTy); 7715 if (S.Context.getLangOpts().Char8) 7716 ArithmeticTypes.push_back(S.Context.Char8Ty); 7717 ArithmeticTypes.push_back(S.Context.Char16Ty); 7718 ArithmeticTypes.push_back(S.Context.Char32Ty); 7719 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7720 ArithmeticTypes.push_back(S.Context.ShortTy); 7721 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7722 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7723 LastIntegralType = ArithmeticTypes.size(); 7724 NumArithmeticTypes = ArithmeticTypes.size(); 7725 // End of integral types. 7726 // FIXME: What about complex? What about half? 7727 7728 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7729 "Enough inline storage for all arithmetic types."); 7730 } 7731 7732 /// Helper method to factor out the common pattern of adding overloads 7733 /// for '++' and '--' builtin operators. 7734 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7735 bool HasVolatile, 7736 bool HasRestrict) { 7737 QualType ParamTypes[2] = { 7738 S.Context.getLValueReferenceType(CandidateTy), 7739 S.Context.IntTy 7740 }; 7741 7742 // Non-volatile version. 7743 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7744 7745 // Use a heuristic to reduce number of builtin candidates in the set: 7746 // add volatile version only if there are conversions to a volatile type. 7747 if (HasVolatile) { 7748 ParamTypes[0] = 7749 S.Context.getLValueReferenceType( 7750 S.Context.getVolatileType(CandidateTy)); 7751 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7752 } 7753 7754 // Add restrict version only if there are conversions to a restrict type 7755 // and our candidate type is a non-restrict-qualified pointer. 7756 if (HasRestrict && CandidateTy->isAnyPointerType() && 7757 !CandidateTy.isRestrictQualified()) { 7758 ParamTypes[0] 7759 = S.Context.getLValueReferenceType( 7760 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7761 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7762 7763 if (HasVolatile) { 7764 ParamTypes[0] 7765 = S.Context.getLValueReferenceType( 7766 S.Context.getCVRQualifiedType(CandidateTy, 7767 (Qualifiers::Volatile | 7768 Qualifiers::Restrict))); 7769 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7770 } 7771 } 7772 7773 } 7774 7775 public: 7776 BuiltinOperatorOverloadBuilder( 7777 Sema &S, ArrayRef<Expr *> Args, 7778 Qualifiers VisibleTypeConversionsQuals, 7779 bool HasArithmeticOrEnumeralCandidateType, 7780 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7781 OverloadCandidateSet &CandidateSet) 7782 : S(S), Args(Args), 7783 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7784 HasArithmeticOrEnumeralCandidateType( 7785 HasArithmeticOrEnumeralCandidateType), 7786 CandidateTypes(CandidateTypes), 7787 CandidateSet(CandidateSet) { 7788 7789 InitArithmeticTypes(); 7790 } 7791 7792 // Increment is deprecated for bool since C++17. 7793 // 7794 // C++ [over.built]p3: 7795 // 7796 // For every pair (T, VQ), where T is an arithmetic type other 7797 // than bool, and VQ is either volatile or empty, there exist 7798 // candidate operator functions of the form 7799 // 7800 // VQ T& operator++(VQ T&); 7801 // T operator++(VQ T&, int); 7802 // 7803 // C++ [over.built]p4: 7804 // 7805 // For every pair (T, VQ), where T is an arithmetic type other 7806 // than bool, and VQ is either volatile or empty, there exist 7807 // candidate operator functions of the form 7808 // 7809 // VQ T& operator--(VQ T&); 7810 // T operator--(VQ T&, int); 7811 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7812 if (!HasArithmeticOrEnumeralCandidateType) 7813 return; 7814 7815 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 7816 const auto TypeOfT = ArithmeticTypes[Arith]; 7817 if (TypeOfT == S.Context.BoolTy) { 7818 if (Op == OO_MinusMinus) 7819 continue; 7820 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 7821 continue; 7822 } 7823 addPlusPlusMinusMinusStyleOverloads( 7824 TypeOfT, 7825 VisibleTypeConversionsQuals.hasVolatile(), 7826 VisibleTypeConversionsQuals.hasRestrict()); 7827 } 7828 } 7829 7830 // C++ [over.built]p5: 7831 // 7832 // For every pair (T, VQ), where T is a cv-qualified or 7833 // cv-unqualified object type, and VQ is either volatile or 7834 // empty, there exist candidate operator functions of the form 7835 // 7836 // T*VQ& operator++(T*VQ&); 7837 // T*VQ& operator--(T*VQ&); 7838 // T* operator++(T*VQ&, int); 7839 // T* operator--(T*VQ&, int); 7840 void addPlusPlusMinusMinusPointerOverloads() { 7841 for (BuiltinCandidateTypeSet::iterator 7842 Ptr = CandidateTypes[0].pointer_begin(), 7843 PtrEnd = CandidateTypes[0].pointer_end(); 7844 Ptr != PtrEnd; ++Ptr) { 7845 // Skip pointer types that aren't pointers to object types. 7846 if (!(*Ptr)->getPointeeType()->isObjectType()) 7847 continue; 7848 7849 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7850 (!(*Ptr).isVolatileQualified() && 7851 VisibleTypeConversionsQuals.hasVolatile()), 7852 (!(*Ptr).isRestrictQualified() && 7853 VisibleTypeConversionsQuals.hasRestrict())); 7854 } 7855 } 7856 7857 // C++ [over.built]p6: 7858 // For every cv-qualified or cv-unqualified object type T, there 7859 // exist candidate operator functions of the form 7860 // 7861 // T& operator*(T*); 7862 // 7863 // C++ [over.built]p7: 7864 // For every function type T that does not have cv-qualifiers or a 7865 // ref-qualifier, there exist candidate operator functions of the form 7866 // T& operator*(T*); 7867 void addUnaryStarPointerOverloads() { 7868 for (BuiltinCandidateTypeSet::iterator 7869 Ptr = CandidateTypes[0].pointer_begin(), 7870 PtrEnd = CandidateTypes[0].pointer_end(); 7871 Ptr != PtrEnd; ++Ptr) { 7872 QualType ParamTy = *Ptr; 7873 QualType PointeeTy = ParamTy->getPointeeType(); 7874 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7875 continue; 7876 7877 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7878 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7879 continue; 7880 7881 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7882 } 7883 } 7884 7885 // C++ [over.built]p9: 7886 // For every promoted arithmetic type T, there exist candidate 7887 // operator functions of the form 7888 // 7889 // T operator+(T); 7890 // T operator-(T); 7891 void addUnaryPlusOrMinusArithmeticOverloads() { 7892 if (!HasArithmeticOrEnumeralCandidateType) 7893 return; 7894 7895 for (unsigned Arith = FirstPromotedArithmeticType; 7896 Arith < LastPromotedArithmeticType; ++Arith) { 7897 QualType ArithTy = ArithmeticTypes[Arith]; 7898 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 7899 } 7900 7901 // Extension: We also add these operators for vector types. 7902 for (BuiltinCandidateTypeSet::iterator 7903 Vec = CandidateTypes[0].vector_begin(), 7904 VecEnd = CandidateTypes[0].vector_end(); 7905 Vec != VecEnd; ++Vec) { 7906 QualType VecTy = *Vec; 7907 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 7908 } 7909 } 7910 7911 // C++ [over.built]p8: 7912 // For every type T, there exist candidate operator functions of 7913 // the form 7914 // 7915 // T* operator+(T*); 7916 void addUnaryPlusPointerOverloads() { 7917 for (BuiltinCandidateTypeSet::iterator 7918 Ptr = CandidateTypes[0].pointer_begin(), 7919 PtrEnd = CandidateTypes[0].pointer_end(); 7920 Ptr != PtrEnd; ++Ptr) { 7921 QualType ParamTy = *Ptr; 7922 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7923 } 7924 } 7925 7926 // C++ [over.built]p10: 7927 // For every promoted integral type T, there exist candidate 7928 // operator functions of the form 7929 // 7930 // T operator~(T); 7931 void addUnaryTildePromotedIntegralOverloads() { 7932 if (!HasArithmeticOrEnumeralCandidateType) 7933 return; 7934 7935 for (unsigned Int = FirstPromotedIntegralType; 7936 Int < LastPromotedIntegralType; ++Int) { 7937 QualType IntTy = ArithmeticTypes[Int]; 7938 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 7939 } 7940 7941 // Extension: We also add this operator for vector types. 7942 for (BuiltinCandidateTypeSet::iterator 7943 Vec = CandidateTypes[0].vector_begin(), 7944 VecEnd = CandidateTypes[0].vector_end(); 7945 Vec != VecEnd; ++Vec) { 7946 QualType VecTy = *Vec; 7947 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 7948 } 7949 } 7950 7951 // C++ [over.match.oper]p16: 7952 // For every pointer to member type T or type std::nullptr_t, there 7953 // exist candidate operator functions of the form 7954 // 7955 // bool operator==(T,T); 7956 // bool operator!=(T,T); 7957 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 7958 /// Set of (canonical) types that we've already handled. 7959 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7960 7961 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7962 for (BuiltinCandidateTypeSet::iterator 7963 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7964 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7965 MemPtr != MemPtrEnd; 7966 ++MemPtr) { 7967 // Don't add the same builtin candidate twice. 7968 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7969 continue; 7970 7971 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7972 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7973 } 7974 7975 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7976 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7977 if (AddedTypes.insert(NullPtrTy).second) { 7978 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7979 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7980 } 7981 } 7982 } 7983 } 7984 7985 // C++ [over.built]p15: 7986 // 7987 // For every T, where T is an enumeration type or a pointer type, 7988 // there exist candidate operator functions of the form 7989 // 7990 // bool operator<(T, T); 7991 // bool operator>(T, T); 7992 // bool operator<=(T, T); 7993 // bool operator>=(T, T); 7994 // bool operator==(T, T); 7995 // bool operator!=(T, T); 7996 // R operator<=>(T, T) 7997 void addGenericBinaryPointerOrEnumeralOverloads() { 7998 // C++ [over.match.oper]p3: 7999 // [...]the built-in candidates include all of the candidate operator 8000 // functions defined in 13.6 that, compared to the given operator, [...] 8001 // do not have the same parameter-type-list as any non-template non-member 8002 // candidate. 8003 // 8004 // Note that in practice, this only affects enumeration types because there 8005 // aren't any built-in candidates of record type, and a user-defined operator 8006 // must have an operand of record or enumeration type. Also, the only other 8007 // overloaded operator with enumeration arguments, operator=, 8008 // cannot be overloaded for enumeration types, so this is the only place 8009 // where we must suppress candidates like this. 8010 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8011 UserDefinedBinaryOperators; 8012 8013 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8014 if (CandidateTypes[ArgIdx].enumeration_begin() != 8015 CandidateTypes[ArgIdx].enumeration_end()) { 8016 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8017 CEnd = CandidateSet.end(); 8018 C != CEnd; ++C) { 8019 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8020 continue; 8021 8022 if (C->Function->isFunctionTemplateSpecialization()) 8023 continue; 8024 8025 QualType FirstParamType = 8026 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 8027 QualType SecondParamType = 8028 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 8029 8030 // Skip if either parameter isn't of enumeral type. 8031 if (!FirstParamType->isEnumeralType() || 8032 !SecondParamType->isEnumeralType()) 8033 continue; 8034 8035 // Add this operator to the set of known user-defined operators. 8036 UserDefinedBinaryOperators.insert( 8037 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8038 S.Context.getCanonicalType(SecondParamType))); 8039 } 8040 } 8041 } 8042 8043 /// Set of (canonical) types that we've already handled. 8044 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8045 8046 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8047 for (BuiltinCandidateTypeSet::iterator 8048 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8049 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8050 Ptr != PtrEnd; ++Ptr) { 8051 // Don't add the same builtin candidate twice. 8052 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8053 continue; 8054 8055 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8056 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8057 } 8058 for (BuiltinCandidateTypeSet::iterator 8059 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8060 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8061 Enum != EnumEnd; ++Enum) { 8062 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8063 8064 // Don't add the same builtin candidate twice, or if a user defined 8065 // candidate exists. 8066 if (!AddedTypes.insert(CanonType).second || 8067 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8068 CanonType))) 8069 continue; 8070 QualType ParamTypes[2] = { *Enum, *Enum }; 8071 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8072 } 8073 } 8074 } 8075 8076 // C++ [over.built]p13: 8077 // 8078 // For every cv-qualified or cv-unqualified object type T 8079 // there exist candidate operator functions of the form 8080 // 8081 // T* operator+(T*, ptrdiff_t); 8082 // T& operator[](T*, ptrdiff_t); [BELOW] 8083 // T* operator-(T*, ptrdiff_t); 8084 // T* operator+(ptrdiff_t, T*); 8085 // T& operator[](ptrdiff_t, T*); [BELOW] 8086 // 8087 // C++ [over.built]p14: 8088 // 8089 // For every T, where T is a pointer to object type, there 8090 // exist candidate operator functions of the form 8091 // 8092 // ptrdiff_t operator-(T, T); 8093 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8094 /// Set of (canonical) types that we've already handled. 8095 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8096 8097 for (int Arg = 0; Arg < 2; ++Arg) { 8098 QualType AsymmetricParamTypes[2] = { 8099 S.Context.getPointerDiffType(), 8100 S.Context.getPointerDiffType(), 8101 }; 8102 for (BuiltinCandidateTypeSet::iterator 8103 Ptr = CandidateTypes[Arg].pointer_begin(), 8104 PtrEnd = CandidateTypes[Arg].pointer_end(); 8105 Ptr != PtrEnd; ++Ptr) { 8106 QualType PointeeTy = (*Ptr)->getPointeeType(); 8107 if (!PointeeTy->isObjectType()) 8108 continue; 8109 8110 AsymmetricParamTypes[Arg] = *Ptr; 8111 if (Arg == 0 || Op == OO_Plus) { 8112 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8113 // T* operator+(ptrdiff_t, T*); 8114 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8115 } 8116 if (Op == OO_Minus) { 8117 // ptrdiff_t operator-(T, T); 8118 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8119 continue; 8120 8121 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8122 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8123 } 8124 } 8125 } 8126 } 8127 8128 // C++ [over.built]p12: 8129 // 8130 // For every pair of promoted arithmetic types L and R, there 8131 // exist candidate operator functions of the form 8132 // 8133 // LR operator*(L, R); 8134 // LR operator/(L, R); 8135 // LR operator+(L, R); 8136 // LR operator-(L, R); 8137 // bool operator<(L, R); 8138 // bool operator>(L, R); 8139 // bool operator<=(L, R); 8140 // bool operator>=(L, R); 8141 // bool operator==(L, R); 8142 // bool operator!=(L, R); 8143 // 8144 // where LR is the result of the usual arithmetic conversions 8145 // between types L and R. 8146 // 8147 // C++ [over.built]p24: 8148 // 8149 // For every pair of promoted arithmetic types L and R, there exist 8150 // candidate operator functions of the form 8151 // 8152 // LR operator?(bool, L, R); 8153 // 8154 // where LR is the result of the usual arithmetic conversions 8155 // between types L and R. 8156 // Our candidates ignore the first parameter. 8157 void addGenericBinaryArithmeticOverloads() { 8158 if (!HasArithmeticOrEnumeralCandidateType) 8159 return; 8160 8161 for (unsigned Left = FirstPromotedArithmeticType; 8162 Left < LastPromotedArithmeticType; ++Left) { 8163 for (unsigned Right = FirstPromotedArithmeticType; 8164 Right < LastPromotedArithmeticType; ++Right) { 8165 QualType LandR[2] = { ArithmeticTypes[Left], 8166 ArithmeticTypes[Right] }; 8167 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8168 } 8169 } 8170 8171 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8172 // conditional operator for vector types. 8173 for (BuiltinCandidateTypeSet::iterator 8174 Vec1 = CandidateTypes[0].vector_begin(), 8175 Vec1End = CandidateTypes[0].vector_end(); 8176 Vec1 != Vec1End; ++Vec1) { 8177 for (BuiltinCandidateTypeSet::iterator 8178 Vec2 = CandidateTypes[1].vector_begin(), 8179 Vec2End = CandidateTypes[1].vector_end(); 8180 Vec2 != Vec2End; ++Vec2) { 8181 QualType LandR[2] = { *Vec1, *Vec2 }; 8182 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8183 } 8184 } 8185 } 8186 8187 // C++2a [over.built]p14: 8188 // 8189 // For every integral type T there exists a candidate operator function 8190 // of the form 8191 // 8192 // std::strong_ordering operator<=>(T, T) 8193 // 8194 // C++2a [over.built]p15: 8195 // 8196 // For every pair of floating-point types L and R, there exists a candidate 8197 // operator function of the form 8198 // 8199 // std::partial_ordering operator<=>(L, R); 8200 // 8201 // FIXME: The current specification for integral types doesn't play nice with 8202 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8203 // comparisons. Under the current spec this can lead to ambiguity during 8204 // overload resolution. For example: 8205 // 8206 // enum A : int {a}; 8207 // auto x = (a <=> (long)42); 8208 // 8209 // error: call is ambiguous for arguments 'A' and 'long'. 8210 // note: candidate operator<=>(int, int) 8211 // note: candidate operator<=>(long, long) 8212 // 8213 // To avoid this error, this function deviates from the specification and adds 8214 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8215 // arithmetic types (the same as the generic relational overloads). 8216 // 8217 // For now this function acts as a placeholder. 8218 void addThreeWayArithmeticOverloads() { 8219 addGenericBinaryArithmeticOverloads(); 8220 } 8221 8222 // C++ [over.built]p17: 8223 // 8224 // For every pair of promoted integral types L and R, there 8225 // exist candidate operator functions of the form 8226 // 8227 // LR operator%(L, R); 8228 // LR operator&(L, R); 8229 // LR operator^(L, R); 8230 // LR operator|(L, R); 8231 // L operator<<(L, R); 8232 // L operator>>(L, R); 8233 // 8234 // where LR is the result of the usual arithmetic conversions 8235 // between types L and R. 8236 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8237 if (!HasArithmeticOrEnumeralCandidateType) 8238 return; 8239 8240 for (unsigned Left = FirstPromotedIntegralType; 8241 Left < LastPromotedIntegralType; ++Left) { 8242 for (unsigned Right = FirstPromotedIntegralType; 8243 Right < LastPromotedIntegralType; ++Right) { 8244 QualType LandR[2] = { ArithmeticTypes[Left], 8245 ArithmeticTypes[Right] }; 8246 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8247 } 8248 } 8249 } 8250 8251 // C++ [over.built]p20: 8252 // 8253 // For every pair (T, VQ), where T is an enumeration or 8254 // pointer to member type and VQ is either volatile or 8255 // empty, there exist candidate operator functions of the form 8256 // 8257 // VQ T& operator=(VQ T&, T); 8258 void addAssignmentMemberPointerOrEnumeralOverloads() { 8259 /// Set of (canonical) types that we've already handled. 8260 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8261 8262 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8263 for (BuiltinCandidateTypeSet::iterator 8264 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8265 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8266 Enum != EnumEnd; ++Enum) { 8267 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8268 continue; 8269 8270 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8271 } 8272 8273 for (BuiltinCandidateTypeSet::iterator 8274 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8275 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8276 MemPtr != MemPtrEnd; ++MemPtr) { 8277 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8278 continue; 8279 8280 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8281 } 8282 } 8283 } 8284 8285 // C++ [over.built]p19: 8286 // 8287 // For every pair (T, VQ), where T is any type and VQ is either 8288 // volatile or empty, there exist candidate operator functions 8289 // of the form 8290 // 8291 // T*VQ& operator=(T*VQ&, T*); 8292 // 8293 // C++ [over.built]p21: 8294 // 8295 // For every pair (T, VQ), where T is a cv-qualified or 8296 // cv-unqualified object type and VQ is either volatile or 8297 // empty, there exist candidate operator functions of the form 8298 // 8299 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8300 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8301 void addAssignmentPointerOverloads(bool isEqualOp) { 8302 /// Set of (canonical) types that we've already handled. 8303 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8304 8305 for (BuiltinCandidateTypeSet::iterator 8306 Ptr = CandidateTypes[0].pointer_begin(), 8307 PtrEnd = CandidateTypes[0].pointer_end(); 8308 Ptr != PtrEnd; ++Ptr) { 8309 // If this is operator=, keep track of the builtin candidates we added. 8310 if (isEqualOp) 8311 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8312 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8313 continue; 8314 8315 // non-volatile version 8316 QualType ParamTypes[2] = { 8317 S.Context.getLValueReferenceType(*Ptr), 8318 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8319 }; 8320 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8321 /*IsAssigmentOperator=*/ isEqualOp); 8322 8323 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8324 VisibleTypeConversionsQuals.hasVolatile(); 8325 if (NeedVolatile) { 8326 // volatile version 8327 ParamTypes[0] = 8328 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8329 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8330 /*IsAssigmentOperator=*/isEqualOp); 8331 } 8332 8333 if (!(*Ptr).isRestrictQualified() && 8334 VisibleTypeConversionsQuals.hasRestrict()) { 8335 // restrict version 8336 ParamTypes[0] 8337 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8338 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8339 /*IsAssigmentOperator=*/isEqualOp); 8340 8341 if (NeedVolatile) { 8342 // volatile restrict version 8343 ParamTypes[0] 8344 = S.Context.getLValueReferenceType( 8345 S.Context.getCVRQualifiedType(*Ptr, 8346 (Qualifiers::Volatile | 8347 Qualifiers::Restrict))); 8348 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8349 /*IsAssigmentOperator=*/isEqualOp); 8350 } 8351 } 8352 } 8353 8354 if (isEqualOp) { 8355 for (BuiltinCandidateTypeSet::iterator 8356 Ptr = CandidateTypes[1].pointer_begin(), 8357 PtrEnd = CandidateTypes[1].pointer_end(); 8358 Ptr != PtrEnd; ++Ptr) { 8359 // Make sure we don't add the same candidate twice. 8360 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8361 continue; 8362 8363 QualType ParamTypes[2] = { 8364 S.Context.getLValueReferenceType(*Ptr), 8365 *Ptr, 8366 }; 8367 8368 // non-volatile version 8369 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8370 /*IsAssigmentOperator=*/true); 8371 8372 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8373 VisibleTypeConversionsQuals.hasVolatile(); 8374 if (NeedVolatile) { 8375 // volatile version 8376 ParamTypes[0] = 8377 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8378 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8379 /*IsAssigmentOperator=*/true); 8380 } 8381 8382 if (!(*Ptr).isRestrictQualified() && 8383 VisibleTypeConversionsQuals.hasRestrict()) { 8384 // restrict version 8385 ParamTypes[0] 8386 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8387 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8388 /*IsAssigmentOperator=*/true); 8389 8390 if (NeedVolatile) { 8391 // volatile restrict version 8392 ParamTypes[0] 8393 = S.Context.getLValueReferenceType( 8394 S.Context.getCVRQualifiedType(*Ptr, 8395 (Qualifiers::Volatile | 8396 Qualifiers::Restrict))); 8397 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8398 /*IsAssigmentOperator=*/true); 8399 } 8400 } 8401 } 8402 } 8403 } 8404 8405 // C++ [over.built]p18: 8406 // 8407 // For every triple (L, VQ, R), where L is an arithmetic type, 8408 // VQ is either volatile or empty, and R is a promoted 8409 // arithmetic type, there exist candidate operator functions of 8410 // the form 8411 // 8412 // VQ L& operator=(VQ L&, R); 8413 // VQ L& operator*=(VQ L&, R); 8414 // VQ L& operator/=(VQ L&, R); 8415 // VQ L& operator+=(VQ L&, R); 8416 // VQ L& operator-=(VQ L&, R); 8417 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8418 if (!HasArithmeticOrEnumeralCandidateType) 8419 return; 8420 8421 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8422 for (unsigned Right = FirstPromotedArithmeticType; 8423 Right < LastPromotedArithmeticType; ++Right) { 8424 QualType ParamTypes[2]; 8425 ParamTypes[1] = ArithmeticTypes[Right]; 8426 8427 // Add this built-in operator as a candidate (VQ is empty). 8428 ParamTypes[0] = 8429 S.Context.getLValueReferenceType(ArithmeticTypes[Left]); 8430 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8431 /*IsAssigmentOperator=*/isEqualOp); 8432 8433 // Add this built-in operator as a candidate (VQ is 'volatile'). 8434 if (VisibleTypeConversionsQuals.hasVolatile()) { 8435 ParamTypes[0] = 8436 S.Context.getVolatileType(ArithmeticTypes[Left]); 8437 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8438 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8439 /*IsAssigmentOperator=*/isEqualOp); 8440 } 8441 } 8442 } 8443 8444 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8445 for (BuiltinCandidateTypeSet::iterator 8446 Vec1 = CandidateTypes[0].vector_begin(), 8447 Vec1End = CandidateTypes[0].vector_end(); 8448 Vec1 != Vec1End; ++Vec1) { 8449 for (BuiltinCandidateTypeSet::iterator 8450 Vec2 = CandidateTypes[1].vector_begin(), 8451 Vec2End = CandidateTypes[1].vector_end(); 8452 Vec2 != Vec2End; ++Vec2) { 8453 QualType ParamTypes[2]; 8454 ParamTypes[1] = *Vec2; 8455 // Add this built-in operator as a candidate (VQ is empty). 8456 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8457 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8458 /*IsAssigmentOperator=*/isEqualOp); 8459 8460 // Add this built-in operator as a candidate (VQ is 'volatile'). 8461 if (VisibleTypeConversionsQuals.hasVolatile()) { 8462 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8463 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8464 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8465 /*IsAssigmentOperator=*/isEqualOp); 8466 } 8467 } 8468 } 8469 } 8470 8471 // C++ [over.built]p22: 8472 // 8473 // For every triple (L, VQ, R), where L is an integral type, VQ 8474 // is either volatile or empty, and R is a promoted integral 8475 // type, there exist candidate operator functions of the form 8476 // 8477 // VQ L& operator%=(VQ L&, R); 8478 // VQ L& operator<<=(VQ L&, R); 8479 // VQ L& operator>>=(VQ L&, R); 8480 // VQ L& operator&=(VQ L&, R); 8481 // VQ L& operator^=(VQ L&, R); 8482 // VQ L& operator|=(VQ L&, R); 8483 void addAssignmentIntegralOverloads() { 8484 if (!HasArithmeticOrEnumeralCandidateType) 8485 return; 8486 8487 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8488 for (unsigned Right = FirstPromotedIntegralType; 8489 Right < LastPromotedIntegralType; ++Right) { 8490 QualType ParamTypes[2]; 8491 ParamTypes[1] = ArithmeticTypes[Right]; 8492 8493 // Add this built-in operator as a candidate (VQ is empty). 8494 ParamTypes[0] = 8495 S.Context.getLValueReferenceType(ArithmeticTypes[Left]); 8496 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8497 if (VisibleTypeConversionsQuals.hasVolatile()) { 8498 // Add this built-in operator as a candidate (VQ is 'volatile'). 8499 ParamTypes[0] = ArithmeticTypes[Left]; 8500 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8501 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8502 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8503 } 8504 } 8505 } 8506 } 8507 8508 // C++ [over.operator]p23: 8509 // 8510 // There also exist candidate operator functions of the form 8511 // 8512 // bool operator!(bool); 8513 // bool operator&&(bool, bool); 8514 // bool operator||(bool, bool); 8515 void addExclaimOverload() { 8516 QualType ParamTy = S.Context.BoolTy; 8517 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8518 /*IsAssignmentOperator=*/false, 8519 /*NumContextualBoolArguments=*/1); 8520 } 8521 void addAmpAmpOrPipePipeOverload() { 8522 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8523 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8524 /*IsAssignmentOperator=*/false, 8525 /*NumContextualBoolArguments=*/2); 8526 } 8527 8528 // C++ [over.built]p13: 8529 // 8530 // For every cv-qualified or cv-unqualified object type T there 8531 // exist candidate operator functions of the form 8532 // 8533 // T* operator+(T*, ptrdiff_t); [ABOVE] 8534 // T& operator[](T*, ptrdiff_t); 8535 // T* operator-(T*, ptrdiff_t); [ABOVE] 8536 // T* operator+(ptrdiff_t, T*); [ABOVE] 8537 // T& operator[](ptrdiff_t, T*); 8538 void addSubscriptOverloads() { 8539 for (BuiltinCandidateTypeSet::iterator 8540 Ptr = CandidateTypes[0].pointer_begin(), 8541 PtrEnd = CandidateTypes[0].pointer_end(); 8542 Ptr != PtrEnd; ++Ptr) { 8543 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8544 QualType PointeeType = (*Ptr)->getPointeeType(); 8545 if (!PointeeType->isObjectType()) 8546 continue; 8547 8548 // T& operator[](T*, ptrdiff_t) 8549 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8550 } 8551 8552 for (BuiltinCandidateTypeSet::iterator 8553 Ptr = CandidateTypes[1].pointer_begin(), 8554 PtrEnd = CandidateTypes[1].pointer_end(); 8555 Ptr != PtrEnd; ++Ptr) { 8556 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8557 QualType PointeeType = (*Ptr)->getPointeeType(); 8558 if (!PointeeType->isObjectType()) 8559 continue; 8560 8561 // T& operator[](ptrdiff_t, T*) 8562 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8563 } 8564 } 8565 8566 // C++ [over.built]p11: 8567 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8568 // C1 is the same type as C2 or is a derived class of C2, T is an object 8569 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8570 // there exist candidate operator functions of the form 8571 // 8572 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8573 // 8574 // where CV12 is the union of CV1 and CV2. 8575 void addArrowStarOverloads() { 8576 for (BuiltinCandidateTypeSet::iterator 8577 Ptr = CandidateTypes[0].pointer_begin(), 8578 PtrEnd = CandidateTypes[0].pointer_end(); 8579 Ptr != PtrEnd; ++Ptr) { 8580 QualType C1Ty = (*Ptr); 8581 QualType C1; 8582 QualifierCollector Q1; 8583 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8584 if (!isa<RecordType>(C1)) 8585 continue; 8586 // heuristic to reduce number of builtin candidates in the set. 8587 // Add volatile/restrict version only if there are conversions to a 8588 // volatile/restrict type. 8589 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8590 continue; 8591 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8592 continue; 8593 for (BuiltinCandidateTypeSet::iterator 8594 MemPtr = CandidateTypes[1].member_pointer_begin(), 8595 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8596 MemPtr != MemPtrEnd; ++MemPtr) { 8597 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8598 QualType C2 = QualType(mptr->getClass(), 0); 8599 C2 = C2.getUnqualifiedType(); 8600 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8601 break; 8602 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8603 // build CV12 T& 8604 QualType T = mptr->getPointeeType(); 8605 if (!VisibleTypeConversionsQuals.hasVolatile() && 8606 T.isVolatileQualified()) 8607 continue; 8608 if (!VisibleTypeConversionsQuals.hasRestrict() && 8609 T.isRestrictQualified()) 8610 continue; 8611 T = Q1.apply(S.Context, T); 8612 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8613 } 8614 } 8615 } 8616 8617 // Note that we don't consider the first argument, since it has been 8618 // contextually converted to bool long ago. The candidates below are 8619 // therefore added as binary. 8620 // 8621 // C++ [over.built]p25: 8622 // For every type T, where T is a pointer, pointer-to-member, or scoped 8623 // enumeration type, there exist candidate operator functions of the form 8624 // 8625 // T operator?(bool, T, T); 8626 // 8627 void addConditionalOperatorOverloads() { 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 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8634 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8635 Ptr != PtrEnd; ++Ptr) { 8636 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8637 continue; 8638 8639 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8640 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8641 } 8642 8643 for (BuiltinCandidateTypeSet::iterator 8644 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8645 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8646 MemPtr != MemPtrEnd; ++MemPtr) { 8647 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8648 continue; 8649 8650 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8651 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8652 } 8653 8654 if (S.getLangOpts().CPlusPlus11) { 8655 for (BuiltinCandidateTypeSet::iterator 8656 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8657 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8658 Enum != EnumEnd; ++Enum) { 8659 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8660 continue; 8661 8662 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8663 continue; 8664 8665 QualType ParamTypes[2] = { *Enum, *Enum }; 8666 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8667 } 8668 } 8669 } 8670 } 8671 }; 8672 8673 } // end anonymous namespace 8674 8675 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8676 /// operator overloads to the candidate set (C++ [over.built]), based 8677 /// on the operator @p Op and the arguments given. For example, if the 8678 /// operator is a binary '+', this routine might add "int 8679 /// operator+(int, int)" to cover integer addition. 8680 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8681 SourceLocation OpLoc, 8682 ArrayRef<Expr *> Args, 8683 OverloadCandidateSet &CandidateSet) { 8684 // Find all of the types that the arguments can convert to, but only 8685 // if the operator we're looking at has built-in operator candidates 8686 // that make use of these types. Also record whether we encounter non-record 8687 // candidate types or either arithmetic or enumeral candidate types. 8688 Qualifiers VisibleTypeConversionsQuals; 8689 VisibleTypeConversionsQuals.addConst(); 8690 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8691 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8692 8693 bool HasNonRecordCandidateType = false; 8694 bool HasArithmeticOrEnumeralCandidateType = false; 8695 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8696 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8697 CandidateTypes.emplace_back(*this); 8698 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8699 OpLoc, 8700 true, 8701 (Op == OO_Exclaim || 8702 Op == OO_AmpAmp || 8703 Op == OO_PipePipe), 8704 VisibleTypeConversionsQuals); 8705 HasNonRecordCandidateType = HasNonRecordCandidateType || 8706 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8707 HasArithmeticOrEnumeralCandidateType = 8708 HasArithmeticOrEnumeralCandidateType || 8709 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8710 } 8711 8712 // Exit early when no non-record types have been added to the candidate set 8713 // for any of the arguments to the operator. 8714 // 8715 // We can't exit early for !, ||, or &&, since there we have always have 8716 // 'bool' overloads. 8717 if (!HasNonRecordCandidateType && 8718 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8719 return; 8720 8721 // Setup an object to manage the common state for building overloads. 8722 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8723 VisibleTypeConversionsQuals, 8724 HasArithmeticOrEnumeralCandidateType, 8725 CandidateTypes, CandidateSet); 8726 8727 // Dispatch over the operation to add in only those overloads which apply. 8728 switch (Op) { 8729 case OO_None: 8730 case NUM_OVERLOADED_OPERATORS: 8731 llvm_unreachable("Expected an overloaded operator"); 8732 8733 case OO_New: 8734 case OO_Delete: 8735 case OO_Array_New: 8736 case OO_Array_Delete: 8737 case OO_Call: 8738 llvm_unreachable( 8739 "Special operators don't use AddBuiltinOperatorCandidates"); 8740 8741 case OO_Comma: 8742 case OO_Arrow: 8743 case OO_Coawait: 8744 // C++ [over.match.oper]p3: 8745 // -- For the operator ',', the unary operator '&', the 8746 // operator '->', or the operator 'co_await', the 8747 // built-in candidates set is empty. 8748 break; 8749 8750 case OO_Plus: // '+' is either unary or binary 8751 if (Args.size() == 1) 8752 OpBuilder.addUnaryPlusPointerOverloads(); 8753 LLVM_FALLTHROUGH; 8754 8755 case OO_Minus: // '-' is either unary or binary 8756 if (Args.size() == 1) { 8757 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8758 } else { 8759 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8760 OpBuilder.addGenericBinaryArithmeticOverloads(); 8761 } 8762 break; 8763 8764 case OO_Star: // '*' is either unary or binary 8765 if (Args.size() == 1) 8766 OpBuilder.addUnaryStarPointerOverloads(); 8767 else 8768 OpBuilder.addGenericBinaryArithmeticOverloads(); 8769 break; 8770 8771 case OO_Slash: 8772 OpBuilder.addGenericBinaryArithmeticOverloads(); 8773 break; 8774 8775 case OO_PlusPlus: 8776 case OO_MinusMinus: 8777 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8778 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8779 break; 8780 8781 case OO_EqualEqual: 8782 case OO_ExclaimEqual: 8783 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8784 LLVM_FALLTHROUGH; 8785 8786 case OO_Less: 8787 case OO_Greater: 8788 case OO_LessEqual: 8789 case OO_GreaterEqual: 8790 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8791 OpBuilder.addGenericBinaryArithmeticOverloads(); 8792 break; 8793 8794 case OO_Spaceship: 8795 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8796 OpBuilder.addThreeWayArithmeticOverloads(); 8797 break; 8798 8799 case OO_Percent: 8800 case OO_Caret: 8801 case OO_Pipe: 8802 case OO_LessLess: 8803 case OO_GreaterGreater: 8804 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8805 break; 8806 8807 case OO_Amp: // '&' is either unary or binary 8808 if (Args.size() == 1) 8809 // C++ [over.match.oper]p3: 8810 // -- For the operator ',', the unary operator '&', or the 8811 // operator '->', the built-in candidates set is empty. 8812 break; 8813 8814 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8815 break; 8816 8817 case OO_Tilde: 8818 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8819 break; 8820 8821 case OO_Equal: 8822 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8823 LLVM_FALLTHROUGH; 8824 8825 case OO_PlusEqual: 8826 case OO_MinusEqual: 8827 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8828 LLVM_FALLTHROUGH; 8829 8830 case OO_StarEqual: 8831 case OO_SlashEqual: 8832 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8833 break; 8834 8835 case OO_PercentEqual: 8836 case OO_LessLessEqual: 8837 case OO_GreaterGreaterEqual: 8838 case OO_AmpEqual: 8839 case OO_CaretEqual: 8840 case OO_PipeEqual: 8841 OpBuilder.addAssignmentIntegralOverloads(); 8842 break; 8843 8844 case OO_Exclaim: 8845 OpBuilder.addExclaimOverload(); 8846 break; 8847 8848 case OO_AmpAmp: 8849 case OO_PipePipe: 8850 OpBuilder.addAmpAmpOrPipePipeOverload(); 8851 break; 8852 8853 case OO_Subscript: 8854 OpBuilder.addSubscriptOverloads(); 8855 break; 8856 8857 case OO_ArrowStar: 8858 OpBuilder.addArrowStarOverloads(); 8859 break; 8860 8861 case OO_Conditional: 8862 OpBuilder.addConditionalOperatorOverloads(); 8863 OpBuilder.addGenericBinaryArithmeticOverloads(); 8864 break; 8865 } 8866 } 8867 8868 /// Add function candidates found via argument-dependent lookup 8869 /// to the set of overloading candidates. 8870 /// 8871 /// This routine performs argument-dependent name lookup based on the 8872 /// given function name (which may also be an operator name) and adds 8873 /// all of the overload candidates found by ADL to the overload 8874 /// candidate set (C++ [basic.lookup.argdep]). 8875 void 8876 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8877 SourceLocation Loc, 8878 ArrayRef<Expr *> Args, 8879 TemplateArgumentListInfo *ExplicitTemplateArgs, 8880 OverloadCandidateSet& CandidateSet, 8881 bool PartialOverloading) { 8882 ADLResult Fns; 8883 8884 // FIXME: This approach for uniquing ADL results (and removing 8885 // redundant candidates from the set) relies on pointer-equality, 8886 // which means we need to key off the canonical decl. However, 8887 // always going back to the canonical decl might not get us the 8888 // right set of default arguments. What default arguments are 8889 // we supposed to consider on ADL candidates, anyway? 8890 8891 // FIXME: Pass in the explicit template arguments? 8892 ArgumentDependentLookup(Name, Loc, Args, Fns); 8893 8894 // Erase all of the candidates we already knew about. 8895 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8896 CandEnd = CandidateSet.end(); 8897 Cand != CandEnd; ++Cand) 8898 if (Cand->Function) { 8899 Fns.erase(Cand->Function); 8900 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8901 Fns.erase(FunTmpl); 8902 } 8903 8904 // For each of the ADL candidates we found, add it to the overload 8905 // set. 8906 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8907 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8908 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8909 if (ExplicitTemplateArgs) 8910 continue; 8911 8912 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8913 PartialOverloading); 8914 } else 8915 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8916 FoundDecl, ExplicitTemplateArgs, 8917 Args, CandidateSet, PartialOverloading); 8918 } 8919 } 8920 8921 namespace { 8922 enum class Comparison { Equal, Better, Worse }; 8923 } 8924 8925 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8926 /// overload resolution. 8927 /// 8928 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8929 /// Cand1's first N enable_if attributes have precisely the same conditions as 8930 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8931 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8932 /// 8933 /// Note that you can have a pair of candidates such that Cand1's enable_if 8934 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8935 /// worse than Cand1's. 8936 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8937 const FunctionDecl *Cand2) { 8938 // Common case: One (or both) decls don't have enable_if attrs. 8939 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8940 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8941 if (!Cand1Attr || !Cand2Attr) { 8942 if (Cand1Attr == Cand2Attr) 8943 return Comparison::Equal; 8944 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8945 } 8946 8947 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 8948 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 8949 8950 auto Cand1I = Cand1Attrs.begin(); 8951 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8952 for (EnableIfAttr *Cand2A : Cand2Attrs) { 8953 Cand1ID.clear(); 8954 Cand2ID.clear(); 8955 8956 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8957 // has fewer enable_if attributes than Cand2. 8958 auto Cand1A = Cand1I++; 8959 if (Cand1A == Cand1Attrs.end()) 8960 return Comparison::Worse; 8961 8962 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8963 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8964 if (Cand1ID != Cand2ID) 8965 return Comparison::Worse; 8966 } 8967 8968 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8969 } 8970 8971 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 8972 const OverloadCandidate &Cand2) { 8973 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 8974 !Cand2.Function->isMultiVersion()) 8975 return false; 8976 8977 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 8978 // cpu_dispatch, else arbitrarily based on the identifiers. 8979 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 8980 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 8981 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 8982 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 8983 8984 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 8985 return false; 8986 8987 if (Cand1CPUDisp && !Cand2CPUDisp) 8988 return true; 8989 if (Cand2CPUDisp && !Cand1CPUDisp) 8990 return false; 8991 8992 if (Cand1CPUSpec && Cand2CPUSpec) { 8993 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 8994 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 8995 8996 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 8997 FirstDiff = std::mismatch( 8998 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 8999 Cand2CPUSpec->cpus_begin(), 9000 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9001 return LHS->getName() == RHS->getName(); 9002 }); 9003 9004 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9005 "Two different cpu-specific versions should not have the same " 9006 "identifier list, otherwise they'd be the same decl!"); 9007 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9008 } 9009 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9010 } 9011 9012 /// isBetterOverloadCandidate - Determines whether the first overload 9013 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9014 bool clang::isBetterOverloadCandidate( 9015 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9016 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9017 // Define viable functions to be better candidates than non-viable 9018 // functions. 9019 if (!Cand2.Viable) 9020 return Cand1.Viable; 9021 else if (!Cand1.Viable) 9022 return false; 9023 9024 // C++ [over.match.best]p1: 9025 // 9026 // -- if F is a static member function, ICS1(F) is defined such 9027 // that ICS1(F) is neither better nor worse than ICS1(G) for 9028 // any function G, and, symmetrically, ICS1(G) is neither 9029 // better nor worse than ICS1(F). 9030 unsigned StartArg = 0; 9031 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9032 StartArg = 1; 9033 9034 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9035 // We don't allow incompatible pointer conversions in C++. 9036 if (!S.getLangOpts().CPlusPlus) 9037 return ICS.isStandard() && 9038 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9039 9040 // The only ill-formed conversion we allow in C++ is the string literal to 9041 // char* conversion, which is only considered ill-formed after C++11. 9042 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9043 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9044 }; 9045 9046 // Define functions that don't require ill-formed conversions for a given 9047 // argument to be better candidates than functions that do. 9048 unsigned NumArgs = Cand1.Conversions.size(); 9049 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9050 bool HasBetterConversion = false; 9051 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9052 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9053 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9054 if (Cand1Bad != Cand2Bad) { 9055 if (Cand1Bad) 9056 return false; 9057 HasBetterConversion = true; 9058 } 9059 } 9060 9061 if (HasBetterConversion) 9062 return true; 9063 9064 // C++ [over.match.best]p1: 9065 // A viable function F1 is defined to be a better function than another 9066 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9067 // conversion sequence than ICSi(F2), and then... 9068 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9069 switch (CompareImplicitConversionSequences(S, Loc, 9070 Cand1.Conversions[ArgIdx], 9071 Cand2.Conversions[ArgIdx])) { 9072 case ImplicitConversionSequence::Better: 9073 // Cand1 has a better conversion sequence. 9074 HasBetterConversion = true; 9075 break; 9076 9077 case ImplicitConversionSequence::Worse: 9078 // Cand1 can't be better than Cand2. 9079 return false; 9080 9081 case ImplicitConversionSequence::Indistinguishable: 9082 // Do nothing. 9083 break; 9084 } 9085 } 9086 9087 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9088 // ICSj(F2), or, if not that, 9089 if (HasBetterConversion) 9090 return true; 9091 9092 // -- the context is an initialization by user-defined conversion 9093 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9094 // from the return type of F1 to the destination type (i.e., 9095 // the type of the entity being initialized) is a better 9096 // conversion sequence than the standard conversion sequence 9097 // from the return type of F2 to the destination type. 9098 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9099 Cand1.Function && Cand2.Function && 9100 isa<CXXConversionDecl>(Cand1.Function) && 9101 isa<CXXConversionDecl>(Cand2.Function)) { 9102 // First check whether we prefer one of the conversion functions over the 9103 // other. This only distinguishes the results in non-standard, extension 9104 // cases such as the conversion from a lambda closure type to a function 9105 // pointer or block. 9106 ImplicitConversionSequence::CompareKind Result = 9107 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9108 if (Result == ImplicitConversionSequence::Indistinguishable) 9109 Result = CompareStandardConversionSequences(S, Loc, 9110 Cand1.FinalConversion, 9111 Cand2.FinalConversion); 9112 9113 if (Result != ImplicitConversionSequence::Indistinguishable) 9114 return Result == ImplicitConversionSequence::Better; 9115 9116 // FIXME: Compare kind of reference binding if conversion functions 9117 // convert to a reference type used in direct reference binding, per 9118 // C++14 [over.match.best]p1 section 2 bullet 3. 9119 } 9120 9121 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9122 // as combined with the resolution to CWG issue 243. 9123 // 9124 // When the context is initialization by constructor ([over.match.ctor] or 9125 // either phase of [over.match.list]), a constructor is preferred over 9126 // a conversion function. 9127 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9128 Cand1.Function && Cand2.Function && 9129 isa<CXXConstructorDecl>(Cand1.Function) != 9130 isa<CXXConstructorDecl>(Cand2.Function)) 9131 return isa<CXXConstructorDecl>(Cand1.Function); 9132 9133 // -- F1 is a non-template function and F2 is a function template 9134 // specialization, or, if not that, 9135 bool Cand1IsSpecialization = Cand1.Function && 9136 Cand1.Function->getPrimaryTemplate(); 9137 bool Cand2IsSpecialization = Cand2.Function && 9138 Cand2.Function->getPrimaryTemplate(); 9139 if (Cand1IsSpecialization != Cand2IsSpecialization) 9140 return Cand2IsSpecialization; 9141 9142 // -- F1 and F2 are function template specializations, and the function 9143 // template for F1 is more specialized than the template for F2 9144 // according to the partial ordering rules described in 14.5.5.2, or, 9145 // if not that, 9146 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9147 if (FunctionTemplateDecl *BetterTemplate 9148 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9149 Cand2.Function->getPrimaryTemplate(), 9150 Loc, 9151 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9152 : TPOC_Call, 9153 Cand1.ExplicitCallArguments, 9154 Cand2.ExplicitCallArguments)) 9155 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9156 } 9157 9158 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9159 // A derived-class constructor beats an (inherited) base class constructor. 9160 bool Cand1IsInherited = 9161 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9162 bool Cand2IsInherited = 9163 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9164 if (Cand1IsInherited != Cand2IsInherited) 9165 return Cand2IsInherited; 9166 else if (Cand1IsInherited) { 9167 assert(Cand2IsInherited); 9168 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9169 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9170 if (Cand1Class->isDerivedFrom(Cand2Class)) 9171 return true; 9172 if (Cand2Class->isDerivedFrom(Cand1Class)) 9173 return false; 9174 // Inherited from sibling base classes: still ambiguous. 9175 } 9176 9177 // Check C++17 tie-breakers for deduction guides. 9178 { 9179 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9180 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9181 if (Guide1 && Guide2) { 9182 // -- F1 is generated from a deduction-guide and F2 is not 9183 if (Guide1->isImplicit() != Guide2->isImplicit()) 9184 return Guide2->isImplicit(); 9185 9186 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9187 if (Guide1->isCopyDeductionCandidate()) 9188 return true; 9189 } 9190 } 9191 9192 // Check for enable_if value-based overload resolution. 9193 if (Cand1.Function && Cand2.Function) { 9194 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9195 if (Cmp != Comparison::Equal) 9196 return Cmp == Comparison::Better; 9197 } 9198 9199 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9200 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9201 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9202 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9203 } 9204 9205 bool HasPS1 = Cand1.Function != nullptr && 9206 functionHasPassObjectSizeParams(Cand1.Function); 9207 bool HasPS2 = Cand2.Function != nullptr && 9208 functionHasPassObjectSizeParams(Cand2.Function); 9209 if (HasPS1 != HasPS2 && HasPS1) 9210 return true; 9211 9212 return isBetterMultiversionCandidate(Cand1, Cand2); 9213 } 9214 9215 /// Determine whether two declarations are "equivalent" for the purposes of 9216 /// name lookup and overload resolution. This applies when the same internal/no 9217 /// linkage entity is defined by two modules (probably by textually including 9218 /// the same header). In such a case, we don't consider the declarations to 9219 /// declare the same entity, but we also don't want lookups with both 9220 /// declarations visible to be ambiguous in some cases (this happens when using 9221 /// a modularized libstdc++). 9222 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9223 const NamedDecl *B) { 9224 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9225 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9226 if (!VA || !VB) 9227 return false; 9228 9229 // The declarations must be declaring the same name as an internal linkage 9230 // entity in different modules. 9231 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9232 VB->getDeclContext()->getRedeclContext()) || 9233 getOwningModule(const_cast<ValueDecl *>(VA)) == 9234 getOwningModule(const_cast<ValueDecl *>(VB)) || 9235 VA->isExternallyVisible() || VB->isExternallyVisible()) 9236 return false; 9237 9238 // Check that the declarations appear to be equivalent. 9239 // 9240 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9241 // For constants and functions, we should check the initializer or body is 9242 // the same. For non-constant variables, we shouldn't allow it at all. 9243 if (Context.hasSameType(VA->getType(), VB->getType())) 9244 return true; 9245 9246 // Enum constants within unnamed enumerations will have different types, but 9247 // may still be similar enough to be interchangeable for our purposes. 9248 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9249 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9250 // Only handle anonymous enums. If the enumerations were named and 9251 // equivalent, they would have been merged to the same type. 9252 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9253 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9254 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9255 !Context.hasSameType(EnumA->getIntegerType(), 9256 EnumB->getIntegerType())) 9257 return false; 9258 // Allow this only if the value is the same for both enumerators. 9259 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9260 } 9261 } 9262 9263 // Nothing else is sufficiently similar. 9264 return false; 9265 } 9266 9267 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9268 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9269 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9270 9271 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9272 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9273 << !M << (M ? M->getFullModuleName() : ""); 9274 9275 for (auto *E : Equiv) { 9276 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9277 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9278 << !M << (M ? M->getFullModuleName() : ""); 9279 } 9280 } 9281 9282 /// Computes the best viable function (C++ 13.3.3) 9283 /// within an overload candidate set. 9284 /// 9285 /// \param Loc The location of the function name (or operator symbol) for 9286 /// which overload resolution occurs. 9287 /// 9288 /// \param Best If overload resolution was successful or found a deleted 9289 /// function, \p Best points to the candidate function found. 9290 /// 9291 /// \returns The result of overload resolution. 9292 OverloadingResult 9293 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9294 iterator &Best) { 9295 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9296 std::transform(begin(), end(), std::back_inserter(Candidates), 9297 [](OverloadCandidate &Cand) { return &Cand; }); 9298 9299 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9300 // are accepted by both clang and NVCC. However, during a particular 9301 // compilation mode only one call variant is viable. We need to 9302 // exclude non-viable overload candidates from consideration based 9303 // only on their host/device attributes. Specifically, if one 9304 // candidate call is WrongSide and the other is SameSide, we ignore 9305 // the WrongSide candidate. 9306 if (S.getLangOpts().CUDA) { 9307 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9308 bool ContainsSameSideCandidate = 9309 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9310 return Cand->Function && 9311 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9312 Sema::CFP_SameSide; 9313 }); 9314 if (ContainsSameSideCandidate) { 9315 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9316 return Cand->Function && 9317 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9318 Sema::CFP_WrongSide; 9319 }; 9320 llvm::erase_if(Candidates, IsWrongSideCandidate); 9321 } 9322 } 9323 9324 // Find the best viable function. 9325 Best = end(); 9326 for (auto *Cand : Candidates) 9327 if (Cand->Viable) 9328 if (Best == end() || 9329 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9330 Best = Cand; 9331 9332 // If we didn't find any viable functions, abort. 9333 if (Best == end()) 9334 return OR_No_Viable_Function; 9335 9336 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9337 9338 // Make sure that this function is better than every other viable 9339 // function. If not, we have an ambiguity. 9340 for (auto *Cand : Candidates) { 9341 if (Cand->Viable && Cand != Best && 9342 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { 9343 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9344 Cand->Function)) { 9345 EquivalentCands.push_back(Cand->Function); 9346 continue; 9347 } 9348 9349 Best = end(); 9350 return OR_Ambiguous; 9351 } 9352 } 9353 9354 // Best is the best viable function. 9355 if (Best->Function && 9356 (Best->Function->isDeleted() || 9357 S.isFunctionConsideredUnavailable(Best->Function))) 9358 return OR_Deleted; 9359 9360 if (!EquivalentCands.empty()) 9361 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9362 EquivalentCands); 9363 9364 return OR_Success; 9365 } 9366 9367 namespace { 9368 9369 enum OverloadCandidateKind { 9370 oc_function, 9371 oc_method, 9372 oc_constructor, 9373 oc_implicit_default_constructor, 9374 oc_implicit_copy_constructor, 9375 oc_implicit_move_constructor, 9376 oc_implicit_copy_assignment, 9377 oc_implicit_move_assignment, 9378 oc_inherited_constructor 9379 }; 9380 9381 enum OverloadCandidateSelect { 9382 ocs_non_template, 9383 ocs_template, 9384 ocs_described_template, 9385 }; 9386 9387 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9388 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9389 std::string &Description) { 9390 9391 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9392 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9393 isTemplate = true; 9394 Description = S.getTemplateArgumentBindingsText( 9395 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9396 } 9397 9398 OverloadCandidateSelect Select = [&]() { 9399 if (!Description.empty()) 9400 return ocs_described_template; 9401 return isTemplate ? ocs_template : ocs_non_template; 9402 }(); 9403 9404 OverloadCandidateKind Kind = [&]() { 9405 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9406 if (!Ctor->isImplicit()) { 9407 if (isa<ConstructorUsingShadowDecl>(Found)) 9408 return oc_inherited_constructor; 9409 else 9410 return oc_constructor; 9411 } 9412 9413 if (Ctor->isDefaultConstructor()) 9414 return oc_implicit_default_constructor; 9415 9416 if (Ctor->isMoveConstructor()) 9417 return oc_implicit_move_constructor; 9418 9419 assert(Ctor->isCopyConstructor() && 9420 "unexpected sort of implicit constructor"); 9421 return oc_implicit_copy_constructor; 9422 } 9423 9424 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9425 // This actually gets spelled 'candidate function' for now, but 9426 // it doesn't hurt to split it out. 9427 if (!Meth->isImplicit()) 9428 return oc_method; 9429 9430 if (Meth->isMoveAssignmentOperator()) 9431 return oc_implicit_move_assignment; 9432 9433 if (Meth->isCopyAssignmentOperator()) 9434 return oc_implicit_copy_assignment; 9435 9436 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9437 return oc_method; 9438 } 9439 9440 return oc_function; 9441 }(); 9442 9443 return std::make_pair(Kind, Select); 9444 } 9445 9446 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9447 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9448 // set. 9449 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9450 S.Diag(FoundDecl->getLocation(), 9451 diag::note_ovl_candidate_inherited_constructor) 9452 << Shadow->getNominatedBaseClass(); 9453 } 9454 9455 } // end anonymous namespace 9456 9457 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9458 const FunctionDecl *FD) { 9459 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9460 bool AlwaysTrue; 9461 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9462 return false; 9463 if (!AlwaysTrue) 9464 return false; 9465 } 9466 return true; 9467 } 9468 9469 /// Returns true if we can take the address of the function. 9470 /// 9471 /// \param Complain - If true, we'll emit a diagnostic 9472 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9473 /// we in overload resolution? 9474 /// \param Loc - The location of the statement we're complaining about. Ignored 9475 /// if we're not complaining, or if we're in overload resolution. 9476 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9477 bool Complain, 9478 bool InOverloadResolution, 9479 SourceLocation Loc) { 9480 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9481 if (Complain) { 9482 if (InOverloadResolution) 9483 S.Diag(FD->getBeginLoc(), 9484 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9485 else 9486 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9487 } 9488 return false; 9489 } 9490 9491 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9492 return P->hasAttr<PassObjectSizeAttr>(); 9493 }); 9494 if (I == FD->param_end()) 9495 return true; 9496 9497 if (Complain) { 9498 // Add one to ParamNo because it's user-facing 9499 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9500 if (InOverloadResolution) 9501 S.Diag(FD->getLocation(), 9502 diag::note_ovl_candidate_has_pass_object_size_params) 9503 << ParamNo; 9504 else 9505 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9506 << FD << ParamNo; 9507 } 9508 return false; 9509 } 9510 9511 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9512 const FunctionDecl *FD) { 9513 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9514 /*InOverloadResolution=*/true, 9515 /*Loc=*/SourceLocation()); 9516 } 9517 9518 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9519 bool Complain, 9520 SourceLocation Loc) { 9521 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9522 /*InOverloadResolution=*/false, 9523 Loc); 9524 } 9525 9526 // Notes the location of an overload candidate. 9527 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9528 QualType DestType, bool TakingAddress) { 9529 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9530 return; 9531 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9532 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9533 return; 9534 9535 std::string FnDesc; 9536 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9537 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9538 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9539 << (unsigned)KSPair.first << (unsigned)KSPair.second 9540 << Fn << FnDesc; 9541 9542 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9543 Diag(Fn->getLocation(), PD); 9544 MaybeEmitInheritedConstructorNote(*this, Found); 9545 } 9546 9547 // Notes the location of all overload candidates designated through 9548 // OverloadedExpr 9549 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9550 bool TakingAddress) { 9551 assert(OverloadedExpr->getType() == Context.OverloadTy); 9552 9553 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9554 OverloadExpr *OvlExpr = Ovl.Expression; 9555 9556 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9557 IEnd = OvlExpr->decls_end(); 9558 I != IEnd; ++I) { 9559 if (FunctionTemplateDecl *FunTmpl = 9560 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9561 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9562 TakingAddress); 9563 } else if (FunctionDecl *Fun 9564 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9565 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9566 } 9567 } 9568 } 9569 9570 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9571 /// "lead" diagnostic; it will be given two arguments, the source and 9572 /// target types of the conversion. 9573 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9574 Sema &S, 9575 SourceLocation CaretLoc, 9576 const PartialDiagnostic &PDiag) const { 9577 S.Diag(CaretLoc, PDiag) 9578 << Ambiguous.getFromType() << Ambiguous.getToType(); 9579 // FIXME: The note limiting machinery is borrowed from 9580 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9581 // refactoring here. 9582 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9583 unsigned CandsShown = 0; 9584 AmbiguousConversionSequence::const_iterator I, E; 9585 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9586 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9587 break; 9588 ++CandsShown; 9589 S.NoteOverloadCandidate(I->first, I->second); 9590 } 9591 if (I != E) 9592 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9593 } 9594 9595 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9596 unsigned I, bool TakingCandidateAddress) { 9597 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9598 assert(Conv.isBad()); 9599 assert(Cand->Function && "for now, candidate must be a function"); 9600 FunctionDecl *Fn = Cand->Function; 9601 9602 // There's a conversion slot for the object argument if this is a 9603 // non-constructor method. Note that 'I' corresponds the 9604 // conversion-slot index. 9605 bool isObjectArgument = false; 9606 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9607 if (I == 0) 9608 isObjectArgument = true; 9609 else 9610 I--; 9611 } 9612 9613 std::string FnDesc; 9614 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9615 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9616 9617 Expr *FromExpr = Conv.Bad.FromExpr; 9618 QualType FromTy = Conv.Bad.getFromType(); 9619 QualType ToTy = Conv.Bad.getToType(); 9620 9621 if (FromTy == S.Context.OverloadTy) { 9622 assert(FromExpr && "overload set argument came from implicit argument?"); 9623 Expr *E = FromExpr->IgnoreParens(); 9624 if (isa<UnaryOperator>(E)) 9625 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9626 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9627 9628 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9629 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9630 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9631 << Name << I + 1; 9632 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9633 return; 9634 } 9635 9636 // Do some hand-waving analysis to see if the non-viability is due 9637 // to a qualifier mismatch. 9638 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9639 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9640 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9641 CToTy = RT->getPointeeType(); 9642 else { 9643 // TODO: detect and diagnose the full richness of const mismatches. 9644 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9645 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9646 CFromTy = FromPT->getPointeeType(); 9647 CToTy = ToPT->getPointeeType(); 9648 } 9649 } 9650 9651 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9652 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9653 Qualifiers FromQs = CFromTy.getQualifiers(); 9654 Qualifiers ToQs = CToTy.getQualifiers(); 9655 9656 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9657 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9658 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9659 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9660 << ToTy << (unsigned)isObjectArgument << I + 1; 9661 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9662 return; 9663 } 9664 9665 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9666 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9667 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9668 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9669 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9670 << (unsigned)isObjectArgument << I + 1; 9671 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9672 return; 9673 } 9674 9675 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9676 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9677 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9678 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9679 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9680 << (unsigned)isObjectArgument << I + 1; 9681 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9682 return; 9683 } 9684 9685 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9686 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9687 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9688 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9689 << FromQs.hasUnaligned() << I + 1; 9690 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9691 return; 9692 } 9693 9694 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9695 assert(CVR && "unexpected qualifiers mismatch"); 9696 9697 if (isObjectArgument) { 9698 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9699 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9700 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9701 << (CVR - 1); 9702 } else { 9703 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9704 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9705 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9706 << (CVR - 1) << I + 1; 9707 } 9708 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9709 return; 9710 } 9711 9712 // Special diagnostic for failure to convert an initializer list, since 9713 // telling the user that it has type void is not useful. 9714 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9715 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9716 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9717 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9718 << ToTy << (unsigned)isObjectArgument << I + 1; 9719 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9720 return; 9721 } 9722 9723 // Diagnose references or pointers to incomplete types differently, 9724 // since it's far from impossible that the incompleteness triggered 9725 // the failure. 9726 QualType TempFromTy = FromTy.getNonReferenceType(); 9727 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9728 TempFromTy = PTy->getPointeeType(); 9729 if (TempFromTy->isIncompleteType()) { 9730 // Emit the generic diagnostic and, optionally, add the hints to it. 9731 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9732 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9733 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9734 << ToTy << (unsigned)isObjectArgument << I + 1 9735 << (unsigned)(Cand->Fix.Kind); 9736 9737 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9738 return; 9739 } 9740 9741 // Diagnose base -> derived pointer conversions. 9742 unsigned BaseToDerivedConversion = 0; 9743 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9744 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9745 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9746 FromPtrTy->getPointeeType()) && 9747 !FromPtrTy->getPointeeType()->isIncompleteType() && 9748 !ToPtrTy->getPointeeType()->isIncompleteType() && 9749 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9750 FromPtrTy->getPointeeType())) 9751 BaseToDerivedConversion = 1; 9752 } 9753 } else if (const ObjCObjectPointerType *FromPtrTy 9754 = FromTy->getAs<ObjCObjectPointerType>()) { 9755 if (const ObjCObjectPointerType *ToPtrTy 9756 = ToTy->getAs<ObjCObjectPointerType>()) 9757 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9758 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9759 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9760 FromPtrTy->getPointeeType()) && 9761 FromIface->isSuperClassOf(ToIface)) 9762 BaseToDerivedConversion = 2; 9763 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9764 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9765 !FromTy->isIncompleteType() && 9766 !ToRefTy->getPointeeType()->isIncompleteType() && 9767 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9768 BaseToDerivedConversion = 3; 9769 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9770 ToTy.getNonReferenceType().getCanonicalType() == 9771 FromTy.getNonReferenceType().getCanonicalType()) { 9772 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9773 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9774 << (unsigned)isObjectArgument << I + 1 9775 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 9776 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9777 return; 9778 } 9779 } 9780 9781 if (BaseToDerivedConversion) { 9782 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 9783 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9784 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9785 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 9786 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9787 return; 9788 } 9789 9790 if (isa<ObjCObjectPointerType>(CFromTy) && 9791 isa<PointerType>(CToTy)) { 9792 Qualifiers FromQs = CFromTy.getQualifiers(); 9793 Qualifiers ToQs = CToTy.getQualifiers(); 9794 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9795 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9796 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9797 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9798 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 9799 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9800 return; 9801 } 9802 } 9803 9804 if (TakingCandidateAddress && 9805 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9806 return; 9807 9808 // Emit the generic diagnostic and, optionally, add the hints to it. 9809 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9810 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9811 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9812 << ToTy << (unsigned)isObjectArgument << I + 1 9813 << (unsigned)(Cand->Fix.Kind); 9814 9815 // If we can fix the conversion, suggest the FixIts. 9816 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9817 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9818 FDiag << *HI; 9819 S.Diag(Fn->getLocation(), FDiag); 9820 9821 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9822 } 9823 9824 /// Additional arity mismatch diagnosis specific to a function overload 9825 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9826 /// over a candidate in any candidate set. 9827 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9828 unsigned NumArgs) { 9829 FunctionDecl *Fn = Cand->Function; 9830 unsigned MinParams = Fn->getMinRequiredArguments(); 9831 9832 // With invalid overloaded operators, it's possible that we think we 9833 // have an arity mismatch when in fact it looks like we have the 9834 // right number of arguments, because only overloaded operators have 9835 // the weird behavior of overloading member and non-member functions. 9836 // Just don't report anything. 9837 if (Fn->isInvalidDecl() && 9838 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9839 return true; 9840 9841 if (NumArgs < MinParams) { 9842 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9843 (Cand->FailureKind == ovl_fail_bad_deduction && 9844 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9845 } else { 9846 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9847 (Cand->FailureKind == ovl_fail_bad_deduction && 9848 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9849 } 9850 9851 return false; 9852 } 9853 9854 /// General arity mismatch diagnosis over a candidate in a candidate set. 9855 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9856 unsigned NumFormalArgs) { 9857 assert(isa<FunctionDecl>(D) && 9858 "The templated declaration should at least be a function" 9859 " when diagnosing bad template argument deduction due to too many" 9860 " or too few arguments"); 9861 9862 FunctionDecl *Fn = cast<FunctionDecl>(D); 9863 9864 // TODO: treat calls to a missing default constructor as a special case 9865 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9866 unsigned MinParams = Fn->getMinRequiredArguments(); 9867 9868 // at least / at most / exactly 9869 unsigned mode, modeCount; 9870 if (NumFormalArgs < MinParams) { 9871 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9872 FnTy->isTemplateVariadic()) 9873 mode = 0; // "at least" 9874 else 9875 mode = 2; // "exactly" 9876 modeCount = MinParams; 9877 } else { 9878 if (MinParams != FnTy->getNumParams()) 9879 mode = 1; // "at most" 9880 else 9881 mode = 2; // "exactly" 9882 modeCount = FnTy->getNumParams(); 9883 } 9884 9885 std::string Description; 9886 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9887 ClassifyOverloadCandidate(S, Found, Fn, Description); 9888 9889 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9890 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9891 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9892 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 9893 else 9894 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9895 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9896 << Description << mode << modeCount << NumFormalArgs; 9897 9898 MaybeEmitInheritedConstructorNote(S, Found); 9899 } 9900 9901 /// Arity mismatch diagnosis specific to a function overload candidate. 9902 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9903 unsigned NumFormalArgs) { 9904 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9905 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9906 } 9907 9908 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9909 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9910 return TD; 9911 llvm_unreachable("Unsupported: Getting the described template declaration" 9912 " for bad deduction diagnosis"); 9913 } 9914 9915 /// Diagnose a failed template-argument deduction. 9916 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9917 DeductionFailureInfo &DeductionFailure, 9918 unsigned NumArgs, 9919 bool TakingCandidateAddress) { 9920 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9921 NamedDecl *ParamD; 9922 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9923 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9924 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9925 switch (DeductionFailure.Result) { 9926 case Sema::TDK_Success: 9927 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9928 9929 case Sema::TDK_Incomplete: { 9930 assert(ParamD && "no parameter found for incomplete deduction result"); 9931 S.Diag(Templated->getLocation(), 9932 diag::note_ovl_candidate_incomplete_deduction) 9933 << ParamD->getDeclName(); 9934 MaybeEmitInheritedConstructorNote(S, Found); 9935 return; 9936 } 9937 9938 case Sema::TDK_IncompletePack: { 9939 assert(ParamD && "no parameter found for incomplete deduction result"); 9940 S.Diag(Templated->getLocation(), 9941 diag::note_ovl_candidate_incomplete_deduction_pack) 9942 << ParamD->getDeclName() 9943 << (DeductionFailure.getFirstArg()->pack_size() + 1) 9944 << *DeductionFailure.getFirstArg(); 9945 MaybeEmitInheritedConstructorNote(S, Found); 9946 return; 9947 } 9948 9949 case Sema::TDK_Underqualified: { 9950 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9951 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9952 9953 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9954 9955 // Param will have been canonicalized, but it should just be a 9956 // qualified version of ParamD, so move the qualifiers to that. 9957 QualifierCollector Qs; 9958 Qs.strip(Param); 9959 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9960 assert(S.Context.hasSameType(Param, NonCanonParam)); 9961 9962 // Arg has also been canonicalized, but there's nothing we can do 9963 // about that. It also doesn't matter as much, because it won't 9964 // have any template parameters in it (because deduction isn't 9965 // done on dependent types). 9966 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9967 9968 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9969 << ParamD->getDeclName() << Arg << NonCanonParam; 9970 MaybeEmitInheritedConstructorNote(S, Found); 9971 return; 9972 } 9973 9974 case Sema::TDK_Inconsistent: { 9975 assert(ParamD && "no parameter found for inconsistent deduction result"); 9976 int which = 0; 9977 if (isa<TemplateTypeParmDecl>(ParamD)) 9978 which = 0; 9979 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 9980 // Deduction might have failed because we deduced arguments of two 9981 // different types for a non-type template parameter. 9982 // FIXME: Use a different TDK value for this. 9983 QualType T1 = 9984 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 9985 QualType T2 = 9986 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 9987 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 9988 S.Diag(Templated->getLocation(), 9989 diag::note_ovl_candidate_inconsistent_deduction_types) 9990 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 9991 << *DeductionFailure.getSecondArg() << T2; 9992 MaybeEmitInheritedConstructorNote(S, Found); 9993 return; 9994 } 9995 9996 which = 1; 9997 } else { 9998 which = 2; 9999 } 10000 10001 S.Diag(Templated->getLocation(), 10002 diag::note_ovl_candidate_inconsistent_deduction) 10003 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10004 << *DeductionFailure.getSecondArg(); 10005 MaybeEmitInheritedConstructorNote(S, Found); 10006 return; 10007 } 10008 10009 case Sema::TDK_InvalidExplicitArguments: 10010 assert(ParamD && "no parameter found for invalid explicit arguments"); 10011 if (ParamD->getDeclName()) 10012 S.Diag(Templated->getLocation(), 10013 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10014 << ParamD->getDeclName(); 10015 else { 10016 int index = 0; 10017 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10018 index = TTP->getIndex(); 10019 else if (NonTypeTemplateParmDecl *NTTP 10020 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10021 index = NTTP->getIndex(); 10022 else 10023 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10024 S.Diag(Templated->getLocation(), 10025 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10026 << (index + 1); 10027 } 10028 MaybeEmitInheritedConstructorNote(S, Found); 10029 return; 10030 10031 case Sema::TDK_TooManyArguments: 10032 case Sema::TDK_TooFewArguments: 10033 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10034 return; 10035 10036 case Sema::TDK_InstantiationDepth: 10037 S.Diag(Templated->getLocation(), 10038 diag::note_ovl_candidate_instantiation_depth); 10039 MaybeEmitInheritedConstructorNote(S, Found); 10040 return; 10041 10042 case Sema::TDK_SubstitutionFailure: { 10043 // Format the template argument list into the argument string. 10044 SmallString<128> TemplateArgString; 10045 if (TemplateArgumentList *Args = 10046 DeductionFailure.getTemplateArgumentList()) { 10047 TemplateArgString = " "; 10048 TemplateArgString += S.getTemplateArgumentBindingsText( 10049 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10050 } 10051 10052 // If this candidate was disabled by enable_if, say so. 10053 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10054 if (PDiag && PDiag->second.getDiagID() == 10055 diag::err_typename_nested_not_found_enable_if) { 10056 // FIXME: Use the source range of the condition, and the fully-qualified 10057 // name of the enable_if template. These are both present in PDiag. 10058 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10059 << "'enable_if'" << TemplateArgString; 10060 return; 10061 } 10062 10063 // We found a specific requirement that disabled the enable_if. 10064 if (PDiag && PDiag->second.getDiagID() == 10065 diag::err_typename_nested_not_found_requirement) { 10066 S.Diag(Templated->getLocation(), 10067 diag::note_ovl_candidate_disabled_by_requirement) 10068 << PDiag->second.getStringArg(0) << TemplateArgString; 10069 return; 10070 } 10071 10072 // Format the SFINAE diagnostic into the argument string. 10073 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10074 // formatted message in another diagnostic. 10075 SmallString<128> SFINAEArgString; 10076 SourceRange R; 10077 if (PDiag) { 10078 SFINAEArgString = ": "; 10079 R = SourceRange(PDiag->first, PDiag->first); 10080 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10081 } 10082 10083 S.Diag(Templated->getLocation(), 10084 diag::note_ovl_candidate_substitution_failure) 10085 << TemplateArgString << SFINAEArgString << R; 10086 MaybeEmitInheritedConstructorNote(S, Found); 10087 return; 10088 } 10089 10090 case Sema::TDK_DeducedMismatch: 10091 case Sema::TDK_DeducedMismatchNested: { 10092 // Format the template argument list into the argument string. 10093 SmallString<128> TemplateArgString; 10094 if (TemplateArgumentList *Args = 10095 DeductionFailure.getTemplateArgumentList()) { 10096 TemplateArgString = " "; 10097 TemplateArgString += S.getTemplateArgumentBindingsText( 10098 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10099 } 10100 10101 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10102 << (*DeductionFailure.getCallArgIndex() + 1) 10103 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10104 << TemplateArgString 10105 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10106 break; 10107 } 10108 10109 case Sema::TDK_NonDeducedMismatch: { 10110 // FIXME: Provide a source location to indicate what we couldn't match. 10111 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10112 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10113 if (FirstTA.getKind() == TemplateArgument::Template && 10114 SecondTA.getKind() == TemplateArgument::Template) { 10115 TemplateName FirstTN = FirstTA.getAsTemplate(); 10116 TemplateName SecondTN = SecondTA.getAsTemplate(); 10117 if (FirstTN.getKind() == TemplateName::Template && 10118 SecondTN.getKind() == TemplateName::Template) { 10119 if (FirstTN.getAsTemplateDecl()->getName() == 10120 SecondTN.getAsTemplateDecl()->getName()) { 10121 // FIXME: This fixes a bad diagnostic where both templates are named 10122 // the same. This particular case is a bit difficult since: 10123 // 1) It is passed as a string to the diagnostic printer. 10124 // 2) The diagnostic printer only attempts to find a better 10125 // name for types, not decls. 10126 // Ideally, this should folded into the diagnostic printer. 10127 S.Diag(Templated->getLocation(), 10128 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10129 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10130 return; 10131 } 10132 } 10133 } 10134 10135 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10136 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10137 return; 10138 10139 // FIXME: For generic lambda parameters, check if the function is a lambda 10140 // call operator, and if so, emit a prettier and more informative 10141 // diagnostic that mentions 'auto' and lambda in addition to 10142 // (or instead of?) the canonical template type parameters. 10143 S.Diag(Templated->getLocation(), 10144 diag::note_ovl_candidate_non_deduced_mismatch) 10145 << FirstTA << SecondTA; 10146 return; 10147 } 10148 // TODO: diagnose these individually, then kill off 10149 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10150 case Sema::TDK_MiscellaneousDeductionFailure: 10151 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10152 MaybeEmitInheritedConstructorNote(S, Found); 10153 return; 10154 case Sema::TDK_CUDATargetMismatch: 10155 S.Diag(Templated->getLocation(), 10156 diag::note_cuda_ovl_candidate_target_mismatch); 10157 return; 10158 } 10159 } 10160 10161 /// Diagnose a failed template-argument deduction, for function calls. 10162 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10163 unsigned NumArgs, 10164 bool TakingCandidateAddress) { 10165 unsigned TDK = Cand->DeductionFailure.Result; 10166 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10167 if (CheckArityMismatch(S, Cand, NumArgs)) 10168 return; 10169 } 10170 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10171 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10172 } 10173 10174 /// CUDA: diagnose an invalid call across targets. 10175 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10176 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10177 FunctionDecl *Callee = Cand->Function; 10178 10179 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10180 CalleeTarget = S.IdentifyCUDATarget(Callee); 10181 10182 std::string FnDesc; 10183 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10184 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10185 10186 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10187 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10188 << FnDesc /* Ignored */ 10189 << CalleeTarget << CallerTarget; 10190 10191 // This could be an implicit constructor for which we could not infer the 10192 // target due to a collsion. Diagnose that case. 10193 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10194 if (Meth != nullptr && Meth->isImplicit()) { 10195 CXXRecordDecl *ParentClass = Meth->getParent(); 10196 Sema::CXXSpecialMember CSM; 10197 10198 switch (FnKindPair.first) { 10199 default: 10200 return; 10201 case oc_implicit_default_constructor: 10202 CSM = Sema::CXXDefaultConstructor; 10203 break; 10204 case oc_implicit_copy_constructor: 10205 CSM = Sema::CXXCopyConstructor; 10206 break; 10207 case oc_implicit_move_constructor: 10208 CSM = Sema::CXXMoveConstructor; 10209 break; 10210 case oc_implicit_copy_assignment: 10211 CSM = Sema::CXXCopyAssignment; 10212 break; 10213 case oc_implicit_move_assignment: 10214 CSM = Sema::CXXMoveAssignment; 10215 break; 10216 }; 10217 10218 bool ConstRHS = false; 10219 if (Meth->getNumParams()) { 10220 if (const ReferenceType *RT = 10221 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10222 ConstRHS = RT->getPointeeType().isConstQualified(); 10223 } 10224 } 10225 10226 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10227 /* ConstRHS */ ConstRHS, 10228 /* Diagnose */ true); 10229 } 10230 } 10231 10232 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10233 FunctionDecl *Callee = Cand->Function; 10234 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10235 10236 S.Diag(Callee->getLocation(), 10237 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10238 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10239 } 10240 10241 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10242 FunctionDecl *Callee = Cand->Function; 10243 10244 S.Diag(Callee->getLocation(), 10245 diag::note_ovl_candidate_disabled_by_extension) 10246 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10247 } 10248 10249 /// Generates a 'note' diagnostic for an overload candidate. We've 10250 /// already generated a primary error at the call site. 10251 /// 10252 /// It really does need to be a single diagnostic with its caret 10253 /// pointed at the candidate declaration. Yes, this creates some 10254 /// major challenges of technical writing. Yes, this makes pointing 10255 /// out problems with specific arguments quite awkward. It's still 10256 /// better than generating twenty screens of text for every failed 10257 /// overload. 10258 /// 10259 /// It would be great to be able to express per-candidate problems 10260 /// more richly for those diagnostic clients that cared, but we'd 10261 /// still have to be just as careful with the default diagnostics. 10262 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10263 unsigned NumArgs, 10264 bool TakingCandidateAddress) { 10265 FunctionDecl *Fn = Cand->Function; 10266 10267 // Note deleted candidates, but only if they're viable. 10268 if (Cand->Viable) { 10269 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) { 10270 std::string FnDesc; 10271 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10272 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10273 10274 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10275 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10276 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10277 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10278 return; 10279 } 10280 10281 // We don't really have anything else to say about viable candidates. 10282 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10283 return; 10284 } 10285 10286 switch (Cand->FailureKind) { 10287 case ovl_fail_too_many_arguments: 10288 case ovl_fail_too_few_arguments: 10289 return DiagnoseArityMismatch(S, Cand, NumArgs); 10290 10291 case ovl_fail_bad_deduction: 10292 return DiagnoseBadDeduction(S, Cand, NumArgs, 10293 TakingCandidateAddress); 10294 10295 case ovl_fail_illegal_constructor: { 10296 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10297 << (Fn->getPrimaryTemplate() ? 1 : 0); 10298 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10299 return; 10300 } 10301 10302 case ovl_fail_trivial_conversion: 10303 case ovl_fail_bad_final_conversion: 10304 case ovl_fail_final_conversion_not_exact: 10305 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10306 10307 case ovl_fail_bad_conversion: { 10308 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10309 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10310 if (Cand->Conversions[I].isBad()) 10311 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10312 10313 // FIXME: this currently happens when we're called from SemaInit 10314 // when user-conversion overload fails. Figure out how to handle 10315 // those conditions and diagnose them well. 10316 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10317 } 10318 10319 case ovl_fail_bad_target: 10320 return DiagnoseBadTarget(S, Cand); 10321 10322 case ovl_fail_enable_if: 10323 return DiagnoseFailedEnableIfAttr(S, Cand); 10324 10325 case ovl_fail_ext_disabled: 10326 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10327 10328 case ovl_fail_inhctor_slice: 10329 // It's generally not interesting to note copy/move constructors here. 10330 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10331 return; 10332 S.Diag(Fn->getLocation(), 10333 diag::note_ovl_candidate_inherited_constructor_slice) 10334 << (Fn->getPrimaryTemplate() ? 1 : 0) 10335 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10336 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10337 return; 10338 10339 case ovl_fail_addr_not_available: { 10340 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10341 (void)Available; 10342 assert(!Available); 10343 break; 10344 } 10345 case ovl_non_default_multiversion_function: 10346 // Do nothing, these should simply be ignored. 10347 break; 10348 } 10349 } 10350 10351 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10352 // Desugar the type of the surrogate down to a function type, 10353 // retaining as many typedefs as possible while still showing 10354 // the function type (and, therefore, its parameter types). 10355 QualType FnType = Cand->Surrogate->getConversionType(); 10356 bool isLValueReference = false; 10357 bool isRValueReference = false; 10358 bool isPointer = false; 10359 if (const LValueReferenceType *FnTypeRef = 10360 FnType->getAs<LValueReferenceType>()) { 10361 FnType = FnTypeRef->getPointeeType(); 10362 isLValueReference = true; 10363 } else if (const RValueReferenceType *FnTypeRef = 10364 FnType->getAs<RValueReferenceType>()) { 10365 FnType = FnTypeRef->getPointeeType(); 10366 isRValueReference = true; 10367 } 10368 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10369 FnType = FnTypePtr->getPointeeType(); 10370 isPointer = true; 10371 } 10372 // Desugar down to a function type. 10373 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10374 // Reconstruct the pointer/reference as appropriate. 10375 if (isPointer) FnType = S.Context.getPointerType(FnType); 10376 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10377 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10378 10379 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10380 << FnType; 10381 } 10382 10383 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10384 SourceLocation OpLoc, 10385 OverloadCandidate *Cand) { 10386 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10387 std::string TypeStr("operator"); 10388 TypeStr += Opc; 10389 TypeStr += "("; 10390 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10391 if (Cand->Conversions.size() == 1) { 10392 TypeStr += ")"; 10393 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10394 } else { 10395 TypeStr += ", "; 10396 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10397 TypeStr += ")"; 10398 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10399 } 10400 } 10401 10402 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10403 OverloadCandidate *Cand) { 10404 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10405 if (ICS.isBad()) break; // all meaningless after first invalid 10406 if (!ICS.isAmbiguous()) continue; 10407 10408 ICS.DiagnoseAmbiguousConversion( 10409 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10410 } 10411 } 10412 10413 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10414 if (Cand->Function) 10415 return Cand->Function->getLocation(); 10416 if (Cand->IsSurrogate) 10417 return Cand->Surrogate->getLocation(); 10418 return SourceLocation(); 10419 } 10420 10421 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10422 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10423 case Sema::TDK_Success: 10424 case Sema::TDK_NonDependentConversionFailure: 10425 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10426 10427 case Sema::TDK_Invalid: 10428 case Sema::TDK_Incomplete: 10429 case Sema::TDK_IncompletePack: 10430 return 1; 10431 10432 case Sema::TDK_Underqualified: 10433 case Sema::TDK_Inconsistent: 10434 return 2; 10435 10436 case Sema::TDK_SubstitutionFailure: 10437 case Sema::TDK_DeducedMismatch: 10438 case Sema::TDK_DeducedMismatchNested: 10439 case Sema::TDK_NonDeducedMismatch: 10440 case Sema::TDK_MiscellaneousDeductionFailure: 10441 case Sema::TDK_CUDATargetMismatch: 10442 return 3; 10443 10444 case Sema::TDK_InstantiationDepth: 10445 return 4; 10446 10447 case Sema::TDK_InvalidExplicitArguments: 10448 return 5; 10449 10450 case Sema::TDK_TooManyArguments: 10451 case Sema::TDK_TooFewArguments: 10452 return 6; 10453 } 10454 llvm_unreachable("Unhandled deduction result"); 10455 } 10456 10457 namespace { 10458 struct CompareOverloadCandidatesForDisplay { 10459 Sema &S; 10460 SourceLocation Loc; 10461 size_t NumArgs; 10462 OverloadCandidateSet::CandidateSetKind CSK; 10463 10464 CompareOverloadCandidatesForDisplay( 10465 Sema &S, SourceLocation Loc, size_t NArgs, 10466 OverloadCandidateSet::CandidateSetKind CSK) 10467 : S(S), NumArgs(NArgs), CSK(CSK) {} 10468 10469 bool operator()(const OverloadCandidate *L, 10470 const OverloadCandidate *R) { 10471 // Fast-path this check. 10472 if (L == R) return false; 10473 10474 // Order first by viability. 10475 if (L->Viable) { 10476 if (!R->Viable) return true; 10477 10478 // TODO: introduce a tri-valued comparison for overload 10479 // candidates. Would be more worthwhile if we had a sort 10480 // that could exploit it. 10481 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10482 return true; 10483 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10484 return false; 10485 } else if (R->Viable) 10486 return false; 10487 10488 assert(L->Viable == R->Viable); 10489 10490 // Criteria by which we can sort non-viable candidates: 10491 if (!L->Viable) { 10492 // 1. Arity mismatches come after other candidates. 10493 if (L->FailureKind == ovl_fail_too_many_arguments || 10494 L->FailureKind == ovl_fail_too_few_arguments) { 10495 if (R->FailureKind == ovl_fail_too_many_arguments || 10496 R->FailureKind == ovl_fail_too_few_arguments) { 10497 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10498 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10499 if (LDist == RDist) { 10500 if (L->FailureKind == R->FailureKind) 10501 // Sort non-surrogates before surrogates. 10502 return !L->IsSurrogate && R->IsSurrogate; 10503 // Sort candidates requiring fewer parameters than there were 10504 // arguments given after candidates requiring more parameters 10505 // than there were arguments given. 10506 return L->FailureKind == ovl_fail_too_many_arguments; 10507 } 10508 return LDist < RDist; 10509 } 10510 return false; 10511 } 10512 if (R->FailureKind == ovl_fail_too_many_arguments || 10513 R->FailureKind == ovl_fail_too_few_arguments) 10514 return true; 10515 10516 // 2. Bad conversions come first and are ordered by the number 10517 // of bad conversions and quality of good conversions. 10518 if (L->FailureKind == ovl_fail_bad_conversion) { 10519 if (R->FailureKind != ovl_fail_bad_conversion) 10520 return true; 10521 10522 // The conversion that can be fixed with a smaller number of changes, 10523 // comes first. 10524 unsigned numLFixes = L->Fix.NumConversionsFixed; 10525 unsigned numRFixes = R->Fix.NumConversionsFixed; 10526 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10527 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10528 if (numLFixes != numRFixes) { 10529 return numLFixes < numRFixes; 10530 } 10531 10532 // If there's any ordering between the defined conversions... 10533 // FIXME: this might not be transitive. 10534 assert(L->Conversions.size() == R->Conversions.size()); 10535 10536 int leftBetter = 0; 10537 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10538 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10539 switch (CompareImplicitConversionSequences(S, Loc, 10540 L->Conversions[I], 10541 R->Conversions[I])) { 10542 case ImplicitConversionSequence::Better: 10543 leftBetter++; 10544 break; 10545 10546 case ImplicitConversionSequence::Worse: 10547 leftBetter--; 10548 break; 10549 10550 case ImplicitConversionSequence::Indistinguishable: 10551 break; 10552 } 10553 } 10554 if (leftBetter > 0) return true; 10555 if (leftBetter < 0) return false; 10556 10557 } else if (R->FailureKind == ovl_fail_bad_conversion) 10558 return false; 10559 10560 if (L->FailureKind == ovl_fail_bad_deduction) { 10561 if (R->FailureKind != ovl_fail_bad_deduction) 10562 return true; 10563 10564 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10565 return RankDeductionFailure(L->DeductionFailure) 10566 < RankDeductionFailure(R->DeductionFailure); 10567 } else if (R->FailureKind == ovl_fail_bad_deduction) 10568 return false; 10569 10570 // TODO: others? 10571 } 10572 10573 // Sort everything else by location. 10574 SourceLocation LLoc = GetLocationForCandidate(L); 10575 SourceLocation RLoc = GetLocationForCandidate(R); 10576 10577 // Put candidates without locations (e.g. builtins) at the end. 10578 if (LLoc.isInvalid()) return false; 10579 if (RLoc.isInvalid()) return true; 10580 10581 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10582 } 10583 }; 10584 } 10585 10586 /// CompleteNonViableCandidate - Normally, overload resolution only 10587 /// computes up to the first bad conversion. Produces the FixIt set if 10588 /// possible. 10589 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10590 ArrayRef<Expr *> Args) { 10591 assert(!Cand->Viable); 10592 10593 // Don't do anything on failures other than bad conversion. 10594 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10595 10596 // We only want the FixIts if all the arguments can be corrected. 10597 bool Unfixable = false; 10598 // Use a implicit copy initialization to check conversion fixes. 10599 Cand->Fix.setConversionChecker(TryCopyInitialization); 10600 10601 // Attempt to fix the bad conversion. 10602 unsigned ConvCount = Cand->Conversions.size(); 10603 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10604 ++ConvIdx) { 10605 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10606 if (Cand->Conversions[ConvIdx].isInitialized() && 10607 Cand->Conversions[ConvIdx].isBad()) { 10608 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10609 break; 10610 } 10611 } 10612 10613 // FIXME: this should probably be preserved from the overload 10614 // operation somehow. 10615 bool SuppressUserConversions = false; 10616 10617 unsigned ConvIdx = 0; 10618 ArrayRef<QualType> ParamTypes; 10619 10620 if (Cand->IsSurrogate) { 10621 QualType ConvType 10622 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10623 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10624 ConvType = ConvPtrType->getPointeeType(); 10625 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10626 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10627 ConvIdx = 1; 10628 } else if (Cand->Function) { 10629 ParamTypes = 10630 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10631 if (isa<CXXMethodDecl>(Cand->Function) && 10632 !isa<CXXConstructorDecl>(Cand->Function)) { 10633 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10634 ConvIdx = 1; 10635 } 10636 } else { 10637 // Builtin operator. 10638 assert(ConvCount <= 3); 10639 ParamTypes = Cand->BuiltinParamTypes; 10640 } 10641 10642 // Fill in the rest of the conversions. 10643 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10644 if (Cand->Conversions[ConvIdx].isInitialized()) { 10645 // We've already checked this conversion. 10646 } else if (ArgIdx < ParamTypes.size()) { 10647 if (ParamTypes[ArgIdx]->isDependentType()) 10648 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10649 Args[ArgIdx]->getType()); 10650 else { 10651 Cand->Conversions[ConvIdx] = 10652 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10653 SuppressUserConversions, 10654 /*InOverloadResolution=*/true, 10655 /*AllowObjCWritebackConversion=*/ 10656 S.getLangOpts().ObjCAutoRefCount); 10657 // Store the FixIt in the candidate if it exists. 10658 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10659 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10660 } 10661 } else 10662 Cand->Conversions[ConvIdx].setEllipsis(); 10663 } 10664 } 10665 10666 /// When overload resolution fails, prints diagnostic messages containing the 10667 /// candidates in the candidate set. 10668 void OverloadCandidateSet::NoteCandidates( 10669 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10670 StringRef Opc, SourceLocation OpLoc, 10671 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10672 // Sort the candidates by viability and position. Sorting directly would 10673 // be prohibitive, so we make a set of pointers and sort those. 10674 SmallVector<OverloadCandidate*, 32> Cands; 10675 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10676 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10677 if (!Filter(*Cand)) 10678 continue; 10679 if (Cand->Viable) 10680 Cands.push_back(Cand); 10681 else if (OCD == OCD_AllCandidates) { 10682 CompleteNonViableCandidate(S, Cand, Args); 10683 if (Cand->Function || Cand->IsSurrogate) 10684 Cands.push_back(Cand); 10685 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10686 // want to list every possible builtin candidate. 10687 } 10688 } 10689 10690 std::stable_sort(Cands.begin(), Cands.end(), 10691 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 10692 10693 bool ReportedAmbiguousConversions = false; 10694 10695 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10696 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10697 unsigned CandsShown = 0; 10698 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10699 OverloadCandidate *Cand = *I; 10700 10701 // Set an arbitrary limit on the number of candidate functions we'll spam 10702 // the user with. FIXME: This limit should depend on details of the 10703 // candidate list. 10704 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10705 break; 10706 } 10707 ++CandsShown; 10708 10709 if (Cand->Function) 10710 NoteFunctionCandidate(S, Cand, Args.size(), 10711 /*TakingCandidateAddress=*/false); 10712 else if (Cand->IsSurrogate) 10713 NoteSurrogateCandidate(S, Cand); 10714 else { 10715 assert(Cand->Viable && 10716 "Non-viable built-in candidates are not added to Cands."); 10717 // Generally we only see ambiguities including viable builtin 10718 // operators if overload resolution got screwed up by an 10719 // ambiguous user-defined conversion. 10720 // 10721 // FIXME: It's quite possible for different conversions to see 10722 // different ambiguities, though. 10723 if (!ReportedAmbiguousConversions) { 10724 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10725 ReportedAmbiguousConversions = true; 10726 } 10727 10728 // If this is a viable builtin, print it. 10729 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10730 } 10731 } 10732 10733 if (I != E) 10734 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10735 } 10736 10737 static SourceLocation 10738 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10739 return Cand->Specialization ? Cand->Specialization->getLocation() 10740 : SourceLocation(); 10741 } 10742 10743 namespace { 10744 struct CompareTemplateSpecCandidatesForDisplay { 10745 Sema &S; 10746 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10747 10748 bool operator()(const TemplateSpecCandidate *L, 10749 const TemplateSpecCandidate *R) { 10750 // Fast-path this check. 10751 if (L == R) 10752 return false; 10753 10754 // Assuming that both candidates are not matches... 10755 10756 // Sort by the ranking of deduction failures. 10757 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10758 return RankDeductionFailure(L->DeductionFailure) < 10759 RankDeductionFailure(R->DeductionFailure); 10760 10761 // Sort everything else by location. 10762 SourceLocation LLoc = GetLocationForCandidate(L); 10763 SourceLocation RLoc = GetLocationForCandidate(R); 10764 10765 // Put candidates without locations (e.g. builtins) at the end. 10766 if (LLoc.isInvalid()) 10767 return false; 10768 if (RLoc.isInvalid()) 10769 return true; 10770 10771 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10772 } 10773 }; 10774 } 10775 10776 /// Diagnose a template argument deduction failure. 10777 /// We are treating these failures as overload failures due to bad 10778 /// deductions. 10779 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10780 bool ForTakingAddress) { 10781 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10782 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10783 } 10784 10785 void TemplateSpecCandidateSet::destroyCandidates() { 10786 for (iterator i = begin(), e = end(); i != e; ++i) { 10787 i->DeductionFailure.Destroy(); 10788 } 10789 } 10790 10791 void TemplateSpecCandidateSet::clear() { 10792 destroyCandidates(); 10793 Candidates.clear(); 10794 } 10795 10796 /// NoteCandidates - When no template specialization match is found, prints 10797 /// diagnostic messages containing the non-matching specializations that form 10798 /// the candidate set. 10799 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10800 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10801 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10802 // Sort the candidates by position (assuming no candidate is a match). 10803 // Sorting directly would be prohibitive, so we make a set of pointers 10804 // and sort those. 10805 SmallVector<TemplateSpecCandidate *, 32> Cands; 10806 Cands.reserve(size()); 10807 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10808 if (Cand->Specialization) 10809 Cands.push_back(Cand); 10810 // Otherwise, this is a non-matching builtin candidate. We do not, 10811 // in general, want to list every possible builtin candidate. 10812 } 10813 10814 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 10815 10816 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10817 // for generalization purposes (?). 10818 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10819 10820 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10821 unsigned CandsShown = 0; 10822 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10823 TemplateSpecCandidate *Cand = *I; 10824 10825 // Set an arbitrary limit on the number of candidates we'll spam 10826 // the user with. FIXME: This limit should depend on details of the 10827 // candidate list. 10828 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10829 break; 10830 ++CandsShown; 10831 10832 assert(Cand->Specialization && 10833 "Non-matching built-in candidates are not added to Cands."); 10834 Cand->NoteDeductionFailure(S, ForTakingAddress); 10835 } 10836 10837 if (I != E) 10838 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10839 } 10840 10841 // [PossiblyAFunctionType] --> [Return] 10842 // NonFunctionType --> NonFunctionType 10843 // R (A) --> R(A) 10844 // R (*)(A) --> R (A) 10845 // R (&)(A) --> R (A) 10846 // R (S::*)(A) --> R (A) 10847 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10848 QualType Ret = PossiblyAFunctionType; 10849 if (const PointerType *ToTypePtr = 10850 PossiblyAFunctionType->getAs<PointerType>()) 10851 Ret = ToTypePtr->getPointeeType(); 10852 else if (const ReferenceType *ToTypeRef = 10853 PossiblyAFunctionType->getAs<ReferenceType>()) 10854 Ret = ToTypeRef->getPointeeType(); 10855 else if (const MemberPointerType *MemTypePtr = 10856 PossiblyAFunctionType->getAs<MemberPointerType>()) 10857 Ret = MemTypePtr->getPointeeType(); 10858 Ret = 10859 Context.getCanonicalType(Ret).getUnqualifiedType(); 10860 return Ret; 10861 } 10862 10863 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10864 bool Complain = true) { 10865 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10866 S.DeduceReturnType(FD, Loc, Complain)) 10867 return true; 10868 10869 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10870 if (S.getLangOpts().CPlusPlus17 && 10871 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10872 !S.ResolveExceptionSpec(Loc, FPT)) 10873 return true; 10874 10875 return false; 10876 } 10877 10878 namespace { 10879 // A helper class to help with address of function resolution 10880 // - allows us to avoid passing around all those ugly parameters 10881 class AddressOfFunctionResolver { 10882 Sema& S; 10883 Expr* SourceExpr; 10884 const QualType& TargetType; 10885 QualType TargetFunctionType; // Extracted function type from target type 10886 10887 bool Complain; 10888 //DeclAccessPair& ResultFunctionAccessPair; 10889 ASTContext& Context; 10890 10891 bool TargetTypeIsNonStaticMemberFunction; 10892 bool FoundNonTemplateFunction; 10893 bool StaticMemberFunctionFromBoundPointer; 10894 bool HasComplained; 10895 10896 OverloadExpr::FindResult OvlExprInfo; 10897 OverloadExpr *OvlExpr; 10898 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10899 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10900 TemplateSpecCandidateSet FailedCandidates; 10901 10902 public: 10903 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10904 const QualType &TargetType, bool Complain) 10905 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10906 Complain(Complain), Context(S.getASTContext()), 10907 TargetTypeIsNonStaticMemberFunction( 10908 !!TargetType->getAs<MemberPointerType>()), 10909 FoundNonTemplateFunction(false), 10910 StaticMemberFunctionFromBoundPointer(false), 10911 HasComplained(false), 10912 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10913 OvlExpr(OvlExprInfo.Expression), 10914 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10915 ExtractUnqualifiedFunctionTypeFromTargetType(); 10916 10917 if (TargetFunctionType->isFunctionType()) { 10918 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10919 if (!UME->isImplicitAccess() && 10920 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10921 StaticMemberFunctionFromBoundPointer = true; 10922 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10923 DeclAccessPair dap; 10924 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10925 OvlExpr, false, &dap)) { 10926 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10927 if (!Method->isStatic()) { 10928 // If the target type is a non-function type and the function found 10929 // is a non-static member function, pretend as if that was the 10930 // target, it's the only possible type to end up with. 10931 TargetTypeIsNonStaticMemberFunction = true; 10932 10933 // And skip adding the function if its not in the proper form. 10934 // We'll diagnose this due to an empty set of functions. 10935 if (!OvlExprInfo.HasFormOfMemberPointer) 10936 return; 10937 } 10938 10939 Matches.push_back(std::make_pair(dap, Fn)); 10940 } 10941 return; 10942 } 10943 10944 if (OvlExpr->hasExplicitTemplateArgs()) 10945 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10946 10947 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10948 // C++ [over.over]p4: 10949 // If more than one function is selected, [...] 10950 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10951 if (FoundNonTemplateFunction) 10952 EliminateAllTemplateMatches(); 10953 else 10954 EliminateAllExceptMostSpecializedTemplate(); 10955 } 10956 } 10957 10958 if (S.getLangOpts().CUDA && Matches.size() > 1) 10959 EliminateSuboptimalCudaMatches(); 10960 } 10961 10962 bool hasComplained() const { return HasComplained; } 10963 10964 private: 10965 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10966 QualType Discard; 10967 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10968 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 10969 } 10970 10971 /// \return true if A is considered a better overload candidate for the 10972 /// desired type than B. 10973 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10974 // If A doesn't have exactly the correct type, we don't want to classify it 10975 // as "better" than anything else. This way, the user is required to 10976 // disambiguate for us if there are multiple candidates and no exact match. 10977 return candidateHasExactlyCorrectType(A) && 10978 (!candidateHasExactlyCorrectType(B) || 10979 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10980 } 10981 10982 /// \return true if we were able to eliminate all but one overload candidate, 10983 /// false otherwise. 10984 bool eliminiateSuboptimalOverloadCandidates() { 10985 // Same algorithm as overload resolution -- one pass to pick the "best", 10986 // another pass to be sure that nothing is better than the best. 10987 auto Best = Matches.begin(); 10988 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10989 if (isBetterCandidate(I->second, Best->second)) 10990 Best = I; 10991 10992 const FunctionDecl *BestFn = Best->second; 10993 auto IsBestOrInferiorToBest = [this, BestFn]( 10994 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10995 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10996 }; 10997 10998 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10999 // option, so we can potentially give the user a better error 11000 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11001 return false; 11002 Matches[0] = *Best; 11003 Matches.resize(1); 11004 return true; 11005 } 11006 11007 bool isTargetTypeAFunction() const { 11008 return TargetFunctionType->isFunctionType(); 11009 } 11010 11011 // [ToType] [Return] 11012 11013 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11014 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11015 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11016 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11017 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11018 } 11019 11020 // return true if any matching specializations were found 11021 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11022 const DeclAccessPair& CurAccessFunPair) { 11023 if (CXXMethodDecl *Method 11024 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11025 // Skip non-static function templates when converting to pointer, and 11026 // static when converting to member pointer. 11027 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11028 return false; 11029 } 11030 else if (TargetTypeIsNonStaticMemberFunction) 11031 return false; 11032 11033 // C++ [over.over]p2: 11034 // If the name is a function template, template argument deduction is 11035 // done (14.8.2.2), and if the argument deduction succeeds, the 11036 // resulting template argument list is used to generate a single 11037 // function template specialization, which is added to the set of 11038 // overloaded functions considered. 11039 FunctionDecl *Specialization = nullptr; 11040 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11041 if (Sema::TemplateDeductionResult Result 11042 = S.DeduceTemplateArguments(FunctionTemplate, 11043 &OvlExplicitTemplateArgs, 11044 TargetFunctionType, Specialization, 11045 Info, /*IsAddressOfFunction*/true)) { 11046 // Make a note of the failed deduction for diagnostics. 11047 FailedCandidates.addCandidate() 11048 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11049 MakeDeductionFailureInfo(Context, Result, Info)); 11050 return false; 11051 } 11052 11053 // Template argument deduction ensures that we have an exact match or 11054 // compatible pointer-to-function arguments that would be adjusted by ICS. 11055 // This function template specicalization works. 11056 assert(S.isSameOrCompatibleFunctionType( 11057 Context.getCanonicalType(Specialization->getType()), 11058 Context.getCanonicalType(TargetFunctionType))); 11059 11060 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11061 return false; 11062 11063 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11064 return true; 11065 } 11066 11067 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11068 const DeclAccessPair& CurAccessFunPair) { 11069 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11070 // Skip non-static functions when converting to pointer, and static 11071 // when converting to member pointer. 11072 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11073 return false; 11074 } 11075 else if (TargetTypeIsNonStaticMemberFunction) 11076 return false; 11077 11078 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11079 if (S.getLangOpts().CUDA) 11080 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11081 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11082 return false; 11083 if (FunDecl->isMultiVersion()) { 11084 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11085 if (TA && !TA->isDefaultVersion()) 11086 return false; 11087 } 11088 11089 // If any candidate has a placeholder return type, trigger its deduction 11090 // now. 11091 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11092 Complain)) { 11093 HasComplained |= Complain; 11094 return false; 11095 } 11096 11097 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11098 return false; 11099 11100 // If we're in C, we need to support types that aren't exactly identical. 11101 if (!S.getLangOpts().CPlusPlus || 11102 candidateHasExactlyCorrectType(FunDecl)) { 11103 Matches.push_back(std::make_pair( 11104 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11105 FoundNonTemplateFunction = true; 11106 return true; 11107 } 11108 } 11109 11110 return false; 11111 } 11112 11113 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11114 bool Ret = false; 11115 11116 // If the overload expression doesn't have the form of a pointer to 11117 // member, don't try to convert it to a pointer-to-member type. 11118 if (IsInvalidFormOfPointerToMemberFunction()) 11119 return false; 11120 11121 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11122 E = OvlExpr->decls_end(); 11123 I != E; ++I) { 11124 // Look through any using declarations to find the underlying function. 11125 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11126 11127 // C++ [over.over]p3: 11128 // Non-member functions and static member functions match 11129 // targets of type "pointer-to-function" or "reference-to-function." 11130 // Nonstatic member functions match targets of 11131 // type "pointer-to-member-function." 11132 // Note that according to DR 247, the containing class does not matter. 11133 if (FunctionTemplateDecl *FunctionTemplate 11134 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11135 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11136 Ret = true; 11137 } 11138 // If we have explicit template arguments supplied, skip non-templates. 11139 else if (!OvlExpr->hasExplicitTemplateArgs() && 11140 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11141 Ret = true; 11142 } 11143 assert(Ret || Matches.empty()); 11144 return Ret; 11145 } 11146 11147 void EliminateAllExceptMostSpecializedTemplate() { 11148 // [...] and any given function template specialization F1 is 11149 // eliminated if the set contains a second function template 11150 // specialization whose function template is more specialized 11151 // than the function template of F1 according to the partial 11152 // ordering rules of 14.5.5.2. 11153 11154 // The algorithm specified above is quadratic. We instead use a 11155 // two-pass algorithm (similar to the one used to identify the 11156 // best viable function in an overload set) that identifies the 11157 // best function template (if it exists). 11158 11159 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11160 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11161 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11162 11163 // TODO: It looks like FailedCandidates does not serve much purpose 11164 // here, since the no_viable diagnostic has index 0. 11165 UnresolvedSetIterator Result = S.getMostSpecialized( 11166 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11167 SourceExpr->getBeginLoc(), S.PDiag(), 11168 S.PDiag(diag::err_addr_ovl_ambiguous) 11169 << Matches[0].second->getDeclName(), 11170 S.PDiag(diag::note_ovl_candidate) 11171 << (unsigned)oc_function << (unsigned)ocs_described_template, 11172 Complain, TargetFunctionType); 11173 11174 if (Result != MatchesCopy.end()) { 11175 // Make it the first and only element 11176 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11177 Matches[0].second = cast<FunctionDecl>(*Result); 11178 Matches.resize(1); 11179 } else 11180 HasComplained |= Complain; 11181 } 11182 11183 void EliminateAllTemplateMatches() { 11184 // [...] any function template specializations in the set are 11185 // eliminated if the set also contains a non-template function, [...] 11186 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11187 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11188 ++I; 11189 else { 11190 Matches[I] = Matches[--N]; 11191 Matches.resize(N); 11192 } 11193 } 11194 } 11195 11196 void EliminateSuboptimalCudaMatches() { 11197 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11198 } 11199 11200 public: 11201 void ComplainNoMatchesFound() const { 11202 assert(Matches.empty()); 11203 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11204 << OvlExpr->getName() << TargetFunctionType 11205 << OvlExpr->getSourceRange(); 11206 if (FailedCandidates.empty()) 11207 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11208 /*TakingAddress=*/true); 11209 else { 11210 // We have some deduction failure messages. Use them to diagnose 11211 // the function templates, and diagnose the non-template candidates 11212 // normally. 11213 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11214 IEnd = OvlExpr->decls_end(); 11215 I != IEnd; ++I) 11216 if (FunctionDecl *Fun = 11217 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11218 if (!functionHasPassObjectSizeParams(Fun)) 11219 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11220 /*TakingAddress=*/true); 11221 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11222 } 11223 } 11224 11225 bool IsInvalidFormOfPointerToMemberFunction() const { 11226 return TargetTypeIsNonStaticMemberFunction && 11227 !OvlExprInfo.HasFormOfMemberPointer; 11228 } 11229 11230 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11231 // TODO: Should we condition this on whether any functions might 11232 // have matched, or is it more appropriate to do that in callers? 11233 // TODO: a fixit wouldn't hurt. 11234 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11235 << TargetType << OvlExpr->getSourceRange(); 11236 } 11237 11238 bool IsStaticMemberFunctionFromBoundPointer() const { 11239 return StaticMemberFunctionFromBoundPointer; 11240 } 11241 11242 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11243 S.Diag(OvlExpr->getBeginLoc(), 11244 diag::err_invalid_form_pointer_member_function) 11245 << OvlExpr->getSourceRange(); 11246 } 11247 11248 void ComplainOfInvalidConversion() const { 11249 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11250 << OvlExpr->getName() << TargetType; 11251 } 11252 11253 void ComplainMultipleMatchesFound() const { 11254 assert(Matches.size() > 1); 11255 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11256 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11257 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11258 /*TakingAddress=*/true); 11259 } 11260 11261 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11262 11263 int getNumMatches() const { return Matches.size(); } 11264 11265 FunctionDecl* getMatchingFunctionDecl() const { 11266 if (Matches.size() != 1) return nullptr; 11267 return Matches[0].second; 11268 } 11269 11270 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11271 if (Matches.size() != 1) return nullptr; 11272 return &Matches[0].first; 11273 } 11274 }; 11275 } 11276 11277 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11278 /// an overloaded function (C++ [over.over]), where @p From is an 11279 /// expression with overloaded function type and @p ToType is the type 11280 /// we're trying to resolve to. For example: 11281 /// 11282 /// @code 11283 /// int f(double); 11284 /// int f(int); 11285 /// 11286 /// int (*pfd)(double) = f; // selects f(double) 11287 /// @endcode 11288 /// 11289 /// This routine returns the resulting FunctionDecl if it could be 11290 /// resolved, and NULL otherwise. When @p Complain is true, this 11291 /// routine will emit diagnostics if there is an error. 11292 FunctionDecl * 11293 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11294 QualType TargetType, 11295 bool Complain, 11296 DeclAccessPair &FoundResult, 11297 bool *pHadMultipleCandidates) { 11298 assert(AddressOfExpr->getType() == Context.OverloadTy); 11299 11300 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11301 Complain); 11302 int NumMatches = Resolver.getNumMatches(); 11303 FunctionDecl *Fn = nullptr; 11304 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11305 if (NumMatches == 0 && ShouldComplain) { 11306 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11307 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11308 else 11309 Resolver.ComplainNoMatchesFound(); 11310 } 11311 else if (NumMatches > 1 && ShouldComplain) 11312 Resolver.ComplainMultipleMatchesFound(); 11313 else if (NumMatches == 1) { 11314 Fn = Resolver.getMatchingFunctionDecl(); 11315 assert(Fn); 11316 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11317 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11318 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11319 if (Complain) { 11320 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11321 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11322 else 11323 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11324 } 11325 } 11326 11327 if (pHadMultipleCandidates) 11328 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11329 return Fn; 11330 } 11331 11332 /// Given an expression that refers to an overloaded function, try to 11333 /// resolve that function to a single function that can have its address taken. 11334 /// This will modify `Pair` iff it returns non-null. 11335 /// 11336 /// This routine can only realistically succeed if all but one candidates in the 11337 /// overload set for SrcExpr cannot have their addresses taken. 11338 FunctionDecl * 11339 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11340 DeclAccessPair &Pair) { 11341 OverloadExpr::FindResult R = OverloadExpr::find(E); 11342 OverloadExpr *Ovl = R.Expression; 11343 FunctionDecl *Result = nullptr; 11344 DeclAccessPair DAP; 11345 // Don't use the AddressOfResolver because we're specifically looking for 11346 // cases where we have one overload candidate that lacks 11347 // enable_if/pass_object_size/... 11348 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11349 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11350 if (!FD) 11351 return nullptr; 11352 11353 if (!checkAddressOfFunctionIsAvailable(FD)) 11354 continue; 11355 11356 // We have more than one result; quit. 11357 if (Result) 11358 return nullptr; 11359 DAP = I.getPair(); 11360 Result = FD; 11361 } 11362 11363 if (Result) 11364 Pair = DAP; 11365 return Result; 11366 } 11367 11368 /// Given an overloaded function, tries to turn it into a non-overloaded 11369 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11370 /// will perform access checks, diagnose the use of the resultant decl, and, if 11371 /// requested, potentially perform a function-to-pointer decay. 11372 /// 11373 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11374 /// Otherwise, returns true. This may emit diagnostics and return true. 11375 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11376 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11377 Expr *E = SrcExpr.get(); 11378 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11379 11380 DeclAccessPair DAP; 11381 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11382 if (!Found || Found->isCPUDispatchMultiVersion() || 11383 Found->isCPUSpecificMultiVersion()) 11384 return false; 11385 11386 // Emitting multiple diagnostics for a function that is both inaccessible and 11387 // unavailable is consistent with our behavior elsewhere. So, always check 11388 // for both. 11389 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11390 CheckAddressOfMemberAccess(E, DAP); 11391 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11392 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11393 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11394 else 11395 SrcExpr = Fixed; 11396 return true; 11397 } 11398 11399 /// Given an expression that refers to an overloaded function, try to 11400 /// resolve that overloaded function expression down to a single function. 11401 /// 11402 /// This routine can only resolve template-ids that refer to a single function 11403 /// template, where that template-id refers to a single template whose template 11404 /// arguments are either provided by the template-id or have defaults, 11405 /// as described in C++0x [temp.arg.explicit]p3. 11406 /// 11407 /// If no template-ids are found, no diagnostics are emitted and NULL is 11408 /// returned. 11409 FunctionDecl * 11410 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11411 bool Complain, 11412 DeclAccessPair *FoundResult) { 11413 // C++ [over.over]p1: 11414 // [...] [Note: any redundant set of parentheses surrounding the 11415 // overloaded function name is ignored (5.1). ] 11416 // C++ [over.over]p1: 11417 // [...] The overloaded function name can be preceded by the & 11418 // operator. 11419 11420 // If we didn't actually find any template-ids, we're done. 11421 if (!ovl->hasExplicitTemplateArgs()) 11422 return nullptr; 11423 11424 TemplateArgumentListInfo ExplicitTemplateArgs; 11425 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11426 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11427 11428 // Look through all of the overloaded functions, searching for one 11429 // whose type matches exactly. 11430 FunctionDecl *Matched = nullptr; 11431 for (UnresolvedSetIterator I = ovl->decls_begin(), 11432 E = ovl->decls_end(); I != E; ++I) { 11433 // C++0x [temp.arg.explicit]p3: 11434 // [...] In contexts where deduction is done and fails, or in contexts 11435 // where deduction is not done, if a template argument list is 11436 // specified and it, along with any default template arguments, 11437 // identifies a single function template specialization, then the 11438 // template-id is an lvalue for the function template specialization. 11439 FunctionTemplateDecl *FunctionTemplate 11440 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11441 11442 // C++ [over.over]p2: 11443 // If the name is a function template, template argument deduction is 11444 // done (14.8.2.2), and if the argument deduction succeeds, the 11445 // resulting template argument list is used to generate a single 11446 // function template specialization, which is added to the set of 11447 // overloaded functions considered. 11448 FunctionDecl *Specialization = nullptr; 11449 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11450 if (TemplateDeductionResult Result 11451 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11452 Specialization, Info, 11453 /*IsAddressOfFunction*/true)) { 11454 // Make a note of the failed deduction for diagnostics. 11455 // TODO: Actually use the failed-deduction info? 11456 FailedCandidates.addCandidate() 11457 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11458 MakeDeductionFailureInfo(Context, Result, Info)); 11459 continue; 11460 } 11461 11462 assert(Specialization && "no specialization and no error?"); 11463 11464 // Multiple matches; we can't resolve to a single declaration. 11465 if (Matched) { 11466 if (Complain) { 11467 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11468 << ovl->getName(); 11469 NoteAllOverloadCandidates(ovl); 11470 } 11471 return nullptr; 11472 } 11473 11474 Matched = Specialization; 11475 if (FoundResult) *FoundResult = I.getPair(); 11476 } 11477 11478 if (Matched && 11479 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11480 return nullptr; 11481 11482 return Matched; 11483 } 11484 11485 // Resolve and fix an overloaded expression that can be resolved 11486 // because it identifies a single function template specialization. 11487 // 11488 // Last three arguments should only be supplied if Complain = true 11489 // 11490 // Return true if it was logically possible to so resolve the 11491 // expression, regardless of whether or not it succeeded. Always 11492 // returns true if 'complain' is set. 11493 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11494 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11495 bool complain, SourceRange OpRangeForComplaining, 11496 QualType DestTypeForComplaining, 11497 unsigned DiagIDForComplaining) { 11498 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11499 11500 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11501 11502 DeclAccessPair found; 11503 ExprResult SingleFunctionExpression; 11504 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11505 ovl.Expression, /*complain*/ false, &found)) { 11506 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11507 SrcExpr = ExprError(); 11508 return true; 11509 } 11510 11511 // It is only correct to resolve to an instance method if we're 11512 // resolving a form that's permitted to be a pointer to member. 11513 // Otherwise we'll end up making a bound member expression, which 11514 // is illegal in all the contexts we resolve like this. 11515 if (!ovl.HasFormOfMemberPointer && 11516 isa<CXXMethodDecl>(fn) && 11517 cast<CXXMethodDecl>(fn)->isInstance()) { 11518 if (!complain) return false; 11519 11520 Diag(ovl.Expression->getExprLoc(), 11521 diag::err_bound_member_function) 11522 << 0 << ovl.Expression->getSourceRange(); 11523 11524 // TODO: I believe we only end up here if there's a mix of 11525 // static and non-static candidates (otherwise the expression 11526 // would have 'bound member' type, not 'overload' type). 11527 // Ideally we would note which candidate was chosen and why 11528 // the static candidates were rejected. 11529 SrcExpr = ExprError(); 11530 return true; 11531 } 11532 11533 // Fix the expression to refer to 'fn'. 11534 SingleFunctionExpression = 11535 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11536 11537 // If desired, do function-to-pointer decay. 11538 if (doFunctionPointerConverion) { 11539 SingleFunctionExpression = 11540 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11541 if (SingleFunctionExpression.isInvalid()) { 11542 SrcExpr = ExprError(); 11543 return true; 11544 } 11545 } 11546 } 11547 11548 if (!SingleFunctionExpression.isUsable()) { 11549 if (complain) { 11550 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11551 << ovl.Expression->getName() 11552 << DestTypeForComplaining 11553 << OpRangeForComplaining 11554 << ovl.Expression->getQualifierLoc().getSourceRange(); 11555 NoteAllOverloadCandidates(SrcExpr.get()); 11556 11557 SrcExpr = ExprError(); 11558 return true; 11559 } 11560 11561 return false; 11562 } 11563 11564 SrcExpr = SingleFunctionExpression; 11565 return true; 11566 } 11567 11568 /// Add a single candidate to the overload set. 11569 static void AddOverloadedCallCandidate(Sema &S, 11570 DeclAccessPair FoundDecl, 11571 TemplateArgumentListInfo *ExplicitTemplateArgs, 11572 ArrayRef<Expr *> Args, 11573 OverloadCandidateSet &CandidateSet, 11574 bool PartialOverloading, 11575 bool KnownValid) { 11576 NamedDecl *Callee = FoundDecl.getDecl(); 11577 if (isa<UsingShadowDecl>(Callee)) 11578 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11579 11580 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11581 if (ExplicitTemplateArgs) { 11582 assert(!KnownValid && "Explicit template arguments?"); 11583 return; 11584 } 11585 // Prevent ill-formed function decls to be added as overload candidates. 11586 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11587 return; 11588 11589 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11590 /*SuppressUsedConversions=*/false, 11591 PartialOverloading); 11592 return; 11593 } 11594 11595 if (FunctionTemplateDecl *FuncTemplate 11596 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11597 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11598 ExplicitTemplateArgs, Args, CandidateSet, 11599 /*SuppressUsedConversions=*/false, 11600 PartialOverloading); 11601 return; 11602 } 11603 11604 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11605 } 11606 11607 /// Add the overload candidates named by callee and/or found by argument 11608 /// dependent lookup to the given overload set. 11609 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11610 ArrayRef<Expr *> Args, 11611 OverloadCandidateSet &CandidateSet, 11612 bool PartialOverloading) { 11613 11614 #ifndef NDEBUG 11615 // Verify that ArgumentDependentLookup is consistent with the rules 11616 // in C++0x [basic.lookup.argdep]p3: 11617 // 11618 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11619 // and let Y be the lookup set produced by argument dependent 11620 // lookup (defined as follows). If X contains 11621 // 11622 // -- a declaration of a class member, or 11623 // 11624 // -- a block-scope function declaration that is not a 11625 // using-declaration, or 11626 // 11627 // -- a declaration that is neither a function or a function 11628 // template 11629 // 11630 // then Y is empty. 11631 11632 if (ULE->requiresADL()) { 11633 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11634 E = ULE->decls_end(); I != E; ++I) { 11635 assert(!(*I)->getDeclContext()->isRecord()); 11636 assert(isa<UsingShadowDecl>(*I) || 11637 !(*I)->getDeclContext()->isFunctionOrMethod()); 11638 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11639 } 11640 } 11641 #endif 11642 11643 // It would be nice to avoid this copy. 11644 TemplateArgumentListInfo TABuffer; 11645 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11646 if (ULE->hasExplicitTemplateArgs()) { 11647 ULE->copyTemplateArgumentsInto(TABuffer); 11648 ExplicitTemplateArgs = &TABuffer; 11649 } 11650 11651 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11652 E = ULE->decls_end(); I != E; ++I) 11653 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11654 CandidateSet, PartialOverloading, 11655 /*KnownValid*/ true); 11656 11657 if (ULE->requiresADL()) 11658 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11659 Args, ExplicitTemplateArgs, 11660 CandidateSet, PartialOverloading); 11661 } 11662 11663 /// Determine whether a declaration with the specified name could be moved into 11664 /// a different namespace. 11665 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11666 switch (Name.getCXXOverloadedOperator()) { 11667 case OO_New: case OO_Array_New: 11668 case OO_Delete: case OO_Array_Delete: 11669 return false; 11670 11671 default: 11672 return true; 11673 } 11674 } 11675 11676 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11677 /// template, where the non-dependent name was declared after the template 11678 /// was defined. This is common in code written for a compilers which do not 11679 /// correctly implement two-stage name lookup. 11680 /// 11681 /// Returns true if a viable candidate was found and a diagnostic was issued. 11682 static bool 11683 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11684 const CXXScopeSpec &SS, LookupResult &R, 11685 OverloadCandidateSet::CandidateSetKind CSK, 11686 TemplateArgumentListInfo *ExplicitTemplateArgs, 11687 ArrayRef<Expr *> Args, 11688 bool *DoDiagnoseEmptyLookup = nullptr) { 11689 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 11690 return false; 11691 11692 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11693 if (DC->isTransparentContext()) 11694 continue; 11695 11696 SemaRef.LookupQualifiedName(R, DC); 11697 11698 if (!R.empty()) { 11699 R.suppressDiagnostics(); 11700 11701 if (isa<CXXRecordDecl>(DC)) { 11702 // Don't diagnose names we find in classes; we get much better 11703 // diagnostics for these from DiagnoseEmptyLookup. 11704 R.clear(); 11705 if (DoDiagnoseEmptyLookup) 11706 *DoDiagnoseEmptyLookup = true; 11707 return false; 11708 } 11709 11710 OverloadCandidateSet Candidates(FnLoc, CSK); 11711 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11712 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11713 ExplicitTemplateArgs, Args, 11714 Candidates, false, /*KnownValid*/ false); 11715 11716 OverloadCandidateSet::iterator Best; 11717 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11718 // No viable functions. Don't bother the user with notes for functions 11719 // which don't work and shouldn't be found anyway. 11720 R.clear(); 11721 return false; 11722 } 11723 11724 // Find the namespaces where ADL would have looked, and suggest 11725 // declaring the function there instead. 11726 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11727 Sema::AssociatedClassSet AssociatedClasses; 11728 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11729 AssociatedNamespaces, 11730 AssociatedClasses); 11731 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11732 if (canBeDeclaredInNamespace(R.getLookupName())) { 11733 DeclContext *Std = SemaRef.getStdNamespace(); 11734 for (Sema::AssociatedNamespaceSet::iterator 11735 it = AssociatedNamespaces.begin(), 11736 end = AssociatedNamespaces.end(); it != end; ++it) { 11737 // Never suggest declaring a function within namespace 'std'. 11738 if (Std && Std->Encloses(*it)) 11739 continue; 11740 11741 // Never suggest declaring a function within a namespace with a 11742 // reserved name, like __gnu_cxx. 11743 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11744 if (NS && 11745 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11746 continue; 11747 11748 SuggestedNamespaces.insert(*it); 11749 } 11750 } 11751 11752 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11753 << R.getLookupName(); 11754 if (SuggestedNamespaces.empty()) { 11755 SemaRef.Diag(Best->Function->getLocation(), 11756 diag::note_not_found_by_two_phase_lookup) 11757 << R.getLookupName() << 0; 11758 } else if (SuggestedNamespaces.size() == 1) { 11759 SemaRef.Diag(Best->Function->getLocation(), 11760 diag::note_not_found_by_two_phase_lookup) 11761 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11762 } else { 11763 // FIXME: It would be useful to list the associated namespaces here, 11764 // but the diagnostics infrastructure doesn't provide a way to produce 11765 // a localized representation of a list of items. 11766 SemaRef.Diag(Best->Function->getLocation(), 11767 diag::note_not_found_by_two_phase_lookup) 11768 << R.getLookupName() << 2; 11769 } 11770 11771 // Try to recover by calling this function. 11772 return true; 11773 } 11774 11775 R.clear(); 11776 } 11777 11778 return false; 11779 } 11780 11781 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11782 /// template, where the non-dependent operator was declared after the template 11783 /// was defined. 11784 /// 11785 /// Returns true if a viable candidate was found and a diagnostic was issued. 11786 static bool 11787 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11788 SourceLocation OpLoc, 11789 ArrayRef<Expr *> Args) { 11790 DeclarationName OpName = 11791 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11792 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11793 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11794 OverloadCandidateSet::CSK_Operator, 11795 /*ExplicitTemplateArgs=*/nullptr, Args); 11796 } 11797 11798 namespace { 11799 class BuildRecoveryCallExprRAII { 11800 Sema &SemaRef; 11801 public: 11802 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11803 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11804 SemaRef.IsBuildingRecoveryCallExpr = true; 11805 } 11806 11807 ~BuildRecoveryCallExprRAII() { 11808 SemaRef.IsBuildingRecoveryCallExpr = false; 11809 } 11810 }; 11811 11812 } 11813 11814 static std::unique_ptr<CorrectionCandidateCallback> 11815 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11816 bool HasTemplateArgs, bool AllowTypoCorrection) { 11817 if (!AllowTypoCorrection) 11818 return llvm::make_unique<NoTypoCorrectionCCC>(); 11819 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11820 HasTemplateArgs, ME); 11821 } 11822 11823 /// Attempts to recover from a call where no functions were found. 11824 /// 11825 /// Returns true if new candidates were found. 11826 static ExprResult 11827 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11828 UnresolvedLookupExpr *ULE, 11829 SourceLocation LParenLoc, 11830 MutableArrayRef<Expr *> Args, 11831 SourceLocation RParenLoc, 11832 bool EmptyLookup, bool AllowTypoCorrection) { 11833 // Do not try to recover if it is already building a recovery call. 11834 // This stops infinite loops for template instantiations like 11835 // 11836 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11837 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11838 // 11839 if (SemaRef.IsBuildingRecoveryCallExpr) 11840 return ExprError(); 11841 BuildRecoveryCallExprRAII RCE(SemaRef); 11842 11843 CXXScopeSpec SS; 11844 SS.Adopt(ULE->getQualifierLoc()); 11845 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11846 11847 TemplateArgumentListInfo TABuffer; 11848 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11849 if (ULE->hasExplicitTemplateArgs()) { 11850 ULE->copyTemplateArgumentsInto(TABuffer); 11851 ExplicitTemplateArgs = &TABuffer; 11852 } 11853 11854 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11855 Sema::LookupOrdinaryName); 11856 bool DoDiagnoseEmptyLookup = EmptyLookup; 11857 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11858 OverloadCandidateSet::CSK_Normal, 11859 ExplicitTemplateArgs, Args, 11860 &DoDiagnoseEmptyLookup) && 11861 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11862 S, SS, R, 11863 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11864 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11865 ExplicitTemplateArgs, Args))) 11866 return ExprError(); 11867 11868 assert(!R.empty() && "lookup results empty despite recovery"); 11869 11870 // If recovery created an ambiguity, just bail out. 11871 if (R.isAmbiguous()) { 11872 R.suppressDiagnostics(); 11873 return ExprError(); 11874 } 11875 11876 // Build an implicit member call if appropriate. Just drop the 11877 // casts and such from the call, we don't really care. 11878 ExprResult NewFn = ExprError(); 11879 if ((*R.begin())->isCXXClassMember()) 11880 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11881 ExplicitTemplateArgs, S); 11882 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11883 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11884 ExplicitTemplateArgs); 11885 else 11886 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11887 11888 if (NewFn.isInvalid()) 11889 return ExprError(); 11890 11891 // This shouldn't cause an infinite loop because we're giving it 11892 // an expression with viable lookup results, which should never 11893 // end up here. 11894 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11895 MultiExprArg(Args.data(), Args.size()), 11896 RParenLoc); 11897 } 11898 11899 /// Constructs and populates an OverloadedCandidateSet from 11900 /// the given function. 11901 /// \returns true when an the ExprResult output parameter has been set. 11902 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11903 UnresolvedLookupExpr *ULE, 11904 MultiExprArg Args, 11905 SourceLocation RParenLoc, 11906 OverloadCandidateSet *CandidateSet, 11907 ExprResult *Result) { 11908 #ifndef NDEBUG 11909 if (ULE->requiresADL()) { 11910 // To do ADL, we must have found an unqualified name. 11911 assert(!ULE->getQualifier() && "qualified name with ADL"); 11912 11913 // We don't perform ADL for implicit declarations of builtins. 11914 // Verify that this was correctly set up. 11915 FunctionDecl *F; 11916 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11917 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11918 F->getBuiltinID() && F->isImplicit()) 11919 llvm_unreachable("performing ADL for builtin"); 11920 11921 // We don't perform ADL in C. 11922 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11923 } 11924 #endif 11925 11926 UnbridgedCastsSet UnbridgedCasts; 11927 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11928 *Result = ExprError(); 11929 return true; 11930 } 11931 11932 // Add the functions denoted by the callee to the set of candidate 11933 // functions, including those from argument-dependent lookup. 11934 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11935 11936 if (getLangOpts().MSVCCompat && 11937 CurContext->isDependentContext() && !isSFINAEContext() && 11938 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11939 11940 OverloadCandidateSet::iterator Best; 11941 if (CandidateSet->empty() || 11942 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 11943 OR_No_Viable_Function) { 11944 // In Microsoft mode, if we are inside a template class member function then 11945 // create a type dependent CallExpr. The goal is to postpone name lookup 11946 // to instantiation time to be able to search into type dependent base 11947 // classes. 11948 CallExpr *CE = new (Context) CallExpr( 11949 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11950 CE->setTypeDependent(true); 11951 CE->setValueDependent(true); 11952 CE->setInstantiationDependent(true); 11953 *Result = CE; 11954 return true; 11955 } 11956 } 11957 11958 if (CandidateSet->empty()) 11959 return false; 11960 11961 UnbridgedCasts.restore(); 11962 return false; 11963 } 11964 11965 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11966 /// the completed call expression. If overload resolution fails, emits 11967 /// diagnostics and returns ExprError() 11968 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11969 UnresolvedLookupExpr *ULE, 11970 SourceLocation LParenLoc, 11971 MultiExprArg Args, 11972 SourceLocation RParenLoc, 11973 Expr *ExecConfig, 11974 OverloadCandidateSet *CandidateSet, 11975 OverloadCandidateSet::iterator *Best, 11976 OverloadingResult OverloadResult, 11977 bool AllowTypoCorrection) { 11978 if (CandidateSet->empty()) 11979 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11980 RParenLoc, /*EmptyLookup=*/true, 11981 AllowTypoCorrection); 11982 11983 switch (OverloadResult) { 11984 case OR_Success: { 11985 FunctionDecl *FDecl = (*Best)->Function; 11986 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11987 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11988 return ExprError(); 11989 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11990 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11991 ExecConfig); 11992 } 11993 11994 case OR_No_Viable_Function: { 11995 // Try to recover by looking for viable functions which the user might 11996 // have meant to call. 11997 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11998 Args, RParenLoc, 11999 /*EmptyLookup=*/false, 12000 AllowTypoCorrection); 12001 if (!Recovery.isInvalid()) 12002 return Recovery; 12003 12004 // If the user passes in a function that we can't take the address of, we 12005 // generally end up emitting really bad error messages. Here, we attempt to 12006 // emit better ones. 12007 for (const Expr *Arg : Args) { 12008 if (!Arg->getType()->isFunctionType()) 12009 continue; 12010 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12011 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12012 if (FD && 12013 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12014 Arg->getExprLoc())) 12015 return ExprError(); 12016 } 12017 } 12018 12019 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call) 12020 << ULE->getName() << Fn->getSourceRange(); 12021 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12022 break; 12023 } 12024 12025 case OR_Ambiguous: 12026 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call) 12027 << ULE->getName() << Fn->getSourceRange(); 12028 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 12029 break; 12030 12031 case OR_Deleted: { 12032 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call) 12033 << (*Best)->Function->isDeleted() << ULE->getName() 12034 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 12035 << Fn->getSourceRange(); 12036 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12037 12038 // We emitted an error for the unavailable/deleted function call but keep 12039 // the call in the AST. 12040 FunctionDecl *FDecl = (*Best)->Function; 12041 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12042 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12043 ExecConfig); 12044 } 12045 } 12046 12047 // Overload resolution failed. 12048 return ExprError(); 12049 } 12050 12051 static void markUnaddressableCandidatesUnviable(Sema &S, 12052 OverloadCandidateSet &CS) { 12053 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12054 if (I->Viable && 12055 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12056 I->Viable = false; 12057 I->FailureKind = ovl_fail_addr_not_available; 12058 } 12059 } 12060 } 12061 12062 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12063 /// (which eventually refers to the declaration Func) and the call 12064 /// arguments Args/NumArgs, attempt to resolve the function call down 12065 /// to a specific function. If overload resolution succeeds, returns 12066 /// the call expression produced by overload resolution. 12067 /// Otherwise, emits diagnostics and returns ExprError. 12068 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12069 UnresolvedLookupExpr *ULE, 12070 SourceLocation LParenLoc, 12071 MultiExprArg Args, 12072 SourceLocation RParenLoc, 12073 Expr *ExecConfig, 12074 bool AllowTypoCorrection, 12075 bool CalleesAddressIsTaken) { 12076 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12077 OverloadCandidateSet::CSK_Normal); 12078 ExprResult result; 12079 12080 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12081 &result)) 12082 return result; 12083 12084 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12085 // functions that aren't addressible are considered unviable. 12086 if (CalleesAddressIsTaken) 12087 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12088 12089 OverloadCandidateSet::iterator Best; 12090 OverloadingResult OverloadResult = 12091 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12092 12093 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 12094 RParenLoc, ExecConfig, &CandidateSet, 12095 &Best, OverloadResult, 12096 AllowTypoCorrection); 12097 } 12098 12099 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12100 return Functions.size() > 1 || 12101 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12102 } 12103 12104 /// Create a unary operation that may resolve to an overloaded 12105 /// operator. 12106 /// 12107 /// \param OpLoc The location of the operator itself (e.g., '*'). 12108 /// 12109 /// \param Opc The UnaryOperatorKind that describes this operator. 12110 /// 12111 /// \param Fns The set of non-member functions that will be 12112 /// considered by overload resolution. The caller needs to build this 12113 /// set based on the context using, e.g., 12114 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12115 /// set should not contain any member functions; those will be added 12116 /// by CreateOverloadedUnaryOp(). 12117 /// 12118 /// \param Input The input argument. 12119 ExprResult 12120 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12121 const UnresolvedSetImpl &Fns, 12122 Expr *Input, bool PerformADL) { 12123 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12124 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12125 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12126 // TODO: provide better source location info. 12127 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12128 12129 if (checkPlaceholderForOverload(*this, Input)) 12130 return ExprError(); 12131 12132 Expr *Args[2] = { Input, nullptr }; 12133 unsigned NumArgs = 1; 12134 12135 // For post-increment and post-decrement, add the implicit '0' as 12136 // the second argument, so that we know this is a post-increment or 12137 // post-decrement. 12138 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12139 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12140 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12141 SourceLocation()); 12142 NumArgs = 2; 12143 } 12144 12145 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12146 12147 if (Input->isTypeDependent()) { 12148 if (Fns.empty()) 12149 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12150 VK_RValue, OK_Ordinary, OpLoc, false); 12151 12152 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12153 UnresolvedLookupExpr *Fn 12154 = UnresolvedLookupExpr::Create(Context, NamingClass, 12155 NestedNameSpecifierLoc(), OpNameInfo, 12156 /*ADL*/ true, IsOverloaded(Fns), 12157 Fns.begin(), Fns.end()); 12158 return new (Context) 12159 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 12160 VK_RValue, OpLoc, FPOptions()); 12161 } 12162 12163 // Build an empty overload set. 12164 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12165 12166 // Add the candidates from the given function set. 12167 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 12168 12169 // Add operator candidates that are member functions. 12170 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12171 12172 // Add candidates from ADL. 12173 if (PerformADL) { 12174 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12175 /*ExplicitTemplateArgs*/nullptr, 12176 CandidateSet); 12177 } 12178 12179 // Add builtin operator candidates. 12180 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12181 12182 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12183 12184 // Perform overload resolution. 12185 OverloadCandidateSet::iterator Best; 12186 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12187 case OR_Success: { 12188 // We found a built-in operator or an overloaded operator. 12189 FunctionDecl *FnDecl = Best->Function; 12190 12191 if (FnDecl) { 12192 Expr *Base = nullptr; 12193 // We matched an overloaded operator. Build a call to that 12194 // operator. 12195 12196 // Convert the arguments. 12197 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12198 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12199 12200 ExprResult InputRes = 12201 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12202 Best->FoundDecl, Method); 12203 if (InputRes.isInvalid()) 12204 return ExprError(); 12205 Base = Input = InputRes.get(); 12206 } else { 12207 // Convert the arguments. 12208 ExprResult InputInit 12209 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12210 Context, 12211 FnDecl->getParamDecl(0)), 12212 SourceLocation(), 12213 Input); 12214 if (InputInit.isInvalid()) 12215 return ExprError(); 12216 Input = InputInit.get(); 12217 } 12218 12219 // Build the actual expression node. 12220 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12221 Base, HadMultipleCandidates, 12222 OpLoc); 12223 if (FnExpr.isInvalid()) 12224 return ExprError(); 12225 12226 // Determine the result type. 12227 QualType ResultTy = FnDecl->getReturnType(); 12228 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12229 ResultTy = ResultTy.getNonLValueExprType(Context); 12230 12231 Args[0] = Input; 12232 CallExpr *TheCall = 12233 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 12234 ResultTy, VK, OpLoc, FPOptions()); 12235 12236 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12237 return ExprError(); 12238 12239 if (CheckFunctionCall(FnDecl, TheCall, 12240 FnDecl->getType()->castAs<FunctionProtoType>())) 12241 return ExprError(); 12242 12243 return MaybeBindToTemporary(TheCall); 12244 } else { 12245 // We matched a built-in operator. Convert the arguments, then 12246 // break out so that we will build the appropriate built-in 12247 // operator node. 12248 ExprResult InputRes = PerformImplicitConversion( 12249 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12250 CCK_ForBuiltinOverloadedOp); 12251 if (InputRes.isInvalid()) 12252 return ExprError(); 12253 Input = InputRes.get(); 12254 break; 12255 } 12256 } 12257 12258 case OR_No_Viable_Function: 12259 // This is an erroneous use of an operator which can be overloaded by 12260 // a non-member function. Check for non-member operators which were 12261 // defined too late to be candidates. 12262 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12263 // FIXME: Recover by calling the found function. 12264 return ExprError(); 12265 12266 // No viable function; fall through to handling this as a 12267 // built-in operator, which will produce an error message for us. 12268 break; 12269 12270 case OR_Ambiguous: 12271 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12272 << UnaryOperator::getOpcodeStr(Opc) 12273 << Input->getType() 12274 << Input->getSourceRange(); 12275 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 12276 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12277 return ExprError(); 12278 12279 case OR_Deleted: 12280 Diag(OpLoc, diag::err_ovl_deleted_oper) 12281 << Best->Function->isDeleted() 12282 << UnaryOperator::getOpcodeStr(Opc) 12283 << getDeletedOrUnavailableSuffix(Best->Function) 12284 << Input->getSourceRange(); 12285 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 12286 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12287 return ExprError(); 12288 } 12289 12290 // Either we found no viable overloaded operator or we matched a 12291 // built-in operator. In either case, fall through to trying to 12292 // build a built-in operation. 12293 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12294 } 12295 12296 /// Create a binary operation that may resolve to an overloaded 12297 /// operator. 12298 /// 12299 /// \param OpLoc The location of the operator itself (e.g., '+'). 12300 /// 12301 /// \param Opc The BinaryOperatorKind that describes this operator. 12302 /// 12303 /// \param Fns The set of non-member functions that will be 12304 /// considered by overload resolution. The caller needs to build this 12305 /// set based on the context using, e.g., 12306 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12307 /// set should not contain any member functions; those will be added 12308 /// by CreateOverloadedBinOp(). 12309 /// 12310 /// \param LHS Left-hand argument. 12311 /// \param RHS Right-hand argument. 12312 ExprResult 12313 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12314 BinaryOperatorKind Opc, 12315 const UnresolvedSetImpl &Fns, 12316 Expr *LHS, Expr *RHS, bool PerformADL) { 12317 Expr *Args[2] = { LHS, RHS }; 12318 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12319 12320 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12321 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12322 12323 // If either side is type-dependent, create an appropriate dependent 12324 // expression. 12325 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12326 if (Fns.empty()) { 12327 // If there are no functions to store, just build a dependent 12328 // BinaryOperator or CompoundAssignment. 12329 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12330 return new (Context) BinaryOperator( 12331 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12332 OpLoc, FPFeatures); 12333 12334 return new (Context) CompoundAssignOperator( 12335 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12336 Context.DependentTy, Context.DependentTy, OpLoc, 12337 FPFeatures); 12338 } 12339 12340 // FIXME: save results of ADL from here? 12341 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12342 // TODO: provide better source location info in DNLoc component. 12343 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12344 UnresolvedLookupExpr *Fn 12345 = UnresolvedLookupExpr::Create(Context, NamingClass, 12346 NestedNameSpecifierLoc(), OpNameInfo, 12347 /*ADL*/PerformADL, IsOverloaded(Fns), 12348 Fns.begin(), Fns.end()); 12349 return new (Context) 12350 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 12351 VK_RValue, OpLoc, FPFeatures); 12352 } 12353 12354 // Always do placeholder-like conversions on the RHS. 12355 if (checkPlaceholderForOverload(*this, Args[1])) 12356 return ExprError(); 12357 12358 // Do placeholder-like conversion on the LHS; note that we should 12359 // not get here with a PseudoObject LHS. 12360 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12361 if (checkPlaceholderForOverload(*this, Args[0])) 12362 return ExprError(); 12363 12364 // If this is the assignment operator, we only perform overload resolution 12365 // if the left-hand side is a class or enumeration type. This is actually 12366 // a hack. The standard requires that we do overload resolution between the 12367 // various built-in candidates, but as DR507 points out, this can lead to 12368 // problems. So we do it this way, which pretty much follows what GCC does. 12369 // Note that we go the traditional code path for compound assignment forms. 12370 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12371 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12372 12373 // If this is the .* operator, which is not overloadable, just 12374 // create a built-in binary operator. 12375 if (Opc == BO_PtrMemD) 12376 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12377 12378 // Build an empty overload set. 12379 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12380 12381 // Add the candidates from the given function set. 12382 AddFunctionCandidates(Fns, Args, CandidateSet); 12383 12384 // Add operator candidates that are member functions. 12385 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12386 12387 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12388 // performed for an assignment operator (nor for operator[] nor operator->, 12389 // which don't get here). 12390 if (Opc != BO_Assign && PerformADL) 12391 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12392 /*ExplicitTemplateArgs*/ nullptr, 12393 CandidateSet); 12394 12395 // Add builtin operator candidates. 12396 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12397 12398 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12399 12400 // Perform overload resolution. 12401 OverloadCandidateSet::iterator Best; 12402 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12403 case OR_Success: { 12404 // We found a built-in operator or an overloaded operator. 12405 FunctionDecl *FnDecl = Best->Function; 12406 12407 if (FnDecl) { 12408 Expr *Base = nullptr; 12409 // We matched an overloaded operator. Build a call to that 12410 // operator. 12411 12412 // Convert the arguments. 12413 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12414 // Best->Access is only meaningful for class members. 12415 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12416 12417 ExprResult Arg1 = 12418 PerformCopyInitialization( 12419 InitializedEntity::InitializeParameter(Context, 12420 FnDecl->getParamDecl(0)), 12421 SourceLocation(), Args[1]); 12422 if (Arg1.isInvalid()) 12423 return ExprError(); 12424 12425 ExprResult Arg0 = 12426 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12427 Best->FoundDecl, Method); 12428 if (Arg0.isInvalid()) 12429 return ExprError(); 12430 Base = Args[0] = Arg0.getAs<Expr>(); 12431 Args[1] = RHS = Arg1.getAs<Expr>(); 12432 } else { 12433 // Convert the arguments. 12434 ExprResult Arg0 = PerformCopyInitialization( 12435 InitializedEntity::InitializeParameter(Context, 12436 FnDecl->getParamDecl(0)), 12437 SourceLocation(), Args[0]); 12438 if (Arg0.isInvalid()) 12439 return ExprError(); 12440 12441 ExprResult Arg1 = 12442 PerformCopyInitialization( 12443 InitializedEntity::InitializeParameter(Context, 12444 FnDecl->getParamDecl(1)), 12445 SourceLocation(), Args[1]); 12446 if (Arg1.isInvalid()) 12447 return ExprError(); 12448 Args[0] = LHS = Arg0.getAs<Expr>(); 12449 Args[1] = RHS = Arg1.getAs<Expr>(); 12450 } 12451 12452 // Build the actual expression node. 12453 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12454 Best->FoundDecl, Base, 12455 HadMultipleCandidates, OpLoc); 12456 if (FnExpr.isInvalid()) 12457 return ExprError(); 12458 12459 // Determine the result type. 12460 QualType ResultTy = FnDecl->getReturnType(); 12461 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12462 ResultTy = ResultTy.getNonLValueExprType(Context); 12463 12464 CXXOperatorCallExpr *TheCall = 12465 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 12466 Args, ResultTy, VK, OpLoc, 12467 FPFeatures); 12468 12469 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12470 FnDecl)) 12471 return ExprError(); 12472 12473 ArrayRef<const Expr *> ArgsArray(Args, 2); 12474 const Expr *ImplicitThis = nullptr; 12475 // Cut off the implicit 'this'. 12476 if (isa<CXXMethodDecl>(FnDecl)) { 12477 ImplicitThis = ArgsArray[0]; 12478 ArgsArray = ArgsArray.slice(1); 12479 } 12480 12481 // Check for a self move. 12482 if (Op == OO_Equal) 12483 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12484 12485 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12486 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12487 VariadicDoesNotApply); 12488 12489 return MaybeBindToTemporary(TheCall); 12490 } else { 12491 // We matched a built-in operator. Convert the arguments, then 12492 // break out so that we will build the appropriate built-in 12493 // operator node. 12494 ExprResult ArgsRes0 = PerformImplicitConversion( 12495 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12496 AA_Passing, CCK_ForBuiltinOverloadedOp); 12497 if (ArgsRes0.isInvalid()) 12498 return ExprError(); 12499 Args[0] = ArgsRes0.get(); 12500 12501 ExprResult ArgsRes1 = PerformImplicitConversion( 12502 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12503 AA_Passing, CCK_ForBuiltinOverloadedOp); 12504 if (ArgsRes1.isInvalid()) 12505 return ExprError(); 12506 Args[1] = ArgsRes1.get(); 12507 break; 12508 } 12509 } 12510 12511 case OR_No_Viable_Function: { 12512 // C++ [over.match.oper]p9: 12513 // If the operator is the operator , [...] and there are no 12514 // viable functions, then the operator is assumed to be the 12515 // built-in operator and interpreted according to clause 5. 12516 if (Opc == BO_Comma) 12517 break; 12518 12519 // For class as left operand for assignment or compound assignment 12520 // operator do not fall through to handling in built-in, but report that 12521 // no overloaded assignment operator found 12522 ExprResult Result = ExprError(); 12523 if (Args[0]->getType()->isRecordType() && 12524 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12525 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12526 << BinaryOperator::getOpcodeStr(Opc) 12527 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12528 if (Args[0]->getType()->isIncompleteType()) { 12529 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12530 << Args[0]->getType() 12531 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12532 } 12533 } else { 12534 // This is an erroneous use of an operator which can be overloaded by 12535 // a non-member function. Check for non-member operators which were 12536 // defined too late to be candidates. 12537 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12538 // FIXME: Recover by calling the found function. 12539 return ExprError(); 12540 12541 // No viable function; try to create a built-in operation, which will 12542 // produce an error. Then, show the non-viable candidates. 12543 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12544 } 12545 assert(Result.isInvalid() && 12546 "C++ binary operator overloading is missing candidates!"); 12547 if (Result.isInvalid()) 12548 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12549 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12550 return Result; 12551 } 12552 12553 case OR_Ambiguous: 12554 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12555 << BinaryOperator::getOpcodeStr(Opc) 12556 << Args[0]->getType() << Args[1]->getType() 12557 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12558 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12559 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12560 return ExprError(); 12561 12562 case OR_Deleted: 12563 if (isImplicitlyDeleted(Best->Function)) { 12564 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12565 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12566 << Context.getRecordType(Method->getParent()) 12567 << getSpecialMember(Method); 12568 12569 // The user probably meant to call this special member. Just 12570 // explain why it's deleted. 12571 NoteDeletedFunction(Method); 12572 return ExprError(); 12573 } else { 12574 Diag(OpLoc, diag::err_ovl_deleted_oper) 12575 << Best->Function->isDeleted() 12576 << BinaryOperator::getOpcodeStr(Opc) 12577 << getDeletedOrUnavailableSuffix(Best->Function) 12578 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12579 } 12580 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12581 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12582 return ExprError(); 12583 } 12584 12585 // We matched a built-in operator; build it. 12586 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12587 } 12588 12589 ExprResult 12590 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12591 SourceLocation RLoc, 12592 Expr *Base, Expr *Idx) { 12593 Expr *Args[2] = { Base, Idx }; 12594 DeclarationName OpName = 12595 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12596 12597 // If either side is type-dependent, create an appropriate dependent 12598 // expression. 12599 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12600 12601 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12602 // CHECKME: no 'operator' keyword? 12603 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12604 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12605 UnresolvedLookupExpr *Fn 12606 = UnresolvedLookupExpr::Create(Context, NamingClass, 12607 NestedNameSpecifierLoc(), OpNameInfo, 12608 /*ADL*/ true, /*Overloaded*/ false, 12609 UnresolvedSetIterator(), 12610 UnresolvedSetIterator()); 12611 // Can't add any actual overloads yet 12612 12613 return new (Context) 12614 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12615 Context.DependentTy, VK_RValue, RLoc, FPOptions()); 12616 } 12617 12618 // Handle placeholders on both operands. 12619 if (checkPlaceholderForOverload(*this, Args[0])) 12620 return ExprError(); 12621 if (checkPlaceholderForOverload(*this, Args[1])) 12622 return ExprError(); 12623 12624 // Build an empty overload set. 12625 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12626 12627 // Subscript can only be overloaded as a member function. 12628 12629 // Add operator candidates that are member functions. 12630 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12631 12632 // Add builtin operator candidates. 12633 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12634 12635 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12636 12637 // Perform overload resolution. 12638 OverloadCandidateSet::iterator Best; 12639 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12640 case OR_Success: { 12641 // We found a built-in operator or an overloaded operator. 12642 FunctionDecl *FnDecl = Best->Function; 12643 12644 if (FnDecl) { 12645 // We matched an overloaded operator. Build a call to that 12646 // operator. 12647 12648 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12649 12650 // Convert the arguments. 12651 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12652 ExprResult Arg0 = 12653 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12654 Best->FoundDecl, Method); 12655 if (Arg0.isInvalid()) 12656 return ExprError(); 12657 Args[0] = Arg0.get(); 12658 12659 // Convert the arguments. 12660 ExprResult InputInit 12661 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12662 Context, 12663 FnDecl->getParamDecl(0)), 12664 SourceLocation(), 12665 Args[1]); 12666 if (InputInit.isInvalid()) 12667 return ExprError(); 12668 12669 Args[1] = InputInit.getAs<Expr>(); 12670 12671 // Build the actual expression node. 12672 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12673 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12674 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12675 Best->FoundDecl, 12676 Base, 12677 HadMultipleCandidates, 12678 OpLocInfo.getLoc(), 12679 OpLocInfo.getInfo()); 12680 if (FnExpr.isInvalid()) 12681 return ExprError(); 12682 12683 // Determine the result type 12684 QualType ResultTy = FnDecl->getReturnType(); 12685 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12686 ResultTy = ResultTy.getNonLValueExprType(Context); 12687 12688 CXXOperatorCallExpr *TheCall = 12689 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12690 FnExpr.get(), Args, 12691 ResultTy, VK, RLoc, 12692 FPOptions()); 12693 12694 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12695 return ExprError(); 12696 12697 if (CheckFunctionCall(Method, TheCall, 12698 Method->getType()->castAs<FunctionProtoType>())) 12699 return ExprError(); 12700 12701 return MaybeBindToTemporary(TheCall); 12702 } else { 12703 // We matched a built-in operator. Convert the arguments, then 12704 // break out so that we will build the appropriate built-in 12705 // operator node. 12706 ExprResult ArgsRes0 = PerformImplicitConversion( 12707 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12708 AA_Passing, CCK_ForBuiltinOverloadedOp); 12709 if (ArgsRes0.isInvalid()) 12710 return ExprError(); 12711 Args[0] = ArgsRes0.get(); 12712 12713 ExprResult ArgsRes1 = PerformImplicitConversion( 12714 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12715 AA_Passing, CCK_ForBuiltinOverloadedOp); 12716 if (ArgsRes1.isInvalid()) 12717 return ExprError(); 12718 Args[1] = ArgsRes1.get(); 12719 12720 break; 12721 } 12722 } 12723 12724 case OR_No_Viable_Function: { 12725 if (CandidateSet.empty()) 12726 Diag(LLoc, diag::err_ovl_no_oper) 12727 << Args[0]->getType() << /*subscript*/ 0 12728 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12729 else 12730 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12731 << Args[0]->getType() 12732 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12733 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12734 "[]", LLoc); 12735 return ExprError(); 12736 } 12737 12738 case OR_Ambiguous: 12739 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12740 << "[]" 12741 << Args[0]->getType() << Args[1]->getType() 12742 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12743 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12744 "[]", LLoc); 12745 return ExprError(); 12746 12747 case OR_Deleted: 12748 Diag(LLoc, diag::err_ovl_deleted_oper) 12749 << Best->Function->isDeleted() << "[]" 12750 << getDeletedOrUnavailableSuffix(Best->Function) 12751 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12752 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12753 "[]", LLoc); 12754 return ExprError(); 12755 } 12756 12757 // We matched a built-in operator; build it. 12758 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12759 } 12760 12761 /// BuildCallToMemberFunction - Build a call to a member 12762 /// function. MemExpr is the expression that refers to the member 12763 /// function (and includes the object parameter), Args/NumArgs are the 12764 /// arguments to the function call (not including the object 12765 /// parameter). The caller needs to validate that the member 12766 /// expression refers to a non-static member function or an overloaded 12767 /// member function. 12768 ExprResult 12769 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12770 SourceLocation LParenLoc, 12771 MultiExprArg Args, 12772 SourceLocation RParenLoc) { 12773 assert(MemExprE->getType() == Context.BoundMemberTy || 12774 MemExprE->getType() == Context.OverloadTy); 12775 12776 // Dig out the member expression. This holds both the object 12777 // argument and the member function we're referring to. 12778 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12779 12780 // Determine whether this is a call to a pointer-to-member function. 12781 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12782 assert(op->getType() == Context.BoundMemberTy); 12783 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12784 12785 QualType fnType = 12786 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12787 12788 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12789 QualType resultType = proto->getCallResultType(Context); 12790 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12791 12792 // Check that the object type isn't more qualified than the 12793 // member function we're calling. 12794 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12795 12796 QualType objectType = op->getLHS()->getType(); 12797 if (op->getOpcode() == BO_PtrMemI) 12798 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12799 Qualifiers objectQuals = objectType.getQualifiers(); 12800 12801 Qualifiers difference = objectQuals - funcQuals; 12802 difference.removeObjCGCAttr(); 12803 difference.removeAddressSpace(); 12804 if (difference) { 12805 std::string qualsString = difference.getAsString(); 12806 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12807 << fnType.getUnqualifiedType() 12808 << qualsString 12809 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12810 } 12811 12812 CXXMemberCallExpr *call 12813 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12814 resultType, valueKind, RParenLoc); 12815 12816 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 12817 call, nullptr)) 12818 return ExprError(); 12819 12820 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12821 return ExprError(); 12822 12823 if (CheckOtherCall(call, proto)) 12824 return ExprError(); 12825 12826 return MaybeBindToTemporary(call); 12827 } 12828 12829 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12830 return new (Context) 12831 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12832 12833 UnbridgedCastsSet UnbridgedCasts; 12834 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12835 return ExprError(); 12836 12837 MemberExpr *MemExpr; 12838 CXXMethodDecl *Method = nullptr; 12839 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12840 NestedNameSpecifier *Qualifier = nullptr; 12841 if (isa<MemberExpr>(NakedMemExpr)) { 12842 MemExpr = cast<MemberExpr>(NakedMemExpr); 12843 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12844 FoundDecl = MemExpr->getFoundDecl(); 12845 Qualifier = MemExpr->getQualifier(); 12846 UnbridgedCasts.restore(); 12847 } else { 12848 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12849 Qualifier = UnresExpr->getQualifier(); 12850 12851 QualType ObjectType = UnresExpr->getBaseType(); 12852 Expr::Classification ObjectClassification 12853 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12854 : UnresExpr->getBase()->Classify(Context); 12855 12856 // Add overload candidates 12857 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12858 OverloadCandidateSet::CSK_Normal); 12859 12860 // FIXME: avoid copy. 12861 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12862 if (UnresExpr->hasExplicitTemplateArgs()) { 12863 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12864 TemplateArgs = &TemplateArgsBuffer; 12865 } 12866 12867 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12868 E = UnresExpr->decls_end(); I != E; ++I) { 12869 12870 NamedDecl *Func = *I; 12871 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12872 if (isa<UsingShadowDecl>(Func)) 12873 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12874 12875 12876 // Microsoft supports direct constructor calls. 12877 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12878 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12879 Args, CandidateSet); 12880 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12881 // If explicit template arguments were provided, we can't call a 12882 // non-template member function. 12883 if (TemplateArgs) 12884 continue; 12885 12886 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12887 ObjectClassification, Args, CandidateSet, 12888 /*SuppressUserConversions=*/false); 12889 } else { 12890 AddMethodTemplateCandidate( 12891 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 12892 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 12893 /*SuppressUsedConversions=*/false); 12894 } 12895 } 12896 12897 DeclarationName DeclName = UnresExpr->getMemberName(); 12898 12899 UnbridgedCasts.restore(); 12900 12901 OverloadCandidateSet::iterator Best; 12902 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 12903 Best)) { 12904 case OR_Success: 12905 Method = cast<CXXMethodDecl>(Best->Function); 12906 FoundDecl = Best->FoundDecl; 12907 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12908 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12909 return ExprError(); 12910 // If FoundDecl is different from Method (such as if one is a template 12911 // and the other a specialization), make sure DiagnoseUseOfDecl is 12912 // called on both. 12913 // FIXME: This would be more comprehensively addressed by modifying 12914 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12915 // being used. 12916 if (Method != FoundDecl.getDecl() && 12917 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12918 return ExprError(); 12919 break; 12920 12921 case OR_No_Viable_Function: 12922 Diag(UnresExpr->getMemberLoc(), 12923 diag::err_ovl_no_viable_member_function_in_call) 12924 << DeclName << MemExprE->getSourceRange(); 12925 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12926 // FIXME: Leaking incoming expressions! 12927 return ExprError(); 12928 12929 case OR_Ambiguous: 12930 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12931 << DeclName << MemExprE->getSourceRange(); 12932 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12933 // FIXME: Leaking incoming expressions! 12934 return ExprError(); 12935 12936 case OR_Deleted: 12937 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12938 << Best->Function->isDeleted() 12939 << DeclName 12940 << getDeletedOrUnavailableSuffix(Best->Function) 12941 << MemExprE->getSourceRange(); 12942 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12943 // FIXME: Leaking incoming expressions! 12944 return ExprError(); 12945 } 12946 12947 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12948 12949 // If overload resolution picked a static member, build a 12950 // non-member call based on that function. 12951 if (Method->isStatic()) { 12952 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12953 RParenLoc); 12954 } 12955 12956 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12957 } 12958 12959 QualType ResultType = Method->getReturnType(); 12960 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12961 ResultType = ResultType.getNonLValueExprType(Context); 12962 12963 assert(Method && "Member call to something that isn't a method?"); 12964 CXXMemberCallExpr *TheCall = 12965 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12966 ResultType, VK, RParenLoc); 12967 12968 // Check for a valid return type. 12969 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12970 TheCall, Method)) 12971 return ExprError(); 12972 12973 // Convert the object argument (for a non-static member function call). 12974 // We only need to do this if there was actually an overload; otherwise 12975 // it was done at lookup. 12976 if (!Method->isStatic()) { 12977 ExprResult ObjectArg = 12978 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12979 FoundDecl, Method); 12980 if (ObjectArg.isInvalid()) 12981 return ExprError(); 12982 MemExpr->setBase(ObjectArg.get()); 12983 } 12984 12985 // Convert the rest of the arguments 12986 const FunctionProtoType *Proto = 12987 Method->getType()->getAs<FunctionProtoType>(); 12988 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12989 RParenLoc)) 12990 return ExprError(); 12991 12992 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12993 12994 if (CheckFunctionCall(Method, TheCall, Proto)) 12995 return ExprError(); 12996 12997 // In the case the method to call was not selected by the overloading 12998 // resolution process, we still need to handle the enable_if attribute. Do 12999 // that here, so it will not hide previous -- and more relevant -- errors. 13000 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13001 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13002 Diag(MemE->getMemberLoc(), 13003 diag::err_ovl_no_viable_member_function_in_call) 13004 << Method << Method->getSourceRange(); 13005 Diag(Method->getLocation(), 13006 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13007 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13008 return ExprError(); 13009 } 13010 } 13011 13012 if ((isa<CXXConstructorDecl>(CurContext) || 13013 isa<CXXDestructorDecl>(CurContext)) && 13014 TheCall->getMethodDecl()->isPure()) { 13015 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13016 13017 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13018 MemExpr->performsVirtualDispatch(getLangOpts())) { 13019 Diag(MemExpr->getBeginLoc(), 13020 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13021 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13022 << MD->getParent()->getDeclName(); 13023 13024 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13025 if (getLangOpts().AppleKext) 13026 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13027 << MD->getParent()->getDeclName() << MD->getDeclName(); 13028 } 13029 } 13030 13031 if (CXXDestructorDecl *DD = 13032 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13033 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13034 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13035 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13036 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13037 MemExpr->getMemberLoc()); 13038 } 13039 13040 return MaybeBindToTemporary(TheCall); 13041 } 13042 13043 /// BuildCallToObjectOfClassType - Build a call to an object of class 13044 /// type (C++ [over.call.object]), which can end up invoking an 13045 /// overloaded function call operator (@c operator()) or performing a 13046 /// user-defined conversion on the object argument. 13047 ExprResult 13048 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13049 SourceLocation LParenLoc, 13050 MultiExprArg Args, 13051 SourceLocation RParenLoc) { 13052 if (checkPlaceholderForOverload(*this, Obj)) 13053 return ExprError(); 13054 ExprResult Object = Obj; 13055 13056 UnbridgedCastsSet UnbridgedCasts; 13057 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13058 return ExprError(); 13059 13060 assert(Object.get()->getType()->isRecordType() && 13061 "Requires object type argument"); 13062 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13063 13064 // C++ [over.call.object]p1: 13065 // If the primary-expression E in the function call syntax 13066 // evaluates to a class object of type "cv T", then the set of 13067 // candidate functions includes at least the function call 13068 // operators of T. The function call operators of T are obtained by 13069 // ordinary lookup of the name operator() in the context of 13070 // (E).operator(). 13071 OverloadCandidateSet CandidateSet(LParenLoc, 13072 OverloadCandidateSet::CSK_Operator); 13073 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13074 13075 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13076 diag::err_incomplete_object_call, Object.get())) 13077 return true; 13078 13079 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13080 LookupQualifiedName(R, Record->getDecl()); 13081 R.suppressDiagnostics(); 13082 13083 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13084 Oper != OperEnd; ++Oper) { 13085 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13086 Object.get()->Classify(Context), Args, CandidateSet, 13087 /*SuppressUserConversions=*/false); 13088 } 13089 13090 // C++ [over.call.object]p2: 13091 // In addition, for each (non-explicit in C++0x) conversion function 13092 // declared in T of the form 13093 // 13094 // operator conversion-type-id () cv-qualifier; 13095 // 13096 // where cv-qualifier is the same cv-qualification as, or a 13097 // greater cv-qualification than, cv, and where conversion-type-id 13098 // denotes the type "pointer to function of (P1,...,Pn) returning 13099 // R", or the type "reference to pointer to function of 13100 // (P1,...,Pn) returning R", or the type "reference to function 13101 // of (P1,...,Pn) returning R", a surrogate call function [...] 13102 // is also considered as a candidate function. Similarly, 13103 // surrogate call functions are added to the set of candidate 13104 // functions for each conversion function declared in an 13105 // accessible base class provided the function is not hidden 13106 // within T by another intervening declaration. 13107 const auto &Conversions = 13108 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13109 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13110 NamedDecl *D = *I; 13111 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13112 if (isa<UsingShadowDecl>(D)) 13113 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13114 13115 // Skip over templated conversion functions; they aren't 13116 // surrogates. 13117 if (isa<FunctionTemplateDecl>(D)) 13118 continue; 13119 13120 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13121 if (!Conv->isExplicit()) { 13122 // Strip the reference type (if any) and then the pointer type (if 13123 // any) to get down to what might be a function type. 13124 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13125 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13126 ConvType = ConvPtrType->getPointeeType(); 13127 13128 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13129 { 13130 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13131 Object.get(), Args, CandidateSet); 13132 } 13133 } 13134 } 13135 13136 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13137 13138 // Perform overload resolution. 13139 OverloadCandidateSet::iterator Best; 13140 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13141 Best)) { 13142 case OR_Success: 13143 // Overload resolution succeeded; we'll build the appropriate call 13144 // below. 13145 break; 13146 13147 case OR_No_Viable_Function: 13148 if (CandidateSet.empty()) 13149 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper) 13150 << Object.get()->getType() << /*call*/ 1 13151 << Object.get()->getSourceRange(); 13152 else 13153 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call) 13154 << Object.get()->getType() << Object.get()->getSourceRange(); 13155 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13156 break; 13157 13158 case OR_Ambiguous: 13159 Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call) 13160 << Object.get()->getType() << Object.get()->getSourceRange(); 13161 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13162 break; 13163 13164 case OR_Deleted: 13165 Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call) 13166 << Best->Function->isDeleted() << Object.get()->getType() 13167 << getDeletedOrUnavailableSuffix(Best->Function) 13168 << Object.get()->getSourceRange(); 13169 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13170 break; 13171 } 13172 13173 if (Best == CandidateSet.end()) 13174 return true; 13175 13176 UnbridgedCasts.restore(); 13177 13178 if (Best->Function == nullptr) { 13179 // Since there is no function declaration, this is one of the 13180 // surrogate candidates. Dig out the conversion function. 13181 CXXConversionDecl *Conv 13182 = cast<CXXConversionDecl>( 13183 Best->Conversions[0].UserDefined.ConversionFunction); 13184 13185 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13186 Best->FoundDecl); 13187 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13188 return ExprError(); 13189 assert(Conv == Best->FoundDecl.getDecl() && 13190 "Found Decl & conversion-to-functionptr should be same, right?!"); 13191 // We selected one of the surrogate functions that converts the 13192 // object parameter to a function pointer. Perform the conversion 13193 // on the object argument, then let ActOnCallExpr finish the job. 13194 13195 // Create an implicit member expr to refer to the conversion operator. 13196 // and then call it. 13197 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13198 Conv, HadMultipleCandidates); 13199 if (Call.isInvalid()) 13200 return ExprError(); 13201 // Record usage of conversion in an implicit cast. 13202 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13203 CK_UserDefinedConversion, Call.get(), 13204 nullptr, VK_RValue); 13205 13206 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13207 } 13208 13209 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13210 13211 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13212 // that calls this method, using Object for the implicit object 13213 // parameter and passing along the remaining arguments. 13214 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13215 13216 // An error diagnostic has already been printed when parsing the declaration. 13217 if (Method->isInvalidDecl()) 13218 return ExprError(); 13219 13220 const FunctionProtoType *Proto = 13221 Method->getType()->getAs<FunctionProtoType>(); 13222 13223 unsigned NumParams = Proto->getNumParams(); 13224 13225 DeclarationNameInfo OpLocInfo( 13226 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13227 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13228 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13229 Obj, HadMultipleCandidates, 13230 OpLocInfo.getLoc(), 13231 OpLocInfo.getInfo()); 13232 if (NewFn.isInvalid()) 13233 return true; 13234 13235 // Build the full argument list for the method call (the implicit object 13236 // parameter is placed at the beginning of the list). 13237 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1); 13238 MethodArgs[0] = Object.get(); 13239 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1); 13240 13241 // Once we've built TheCall, all of the expressions are properly 13242 // owned. 13243 QualType ResultTy = Method->getReturnType(); 13244 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13245 ResultTy = ResultTy.getNonLValueExprType(Context); 13246 13247 CXXOperatorCallExpr *TheCall = new (Context) 13248 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, 13249 VK, RParenLoc, FPOptions()); 13250 13251 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13252 return true; 13253 13254 // We may have default arguments. If so, we need to allocate more 13255 // slots in the call for them. 13256 if (Args.size() < NumParams) 13257 TheCall->setNumArgs(Context, NumParams + 1); 13258 13259 bool IsError = false; 13260 13261 // Initialize the implicit object parameter. 13262 ExprResult ObjRes = 13263 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13264 Best->FoundDecl, Method); 13265 if (ObjRes.isInvalid()) 13266 IsError = true; 13267 else 13268 Object = ObjRes; 13269 TheCall->setArg(0, Object.get()); 13270 13271 // Check the argument types. 13272 for (unsigned i = 0; i != NumParams; i++) { 13273 Expr *Arg; 13274 if (i < Args.size()) { 13275 Arg = Args[i]; 13276 13277 // Pass the argument. 13278 13279 ExprResult InputInit 13280 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13281 Context, 13282 Method->getParamDecl(i)), 13283 SourceLocation(), Arg); 13284 13285 IsError |= InputInit.isInvalid(); 13286 Arg = InputInit.getAs<Expr>(); 13287 } else { 13288 ExprResult DefArg 13289 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13290 if (DefArg.isInvalid()) { 13291 IsError = true; 13292 break; 13293 } 13294 13295 Arg = DefArg.getAs<Expr>(); 13296 } 13297 13298 TheCall->setArg(i + 1, Arg); 13299 } 13300 13301 // If this is a variadic call, handle args passed through "...". 13302 if (Proto->isVariadic()) { 13303 // Promote the arguments (C99 6.5.2.2p7). 13304 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13305 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13306 nullptr); 13307 IsError |= Arg.isInvalid(); 13308 TheCall->setArg(i + 1, Arg.get()); 13309 } 13310 } 13311 13312 if (IsError) return true; 13313 13314 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13315 13316 if (CheckFunctionCall(Method, TheCall, Proto)) 13317 return true; 13318 13319 return MaybeBindToTemporary(TheCall); 13320 } 13321 13322 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13323 /// (if one exists), where @c Base is an expression of class type and 13324 /// @c Member is the name of the member we're trying to find. 13325 ExprResult 13326 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13327 bool *NoArrowOperatorFound) { 13328 assert(Base->getType()->isRecordType() && 13329 "left-hand side must have class type"); 13330 13331 if (checkPlaceholderForOverload(*this, Base)) 13332 return ExprError(); 13333 13334 SourceLocation Loc = Base->getExprLoc(); 13335 13336 // C++ [over.ref]p1: 13337 // 13338 // [...] An expression x->m is interpreted as (x.operator->())->m 13339 // for a class object x of type T if T::operator->() exists and if 13340 // the operator is selected as the best match function by the 13341 // overload resolution mechanism (13.3). 13342 DeclarationName OpName = 13343 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13344 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13345 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13346 13347 if (RequireCompleteType(Loc, Base->getType(), 13348 diag::err_typecheck_incomplete_tag, Base)) 13349 return ExprError(); 13350 13351 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13352 LookupQualifiedName(R, BaseRecord->getDecl()); 13353 R.suppressDiagnostics(); 13354 13355 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13356 Oper != OperEnd; ++Oper) { 13357 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13358 None, CandidateSet, /*SuppressUserConversions=*/false); 13359 } 13360 13361 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13362 13363 // Perform overload resolution. 13364 OverloadCandidateSet::iterator Best; 13365 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13366 case OR_Success: 13367 // Overload resolution succeeded; we'll build the call below. 13368 break; 13369 13370 case OR_No_Viable_Function: 13371 if (CandidateSet.empty()) { 13372 QualType BaseType = Base->getType(); 13373 if (NoArrowOperatorFound) { 13374 // Report this specific error to the caller instead of emitting a 13375 // diagnostic, as requested. 13376 *NoArrowOperatorFound = true; 13377 return ExprError(); 13378 } 13379 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13380 << BaseType << Base->getSourceRange(); 13381 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13382 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13383 << FixItHint::CreateReplacement(OpLoc, "."); 13384 } 13385 } else 13386 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13387 << "operator->" << Base->getSourceRange(); 13388 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13389 return ExprError(); 13390 13391 case OR_Ambiguous: 13392 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 13393 << "->" << Base->getType() << Base->getSourceRange(); 13394 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 13395 return ExprError(); 13396 13397 case OR_Deleted: 13398 Diag(OpLoc, diag::err_ovl_deleted_oper) 13399 << Best->Function->isDeleted() 13400 << "->" 13401 << getDeletedOrUnavailableSuffix(Best->Function) 13402 << Base->getSourceRange(); 13403 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13404 return ExprError(); 13405 } 13406 13407 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13408 13409 // Convert the object parameter. 13410 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13411 ExprResult BaseResult = 13412 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13413 Best->FoundDecl, Method); 13414 if (BaseResult.isInvalid()) 13415 return ExprError(); 13416 Base = BaseResult.get(); 13417 13418 // Build the operator call. 13419 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13420 Base, HadMultipleCandidates, OpLoc); 13421 if (FnExpr.isInvalid()) 13422 return ExprError(); 13423 13424 QualType ResultTy = Method->getReturnType(); 13425 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13426 ResultTy = ResultTy.getNonLValueExprType(Context); 13427 CXXOperatorCallExpr *TheCall = 13428 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 13429 Base, ResultTy, VK, OpLoc, FPOptions()); 13430 13431 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13432 return ExprError(); 13433 13434 if (CheckFunctionCall(Method, TheCall, 13435 Method->getType()->castAs<FunctionProtoType>())) 13436 return ExprError(); 13437 13438 return MaybeBindToTemporary(TheCall); 13439 } 13440 13441 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13442 /// a literal operator described by the provided lookup results. 13443 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13444 DeclarationNameInfo &SuffixInfo, 13445 ArrayRef<Expr*> Args, 13446 SourceLocation LitEndLoc, 13447 TemplateArgumentListInfo *TemplateArgs) { 13448 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13449 13450 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13451 OverloadCandidateSet::CSK_Normal); 13452 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13453 /*SuppressUserConversions=*/true); 13454 13455 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13456 13457 // Perform overload resolution. This will usually be trivial, but might need 13458 // to perform substitutions for a literal operator template. 13459 OverloadCandidateSet::iterator Best; 13460 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13461 case OR_Success: 13462 case OR_Deleted: 13463 break; 13464 13465 case OR_No_Viable_Function: 13466 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13467 << R.getLookupName(); 13468 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13469 return ExprError(); 13470 13471 case OR_Ambiguous: 13472 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13473 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13474 return ExprError(); 13475 } 13476 13477 FunctionDecl *FD = Best->Function; 13478 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13479 nullptr, HadMultipleCandidates, 13480 SuffixInfo.getLoc(), 13481 SuffixInfo.getInfo()); 13482 if (Fn.isInvalid()) 13483 return true; 13484 13485 // Check the argument types. This should almost always be a no-op, except 13486 // that array-to-pointer decay is applied to string literals. 13487 Expr *ConvArgs[2]; 13488 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13489 ExprResult InputInit = PerformCopyInitialization( 13490 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13491 SourceLocation(), Args[ArgIdx]); 13492 if (InputInit.isInvalid()) 13493 return true; 13494 ConvArgs[ArgIdx] = InputInit.get(); 13495 } 13496 13497 QualType ResultTy = FD->getReturnType(); 13498 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13499 ResultTy = ResultTy.getNonLValueExprType(Context); 13500 13501 UserDefinedLiteral *UDL = 13502 new (Context) UserDefinedLiteral(Context, Fn.get(), 13503 llvm::makeArrayRef(ConvArgs, Args.size()), 13504 ResultTy, VK, LitEndLoc, UDSuffixLoc); 13505 13506 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13507 return ExprError(); 13508 13509 if (CheckFunctionCall(FD, UDL, nullptr)) 13510 return ExprError(); 13511 13512 return MaybeBindToTemporary(UDL); 13513 } 13514 13515 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13516 /// given LookupResult is non-empty, it is assumed to describe a member which 13517 /// will be invoked. Otherwise, the function will be found via argument 13518 /// dependent lookup. 13519 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13520 /// otherwise CallExpr is set to ExprError() and some non-success value 13521 /// is returned. 13522 Sema::ForRangeStatus 13523 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13524 SourceLocation RangeLoc, 13525 const DeclarationNameInfo &NameInfo, 13526 LookupResult &MemberLookup, 13527 OverloadCandidateSet *CandidateSet, 13528 Expr *Range, ExprResult *CallExpr) { 13529 Scope *S = nullptr; 13530 13531 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 13532 if (!MemberLookup.empty()) { 13533 ExprResult MemberRef = 13534 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13535 /*IsPtr=*/false, CXXScopeSpec(), 13536 /*TemplateKWLoc=*/SourceLocation(), 13537 /*FirstQualifierInScope=*/nullptr, 13538 MemberLookup, 13539 /*TemplateArgs=*/nullptr, S); 13540 if (MemberRef.isInvalid()) { 13541 *CallExpr = ExprError(); 13542 return FRS_DiagnosticIssued; 13543 } 13544 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13545 if (CallExpr->isInvalid()) { 13546 *CallExpr = ExprError(); 13547 return FRS_DiagnosticIssued; 13548 } 13549 } else { 13550 UnresolvedSet<0> FoundNames; 13551 UnresolvedLookupExpr *Fn = 13552 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13553 NestedNameSpecifierLoc(), NameInfo, 13554 /*NeedsADL=*/true, /*Overloaded=*/false, 13555 FoundNames.begin(), FoundNames.end()); 13556 13557 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13558 CandidateSet, CallExpr); 13559 if (CandidateSet->empty() || CandidateSetError) { 13560 *CallExpr = ExprError(); 13561 return FRS_NoViableFunction; 13562 } 13563 OverloadCandidateSet::iterator Best; 13564 OverloadingResult OverloadResult = 13565 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 13566 13567 if (OverloadResult == OR_No_Viable_Function) { 13568 *CallExpr = ExprError(); 13569 return FRS_NoViableFunction; 13570 } 13571 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13572 Loc, nullptr, CandidateSet, &Best, 13573 OverloadResult, 13574 /*AllowTypoCorrection=*/false); 13575 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13576 *CallExpr = ExprError(); 13577 return FRS_DiagnosticIssued; 13578 } 13579 } 13580 return FRS_Success; 13581 } 13582 13583 13584 /// FixOverloadedFunctionReference - E is an expression that refers to 13585 /// a C++ overloaded function (possibly with some parentheses and 13586 /// perhaps a '&' around it). We have resolved the overloaded function 13587 /// to the function declaration Fn, so patch up the expression E to 13588 /// refer (possibly indirectly) to Fn. Returns the new expr. 13589 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13590 FunctionDecl *Fn) { 13591 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13592 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13593 Found, Fn); 13594 if (SubExpr == PE->getSubExpr()) 13595 return PE; 13596 13597 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13598 } 13599 13600 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13601 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13602 Found, Fn); 13603 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13604 SubExpr->getType()) && 13605 "Implicit cast type cannot be determined from overload"); 13606 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13607 if (SubExpr == ICE->getSubExpr()) 13608 return ICE; 13609 13610 return ImplicitCastExpr::Create(Context, ICE->getType(), 13611 ICE->getCastKind(), 13612 SubExpr, nullptr, 13613 ICE->getValueKind()); 13614 } 13615 13616 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13617 if (!GSE->isResultDependent()) { 13618 Expr *SubExpr = 13619 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13620 if (SubExpr == GSE->getResultExpr()) 13621 return GSE; 13622 13623 // Replace the resulting type information before rebuilding the generic 13624 // selection expression. 13625 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13626 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13627 unsigned ResultIdx = GSE->getResultIndex(); 13628 AssocExprs[ResultIdx] = SubExpr; 13629 13630 return new (Context) GenericSelectionExpr( 13631 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13632 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13633 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13634 ResultIdx); 13635 } 13636 // Rather than fall through to the unreachable, return the original generic 13637 // selection expression. 13638 return GSE; 13639 } 13640 13641 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13642 assert(UnOp->getOpcode() == UO_AddrOf && 13643 "Can only take the address of an overloaded function"); 13644 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13645 if (Method->isStatic()) { 13646 // Do nothing: static member functions aren't any different 13647 // from non-member functions. 13648 } else { 13649 // Fix the subexpression, which really has to be an 13650 // UnresolvedLookupExpr holding an overloaded member function 13651 // or template. 13652 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13653 Found, Fn); 13654 if (SubExpr == UnOp->getSubExpr()) 13655 return UnOp; 13656 13657 assert(isa<DeclRefExpr>(SubExpr) 13658 && "fixed to something other than a decl ref"); 13659 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13660 && "fixed to a member ref with no nested name qualifier"); 13661 13662 // We have taken the address of a pointer to member 13663 // function. Perform the computation here so that we get the 13664 // appropriate pointer to member type. 13665 QualType ClassType 13666 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13667 QualType MemPtrType 13668 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13669 // Under the MS ABI, lock down the inheritance model now. 13670 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13671 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13672 13673 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13674 VK_RValue, OK_Ordinary, 13675 UnOp->getOperatorLoc(), false); 13676 } 13677 } 13678 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13679 Found, Fn); 13680 if (SubExpr == UnOp->getSubExpr()) 13681 return UnOp; 13682 13683 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13684 Context.getPointerType(SubExpr->getType()), 13685 VK_RValue, OK_Ordinary, 13686 UnOp->getOperatorLoc(), false); 13687 } 13688 13689 // C++ [except.spec]p17: 13690 // An exception-specification is considered to be needed when: 13691 // - in an expression the function is the unique lookup result or the 13692 // selected member of a set of overloaded functions 13693 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13694 ResolveExceptionSpec(E->getExprLoc(), FPT); 13695 13696 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13697 // FIXME: avoid copy. 13698 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13699 if (ULE->hasExplicitTemplateArgs()) { 13700 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13701 TemplateArgs = &TemplateArgsBuffer; 13702 } 13703 13704 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13705 ULE->getQualifierLoc(), 13706 ULE->getTemplateKeywordLoc(), 13707 Fn, 13708 /*enclosing*/ false, // FIXME? 13709 ULE->getNameLoc(), 13710 Fn->getType(), 13711 VK_LValue, 13712 Found.getDecl(), 13713 TemplateArgs); 13714 MarkDeclRefReferenced(DRE); 13715 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13716 return DRE; 13717 } 13718 13719 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13720 // FIXME: avoid copy. 13721 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13722 if (MemExpr->hasExplicitTemplateArgs()) { 13723 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13724 TemplateArgs = &TemplateArgsBuffer; 13725 } 13726 13727 Expr *Base; 13728 13729 // If we're filling in a static method where we used to have an 13730 // implicit member access, rewrite to a simple decl ref. 13731 if (MemExpr->isImplicitAccess()) { 13732 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13733 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13734 MemExpr->getQualifierLoc(), 13735 MemExpr->getTemplateKeywordLoc(), 13736 Fn, 13737 /*enclosing*/ false, 13738 MemExpr->getMemberLoc(), 13739 Fn->getType(), 13740 VK_LValue, 13741 Found.getDecl(), 13742 TemplateArgs); 13743 MarkDeclRefReferenced(DRE); 13744 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13745 return DRE; 13746 } else { 13747 SourceLocation Loc = MemExpr->getMemberLoc(); 13748 if (MemExpr->getQualifier()) 13749 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13750 CheckCXXThisCapture(Loc); 13751 Base = new (Context) CXXThisExpr(Loc, 13752 MemExpr->getBaseType(), 13753 /*isImplicit=*/true); 13754 } 13755 } else 13756 Base = MemExpr->getBase(); 13757 13758 ExprValueKind valueKind; 13759 QualType type; 13760 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13761 valueKind = VK_LValue; 13762 type = Fn->getType(); 13763 } else { 13764 valueKind = VK_RValue; 13765 type = Context.BoundMemberTy; 13766 } 13767 13768 MemberExpr *ME = MemberExpr::Create( 13769 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13770 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13771 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13772 OK_Ordinary); 13773 ME->setHadMultipleCandidates(true); 13774 MarkMemberReferenced(ME); 13775 return ME; 13776 } 13777 13778 llvm_unreachable("Invalid reference to overloaded function"); 13779 } 13780 13781 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13782 DeclAccessPair Found, 13783 FunctionDecl *Fn) { 13784 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13785 } 13786