1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides Sema routines for C++ overloading. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Sema/Overload.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/DeclObjC.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/TypeOrdering.h" 21 #include "clang/Basic/Diagnostic.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Basic/TargetInfo.h" 25 #include "clang/Sema/Initialization.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/SemaInternal.h" 28 #include "clang/Sema/Template.h" 29 #include "clang/Sema/TemplateDeduction.h" 30 #include "llvm/ADT/DenseSet.h" 31 #include "llvm/ADT/Optional.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 42 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 43 return P->hasAttr<PassObjectSizeAttr>(); 44 }); 45 } 46 47 /// A convenience routine for creating a decayed reference to a function. 48 static ExprResult 49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 50 const Expr *Base, bool HadMultipleCandidates, 51 SourceLocation Loc = SourceLocation(), 52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 54 return ExprError(); 55 // If FoundDecl is different from Fn (such as if one is a template 56 // and the other a specialization), make sure DiagnoseUseOfDecl is 57 // called on both. 58 // FIXME: This would be more comprehensively addressed by modifying 59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 60 // being used. 61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 62 return ExprError(); 63 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 64 S.ResolveExceptionSpec(Loc, FPT); 65 DeclRefExpr *DRE = new (S.Context) 66 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 67 if (HadMultipleCandidates) 68 DRE->setHadMultipleCandidates(true); 69 70 S.MarkDeclRefReferenced(DRE, Base); 71 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 72 CK_FunctionToPointerDecay); 73 } 74 75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 76 bool InOverloadResolution, 77 StandardConversionSequence &SCS, 78 bool CStyle, 79 bool AllowObjCWritebackConversion); 80 81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 82 QualType &ToType, 83 bool InOverloadResolution, 84 StandardConversionSequence &SCS, 85 bool CStyle); 86 static OverloadingResult 87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 88 UserDefinedConversionSequence& User, 89 OverloadCandidateSet& Conversions, 90 bool AllowExplicit, 91 bool AllowObjCConversionOnExplicit); 92 93 94 static ImplicitConversionSequence::CompareKind 95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 96 const StandardConversionSequence& SCS1, 97 const StandardConversionSequence& SCS2); 98 99 static ImplicitConversionSequence::CompareKind 100 CompareQualificationConversions(Sema &S, 101 const StandardConversionSequence& SCS1, 102 const StandardConversionSequence& SCS2); 103 104 static ImplicitConversionSequence::CompareKind 105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 106 const StandardConversionSequence& SCS1, 107 const StandardConversionSequence& SCS2); 108 109 /// GetConversionRank - Retrieve the implicit conversion rank 110 /// corresponding to the given implicit conversion kind. 111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 112 static const ImplicitConversionRank 113 Rank[(int)ICK_Num_Conversion_Kinds] = { 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Promotion, 121 ICR_Promotion, 122 ICR_Promotion, 123 ICR_Conversion, 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_OCL_Scalar_Widening, 134 ICR_Complex_Real_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Writeback_Conversion, 138 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 139 // it was omitted by the patch that added 140 // ICK_Zero_Event_Conversion 141 ICR_C_Conversion, 142 ICR_C_Conversion_Extension 143 }; 144 return Rank[(int)Kind]; 145 } 146 147 /// GetImplicitConversionName - Return the name of this kind of 148 /// implicit conversion. 149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 150 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 151 "No conversion", 152 "Lvalue-to-rvalue", 153 "Array-to-pointer", 154 "Function-to-pointer", 155 "Function pointer conversion", 156 "Qualification", 157 "Integral promotion", 158 "Floating point promotion", 159 "Complex promotion", 160 "Integral conversion", 161 "Floating conversion", 162 "Complex conversion", 163 "Floating-integral conversion", 164 "Pointer conversion", 165 "Pointer-to-member conversion", 166 "Boolean conversion", 167 "Compatible-types conversion", 168 "Derived-to-base conversion", 169 "Vector conversion", 170 "Vector splat", 171 "Complex-real conversion", 172 "Block Pointer conversion", 173 "Transparent Union Conversion", 174 "Writeback conversion", 175 "OpenCL Zero Event Conversion", 176 "C specific type conversion", 177 "Incompatible pointer conversion" 178 }; 179 return Name[Kind]; 180 } 181 182 /// StandardConversionSequence - Set the standard conversion 183 /// sequence to the identity conversion. 184 void StandardConversionSequence::setAsIdentityConversion() { 185 First = ICK_Identity; 186 Second = ICK_Identity; 187 Third = ICK_Identity; 188 DeprecatedStringLiteralToCharPtr = false; 189 QualificationIncludesObjCLifetime = false; 190 ReferenceBinding = false; 191 DirectBinding = false; 192 IsLvalueReference = true; 193 BindsToFunctionLvalue = false; 194 BindsToRvalue = false; 195 BindsImplicitObjectArgumentWithoutRefQualifier = false; 196 ObjCLifetimeConversionBinding = false; 197 CopyConstructor = nullptr; 198 } 199 200 /// getRank - Retrieve the rank of this standard conversion sequence 201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 202 /// implicit conversions. 203 ImplicitConversionRank StandardConversionSequence::getRank() const { 204 ImplicitConversionRank Rank = ICR_Exact_Match; 205 if (GetConversionRank(First) > Rank) 206 Rank = GetConversionRank(First); 207 if (GetConversionRank(Second) > Rank) 208 Rank = GetConversionRank(Second); 209 if (GetConversionRank(Third) > Rank) 210 Rank = GetConversionRank(Third); 211 return Rank; 212 } 213 214 /// isPointerConversionToBool - Determines whether this conversion is 215 /// a conversion of a pointer or pointer-to-member to bool. This is 216 /// used as part of the ranking of standard conversion sequences 217 /// (C++ 13.3.3.2p4). 218 bool StandardConversionSequence::isPointerConversionToBool() const { 219 // Note that FromType has not necessarily been transformed by the 220 // array-to-pointer or function-to-pointer implicit conversions, so 221 // check for their presence as well as checking whether FromType is 222 // a pointer. 223 if (getToType(1)->isBooleanType() && 224 (getFromType()->isPointerType() || 225 getFromType()->isMemberPointerType() || 226 getFromType()->isObjCObjectPointerType() || 227 getFromType()->isBlockPointerType() || 228 getFromType()->isNullPtrType() || 229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 230 return true; 231 232 return false; 233 } 234 235 /// isPointerConversionToVoidPointer - Determines whether this 236 /// conversion is a conversion of a pointer to a void pointer. This is 237 /// used as part of the ranking of standard conversion sequences (C++ 238 /// 13.3.3.2p4). 239 bool 240 StandardConversionSequence:: 241 isPointerConversionToVoidPointer(ASTContext& Context) const { 242 QualType FromType = getFromType(); 243 QualType ToType = getToType(1); 244 245 // Note that FromType has not necessarily been transformed by the 246 // array-to-pointer implicit conversion, so check for its presence 247 // and redo the conversion to get a pointer. 248 if (First == ICK_Array_To_Pointer) 249 FromType = Context.getArrayDecayedType(FromType); 250 251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 253 return ToPtrType->getPointeeType()->isVoidType(); 254 255 return false; 256 } 257 258 /// Skip any implicit casts which could be either part of a narrowing conversion 259 /// or after one in an implicit conversion. 260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 261 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 262 switch (ICE->getCastKind()) { 263 case CK_NoOp: 264 case CK_IntegralCast: 265 case CK_IntegralToBoolean: 266 case CK_IntegralToFloating: 267 case CK_BooleanToSignedIntegral: 268 case CK_FloatingToIntegral: 269 case CK_FloatingToBoolean: 270 case CK_FloatingCast: 271 Converted = ICE->getSubExpr(); 272 continue; 273 274 default: 275 return Converted; 276 } 277 } 278 279 return Converted; 280 } 281 282 /// Check if this standard conversion sequence represents a narrowing 283 /// conversion, according to C++11 [dcl.init.list]p7. 284 /// 285 /// \param Ctx The AST context. 286 /// \param Converted The result of applying this standard conversion sequence. 287 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 288 /// value of the expression prior to the narrowing conversion. 289 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 290 /// type of the expression prior to the narrowing conversion. 291 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 292 /// from floating point types to integral types should be ignored. 293 NarrowingKind StandardConversionSequence::getNarrowingKind( 294 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 295 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 296 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 297 298 // C++11 [dcl.init.list]p7: 299 // A narrowing conversion is an implicit conversion ... 300 QualType FromType = getToType(0); 301 QualType ToType = getToType(1); 302 303 // A conversion to an enumeration type is narrowing if the conversion to 304 // the underlying type is narrowing. This only arises for expressions of 305 // the form 'Enum{init}'. 306 if (auto *ET = ToType->getAs<EnumType>()) 307 ToType = ET->getDecl()->getIntegerType(); 308 309 switch (Second) { 310 // 'bool' is an integral type; dispatch to the right place to handle it. 311 case ICK_Boolean_Conversion: 312 if (FromType->isRealFloatingType()) 313 goto FloatingIntegralConversion; 314 if (FromType->isIntegralOrUnscopedEnumerationType()) 315 goto IntegralConversion; 316 // Boolean conversions can be from pointers and pointers to members 317 // [conv.bool], and those aren't considered narrowing conversions. 318 return NK_Not_Narrowing; 319 320 // -- from a floating-point type to an integer type, or 321 // 322 // -- from an integer type or unscoped enumeration type to a floating-point 323 // type, except where the source is a constant expression and the actual 324 // value after conversion will fit into the target type and will produce 325 // the original value when converted back to the original type, or 326 case ICK_Floating_Integral: 327 FloatingIntegralConversion: 328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 329 return NK_Type_Narrowing; 330 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 331 ToType->isRealFloatingType()) { 332 if (IgnoreFloatToIntegralConversion) 333 return NK_Not_Narrowing; 334 llvm::APSInt IntConstantValue; 335 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 336 assert(Initializer && "Unknown conversion expression"); 337 338 // If it's value-dependent, we can't tell whether it's narrowing. 339 if (Initializer->isValueDependent()) 340 return NK_Dependent_Narrowing; 341 342 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 343 // Convert the integer to the floating type. 344 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 345 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 346 llvm::APFloat::rmNearestTiesToEven); 347 // And back. 348 llvm::APSInt ConvertedValue = IntConstantValue; 349 bool ignored; 350 Result.convertToInteger(ConvertedValue, 351 llvm::APFloat::rmTowardZero, &ignored); 352 // If the resulting value is different, this was a narrowing conversion. 353 if (IntConstantValue != ConvertedValue) { 354 ConstantValue = APValue(IntConstantValue); 355 ConstantType = Initializer->getType(); 356 return NK_Constant_Narrowing; 357 } 358 } else { 359 // Variables are always narrowings. 360 return NK_Variable_Narrowing; 361 } 362 } 363 return NK_Not_Narrowing; 364 365 // -- from long double to double or float, or from double to float, except 366 // where the source is a constant expression and the actual value after 367 // conversion is within the range of values that can be represented (even 368 // if it cannot be represented exactly), or 369 case ICK_Floating_Conversion: 370 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 371 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 372 // FromType is larger than ToType. 373 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 374 375 // If it's value-dependent, we can't tell whether it's narrowing. 376 if (Initializer->isValueDependent()) 377 return NK_Dependent_Narrowing; 378 379 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 380 // Constant! 381 assert(ConstantValue.isFloat()); 382 llvm::APFloat FloatVal = ConstantValue.getFloat(); 383 // Convert the source value into the target type. 384 bool ignored; 385 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 386 Ctx.getFloatTypeSemantics(ToType), 387 llvm::APFloat::rmNearestTiesToEven, &ignored); 388 // If there was no overflow, the source value is within the range of 389 // values that can be represented. 390 if (ConvertStatus & llvm::APFloat::opOverflow) { 391 ConstantType = Initializer->getType(); 392 return NK_Constant_Narrowing; 393 } 394 } else { 395 return NK_Variable_Narrowing; 396 } 397 } 398 return NK_Not_Narrowing; 399 400 // -- from an integer type or unscoped enumeration type to an integer type 401 // that cannot represent all the values of the original type, except where 402 // the source is a constant expression and the actual value after 403 // conversion will fit into the target type and will produce the original 404 // value when converted back to the original type. 405 case ICK_Integral_Conversion: 406 IntegralConversion: { 407 assert(FromType->isIntegralOrUnscopedEnumerationType()); 408 assert(ToType->isIntegralOrUnscopedEnumerationType()); 409 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 410 const unsigned FromWidth = Ctx.getIntWidth(FromType); 411 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 412 const unsigned ToWidth = Ctx.getIntWidth(ToType); 413 414 if (FromWidth > ToWidth || 415 (FromWidth == ToWidth && FromSigned != ToSigned) || 416 (FromSigned && !ToSigned)) { 417 // Not all values of FromType can be represented in ToType. 418 llvm::APSInt InitializerValue; 419 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 420 421 // If it's value-dependent, we can't tell whether it's narrowing. 422 if (Initializer->isValueDependent()) 423 return NK_Dependent_Narrowing; 424 425 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 426 // Such conversions on variables are always narrowing. 427 return NK_Variable_Narrowing; 428 } 429 bool Narrowing = false; 430 if (FromWidth < ToWidth) { 431 // Negative -> unsigned is narrowing. Otherwise, more bits is never 432 // narrowing. 433 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 434 Narrowing = true; 435 } else { 436 // Add a bit to the InitializerValue so we don't have to worry about 437 // signed vs. unsigned comparisons. 438 InitializerValue = InitializerValue.extend( 439 InitializerValue.getBitWidth() + 1); 440 // Convert the initializer to and from the target width and signed-ness. 441 llvm::APSInt ConvertedValue = InitializerValue; 442 ConvertedValue = ConvertedValue.trunc(ToWidth); 443 ConvertedValue.setIsSigned(ToSigned); 444 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 445 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 446 // If the result is different, this was a narrowing conversion. 447 if (ConvertedValue != InitializerValue) 448 Narrowing = true; 449 } 450 if (Narrowing) { 451 ConstantType = Initializer->getType(); 452 ConstantValue = APValue(InitializerValue); 453 return NK_Constant_Narrowing; 454 } 455 } 456 return NK_Not_Narrowing; 457 } 458 459 default: 460 // Other kinds of conversions are not narrowings. 461 return NK_Not_Narrowing; 462 } 463 } 464 465 /// dump - Print this standard conversion sequence to standard 466 /// error. Useful for debugging overloading issues. 467 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 468 raw_ostream &OS = llvm::errs(); 469 bool PrintedSomething = false; 470 if (First != ICK_Identity) { 471 OS << GetImplicitConversionName(First); 472 PrintedSomething = true; 473 } 474 475 if (Second != ICK_Identity) { 476 if (PrintedSomething) { 477 OS << " -> "; 478 } 479 OS << GetImplicitConversionName(Second); 480 481 if (CopyConstructor) { 482 OS << " (by copy constructor)"; 483 } else if (DirectBinding) { 484 OS << " (direct reference binding)"; 485 } else if (ReferenceBinding) { 486 OS << " (reference binding)"; 487 } 488 PrintedSomething = true; 489 } 490 491 if (Third != ICK_Identity) { 492 if (PrintedSomething) { 493 OS << " -> "; 494 } 495 OS << GetImplicitConversionName(Third); 496 PrintedSomething = true; 497 } 498 499 if (!PrintedSomething) { 500 OS << "No conversions required"; 501 } 502 } 503 504 /// dump - Print this user-defined conversion sequence to standard 505 /// error. Useful for debugging overloading issues. 506 void UserDefinedConversionSequence::dump() const { 507 raw_ostream &OS = llvm::errs(); 508 if (Before.First || Before.Second || Before.Third) { 509 Before.dump(); 510 OS << " -> "; 511 } 512 if (ConversionFunction) 513 OS << '\'' << *ConversionFunction << '\''; 514 else 515 OS << "aggregate initialization"; 516 if (After.First || After.Second || After.Third) { 517 OS << " -> "; 518 After.dump(); 519 } 520 } 521 522 /// dump - Print this implicit conversion sequence to standard 523 /// error. Useful for debugging overloading issues. 524 void ImplicitConversionSequence::dump() const { 525 raw_ostream &OS = llvm::errs(); 526 if (isStdInitializerListElement()) 527 OS << "Worst std::initializer_list element conversion: "; 528 switch (ConversionKind) { 529 case StandardConversion: 530 OS << "Standard conversion: "; 531 Standard.dump(); 532 break; 533 case UserDefinedConversion: 534 OS << "User-defined conversion: "; 535 UserDefined.dump(); 536 break; 537 case EllipsisConversion: 538 OS << "Ellipsis conversion"; 539 break; 540 case AmbiguousConversion: 541 OS << "Ambiguous conversion"; 542 break; 543 case BadConversion: 544 OS << "Bad conversion"; 545 break; 546 } 547 548 OS << "\n"; 549 } 550 551 void AmbiguousConversionSequence::construct() { 552 new (&conversions()) ConversionSet(); 553 } 554 555 void AmbiguousConversionSequence::destruct() { 556 conversions().~ConversionSet(); 557 } 558 559 void 560 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 561 FromTypePtr = O.FromTypePtr; 562 ToTypePtr = O.ToTypePtr; 563 new (&conversions()) ConversionSet(O.conversions()); 564 } 565 566 namespace { 567 // Structure used by DeductionFailureInfo to store 568 // template argument information. 569 struct DFIArguments { 570 TemplateArgument FirstArg; 571 TemplateArgument SecondArg; 572 }; 573 // Structure used by DeductionFailureInfo to store 574 // template parameter and template argument information. 575 struct DFIParamWithArguments : DFIArguments { 576 TemplateParameter Param; 577 }; 578 // Structure used by DeductionFailureInfo to store template argument 579 // information and the index of the problematic call argument. 580 struct DFIDeducedMismatchArgs : DFIArguments { 581 TemplateArgumentList *TemplateArgs; 582 unsigned CallArgIndex; 583 }; 584 } 585 586 /// Convert from Sema's representation of template deduction information 587 /// to the form used in overload-candidate information. 588 DeductionFailureInfo 589 clang::MakeDeductionFailureInfo(ASTContext &Context, 590 Sema::TemplateDeductionResult TDK, 591 TemplateDeductionInfo &Info) { 592 DeductionFailureInfo Result; 593 Result.Result = static_cast<unsigned>(TDK); 594 Result.HasDiagnostic = false; 595 switch (TDK) { 596 case Sema::TDK_Invalid: 597 case Sema::TDK_InstantiationDepth: 598 case Sema::TDK_TooManyArguments: 599 case Sema::TDK_TooFewArguments: 600 case Sema::TDK_MiscellaneousDeductionFailure: 601 case Sema::TDK_CUDATargetMismatch: 602 Result.Data = nullptr; 603 break; 604 605 case Sema::TDK_Incomplete: 606 case Sema::TDK_InvalidExplicitArguments: 607 Result.Data = Info.Param.getOpaqueValue(); 608 break; 609 610 case Sema::TDK_DeducedMismatch: 611 case Sema::TDK_DeducedMismatchNested: { 612 // FIXME: Should allocate from normal heap so that we can free this later. 613 auto *Saved = new (Context) DFIDeducedMismatchArgs; 614 Saved->FirstArg = Info.FirstArg; 615 Saved->SecondArg = Info.SecondArg; 616 Saved->TemplateArgs = Info.take(); 617 Saved->CallArgIndex = Info.CallArgIndex; 618 Result.Data = Saved; 619 break; 620 } 621 622 case Sema::TDK_NonDeducedMismatch: { 623 // FIXME: Should allocate from normal heap so that we can free this later. 624 DFIArguments *Saved = new (Context) DFIArguments; 625 Saved->FirstArg = Info.FirstArg; 626 Saved->SecondArg = Info.SecondArg; 627 Result.Data = Saved; 628 break; 629 } 630 631 case Sema::TDK_IncompletePack: 632 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 633 case Sema::TDK_Inconsistent: 634 case Sema::TDK_Underqualified: { 635 // FIXME: Should allocate from normal heap so that we can free this later. 636 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 637 Saved->Param = Info.Param; 638 Saved->FirstArg = Info.FirstArg; 639 Saved->SecondArg = Info.SecondArg; 640 Result.Data = Saved; 641 break; 642 } 643 644 case Sema::TDK_SubstitutionFailure: 645 Result.Data = Info.take(); 646 if (Info.hasSFINAEDiagnostic()) { 647 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 648 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 649 Info.takeSFINAEDiagnostic(*Diag); 650 Result.HasDiagnostic = true; 651 } 652 break; 653 654 case Sema::TDK_Success: 655 case Sema::TDK_NonDependentConversionFailure: 656 llvm_unreachable("not a deduction failure"); 657 } 658 659 return Result; 660 } 661 662 void DeductionFailureInfo::Destroy() { 663 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 664 case Sema::TDK_Success: 665 case Sema::TDK_Invalid: 666 case Sema::TDK_InstantiationDepth: 667 case Sema::TDK_Incomplete: 668 case Sema::TDK_TooManyArguments: 669 case Sema::TDK_TooFewArguments: 670 case Sema::TDK_InvalidExplicitArguments: 671 case Sema::TDK_CUDATargetMismatch: 672 case Sema::TDK_NonDependentConversionFailure: 673 break; 674 675 case Sema::TDK_IncompletePack: 676 case Sema::TDK_Inconsistent: 677 case Sema::TDK_Underqualified: 678 case Sema::TDK_DeducedMismatch: 679 case Sema::TDK_DeducedMismatchNested: 680 case Sema::TDK_NonDeducedMismatch: 681 // FIXME: Destroy the data? 682 Data = nullptr; 683 break; 684 685 case Sema::TDK_SubstitutionFailure: 686 // FIXME: Destroy the template argument list? 687 Data = nullptr; 688 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 689 Diag->~PartialDiagnosticAt(); 690 HasDiagnostic = false; 691 } 692 break; 693 694 // Unhandled 695 case Sema::TDK_MiscellaneousDeductionFailure: 696 break; 697 } 698 } 699 700 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 701 if (HasDiagnostic) 702 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 703 return nullptr; 704 } 705 706 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 707 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 708 case Sema::TDK_Success: 709 case Sema::TDK_Invalid: 710 case Sema::TDK_InstantiationDepth: 711 case Sema::TDK_TooManyArguments: 712 case Sema::TDK_TooFewArguments: 713 case Sema::TDK_SubstitutionFailure: 714 case Sema::TDK_DeducedMismatch: 715 case Sema::TDK_DeducedMismatchNested: 716 case Sema::TDK_NonDeducedMismatch: 717 case Sema::TDK_CUDATargetMismatch: 718 case Sema::TDK_NonDependentConversionFailure: 719 return TemplateParameter(); 720 721 case Sema::TDK_Incomplete: 722 case Sema::TDK_InvalidExplicitArguments: 723 return TemplateParameter::getFromOpaqueValue(Data); 724 725 case Sema::TDK_IncompletePack: 726 case Sema::TDK_Inconsistent: 727 case Sema::TDK_Underqualified: 728 return static_cast<DFIParamWithArguments*>(Data)->Param; 729 730 // Unhandled 731 case Sema::TDK_MiscellaneousDeductionFailure: 732 break; 733 } 734 735 return TemplateParameter(); 736 } 737 738 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 739 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 740 case Sema::TDK_Success: 741 case Sema::TDK_Invalid: 742 case Sema::TDK_InstantiationDepth: 743 case Sema::TDK_TooManyArguments: 744 case Sema::TDK_TooFewArguments: 745 case Sema::TDK_Incomplete: 746 case Sema::TDK_IncompletePack: 747 case Sema::TDK_InvalidExplicitArguments: 748 case Sema::TDK_Inconsistent: 749 case Sema::TDK_Underqualified: 750 case Sema::TDK_NonDeducedMismatch: 751 case Sema::TDK_CUDATargetMismatch: 752 case Sema::TDK_NonDependentConversionFailure: 753 return nullptr; 754 755 case Sema::TDK_DeducedMismatch: 756 case Sema::TDK_DeducedMismatchNested: 757 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 758 759 case Sema::TDK_SubstitutionFailure: 760 return static_cast<TemplateArgumentList*>(Data); 761 762 // Unhandled 763 case Sema::TDK_MiscellaneousDeductionFailure: 764 break; 765 } 766 767 return nullptr; 768 } 769 770 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 771 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 772 case Sema::TDK_Success: 773 case Sema::TDK_Invalid: 774 case Sema::TDK_InstantiationDepth: 775 case Sema::TDK_Incomplete: 776 case Sema::TDK_TooManyArguments: 777 case Sema::TDK_TooFewArguments: 778 case Sema::TDK_InvalidExplicitArguments: 779 case Sema::TDK_SubstitutionFailure: 780 case Sema::TDK_CUDATargetMismatch: 781 case Sema::TDK_NonDependentConversionFailure: 782 return nullptr; 783 784 case Sema::TDK_IncompletePack: 785 case Sema::TDK_Inconsistent: 786 case Sema::TDK_Underqualified: 787 case Sema::TDK_DeducedMismatch: 788 case Sema::TDK_DeducedMismatchNested: 789 case Sema::TDK_NonDeducedMismatch: 790 return &static_cast<DFIArguments*>(Data)->FirstArg; 791 792 // Unhandled 793 case Sema::TDK_MiscellaneousDeductionFailure: 794 break; 795 } 796 797 return nullptr; 798 } 799 800 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 801 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 802 case Sema::TDK_Success: 803 case Sema::TDK_Invalid: 804 case Sema::TDK_InstantiationDepth: 805 case Sema::TDK_Incomplete: 806 case Sema::TDK_IncompletePack: 807 case Sema::TDK_TooManyArguments: 808 case Sema::TDK_TooFewArguments: 809 case Sema::TDK_InvalidExplicitArguments: 810 case Sema::TDK_SubstitutionFailure: 811 case Sema::TDK_CUDATargetMismatch: 812 case Sema::TDK_NonDependentConversionFailure: 813 return nullptr; 814 815 case Sema::TDK_Inconsistent: 816 case Sema::TDK_Underqualified: 817 case Sema::TDK_DeducedMismatch: 818 case Sema::TDK_DeducedMismatchNested: 819 case Sema::TDK_NonDeducedMismatch: 820 return &static_cast<DFIArguments*>(Data)->SecondArg; 821 822 // Unhandled 823 case Sema::TDK_MiscellaneousDeductionFailure: 824 break; 825 } 826 827 return nullptr; 828 } 829 830 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 831 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 832 case Sema::TDK_DeducedMismatch: 833 case Sema::TDK_DeducedMismatchNested: 834 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 835 836 default: 837 return llvm::None; 838 } 839 } 840 841 void OverloadCandidateSet::destroyCandidates() { 842 for (iterator i = begin(), e = end(); i != e; ++i) { 843 for (auto &C : i->Conversions) 844 C.~ImplicitConversionSequence(); 845 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 846 i->DeductionFailure.Destroy(); 847 } 848 } 849 850 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 851 destroyCandidates(); 852 SlabAllocator.Reset(); 853 NumInlineBytesUsed = 0; 854 Candidates.clear(); 855 Functions.clear(); 856 Kind = CSK; 857 } 858 859 namespace { 860 class UnbridgedCastsSet { 861 struct Entry { 862 Expr **Addr; 863 Expr *Saved; 864 }; 865 SmallVector<Entry, 2> Entries; 866 867 public: 868 void save(Sema &S, Expr *&E) { 869 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 870 Entry entry = { &E, E }; 871 Entries.push_back(entry); 872 E = S.stripARCUnbridgedCast(E); 873 } 874 875 void restore() { 876 for (SmallVectorImpl<Entry>::iterator 877 i = Entries.begin(), e = Entries.end(); i != e; ++i) 878 *i->Addr = i->Saved; 879 } 880 }; 881 } 882 883 /// checkPlaceholderForOverload - Do any interesting placeholder-like 884 /// preprocessing on the given expression. 885 /// 886 /// \param unbridgedCasts a collection to which to add unbridged casts; 887 /// without this, they will be immediately diagnosed as errors 888 /// 889 /// Return true on unrecoverable error. 890 static bool 891 checkPlaceholderForOverload(Sema &S, Expr *&E, 892 UnbridgedCastsSet *unbridgedCasts = nullptr) { 893 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 894 // We can't handle overloaded expressions here because overload 895 // resolution might reasonably tweak them. 896 if (placeholder->getKind() == BuiltinType::Overload) return false; 897 898 // If the context potentially accepts unbridged ARC casts, strip 899 // the unbridged cast and add it to the collection for later restoration. 900 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 901 unbridgedCasts) { 902 unbridgedCasts->save(S, E); 903 return false; 904 } 905 906 // Go ahead and check everything else. 907 ExprResult result = S.CheckPlaceholderExpr(E); 908 if (result.isInvalid()) 909 return true; 910 911 E = result.get(); 912 return false; 913 } 914 915 // Nothing to do. 916 return false; 917 } 918 919 /// checkArgPlaceholdersForOverload - Check a set of call operands for 920 /// placeholders. 921 static bool checkArgPlaceholdersForOverload(Sema &S, 922 MultiExprArg Args, 923 UnbridgedCastsSet &unbridged) { 924 for (unsigned i = 0, e = Args.size(); i != e; ++i) 925 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 926 return true; 927 928 return false; 929 } 930 931 /// Determine whether the given New declaration is an overload of the 932 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 933 /// New and Old cannot be overloaded, e.g., if New has the same signature as 934 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 935 /// functions (or function templates) at all. When it does return Ovl_Match or 936 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 937 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 938 /// declaration. 939 /// 940 /// Example: Given the following input: 941 /// 942 /// void f(int, float); // #1 943 /// void f(int, int); // #2 944 /// int f(int, int); // #3 945 /// 946 /// When we process #1, there is no previous declaration of "f", so IsOverload 947 /// will not be used. 948 /// 949 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 950 /// the parameter types, we see that #1 and #2 are overloaded (since they have 951 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 952 /// unchanged. 953 /// 954 /// When we process #3, Old is an overload set containing #1 and #2. We compare 955 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 956 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 957 /// functions are not part of the signature), IsOverload returns Ovl_Match and 958 /// MatchedDecl will be set to point to the FunctionDecl for #2. 959 /// 960 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 961 /// by a using declaration. The rules for whether to hide shadow declarations 962 /// ignore some properties which otherwise figure into a function template's 963 /// signature. 964 Sema::OverloadKind 965 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 966 NamedDecl *&Match, bool NewIsUsingDecl) { 967 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 968 I != E; ++I) { 969 NamedDecl *OldD = *I; 970 971 bool OldIsUsingDecl = false; 972 if (isa<UsingShadowDecl>(OldD)) { 973 OldIsUsingDecl = true; 974 975 // We can always introduce two using declarations into the same 976 // context, even if they have identical signatures. 977 if (NewIsUsingDecl) continue; 978 979 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 980 } 981 982 // A using-declaration does not conflict with another declaration 983 // if one of them is hidden. 984 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 985 continue; 986 987 // If either declaration was introduced by a using declaration, 988 // we'll need to use slightly different rules for matching. 989 // Essentially, these rules are the normal rules, except that 990 // function templates hide function templates with different 991 // return types or template parameter lists. 992 bool UseMemberUsingDeclRules = 993 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 994 !New->getFriendObjectKind(); 995 996 if (FunctionDecl *OldF = OldD->getAsFunction()) { 997 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 998 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 999 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1000 continue; 1001 } 1002 1003 if (!isa<FunctionTemplateDecl>(OldD) && 1004 !shouldLinkPossiblyHiddenDecl(*I, New)) 1005 continue; 1006 1007 Match = *I; 1008 return Ovl_Match; 1009 } 1010 1011 // Builtins that have custom typechecking or have a reference should 1012 // not be overloadable or redeclarable. 1013 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1014 Match = *I; 1015 return Ovl_NonFunction; 1016 } 1017 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1018 // We can overload with these, which can show up when doing 1019 // redeclaration checks for UsingDecls. 1020 assert(Old.getLookupKind() == LookupUsingDeclName); 1021 } else if (isa<TagDecl>(OldD)) { 1022 // We can always overload with tags by hiding them. 1023 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1024 // Optimistically assume that an unresolved using decl will 1025 // overload; if it doesn't, we'll have to diagnose during 1026 // template instantiation. 1027 // 1028 // Exception: if the scope is dependent and this is not a class 1029 // member, the using declaration can only introduce an enumerator. 1030 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1031 Match = *I; 1032 return Ovl_NonFunction; 1033 } 1034 } else { 1035 // (C++ 13p1): 1036 // Only function declarations can be overloaded; object and type 1037 // declarations cannot be overloaded. 1038 Match = *I; 1039 return Ovl_NonFunction; 1040 } 1041 } 1042 1043 // C++ [temp.friend]p1: 1044 // For a friend function declaration that is not a template declaration: 1045 // -- if the name of the friend is a qualified or unqualified template-id, 1046 // [...], otherwise 1047 // -- if the name of the friend is a qualified-id and a matching 1048 // non-template function is found in the specified class or namespace, 1049 // the friend declaration refers to that function, otherwise, 1050 // -- if the name of the friend is a qualified-id and a matching function 1051 // template is found in the specified class or namespace, the friend 1052 // declaration refers to the deduced specialization of that function 1053 // template, otherwise 1054 // -- the name shall be an unqualified-id [...] 1055 // If we get here for a qualified friend declaration, we've just reached the 1056 // third bullet. If the type of the friend is dependent, skip this lookup 1057 // until instantiation. 1058 if (New->getFriendObjectKind() && New->getQualifier() && 1059 !New->getDescribedFunctionTemplate() && 1060 !New->getDependentSpecializationInfo() && 1061 !New->getType()->isDependentType()) { 1062 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1063 TemplateSpecResult.addAllDecls(Old); 1064 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1065 /*QualifiedFriend*/true)) { 1066 New->setInvalidDecl(); 1067 return Ovl_Overload; 1068 } 1069 1070 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1071 return Ovl_Match; 1072 } 1073 1074 return Ovl_Overload; 1075 } 1076 1077 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1078 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1079 // C++ [basic.start.main]p2: This function shall not be overloaded. 1080 if (New->isMain()) 1081 return false; 1082 1083 // MSVCRT user defined entry points cannot be overloaded. 1084 if (New->isMSVCRTEntryPoint()) 1085 return false; 1086 1087 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1088 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1089 1090 // C++ [temp.fct]p2: 1091 // A function template can be overloaded with other function templates 1092 // and with normal (non-template) functions. 1093 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1094 return true; 1095 1096 // Is the function New an overload of the function Old? 1097 QualType OldQType = Context.getCanonicalType(Old->getType()); 1098 QualType NewQType = Context.getCanonicalType(New->getType()); 1099 1100 // Compare the signatures (C++ 1.3.10) of the two functions to 1101 // determine whether they are overloads. If we find any mismatch 1102 // in the signature, they are overloads. 1103 1104 // If either of these functions is a K&R-style function (no 1105 // prototype), then we consider them to have matching signatures. 1106 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1107 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1108 return false; 1109 1110 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1111 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1112 1113 // The signature of a function includes the types of its 1114 // parameters (C++ 1.3.10), which includes the presence or absence 1115 // of the ellipsis; see C++ DR 357). 1116 if (OldQType != NewQType && 1117 (OldType->getNumParams() != NewType->getNumParams() || 1118 OldType->isVariadic() != NewType->isVariadic() || 1119 !FunctionParamTypesAreEqual(OldType, NewType))) 1120 return true; 1121 1122 // C++ [temp.over.link]p4: 1123 // The signature of a function template consists of its function 1124 // signature, its return type and its template parameter list. The names 1125 // of the template parameters are significant only for establishing the 1126 // relationship between the template parameters and the rest of the 1127 // signature. 1128 // 1129 // We check the return type and template parameter lists for function 1130 // templates first; the remaining checks follow. 1131 // 1132 // However, we don't consider either of these when deciding whether 1133 // a member introduced by a shadow declaration is hidden. 1134 if (!UseMemberUsingDeclRules && NewTemplate && 1135 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1136 OldTemplate->getTemplateParameters(), 1137 false, TPL_TemplateMatch) || 1138 !Context.hasSameType(Old->getDeclaredReturnType(), 1139 New->getDeclaredReturnType()))) 1140 return true; 1141 1142 // If the function is a class member, its signature includes the 1143 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1144 // 1145 // As part of this, also check whether one of the member functions 1146 // is static, in which case they are not overloads (C++ 1147 // 13.1p2). While not part of the definition of the signature, 1148 // this check is important to determine whether these functions 1149 // can be overloaded. 1150 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1151 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1152 if (OldMethod && NewMethod && 1153 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1154 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1155 if (!UseMemberUsingDeclRules && 1156 (OldMethod->getRefQualifier() == RQ_None || 1157 NewMethod->getRefQualifier() == RQ_None)) { 1158 // C++0x [over.load]p2: 1159 // - Member function declarations with the same name and the same 1160 // parameter-type-list as well as member function template 1161 // declarations with the same name, the same parameter-type-list, and 1162 // the same template parameter lists cannot be overloaded if any of 1163 // them, but not all, have a ref-qualifier (8.3.5). 1164 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1165 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1166 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1167 } 1168 return true; 1169 } 1170 1171 // We may not have applied the implicit const for a constexpr member 1172 // function yet (because we haven't yet resolved whether this is a static 1173 // or non-static member function). Add it now, on the assumption that this 1174 // is a redeclaration of OldMethod. 1175 auto OldQuals = OldMethod->getMethodQualifiers(); 1176 auto NewQuals = NewMethod->getMethodQualifiers(); 1177 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1178 !isa<CXXConstructorDecl>(NewMethod)) 1179 NewQuals.addConst(); 1180 // We do not allow overloading based off of '__restrict'. 1181 OldQuals.removeRestrict(); 1182 NewQuals.removeRestrict(); 1183 if (OldQuals != NewQuals) 1184 return true; 1185 } 1186 1187 // Though pass_object_size is placed on parameters and takes an argument, we 1188 // consider it to be a function-level modifier for the sake of function 1189 // identity. Either the function has one or more parameters with 1190 // pass_object_size or it doesn't. 1191 if (functionHasPassObjectSizeParams(New) != 1192 functionHasPassObjectSizeParams(Old)) 1193 return true; 1194 1195 // enable_if attributes are an order-sensitive part of the signature. 1196 for (specific_attr_iterator<EnableIfAttr> 1197 NewI = New->specific_attr_begin<EnableIfAttr>(), 1198 NewE = New->specific_attr_end<EnableIfAttr>(), 1199 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1200 OldE = Old->specific_attr_end<EnableIfAttr>(); 1201 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1202 if (NewI == NewE || OldI == OldE) 1203 return true; 1204 llvm::FoldingSetNodeID NewID, OldID; 1205 NewI->getCond()->Profile(NewID, Context, true); 1206 OldI->getCond()->Profile(OldID, Context, true); 1207 if (NewID != OldID) 1208 return true; 1209 } 1210 1211 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1212 // Don't allow overloading of destructors. (In theory we could, but it 1213 // would be a giant change to clang.) 1214 if (isa<CXXDestructorDecl>(New)) 1215 return false; 1216 1217 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1218 OldTarget = IdentifyCUDATarget(Old); 1219 if (NewTarget == CFT_InvalidTarget) 1220 return false; 1221 1222 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1223 1224 // Allow overloading of functions with same signature and different CUDA 1225 // target attributes. 1226 return NewTarget != OldTarget; 1227 } 1228 1229 // The signatures match; this is not an overload. 1230 return false; 1231 } 1232 1233 /// Tries a user-defined conversion from From to ToType. 1234 /// 1235 /// Produces an implicit conversion sequence for when a standard conversion 1236 /// is not an option. See TryImplicitConversion for more information. 1237 static ImplicitConversionSequence 1238 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1239 bool SuppressUserConversions, 1240 bool AllowExplicit, 1241 bool InOverloadResolution, 1242 bool CStyle, 1243 bool AllowObjCWritebackConversion, 1244 bool AllowObjCConversionOnExplicit) { 1245 ImplicitConversionSequence ICS; 1246 1247 if (SuppressUserConversions) { 1248 // We're not in the case above, so there is no conversion that 1249 // we can perform. 1250 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1251 return ICS; 1252 } 1253 1254 // Attempt user-defined conversion. 1255 OverloadCandidateSet Conversions(From->getExprLoc(), 1256 OverloadCandidateSet::CSK_Normal); 1257 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1258 Conversions, AllowExplicit, 1259 AllowObjCConversionOnExplicit)) { 1260 case OR_Success: 1261 case OR_Deleted: 1262 ICS.setUserDefined(); 1263 // C++ [over.ics.user]p4: 1264 // A conversion of an expression of class type to the same class 1265 // type is given Exact Match rank, and a conversion of an 1266 // expression of class type to a base class of that type is 1267 // given Conversion rank, in spite of the fact that a copy 1268 // constructor (i.e., a user-defined conversion function) is 1269 // called for those cases. 1270 if (CXXConstructorDecl *Constructor 1271 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1272 QualType FromCanon 1273 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1274 QualType ToCanon 1275 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1276 if (Constructor->isCopyConstructor() && 1277 (FromCanon == ToCanon || 1278 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1279 // Turn this into a "standard" conversion sequence, so that it 1280 // gets ranked with standard conversion sequences. 1281 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1282 ICS.setStandard(); 1283 ICS.Standard.setAsIdentityConversion(); 1284 ICS.Standard.setFromType(From->getType()); 1285 ICS.Standard.setAllToTypes(ToType); 1286 ICS.Standard.CopyConstructor = Constructor; 1287 ICS.Standard.FoundCopyConstructor = Found; 1288 if (ToCanon != FromCanon) 1289 ICS.Standard.Second = ICK_Derived_To_Base; 1290 } 1291 } 1292 break; 1293 1294 case OR_Ambiguous: 1295 ICS.setAmbiguous(); 1296 ICS.Ambiguous.setFromType(From->getType()); 1297 ICS.Ambiguous.setToType(ToType); 1298 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1299 Cand != Conversions.end(); ++Cand) 1300 if (Cand->Viable) 1301 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1302 break; 1303 1304 // Fall through. 1305 case OR_No_Viable_Function: 1306 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1307 break; 1308 } 1309 1310 return ICS; 1311 } 1312 1313 /// TryImplicitConversion - Attempt to perform an implicit conversion 1314 /// from the given expression (Expr) to the given type (ToType). This 1315 /// function returns an implicit conversion sequence that can be used 1316 /// to perform the initialization. Given 1317 /// 1318 /// void f(float f); 1319 /// void g(int i) { f(i); } 1320 /// 1321 /// this routine would produce an implicit conversion sequence to 1322 /// describe the initialization of f from i, which will be a standard 1323 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1324 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1325 // 1326 /// Note that this routine only determines how the conversion can be 1327 /// performed; it does not actually perform the conversion. As such, 1328 /// it will not produce any diagnostics if no conversion is available, 1329 /// but will instead return an implicit conversion sequence of kind 1330 /// "BadConversion". 1331 /// 1332 /// If @p SuppressUserConversions, then user-defined conversions are 1333 /// not permitted. 1334 /// If @p AllowExplicit, then explicit user-defined conversions are 1335 /// permitted. 1336 /// 1337 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1338 /// writeback conversion, which allows __autoreleasing id* parameters to 1339 /// be initialized with __strong id* or __weak id* arguments. 1340 static ImplicitConversionSequence 1341 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1342 bool SuppressUserConversions, 1343 bool AllowExplicit, 1344 bool InOverloadResolution, 1345 bool CStyle, 1346 bool AllowObjCWritebackConversion, 1347 bool AllowObjCConversionOnExplicit) { 1348 ImplicitConversionSequence ICS; 1349 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1350 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1351 ICS.setStandard(); 1352 return ICS; 1353 } 1354 1355 if (!S.getLangOpts().CPlusPlus) { 1356 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1357 return ICS; 1358 } 1359 1360 // C++ [over.ics.user]p4: 1361 // A conversion of an expression of class type to the same class 1362 // type is given Exact Match rank, and a conversion of an 1363 // expression of class type to a base class of that type is 1364 // given Conversion rank, in spite of the fact that a copy/move 1365 // constructor (i.e., a user-defined conversion function) is 1366 // called for those cases. 1367 QualType FromType = From->getType(); 1368 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1369 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1370 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1371 ICS.setStandard(); 1372 ICS.Standard.setAsIdentityConversion(); 1373 ICS.Standard.setFromType(FromType); 1374 ICS.Standard.setAllToTypes(ToType); 1375 1376 // We don't actually check at this point whether there is a valid 1377 // copy/move constructor, since overloading just assumes that it 1378 // exists. When we actually perform initialization, we'll find the 1379 // appropriate constructor to copy the returned object, if needed. 1380 ICS.Standard.CopyConstructor = nullptr; 1381 1382 // Determine whether this is considered a derived-to-base conversion. 1383 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1384 ICS.Standard.Second = ICK_Derived_To_Base; 1385 1386 return ICS; 1387 } 1388 1389 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1390 AllowExplicit, InOverloadResolution, CStyle, 1391 AllowObjCWritebackConversion, 1392 AllowObjCConversionOnExplicit); 1393 } 1394 1395 ImplicitConversionSequence 1396 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1397 bool SuppressUserConversions, 1398 bool AllowExplicit, 1399 bool InOverloadResolution, 1400 bool CStyle, 1401 bool AllowObjCWritebackConversion) { 1402 return ::TryImplicitConversion(*this, From, ToType, 1403 SuppressUserConversions, AllowExplicit, 1404 InOverloadResolution, CStyle, 1405 AllowObjCWritebackConversion, 1406 /*AllowObjCConversionOnExplicit=*/false); 1407 } 1408 1409 /// PerformImplicitConversion - Perform an implicit conversion of the 1410 /// expression From to the type ToType. Returns the 1411 /// converted expression. Flavor is the kind of conversion we're 1412 /// performing, used in the error message. If @p AllowExplicit, 1413 /// explicit user-defined conversions are permitted. 1414 ExprResult 1415 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1416 AssignmentAction Action, bool AllowExplicit) { 1417 ImplicitConversionSequence ICS; 1418 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1419 } 1420 1421 ExprResult 1422 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1423 AssignmentAction Action, bool AllowExplicit, 1424 ImplicitConversionSequence& ICS) { 1425 if (checkPlaceholderForOverload(*this, From)) 1426 return ExprError(); 1427 1428 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1429 bool AllowObjCWritebackConversion 1430 = getLangOpts().ObjCAutoRefCount && 1431 (Action == AA_Passing || Action == AA_Sending); 1432 if (getLangOpts().ObjC) 1433 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1434 From->getType(), From); 1435 ICS = ::TryImplicitConversion(*this, From, ToType, 1436 /*SuppressUserConversions=*/false, 1437 AllowExplicit, 1438 /*InOverloadResolution=*/false, 1439 /*CStyle=*/false, 1440 AllowObjCWritebackConversion, 1441 /*AllowObjCConversionOnExplicit=*/false); 1442 return PerformImplicitConversion(From, ToType, ICS, Action); 1443 } 1444 1445 /// Determine whether the conversion from FromType to ToType is a valid 1446 /// conversion that strips "noexcept" or "noreturn" off the nested function 1447 /// type. 1448 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1449 QualType &ResultTy) { 1450 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1451 return false; 1452 1453 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1454 // or F(t noexcept) -> F(t) 1455 // where F adds one of the following at most once: 1456 // - a pointer 1457 // - a member pointer 1458 // - a block pointer 1459 // Changes here need matching changes in FindCompositePointerType. 1460 CanQualType CanTo = Context.getCanonicalType(ToType); 1461 CanQualType CanFrom = Context.getCanonicalType(FromType); 1462 Type::TypeClass TyClass = CanTo->getTypeClass(); 1463 if (TyClass != CanFrom->getTypeClass()) return false; 1464 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1465 if (TyClass == Type::Pointer) { 1466 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1467 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1468 } else if (TyClass == Type::BlockPointer) { 1469 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1470 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1471 } else if (TyClass == Type::MemberPointer) { 1472 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1473 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1474 // A function pointer conversion cannot change the class of the function. 1475 if (ToMPT->getClass() != FromMPT->getClass()) 1476 return false; 1477 CanTo = ToMPT->getPointeeType(); 1478 CanFrom = FromMPT->getPointeeType(); 1479 } else { 1480 return false; 1481 } 1482 1483 TyClass = CanTo->getTypeClass(); 1484 if (TyClass != CanFrom->getTypeClass()) return false; 1485 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1486 return false; 1487 } 1488 1489 const auto *FromFn = cast<FunctionType>(CanFrom); 1490 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1491 1492 const auto *ToFn = cast<FunctionType>(CanTo); 1493 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1494 1495 bool Changed = false; 1496 1497 // Drop 'noreturn' if not present in target type. 1498 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1499 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1500 Changed = true; 1501 } 1502 1503 // Drop 'noexcept' if not present in target type. 1504 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1505 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1506 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1507 FromFn = cast<FunctionType>( 1508 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1509 EST_None) 1510 .getTypePtr()); 1511 Changed = true; 1512 } 1513 1514 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1515 // only if the ExtParameterInfo lists of the two function prototypes can be 1516 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1517 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1518 bool CanUseToFPT, CanUseFromFPT; 1519 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1520 CanUseFromFPT, NewParamInfos) && 1521 CanUseToFPT && !CanUseFromFPT) { 1522 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1523 ExtInfo.ExtParameterInfos = 1524 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1525 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1526 FromFPT->getParamTypes(), ExtInfo); 1527 FromFn = QT->getAs<FunctionType>(); 1528 Changed = true; 1529 } 1530 } 1531 1532 if (!Changed) 1533 return false; 1534 1535 assert(QualType(FromFn, 0).isCanonical()); 1536 if (QualType(FromFn, 0) != CanTo) return false; 1537 1538 ResultTy = ToType; 1539 return true; 1540 } 1541 1542 /// Determine whether the conversion from FromType to ToType is a valid 1543 /// vector conversion. 1544 /// 1545 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1546 /// conversion. 1547 static bool IsVectorConversion(Sema &S, QualType FromType, 1548 QualType ToType, ImplicitConversionKind &ICK) { 1549 // We need at least one of these types to be a vector type to have a vector 1550 // conversion. 1551 if (!ToType->isVectorType() && !FromType->isVectorType()) 1552 return false; 1553 1554 // Identical types require no conversions. 1555 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1556 return false; 1557 1558 // There are no conversions between extended vector types, only identity. 1559 if (ToType->isExtVectorType()) { 1560 // There are no conversions between extended vector types other than the 1561 // identity conversion. 1562 if (FromType->isExtVectorType()) 1563 return false; 1564 1565 // Vector splat from any arithmetic type to a vector. 1566 if (FromType->isArithmeticType()) { 1567 ICK = ICK_Vector_Splat; 1568 return true; 1569 } 1570 } 1571 1572 // We can perform the conversion between vector types in the following cases: 1573 // 1)vector types are equivalent AltiVec and GCC vector types 1574 // 2)lax vector conversions are permitted and the vector types are of the 1575 // same size 1576 if (ToType->isVectorType() && FromType->isVectorType()) { 1577 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1578 S.isLaxVectorConversion(FromType, ToType)) { 1579 ICK = ICK_Vector_Conversion; 1580 return true; 1581 } 1582 } 1583 1584 return false; 1585 } 1586 1587 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1588 bool InOverloadResolution, 1589 StandardConversionSequence &SCS, 1590 bool CStyle); 1591 1592 /// IsStandardConversion - Determines whether there is a standard 1593 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1594 /// expression From to the type ToType. Standard conversion sequences 1595 /// only consider non-class types; for conversions that involve class 1596 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1597 /// contain the standard conversion sequence required to perform this 1598 /// conversion and this routine will return true. Otherwise, this 1599 /// routine will return false and the value of SCS is unspecified. 1600 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1601 bool InOverloadResolution, 1602 StandardConversionSequence &SCS, 1603 bool CStyle, 1604 bool AllowObjCWritebackConversion) { 1605 QualType FromType = From->getType(); 1606 1607 // Standard conversions (C++ [conv]) 1608 SCS.setAsIdentityConversion(); 1609 SCS.IncompatibleObjC = false; 1610 SCS.setFromType(FromType); 1611 SCS.CopyConstructor = nullptr; 1612 1613 // There are no standard conversions for class types in C++, so 1614 // abort early. When overloading in C, however, we do permit them. 1615 if (S.getLangOpts().CPlusPlus && 1616 (FromType->isRecordType() || ToType->isRecordType())) 1617 return false; 1618 1619 // The first conversion can be an lvalue-to-rvalue conversion, 1620 // array-to-pointer conversion, or function-to-pointer conversion 1621 // (C++ 4p1). 1622 1623 if (FromType == S.Context.OverloadTy) { 1624 DeclAccessPair AccessPair; 1625 if (FunctionDecl *Fn 1626 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1627 AccessPair)) { 1628 // We were able to resolve the address of the overloaded function, 1629 // so we can convert to the type of that function. 1630 FromType = Fn->getType(); 1631 SCS.setFromType(FromType); 1632 1633 // we can sometimes resolve &foo<int> regardless of ToType, so check 1634 // if the type matches (identity) or we are converting to bool 1635 if (!S.Context.hasSameUnqualifiedType( 1636 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1637 QualType resultTy; 1638 // if the function type matches except for [[noreturn]], it's ok 1639 if (!S.IsFunctionConversion(FromType, 1640 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1641 // otherwise, only a boolean conversion is standard 1642 if (!ToType->isBooleanType()) 1643 return false; 1644 } 1645 1646 // Check if the "from" expression is taking the address of an overloaded 1647 // function and recompute the FromType accordingly. Take advantage of the 1648 // fact that non-static member functions *must* have such an address-of 1649 // expression. 1650 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1651 if (Method && !Method->isStatic()) { 1652 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1653 "Non-unary operator on non-static member address"); 1654 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1655 == UO_AddrOf && 1656 "Non-address-of operator on non-static member address"); 1657 const Type *ClassType 1658 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1659 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1660 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1661 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1662 UO_AddrOf && 1663 "Non-address-of operator for overloaded function expression"); 1664 FromType = S.Context.getPointerType(FromType); 1665 } 1666 1667 // Check that we've computed the proper type after overload resolution. 1668 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1669 // be calling it from within an NDEBUG block. 1670 assert(S.Context.hasSameType( 1671 FromType, 1672 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1673 } else { 1674 return false; 1675 } 1676 } 1677 // Lvalue-to-rvalue conversion (C++11 4.1): 1678 // A glvalue (3.10) of a non-function, non-array type T can 1679 // be converted to a prvalue. 1680 bool argIsLValue = From->isGLValue(); 1681 if (argIsLValue && 1682 !FromType->isFunctionType() && !FromType->isArrayType() && 1683 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1684 SCS.First = ICK_Lvalue_To_Rvalue; 1685 1686 // C11 6.3.2.1p2: 1687 // ... if the lvalue has atomic type, the value has the non-atomic version 1688 // of the type of the lvalue ... 1689 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1690 FromType = Atomic->getValueType(); 1691 1692 // If T is a non-class type, the type of the rvalue is the 1693 // cv-unqualified version of T. Otherwise, the type of the rvalue 1694 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1695 // just strip the qualifiers because they don't matter. 1696 FromType = FromType.getUnqualifiedType(); 1697 } else if (FromType->isArrayType()) { 1698 // Array-to-pointer conversion (C++ 4.2) 1699 SCS.First = ICK_Array_To_Pointer; 1700 1701 // An lvalue or rvalue of type "array of N T" or "array of unknown 1702 // bound of T" can be converted to an rvalue of type "pointer to 1703 // T" (C++ 4.2p1). 1704 FromType = S.Context.getArrayDecayedType(FromType); 1705 1706 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1707 // This conversion is deprecated in C++03 (D.4) 1708 SCS.DeprecatedStringLiteralToCharPtr = true; 1709 1710 // For the purpose of ranking in overload resolution 1711 // (13.3.3.1.1), this conversion is considered an 1712 // array-to-pointer conversion followed by a qualification 1713 // conversion (4.4). (C++ 4.2p2) 1714 SCS.Second = ICK_Identity; 1715 SCS.Third = ICK_Qualification; 1716 SCS.QualificationIncludesObjCLifetime = false; 1717 SCS.setAllToTypes(FromType); 1718 return true; 1719 } 1720 } else if (FromType->isFunctionType() && argIsLValue) { 1721 // Function-to-pointer conversion (C++ 4.3). 1722 SCS.First = ICK_Function_To_Pointer; 1723 1724 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1725 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1726 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1727 return false; 1728 1729 // An lvalue of function type T can be converted to an rvalue of 1730 // type "pointer to T." The result is a pointer to the 1731 // function. (C++ 4.3p1). 1732 FromType = S.Context.getPointerType(FromType); 1733 } else { 1734 // We don't require any conversions for the first step. 1735 SCS.First = ICK_Identity; 1736 } 1737 SCS.setToType(0, FromType); 1738 1739 // The second conversion can be an integral promotion, floating 1740 // point promotion, integral conversion, floating point conversion, 1741 // floating-integral conversion, pointer conversion, 1742 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1743 // For overloading in C, this can also be a "compatible-type" 1744 // conversion. 1745 bool IncompatibleObjC = false; 1746 ImplicitConversionKind SecondICK = ICK_Identity; 1747 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1748 // The unqualified versions of the types are the same: there's no 1749 // conversion to do. 1750 SCS.Second = ICK_Identity; 1751 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1752 // Integral promotion (C++ 4.5). 1753 SCS.Second = ICK_Integral_Promotion; 1754 FromType = ToType.getUnqualifiedType(); 1755 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1756 // Floating point promotion (C++ 4.6). 1757 SCS.Second = ICK_Floating_Promotion; 1758 FromType = ToType.getUnqualifiedType(); 1759 } else if (S.IsComplexPromotion(FromType, ToType)) { 1760 // Complex promotion (Clang extension) 1761 SCS.Second = ICK_Complex_Promotion; 1762 FromType = ToType.getUnqualifiedType(); 1763 } else if (ToType->isBooleanType() && 1764 (FromType->isArithmeticType() || 1765 FromType->isAnyPointerType() || 1766 FromType->isBlockPointerType() || 1767 FromType->isMemberPointerType() || 1768 FromType->isNullPtrType())) { 1769 // Boolean conversions (C++ 4.12). 1770 SCS.Second = ICK_Boolean_Conversion; 1771 FromType = S.Context.BoolTy; 1772 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1773 ToType->isIntegralType(S.Context)) { 1774 // Integral conversions (C++ 4.7). 1775 SCS.Second = ICK_Integral_Conversion; 1776 FromType = ToType.getUnqualifiedType(); 1777 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1778 // Complex conversions (C99 6.3.1.6) 1779 SCS.Second = ICK_Complex_Conversion; 1780 FromType = ToType.getUnqualifiedType(); 1781 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1782 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1783 // Complex-real conversions (C99 6.3.1.7) 1784 SCS.Second = ICK_Complex_Real; 1785 FromType = ToType.getUnqualifiedType(); 1786 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1787 // FIXME: disable conversions between long double and __float128 if 1788 // their representation is different until there is back end support 1789 // We of course allow this conversion if long double is really double. 1790 if (&S.Context.getFloatTypeSemantics(FromType) != 1791 &S.Context.getFloatTypeSemantics(ToType)) { 1792 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1793 ToType == S.Context.LongDoubleTy) || 1794 (FromType == S.Context.LongDoubleTy && 1795 ToType == S.Context.Float128Ty)); 1796 if (Float128AndLongDouble && 1797 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1798 &llvm::APFloat::PPCDoubleDouble())) 1799 return false; 1800 } 1801 // Floating point conversions (C++ 4.8). 1802 SCS.Second = ICK_Floating_Conversion; 1803 FromType = ToType.getUnqualifiedType(); 1804 } else if ((FromType->isRealFloatingType() && 1805 ToType->isIntegralType(S.Context)) || 1806 (FromType->isIntegralOrUnscopedEnumerationType() && 1807 ToType->isRealFloatingType())) { 1808 // Floating-integral conversions (C++ 4.9). 1809 SCS.Second = ICK_Floating_Integral; 1810 FromType = ToType.getUnqualifiedType(); 1811 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1812 SCS.Second = ICK_Block_Pointer_Conversion; 1813 } else if (AllowObjCWritebackConversion && 1814 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1815 SCS.Second = ICK_Writeback_Conversion; 1816 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1817 FromType, IncompatibleObjC)) { 1818 // Pointer conversions (C++ 4.10). 1819 SCS.Second = ICK_Pointer_Conversion; 1820 SCS.IncompatibleObjC = IncompatibleObjC; 1821 FromType = FromType.getUnqualifiedType(); 1822 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1823 InOverloadResolution, FromType)) { 1824 // Pointer to member conversions (4.11). 1825 SCS.Second = ICK_Pointer_Member; 1826 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1827 SCS.Second = SecondICK; 1828 FromType = ToType.getUnqualifiedType(); 1829 } else if (!S.getLangOpts().CPlusPlus && 1830 S.Context.typesAreCompatible(ToType, FromType)) { 1831 // Compatible conversions (Clang extension for C function overloading) 1832 SCS.Second = ICK_Compatible_Conversion; 1833 FromType = ToType.getUnqualifiedType(); 1834 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1835 InOverloadResolution, 1836 SCS, CStyle)) { 1837 SCS.Second = ICK_TransparentUnionConversion; 1838 FromType = ToType; 1839 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1840 CStyle)) { 1841 // tryAtomicConversion has updated the standard conversion sequence 1842 // appropriately. 1843 return true; 1844 } else if (ToType->isEventT() && 1845 From->isIntegerConstantExpr(S.getASTContext()) && 1846 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1847 SCS.Second = ICK_Zero_Event_Conversion; 1848 FromType = ToType; 1849 } else if (ToType->isQueueT() && 1850 From->isIntegerConstantExpr(S.getASTContext()) && 1851 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1852 SCS.Second = ICK_Zero_Queue_Conversion; 1853 FromType = ToType; 1854 } else { 1855 // No second conversion required. 1856 SCS.Second = ICK_Identity; 1857 } 1858 SCS.setToType(1, FromType); 1859 1860 // The third conversion can be a function pointer conversion or a 1861 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1862 bool ObjCLifetimeConversion; 1863 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1864 // Function pointer conversions (removing 'noexcept') including removal of 1865 // 'noreturn' (Clang extension). 1866 SCS.Third = ICK_Function_Conversion; 1867 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1868 ObjCLifetimeConversion)) { 1869 SCS.Third = ICK_Qualification; 1870 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1871 FromType = ToType; 1872 } else { 1873 // No conversion required 1874 SCS.Third = ICK_Identity; 1875 } 1876 1877 // C++ [over.best.ics]p6: 1878 // [...] Any difference in top-level cv-qualification is 1879 // subsumed by the initialization itself and does not constitute 1880 // a conversion. [...] 1881 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1882 QualType CanonTo = S.Context.getCanonicalType(ToType); 1883 if (CanonFrom.getLocalUnqualifiedType() 1884 == CanonTo.getLocalUnqualifiedType() && 1885 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1886 FromType = ToType; 1887 CanonFrom = CanonTo; 1888 } 1889 1890 SCS.setToType(2, FromType); 1891 1892 if (CanonFrom == CanonTo) 1893 return true; 1894 1895 // If we have not converted the argument type to the parameter type, 1896 // this is a bad conversion sequence, unless we're resolving an overload in C. 1897 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1898 return false; 1899 1900 ExprResult ER = ExprResult{From}; 1901 Sema::AssignConvertType Conv = 1902 S.CheckSingleAssignmentConstraints(ToType, ER, 1903 /*Diagnose=*/false, 1904 /*DiagnoseCFAudited=*/false, 1905 /*ConvertRHS=*/false); 1906 ImplicitConversionKind SecondConv; 1907 switch (Conv) { 1908 case Sema::Compatible: 1909 SecondConv = ICK_C_Only_Conversion; 1910 break; 1911 // For our purposes, discarding qualifiers is just as bad as using an 1912 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1913 // qualifiers, as well. 1914 case Sema::CompatiblePointerDiscardsQualifiers: 1915 case Sema::IncompatiblePointer: 1916 case Sema::IncompatiblePointerSign: 1917 SecondConv = ICK_Incompatible_Pointer_Conversion; 1918 break; 1919 default: 1920 return false; 1921 } 1922 1923 // First can only be an lvalue conversion, so we pretend that this was the 1924 // second conversion. First should already be valid from earlier in the 1925 // function. 1926 SCS.Second = SecondConv; 1927 SCS.setToType(1, ToType); 1928 1929 // Third is Identity, because Second should rank us worse than any other 1930 // conversion. This could also be ICK_Qualification, but it's simpler to just 1931 // lump everything in with the second conversion, and we don't gain anything 1932 // from making this ICK_Qualification. 1933 SCS.Third = ICK_Identity; 1934 SCS.setToType(2, ToType); 1935 return true; 1936 } 1937 1938 static bool 1939 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1940 QualType &ToType, 1941 bool InOverloadResolution, 1942 StandardConversionSequence &SCS, 1943 bool CStyle) { 1944 1945 const RecordType *UT = ToType->getAsUnionType(); 1946 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1947 return false; 1948 // The field to initialize within the transparent union. 1949 RecordDecl *UD = UT->getDecl(); 1950 // It's compatible if the expression matches any of the fields. 1951 for (const auto *it : UD->fields()) { 1952 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1953 CStyle, /*ObjCWritebackConversion=*/false)) { 1954 ToType = it->getType(); 1955 return true; 1956 } 1957 } 1958 return false; 1959 } 1960 1961 /// IsIntegralPromotion - Determines whether the conversion from the 1962 /// expression From (whose potentially-adjusted type is FromType) to 1963 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1964 /// sets PromotedType to the promoted type. 1965 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1966 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1967 // All integers are built-in. 1968 if (!To) { 1969 return false; 1970 } 1971 1972 // An rvalue of type char, signed char, unsigned char, short int, or 1973 // unsigned short int can be converted to an rvalue of type int if 1974 // int can represent all the values of the source type; otherwise, 1975 // the source rvalue can be converted to an rvalue of type unsigned 1976 // int (C++ 4.5p1). 1977 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1978 !FromType->isEnumeralType()) { 1979 if (// We can promote any signed, promotable integer type to an int 1980 (FromType->isSignedIntegerType() || 1981 // We can promote any unsigned integer type whose size is 1982 // less than int to an int. 1983 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1984 return To->getKind() == BuiltinType::Int; 1985 } 1986 1987 return To->getKind() == BuiltinType::UInt; 1988 } 1989 1990 // C++11 [conv.prom]p3: 1991 // A prvalue of an unscoped enumeration type whose underlying type is not 1992 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1993 // following types that can represent all the values of the enumeration 1994 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1995 // unsigned int, long int, unsigned long int, long long int, or unsigned 1996 // long long int. If none of the types in that list can represent all the 1997 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1998 // type can be converted to an rvalue a prvalue of the extended integer type 1999 // with lowest integer conversion rank (4.13) greater than the rank of long 2000 // long in which all the values of the enumeration can be represented. If 2001 // there are two such extended types, the signed one is chosen. 2002 // C++11 [conv.prom]p4: 2003 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2004 // can be converted to a prvalue of its underlying type. Moreover, if 2005 // integral promotion can be applied to its underlying type, a prvalue of an 2006 // unscoped enumeration type whose underlying type is fixed can also be 2007 // converted to a prvalue of the promoted underlying type. 2008 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2009 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2010 // provided for a scoped enumeration. 2011 if (FromEnumType->getDecl()->isScoped()) 2012 return false; 2013 2014 // We can perform an integral promotion to the underlying type of the enum, 2015 // even if that's not the promoted type. Note that the check for promoting 2016 // the underlying type is based on the type alone, and does not consider 2017 // the bitfield-ness of the actual source expression. 2018 if (FromEnumType->getDecl()->isFixed()) { 2019 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2020 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2021 IsIntegralPromotion(nullptr, Underlying, ToType); 2022 } 2023 2024 // We have already pre-calculated the promotion type, so this is trivial. 2025 if (ToType->isIntegerType() && 2026 isCompleteType(From->getBeginLoc(), FromType)) 2027 return Context.hasSameUnqualifiedType( 2028 ToType, FromEnumType->getDecl()->getPromotionType()); 2029 2030 // C++ [conv.prom]p5: 2031 // If the bit-field has an enumerated type, it is treated as any other 2032 // value of that type for promotion purposes. 2033 // 2034 // ... so do not fall through into the bit-field checks below in C++. 2035 if (getLangOpts().CPlusPlus) 2036 return false; 2037 } 2038 2039 // C++0x [conv.prom]p2: 2040 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2041 // to an rvalue a prvalue of the first of the following types that can 2042 // represent all the values of its underlying type: int, unsigned int, 2043 // long int, unsigned long int, long long int, or unsigned long long int. 2044 // If none of the types in that list can represent all the values of its 2045 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2046 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2047 // type. 2048 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2049 ToType->isIntegerType()) { 2050 // Determine whether the type we're converting from is signed or 2051 // unsigned. 2052 bool FromIsSigned = FromType->isSignedIntegerType(); 2053 uint64_t FromSize = Context.getTypeSize(FromType); 2054 2055 // The types we'll try to promote to, in the appropriate 2056 // order. Try each of these types. 2057 QualType PromoteTypes[6] = { 2058 Context.IntTy, Context.UnsignedIntTy, 2059 Context.LongTy, Context.UnsignedLongTy , 2060 Context.LongLongTy, Context.UnsignedLongLongTy 2061 }; 2062 for (int Idx = 0; Idx < 6; ++Idx) { 2063 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2064 if (FromSize < ToSize || 2065 (FromSize == ToSize && 2066 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2067 // We found the type that we can promote to. If this is the 2068 // type we wanted, we have a promotion. Otherwise, no 2069 // promotion. 2070 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2071 } 2072 } 2073 } 2074 2075 // An rvalue for an integral bit-field (9.6) can be converted to an 2076 // rvalue of type int if int can represent all the values of the 2077 // bit-field; otherwise, it can be converted to unsigned int if 2078 // unsigned int can represent all the values of the bit-field. If 2079 // the bit-field is larger yet, no integral promotion applies to 2080 // it. If the bit-field has an enumerated type, it is treated as any 2081 // other value of that type for promotion purposes (C++ 4.5p3). 2082 // FIXME: We should delay checking of bit-fields until we actually perform the 2083 // conversion. 2084 // 2085 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2086 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2087 // bit-fields and those whose underlying type is larger than int) for GCC 2088 // compatibility. 2089 if (From) { 2090 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2091 llvm::APSInt BitWidth; 2092 if (FromType->isIntegralType(Context) && 2093 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2094 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2095 ToSize = Context.getTypeSize(ToType); 2096 2097 // Are we promoting to an int from a bitfield that fits in an int? 2098 if (BitWidth < ToSize || 2099 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2100 return To->getKind() == BuiltinType::Int; 2101 } 2102 2103 // Are we promoting to an unsigned int from an unsigned bitfield 2104 // that fits into an unsigned int? 2105 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2106 return To->getKind() == BuiltinType::UInt; 2107 } 2108 2109 return false; 2110 } 2111 } 2112 } 2113 2114 // An rvalue of type bool can be converted to an rvalue of type int, 2115 // with false becoming zero and true becoming one (C++ 4.5p4). 2116 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2117 return true; 2118 } 2119 2120 return false; 2121 } 2122 2123 /// IsFloatingPointPromotion - Determines whether the conversion from 2124 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2125 /// returns true and sets PromotedType to the promoted type. 2126 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2127 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2128 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2129 /// An rvalue of type float can be converted to an rvalue of type 2130 /// double. (C++ 4.6p1). 2131 if (FromBuiltin->getKind() == BuiltinType::Float && 2132 ToBuiltin->getKind() == BuiltinType::Double) 2133 return true; 2134 2135 // C99 6.3.1.5p1: 2136 // When a float is promoted to double or long double, or a 2137 // double is promoted to long double [...]. 2138 if (!getLangOpts().CPlusPlus && 2139 (FromBuiltin->getKind() == BuiltinType::Float || 2140 FromBuiltin->getKind() == BuiltinType::Double) && 2141 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2142 ToBuiltin->getKind() == BuiltinType::Float128)) 2143 return true; 2144 2145 // Half can be promoted to float. 2146 if (!getLangOpts().NativeHalfType && 2147 FromBuiltin->getKind() == BuiltinType::Half && 2148 ToBuiltin->getKind() == BuiltinType::Float) 2149 return true; 2150 } 2151 2152 return false; 2153 } 2154 2155 /// Determine if a conversion is a complex promotion. 2156 /// 2157 /// A complex promotion is defined as a complex -> complex conversion 2158 /// where the conversion between the underlying real types is a 2159 /// floating-point or integral promotion. 2160 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2161 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2162 if (!FromComplex) 2163 return false; 2164 2165 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2166 if (!ToComplex) 2167 return false; 2168 2169 return IsFloatingPointPromotion(FromComplex->getElementType(), 2170 ToComplex->getElementType()) || 2171 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2172 ToComplex->getElementType()); 2173 } 2174 2175 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2176 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2177 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2178 /// if non-empty, will be a pointer to ToType that may or may not have 2179 /// the right set of qualifiers on its pointee. 2180 /// 2181 static QualType 2182 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2183 QualType ToPointee, QualType ToType, 2184 ASTContext &Context, 2185 bool StripObjCLifetime = false) { 2186 assert((FromPtr->getTypeClass() == Type::Pointer || 2187 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2188 "Invalid similarly-qualified pointer type"); 2189 2190 /// Conversions to 'id' subsume cv-qualifier conversions. 2191 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2192 return ToType.getUnqualifiedType(); 2193 2194 QualType CanonFromPointee 2195 = Context.getCanonicalType(FromPtr->getPointeeType()); 2196 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2197 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2198 2199 if (StripObjCLifetime) 2200 Quals.removeObjCLifetime(); 2201 2202 // Exact qualifier match -> return the pointer type we're converting to. 2203 if (CanonToPointee.getLocalQualifiers() == Quals) { 2204 // ToType is exactly what we need. Return it. 2205 if (!ToType.isNull()) 2206 return ToType.getUnqualifiedType(); 2207 2208 // Build a pointer to ToPointee. It has the right qualifiers 2209 // already. 2210 if (isa<ObjCObjectPointerType>(ToType)) 2211 return Context.getObjCObjectPointerType(ToPointee); 2212 return Context.getPointerType(ToPointee); 2213 } 2214 2215 // Just build a canonical type that has the right qualifiers. 2216 QualType QualifiedCanonToPointee 2217 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2218 2219 if (isa<ObjCObjectPointerType>(ToType)) 2220 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2221 return Context.getPointerType(QualifiedCanonToPointee); 2222 } 2223 2224 static bool isNullPointerConstantForConversion(Expr *Expr, 2225 bool InOverloadResolution, 2226 ASTContext &Context) { 2227 // Handle value-dependent integral null pointer constants correctly. 2228 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2229 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2230 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2231 return !InOverloadResolution; 2232 2233 return Expr->isNullPointerConstant(Context, 2234 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2235 : Expr::NPC_ValueDependentIsNull); 2236 } 2237 2238 /// IsPointerConversion - Determines whether the conversion of the 2239 /// expression From, which has the (possibly adjusted) type FromType, 2240 /// can be converted to the type ToType via a pointer conversion (C++ 2241 /// 4.10). If so, returns true and places the converted type (that 2242 /// might differ from ToType in its cv-qualifiers at some level) into 2243 /// ConvertedType. 2244 /// 2245 /// This routine also supports conversions to and from block pointers 2246 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2247 /// pointers to interfaces. FIXME: Once we've determined the 2248 /// appropriate overloading rules for Objective-C, we may want to 2249 /// split the Objective-C checks into a different routine; however, 2250 /// GCC seems to consider all of these conversions to be pointer 2251 /// conversions, so for now they live here. IncompatibleObjC will be 2252 /// set if the conversion is an allowed Objective-C conversion that 2253 /// should result in a warning. 2254 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2255 bool InOverloadResolution, 2256 QualType& ConvertedType, 2257 bool &IncompatibleObjC) { 2258 IncompatibleObjC = false; 2259 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2260 IncompatibleObjC)) 2261 return true; 2262 2263 // Conversion from a null pointer constant to any Objective-C pointer type. 2264 if (ToType->isObjCObjectPointerType() && 2265 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2266 ConvertedType = ToType; 2267 return true; 2268 } 2269 2270 // Blocks: Block pointers can be converted to void*. 2271 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2272 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2273 ConvertedType = ToType; 2274 return true; 2275 } 2276 // Blocks: A null pointer constant can be converted to a block 2277 // pointer type. 2278 if (ToType->isBlockPointerType() && 2279 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2280 ConvertedType = ToType; 2281 return true; 2282 } 2283 2284 // If the left-hand-side is nullptr_t, the right side can be a null 2285 // pointer constant. 2286 if (ToType->isNullPtrType() && 2287 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2288 ConvertedType = ToType; 2289 return true; 2290 } 2291 2292 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2293 if (!ToTypePtr) 2294 return false; 2295 2296 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2297 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2298 ConvertedType = ToType; 2299 return true; 2300 } 2301 2302 // Beyond this point, both types need to be pointers 2303 // , including objective-c pointers. 2304 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2305 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2306 !getLangOpts().ObjCAutoRefCount) { 2307 ConvertedType = BuildSimilarlyQualifiedPointerType( 2308 FromType->getAs<ObjCObjectPointerType>(), 2309 ToPointeeType, 2310 ToType, Context); 2311 return true; 2312 } 2313 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2314 if (!FromTypePtr) 2315 return false; 2316 2317 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2318 2319 // If the unqualified pointee types are the same, this can't be a 2320 // pointer conversion, so don't do all of the work below. 2321 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2322 return false; 2323 2324 // An rvalue of type "pointer to cv T," where T is an object type, 2325 // can be converted to an rvalue of type "pointer to cv void" (C++ 2326 // 4.10p2). 2327 if (FromPointeeType->isIncompleteOrObjectType() && 2328 ToPointeeType->isVoidType()) { 2329 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2330 ToPointeeType, 2331 ToType, Context, 2332 /*StripObjCLifetime=*/true); 2333 return true; 2334 } 2335 2336 // MSVC allows implicit function to void* type conversion. 2337 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2338 ToPointeeType->isVoidType()) { 2339 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2340 ToPointeeType, 2341 ToType, Context); 2342 return true; 2343 } 2344 2345 // When we're overloading in C, we allow a special kind of pointer 2346 // conversion for compatible-but-not-identical pointee types. 2347 if (!getLangOpts().CPlusPlus && 2348 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2349 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2350 ToPointeeType, 2351 ToType, Context); 2352 return true; 2353 } 2354 2355 // C++ [conv.ptr]p3: 2356 // 2357 // An rvalue of type "pointer to cv D," where D is a class type, 2358 // can be converted to an rvalue of type "pointer to cv B," where 2359 // B is a base class (clause 10) of D. If B is an inaccessible 2360 // (clause 11) or ambiguous (10.2) base class of D, a program that 2361 // necessitates this conversion is ill-formed. The result of the 2362 // conversion is a pointer to the base class sub-object of the 2363 // derived class object. The null pointer value is converted to 2364 // the null pointer value of the destination type. 2365 // 2366 // Note that we do not check for ambiguity or inaccessibility 2367 // here. That is handled by CheckPointerConversion. 2368 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2369 ToPointeeType->isRecordType() && 2370 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2371 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2372 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2373 ToPointeeType, 2374 ToType, Context); 2375 return true; 2376 } 2377 2378 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2379 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2380 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2381 ToPointeeType, 2382 ToType, Context); 2383 return true; 2384 } 2385 2386 return false; 2387 } 2388 2389 /// Adopt the given qualifiers for the given type. 2390 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2391 Qualifiers TQs = T.getQualifiers(); 2392 2393 // Check whether qualifiers already match. 2394 if (TQs == Qs) 2395 return T; 2396 2397 if (Qs.compatiblyIncludes(TQs)) 2398 return Context.getQualifiedType(T, Qs); 2399 2400 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2401 } 2402 2403 /// isObjCPointerConversion - Determines whether this is an 2404 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2405 /// with the same arguments and return values. 2406 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2407 QualType& ConvertedType, 2408 bool &IncompatibleObjC) { 2409 if (!getLangOpts().ObjC) 2410 return false; 2411 2412 // The set of qualifiers on the type we're converting from. 2413 Qualifiers FromQualifiers = FromType.getQualifiers(); 2414 2415 // First, we handle all conversions on ObjC object pointer types. 2416 const ObjCObjectPointerType* ToObjCPtr = 2417 ToType->getAs<ObjCObjectPointerType>(); 2418 const ObjCObjectPointerType *FromObjCPtr = 2419 FromType->getAs<ObjCObjectPointerType>(); 2420 2421 if (ToObjCPtr && FromObjCPtr) { 2422 // If the pointee types are the same (ignoring qualifications), 2423 // then this is not a pointer conversion. 2424 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2425 FromObjCPtr->getPointeeType())) 2426 return false; 2427 2428 // Conversion between Objective-C pointers. 2429 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2430 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2431 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2432 if (getLangOpts().CPlusPlus && LHS && RHS && 2433 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2434 FromObjCPtr->getPointeeType())) 2435 return false; 2436 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2437 ToObjCPtr->getPointeeType(), 2438 ToType, Context); 2439 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2440 return true; 2441 } 2442 2443 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2444 // Okay: this is some kind of implicit downcast of Objective-C 2445 // interfaces, which is permitted. However, we're going to 2446 // complain about it. 2447 IncompatibleObjC = true; 2448 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2449 ToObjCPtr->getPointeeType(), 2450 ToType, Context); 2451 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2452 return true; 2453 } 2454 } 2455 // Beyond this point, both types need to be C pointers or block pointers. 2456 QualType ToPointeeType; 2457 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2458 ToPointeeType = ToCPtr->getPointeeType(); 2459 else if (const BlockPointerType *ToBlockPtr = 2460 ToType->getAs<BlockPointerType>()) { 2461 // Objective C++: We're able to convert from a pointer to any object 2462 // to a block pointer type. 2463 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2464 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2465 return true; 2466 } 2467 ToPointeeType = ToBlockPtr->getPointeeType(); 2468 } 2469 else if (FromType->getAs<BlockPointerType>() && 2470 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2471 // Objective C++: We're able to convert from a block pointer type to a 2472 // pointer to any object. 2473 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2474 return true; 2475 } 2476 else 2477 return false; 2478 2479 QualType FromPointeeType; 2480 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2481 FromPointeeType = FromCPtr->getPointeeType(); 2482 else if (const BlockPointerType *FromBlockPtr = 2483 FromType->getAs<BlockPointerType>()) 2484 FromPointeeType = FromBlockPtr->getPointeeType(); 2485 else 2486 return false; 2487 2488 // If we have pointers to pointers, recursively check whether this 2489 // is an Objective-C conversion. 2490 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2491 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2492 IncompatibleObjC)) { 2493 // We always complain about this conversion. 2494 IncompatibleObjC = true; 2495 ConvertedType = Context.getPointerType(ConvertedType); 2496 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2497 return true; 2498 } 2499 // Allow conversion of pointee being objective-c pointer to another one; 2500 // as in I* to id. 2501 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2502 ToPointeeType->getAs<ObjCObjectPointerType>() && 2503 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2504 IncompatibleObjC)) { 2505 2506 ConvertedType = Context.getPointerType(ConvertedType); 2507 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2508 return true; 2509 } 2510 2511 // If we have pointers to functions or blocks, check whether the only 2512 // differences in the argument and result types are in Objective-C 2513 // pointer conversions. If so, we permit the conversion (but 2514 // complain about it). 2515 const FunctionProtoType *FromFunctionType 2516 = FromPointeeType->getAs<FunctionProtoType>(); 2517 const FunctionProtoType *ToFunctionType 2518 = ToPointeeType->getAs<FunctionProtoType>(); 2519 if (FromFunctionType && ToFunctionType) { 2520 // If the function types are exactly the same, this isn't an 2521 // Objective-C pointer conversion. 2522 if (Context.getCanonicalType(FromPointeeType) 2523 == Context.getCanonicalType(ToPointeeType)) 2524 return false; 2525 2526 // Perform the quick checks that will tell us whether these 2527 // function types are obviously different. 2528 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2529 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2530 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2531 return false; 2532 2533 bool HasObjCConversion = false; 2534 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2535 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2536 // Okay, the types match exactly. Nothing to do. 2537 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2538 ToFunctionType->getReturnType(), 2539 ConvertedType, IncompatibleObjC)) { 2540 // Okay, we have an Objective-C pointer conversion. 2541 HasObjCConversion = true; 2542 } else { 2543 // Function types are too different. Abort. 2544 return false; 2545 } 2546 2547 // Check argument types. 2548 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2549 ArgIdx != NumArgs; ++ArgIdx) { 2550 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2551 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2552 if (Context.getCanonicalType(FromArgType) 2553 == Context.getCanonicalType(ToArgType)) { 2554 // Okay, the types match exactly. Nothing to do. 2555 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2556 ConvertedType, IncompatibleObjC)) { 2557 // Okay, we have an Objective-C pointer conversion. 2558 HasObjCConversion = true; 2559 } else { 2560 // Argument types are too different. Abort. 2561 return false; 2562 } 2563 } 2564 2565 if (HasObjCConversion) { 2566 // We had an Objective-C conversion. Allow this pointer 2567 // conversion, but complain about it. 2568 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2569 IncompatibleObjC = true; 2570 return true; 2571 } 2572 } 2573 2574 return false; 2575 } 2576 2577 /// Determine whether this is an Objective-C writeback conversion, 2578 /// used for parameter passing when performing automatic reference counting. 2579 /// 2580 /// \param FromType The type we're converting form. 2581 /// 2582 /// \param ToType The type we're converting to. 2583 /// 2584 /// \param ConvertedType The type that will be produced after applying 2585 /// this conversion. 2586 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2587 QualType &ConvertedType) { 2588 if (!getLangOpts().ObjCAutoRefCount || 2589 Context.hasSameUnqualifiedType(FromType, ToType)) 2590 return false; 2591 2592 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2593 QualType ToPointee; 2594 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2595 ToPointee = ToPointer->getPointeeType(); 2596 else 2597 return false; 2598 2599 Qualifiers ToQuals = ToPointee.getQualifiers(); 2600 if (!ToPointee->isObjCLifetimeType() || 2601 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2602 !ToQuals.withoutObjCLifetime().empty()) 2603 return false; 2604 2605 // Argument must be a pointer to __strong to __weak. 2606 QualType FromPointee; 2607 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2608 FromPointee = FromPointer->getPointeeType(); 2609 else 2610 return false; 2611 2612 Qualifiers FromQuals = FromPointee.getQualifiers(); 2613 if (!FromPointee->isObjCLifetimeType() || 2614 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2615 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2616 return false; 2617 2618 // Make sure that we have compatible qualifiers. 2619 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2620 if (!ToQuals.compatiblyIncludes(FromQuals)) 2621 return false; 2622 2623 // Remove qualifiers from the pointee type we're converting from; they 2624 // aren't used in the compatibility check belong, and we'll be adding back 2625 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2626 FromPointee = FromPointee.getUnqualifiedType(); 2627 2628 // The unqualified form of the pointee types must be compatible. 2629 ToPointee = ToPointee.getUnqualifiedType(); 2630 bool IncompatibleObjC; 2631 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2632 FromPointee = ToPointee; 2633 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2634 IncompatibleObjC)) 2635 return false; 2636 2637 /// Construct the type we're converting to, which is a pointer to 2638 /// __autoreleasing pointee. 2639 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2640 ConvertedType = Context.getPointerType(FromPointee); 2641 return true; 2642 } 2643 2644 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2645 QualType& ConvertedType) { 2646 QualType ToPointeeType; 2647 if (const BlockPointerType *ToBlockPtr = 2648 ToType->getAs<BlockPointerType>()) 2649 ToPointeeType = ToBlockPtr->getPointeeType(); 2650 else 2651 return false; 2652 2653 QualType FromPointeeType; 2654 if (const BlockPointerType *FromBlockPtr = 2655 FromType->getAs<BlockPointerType>()) 2656 FromPointeeType = FromBlockPtr->getPointeeType(); 2657 else 2658 return false; 2659 // We have pointer to blocks, check whether the only 2660 // differences in the argument and result types are in Objective-C 2661 // pointer conversions. If so, we permit the conversion. 2662 2663 const FunctionProtoType *FromFunctionType 2664 = FromPointeeType->getAs<FunctionProtoType>(); 2665 const FunctionProtoType *ToFunctionType 2666 = ToPointeeType->getAs<FunctionProtoType>(); 2667 2668 if (!FromFunctionType || !ToFunctionType) 2669 return false; 2670 2671 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2672 return true; 2673 2674 // Perform the quick checks that will tell us whether these 2675 // function types are obviously different. 2676 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2677 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2678 return false; 2679 2680 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2681 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2682 if (FromEInfo != ToEInfo) 2683 return false; 2684 2685 bool IncompatibleObjC = false; 2686 if (Context.hasSameType(FromFunctionType->getReturnType(), 2687 ToFunctionType->getReturnType())) { 2688 // Okay, the types match exactly. Nothing to do. 2689 } else { 2690 QualType RHS = FromFunctionType->getReturnType(); 2691 QualType LHS = ToFunctionType->getReturnType(); 2692 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2693 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2694 LHS = LHS.getUnqualifiedType(); 2695 2696 if (Context.hasSameType(RHS,LHS)) { 2697 // OK exact match. 2698 } else if (isObjCPointerConversion(RHS, LHS, 2699 ConvertedType, IncompatibleObjC)) { 2700 if (IncompatibleObjC) 2701 return false; 2702 // Okay, we have an Objective-C pointer conversion. 2703 } 2704 else 2705 return false; 2706 } 2707 2708 // Check argument types. 2709 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2710 ArgIdx != NumArgs; ++ArgIdx) { 2711 IncompatibleObjC = false; 2712 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2713 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2714 if (Context.hasSameType(FromArgType, ToArgType)) { 2715 // Okay, the types match exactly. Nothing to do. 2716 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2717 ConvertedType, IncompatibleObjC)) { 2718 if (IncompatibleObjC) 2719 return false; 2720 // Okay, we have an Objective-C pointer conversion. 2721 } else 2722 // Argument types are too different. Abort. 2723 return false; 2724 } 2725 2726 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2727 bool CanUseToFPT, CanUseFromFPT; 2728 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2729 CanUseToFPT, CanUseFromFPT, 2730 NewParamInfos)) 2731 return false; 2732 2733 ConvertedType = ToType; 2734 return true; 2735 } 2736 2737 enum { 2738 ft_default, 2739 ft_different_class, 2740 ft_parameter_arity, 2741 ft_parameter_mismatch, 2742 ft_return_type, 2743 ft_qualifer_mismatch, 2744 ft_noexcept 2745 }; 2746 2747 /// Attempts to get the FunctionProtoType from a Type. Handles 2748 /// MemberFunctionPointers properly. 2749 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2750 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2751 return FPT; 2752 2753 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2754 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2755 2756 return nullptr; 2757 } 2758 2759 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2760 /// function types. Catches different number of parameter, mismatch in 2761 /// parameter types, and different return types. 2762 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2763 QualType FromType, QualType ToType) { 2764 // If either type is not valid, include no extra info. 2765 if (FromType.isNull() || ToType.isNull()) { 2766 PDiag << ft_default; 2767 return; 2768 } 2769 2770 // Get the function type from the pointers. 2771 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2772 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2773 *ToMember = ToType->getAs<MemberPointerType>(); 2774 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2775 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2776 << QualType(FromMember->getClass(), 0); 2777 return; 2778 } 2779 FromType = FromMember->getPointeeType(); 2780 ToType = ToMember->getPointeeType(); 2781 } 2782 2783 if (FromType->isPointerType()) 2784 FromType = FromType->getPointeeType(); 2785 if (ToType->isPointerType()) 2786 ToType = ToType->getPointeeType(); 2787 2788 // Remove references. 2789 FromType = FromType.getNonReferenceType(); 2790 ToType = ToType.getNonReferenceType(); 2791 2792 // Don't print extra info for non-specialized template functions. 2793 if (FromType->isInstantiationDependentType() && 2794 !FromType->getAs<TemplateSpecializationType>()) { 2795 PDiag << ft_default; 2796 return; 2797 } 2798 2799 // No extra info for same types. 2800 if (Context.hasSameType(FromType, ToType)) { 2801 PDiag << ft_default; 2802 return; 2803 } 2804 2805 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2806 *ToFunction = tryGetFunctionProtoType(ToType); 2807 2808 // Both types need to be function types. 2809 if (!FromFunction || !ToFunction) { 2810 PDiag << ft_default; 2811 return; 2812 } 2813 2814 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2815 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2816 << FromFunction->getNumParams(); 2817 return; 2818 } 2819 2820 // Handle different parameter types. 2821 unsigned ArgPos; 2822 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2823 PDiag << ft_parameter_mismatch << ArgPos + 1 2824 << ToFunction->getParamType(ArgPos) 2825 << FromFunction->getParamType(ArgPos); 2826 return; 2827 } 2828 2829 // Handle different return type. 2830 if (!Context.hasSameType(FromFunction->getReturnType(), 2831 ToFunction->getReturnType())) { 2832 PDiag << ft_return_type << ToFunction->getReturnType() 2833 << FromFunction->getReturnType(); 2834 return; 2835 } 2836 2837 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2838 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2839 << FromFunction->getMethodQuals(); 2840 return; 2841 } 2842 2843 // Handle exception specification differences on canonical type (in C++17 2844 // onwards). 2845 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2846 ->isNothrow() != 2847 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2848 ->isNothrow()) { 2849 PDiag << ft_noexcept; 2850 return; 2851 } 2852 2853 // Unable to find a difference, so add no extra info. 2854 PDiag << ft_default; 2855 } 2856 2857 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2858 /// for equality of their argument types. Caller has already checked that 2859 /// they have same number of arguments. If the parameters are different, 2860 /// ArgPos will have the parameter index of the first different parameter. 2861 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2862 const FunctionProtoType *NewType, 2863 unsigned *ArgPos) { 2864 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2865 N = NewType->param_type_begin(), 2866 E = OldType->param_type_end(); 2867 O && (O != E); ++O, ++N) { 2868 if (!Context.hasSameType(O->getUnqualifiedType(), 2869 N->getUnqualifiedType())) { 2870 if (ArgPos) 2871 *ArgPos = O - OldType->param_type_begin(); 2872 return false; 2873 } 2874 } 2875 return true; 2876 } 2877 2878 /// CheckPointerConversion - Check the pointer conversion from the 2879 /// expression From to the type ToType. This routine checks for 2880 /// ambiguous or inaccessible derived-to-base pointer 2881 /// conversions for which IsPointerConversion has already returned 2882 /// true. It returns true and produces a diagnostic if there was an 2883 /// error, or returns false otherwise. 2884 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2885 CastKind &Kind, 2886 CXXCastPath& BasePath, 2887 bool IgnoreBaseAccess, 2888 bool Diagnose) { 2889 QualType FromType = From->getType(); 2890 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2891 2892 Kind = CK_BitCast; 2893 2894 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2895 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2896 Expr::NPCK_ZeroExpression) { 2897 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2898 DiagRuntimeBehavior(From->getExprLoc(), From, 2899 PDiag(diag::warn_impcast_bool_to_null_pointer) 2900 << ToType << From->getSourceRange()); 2901 else if (!isUnevaluatedContext()) 2902 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2903 << ToType << From->getSourceRange(); 2904 } 2905 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2906 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2907 QualType FromPointeeType = FromPtrType->getPointeeType(), 2908 ToPointeeType = ToPtrType->getPointeeType(); 2909 2910 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2911 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2912 // We must have a derived-to-base conversion. Check an 2913 // ambiguous or inaccessible conversion. 2914 unsigned InaccessibleID = 0; 2915 unsigned AmbigiousID = 0; 2916 if (Diagnose) { 2917 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2918 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2919 } 2920 if (CheckDerivedToBaseConversion( 2921 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2922 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2923 &BasePath, IgnoreBaseAccess)) 2924 return true; 2925 2926 // The conversion was successful. 2927 Kind = CK_DerivedToBase; 2928 } 2929 2930 if (Diagnose && !IsCStyleOrFunctionalCast && 2931 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2932 assert(getLangOpts().MSVCCompat && 2933 "this should only be possible with MSVCCompat!"); 2934 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2935 << From->getSourceRange(); 2936 } 2937 } 2938 } else if (const ObjCObjectPointerType *ToPtrType = 2939 ToType->getAs<ObjCObjectPointerType>()) { 2940 if (const ObjCObjectPointerType *FromPtrType = 2941 FromType->getAs<ObjCObjectPointerType>()) { 2942 // Objective-C++ conversions are always okay. 2943 // FIXME: We should have a different class of conversions for the 2944 // Objective-C++ implicit conversions. 2945 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2946 return false; 2947 } else if (FromType->isBlockPointerType()) { 2948 Kind = CK_BlockPointerToObjCPointerCast; 2949 } else { 2950 Kind = CK_CPointerToObjCPointerCast; 2951 } 2952 } else if (ToType->isBlockPointerType()) { 2953 if (!FromType->isBlockPointerType()) 2954 Kind = CK_AnyPointerToBlockPointerCast; 2955 } 2956 2957 // We shouldn't fall into this case unless it's valid for other 2958 // reasons. 2959 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2960 Kind = CK_NullToPointer; 2961 2962 return false; 2963 } 2964 2965 /// IsMemberPointerConversion - Determines whether the conversion of the 2966 /// expression From, which has the (possibly adjusted) type FromType, can be 2967 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2968 /// If so, returns true and places the converted type (that might differ from 2969 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2970 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2971 QualType ToType, 2972 bool InOverloadResolution, 2973 QualType &ConvertedType) { 2974 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2975 if (!ToTypePtr) 2976 return false; 2977 2978 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2979 if (From->isNullPointerConstant(Context, 2980 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2981 : Expr::NPC_ValueDependentIsNull)) { 2982 ConvertedType = ToType; 2983 return true; 2984 } 2985 2986 // Otherwise, both types have to be member pointers. 2987 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2988 if (!FromTypePtr) 2989 return false; 2990 2991 // A pointer to member of B can be converted to a pointer to member of D, 2992 // where D is derived from B (C++ 4.11p2). 2993 QualType FromClass(FromTypePtr->getClass(), 0); 2994 QualType ToClass(ToTypePtr->getClass(), 0); 2995 2996 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2997 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 2998 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2999 ToClass.getTypePtr()); 3000 return true; 3001 } 3002 3003 return false; 3004 } 3005 3006 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3007 /// expression From to the type ToType. This routine checks for ambiguous or 3008 /// virtual or inaccessible base-to-derived member pointer conversions 3009 /// for which IsMemberPointerConversion has already returned true. It returns 3010 /// true and produces a diagnostic if there was an error, or returns false 3011 /// otherwise. 3012 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3013 CastKind &Kind, 3014 CXXCastPath &BasePath, 3015 bool IgnoreBaseAccess) { 3016 QualType FromType = From->getType(); 3017 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3018 if (!FromPtrType) { 3019 // This must be a null pointer to member pointer conversion 3020 assert(From->isNullPointerConstant(Context, 3021 Expr::NPC_ValueDependentIsNull) && 3022 "Expr must be null pointer constant!"); 3023 Kind = CK_NullToMemberPointer; 3024 return false; 3025 } 3026 3027 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3028 assert(ToPtrType && "No member pointer cast has a target type " 3029 "that is not a member pointer."); 3030 3031 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3032 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3033 3034 // FIXME: What about dependent types? 3035 assert(FromClass->isRecordType() && "Pointer into non-class."); 3036 assert(ToClass->isRecordType() && "Pointer into non-class."); 3037 3038 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3039 /*DetectVirtual=*/true); 3040 bool DerivationOkay = 3041 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3042 assert(DerivationOkay && 3043 "Should not have been called if derivation isn't OK."); 3044 (void)DerivationOkay; 3045 3046 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3047 getUnqualifiedType())) { 3048 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3049 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3050 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3051 return true; 3052 } 3053 3054 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3055 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3056 << FromClass << ToClass << QualType(VBase, 0) 3057 << From->getSourceRange(); 3058 return true; 3059 } 3060 3061 if (!IgnoreBaseAccess) 3062 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3063 Paths.front(), 3064 diag::err_downcast_from_inaccessible_base); 3065 3066 // Must be a base to derived member conversion. 3067 BuildBasePathArray(Paths, BasePath); 3068 Kind = CK_BaseToDerivedMemberPointer; 3069 return false; 3070 } 3071 3072 /// Determine whether the lifetime conversion between the two given 3073 /// qualifiers sets is nontrivial. 3074 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3075 Qualifiers ToQuals) { 3076 // Converting anything to const __unsafe_unretained is trivial. 3077 if (ToQuals.hasConst() && 3078 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3079 return false; 3080 3081 return true; 3082 } 3083 3084 /// IsQualificationConversion - Determines whether the conversion from 3085 /// an rvalue of type FromType to ToType is a qualification conversion 3086 /// (C++ 4.4). 3087 /// 3088 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3089 /// when the qualification conversion involves a change in the Objective-C 3090 /// object lifetime. 3091 bool 3092 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3093 bool CStyle, bool &ObjCLifetimeConversion) { 3094 FromType = Context.getCanonicalType(FromType); 3095 ToType = Context.getCanonicalType(ToType); 3096 ObjCLifetimeConversion = false; 3097 3098 // If FromType and ToType are the same type, this is not a 3099 // qualification conversion. 3100 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3101 return false; 3102 3103 // (C++ 4.4p4): 3104 // A conversion can add cv-qualifiers at levels other than the first 3105 // in multi-level pointers, subject to the following rules: [...] 3106 bool PreviousToQualsIncludeConst = true; 3107 bool UnwrappedAnyPointer = false; 3108 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3109 // Within each iteration of the loop, we check the qualifiers to 3110 // determine if this still looks like a qualification 3111 // conversion. Then, if all is well, we unwrap one more level of 3112 // pointers or pointers-to-members and do it all again 3113 // until there are no more pointers or pointers-to-members left to 3114 // unwrap. 3115 UnwrappedAnyPointer = true; 3116 3117 Qualifiers FromQuals = FromType.getQualifiers(); 3118 Qualifiers ToQuals = ToType.getQualifiers(); 3119 3120 // Ignore __unaligned qualifier if this type is void. 3121 if (ToType.getUnqualifiedType()->isVoidType()) 3122 FromQuals.removeUnaligned(); 3123 3124 // Objective-C ARC: 3125 // Check Objective-C lifetime conversions. 3126 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3127 UnwrappedAnyPointer) { 3128 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3129 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3130 ObjCLifetimeConversion = true; 3131 FromQuals.removeObjCLifetime(); 3132 ToQuals.removeObjCLifetime(); 3133 } else { 3134 // Qualification conversions cannot cast between different 3135 // Objective-C lifetime qualifiers. 3136 return false; 3137 } 3138 } 3139 3140 // Allow addition/removal of GC attributes but not changing GC attributes. 3141 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3142 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3143 FromQuals.removeObjCGCAttr(); 3144 ToQuals.removeObjCGCAttr(); 3145 } 3146 3147 // -- for every j > 0, if const is in cv 1,j then const is in cv 3148 // 2,j, and similarly for volatile. 3149 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3150 return false; 3151 3152 // -- if the cv 1,j and cv 2,j are different, then const is in 3153 // every cv for 0 < k < j. 3154 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3155 && !PreviousToQualsIncludeConst) 3156 return false; 3157 3158 // Keep track of whether all prior cv-qualifiers in the "to" type 3159 // include const. 3160 PreviousToQualsIncludeConst 3161 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3162 } 3163 3164 // Allows address space promotion by language rules implemented in 3165 // Type::Qualifiers::isAddressSpaceSupersetOf. 3166 Qualifiers FromQuals = FromType.getQualifiers(); 3167 Qualifiers ToQuals = ToType.getQualifiers(); 3168 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3169 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3170 return false; 3171 } 3172 3173 // We are left with FromType and ToType being the pointee types 3174 // after unwrapping the original FromType and ToType the same number 3175 // of types. If we unwrapped any pointers, and if FromType and 3176 // ToType have the same unqualified type (since we checked 3177 // qualifiers above), then this is a qualification conversion. 3178 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3179 } 3180 3181 /// - Determine whether this is a conversion from a scalar type to an 3182 /// atomic type. 3183 /// 3184 /// If successful, updates \c SCS's second and third steps in the conversion 3185 /// sequence to finish the conversion. 3186 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3187 bool InOverloadResolution, 3188 StandardConversionSequence &SCS, 3189 bool CStyle) { 3190 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3191 if (!ToAtomic) 3192 return false; 3193 3194 StandardConversionSequence InnerSCS; 3195 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3196 InOverloadResolution, InnerSCS, 3197 CStyle, /*AllowObjCWritebackConversion=*/false)) 3198 return false; 3199 3200 SCS.Second = InnerSCS.Second; 3201 SCS.setToType(1, InnerSCS.getToType(1)); 3202 SCS.Third = InnerSCS.Third; 3203 SCS.QualificationIncludesObjCLifetime 3204 = InnerSCS.QualificationIncludesObjCLifetime; 3205 SCS.setToType(2, InnerSCS.getToType(2)); 3206 return true; 3207 } 3208 3209 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3210 CXXConstructorDecl *Constructor, 3211 QualType Type) { 3212 const FunctionProtoType *CtorType = 3213 Constructor->getType()->getAs<FunctionProtoType>(); 3214 if (CtorType->getNumParams() > 0) { 3215 QualType FirstArg = CtorType->getParamType(0); 3216 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3217 return true; 3218 } 3219 return false; 3220 } 3221 3222 static OverloadingResult 3223 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3224 CXXRecordDecl *To, 3225 UserDefinedConversionSequence &User, 3226 OverloadCandidateSet &CandidateSet, 3227 bool AllowExplicit) { 3228 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3229 for (auto *D : S.LookupConstructors(To)) { 3230 auto Info = getConstructorInfo(D); 3231 if (!Info) 3232 continue; 3233 3234 bool Usable = !Info.Constructor->isInvalidDecl() && 3235 S.isInitListConstructor(Info.Constructor) && 3236 (AllowExplicit || !Info.Constructor->isExplicit()); 3237 if (Usable) { 3238 // If the first argument is (a reference to) the target type, 3239 // suppress conversions. 3240 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3241 S.Context, Info.Constructor, ToType); 3242 if (Info.ConstructorTmpl) 3243 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3244 /*ExplicitArgs*/ nullptr, From, 3245 CandidateSet, SuppressUserConversions, 3246 /*PartialOverloading*/ false, 3247 AllowExplicit); 3248 else 3249 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3250 CandidateSet, SuppressUserConversions, 3251 /*PartialOverloading*/ false, AllowExplicit); 3252 } 3253 } 3254 3255 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3256 3257 OverloadCandidateSet::iterator Best; 3258 switch (auto Result = 3259 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3260 case OR_Deleted: 3261 case OR_Success: { 3262 // Record the standard conversion we used and the conversion function. 3263 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3264 QualType ThisType = Constructor->getThisType(); 3265 // Initializer lists don't have conversions as such. 3266 User.Before.setAsIdentityConversion(); 3267 User.HadMultipleCandidates = HadMultipleCandidates; 3268 User.ConversionFunction = Constructor; 3269 User.FoundConversionFunction = Best->FoundDecl; 3270 User.After.setAsIdentityConversion(); 3271 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3272 User.After.setAllToTypes(ToType); 3273 return Result; 3274 } 3275 3276 case OR_No_Viable_Function: 3277 return OR_No_Viable_Function; 3278 case OR_Ambiguous: 3279 return OR_Ambiguous; 3280 } 3281 3282 llvm_unreachable("Invalid OverloadResult!"); 3283 } 3284 3285 /// Determines whether there is a user-defined conversion sequence 3286 /// (C++ [over.ics.user]) that converts expression From to the type 3287 /// ToType. If such a conversion exists, User will contain the 3288 /// user-defined conversion sequence that performs such a conversion 3289 /// and this routine will return true. Otherwise, this routine returns 3290 /// false and User is unspecified. 3291 /// 3292 /// \param AllowExplicit true if the conversion should consider C++0x 3293 /// "explicit" conversion functions as well as non-explicit conversion 3294 /// functions (C++0x [class.conv.fct]p2). 3295 /// 3296 /// \param AllowObjCConversionOnExplicit true if the conversion should 3297 /// allow an extra Objective-C pointer conversion on uses of explicit 3298 /// constructors. Requires \c AllowExplicit to also be set. 3299 static OverloadingResult 3300 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3301 UserDefinedConversionSequence &User, 3302 OverloadCandidateSet &CandidateSet, 3303 bool AllowExplicit, 3304 bool AllowObjCConversionOnExplicit) { 3305 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3306 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3307 3308 // Whether we will only visit constructors. 3309 bool ConstructorsOnly = false; 3310 3311 // If the type we are conversion to is a class type, enumerate its 3312 // constructors. 3313 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3314 // C++ [over.match.ctor]p1: 3315 // When objects of class type are direct-initialized (8.5), or 3316 // copy-initialized from an expression of the same or a 3317 // derived class type (8.5), overload resolution selects the 3318 // constructor. [...] For copy-initialization, the candidate 3319 // functions are all the converting constructors (12.3.1) of 3320 // that class. The argument list is the expression-list within 3321 // the parentheses of the initializer. 3322 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3323 (From->getType()->getAs<RecordType>() && 3324 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3325 ConstructorsOnly = true; 3326 3327 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3328 // We're not going to find any constructors. 3329 } else if (CXXRecordDecl *ToRecordDecl 3330 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3331 3332 Expr **Args = &From; 3333 unsigned NumArgs = 1; 3334 bool ListInitializing = false; 3335 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3336 // But first, see if there is an init-list-constructor that will work. 3337 OverloadingResult Result = IsInitializerListConstructorConversion( 3338 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3339 if (Result != OR_No_Viable_Function) 3340 return Result; 3341 // Never mind. 3342 CandidateSet.clear( 3343 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3344 3345 // If we're list-initializing, we pass the individual elements as 3346 // arguments, not the entire list. 3347 Args = InitList->getInits(); 3348 NumArgs = InitList->getNumInits(); 3349 ListInitializing = true; 3350 } 3351 3352 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3353 auto Info = getConstructorInfo(D); 3354 if (!Info) 3355 continue; 3356 3357 bool Usable = !Info.Constructor->isInvalidDecl(); 3358 if (ListInitializing) 3359 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3360 else 3361 Usable = Usable && 3362 Info.Constructor->isConvertingConstructor(AllowExplicit); 3363 if (Usable) { 3364 bool SuppressUserConversions = !ConstructorsOnly; 3365 if (SuppressUserConversions && ListInitializing) { 3366 SuppressUserConversions = false; 3367 if (NumArgs == 1) { 3368 // If the first argument is (a reference to) the target type, 3369 // suppress conversions. 3370 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3371 S.Context, Info.Constructor, ToType); 3372 } 3373 } 3374 if (Info.ConstructorTmpl) 3375 S.AddTemplateOverloadCandidate( 3376 Info.ConstructorTmpl, Info.FoundDecl, 3377 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3378 CandidateSet, SuppressUserConversions, 3379 /*PartialOverloading*/ false, AllowExplicit); 3380 else 3381 // Allow one user-defined conversion when user specifies a 3382 // From->ToType conversion via an static cast (c-style, etc). 3383 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3384 llvm::makeArrayRef(Args, NumArgs), 3385 CandidateSet, SuppressUserConversions, 3386 /*PartialOverloading*/ false, AllowExplicit); 3387 } 3388 } 3389 } 3390 } 3391 3392 // Enumerate conversion functions, if we're allowed to. 3393 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3394 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3395 // No conversion functions from incomplete types. 3396 } else if (const RecordType *FromRecordType = 3397 From->getType()->getAs<RecordType>()) { 3398 if (CXXRecordDecl *FromRecordDecl 3399 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3400 // Add all of the conversion functions as candidates. 3401 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3402 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3403 DeclAccessPair FoundDecl = I.getPair(); 3404 NamedDecl *D = FoundDecl.getDecl(); 3405 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3406 if (isa<UsingShadowDecl>(D)) 3407 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3408 3409 CXXConversionDecl *Conv; 3410 FunctionTemplateDecl *ConvTemplate; 3411 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3412 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3413 else 3414 Conv = cast<CXXConversionDecl>(D); 3415 3416 if (AllowExplicit || !Conv->isExplicit()) { 3417 if (ConvTemplate) 3418 S.AddTemplateConversionCandidate( 3419 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3420 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit); 3421 else 3422 S.AddConversionCandidate( 3423 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet, 3424 AllowObjCConversionOnExplicit, AllowExplicit); 3425 } 3426 } 3427 } 3428 } 3429 3430 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3431 3432 OverloadCandidateSet::iterator Best; 3433 switch (auto Result = 3434 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3435 case OR_Success: 3436 case OR_Deleted: 3437 // Record the standard conversion we used and the conversion function. 3438 if (CXXConstructorDecl *Constructor 3439 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3440 // C++ [over.ics.user]p1: 3441 // If the user-defined conversion is specified by a 3442 // constructor (12.3.1), the initial standard conversion 3443 // sequence converts the source type to the type required by 3444 // the argument of the constructor. 3445 // 3446 QualType ThisType = Constructor->getThisType(); 3447 if (isa<InitListExpr>(From)) { 3448 // Initializer lists don't have conversions as such. 3449 User.Before.setAsIdentityConversion(); 3450 } else { 3451 if (Best->Conversions[0].isEllipsis()) 3452 User.EllipsisConversion = true; 3453 else { 3454 User.Before = Best->Conversions[0].Standard; 3455 User.EllipsisConversion = false; 3456 } 3457 } 3458 User.HadMultipleCandidates = HadMultipleCandidates; 3459 User.ConversionFunction = Constructor; 3460 User.FoundConversionFunction = Best->FoundDecl; 3461 User.After.setAsIdentityConversion(); 3462 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3463 User.After.setAllToTypes(ToType); 3464 return Result; 3465 } 3466 if (CXXConversionDecl *Conversion 3467 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3468 // C++ [over.ics.user]p1: 3469 // 3470 // [...] If the user-defined conversion is specified by a 3471 // conversion function (12.3.2), the initial standard 3472 // conversion sequence converts the source type to the 3473 // implicit object parameter of the conversion function. 3474 User.Before = Best->Conversions[0].Standard; 3475 User.HadMultipleCandidates = HadMultipleCandidates; 3476 User.ConversionFunction = Conversion; 3477 User.FoundConversionFunction = Best->FoundDecl; 3478 User.EllipsisConversion = false; 3479 3480 // C++ [over.ics.user]p2: 3481 // The second standard conversion sequence converts the 3482 // result of the user-defined conversion to the target type 3483 // for the sequence. Since an implicit conversion sequence 3484 // is an initialization, the special rules for 3485 // initialization by user-defined conversion apply when 3486 // selecting the best user-defined conversion for a 3487 // user-defined conversion sequence (see 13.3.3 and 3488 // 13.3.3.1). 3489 User.After = Best->FinalConversion; 3490 return Result; 3491 } 3492 llvm_unreachable("Not a constructor or conversion function?"); 3493 3494 case OR_No_Viable_Function: 3495 return OR_No_Viable_Function; 3496 3497 case OR_Ambiguous: 3498 return OR_Ambiguous; 3499 } 3500 3501 llvm_unreachable("Invalid OverloadResult!"); 3502 } 3503 3504 bool 3505 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3506 ImplicitConversionSequence ICS; 3507 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3508 OverloadCandidateSet::CSK_Normal); 3509 OverloadingResult OvResult = 3510 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3511 CandidateSet, false, false); 3512 3513 if (!(OvResult == OR_Ambiguous || 3514 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3515 return false; 3516 3517 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, From); 3518 if (OvResult == OR_Ambiguous) 3519 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3520 << From->getType() << ToType << From->getSourceRange(); 3521 else { // OR_No_Viable_Function && !CandidateSet.empty() 3522 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3523 diag::err_typecheck_nonviable_condition_incomplete, 3524 From->getType(), From->getSourceRange())) 3525 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3526 << false << From->getType() << From->getSourceRange() << ToType; 3527 } 3528 3529 CandidateSet.NoteCandidates( 3530 *this, From, Cands); 3531 return true; 3532 } 3533 3534 /// Compare the user-defined conversion functions or constructors 3535 /// of two user-defined conversion sequences to determine whether any ordering 3536 /// is possible. 3537 static ImplicitConversionSequence::CompareKind 3538 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3539 FunctionDecl *Function2) { 3540 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3541 return ImplicitConversionSequence::Indistinguishable; 3542 3543 // Objective-C++: 3544 // If both conversion functions are implicitly-declared conversions from 3545 // a lambda closure type to a function pointer and a block pointer, 3546 // respectively, always prefer the conversion to a function pointer, 3547 // because the function pointer is more lightweight and is more likely 3548 // to keep code working. 3549 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3550 if (!Conv1) 3551 return ImplicitConversionSequence::Indistinguishable; 3552 3553 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3554 if (!Conv2) 3555 return ImplicitConversionSequence::Indistinguishable; 3556 3557 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3558 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3559 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3560 if (Block1 != Block2) 3561 return Block1 ? ImplicitConversionSequence::Worse 3562 : ImplicitConversionSequence::Better; 3563 } 3564 3565 return ImplicitConversionSequence::Indistinguishable; 3566 } 3567 3568 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3569 const ImplicitConversionSequence &ICS) { 3570 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3571 (ICS.isUserDefined() && 3572 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3573 } 3574 3575 /// CompareImplicitConversionSequences - Compare two implicit 3576 /// conversion sequences to determine whether one is better than the 3577 /// other or if they are indistinguishable (C++ 13.3.3.2). 3578 static ImplicitConversionSequence::CompareKind 3579 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3580 const ImplicitConversionSequence& ICS1, 3581 const ImplicitConversionSequence& ICS2) 3582 { 3583 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3584 // conversion sequences (as defined in 13.3.3.1) 3585 // -- a standard conversion sequence (13.3.3.1.1) is a better 3586 // conversion sequence than a user-defined conversion sequence or 3587 // an ellipsis conversion sequence, and 3588 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3589 // conversion sequence than an ellipsis conversion sequence 3590 // (13.3.3.1.3). 3591 // 3592 // C++0x [over.best.ics]p10: 3593 // For the purpose of ranking implicit conversion sequences as 3594 // described in 13.3.3.2, the ambiguous conversion sequence is 3595 // treated as a user-defined sequence that is indistinguishable 3596 // from any other user-defined conversion sequence. 3597 3598 // String literal to 'char *' conversion has been deprecated in C++03. It has 3599 // been removed from C++11. We still accept this conversion, if it happens at 3600 // the best viable function. Otherwise, this conversion is considered worse 3601 // than ellipsis conversion. Consider this as an extension; this is not in the 3602 // standard. For example: 3603 // 3604 // int &f(...); // #1 3605 // void f(char*); // #2 3606 // void g() { int &r = f("foo"); } 3607 // 3608 // In C++03, we pick #2 as the best viable function. 3609 // In C++11, we pick #1 as the best viable function, because ellipsis 3610 // conversion is better than string-literal to char* conversion (since there 3611 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3612 // convert arguments, #2 would be the best viable function in C++11. 3613 // If the best viable function has this conversion, a warning will be issued 3614 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3615 3616 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3617 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3618 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3619 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3620 ? ImplicitConversionSequence::Worse 3621 : ImplicitConversionSequence::Better; 3622 3623 if (ICS1.getKindRank() < ICS2.getKindRank()) 3624 return ImplicitConversionSequence::Better; 3625 if (ICS2.getKindRank() < ICS1.getKindRank()) 3626 return ImplicitConversionSequence::Worse; 3627 3628 // The following checks require both conversion sequences to be of 3629 // the same kind. 3630 if (ICS1.getKind() != ICS2.getKind()) 3631 return ImplicitConversionSequence::Indistinguishable; 3632 3633 ImplicitConversionSequence::CompareKind Result = 3634 ImplicitConversionSequence::Indistinguishable; 3635 3636 // Two implicit conversion sequences of the same form are 3637 // indistinguishable conversion sequences unless one of the 3638 // following rules apply: (C++ 13.3.3.2p3): 3639 3640 // List-initialization sequence L1 is a better conversion sequence than 3641 // list-initialization sequence L2 if: 3642 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3643 // if not that, 3644 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3645 // and N1 is smaller than N2., 3646 // even if one of the other rules in this paragraph would otherwise apply. 3647 if (!ICS1.isBad()) { 3648 if (ICS1.isStdInitializerListElement() && 3649 !ICS2.isStdInitializerListElement()) 3650 return ImplicitConversionSequence::Better; 3651 if (!ICS1.isStdInitializerListElement() && 3652 ICS2.isStdInitializerListElement()) 3653 return ImplicitConversionSequence::Worse; 3654 } 3655 3656 if (ICS1.isStandard()) 3657 // Standard conversion sequence S1 is a better conversion sequence than 3658 // standard conversion sequence S2 if [...] 3659 Result = CompareStandardConversionSequences(S, Loc, 3660 ICS1.Standard, ICS2.Standard); 3661 else if (ICS1.isUserDefined()) { 3662 // User-defined conversion sequence U1 is a better conversion 3663 // sequence than another user-defined conversion sequence U2 if 3664 // they contain the same user-defined conversion function or 3665 // constructor and if the second standard conversion sequence of 3666 // U1 is better than the second standard conversion sequence of 3667 // U2 (C++ 13.3.3.2p3). 3668 if (ICS1.UserDefined.ConversionFunction == 3669 ICS2.UserDefined.ConversionFunction) 3670 Result = CompareStandardConversionSequences(S, Loc, 3671 ICS1.UserDefined.After, 3672 ICS2.UserDefined.After); 3673 else 3674 Result = compareConversionFunctions(S, 3675 ICS1.UserDefined.ConversionFunction, 3676 ICS2.UserDefined.ConversionFunction); 3677 } 3678 3679 return Result; 3680 } 3681 3682 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3683 // determine if one is a proper subset of the other. 3684 static ImplicitConversionSequence::CompareKind 3685 compareStandardConversionSubsets(ASTContext &Context, 3686 const StandardConversionSequence& SCS1, 3687 const StandardConversionSequence& SCS2) { 3688 ImplicitConversionSequence::CompareKind Result 3689 = ImplicitConversionSequence::Indistinguishable; 3690 3691 // the identity conversion sequence is considered to be a subsequence of 3692 // any non-identity conversion sequence 3693 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3694 return ImplicitConversionSequence::Better; 3695 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3696 return ImplicitConversionSequence::Worse; 3697 3698 if (SCS1.Second != SCS2.Second) { 3699 if (SCS1.Second == ICK_Identity) 3700 Result = ImplicitConversionSequence::Better; 3701 else if (SCS2.Second == ICK_Identity) 3702 Result = ImplicitConversionSequence::Worse; 3703 else 3704 return ImplicitConversionSequence::Indistinguishable; 3705 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3706 return ImplicitConversionSequence::Indistinguishable; 3707 3708 if (SCS1.Third == SCS2.Third) { 3709 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3710 : ImplicitConversionSequence::Indistinguishable; 3711 } 3712 3713 if (SCS1.Third == ICK_Identity) 3714 return Result == ImplicitConversionSequence::Worse 3715 ? ImplicitConversionSequence::Indistinguishable 3716 : ImplicitConversionSequence::Better; 3717 3718 if (SCS2.Third == ICK_Identity) 3719 return Result == ImplicitConversionSequence::Better 3720 ? ImplicitConversionSequence::Indistinguishable 3721 : ImplicitConversionSequence::Worse; 3722 3723 return ImplicitConversionSequence::Indistinguishable; 3724 } 3725 3726 /// Determine whether one of the given reference bindings is better 3727 /// than the other based on what kind of bindings they are. 3728 static bool 3729 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3730 const StandardConversionSequence &SCS2) { 3731 // C++0x [over.ics.rank]p3b4: 3732 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3733 // implicit object parameter of a non-static member function declared 3734 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3735 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3736 // lvalue reference to a function lvalue and S2 binds an rvalue 3737 // reference*. 3738 // 3739 // FIXME: Rvalue references. We're going rogue with the above edits, 3740 // because the semantics in the current C++0x working paper (N3225 at the 3741 // time of this writing) break the standard definition of std::forward 3742 // and std::reference_wrapper when dealing with references to functions. 3743 // Proposed wording changes submitted to CWG for consideration. 3744 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3745 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3746 return false; 3747 3748 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3749 SCS2.IsLvalueReference) || 3750 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3751 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3752 } 3753 3754 /// CompareStandardConversionSequences - Compare two standard 3755 /// conversion sequences to determine whether one is better than the 3756 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3757 static ImplicitConversionSequence::CompareKind 3758 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3759 const StandardConversionSequence& SCS1, 3760 const StandardConversionSequence& SCS2) 3761 { 3762 // Standard conversion sequence S1 is a better conversion sequence 3763 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3764 3765 // -- S1 is a proper subsequence of S2 (comparing the conversion 3766 // sequences in the canonical form defined by 13.3.3.1.1, 3767 // excluding any Lvalue Transformation; the identity conversion 3768 // sequence is considered to be a subsequence of any 3769 // non-identity conversion sequence) or, if not that, 3770 if (ImplicitConversionSequence::CompareKind CK 3771 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3772 return CK; 3773 3774 // -- the rank of S1 is better than the rank of S2 (by the rules 3775 // defined below), or, if not that, 3776 ImplicitConversionRank Rank1 = SCS1.getRank(); 3777 ImplicitConversionRank Rank2 = SCS2.getRank(); 3778 if (Rank1 < Rank2) 3779 return ImplicitConversionSequence::Better; 3780 else if (Rank2 < Rank1) 3781 return ImplicitConversionSequence::Worse; 3782 3783 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3784 // are indistinguishable unless one of the following rules 3785 // applies: 3786 3787 // A conversion that is not a conversion of a pointer, or 3788 // pointer to member, to bool is better than another conversion 3789 // that is such a conversion. 3790 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3791 return SCS2.isPointerConversionToBool() 3792 ? ImplicitConversionSequence::Better 3793 : ImplicitConversionSequence::Worse; 3794 3795 // C++ [over.ics.rank]p4b2: 3796 // 3797 // If class B is derived directly or indirectly from class A, 3798 // conversion of B* to A* is better than conversion of B* to 3799 // void*, and conversion of A* to void* is better than conversion 3800 // of B* to void*. 3801 bool SCS1ConvertsToVoid 3802 = SCS1.isPointerConversionToVoidPointer(S.Context); 3803 bool SCS2ConvertsToVoid 3804 = SCS2.isPointerConversionToVoidPointer(S.Context); 3805 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3806 // Exactly one of the conversion sequences is a conversion to 3807 // a void pointer; it's the worse conversion. 3808 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3809 : ImplicitConversionSequence::Worse; 3810 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3811 // Neither conversion sequence converts to a void pointer; compare 3812 // their derived-to-base conversions. 3813 if (ImplicitConversionSequence::CompareKind DerivedCK 3814 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3815 return DerivedCK; 3816 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3817 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3818 // Both conversion sequences are conversions to void 3819 // pointers. Compare the source types to determine if there's an 3820 // inheritance relationship in their sources. 3821 QualType FromType1 = SCS1.getFromType(); 3822 QualType FromType2 = SCS2.getFromType(); 3823 3824 // Adjust the types we're converting from via the array-to-pointer 3825 // conversion, if we need to. 3826 if (SCS1.First == ICK_Array_To_Pointer) 3827 FromType1 = S.Context.getArrayDecayedType(FromType1); 3828 if (SCS2.First == ICK_Array_To_Pointer) 3829 FromType2 = S.Context.getArrayDecayedType(FromType2); 3830 3831 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3832 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3833 3834 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3835 return ImplicitConversionSequence::Better; 3836 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3837 return ImplicitConversionSequence::Worse; 3838 3839 // Objective-C++: If one interface is more specific than the 3840 // other, it is the better one. 3841 const ObjCObjectPointerType* FromObjCPtr1 3842 = FromType1->getAs<ObjCObjectPointerType>(); 3843 const ObjCObjectPointerType* FromObjCPtr2 3844 = FromType2->getAs<ObjCObjectPointerType>(); 3845 if (FromObjCPtr1 && FromObjCPtr2) { 3846 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3847 FromObjCPtr2); 3848 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3849 FromObjCPtr1); 3850 if (AssignLeft != AssignRight) { 3851 return AssignLeft? ImplicitConversionSequence::Better 3852 : ImplicitConversionSequence::Worse; 3853 } 3854 } 3855 } 3856 3857 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3858 // bullet 3). 3859 if (ImplicitConversionSequence::CompareKind QualCK 3860 = CompareQualificationConversions(S, SCS1, SCS2)) 3861 return QualCK; 3862 3863 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3864 // Check for a better reference binding based on the kind of bindings. 3865 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3866 return ImplicitConversionSequence::Better; 3867 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3868 return ImplicitConversionSequence::Worse; 3869 3870 // C++ [over.ics.rank]p3b4: 3871 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3872 // which the references refer are the same type except for 3873 // top-level cv-qualifiers, and the type to which the reference 3874 // initialized by S2 refers is more cv-qualified than the type 3875 // to which the reference initialized by S1 refers. 3876 QualType T1 = SCS1.getToType(2); 3877 QualType T2 = SCS2.getToType(2); 3878 T1 = S.Context.getCanonicalType(T1); 3879 T2 = S.Context.getCanonicalType(T2); 3880 Qualifiers T1Quals, T2Quals; 3881 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3882 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3883 if (UnqualT1 == UnqualT2) { 3884 // Objective-C++ ARC: If the references refer to objects with different 3885 // lifetimes, prefer bindings that don't change lifetime. 3886 if (SCS1.ObjCLifetimeConversionBinding != 3887 SCS2.ObjCLifetimeConversionBinding) { 3888 return SCS1.ObjCLifetimeConversionBinding 3889 ? ImplicitConversionSequence::Worse 3890 : ImplicitConversionSequence::Better; 3891 } 3892 3893 // If the type is an array type, promote the element qualifiers to the 3894 // type for comparison. 3895 if (isa<ArrayType>(T1) && T1Quals) 3896 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3897 if (isa<ArrayType>(T2) && T2Quals) 3898 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3899 if (T2.isMoreQualifiedThan(T1)) 3900 return ImplicitConversionSequence::Better; 3901 else if (T1.isMoreQualifiedThan(T2)) 3902 return ImplicitConversionSequence::Worse; 3903 } 3904 } 3905 3906 // In Microsoft mode, prefer an integral conversion to a 3907 // floating-to-integral conversion if the integral conversion 3908 // is between types of the same size. 3909 // For example: 3910 // void f(float); 3911 // void f(int); 3912 // int main { 3913 // long a; 3914 // f(a); 3915 // } 3916 // Here, MSVC will call f(int) instead of generating a compile error 3917 // as clang will do in standard mode. 3918 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3919 SCS2.Second == ICK_Floating_Integral && 3920 S.Context.getTypeSize(SCS1.getFromType()) == 3921 S.Context.getTypeSize(SCS1.getToType(2))) 3922 return ImplicitConversionSequence::Better; 3923 3924 // Prefer a compatible vector conversion over a lax vector conversion 3925 // For example: 3926 // 3927 // typedef float __v4sf __attribute__((__vector_size__(16))); 3928 // void f(vector float); 3929 // void f(vector signed int); 3930 // int main() { 3931 // __v4sf a; 3932 // f(a); 3933 // } 3934 // Here, we'd like to choose f(vector float) and not 3935 // report an ambiguous call error 3936 if (SCS1.Second == ICK_Vector_Conversion && 3937 SCS2.Second == ICK_Vector_Conversion) { 3938 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3939 SCS1.getFromType(), SCS1.getToType(2)); 3940 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3941 SCS2.getFromType(), SCS2.getToType(2)); 3942 3943 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 3944 return SCS1IsCompatibleVectorConversion 3945 ? ImplicitConversionSequence::Better 3946 : ImplicitConversionSequence::Worse; 3947 } 3948 3949 return ImplicitConversionSequence::Indistinguishable; 3950 } 3951 3952 /// CompareQualificationConversions - Compares two standard conversion 3953 /// sequences to determine whether they can be ranked based on their 3954 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3955 static ImplicitConversionSequence::CompareKind 3956 CompareQualificationConversions(Sema &S, 3957 const StandardConversionSequence& SCS1, 3958 const StandardConversionSequence& SCS2) { 3959 // C++ 13.3.3.2p3: 3960 // -- S1 and S2 differ only in their qualification conversion and 3961 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3962 // cv-qualification signature of type T1 is a proper subset of 3963 // the cv-qualification signature of type T2, and S1 is not the 3964 // deprecated string literal array-to-pointer conversion (4.2). 3965 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3966 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3967 return ImplicitConversionSequence::Indistinguishable; 3968 3969 // FIXME: the example in the standard doesn't use a qualification 3970 // conversion (!) 3971 QualType T1 = SCS1.getToType(2); 3972 QualType T2 = SCS2.getToType(2); 3973 T1 = S.Context.getCanonicalType(T1); 3974 T2 = S.Context.getCanonicalType(T2); 3975 Qualifiers T1Quals, T2Quals; 3976 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3977 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3978 3979 // If the types are the same, we won't learn anything by unwrapped 3980 // them. 3981 if (UnqualT1 == UnqualT2) 3982 return ImplicitConversionSequence::Indistinguishable; 3983 3984 // If the type is an array type, promote the element qualifiers to the type 3985 // for comparison. 3986 if (isa<ArrayType>(T1) && T1Quals) 3987 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3988 if (isa<ArrayType>(T2) && T2Quals) 3989 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3990 3991 ImplicitConversionSequence::CompareKind Result 3992 = ImplicitConversionSequence::Indistinguishable; 3993 3994 // Objective-C++ ARC: 3995 // Prefer qualification conversions not involving a change in lifetime 3996 // to qualification conversions that do not change lifetime. 3997 if (SCS1.QualificationIncludesObjCLifetime != 3998 SCS2.QualificationIncludesObjCLifetime) { 3999 Result = SCS1.QualificationIncludesObjCLifetime 4000 ? ImplicitConversionSequence::Worse 4001 : ImplicitConversionSequence::Better; 4002 } 4003 4004 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4005 // Within each iteration of the loop, we check the qualifiers to 4006 // determine if this still looks like a qualification 4007 // conversion. Then, if all is well, we unwrap one more level of 4008 // pointers or pointers-to-members and do it all again 4009 // until there are no more pointers or pointers-to-members left 4010 // to unwrap. This essentially mimics what 4011 // IsQualificationConversion does, but here we're checking for a 4012 // strict subset of qualifiers. 4013 if (T1.getQualifiers().withoutObjCLifetime() == 4014 T2.getQualifiers().withoutObjCLifetime()) 4015 // The qualifiers are the same, so this doesn't tell us anything 4016 // about how the sequences rank. 4017 // ObjC ownership quals are omitted above as they interfere with 4018 // the ARC overload rule. 4019 ; 4020 else if (T2.isMoreQualifiedThan(T1)) { 4021 // T1 has fewer qualifiers, so it could be the better sequence. 4022 if (Result == ImplicitConversionSequence::Worse) 4023 // Neither has qualifiers that are a subset of the other's 4024 // qualifiers. 4025 return ImplicitConversionSequence::Indistinguishable; 4026 4027 Result = ImplicitConversionSequence::Better; 4028 } else if (T1.isMoreQualifiedThan(T2)) { 4029 // T2 has fewer qualifiers, so it could be the better sequence. 4030 if (Result == ImplicitConversionSequence::Better) 4031 // Neither has qualifiers that are a subset of the other's 4032 // qualifiers. 4033 return ImplicitConversionSequence::Indistinguishable; 4034 4035 Result = ImplicitConversionSequence::Worse; 4036 } else { 4037 // Qualifiers are disjoint. 4038 return ImplicitConversionSequence::Indistinguishable; 4039 } 4040 4041 // If the types after this point are equivalent, we're done. 4042 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4043 break; 4044 } 4045 4046 // Check that the winning standard conversion sequence isn't using 4047 // the deprecated string literal array to pointer conversion. 4048 switch (Result) { 4049 case ImplicitConversionSequence::Better: 4050 if (SCS1.DeprecatedStringLiteralToCharPtr) 4051 Result = ImplicitConversionSequence::Indistinguishable; 4052 break; 4053 4054 case ImplicitConversionSequence::Indistinguishable: 4055 break; 4056 4057 case ImplicitConversionSequence::Worse: 4058 if (SCS2.DeprecatedStringLiteralToCharPtr) 4059 Result = ImplicitConversionSequence::Indistinguishable; 4060 break; 4061 } 4062 4063 return Result; 4064 } 4065 4066 /// CompareDerivedToBaseConversions - Compares two standard conversion 4067 /// sequences to determine whether they can be ranked based on their 4068 /// various kinds of derived-to-base conversions (C++ 4069 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4070 /// conversions between Objective-C interface types. 4071 static ImplicitConversionSequence::CompareKind 4072 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4073 const StandardConversionSequence& SCS1, 4074 const StandardConversionSequence& SCS2) { 4075 QualType FromType1 = SCS1.getFromType(); 4076 QualType ToType1 = SCS1.getToType(1); 4077 QualType FromType2 = SCS2.getFromType(); 4078 QualType ToType2 = SCS2.getToType(1); 4079 4080 // Adjust the types we're converting from via the array-to-pointer 4081 // conversion, if we need to. 4082 if (SCS1.First == ICK_Array_To_Pointer) 4083 FromType1 = S.Context.getArrayDecayedType(FromType1); 4084 if (SCS2.First == ICK_Array_To_Pointer) 4085 FromType2 = S.Context.getArrayDecayedType(FromType2); 4086 4087 // Canonicalize all of the types. 4088 FromType1 = S.Context.getCanonicalType(FromType1); 4089 ToType1 = S.Context.getCanonicalType(ToType1); 4090 FromType2 = S.Context.getCanonicalType(FromType2); 4091 ToType2 = S.Context.getCanonicalType(ToType2); 4092 4093 // C++ [over.ics.rank]p4b3: 4094 // 4095 // If class B is derived directly or indirectly from class A and 4096 // class C is derived directly or indirectly from B, 4097 // 4098 // Compare based on pointer conversions. 4099 if (SCS1.Second == ICK_Pointer_Conversion && 4100 SCS2.Second == ICK_Pointer_Conversion && 4101 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4102 FromType1->isPointerType() && FromType2->isPointerType() && 4103 ToType1->isPointerType() && ToType2->isPointerType()) { 4104 QualType FromPointee1 4105 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4106 QualType ToPointee1 4107 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4108 QualType FromPointee2 4109 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4110 QualType ToPointee2 4111 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4112 4113 // -- conversion of C* to B* is better than conversion of C* to A*, 4114 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4115 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4116 return ImplicitConversionSequence::Better; 4117 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4118 return ImplicitConversionSequence::Worse; 4119 } 4120 4121 // -- conversion of B* to A* is better than conversion of C* to A*, 4122 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4123 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4124 return ImplicitConversionSequence::Better; 4125 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4126 return ImplicitConversionSequence::Worse; 4127 } 4128 } else if (SCS1.Second == ICK_Pointer_Conversion && 4129 SCS2.Second == ICK_Pointer_Conversion) { 4130 const ObjCObjectPointerType *FromPtr1 4131 = FromType1->getAs<ObjCObjectPointerType>(); 4132 const ObjCObjectPointerType *FromPtr2 4133 = FromType2->getAs<ObjCObjectPointerType>(); 4134 const ObjCObjectPointerType *ToPtr1 4135 = ToType1->getAs<ObjCObjectPointerType>(); 4136 const ObjCObjectPointerType *ToPtr2 4137 = ToType2->getAs<ObjCObjectPointerType>(); 4138 4139 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4140 // Apply the same conversion ranking rules for Objective-C pointer types 4141 // that we do for C++ pointers to class types. However, we employ the 4142 // Objective-C pseudo-subtyping relationship used for assignment of 4143 // Objective-C pointer types. 4144 bool FromAssignLeft 4145 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4146 bool FromAssignRight 4147 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4148 bool ToAssignLeft 4149 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4150 bool ToAssignRight 4151 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4152 4153 // A conversion to an a non-id object pointer type or qualified 'id' 4154 // type is better than a conversion to 'id'. 4155 if (ToPtr1->isObjCIdType() && 4156 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4157 return ImplicitConversionSequence::Worse; 4158 if (ToPtr2->isObjCIdType() && 4159 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4160 return ImplicitConversionSequence::Better; 4161 4162 // A conversion to a non-id object pointer type is better than a 4163 // conversion to a qualified 'id' type 4164 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4165 return ImplicitConversionSequence::Worse; 4166 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4167 return ImplicitConversionSequence::Better; 4168 4169 // A conversion to an a non-Class object pointer type or qualified 'Class' 4170 // type is better than a conversion to 'Class'. 4171 if (ToPtr1->isObjCClassType() && 4172 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4173 return ImplicitConversionSequence::Worse; 4174 if (ToPtr2->isObjCClassType() && 4175 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4176 return ImplicitConversionSequence::Better; 4177 4178 // A conversion to a non-Class object pointer type is better than a 4179 // conversion to a qualified 'Class' type. 4180 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4181 return ImplicitConversionSequence::Worse; 4182 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4183 return ImplicitConversionSequence::Better; 4184 4185 // -- "conversion of C* to B* is better than conversion of C* to A*," 4186 if (S.Context.hasSameType(FromType1, FromType2) && 4187 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4188 (ToAssignLeft != ToAssignRight)) { 4189 if (FromPtr1->isSpecialized()) { 4190 // "conversion of B<A> * to B * is better than conversion of B * to 4191 // C *. 4192 bool IsFirstSame = 4193 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4194 bool IsSecondSame = 4195 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4196 if (IsFirstSame) { 4197 if (!IsSecondSame) 4198 return ImplicitConversionSequence::Better; 4199 } else if (IsSecondSame) 4200 return ImplicitConversionSequence::Worse; 4201 } 4202 return ToAssignLeft? ImplicitConversionSequence::Worse 4203 : ImplicitConversionSequence::Better; 4204 } 4205 4206 // -- "conversion of B* to A* is better than conversion of C* to A*," 4207 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4208 (FromAssignLeft != FromAssignRight)) 4209 return FromAssignLeft? ImplicitConversionSequence::Better 4210 : ImplicitConversionSequence::Worse; 4211 } 4212 } 4213 4214 // Ranking of member-pointer types. 4215 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4216 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4217 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4218 const MemberPointerType * FromMemPointer1 = 4219 FromType1->getAs<MemberPointerType>(); 4220 const MemberPointerType * ToMemPointer1 = 4221 ToType1->getAs<MemberPointerType>(); 4222 const MemberPointerType * FromMemPointer2 = 4223 FromType2->getAs<MemberPointerType>(); 4224 const MemberPointerType * ToMemPointer2 = 4225 ToType2->getAs<MemberPointerType>(); 4226 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4227 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4228 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4229 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4230 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4231 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4232 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4233 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4234 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4235 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4236 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4237 return ImplicitConversionSequence::Worse; 4238 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4239 return ImplicitConversionSequence::Better; 4240 } 4241 // conversion of B::* to C::* is better than conversion of A::* to C::* 4242 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4243 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4244 return ImplicitConversionSequence::Better; 4245 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4246 return ImplicitConversionSequence::Worse; 4247 } 4248 } 4249 4250 if (SCS1.Second == ICK_Derived_To_Base) { 4251 // -- conversion of C to B is better than conversion of C to A, 4252 // -- binding of an expression of type C to a reference of type 4253 // B& is better than binding an expression of type C to a 4254 // reference of type A&, 4255 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4256 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4257 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4258 return ImplicitConversionSequence::Better; 4259 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4260 return ImplicitConversionSequence::Worse; 4261 } 4262 4263 // -- conversion of B to A is better than conversion of C to A. 4264 // -- binding of an expression of type B to a reference of type 4265 // A& is better than binding an expression of type C to a 4266 // reference of type A&, 4267 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4268 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4269 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4270 return ImplicitConversionSequence::Better; 4271 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4272 return ImplicitConversionSequence::Worse; 4273 } 4274 } 4275 4276 return ImplicitConversionSequence::Indistinguishable; 4277 } 4278 4279 /// Determine whether the given type is valid, e.g., it is not an invalid 4280 /// C++ class. 4281 static bool isTypeValid(QualType T) { 4282 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4283 return !Record->isInvalidDecl(); 4284 4285 return true; 4286 } 4287 4288 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4289 /// determine whether they are reference-related, 4290 /// reference-compatible, reference-compatible with added 4291 /// qualification, or incompatible, for use in C++ initialization by 4292 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4293 /// type, and the first type (T1) is the pointee type of the reference 4294 /// type being initialized. 4295 Sema::ReferenceCompareResult 4296 Sema::CompareReferenceRelationship(SourceLocation Loc, 4297 QualType OrigT1, QualType OrigT2, 4298 bool &DerivedToBase, 4299 bool &ObjCConversion, 4300 bool &ObjCLifetimeConversion) { 4301 assert(!OrigT1->isReferenceType() && 4302 "T1 must be the pointee type of the reference type"); 4303 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4304 4305 QualType T1 = Context.getCanonicalType(OrigT1); 4306 QualType T2 = Context.getCanonicalType(OrigT2); 4307 Qualifiers T1Quals, T2Quals; 4308 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4309 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4310 4311 // C++ [dcl.init.ref]p4: 4312 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4313 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4314 // T1 is a base class of T2. 4315 DerivedToBase = false; 4316 ObjCConversion = false; 4317 ObjCLifetimeConversion = false; 4318 QualType ConvertedT2; 4319 if (UnqualT1 == UnqualT2) { 4320 // Nothing to do. 4321 } else if (isCompleteType(Loc, OrigT2) && 4322 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4323 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4324 DerivedToBase = true; 4325 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4326 UnqualT2->isObjCObjectOrInterfaceType() && 4327 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4328 ObjCConversion = true; 4329 else if (UnqualT2->isFunctionType() && 4330 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4331 // C++1z [dcl.init.ref]p4: 4332 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4333 // function" and T1 is "function" 4334 // 4335 // We extend this to also apply to 'noreturn', so allow any function 4336 // conversion between function types. 4337 return Ref_Compatible; 4338 else 4339 return Ref_Incompatible; 4340 4341 // At this point, we know that T1 and T2 are reference-related (at 4342 // least). 4343 4344 // If the type is an array type, promote the element qualifiers to the type 4345 // for comparison. 4346 if (isa<ArrayType>(T1) && T1Quals) 4347 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4348 if (isa<ArrayType>(T2) && T2Quals) 4349 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4350 4351 // C++ [dcl.init.ref]p4: 4352 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4353 // reference-related to T2 and cv1 is the same cv-qualification 4354 // as, or greater cv-qualification than, cv2. For purposes of 4355 // overload resolution, cases for which cv1 is greater 4356 // cv-qualification than cv2 are identified as 4357 // reference-compatible with added qualification (see 13.3.3.2). 4358 // 4359 // Note that we also require equivalence of Objective-C GC and address-space 4360 // qualifiers when performing these computations, so that e.g., an int in 4361 // address space 1 is not reference-compatible with an int in address 4362 // space 2. 4363 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4364 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4365 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4366 ObjCLifetimeConversion = true; 4367 4368 T1Quals.removeObjCLifetime(); 4369 T2Quals.removeObjCLifetime(); 4370 } 4371 4372 // MS compiler ignores __unaligned qualifier for references; do the same. 4373 T1Quals.removeUnaligned(); 4374 T2Quals.removeUnaligned(); 4375 4376 if (T1Quals.compatiblyIncludes(T2Quals)) 4377 return Ref_Compatible; 4378 else 4379 return Ref_Related; 4380 } 4381 4382 /// Look for a user-defined conversion to a value reference-compatible 4383 /// with DeclType. Return true if something definite is found. 4384 static bool 4385 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4386 QualType DeclType, SourceLocation DeclLoc, 4387 Expr *Init, QualType T2, bool AllowRvalues, 4388 bool AllowExplicit) { 4389 assert(T2->isRecordType() && "Can only find conversions of record types."); 4390 CXXRecordDecl *T2RecordDecl 4391 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4392 4393 OverloadCandidateSet CandidateSet( 4394 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4395 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4396 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4397 NamedDecl *D = *I; 4398 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4399 if (isa<UsingShadowDecl>(D)) 4400 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4401 4402 FunctionTemplateDecl *ConvTemplate 4403 = dyn_cast<FunctionTemplateDecl>(D); 4404 CXXConversionDecl *Conv; 4405 if (ConvTemplate) 4406 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4407 else 4408 Conv = cast<CXXConversionDecl>(D); 4409 4410 // If this is an explicit conversion, and we're not allowed to consider 4411 // explicit conversions, skip it. 4412 if (!AllowExplicit && Conv->isExplicit()) 4413 continue; 4414 4415 if (AllowRvalues) { 4416 bool DerivedToBase = false; 4417 bool ObjCConversion = false; 4418 bool ObjCLifetimeConversion = false; 4419 4420 // If we are initializing an rvalue reference, don't permit conversion 4421 // functions that return lvalues. 4422 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4423 const ReferenceType *RefType 4424 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4425 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4426 continue; 4427 } 4428 4429 if (!ConvTemplate && 4430 S.CompareReferenceRelationship( 4431 DeclLoc, 4432 Conv->getConversionType().getNonReferenceType() 4433 .getUnqualifiedType(), 4434 DeclType.getNonReferenceType().getUnqualifiedType(), 4435 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4436 Sema::Ref_Incompatible) 4437 continue; 4438 } else { 4439 // If the conversion function doesn't return a reference type, 4440 // it can't be considered for this conversion. An rvalue reference 4441 // is only acceptable if its referencee is a function type. 4442 4443 const ReferenceType *RefType = 4444 Conv->getConversionType()->getAs<ReferenceType>(); 4445 if (!RefType || 4446 (!RefType->isLValueReferenceType() && 4447 !RefType->getPointeeType()->isFunctionType())) 4448 continue; 4449 } 4450 4451 if (ConvTemplate) 4452 S.AddTemplateConversionCandidate( 4453 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4454 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4455 else 4456 S.AddConversionCandidate( 4457 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4458 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4459 } 4460 4461 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4462 4463 OverloadCandidateSet::iterator Best; 4464 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4465 case OR_Success: 4466 // C++ [over.ics.ref]p1: 4467 // 4468 // [...] If the parameter binds directly to the result of 4469 // applying a conversion function to the argument 4470 // expression, the implicit conversion sequence is a 4471 // user-defined conversion sequence (13.3.3.1.2), with the 4472 // second standard conversion sequence either an identity 4473 // conversion or, if the conversion function returns an 4474 // entity of a type that is a derived class of the parameter 4475 // type, a derived-to-base Conversion. 4476 if (!Best->FinalConversion.DirectBinding) 4477 return false; 4478 4479 ICS.setUserDefined(); 4480 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4481 ICS.UserDefined.After = Best->FinalConversion; 4482 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4483 ICS.UserDefined.ConversionFunction = Best->Function; 4484 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4485 ICS.UserDefined.EllipsisConversion = false; 4486 assert(ICS.UserDefined.After.ReferenceBinding && 4487 ICS.UserDefined.After.DirectBinding && 4488 "Expected a direct reference binding!"); 4489 return true; 4490 4491 case OR_Ambiguous: 4492 ICS.setAmbiguous(); 4493 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4494 Cand != CandidateSet.end(); ++Cand) 4495 if (Cand->Viable) 4496 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4497 return true; 4498 4499 case OR_No_Viable_Function: 4500 case OR_Deleted: 4501 // There was no suitable conversion, or we found a deleted 4502 // conversion; continue with other checks. 4503 return false; 4504 } 4505 4506 llvm_unreachable("Invalid OverloadResult!"); 4507 } 4508 4509 /// Compute an implicit conversion sequence for reference 4510 /// initialization. 4511 static ImplicitConversionSequence 4512 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4513 SourceLocation DeclLoc, 4514 bool SuppressUserConversions, 4515 bool AllowExplicit) { 4516 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4517 4518 // Most paths end in a failed conversion. 4519 ImplicitConversionSequence ICS; 4520 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4521 4522 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4523 QualType T2 = Init->getType(); 4524 4525 // If the initializer is the address of an overloaded function, try 4526 // to resolve the overloaded function. If all goes well, T2 is the 4527 // type of the resulting function. 4528 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4529 DeclAccessPair Found; 4530 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4531 false, Found)) 4532 T2 = Fn->getType(); 4533 } 4534 4535 // Compute some basic properties of the types and the initializer. 4536 bool isRValRef = DeclType->isRValueReferenceType(); 4537 bool DerivedToBase = false; 4538 bool ObjCConversion = false; 4539 bool ObjCLifetimeConversion = false; 4540 Expr::Classification InitCategory = Init->Classify(S.Context); 4541 Sema::ReferenceCompareResult RefRelationship 4542 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4543 ObjCConversion, ObjCLifetimeConversion); 4544 4545 4546 // C++0x [dcl.init.ref]p5: 4547 // A reference to type "cv1 T1" is initialized by an expression 4548 // of type "cv2 T2" as follows: 4549 4550 // -- If reference is an lvalue reference and the initializer expression 4551 if (!isRValRef) { 4552 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4553 // reference-compatible with "cv2 T2," or 4554 // 4555 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4556 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4557 // C++ [over.ics.ref]p1: 4558 // When a parameter of reference type binds directly (8.5.3) 4559 // to an argument expression, the implicit conversion sequence 4560 // is the identity conversion, unless the argument expression 4561 // has a type that is a derived class of the parameter type, 4562 // in which case the implicit conversion sequence is a 4563 // derived-to-base Conversion (13.3.3.1). 4564 ICS.setStandard(); 4565 ICS.Standard.First = ICK_Identity; 4566 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4567 : ObjCConversion? ICK_Compatible_Conversion 4568 : ICK_Identity; 4569 ICS.Standard.Third = ICK_Identity; 4570 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4571 ICS.Standard.setToType(0, T2); 4572 ICS.Standard.setToType(1, T1); 4573 ICS.Standard.setToType(2, T1); 4574 ICS.Standard.ReferenceBinding = true; 4575 ICS.Standard.DirectBinding = true; 4576 ICS.Standard.IsLvalueReference = !isRValRef; 4577 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4578 ICS.Standard.BindsToRvalue = false; 4579 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4580 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4581 ICS.Standard.CopyConstructor = nullptr; 4582 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4583 4584 // Nothing more to do: the inaccessibility/ambiguity check for 4585 // derived-to-base conversions is suppressed when we're 4586 // computing the implicit conversion sequence (C++ 4587 // [over.best.ics]p2). 4588 return ICS; 4589 } 4590 4591 // -- has a class type (i.e., T2 is a class type), where T1 is 4592 // not reference-related to T2, and can be implicitly 4593 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4594 // is reference-compatible with "cv3 T3" 92) (this 4595 // conversion is selected by enumerating the applicable 4596 // conversion functions (13.3.1.6) and choosing the best 4597 // one through overload resolution (13.3)), 4598 if (!SuppressUserConversions && T2->isRecordType() && 4599 S.isCompleteType(DeclLoc, T2) && 4600 RefRelationship == Sema::Ref_Incompatible) { 4601 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4602 Init, T2, /*AllowRvalues=*/false, 4603 AllowExplicit)) 4604 return ICS; 4605 } 4606 } 4607 4608 // -- Otherwise, the reference shall be an lvalue reference to a 4609 // non-volatile const type (i.e., cv1 shall be const), or the reference 4610 // shall be an rvalue reference. 4611 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4612 return ICS; 4613 4614 // -- If the initializer expression 4615 // 4616 // -- is an xvalue, class prvalue, array prvalue or function 4617 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4618 if (RefRelationship == Sema::Ref_Compatible && 4619 (InitCategory.isXValue() || 4620 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4621 (InitCategory.isLValue() && T2->isFunctionType()))) { 4622 ICS.setStandard(); 4623 ICS.Standard.First = ICK_Identity; 4624 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4625 : ObjCConversion? ICK_Compatible_Conversion 4626 : ICK_Identity; 4627 ICS.Standard.Third = ICK_Identity; 4628 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4629 ICS.Standard.setToType(0, T2); 4630 ICS.Standard.setToType(1, T1); 4631 ICS.Standard.setToType(2, T1); 4632 ICS.Standard.ReferenceBinding = true; 4633 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4634 // binding unless we're binding to a class prvalue. 4635 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4636 // allow the use of rvalue references in C++98/03 for the benefit of 4637 // standard library implementors; therefore, we need the xvalue check here. 4638 ICS.Standard.DirectBinding = 4639 S.getLangOpts().CPlusPlus11 || 4640 !(InitCategory.isPRValue() || T2->isRecordType()); 4641 ICS.Standard.IsLvalueReference = !isRValRef; 4642 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4643 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4644 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4645 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4646 ICS.Standard.CopyConstructor = nullptr; 4647 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4648 return ICS; 4649 } 4650 4651 // -- has a class type (i.e., T2 is a class type), where T1 is not 4652 // reference-related to T2, and can be implicitly converted to 4653 // an xvalue, class prvalue, or function lvalue of type 4654 // "cv3 T3", where "cv1 T1" is reference-compatible with 4655 // "cv3 T3", 4656 // 4657 // then the reference is bound to the value of the initializer 4658 // expression in the first case and to the result of the conversion 4659 // in the second case (or, in either case, to an appropriate base 4660 // class subobject). 4661 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4662 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4663 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4664 Init, T2, /*AllowRvalues=*/true, 4665 AllowExplicit)) { 4666 // In the second case, if the reference is an rvalue reference 4667 // and the second standard conversion sequence of the 4668 // user-defined conversion sequence includes an lvalue-to-rvalue 4669 // conversion, the program is ill-formed. 4670 if (ICS.isUserDefined() && isRValRef && 4671 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4672 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4673 4674 return ICS; 4675 } 4676 4677 // A temporary of function type cannot be created; don't even try. 4678 if (T1->isFunctionType()) 4679 return ICS; 4680 4681 // -- Otherwise, a temporary of type "cv1 T1" is created and 4682 // initialized from the initializer expression using the 4683 // rules for a non-reference copy initialization (8.5). The 4684 // reference is then bound to the temporary. If T1 is 4685 // reference-related to T2, cv1 must be the same 4686 // cv-qualification as, or greater cv-qualification than, 4687 // cv2; otherwise, the program is ill-formed. 4688 if (RefRelationship == Sema::Ref_Related) { 4689 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4690 // we would be reference-compatible or reference-compatible with 4691 // added qualification. But that wasn't the case, so the reference 4692 // initialization fails. 4693 // 4694 // Note that we only want to check address spaces and cvr-qualifiers here. 4695 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4696 Qualifiers T1Quals = T1.getQualifiers(); 4697 Qualifiers T2Quals = T2.getQualifiers(); 4698 T1Quals.removeObjCGCAttr(); 4699 T1Quals.removeObjCLifetime(); 4700 T2Quals.removeObjCGCAttr(); 4701 T2Quals.removeObjCLifetime(); 4702 // MS compiler ignores __unaligned qualifier for references; do the same. 4703 T1Quals.removeUnaligned(); 4704 T2Quals.removeUnaligned(); 4705 if (!T1Quals.compatiblyIncludes(T2Quals)) 4706 return ICS; 4707 } 4708 4709 // If at least one of the types is a class type, the types are not 4710 // related, and we aren't allowed any user conversions, the 4711 // reference binding fails. This case is important for breaking 4712 // recursion, since TryImplicitConversion below will attempt to 4713 // create a temporary through the use of a copy constructor. 4714 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4715 (T1->isRecordType() || T2->isRecordType())) 4716 return ICS; 4717 4718 // If T1 is reference-related to T2 and the reference is an rvalue 4719 // reference, the initializer expression shall not be an lvalue. 4720 if (RefRelationship >= Sema::Ref_Related && 4721 isRValRef && Init->Classify(S.Context).isLValue()) 4722 return ICS; 4723 4724 // C++ [over.ics.ref]p2: 4725 // When a parameter of reference type is not bound directly to 4726 // an argument expression, the conversion sequence is the one 4727 // required to convert the argument expression to the 4728 // underlying type of the reference according to 4729 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4730 // to copy-initializing a temporary of the underlying type with 4731 // the argument expression. Any difference in top-level 4732 // cv-qualification is subsumed by the initialization itself 4733 // and does not constitute a conversion. 4734 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4735 /*AllowExplicit=*/false, 4736 /*InOverloadResolution=*/false, 4737 /*CStyle=*/false, 4738 /*AllowObjCWritebackConversion=*/false, 4739 /*AllowObjCConversionOnExplicit=*/false); 4740 4741 // Of course, that's still a reference binding. 4742 if (ICS.isStandard()) { 4743 ICS.Standard.ReferenceBinding = true; 4744 ICS.Standard.IsLvalueReference = !isRValRef; 4745 ICS.Standard.BindsToFunctionLvalue = false; 4746 ICS.Standard.BindsToRvalue = true; 4747 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4748 ICS.Standard.ObjCLifetimeConversionBinding = false; 4749 } else if (ICS.isUserDefined()) { 4750 const ReferenceType *LValRefType = 4751 ICS.UserDefined.ConversionFunction->getReturnType() 4752 ->getAs<LValueReferenceType>(); 4753 4754 // C++ [over.ics.ref]p3: 4755 // Except for an implicit object parameter, for which see 13.3.1, a 4756 // standard conversion sequence cannot be formed if it requires [...] 4757 // binding an rvalue reference to an lvalue other than a function 4758 // lvalue. 4759 // Note that the function case is not possible here. 4760 if (DeclType->isRValueReferenceType() && LValRefType) { 4761 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4762 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4763 // reference to an rvalue! 4764 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4765 return ICS; 4766 } 4767 4768 ICS.UserDefined.After.ReferenceBinding = true; 4769 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4770 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4771 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4772 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4773 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4774 } 4775 4776 return ICS; 4777 } 4778 4779 static ImplicitConversionSequence 4780 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4781 bool SuppressUserConversions, 4782 bool InOverloadResolution, 4783 bool AllowObjCWritebackConversion, 4784 bool AllowExplicit = false); 4785 4786 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4787 /// initializer list From. 4788 static ImplicitConversionSequence 4789 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4790 bool SuppressUserConversions, 4791 bool InOverloadResolution, 4792 bool AllowObjCWritebackConversion) { 4793 // C++11 [over.ics.list]p1: 4794 // When an argument is an initializer list, it is not an expression and 4795 // special rules apply for converting it to a parameter type. 4796 4797 ImplicitConversionSequence Result; 4798 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4799 4800 // We need a complete type for what follows. Incomplete types can never be 4801 // initialized from init lists. 4802 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4803 return Result; 4804 4805 // Per DR1467: 4806 // If the parameter type is a class X and the initializer list has a single 4807 // element of type cv U, where U is X or a class derived from X, the 4808 // implicit conversion sequence is the one required to convert the element 4809 // to the parameter type. 4810 // 4811 // Otherwise, if the parameter type is a character array [... ] 4812 // and the initializer list has a single element that is an 4813 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4814 // implicit conversion sequence is the identity conversion. 4815 if (From->getNumInits() == 1) { 4816 if (ToType->isRecordType()) { 4817 QualType InitType = From->getInit(0)->getType(); 4818 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4819 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4820 return TryCopyInitialization(S, From->getInit(0), ToType, 4821 SuppressUserConversions, 4822 InOverloadResolution, 4823 AllowObjCWritebackConversion); 4824 } 4825 // FIXME: Check the other conditions here: array of character type, 4826 // initializer is a string literal. 4827 if (ToType->isArrayType()) { 4828 InitializedEntity Entity = 4829 InitializedEntity::InitializeParameter(S.Context, ToType, 4830 /*Consumed=*/false); 4831 if (S.CanPerformCopyInitialization(Entity, From)) { 4832 Result.setStandard(); 4833 Result.Standard.setAsIdentityConversion(); 4834 Result.Standard.setFromType(ToType); 4835 Result.Standard.setAllToTypes(ToType); 4836 return Result; 4837 } 4838 } 4839 } 4840 4841 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4842 // C++11 [over.ics.list]p2: 4843 // If the parameter type is std::initializer_list<X> or "array of X" and 4844 // all the elements can be implicitly converted to X, the implicit 4845 // conversion sequence is the worst conversion necessary to convert an 4846 // element of the list to X. 4847 // 4848 // C++14 [over.ics.list]p3: 4849 // Otherwise, if the parameter type is "array of N X", if the initializer 4850 // list has exactly N elements or if it has fewer than N elements and X is 4851 // default-constructible, and if all the elements of the initializer list 4852 // can be implicitly converted to X, the implicit conversion sequence is 4853 // the worst conversion necessary to convert an element of the list to X. 4854 // 4855 // FIXME: We're missing a lot of these checks. 4856 bool toStdInitializerList = false; 4857 QualType X; 4858 if (ToType->isArrayType()) 4859 X = S.Context.getAsArrayType(ToType)->getElementType(); 4860 else 4861 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4862 if (!X.isNull()) { 4863 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4864 Expr *Init = From->getInit(i); 4865 ImplicitConversionSequence ICS = 4866 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4867 InOverloadResolution, 4868 AllowObjCWritebackConversion); 4869 // If a single element isn't convertible, fail. 4870 if (ICS.isBad()) { 4871 Result = ICS; 4872 break; 4873 } 4874 // Otherwise, look for the worst conversion. 4875 if (Result.isBad() || CompareImplicitConversionSequences( 4876 S, From->getBeginLoc(), ICS, Result) == 4877 ImplicitConversionSequence::Worse) 4878 Result = ICS; 4879 } 4880 4881 // For an empty list, we won't have computed any conversion sequence. 4882 // Introduce the identity conversion sequence. 4883 if (From->getNumInits() == 0) { 4884 Result.setStandard(); 4885 Result.Standard.setAsIdentityConversion(); 4886 Result.Standard.setFromType(ToType); 4887 Result.Standard.setAllToTypes(ToType); 4888 } 4889 4890 Result.setStdInitializerListElement(toStdInitializerList); 4891 return Result; 4892 } 4893 4894 // C++14 [over.ics.list]p4: 4895 // C++11 [over.ics.list]p3: 4896 // Otherwise, if the parameter is a non-aggregate class X and overload 4897 // resolution chooses a single best constructor [...] the implicit 4898 // conversion sequence is a user-defined conversion sequence. If multiple 4899 // constructors are viable but none is better than the others, the 4900 // implicit conversion sequence is a user-defined conversion sequence. 4901 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4902 // This function can deal with initializer lists. 4903 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4904 /*AllowExplicit=*/false, 4905 InOverloadResolution, /*CStyle=*/false, 4906 AllowObjCWritebackConversion, 4907 /*AllowObjCConversionOnExplicit=*/false); 4908 } 4909 4910 // C++14 [over.ics.list]p5: 4911 // C++11 [over.ics.list]p4: 4912 // Otherwise, if the parameter has an aggregate type which can be 4913 // initialized from the initializer list [...] the implicit conversion 4914 // sequence is a user-defined conversion sequence. 4915 if (ToType->isAggregateType()) { 4916 // Type is an aggregate, argument is an init list. At this point it comes 4917 // down to checking whether the initialization works. 4918 // FIXME: Find out whether this parameter is consumed or not. 4919 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4920 // need to call into the initialization code here; overload resolution 4921 // should not be doing that. 4922 InitializedEntity Entity = 4923 InitializedEntity::InitializeParameter(S.Context, ToType, 4924 /*Consumed=*/false); 4925 if (S.CanPerformCopyInitialization(Entity, From)) { 4926 Result.setUserDefined(); 4927 Result.UserDefined.Before.setAsIdentityConversion(); 4928 // Initializer lists don't have a type. 4929 Result.UserDefined.Before.setFromType(QualType()); 4930 Result.UserDefined.Before.setAllToTypes(QualType()); 4931 4932 Result.UserDefined.After.setAsIdentityConversion(); 4933 Result.UserDefined.After.setFromType(ToType); 4934 Result.UserDefined.After.setAllToTypes(ToType); 4935 Result.UserDefined.ConversionFunction = nullptr; 4936 } 4937 return Result; 4938 } 4939 4940 // C++14 [over.ics.list]p6: 4941 // C++11 [over.ics.list]p5: 4942 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4943 if (ToType->isReferenceType()) { 4944 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4945 // mention initializer lists in any way. So we go by what list- 4946 // initialization would do and try to extrapolate from that. 4947 4948 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4949 4950 // If the initializer list has a single element that is reference-related 4951 // to the parameter type, we initialize the reference from that. 4952 if (From->getNumInits() == 1) { 4953 Expr *Init = From->getInit(0); 4954 4955 QualType T2 = Init->getType(); 4956 4957 // If the initializer is the address of an overloaded function, try 4958 // to resolve the overloaded function. If all goes well, T2 is the 4959 // type of the resulting function. 4960 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4961 DeclAccessPair Found; 4962 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4963 Init, ToType, false, Found)) 4964 T2 = Fn->getType(); 4965 } 4966 4967 // Compute some basic properties of the types and the initializer. 4968 bool dummy1 = false; 4969 bool dummy2 = false; 4970 bool dummy3 = false; 4971 Sema::ReferenceCompareResult RefRelationship = 4972 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, 4973 dummy2, dummy3); 4974 4975 if (RefRelationship >= Sema::Ref_Related) { 4976 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 4977 SuppressUserConversions, 4978 /*AllowExplicit=*/false); 4979 } 4980 } 4981 4982 // Otherwise, we bind the reference to a temporary created from the 4983 // initializer list. 4984 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4985 InOverloadResolution, 4986 AllowObjCWritebackConversion); 4987 if (Result.isFailure()) 4988 return Result; 4989 assert(!Result.isEllipsis() && 4990 "Sub-initialization cannot result in ellipsis conversion."); 4991 4992 // Can we even bind to a temporary? 4993 if (ToType->isRValueReferenceType() || 4994 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4995 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4996 Result.UserDefined.After; 4997 SCS.ReferenceBinding = true; 4998 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4999 SCS.BindsToRvalue = true; 5000 SCS.BindsToFunctionLvalue = false; 5001 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5002 SCS.ObjCLifetimeConversionBinding = false; 5003 } else 5004 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5005 From, ToType); 5006 return Result; 5007 } 5008 5009 // C++14 [over.ics.list]p7: 5010 // C++11 [over.ics.list]p6: 5011 // Otherwise, if the parameter type is not a class: 5012 if (!ToType->isRecordType()) { 5013 // - if the initializer list has one element that is not itself an 5014 // initializer list, the implicit conversion sequence is the one 5015 // required to convert the element to the parameter type. 5016 unsigned NumInits = From->getNumInits(); 5017 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5018 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5019 SuppressUserConversions, 5020 InOverloadResolution, 5021 AllowObjCWritebackConversion); 5022 // - if the initializer list has no elements, the implicit conversion 5023 // sequence is the identity conversion. 5024 else if (NumInits == 0) { 5025 Result.setStandard(); 5026 Result.Standard.setAsIdentityConversion(); 5027 Result.Standard.setFromType(ToType); 5028 Result.Standard.setAllToTypes(ToType); 5029 } 5030 return Result; 5031 } 5032 5033 // C++14 [over.ics.list]p8: 5034 // C++11 [over.ics.list]p7: 5035 // In all cases other than those enumerated above, no conversion is possible 5036 return Result; 5037 } 5038 5039 /// TryCopyInitialization - Try to copy-initialize a value of type 5040 /// ToType from the expression From. Return the implicit conversion 5041 /// sequence required to pass this argument, which may be a bad 5042 /// conversion sequence (meaning that the argument cannot be passed to 5043 /// a parameter of this type). If @p SuppressUserConversions, then we 5044 /// do not permit any user-defined conversion sequences. 5045 static ImplicitConversionSequence 5046 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5047 bool SuppressUserConversions, 5048 bool InOverloadResolution, 5049 bool AllowObjCWritebackConversion, 5050 bool AllowExplicit) { 5051 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5052 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5053 InOverloadResolution,AllowObjCWritebackConversion); 5054 5055 if (ToType->isReferenceType()) 5056 return TryReferenceInit(S, From, ToType, 5057 /*FIXME:*/ From->getBeginLoc(), 5058 SuppressUserConversions, AllowExplicit); 5059 5060 return TryImplicitConversion(S, From, ToType, 5061 SuppressUserConversions, 5062 /*AllowExplicit=*/false, 5063 InOverloadResolution, 5064 /*CStyle=*/false, 5065 AllowObjCWritebackConversion, 5066 /*AllowObjCConversionOnExplicit=*/false); 5067 } 5068 5069 static bool TryCopyInitialization(const CanQualType FromQTy, 5070 const CanQualType ToQTy, 5071 Sema &S, 5072 SourceLocation Loc, 5073 ExprValueKind FromVK) { 5074 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5075 ImplicitConversionSequence ICS = 5076 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5077 5078 return !ICS.isBad(); 5079 } 5080 5081 /// TryObjectArgumentInitialization - Try to initialize the object 5082 /// parameter of the given member function (@c Method) from the 5083 /// expression @p From. 5084 static ImplicitConversionSequence 5085 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5086 Expr::Classification FromClassification, 5087 CXXMethodDecl *Method, 5088 CXXRecordDecl *ActingContext) { 5089 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5090 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5091 // const volatile object. 5092 Qualifiers Quals; 5093 if (isa<CXXDestructorDecl>(Method)) { 5094 Quals.addConst(); 5095 Quals.addVolatile(); 5096 } else { 5097 Quals = Method->getMethodQualifiers(); 5098 } 5099 5100 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5101 5102 // Set up the conversion sequence as a "bad" conversion, to allow us 5103 // to exit early. 5104 ImplicitConversionSequence ICS; 5105 5106 // We need to have an object of class type. 5107 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5108 FromType = PT->getPointeeType(); 5109 5110 // When we had a pointer, it's implicitly dereferenced, so we 5111 // better have an lvalue. 5112 assert(FromClassification.isLValue()); 5113 } 5114 5115 assert(FromType->isRecordType()); 5116 5117 // C++0x [over.match.funcs]p4: 5118 // For non-static member functions, the type of the implicit object 5119 // parameter is 5120 // 5121 // - "lvalue reference to cv X" for functions declared without a 5122 // ref-qualifier or with the & ref-qualifier 5123 // - "rvalue reference to cv X" for functions declared with the && 5124 // ref-qualifier 5125 // 5126 // where X is the class of which the function is a member and cv is the 5127 // cv-qualification on the member function declaration. 5128 // 5129 // However, when finding an implicit conversion sequence for the argument, we 5130 // are not allowed to perform user-defined conversions 5131 // (C++ [over.match.funcs]p5). We perform a simplified version of 5132 // reference binding here, that allows class rvalues to bind to 5133 // non-constant references. 5134 5135 // First check the qualifiers. 5136 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5137 if (ImplicitParamType.getCVRQualifiers() 5138 != FromTypeCanon.getLocalCVRQualifiers() && 5139 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5140 ICS.setBad(BadConversionSequence::bad_qualifiers, 5141 FromType, ImplicitParamType); 5142 return ICS; 5143 } 5144 5145 if (FromTypeCanon.getQualifiers().hasAddressSpace()) { 5146 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5147 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5148 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5149 ICS.setBad(BadConversionSequence::bad_qualifiers, 5150 FromType, ImplicitParamType); 5151 return ICS; 5152 } 5153 } 5154 5155 // Check that we have either the same type or a derived type. It 5156 // affects the conversion rank. 5157 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5158 ImplicitConversionKind SecondKind; 5159 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5160 SecondKind = ICK_Identity; 5161 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5162 SecondKind = ICK_Derived_To_Base; 5163 else { 5164 ICS.setBad(BadConversionSequence::unrelated_class, 5165 FromType, ImplicitParamType); 5166 return ICS; 5167 } 5168 5169 // Check the ref-qualifier. 5170 switch (Method->getRefQualifier()) { 5171 case RQ_None: 5172 // Do nothing; we don't care about lvalueness or rvalueness. 5173 break; 5174 5175 case RQ_LValue: 5176 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5177 // non-const lvalue reference cannot bind to an rvalue 5178 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5179 ImplicitParamType); 5180 return ICS; 5181 } 5182 break; 5183 5184 case RQ_RValue: 5185 if (!FromClassification.isRValue()) { 5186 // rvalue reference cannot bind to an lvalue 5187 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5188 ImplicitParamType); 5189 return ICS; 5190 } 5191 break; 5192 } 5193 5194 // Success. Mark this as a reference binding. 5195 ICS.setStandard(); 5196 ICS.Standard.setAsIdentityConversion(); 5197 ICS.Standard.Second = SecondKind; 5198 ICS.Standard.setFromType(FromType); 5199 ICS.Standard.setAllToTypes(ImplicitParamType); 5200 ICS.Standard.ReferenceBinding = true; 5201 ICS.Standard.DirectBinding = true; 5202 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5203 ICS.Standard.BindsToFunctionLvalue = false; 5204 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5205 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5206 = (Method->getRefQualifier() == RQ_None); 5207 return ICS; 5208 } 5209 5210 /// PerformObjectArgumentInitialization - Perform initialization of 5211 /// the implicit object parameter for the given Method with the given 5212 /// expression. 5213 ExprResult 5214 Sema::PerformObjectArgumentInitialization(Expr *From, 5215 NestedNameSpecifier *Qualifier, 5216 NamedDecl *FoundDecl, 5217 CXXMethodDecl *Method) { 5218 QualType FromRecordType, DestType; 5219 QualType ImplicitParamRecordType = 5220 Method->getThisType()->getAs<PointerType>()->getPointeeType(); 5221 5222 Expr::Classification FromClassification; 5223 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5224 FromRecordType = PT->getPointeeType(); 5225 DestType = Method->getThisType(); 5226 FromClassification = Expr::Classification::makeSimpleLValue(); 5227 } else { 5228 FromRecordType = From->getType(); 5229 DestType = ImplicitParamRecordType; 5230 FromClassification = From->Classify(Context); 5231 5232 // When performing member access on an rvalue, materialize a temporary. 5233 if (From->isRValue()) { 5234 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5235 Method->getRefQualifier() != 5236 RefQualifierKind::RQ_RValue); 5237 } 5238 } 5239 5240 // Note that we always use the true parent context when performing 5241 // the actual argument initialization. 5242 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5243 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5244 Method->getParent()); 5245 if (ICS.isBad()) { 5246 switch (ICS.Bad.Kind) { 5247 case BadConversionSequence::bad_qualifiers: { 5248 Qualifiers FromQs = FromRecordType.getQualifiers(); 5249 Qualifiers ToQs = DestType.getQualifiers(); 5250 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5251 if (CVR) { 5252 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5253 << Method->getDeclName() << FromRecordType << (CVR - 1) 5254 << From->getSourceRange(); 5255 Diag(Method->getLocation(), diag::note_previous_decl) 5256 << Method->getDeclName(); 5257 return ExprError(); 5258 } 5259 break; 5260 } 5261 5262 case BadConversionSequence::lvalue_ref_to_rvalue: 5263 case BadConversionSequence::rvalue_ref_to_lvalue: { 5264 bool IsRValueQualified = 5265 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5266 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5267 << Method->getDeclName() << FromClassification.isRValue() 5268 << IsRValueQualified; 5269 Diag(Method->getLocation(), diag::note_previous_decl) 5270 << Method->getDeclName(); 5271 return ExprError(); 5272 } 5273 5274 case BadConversionSequence::no_conversion: 5275 case BadConversionSequence::unrelated_class: 5276 break; 5277 } 5278 5279 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5280 << ImplicitParamRecordType << FromRecordType 5281 << From->getSourceRange(); 5282 } 5283 5284 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5285 ExprResult FromRes = 5286 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5287 if (FromRes.isInvalid()) 5288 return ExprError(); 5289 From = FromRes.get(); 5290 } 5291 5292 if (!Context.hasSameType(From->getType(), DestType)) { 5293 CastKind CK; 5294 if (FromRecordType.getAddressSpace() != DestType.getAddressSpace()) 5295 CK = CK_AddressSpaceConversion; 5296 else 5297 CK = CK_NoOp; 5298 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5299 } 5300 return From; 5301 } 5302 5303 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5304 /// expression From to bool (C++0x [conv]p3). 5305 static ImplicitConversionSequence 5306 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5307 return TryImplicitConversion(S, From, S.Context.BoolTy, 5308 /*SuppressUserConversions=*/false, 5309 /*AllowExplicit=*/true, 5310 /*InOverloadResolution=*/false, 5311 /*CStyle=*/false, 5312 /*AllowObjCWritebackConversion=*/false, 5313 /*AllowObjCConversionOnExplicit=*/false); 5314 } 5315 5316 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5317 /// of the expression From to bool (C++0x [conv]p3). 5318 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5319 if (checkPlaceholderForOverload(*this, From)) 5320 return ExprError(); 5321 5322 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5323 if (!ICS.isBad()) 5324 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5325 5326 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5327 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5328 << From->getType() << From->getSourceRange(); 5329 return ExprError(); 5330 } 5331 5332 /// Check that the specified conversion is permitted in a converted constant 5333 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5334 /// is acceptable. 5335 static bool CheckConvertedConstantConversions(Sema &S, 5336 StandardConversionSequence &SCS) { 5337 // Since we know that the target type is an integral or unscoped enumeration 5338 // type, most conversion kinds are impossible. All possible First and Third 5339 // conversions are fine. 5340 switch (SCS.Second) { 5341 case ICK_Identity: 5342 case ICK_Function_Conversion: 5343 case ICK_Integral_Promotion: 5344 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5345 case ICK_Zero_Queue_Conversion: 5346 return true; 5347 5348 case ICK_Boolean_Conversion: 5349 // Conversion from an integral or unscoped enumeration type to bool is 5350 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5351 // conversion, so we allow it in a converted constant expression. 5352 // 5353 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5354 // a lot of popular code. We should at least add a warning for this 5355 // (non-conforming) extension. 5356 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5357 SCS.getToType(2)->isBooleanType(); 5358 5359 case ICK_Pointer_Conversion: 5360 case ICK_Pointer_Member: 5361 // C++1z: null pointer conversions and null member pointer conversions are 5362 // only permitted if the source type is std::nullptr_t. 5363 return SCS.getFromType()->isNullPtrType(); 5364 5365 case ICK_Floating_Promotion: 5366 case ICK_Complex_Promotion: 5367 case ICK_Floating_Conversion: 5368 case ICK_Complex_Conversion: 5369 case ICK_Floating_Integral: 5370 case ICK_Compatible_Conversion: 5371 case ICK_Derived_To_Base: 5372 case ICK_Vector_Conversion: 5373 case ICK_Vector_Splat: 5374 case ICK_Complex_Real: 5375 case ICK_Block_Pointer_Conversion: 5376 case ICK_TransparentUnionConversion: 5377 case ICK_Writeback_Conversion: 5378 case ICK_Zero_Event_Conversion: 5379 case ICK_C_Only_Conversion: 5380 case ICK_Incompatible_Pointer_Conversion: 5381 return false; 5382 5383 case ICK_Lvalue_To_Rvalue: 5384 case ICK_Array_To_Pointer: 5385 case ICK_Function_To_Pointer: 5386 llvm_unreachable("found a first conversion kind in Second"); 5387 5388 case ICK_Qualification: 5389 llvm_unreachable("found a third conversion kind in Second"); 5390 5391 case ICK_Num_Conversion_Kinds: 5392 break; 5393 } 5394 5395 llvm_unreachable("unknown conversion kind"); 5396 } 5397 5398 /// CheckConvertedConstantExpression - Check that the expression From is a 5399 /// converted constant expression of type T, perform the conversion and produce 5400 /// the converted expression, per C++11 [expr.const]p3. 5401 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5402 QualType T, APValue &Value, 5403 Sema::CCEKind CCE, 5404 bool RequireInt) { 5405 assert(S.getLangOpts().CPlusPlus11 && 5406 "converted constant expression outside C++11"); 5407 5408 if (checkPlaceholderForOverload(S, From)) 5409 return ExprError(); 5410 5411 // C++1z [expr.const]p3: 5412 // A converted constant expression of type T is an expression, 5413 // implicitly converted to type T, where the converted 5414 // expression is a constant expression and the implicit conversion 5415 // sequence contains only [... list of conversions ...]. 5416 // C++1z [stmt.if]p2: 5417 // If the if statement is of the form if constexpr, the value of the 5418 // condition shall be a contextually converted constant expression of type 5419 // bool. 5420 ImplicitConversionSequence ICS = 5421 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5422 ? TryContextuallyConvertToBool(S, From) 5423 : TryCopyInitialization(S, From, T, 5424 /*SuppressUserConversions=*/false, 5425 /*InOverloadResolution=*/false, 5426 /*AllowObjcWritebackConversion=*/false, 5427 /*AllowExplicit=*/false); 5428 StandardConversionSequence *SCS = nullptr; 5429 switch (ICS.getKind()) { 5430 case ImplicitConversionSequence::StandardConversion: 5431 SCS = &ICS.Standard; 5432 break; 5433 case ImplicitConversionSequence::UserDefinedConversion: 5434 // We are converting to a non-class type, so the Before sequence 5435 // must be trivial. 5436 SCS = &ICS.UserDefined.After; 5437 break; 5438 case ImplicitConversionSequence::AmbiguousConversion: 5439 case ImplicitConversionSequence::BadConversion: 5440 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5441 return S.Diag(From->getBeginLoc(), 5442 diag::err_typecheck_converted_constant_expression) 5443 << From->getType() << From->getSourceRange() << T; 5444 return ExprError(); 5445 5446 case ImplicitConversionSequence::EllipsisConversion: 5447 llvm_unreachable("ellipsis conversion in converted constant expression"); 5448 } 5449 5450 // Check that we would only use permitted conversions. 5451 if (!CheckConvertedConstantConversions(S, *SCS)) { 5452 return S.Diag(From->getBeginLoc(), 5453 diag::err_typecheck_converted_constant_expression_disallowed) 5454 << From->getType() << From->getSourceRange() << T; 5455 } 5456 // [...] and where the reference binding (if any) binds directly. 5457 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5458 return S.Diag(From->getBeginLoc(), 5459 diag::err_typecheck_converted_constant_expression_indirect) 5460 << From->getType() << From->getSourceRange() << T; 5461 } 5462 5463 ExprResult Result = 5464 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5465 if (Result.isInvalid()) 5466 return Result; 5467 5468 // Check for a narrowing implicit conversion. 5469 APValue PreNarrowingValue; 5470 QualType PreNarrowingType; 5471 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5472 PreNarrowingType)) { 5473 case NK_Dependent_Narrowing: 5474 // Implicit conversion to a narrower type, but the expression is 5475 // value-dependent so we can't tell whether it's actually narrowing. 5476 case NK_Variable_Narrowing: 5477 // Implicit conversion to a narrower type, and the value is not a constant 5478 // expression. We'll diagnose this in a moment. 5479 case NK_Not_Narrowing: 5480 break; 5481 5482 case NK_Constant_Narrowing: 5483 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5484 << CCE << /*Constant*/ 1 5485 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5486 break; 5487 5488 case NK_Type_Narrowing: 5489 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5490 << CCE << /*Constant*/ 0 << From->getType() << T; 5491 break; 5492 } 5493 5494 if (Result.get()->isValueDependent()) { 5495 Value = APValue(); 5496 return Result; 5497 } 5498 5499 // Check the expression is a constant expression. 5500 SmallVector<PartialDiagnosticAt, 8> Notes; 5501 Expr::EvalResult Eval; 5502 Eval.Diag = &Notes; 5503 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5504 ? Expr::EvaluateForMangling 5505 : Expr::EvaluateForCodeGen; 5506 5507 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5508 (RequireInt && !Eval.Val.isInt())) { 5509 // The expression can't be folded, so we can't keep it at this position in 5510 // the AST. 5511 Result = ExprError(); 5512 } else { 5513 Value = Eval.Val; 5514 5515 if (Notes.empty()) { 5516 // It's a constant expression. 5517 return ConstantExpr::Create(S.Context, Result.get(), Value); 5518 } 5519 } 5520 5521 // It's not a constant expression. Produce an appropriate diagnostic. 5522 if (Notes.size() == 1 && 5523 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5524 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5525 else { 5526 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5527 << CCE << From->getSourceRange(); 5528 for (unsigned I = 0; I < Notes.size(); ++I) 5529 S.Diag(Notes[I].first, Notes[I].second); 5530 } 5531 return ExprError(); 5532 } 5533 5534 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5535 APValue &Value, CCEKind CCE) { 5536 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5537 } 5538 5539 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5540 llvm::APSInt &Value, 5541 CCEKind CCE) { 5542 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5543 5544 APValue V; 5545 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5546 if (!R.isInvalid() && !R.get()->isValueDependent()) 5547 Value = V.getInt(); 5548 return R; 5549 } 5550 5551 5552 /// dropPointerConversions - If the given standard conversion sequence 5553 /// involves any pointer conversions, remove them. This may change 5554 /// the result type of the conversion sequence. 5555 static void dropPointerConversion(StandardConversionSequence &SCS) { 5556 if (SCS.Second == ICK_Pointer_Conversion) { 5557 SCS.Second = ICK_Identity; 5558 SCS.Third = ICK_Identity; 5559 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5560 } 5561 } 5562 5563 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5564 /// convert the expression From to an Objective-C pointer type. 5565 static ImplicitConversionSequence 5566 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5567 // Do an implicit conversion to 'id'. 5568 QualType Ty = S.Context.getObjCIdType(); 5569 ImplicitConversionSequence ICS 5570 = TryImplicitConversion(S, From, Ty, 5571 // FIXME: Are these flags correct? 5572 /*SuppressUserConversions=*/false, 5573 /*AllowExplicit=*/true, 5574 /*InOverloadResolution=*/false, 5575 /*CStyle=*/false, 5576 /*AllowObjCWritebackConversion=*/false, 5577 /*AllowObjCConversionOnExplicit=*/true); 5578 5579 // Strip off any final conversions to 'id'. 5580 switch (ICS.getKind()) { 5581 case ImplicitConversionSequence::BadConversion: 5582 case ImplicitConversionSequence::AmbiguousConversion: 5583 case ImplicitConversionSequence::EllipsisConversion: 5584 break; 5585 5586 case ImplicitConversionSequence::UserDefinedConversion: 5587 dropPointerConversion(ICS.UserDefined.After); 5588 break; 5589 5590 case ImplicitConversionSequence::StandardConversion: 5591 dropPointerConversion(ICS.Standard); 5592 break; 5593 } 5594 5595 return ICS; 5596 } 5597 5598 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5599 /// conversion of the expression From to an Objective-C pointer type. 5600 /// Returns a valid but null ExprResult if no conversion sequence exists. 5601 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5602 if (checkPlaceholderForOverload(*this, From)) 5603 return ExprError(); 5604 5605 QualType Ty = Context.getObjCIdType(); 5606 ImplicitConversionSequence ICS = 5607 TryContextuallyConvertToObjCPointer(*this, From); 5608 if (!ICS.isBad()) 5609 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5610 return ExprResult(); 5611 } 5612 5613 /// Determine whether the provided type is an integral type, or an enumeration 5614 /// type of a permitted flavor. 5615 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5616 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5617 : T->isIntegralOrUnscopedEnumerationType(); 5618 } 5619 5620 static ExprResult 5621 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5622 Sema::ContextualImplicitConverter &Converter, 5623 QualType T, UnresolvedSetImpl &ViableConversions) { 5624 5625 if (Converter.Suppress) 5626 return ExprError(); 5627 5628 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5629 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5630 CXXConversionDecl *Conv = 5631 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5632 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5633 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5634 } 5635 return From; 5636 } 5637 5638 static bool 5639 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5640 Sema::ContextualImplicitConverter &Converter, 5641 QualType T, bool HadMultipleCandidates, 5642 UnresolvedSetImpl &ExplicitConversions) { 5643 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5644 DeclAccessPair Found = ExplicitConversions[0]; 5645 CXXConversionDecl *Conversion = 5646 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5647 5648 // The user probably meant to invoke the given explicit 5649 // conversion; use it. 5650 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5651 std::string TypeStr; 5652 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5653 5654 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5655 << FixItHint::CreateInsertion(From->getBeginLoc(), 5656 "static_cast<" + TypeStr + ">(") 5657 << FixItHint::CreateInsertion( 5658 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5659 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5660 5661 // If we aren't in a SFINAE context, build a call to the 5662 // explicit conversion function. 5663 if (SemaRef.isSFINAEContext()) 5664 return true; 5665 5666 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5667 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5668 HadMultipleCandidates); 5669 if (Result.isInvalid()) 5670 return true; 5671 // Record usage of conversion in an implicit cast. 5672 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5673 CK_UserDefinedConversion, Result.get(), 5674 nullptr, Result.get()->getValueKind()); 5675 } 5676 return false; 5677 } 5678 5679 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5680 Sema::ContextualImplicitConverter &Converter, 5681 QualType T, bool HadMultipleCandidates, 5682 DeclAccessPair &Found) { 5683 CXXConversionDecl *Conversion = 5684 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5685 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5686 5687 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5688 if (!Converter.SuppressConversion) { 5689 if (SemaRef.isSFINAEContext()) 5690 return true; 5691 5692 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5693 << From->getSourceRange(); 5694 } 5695 5696 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5697 HadMultipleCandidates); 5698 if (Result.isInvalid()) 5699 return true; 5700 // Record usage of conversion in an implicit cast. 5701 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5702 CK_UserDefinedConversion, Result.get(), 5703 nullptr, Result.get()->getValueKind()); 5704 return false; 5705 } 5706 5707 static ExprResult finishContextualImplicitConversion( 5708 Sema &SemaRef, SourceLocation Loc, Expr *From, 5709 Sema::ContextualImplicitConverter &Converter) { 5710 if (!Converter.match(From->getType()) && !Converter.Suppress) 5711 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5712 << From->getSourceRange(); 5713 5714 return SemaRef.DefaultLvalueConversion(From); 5715 } 5716 5717 static void 5718 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5719 UnresolvedSetImpl &ViableConversions, 5720 OverloadCandidateSet &CandidateSet) { 5721 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5722 DeclAccessPair FoundDecl = ViableConversions[I]; 5723 NamedDecl *D = FoundDecl.getDecl(); 5724 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5725 if (isa<UsingShadowDecl>(D)) 5726 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5727 5728 CXXConversionDecl *Conv; 5729 FunctionTemplateDecl *ConvTemplate; 5730 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5731 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5732 else 5733 Conv = cast<CXXConversionDecl>(D); 5734 5735 if (ConvTemplate) 5736 SemaRef.AddTemplateConversionCandidate( 5737 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5738 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5739 else 5740 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5741 ToType, CandidateSet, 5742 /*AllowObjCConversionOnExplicit=*/false, 5743 /*AllowExplicit*/ true); 5744 } 5745 } 5746 5747 /// Attempt to convert the given expression to a type which is accepted 5748 /// by the given converter. 5749 /// 5750 /// This routine will attempt to convert an expression of class type to a 5751 /// type accepted by the specified converter. In C++11 and before, the class 5752 /// must have a single non-explicit conversion function converting to a matching 5753 /// type. In C++1y, there can be multiple such conversion functions, but only 5754 /// one target type. 5755 /// 5756 /// \param Loc The source location of the construct that requires the 5757 /// conversion. 5758 /// 5759 /// \param From The expression we're converting from. 5760 /// 5761 /// \param Converter Used to control and diagnose the conversion process. 5762 /// 5763 /// \returns The expression, converted to an integral or enumeration type if 5764 /// successful. 5765 ExprResult Sema::PerformContextualImplicitConversion( 5766 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5767 // We can't perform any more checking for type-dependent expressions. 5768 if (From->isTypeDependent()) 5769 return From; 5770 5771 // Process placeholders immediately. 5772 if (From->hasPlaceholderType()) { 5773 ExprResult result = CheckPlaceholderExpr(From); 5774 if (result.isInvalid()) 5775 return result; 5776 From = result.get(); 5777 } 5778 5779 // If the expression already has a matching type, we're golden. 5780 QualType T = From->getType(); 5781 if (Converter.match(T)) 5782 return DefaultLvalueConversion(From); 5783 5784 // FIXME: Check for missing '()' if T is a function type? 5785 5786 // We can only perform contextual implicit conversions on objects of class 5787 // type. 5788 const RecordType *RecordTy = T->getAs<RecordType>(); 5789 if (!RecordTy || !getLangOpts().CPlusPlus) { 5790 if (!Converter.Suppress) 5791 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5792 return From; 5793 } 5794 5795 // We must have a complete class type. 5796 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5797 ContextualImplicitConverter &Converter; 5798 Expr *From; 5799 5800 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5801 : Converter(Converter), From(From) {} 5802 5803 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5804 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5805 } 5806 } IncompleteDiagnoser(Converter, From); 5807 5808 if (Converter.Suppress ? !isCompleteType(Loc, T) 5809 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5810 return From; 5811 5812 // Look for a conversion to an integral or enumeration type. 5813 UnresolvedSet<4> 5814 ViableConversions; // These are *potentially* viable in C++1y. 5815 UnresolvedSet<4> ExplicitConversions; 5816 const auto &Conversions = 5817 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5818 5819 bool HadMultipleCandidates = 5820 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5821 5822 // To check that there is only one target type, in C++1y: 5823 QualType ToType; 5824 bool HasUniqueTargetType = true; 5825 5826 // Collect explicit or viable (potentially in C++1y) conversions. 5827 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5828 NamedDecl *D = (*I)->getUnderlyingDecl(); 5829 CXXConversionDecl *Conversion; 5830 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5831 if (ConvTemplate) { 5832 if (getLangOpts().CPlusPlus14) 5833 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5834 else 5835 continue; // C++11 does not consider conversion operator templates(?). 5836 } else 5837 Conversion = cast<CXXConversionDecl>(D); 5838 5839 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5840 "Conversion operator templates are considered potentially " 5841 "viable in C++1y"); 5842 5843 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5844 if (Converter.match(CurToType) || ConvTemplate) { 5845 5846 if (Conversion->isExplicit()) { 5847 // FIXME: For C++1y, do we need this restriction? 5848 // cf. diagnoseNoViableConversion() 5849 if (!ConvTemplate) 5850 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5851 } else { 5852 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5853 if (ToType.isNull()) 5854 ToType = CurToType.getUnqualifiedType(); 5855 else if (HasUniqueTargetType && 5856 (CurToType.getUnqualifiedType() != ToType)) 5857 HasUniqueTargetType = false; 5858 } 5859 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5860 } 5861 } 5862 } 5863 5864 if (getLangOpts().CPlusPlus14) { 5865 // C++1y [conv]p6: 5866 // ... An expression e of class type E appearing in such a context 5867 // is said to be contextually implicitly converted to a specified 5868 // type T and is well-formed if and only if e can be implicitly 5869 // converted to a type T that is determined as follows: E is searched 5870 // for conversion functions whose return type is cv T or reference to 5871 // cv T such that T is allowed by the context. There shall be 5872 // exactly one such T. 5873 5874 // If no unique T is found: 5875 if (ToType.isNull()) { 5876 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5877 HadMultipleCandidates, 5878 ExplicitConversions)) 5879 return ExprError(); 5880 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5881 } 5882 5883 // If more than one unique Ts are found: 5884 if (!HasUniqueTargetType) 5885 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5886 ViableConversions); 5887 5888 // If one unique T is found: 5889 // First, build a candidate set from the previously recorded 5890 // potentially viable conversions. 5891 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5892 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5893 CandidateSet); 5894 5895 // Then, perform overload resolution over the candidate set. 5896 OverloadCandidateSet::iterator Best; 5897 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5898 case OR_Success: { 5899 // Apply this conversion. 5900 DeclAccessPair Found = 5901 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5902 if (recordConversion(*this, Loc, From, Converter, T, 5903 HadMultipleCandidates, Found)) 5904 return ExprError(); 5905 break; 5906 } 5907 case OR_Ambiguous: 5908 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5909 ViableConversions); 5910 case OR_No_Viable_Function: 5911 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5912 HadMultipleCandidates, 5913 ExplicitConversions)) 5914 return ExprError(); 5915 LLVM_FALLTHROUGH; 5916 case OR_Deleted: 5917 // We'll complain below about a non-integral condition type. 5918 break; 5919 } 5920 } else { 5921 switch (ViableConversions.size()) { 5922 case 0: { 5923 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5924 HadMultipleCandidates, 5925 ExplicitConversions)) 5926 return ExprError(); 5927 5928 // We'll complain below about a non-integral condition type. 5929 break; 5930 } 5931 case 1: { 5932 // Apply this conversion. 5933 DeclAccessPair Found = ViableConversions[0]; 5934 if (recordConversion(*this, Loc, From, Converter, T, 5935 HadMultipleCandidates, Found)) 5936 return ExprError(); 5937 break; 5938 } 5939 default: 5940 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5941 ViableConversions); 5942 } 5943 } 5944 5945 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5946 } 5947 5948 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5949 /// an acceptable non-member overloaded operator for a call whose 5950 /// arguments have types T1 (and, if non-empty, T2). This routine 5951 /// implements the check in C++ [over.match.oper]p3b2 concerning 5952 /// enumeration types. 5953 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5954 FunctionDecl *Fn, 5955 ArrayRef<Expr *> Args) { 5956 QualType T1 = Args[0]->getType(); 5957 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5958 5959 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5960 return true; 5961 5962 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5963 return true; 5964 5965 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5966 if (Proto->getNumParams() < 1) 5967 return false; 5968 5969 if (T1->isEnumeralType()) { 5970 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5971 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5972 return true; 5973 } 5974 5975 if (Proto->getNumParams() < 2) 5976 return false; 5977 5978 if (!T2.isNull() && T2->isEnumeralType()) { 5979 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5980 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5981 return true; 5982 } 5983 5984 return false; 5985 } 5986 5987 /// AddOverloadCandidate - Adds the given function to the set of 5988 /// candidate functions, using the given function call arguments. If 5989 /// @p SuppressUserConversions, then don't allow user-defined 5990 /// conversions via constructors or conversion operators. 5991 /// 5992 /// \param PartialOverloading true if we are performing "partial" overloading 5993 /// based on an incomplete set of function arguments. This feature is used by 5994 /// code completion. 5995 void Sema::AddOverloadCandidate( 5996 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 5997 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 5998 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 5999 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions) { 6000 const FunctionProtoType *Proto 6001 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6002 assert(Proto && "Functions without a prototype cannot be overloaded"); 6003 assert(!Function->getDescribedFunctionTemplate() && 6004 "Use AddTemplateOverloadCandidate for function templates"); 6005 6006 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6007 if (!isa<CXXConstructorDecl>(Method)) { 6008 // If we get here, it's because we're calling a member function 6009 // that is named without a member access expression (e.g., 6010 // "this->f") that was either written explicitly or created 6011 // implicitly. This can happen with a qualified call to a member 6012 // function, e.g., X::f(). We use an empty type for the implied 6013 // object argument (C++ [over.call.func]p3), and the acting context 6014 // is irrelevant. 6015 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6016 Expr::Classification::makeSimpleLValue(), Args, 6017 CandidateSet, SuppressUserConversions, 6018 PartialOverloading, EarlyConversions); 6019 return; 6020 } 6021 // We treat a constructor like a non-member function, since its object 6022 // argument doesn't participate in overload resolution. 6023 } 6024 6025 if (!CandidateSet.isNewCandidate(Function)) 6026 return; 6027 6028 // C++ [over.match.oper]p3: 6029 // if no operand has a class type, only those non-member functions in the 6030 // lookup set that have a first parameter of type T1 or "reference to 6031 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6032 // is a right operand) a second parameter of type T2 or "reference to 6033 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6034 // candidate functions. 6035 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6036 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6037 return; 6038 6039 // C++11 [class.copy]p11: [DR1402] 6040 // A defaulted move constructor that is defined as deleted is ignored by 6041 // overload resolution. 6042 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6043 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6044 Constructor->isMoveConstructor()) 6045 return; 6046 6047 // Overload resolution is always an unevaluated context. 6048 EnterExpressionEvaluationContext Unevaluated( 6049 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6050 6051 // Add this candidate 6052 OverloadCandidate &Candidate = 6053 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6054 Candidate.FoundDecl = FoundDecl; 6055 Candidate.Function = Function; 6056 Candidate.Viable = true; 6057 Candidate.IsSurrogate = false; 6058 Candidate.IsADLCandidate = IsADLCandidate; 6059 Candidate.IgnoreObjectArgument = false; 6060 Candidate.ExplicitCallArguments = Args.size(); 6061 6062 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6063 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6064 Candidate.Viable = false; 6065 Candidate.FailureKind = ovl_non_default_multiversion_function; 6066 return; 6067 } 6068 6069 if (Constructor) { 6070 // C++ [class.copy]p3: 6071 // A member function template is never instantiated to perform the copy 6072 // of a class object to an object of its class type. 6073 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6074 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6075 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6076 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6077 ClassType))) { 6078 Candidate.Viable = false; 6079 Candidate.FailureKind = ovl_fail_illegal_constructor; 6080 return; 6081 } 6082 6083 // C++ [over.match.funcs]p8: (proposed DR resolution) 6084 // A constructor inherited from class type C that has a first parameter 6085 // of type "reference to P" (including such a constructor instantiated 6086 // from a template) is excluded from the set of candidate functions when 6087 // constructing an object of type cv D if the argument list has exactly 6088 // one argument and D is reference-related to P and P is reference-related 6089 // to C. 6090 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6091 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6092 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6093 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6094 QualType C = Context.getRecordType(Constructor->getParent()); 6095 QualType D = Context.getRecordType(Shadow->getParent()); 6096 SourceLocation Loc = Args.front()->getExprLoc(); 6097 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6098 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6099 Candidate.Viable = false; 6100 Candidate.FailureKind = ovl_fail_inhctor_slice; 6101 return; 6102 } 6103 } 6104 6105 // Check that the constructor is capable of constructing an object in the 6106 // destination address space. 6107 if (!Qualifiers::isAddressSpaceSupersetOf( 6108 Constructor->getMethodQualifiers().getAddressSpace(), 6109 CandidateSet.getDestAS())) { 6110 Candidate.Viable = false; 6111 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6112 } 6113 } 6114 6115 unsigned NumParams = Proto->getNumParams(); 6116 6117 // (C++ 13.3.2p2): A candidate function having fewer than m 6118 // parameters is viable only if it has an ellipsis in its parameter 6119 // list (8.3.5). 6120 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6121 !Proto->isVariadic()) { 6122 Candidate.Viable = false; 6123 Candidate.FailureKind = ovl_fail_too_many_arguments; 6124 return; 6125 } 6126 6127 // (C++ 13.3.2p2): A candidate function having more than m parameters 6128 // is viable only if the (m+1)st parameter has a default argument 6129 // (8.3.6). For the purposes of overload resolution, the 6130 // parameter list is truncated on the right, so that there are 6131 // exactly m parameters. 6132 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6133 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6134 // Not enough arguments. 6135 Candidate.Viable = false; 6136 Candidate.FailureKind = ovl_fail_too_few_arguments; 6137 return; 6138 } 6139 6140 // (CUDA B.1): Check for invalid calls between targets. 6141 if (getLangOpts().CUDA) 6142 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6143 // Skip the check for callers that are implicit members, because in this 6144 // case we may not yet know what the member's target is; the target is 6145 // inferred for the member automatically, based on the bases and fields of 6146 // the class. 6147 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6148 Candidate.Viable = false; 6149 Candidate.FailureKind = ovl_fail_bad_target; 6150 return; 6151 } 6152 6153 // Determine the implicit conversion sequences for each of the 6154 // arguments. 6155 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6156 if (Candidate.Conversions[ArgIdx].isInitialized()) { 6157 // We already formed a conversion sequence for this parameter during 6158 // template argument deduction. 6159 } else if (ArgIdx < NumParams) { 6160 // (C++ 13.3.2p3): for F to be a viable function, there shall 6161 // exist for each argument an implicit conversion sequence 6162 // (13.3.3.1) that converts that argument to the corresponding 6163 // parameter of F. 6164 QualType ParamType = Proto->getParamType(ArgIdx); 6165 Candidate.Conversions[ArgIdx] = TryCopyInitialization( 6166 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6167 /*InOverloadResolution=*/true, 6168 /*AllowObjCWritebackConversion=*/ 6169 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6170 if (Candidate.Conversions[ArgIdx].isBad()) { 6171 Candidate.Viable = false; 6172 Candidate.FailureKind = ovl_fail_bad_conversion; 6173 return; 6174 } 6175 } else { 6176 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6177 // argument for which there is no corresponding parameter is 6178 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6179 Candidate.Conversions[ArgIdx].setEllipsis(); 6180 } 6181 } 6182 6183 if (!AllowExplicit) { 6184 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function); 6185 if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) { 6186 Candidate.Viable = false; 6187 Candidate.FailureKind = ovl_fail_explicit_resolved; 6188 return; 6189 } 6190 } 6191 6192 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6193 Candidate.Viable = false; 6194 Candidate.FailureKind = ovl_fail_enable_if; 6195 Candidate.DeductionFailure.Data = FailedAttr; 6196 return; 6197 } 6198 6199 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6200 Candidate.Viable = false; 6201 Candidate.FailureKind = ovl_fail_ext_disabled; 6202 return; 6203 } 6204 } 6205 6206 ObjCMethodDecl * 6207 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6208 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6209 if (Methods.size() <= 1) 6210 return nullptr; 6211 6212 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6213 bool Match = true; 6214 ObjCMethodDecl *Method = Methods[b]; 6215 unsigned NumNamedArgs = Sel.getNumArgs(); 6216 // Method might have more arguments than selector indicates. This is due 6217 // to addition of c-style arguments in method. 6218 if (Method->param_size() > NumNamedArgs) 6219 NumNamedArgs = Method->param_size(); 6220 if (Args.size() < NumNamedArgs) 6221 continue; 6222 6223 for (unsigned i = 0; i < NumNamedArgs; i++) { 6224 // We can't do any type-checking on a type-dependent argument. 6225 if (Args[i]->isTypeDependent()) { 6226 Match = false; 6227 break; 6228 } 6229 6230 ParmVarDecl *param = Method->parameters()[i]; 6231 Expr *argExpr = Args[i]; 6232 assert(argExpr && "SelectBestMethod(): missing expression"); 6233 6234 // Strip the unbridged-cast placeholder expression off unless it's 6235 // a consumed argument. 6236 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6237 !param->hasAttr<CFConsumedAttr>()) 6238 argExpr = stripARCUnbridgedCast(argExpr); 6239 6240 // If the parameter is __unknown_anytype, move on to the next method. 6241 if (param->getType() == Context.UnknownAnyTy) { 6242 Match = false; 6243 break; 6244 } 6245 6246 ImplicitConversionSequence ConversionState 6247 = TryCopyInitialization(*this, argExpr, param->getType(), 6248 /*SuppressUserConversions*/false, 6249 /*InOverloadResolution=*/true, 6250 /*AllowObjCWritebackConversion=*/ 6251 getLangOpts().ObjCAutoRefCount, 6252 /*AllowExplicit*/false); 6253 // This function looks for a reasonably-exact match, so we consider 6254 // incompatible pointer conversions to be a failure here. 6255 if (ConversionState.isBad() || 6256 (ConversionState.isStandard() && 6257 ConversionState.Standard.Second == 6258 ICK_Incompatible_Pointer_Conversion)) { 6259 Match = false; 6260 break; 6261 } 6262 } 6263 // Promote additional arguments to variadic methods. 6264 if (Match && Method->isVariadic()) { 6265 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6266 if (Args[i]->isTypeDependent()) { 6267 Match = false; 6268 break; 6269 } 6270 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6271 nullptr); 6272 if (Arg.isInvalid()) { 6273 Match = false; 6274 break; 6275 } 6276 } 6277 } else { 6278 // Check for extra arguments to non-variadic methods. 6279 if (Args.size() != NumNamedArgs) 6280 Match = false; 6281 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6282 // Special case when selectors have no argument. In this case, select 6283 // one with the most general result type of 'id'. 6284 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6285 QualType ReturnT = Methods[b]->getReturnType(); 6286 if (ReturnT->isObjCIdType()) 6287 return Methods[b]; 6288 } 6289 } 6290 } 6291 6292 if (Match) 6293 return Method; 6294 } 6295 return nullptr; 6296 } 6297 6298 static bool 6299 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6300 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6301 bool MissingImplicitThis, Expr *&ConvertedThis, 6302 SmallVectorImpl<Expr *> &ConvertedArgs) { 6303 if (ThisArg) { 6304 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6305 assert(!isa<CXXConstructorDecl>(Method) && 6306 "Shouldn't have `this` for ctors!"); 6307 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6308 ExprResult R = S.PerformObjectArgumentInitialization( 6309 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6310 if (R.isInvalid()) 6311 return false; 6312 ConvertedThis = R.get(); 6313 } else { 6314 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6315 (void)MD; 6316 assert((MissingImplicitThis || MD->isStatic() || 6317 isa<CXXConstructorDecl>(MD)) && 6318 "Expected `this` for non-ctor instance methods"); 6319 } 6320 ConvertedThis = nullptr; 6321 } 6322 6323 // Ignore any variadic arguments. Converting them is pointless, since the 6324 // user can't refer to them in the function condition. 6325 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6326 6327 // Convert the arguments. 6328 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6329 ExprResult R; 6330 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6331 S.Context, Function->getParamDecl(I)), 6332 SourceLocation(), Args[I]); 6333 6334 if (R.isInvalid()) 6335 return false; 6336 6337 ConvertedArgs.push_back(R.get()); 6338 } 6339 6340 if (Trap.hasErrorOccurred()) 6341 return false; 6342 6343 // Push default arguments if needed. 6344 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6345 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6346 ParmVarDecl *P = Function->getParamDecl(i); 6347 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6348 ? P->getUninstantiatedDefaultArg() 6349 : P->getDefaultArg(); 6350 // This can only happen in code completion, i.e. when PartialOverloading 6351 // is true. 6352 if (!DefArg) 6353 return false; 6354 ExprResult R = 6355 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6356 S.Context, Function->getParamDecl(i)), 6357 SourceLocation(), DefArg); 6358 if (R.isInvalid()) 6359 return false; 6360 ConvertedArgs.push_back(R.get()); 6361 } 6362 6363 if (Trap.hasErrorOccurred()) 6364 return false; 6365 } 6366 return true; 6367 } 6368 6369 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6370 bool MissingImplicitThis) { 6371 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6372 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6373 return nullptr; 6374 6375 SFINAETrap Trap(*this); 6376 SmallVector<Expr *, 16> ConvertedArgs; 6377 // FIXME: We should look into making enable_if late-parsed. 6378 Expr *DiscardedThis; 6379 if (!convertArgsForAvailabilityChecks( 6380 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6381 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6382 return *EnableIfAttrs.begin(); 6383 6384 for (auto *EIA : EnableIfAttrs) { 6385 APValue Result; 6386 // FIXME: This doesn't consider value-dependent cases, because doing so is 6387 // very difficult. Ideally, we should handle them more gracefully. 6388 if (EIA->getCond()->isValueDependent() || 6389 !EIA->getCond()->EvaluateWithSubstitution( 6390 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6391 return EIA; 6392 6393 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6394 return EIA; 6395 } 6396 return nullptr; 6397 } 6398 6399 template <typename CheckFn> 6400 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6401 bool ArgDependent, SourceLocation Loc, 6402 CheckFn &&IsSuccessful) { 6403 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6404 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6405 if (ArgDependent == DIA->getArgDependent()) 6406 Attrs.push_back(DIA); 6407 } 6408 6409 // Common case: No diagnose_if attributes, so we can quit early. 6410 if (Attrs.empty()) 6411 return false; 6412 6413 auto WarningBegin = std::stable_partition( 6414 Attrs.begin(), Attrs.end(), 6415 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6416 6417 // Note that diagnose_if attributes are late-parsed, so they appear in the 6418 // correct order (unlike enable_if attributes). 6419 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6420 IsSuccessful); 6421 if (ErrAttr != WarningBegin) { 6422 const DiagnoseIfAttr *DIA = *ErrAttr; 6423 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6424 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6425 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6426 return true; 6427 } 6428 6429 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6430 if (IsSuccessful(DIA)) { 6431 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6432 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6433 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6434 } 6435 6436 return false; 6437 } 6438 6439 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6440 const Expr *ThisArg, 6441 ArrayRef<const Expr *> Args, 6442 SourceLocation Loc) { 6443 return diagnoseDiagnoseIfAttrsWith( 6444 *this, Function, /*ArgDependent=*/true, Loc, 6445 [&](const DiagnoseIfAttr *DIA) { 6446 APValue Result; 6447 // It's sane to use the same Args for any redecl of this function, since 6448 // EvaluateWithSubstitution only cares about the position of each 6449 // argument in the arg list, not the ParmVarDecl* it maps to. 6450 if (!DIA->getCond()->EvaluateWithSubstitution( 6451 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6452 return false; 6453 return Result.isInt() && Result.getInt().getBoolValue(); 6454 }); 6455 } 6456 6457 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6458 SourceLocation Loc) { 6459 return diagnoseDiagnoseIfAttrsWith( 6460 *this, ND, /*ArgDependent=*/false, Loc, 6461 [&](const DiagnoseIfAttr *DIA) { 6462 bool Result; 6463 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6464 Result; 6465 }); 6466 } 6467 6468 /// Add all of the function declarations in the given function set to 6469 /// the overload candidate set. 6470 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6471 ArrayRef<Expr *> Args, 6472 OverloadCandidateSet &CandidateSet, 6473 TemplateArgumentListInfo *ExplicitTemplateArgs, 6474 bool SuppressUserConversions, 6475 bool PartialOverloading, 6476 bool FirstArgumentIsBase) { 6477 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6478 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6479 ArrayRef<Expr *> FunctionArgs = Args; 6480 6481 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6482 FunctionDecl *FD = 6483 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6484 6485 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6486 QualType ObjectType; 6487 Expr::Classification ObjectClassification; 6488 if (Args.size() > 0) { 6489 if (Expr *E = Args[0]) { 6490 // Use the explicit base to restrict the lookup: 6491 ObjectType = E->getType(); 6492 // Pointers in the object arguments are implicitly dereferenced, so we 6493 // always classify them as l-values. 6494 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6495 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6496 else 6497 ObjectClassification = E->Classify(Context); 6498 } // .. else there is an implicit base. 6499 FunctionArgs = Args.slice(1); 6500 } 6501 if (FunTmpl) { 6502 AddMethodTemplateCandidate( 6503 FunTmpl, F.getPair(), 6504 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6505 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6506 FunctionArgs, CandidateSet, SuppressUserConversions, 6507 PartialOverloading); 6508 } else { 6509 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6510 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6511 ObjectClassification, FunctionArgs, CandidateSet, 6512 SuppressUserConversions, PartialOverloading); 6513 } 6514 } else { 6515 // This branch handles both standalone functions and static methods. 6516 6517 // Slice the first argument (which is the base) when we access 6518 // static method as non-static. 6519 if (Args.size() > 0 && 6520 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6521 !isa<CXXConstructorDecl>(FD)))) { 6522 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6523 FunctionArgs = Args.slice(1); 6524 } 6525 if (FunTmpl) { 6526 AddTemplateOverloadCandidate( 6527 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs, 6528 CandidateSet, SuppressUserConversions, PartialOverloading); 6529 } else { 6530 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6531 SuppressUserConversions, PartialOverloading); 6532 } 6533 } 6534 } 6535 } 6536 6537 /// AddMethodCandidate - Adds a named decl (which is some kind of 6538 /// method) as a method candidate to the given overload set. 6539 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6540 QualType ObjectType, 6541 Expr::Classification ObjectClassification, 6542 ArrayRef<Expr *> Args, 6543 OverloadCandidateSet& CandidateSet, 6544 bool SuppressUserConversions) { 6545 NamedDecl *Decl = FoundDecl.getDecl(); 6546 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6547 6548 if (isa<UsingShadowDecl>(Decl)) 6549 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6550 6551 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6552 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6553 "Expected a member function template"); 6554 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6555 /*ExplicitArgs*/ nullptr, ObjectType, 6556 ObjectClassification, Args, CandidateSet, 6557 SuppressUserConversions); 6558 } else { 6559 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6560 ObjectType, ObjectClassification, Args, CandidateSet, 6561 SuppressUserConversions); 6562 } 6563 } 6564 6565 /// AddMethodCandidate - Adds the given C++ member function to the set 6566 /// of candidate functions, using the given function call arguments 6567 /// and the object argument (@c Object). For example, in a call 6568 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6569 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6570 /// allow user-defined conversions via constructors or conversion 6571 /// operators. 6572 void 6573 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6574 CXXRecordDecl *ActingContext, QualType ObjectType, 6575 Expr::Classification ObjectClassification, 6576 ArrayRef<Expr *> Args, 6577 OverloadCandidateSet &CandidateSet, 6578 bool SuppressUserConversions, 6579 bool PartialOverloading, 6580 ConversionSequenceList EarlyConversions) { 6581 const FunctionProtoType *Proto 6582 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6583 assert(Proto && "Methods without a prototype cannot be overloaded"); 6584 assert(!isa<CXXConstructorDecl>(Method) && 6585 "Use AddOverloadCandidate for constructors"); 6586 6587 if (!CandidateSet.isNewCandidate(Method)) 6588 return; 6589 6590 // C++11 [class.copy]p23: [DR1402] 6591 // A defaulted move assignment operator that is defined as deleted is 6592 // ignored by overload resolution. 6593 if (Method->isDefaulted() && Method->isDeleted() && 6594 Method->isMoveAssignmentOperator()) 6595 return; 6596 6597 // Overload resolution is always an unevaluated context. 6598 EnterExpressionEvaluationContext Unevaluated( 6599 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6600 6601 // Add this candidate 6602 OverloadCandidate &Candidate = 6603 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6604 Candidate.FoundDecl = FoundDecl; 6605 Candidate.Function = Method; 6606 Candidate.IsSurrogate = false; 6607 Candidate.IgnoreObjectArgument = false; 6608 Candidate.ExplicitCallArguments = Args.size(); 6609 6610 unsigned NumParams = Proto->getNumParams(); 6611 6612 // (C++ 13.3.2p2): A candidate function having fewer than m 6613 // parameters is viable only if it has an ellipsis in its parameter 6614 // list (8.3.5). 6615 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6616 !Proto->isVariadic()) { 6617 Candidate.Viable = false; 6618 Candidate.FailureKind = ovl_fail_too_many_arguments; 6619 return; 6620 } 6621 6622 // (C++ 13.3.2p2): A candidate function having more than m parameters 6623 // is viable only if the (m+1)st parameter has a default argument 6624 // (8.3.6). For the purposes of overload resolution, the 6625 // parameter list is truncated on the right, so that there are 6626 // exactly m parameters. 6627 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6628 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6629 // Not enough arguments. 6630 Candidate.Viable = false; 6631 Candidate.FailureKind = ovl_fail_too_few_arguments; 6632 return; 6633 } 6634 6635 Candidate.Viable = true; 6636 6637 if (Method->isStatic() || ObjectType.isNull()) 6638 // The implicit object argument is ignored. 6639 Candidate.IgnoreObjectArgument = true; 6640 else { 6641 // Determine the implicit conversion sequence for the object 6642 // parameter. 6643 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6644 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6645 Method, ActingContext); 6646 if (Candidate.Conversions[0].isBad()) { 6647 Candidate.Viable = false; 6648 Candidate.FailureKind = ovl_fail_bad_conversion; 6649 return; 6650 } 6651 } 6652 6653 // (CUDA B.1): Check for invalid calls between targets. 6654 if (getLangOpts().CUDA) 6655 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6656 if (!IsAllowedCUDACall(Caller, Method)) { 6657 Candidate.Viable = false; 6658 Candidate.FailureKind = ovl_fail_bad_target; 6659 return; 6660 } 6661 6662 // Determine the implicit conversion sequences for each of the 6663 // arguments. 6664 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6665 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6666 // We already formed a conversion sequence for this parameter during 6667 // template argument deduction. 6668 } else if (ArgIdx < NumParams) { 6669 // (C++ 13.3.2p3): for F to be a viable function, there shall 6670 // exist for each argument an implicit conversion sequence 6671 // (13.3.3.1) that converts that argument to the corresponding 6672 // parameter of F. 6673 QualType ParamType = Proto->getParamType(ArgIdx); 6674 Candidate.Conversions[ArgIdx + 1] 6675 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6676 SuppressUserConversions, 6677 /*InOverloadResolution=*/true, 6678 /*AllowObjCWritebackConversion=*/ 6679 getLangOpts().ObjCAutoRefCount); 6680 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6681 Candidate.Viable = false; 6682 Candidate.FailureKind = ovl_fail_bad_conversion; 6683 return; 6684 } 6685 } else { 6686 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6687 // argument for which there is no corresponding parameter is 6688 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6689 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6690 } 6691 } 6692 6693 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6694 Candidate.Viable = false; 6695 Candidate.FailureKind = ovl_fail_enable_if; 6696 Candidate.DeductionFailure.Data = FailedAttr; 6697 return; 6698 } 6699 6700 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6701 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6702 Candidate.Viable = false; 6703 Candidate.FailureKind = ovl_non_default_multiversion_function; 6704 } 6705 } 6706 6707 /// Add a C++ member function template as a candidate to the candidate 6708 /// set, using template argument deduction to produce an appropriate member 6709 /// function template specialization. 6710 void 6711 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6712 DeclAccessPair FoundDecl, 6713 CXXRecordDecl *ActingContext, 6714 TemplateArgumentListInfo *ExplicitTemplateArgs, 6715 QualType ObjectType, 6716 Expr::Classification ObjectClassification, 6717 ArrayRef<Expr *> Args, 6718 OverloadCandidateSet& CandidateSet, 6719 bool SuppressUserConversions, 6720 bool PartialOverloading) { 6721 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6722 return; 6723 6724 // C++ [over.match.funcs]p7: 6725 // In each case where a candidate is a function template, candidate 6726 // function template specializations are generated using template argument 6727 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6728 // candidate functions in the usual way.113) A given name can refer to one 6729 // or more function templates and also to a set of overloaded non-template 6730 // functions. In such a case, the candidate functions generated from each 6731 // function template are combined with the set of non-template candidate 6732 // functions. 6733 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6734 FunctionDecl *Specialization = nullptr; 6735 ConversionSequenceList Conversions; 6736 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6737 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6738 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6739 return CheckNonDependentConversions( 6740 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6741 SuppressUserConversions, ActingContext, ObjectType, 6742 ObjectClassification); 6743 })) { 6744 OverloadCandidate &Candidate = 6745 CandidateSet.addCandidate(Conversions.size(), Conversions); 6746 Candidate.FoundDecl = FoundDecl; 6747 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6748 Candidate.Viable = false; 6749 Candidate.IsSurrogate = false; 6750 Candidate.IgnoreObjectArgument = 6751 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6752 ObjectType.isNull(); 6753 Candidate.ExplicitCallArguments = Args.size(); 6754 if (Result == TDK_NonDependentConversionFailure) 6755 Candidate.FailureKind = ovl_fail_bad_conversion; 6756 else { 6757 Candidate.FailureKind = ovl_fail_bad_deduction; 6758 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6759 Info); 6760 } 6761 return; 6762 } 6763 6764 // Add the function template specialization produced by template argument 6765 // deduction as a candidate. 6766 assert(Specialization && "Missing member function template specialization?"); 6767 assert(isa<CXXMethodDecl>(Specialization) && 6768 "Specialization is not a member function?"); 6769 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6770 ActingContext, ObjectType, ObjectClassification, Args, 6771 CandidateSet, SuppressUserConversions, PartialOverloading, 6772 Conversions); 6773 } 6774 6775 /// Add a C++ function template specialization as a candidate 6776 /// in the candidate set, using template argument deduction to produce 6777 /// an appropriate function template specialization. 6778 void Sema::AddTemplateOverloadCandidate( 6779 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6780 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6781 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6782 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate) { 6783 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6784 return; 6785 6786 // C++ [over.match.funcs]p7: 6787 // In each case where a candidate is a function template, candidate 6788 // function template specializations are generated using template argument 6789 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6790 // candidate functions in the usual way.113) A given name can refer to one 6791 // or more function templates and also to a set of overloaded non-template 6792 // functions. In such a case, the candidate functions generated from each 6793 // function template are combined with the set of non-template candidate 6794 // functions. 6795 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6796 FunctionDecl *Specialization = nullptr; 6797 ConversionSequenceList Conversions; 6798 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6799 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6800 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6801 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6802 Args, CandidateSet, Conversions, 6803 SuppressUserConversions); 6804 })) { 6805 OverloadCandidate &Candidate = 6806 CandidateSet.addCandidate(Conversions.size(), Conversions); 6807 Candidate.FoundDecl = FoundDecl; 6808 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6809 Candidate.Viable = false; 6810 Candidate.IsSurrogate = false; 6811 Candidate.IsADLCandidate = IsADLCandidate; 6812 // Ignore the object argument if there is one, since we don't have an object 6813 // type. 6814 Candidate.IgnoreObjectArgument = 6815 isa<CXXMethodDecl>(Candidate.Function) && 6816 !isa<CXXConstructorDecl>(Candidate.Function); 6817 Candidate.ExplicitCallArguments = Args.size(); 6818 if (Result == TDK_NonDependentConversionFailure) 6819 Candidate.FailureKind = ovl_fail_bad_conversion; 6820 else { 6821 Candidate.FailureKind = ovl_fail_bad_deduction; 6822 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6823 Info); 6824 } 6825 return; 6826 } 6827 6828 // Add the function template specialization produced by template argument 6829 // deduction as a candidate. 6830 assert(Specialization && "Missing function template specialization?"); 6831 AddOverloadCandidate( 6832 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 6833 PartialOverloading, AllowExplicit, 6834 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions); 6835 } 6836 6837 /// Check that implicit conversion sequences can be formed for each argument 6838 /// whose corresponding parameter has a non-dependent type, per DR1391's 6839 /// [temp.deduct.call]p10. 6840 bool Sema::CheckNonDependentConversions( 6841 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6842 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6843 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6844 CXXRecordDecl *ActingContext, QualType ObjectType, 6845 Expr::Classification ObjectClassification) { 6846 // FIXME: The cases in which we allow explicit conversions for constructor 6847 // arguments never consider calling a constructor template. It's not clear 6848 // that is correct. 6849 const bool AllowExplicit = false; 6850 6851 auto *FD = FunctionTemplate->getTemplatedDecl(); 6852 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6853 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6854 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6855 6856 Conversions = 6857 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6858 6859 // Overload resolution is always an unevaluated context. 6860 EnterExpressionEvaluationContext Unevaluated( 6861 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6862 6863 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6864 // require that, but this check should never result in a hard error, and 6865 // overload resolution is permitted to sidestep instantiations. 6866 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6867 !ObjectType.isNull()) { 6868 Conversions[0] = TryObjectArgumentInitialization( 6869 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6870 Method, ActingContext); 6871 if (Conversions[0].isBad()) 6872 return true; 6873 } 6874 6875 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6876 ++I) { 6877 QualType ParamType = ParamTypes[I]; 6878 if (!ParamType->isDependentType()) { 6879 Conversions[ThisConversions + I] 6880 = TryCopyInitialization(*this, Args[I], ParamType, 6881 SuppressUserConversions, 6882 /*InOverloadResolution=*/true, 6883 /*AllowObjCWritebackConversion=*/ 6884 getLangOpts().ObjCAutoRefCount, 6885 AllowExplicit); 6886 if (Conversions[ThisConversions + I].isBad()) 6887 return true; 6888 } 6889 } 6890 6891 return false; 6892 } 6893 6894 /// Determine whether this is an allowable conversion from the result 6895 /// of an explicit conversion operator to the expected type, per C++ 6896 /// [over.match.conv]p1 and [over.match.ref]p1. 6897 /// 6898 /// \param ConvType The return type of the conversion function. 6899 /// 6900 /// \param ToType The type we are converting to. 6901 /// 6902 /// \param AllowObjCPointerConversion Allow a conversion from one 6903 /// Objective-C pointer to another. 6904 /// 6905 /// \returns true if the conversion is allowable, false otherwise. 6906 static bool isAllowableExplicitConversion(Sema &S, 6907 QualType ConvType, QualType ToType, 6908 bool AllowObjCPointerConversion) { 6909 QualType ToNonRefType = ToType.getNonReferenceType(); 6910 6911 // Easy case: the types are the same. 6912 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6913 return true; 6914 6915 // Allow qualification conversions. 6916 bool ObjCLifetimeConversion; 6917 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6918 ObjCLifetimeConversion)) 6919 return true; 6920 6921 // If we're not allowed to consider Objective-C pointer conversions, 6922 // we're done. 6923 if (!AllowObjCPointerConversion) 6924 return false; 6925 6926 // Is this an Objective-C pointer conversion? 6927 bool IncompatibleObjC = false; 6928 QualType ConvertedType; 6929 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6930 IncompatibleObjC); 6931 } 6932 6933 /// AddConversionCandidate - Add a C++ conversion function as a 6934 /// candidate in the candidate set (C++ [over.match.conv], 6935 /// C++ [over.match.copy]). From is the expression we're converting from, 6936 /// and ToType is the type that we're eventually trying to convert to 6937 /// (which may or may not be the same type as the type that the 6938 /// conversion function produces). 6939 void Sema::AddConversionCandidate( 6940 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 6941 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 6942 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 6943 bool AllowExplicit, bool AllowResultConversion) { 6944 assert(!Conversion->getDescribedFunctionTemplate() && 6945 "Conversion function templates use AddTemplateConversionCandidate"); 6946 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6947 if (!CandidateSet.isNewCandidate(Conversion)) 6948 return; 6949 6950 // If the conversion function has an undeduced return type, trigger its 6951 // deduction now. 6952 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6953 if (DeduceReturnType(Conversion, From->getExprLoc())) 6954 return; 6955 ConvType = Conversion->getConversionType().getNonReferenceType(); 6956 } 6957 6958 // If we don't allow any conversion of the result type, ignore conversion 6959 // functions that don't convert to exactly (possibly cv-qualified) T. 6960 if (!AllowResultConversion && 6961 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 6962 return; 6963 6964 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6965 // operator is only a candidate if its return type is the target type or 6966 // can be converted to the target type with a qualification conversion. 6967 if (Conversion->isExplicit() && 6968 !isAllowableExplicitConversion(*this, ConvType, ToType, 6969 AllowObjCConversionOnExplicit)) 6970 return; 6971 6972 // Overload resolution is always an unevaluated context. 6973 EnterExpressionEvaluationContext Unevaluated( 6974 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6975 6976 // Add this candidate 6977 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6978 Candidate.FoundDecl = FoundDecl; 6979 Candidate.Function = Conversion; 6980 Candidate.IsSurrogate = false; 6981 Candidate.IgnoreObjectArgument = false; 6982 Candidate.FinalConversion.setAsIdentityConversion(); 6983 Candidate.FinalConversion.setFromType(ConvType); 6984 Candidate.FinalConversion.setAllToTypes(ToType); 6985 Candidate.Viable = true; 6986 Candidate.ExplicitCallArguments = 1; 6987 6988 // C++ [over.match.funcs]p4: 6989 // For conversion functions, the function is considered to be a member of 6990 // the class of the implicit implied object argument for the purpose of 6991 // defining the type of the implicit object parameter. 6992 // 6993 // Determine the implicit conversion sequence for the implicit 6994 // object parameter. 6995 QualType ImplicitParamType = From->getType(); 6996 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6997 ImplicitParamType = FromPtrType->getPointeeType(); 6998 CXXRecordDecl *ConversionContext 6999 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 7000 7001 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7002 *this, CandidateSet.getLocation(), From->getType(), 7003 From->Classify(Context), Conversion, ConversionContext); 7004 7005 if (Candidate.Conversions[0].isBad()) { 7006 Candidate.Viable = false; 7007 Candidate.FailureKind = ovl_fail_bad_conversion; 7008 return; 7009 } 7010 7011 // We won't go through a user-defined type conversion function to convert a 7012 // derived to base as such conversions are given Conversion Rank. They only 7013 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7014 QualType FromCanon 7015 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7016 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7017 if (FromCanon == ToCanon || 7018 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7019 Candidate.Viable = false; 7020 Candidate.FailureKind = ovl_fail_trivial_conversion; 7021 return; 7022 } 7023 7024 // To determine what the conversion from the result of calling the 7025 // conversion function to the type we're eventually trying to 7026 // convert to (ToType), we need to synthesize a call to the 7027 // conversion function and attempt copy initialization from it. This 7028 // makes sure that we get the right semantics with respect to 7029 // lvalues/rvalues and the type. Fortunately, we can allocate this 7030 // call on the stack and we don't need its arguments to be 7031 // well-formed. 7032 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7033 VK_LValue, From->getBeginLoc()); 7034 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7035 Context.getPointerType(Conversion->getType()), 7036 CK_FunctionToPointerDecay, 7037 &ConversionRef, VK_RValue); 7038 7039 QualType ConversionType = Conversion->getConversionType(); 7040 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7041 Candidate.Viable = false; 7042 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7043 return; 7044 } 7045 7046 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7047 7048 // Note that it is safe to allocate CallExpr on the stack here because 7049 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7050 // allocator). 7051 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7052 7053 llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)> 7054 Buffer; 7055 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7056 Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7057 7058 ImplicitConversionSequence ICS = 7059 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7060 /*SuppressUserConversions=*/true, 7061 /*InOverloadResolution=*/false, 7062 /*AllowObjCWritebackConversion=*/false); 7063 7064 switch (ICS.getKind()) { 7065 case ImplicitConversionSequence::StandardConversion: 7066 Candidate.FinalConversion = ICS.Standard; 7067 7068 // C++ [over.ics.user]p3: 7069 // If the user-defined conversion is specified by a specialization of a 7070 // conversion function template, the second standard conversion sequence 7071 // shall have exact match rank. 7072 if (Conversion->getPrimaryTemplate() && 7073 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7074 Candidate.Viable = false; 7075 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7076 return; 7077 } 7078 7079 // C++0x [dcl.init.ref]p5: 7080 // In the second case, if the reference is an rvalue reference and 7081 // the second standard conversion sequence of the user-defined 7082 // conversion sequence includes an lvalue-to-rvalue conversion, the 7083 // program is ill-formed. 7084 if (ToType->isRValueReferenceType() && 7085 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7086 Candidate.Viable = false; 7087 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7088 return; 7089 } 7090 break; 7091 7092 case ImplicitConversionSequence::BadConversion: 7093 Candidate.Viable = false; 7094 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7095 return; 7096 7097 default: 7098 llvm_unreachable( 7099 "Can only end up with a standard conversion sequence or failure"); 7100 } 7101 7102 if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() != 7103 ExplicitSpecKind::ResolvedFalse) { 7104 Candidate.Viable = false; 7105 Candidate.FailureKind = ovl_fail_explicit_resolved; 7106 return; 7107 } 7108 7109 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7110 Candidate.Viable = false; 7111 Candidate.FailureKind = ovl_fail_enable_if; 7112 Candidate.DeductionFailure.Data = FailedAttr; 7113 return; 7114 } 7115 7116 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7117 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7118 Candidate.Viable = false; 7119 Candidate.FailureKind = ovl_non_default_multiversion_function; 7120 } 7121 } 7122 7123 /// Adds a conversion function template specialization 7124 /// candidate to the overload set, using template argument deduction 7125 /// to deduce the template arguments of the conversion function 7126 /// template from the type that we are converting to (C++ 7127 /// [temp.deduct.conv]). 7128 void Sema::AddTemplateConversionCandidate( 7129 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7130 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7131 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7132 bool AllowExplicit, bool AllowResultConversion) { 7133 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7134 "Only conversion function templates permitted here"); 7135 7136 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7137 return; 7138 7139 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7140 CXXConversionDecl *Specialization = nullptr; 7141 if (TemplateDeductionResult Result 7142 = DeduceTemplateArguments(FunctionTemplate, ToType, 7143 Specialization, Info)) { 7144 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7145 Candidate.FoundDecl = FoundDecl; 7146 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7147 Candidate.Viable = false; 7148 Candidate.FailureKind = ovl_fail_bad_deduction; 7149 Candidate.IsSurrogate = false; 7150 Candidate.IgnoreObjectArgument = false; 7151 Candidate.ExplicitCallArguments = 1; 7152 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7153 Info); 7154 return; 7155 } 7156 7157 // Add the conversion function template specialization produced by 7158 // template argument deduction as a candidate. 7159 assert(Specialization && "Missing function template specialization?"); 7160 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7161 CandidateSet, AllowObjCConversionOnExplicit, 7162 AllowExplicit, AllowResultConversion); 7163 } 7164 7165 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7166 /// converts the given @c Object to a function pointer via the 7167 /// conversion function @c Conversion, and then attempts to call it 7168 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7169 /// the type of function that we'll eventually be calling. 7170 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7171 DeclAccessPair FoundDecl, 7172 CXXRecordDecl *ActingContext, 7173 const FunctionProtoType *Proto, 7174 Expr *Object, 7175 ArrayRef<Expr *> Args, 7176 OverloadCandidateSet& CandidateSet) { 7177 if (!CandidateSet.isNewCandidate(Conversion)) 7178 return; 7179 7180 // Overload resolution is always an unevaluated context. 7181 EnterExpressionEvaluationContext Unevaluated( 7182 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7183 7184 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7185 Candidate.FoundDecl = FoundDecl; 7186 Candidate.Function = nullptr; 7187 Candidate.Surrogate = Conversion; 7188 Candidate.Viable = true; 7189 Candidate.IsSurrogate = true; 7190 Candidate.IgnoreObjectArgument = false; 7191 Candidate.ExplicitCallArguments = Args.size(); 7192 7193 // Determine the implicit conversion sequence for the implicit 7194 // object parameter. 7195 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7196 *this, CandidateSet.getLocation(), Object->getType(), 7197 Object->Classify(Context), Conversion, ActingContext); 7198 if (ObjectInit.isBad()) { 7199 Candidate.Viable = false; 7200 Candidate.FailureKind = ovl_fail_bad_conversion; 7201 Candidate.Conversions[0] = ObjectInit; 7202 return; 7203 } 7204 7205 // The first conversion is actually a user-defined conversion whose 7206 // first conversion is ObjectInit's standard conversion (which is 7207 // effectively a reference binding). Record it as such. 7208 Candidate.Conversions[0].setUserDefined(); 7209 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7210 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7211 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7212 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7213 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7214 Candidate.Conversions[0].UserDefined.After 7215 = Candidate.Conversions[0].UserDefined.Before; 7216 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7217 7218 // Find the 7219 unsigned NumParams = Proto->getNumParams(); 7220 7221 // (C++ 13.3.2p2): A candidate function having fewer than m 7222 // parameters is viable only if it has an ellipsis in its parameter 7223 // list (8.3.5). 7224 if (Args.size() > NumParams && !Proto->isVariadic()) { 7225 Candidate.Viable = false; 7226 Candidate.FailureKind = ovl_fail_too_many_arguments; 7227 return; 7228 } 7229 7230 // Function types don't have any default arguments, so just check if 7231 // we have enough arguments. 7232 if (Args.size() < NumParams) { 7233 // Not enough arguments. 7234 Candidate.Viable = false; 7235 Candidate.FailureKind = ovl_fail_too_few_arguments; 7236 return; 7237 } 7238 7239 // Determine the implicit conversion sequences for each of the 7240 // arguments. 7241 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7242 if (ArgIdx < NumParams) { 7243 // (C++ 13.3.2p3): for F to be a viable function, there shall 7244 // exist for each argument an implicit conversion sequence 7245 // (13.3.3.1) that converts that argument to the corresponding 7246 // parameter of F. 7247 QualType ParamType = Proto->getParamType(ArgIdx); 7248 Candidate.Conversions[ArgIdx + 1] 7249 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7250 /*SuppressUserConversions=*/false, 7251 /*InOverloadResolution=*/false, 7252 /*AllowObjCWritebackConversion=*/ 7253 getLangOpts().ObjCAutoRefCount); 7254 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7255 Candidate.Viable = false; 7256 Candidate.FailureKind = ovl_fail_bad_conversion; 7257 return; 7258 } 7259 } else { 7260 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7261 // argument for which there is no corresponding parameter is 7262 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7263 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7264 } 7265 } 7266 7267 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7268 Candidate.Viable = false; 7269 Candidate.FailureKind = ovl_fail_enable_if; 7270 Candidate.DeductionFailure.Data = FailedAttr; 7271 return; 7272 } 7273 } 7274 7275 /// Add overload candidates for overloaded operators that are 7276 /// member functions. 7277 /// 7278 /// Add the overloaded operator candidates that are member functions 7279 /// for the operator Op that was used in an operator expression such 7280 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7281 /// CandidateSet will store the added overload candidates. (C++ 7282 /// [over.match.oper]). 7283 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7284 SourceLocation OpLoc, 7285 ArrayRef<Expr *> Args, 7286 OverloadCandidateSet& CandidateSet, 7287 SourceRange OpRange) { 7288 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7289 7290 // C++ [over.match.oper]p3: 7291 // For a unary operator @ with an operand of a type whose 7292 // cv-unqualified version is T1, and for a binary operator @ with 7293 // a left operand of a type whose cv-unqualified version is T1 and 7294 // a right operand of a type whose cv-unqualified version is T2, 7295 // three sets of candidate functions, designated member 7296 // candidates, non-member candidates and built-in candidates, are 7297 // constructed as follows: 7298 QualType T1 = Args[0]->getType(); 7299 7300 // -- If T1 is a complete class type or a class currently being 7301 // defined, the set of member candidates is the result of the 7302 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7303 // the set of member candidates is empty. 7304 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7305 // Complete the type if it can be completed. 7306 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7307 return; 7308 // If the type is neither complete nor being defined, bail out now. 7309 if (!T1Rec->getDecl()->getDefinition()) 7310 return; 7311 7312 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7313 LookupQualifiedName(Operators, T1Rec->getDecl()); 7314 Operators.suppressDiagnostics(); 7315 7316 for (LookupResult::iterator Oper = Operators.begin(), 7317 OperEnd = Operators.end(); 7318 Oper != OperEnd; 7319 ++Oper) 7320 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7321 Args[0]->Classify(Context), Args.slice(1), 7322 CandidateSet, /*SuppressUserConversions=*/false); 7323 } 7324 } 7325 7326 /// AddBuiltinCandidate - Add a candidate for a built-in 7327 /// operator. ResultTy and ParamTys are the result and parameter types 7328 /// of the built-in candidate, respectively. Args and NumArgs are the 7329 /// arguments being passed to the candidate. IsAssignmentOperator 7330 /// should be true when this built-in candidate is an assignment 7331 /// operator. NumContextualBoolArguments is the number of arguments 7332 /// (at the beginning of the argument list) that will be contextually 7333 /// converted to bool. 7334 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7335 OverloadCandidateSet& CandidateSet, 7336 bool IsAssignmentOperator, 7337 unsigned NumContextualBoolArguments) { 7338 // Overload resolution is always an unevaluated context. 7339 EnterExpressionEvaluationContext Unevaluated( 7340 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7341 7342 // Add this candidate 7343 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7344 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7345 Candidate.Function = nullptr; 7346 Candidate.IsSurrogate = false; 7347 Candidate.IgnoreObjectArgument = false; 7348 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7349 7350 // Determine the implicit conversion sequences for each of the 7351 // arguments. 7352 Candidate.Viable = true; 7353 Candidate.ExplicitCallArguments = Args.size(); 7354 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7355 // C++ [over.match.oper]p4: 7356 // For the built-in assignment operators, conversions of the 7357 // left operand are restricted as follows: 7358 // -- no temporaries are introduced to hold the left operand, and 7359 // -- no user-defined conversions are applied to the left 7360 // operand to achieve a type match with the left-most 7361 // parameter of a built-in candidate. 7362 // 7363 // We block these conversions by turning off user-defined 7364 // conversions, since that is the only way that initialization of 7365 // a reference to a non-class type can occur from something that 7366 // is not of the same type. 7367 if (ArgIdx < NumContextualBoolArguments) { 7368 assert(ParamTys[ArgIdx] == Context.BoolTy && 7369 "Contextual conversion to bool requires bool type"); 7370 Candidate.Conversions[ArgIdx] 7371 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7372 } else { 7373 Candidate.Conversions[ArgIdx] 7374 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7375 ArgIdx == 0 && IsAssignmentOperator, 7376 /*InOverloadResolution=*/false, 7377 /*AllowObjCWritebackConversion=*/ 7378 getLangOpts().ObjCAutoRefCount); 7379 } 7380 if (Candidate.Conversions[ArgIdx].isBad()) { 7381 Candidate.Viable = false; 7382 Candidate.FailureKind = ovl_fail_bad_conversion; 7383 break; 7384 } 7385 } 7386 } 7387 7388 namespace { 7389 7390 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7391 /// candidate operator functions for built-in operators (C++ 7392 /// [over.built]). The types are separated into pointer types and 7393 /// enumeration types. 7394 class BuiltinCandidateTypeSet { 7395 /// TypeSet - A set of types. 7396 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7397 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7398 7399 /// PointerTypes - The set of pointer types that will be used in the 7400 /// built-in candidates. 7401 TypeSet PointerTypes; 7402 7403 /// MemberPointerTypes - The set of member pointer types that will be 7404 /// used in the built-in candidates. 7405 TypeSet MemberPointerTypes; 7406 7407 /// EnumerationTypes - The set of enumeration types that will be 7408 /// used in the built-in candidates. 7409 TypeSet EnumerationTypes; 7410 7411 /// The set of vector types that will be used in the built-in 7412 /// candidates. 7413 TypeSet VectorTypes; 7414 7415 /// A flag indicating non-record types are viable candidates 7416 bool HasNonRecordTypes; 7417 7418 /// A flag indicating whether either arithmetic or enumeration types 7419 /// were present in the candidate set. 7420 bool HasArithmeticOrEnumeralTypes; 7421 7422 /// A flag indicating whether the nullptr type was present in the 7423 /// candidate set. 7424 bool HasNullPtrType; 7425 7426 /// Sema - The semantic analysis instance where we are building the 7427 /// candidate type set. 7428 Sema &SemaRef; 7429 7430 /// Context - The AST context in which we will build the type sets. 7431 ASTContext &Context; 7432 7433 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7434 const Qualifiers &VisibleQuals); 7435 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7436 7437 public: 7438 /// iterator - Iterates through the types that are part of the set. 7439 typedef TypeSet::iterator iterator; 7440 7441 BuiltinCandidateTypeSet(Sema &SemaRef) 7442 : HasNonRecordTypes(false), 7443 HasArithmeticOrEnumeralTypes(false), 7444 HasNullPtrType(false), 7445 SemaRef(SemaRef), 7446 Context(SemaRef.Context) { } 7447 7448 void AddTypesConvertedFrom(QualType Ty, 7449 SourceLocation Loc, 7450 bool AllowUserConversions, 7451 bool AllowExplicitConversions, 7452 const Qualifiers &VisibleTypeConversionsQuals); 7453 7454 /// pointer_begin - First pointer type found; 7455 iterator pointer_begin() { return PointerTypes.begin(); } 7456 7457 /// pointer_end - Past the last pointer type found; 7458 iterator pointer_end() { return PointerTypes.end(); } 7459 7460 /// member_pointer_begin - First member pointer type found; 7461 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7462 7463 /// member_pointer_end - Past the last member pointer type found; 7464 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7465 7466 /// enumeration_begin - First enumeration type found; 7467 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7468 7469 /// enumeration_end - Past the last enumeration type found; 7470 iterator enumeration_end() { return EnumerationTypes.end(); } 7471 7472 iterator vector_begin() { return VectorTypes.begin(); } 7473 iterator vector_end() { return VectorTypes.end(); } 7474 7475 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7476 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7477 bool hasNullPtrType() const { return HasNullPtrType; } 7478 }; 7479 7480 } // end anonymous namespace 7481 7482 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7483 /// the set of pointer types along with any more-qualified variants of 7484 /// that type. For example, if @p Ty is "int const *", this routine 7485 /// will add "int const *", "int const volatile *", "int const 7486 /// restrict *", and "int const volatile restrict *" to the set of 7487 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7488 /// false otherwise. 7489 /// 7490 /// FIXME: what to do about extended qualifiers? 7491 bool 7492 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7493 const Qualifiers &VisibleQuals) { 7494 7495 // Insert this type. 7496 if (!PointerTypes.insert(Ty)) 7497 return false; 7498 7499 QualType PointeeTy; 7500 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7501 bool buildObjCPtr = false; 7502 if (!PointerTy) { 7503 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7504 PointeeTy = PTy->getPointeeType(); 7505 buildObjCPtr = true; 7506 } else { 7507 PointeeTy = PointerTy->getPointeeType(); 7508 } 7509 7510 // Don't add qualified variants of arrays. For one, they're not allowed 7511 // (the qualifier would sink to the element type), and for another, the 7512 // only overload situation where it matters is subscript or pointer +- int, 7513 // and those shouldn't have qualifier variants anyway. 7514 if (PointeeTy->isArrayType()) 7515 return true; 7516 7517 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7518 bool hasVolatile = VisibleQuals.hasVolatile(); 7519 bool hasRestrict = VisibleQuals.hasRestrict(); 7520 7521 // Iterate through all strict supersets of BaseCVR. 7522 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7523 if ((CVR | BaseCVR) != CVR) continue; 7524 // Skip over volatile if no volatile found anywhere in the types. 7525 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7526 7527 // Skip over restrict if no restrict found anywhere in the types, or if 7528 // the type cannot be restrict-qualified. 7529 if ((CVR & Qualifiers::Restrict) && 7530 (!hasRestrict || 7531 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7532 continue; 7533 7534 // Build qualified pointee type. 7535 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7536 7537 // Build qualified pointer type. 7538 QualType QPointerTy; 7539 if (!buildObjCPtr) 7540 QPointerTy = Context.getPointerType(QPointeeTy); 7541 else 7542 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7543 7544 // Insert qualified pointer type. 7545 PointerTypes.insert(QPointerTy); 7546 } 7547 7548 return true; 7549 } 7550 7551 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7552 /// to the set of pointer types along with any more-qualified variants of 7553 /// that type. For example, if @p Ty is "int const *", this routine 7554 /// will add "int const *", "int const volatile *", "int const 7555 /// restrict *", and "int const volatile restrict *" to the set of 7556 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7557 /// false otherwise. 7558 /// 7559 /// FIXME: what to do about extended qualifiers? 7560 bool 7561 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7562 QualType Ty) { 7563 // Insert this type. 7564 if (!MemberPointerTypes.insert(Ty)) 7565 return false; 7566 7567 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7568 assert(PointerTy && "type was not a member pointer type!"); 7569 7570 QualType PointeeTy = PointerTy->getPointeeType(); 7571 // Don't add qualified variants of arrays. For one, they're not allowed 7572 // (the qualifier would sink to the element type), and for another, the 7573 // only overload situation where it matters is subscript or pointer +- int, 7574 // and those shouldn't have qualifier variants anyway. 7575 if (PointeeTy->isArrayType()) 7576 return true; 7577 const Type *ClassTy = PointerTy->getClass(); 7578 7579 // Iterate through all strict supersets of the pointee type's CVR 7580 // qualifiers. 7581 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7582 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7583 if ((CVR | BaseCVR) != CVR) continue; 7584 7585 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7586 MemberPointerTypes.insert( 7587 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7588 } 7589 7590 return true; 7591 } 7592 7593 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7594 /// Ty can be implicit converted to the given set of @p Types. We're 7595 /// primarily interested in pointer types and enumeration types. We also 7596 /// take member pointer types, for the conditional operator. 7597 /// AllowUserConversions is true if we should look at the conversion 7598 /// functions of a class type, and AllowExplicitConversions if we 7599 /// should also include the explicit conversion functions of a class 7600 /// type. 7601 void 7602 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7603 SourceLocation Loc, 7604 bool AllowUserConversions, 7605 bool AllowExplicitConversions, 7606 const Qualifiers &VisibleQuals) { 7607 // Only deal with canonical types. 7608 Ty = Context.getCanonicalType(Ty); 7609 7610 // Look through reference types; they aren't part of the type of an 7611 // expression for the purposes of conversions. 7612 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7613 Ty = RefTy->getPointeeType(); 7614 7615 // If we're dealing with an array type, decay to the pointer. 7616 if (Ty->isArrayType()) 7617 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7618 7619 // Otherwise, we don't care about qualifiers on the type. 7620 Ty = Ty.getLocalUnqualifiedType(); 7621 7622 // Flag if we ever add a non-record type. 7623 const RecordType *TyRec = Ty->getAs<RecordType>(); 7624 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7625 7626 // Flag if we encounter an arithmetic type. 7627 HasArithmeticOrEnumeralTypes = 7628 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7629 7630 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7631 PointerTypes.insert(Ty); 7632 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7633 // Insert our type, and its more-qualified variants, into the set 7634 // of types. 7635 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7636 return; 7637 } else if (Ty->isMemberPointerType()) { 7638 // Member pointers are far easier, since the pointee can't be converted. 7639 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7640 return; 7641 } else if (Ty->isEnumeralType()) { 7642 HasArithmeticOrEnumeralTypes = true; 7643 EnumerationTypes.insert(Ty); 7644 } else if (Ty->isVectorType()) { 7645 // We treat vector types as arithmetic types in many contexts as an 7646 // extension. 7647 HasArithmeticOrEnumeralTypes = true; 7648 VectorTypes.insert(Ty); 7649 } else if (Ty->isNullPtrType()) { 7650 HasNullPtrType = true; 7651 } else if (AllowUserConversions && TyRec) { 7652 // No conversion functions in incomplete types. 7653 if (!SemaRef.isCompleteType(Loc, Ty)) 7654 return; 7655 7656 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7657 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7658 if (isa<UsingShadowDecl>(D)) 7659 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7660 7661 // Skip conversion function templates; they don't tell us anything 7662 // about which builtin types we can convert to. 7663 if (isa<FunctionTemplateDecl>(D)) 7664 continue; 7665 7666 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7667 if (AllowExplicitConversions || !Conv->isExplicit()) { 7668 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7669 VisibleQuals); 7670 } 7671 } 7672 } 7673 } 7674 /// Helper function for adjusting address spaces for the pointer or reference 7675 /// operands of builtin operators depending on the argument. 7676 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7677 Expr *Arg) { 7678 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7679 } 7680 7681 /// Helper function for AddBuiltinOperatorCandidates() that adds 7682 /// the volatile- and non-volatile-qualified assignment operators for the 7683 /// given type to the candidate set. 7684 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7685 QualType T, 7686 ArrayRef<Expr *> Args, 7687 OverloadCandidateSet &CandidateSet) { 7688 QualType ParamTypes[2]; 7689 7690 // T& operator=(T&, T) 7691 ParamTypes[0] = S.Context.getLValueReferenceType( 7692 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7693 ParamTypes[1] = T; 7694 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7695 /*IsAssignmentOperator=*/true); 7696 7697 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7698 // volatile T& operator=(volatile T&, T) 7699 ParamTypes[0] = S.Context.getLValueReferenceType( 7700 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7701 Args[0])); 7702 ParamTypes[1] = T; 7703 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7704 /*IsAssignmentOperator=*/true); 7705 } 7706 } 7707 7708 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7709 /// if any, found in visible type conversion functions found in ArgExpr's type. 7710 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7711 Qualifiers VRQuals; 7712 const RecordType *TyRec; 7713 if (const MemberPointerType *RHSMPType = 7714 ArgExpr->getType()->getAs<MemberPointerType>()) 7715 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7716 else 7717 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7718 if (!TyRec) { 7719 // Just to be safe, assume the worst case. 7720 VRQuals.addVolatile(); 7721 VRQuals.addRestrict(); 7722 return VRQuals; 7723 } 7724 7725 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7726 if (!ClassDecl->hasDefinition()) 7727 return VRQuals; 7728 7729 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7730 if (isa<UsingShadowDecl>(D)) 7731 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7732 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7733 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7734 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7735 CanTy = ResTypeRef->getPointeeType(); 7736 // Need to go down the pointer/mempointer chain and add qualifiers 7737 // as see them. 7738 bool done = false; 7739 while (!done) { 7740 if (CanTy.isRestrictQualified()) 7741 VRQuals.addRestrict(); 7742 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7743 CanTy = ResTypePtr->getPointeeType(); 7744 else if (const MemberPointerType *ResTypeMPtr = 7745 CanTy->getAs<MemberPointerType>()) 7746 CanTy = ResTypeMPtr->getPointeeType(); 7747 else 7748 done = true; 7749 if (CanTy.isVolatileQualified()) 7750 VRQuals.addVolatile(); 7751 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7752 return VRQuals; 7753 } 7754 } 7755 } 7756 return VRQuals; 7757 } 7758 7759 namespace { 7760 7761 /// Helper class to manage the addition of builtin operator overload 7762 /// candidates. It provides shared state and utility methods used throughout 7763 /// the process, as well as a helper method to add each group of builtin 7764 /// operator overloads from the standard to a candidate set. 7765 class BuiltinOperatorOverloadBuilder { 7766 // Common instance state available to all overload candidate addition methods. 7767 Sema &S; 7768 ArrayRef<Expr *> Args; 7769 Qualifiers VisibleTypeConversionsQuals; 7770 bool HasArithmeticOrEnumeralCandidateType; 7771 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7772 OverloadCandidateSet &CandidateSet; 7773 7774 static constexpr int ArithmeticTypesCap = 24; 7775 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7776 7777 // Define some indices used to iterate over the arithemetic types in 7778 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7779 // types are that preserved by promotion (C++ [over.built]p2). 7780 unsigned FirstIntegralType, 7781 LastIntegralType; 7782 unsigned FirstPromotedIntegralType, 7783 LastPromotedIntegralType; 7784 unsigned FirstPromotedArithmeticType, 7785 LastPromotedArithmeticType; 7786 unsigned NumArithmeticTypes; 7787 7788 void InitArithmeticTypes() { 7789 // Start of promoted types. 7790 FirstPromotedArithmeticType = 0; 7791 ArithmeticTypes.push_back(S.Context.FloatTy); 7792 ArithmeticTypes.push_back(S.Context.DoubleTy); 7793 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7794 if (S.Context.getTargetInfo().hasFloat128Type()) 7795 ArithmeticTypes.push_back(S.Context.Float128Ty); 7796 7797 // Start of integral types. 7798 FirstIntegralType = ArithmeticTypes.size(); 7799 FirstPromotedIntegralType = ArithmeticTypes.size(); 7800 ArithmeticTypes.push_back(S.Context.IntTy); 7801 ArithmeticTypes.push_back(S.Context.LongTy); 7802 ArithmeticTypes.push_back(S.Context.LongLongTy); 7803 if (S.Context.getTargetInfo().hasInt128Type()) 7804 ArithmeticTypes.push_back(S.Context.Int128Ty); 7805 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7806 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7807 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7808 if (S.Context.getTargetInfo().hasInt128Type()) 7809 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7810 LastPromotedIntegralType = ArithmeticTypes.size(); 7811 LastPromotedArithmeticType = ArithmeticTypes.size(); 7812 // End of promoted types. 7813 7814 ArithmeticTypes.push_back(S.Context.BoolTy); 7815 ArithmeticTypes.push_back(S.Context.CharTy); 7816 ArithmeticTypes.push_back(S.Context.WCharTy); 7817 if (S.Context.getLangOpts().Char8) 7818 ArithmeticTypes.push_back(S.Context.Char8Ty); 7819 ArithmeticTypes.push_back(S.Context.Char16Ty); 7820 ArithmeticTypes.push_back(S.Context.Char32Ty); 7821 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7822 ArithmeticTypes.push_back(S.Context.ShortTy); 7823 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7824 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7825 LastIntegralType = ArithmeticTypes.size(); 7826 NumArithmeticTypes = ArithmeticTypes.size(); 7827 // End of integral types. 7828 // FIXME: What about complex? What about half? 7829 7830 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7831 "Enough inline storage for all arithmetic types."); 7832 } 7833 7834 /// Helper method to factor out the common pattern of adding overloads 7835 /// for '++' and '--' builtin operators. 7836 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7837 bool HasVolatile, 7838 bool HasRestrict) { 7839 QualType ParamTypes[2] = { 7840 S.Context.getLValueReferenceType(CandidateTy), 7841 S.Context.IntTy 7842 }; 7843 7844 // Non-volatile version. 7845 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7846 7847 // Use a heuristic to reduce number of builtin candidates in the set: 7848 // add volatile version only if there are conversions to a volatile type. 7849 if (HasVolatile) { 7850 ParamTypes[0] = 7851 S.Context.getLValueReferenceType( 7852 S.Context.getVolatileType(CandidateTy)); 7853 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7854 } 7855 7856 // Add restrict version only if there are conversions to a restrict type 7857 // and our candidate type is a non-restrict-qualified pointer. 7858 if (HasRestrict && CandidateTy->isAnyPointerType() && 7859 !CandidateTy.isRestrictQualified()) { 7860 ParamTypes[0] 7861 = S.Context.getLValueReferenceType( 7862 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7863 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7864 7865 if (HasVolatile) { 7866 ParamTypes[0] 7867 = S.Context.getLValueReferenceType( 7868 S.Context.getCVRQualifiedType(CandidateTy, 7869 (Qualifiers::Volatile | 7870 Qualifiers::Restrict))); 7871 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7872 } 7873 } 7874 7875 } 7876 7877 public: 7878 BuiltinOperatorOverloadBuilder( 7879 Sema &S, ArrayRef<Expr *> Args, 7880 Qualifiers VisibleTypeConversionsQuals, 7881 bool HasArithmeticOrEnumeralCandidateType, 7882 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7883 OverloadCandidateSet &CandidateSet) 7884 : S(S), Args(Args), 7885 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7886 HasArithmeticOrEnumeralCandidateType( 7887 HasArithmeticOrEnumeralCandidateType), 7888 CandidateTypes(CandidateTypes), 7889 CandidateSet(CandidateSet) { 7890 7891 InitArithmeticTypes(); 7892 } 7893 7894 // Increment is deprecated for bool since C++17. 7895 // 7896 // C++ [over.built]p3: 7897 // 7898 // For every pair (T, VQ), where T is an arithmetic type other 7899 // than bool, and VQ is either volatile or empty, there exist 7900 // candidate operator functions of the form 7901 // 7902 // VQ T& operator++(VQ T&); 7903 // T operator++(VQ T&, int); 7904 // 7905 // C++ [over.built]p4: 7906 // 7907 // For every pair (T, VQ), where T is an arithmetic type other 7908 // than bool, and VQ is either volatile or empty, there exist 7909 // candidate operator functions of the form 7910 // 7911 // VQ T& operator--(VQ T&); 7912 // T operator--(VQ T&, int); 7913 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7914 if (!HasArithmeticOrEnumeralCandidateType) 7915 return; 7916 7917 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 7918 const auto TypeOfT = ArithmeticTypes[Arith]; 7919 if (TypeOfT == S.Context.BoolTy) { 7920 if (Op == OO_MinusMinus) 7921 continue; 7922 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 7923 continue; 7924 } 7925 addPlusPlusMinusMinusStyleOverloads( 7926 TypeOfT, 7927 VisibleTypeConversionsQuals.hasVolatile(), 7928 VisibleTypeConversionsQuals.hasRestrict()); 7929 } 7930 } 7931 7932 // C++ [over.built]p5: 7933 // 7934 // For every pair (T, VQ), where T is a cv-qualified or 7935 // cv-unqualified object type, and VQ is either volatile or 7936 // empty, there exist candidate operator functions of the form 7937 // 7938 // T*VQ& operator++(T*VQ&); 7939 // T*VQ& operator--(T*VQ&); 7940 // T* operator++(T*VQ&, int); 7941 // T* operator--(T*VQ&, int); 7942 void addPlusPlusMinusMinusPointerOverloads() { 7943 for (BuiltinCandidateTypeSet::iterator 7944 Ptr = CandidateTypes[0].pointer_begin(), 7945 PtrEnd = CandidateTypes[0].pointer_end(); 7946 Ptr != PtrEnd; ++Ptr) { 7947 // Skip pointer types that aren't pointers to object types. 7948 if (!(*Ptr)->getPointeeType()->isObjectType()) 7949 continue; 7950 7951 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7952 (!(*Ptr).isVolatileQualified() && 7953 VisibleTypeConversionsQuals.hasVolatile()), 7954 (!(*Ptr).isRestrictQualified() && 7955 VisibleTypeConversionsQuals.hasRestrict())); 7956 } 7957 } 7958 7959 // C++ [over.built]p6: 7960 // For every cv-qualified or cv-unqualified object type T, there 7961 // exist candidate operator functions of the form 7962 // 7963 // T& operator*(T*); 7964 // 7965 // C++ [over.built]p7: 7966 // For every function type T that does not have cv-qualifiers or a 7967 // ref-qualifier, there exist candidate operator functions of the form 7968 // T& operator*(T*); 7969 void addUnaryStarPointerOverloads() { 7970 for (BuiltinCandidateTypeSet::iterator 7971 Ptr = CandidateTypes[0].pointer_begin(), 7972 PtrEnd = CandidateTypes[0].pointer_end(); 7973 Ptr != PtrEnd; ++Ptr) { 7974 QualType ParamTy = *Ptr; 7975 QualType PointeeTy = ParamTy->getPointeeType(); 7976 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7977 continue; 7978 7979 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7980 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 7981 continue; 7982 7983 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7984 } 7985 } 7986 7987 // C++ [over.built]p9: 7988 // For every promoted arithmetic type T, there exist candidate 7989 // operator functions of the form 7990 // 7991 // T operator+(T); 7992 // T operator-(T); 7993 void addUnaryPlusOrMinusArithmeticOverloads() { 7994 if (!HasArithmeticOrEnumeralCandidateType) 7995 return; 7996 7997 for (unsigned Arith = FirstPromotedArithmeticType; 7998 Arith < LastPromotedArithmeticType; ++Arith) { 7999 QualType ArithTy = ArithmeticTypes[Arith]; 8000 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8001 } 8002 8003 // Extension: We also add these operators for vector types. 8004 for (BuiltinCandidateTypeSet::iterator 8005 Vec = CandidateTypes[0].vector_begin(), 8006 VecEnd = CandidateTypes[0].vector_end(); 8007 Vec != VecEnd; ++Vec) { 8008 QualType VecTy = *Vec; 8009 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8010 } 8011 } 8012 8013 // C++ [over.built]p8: 8014 // For every type T, there exist candidate operator functions of 8015 // the form 8016 // 8017 // T* operator+(T*); 8018 void addUnaryPlusPointerOverloads() { 8019 for (BuiltinCandidateTypeSet::iterator 8020 Ptr = CandidateTypes[0].pointer_begin(), 8021 PtrEnd = CandidateTypes[0].pointer_end(); 8022 Ptr != PtrEnd; ++Ptr) { 8023 QualType ParamTy = *Ptr; 8024 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8025 } 8026 } 8027 8028 // C++ [over.built]p10: 8029 // For every promoted integral type T, there exist candidate 8030 // operator functions of the form 8031 // 8032 // T operator~(T); 8033 void addUnaryTildePromotedIntegralOverloads() { 8034 if (!HasArithmeticOrEnumeralCandidateType) 8035 return; 8036 8037 for (unsigned Int = FirstPromotedIntegralType; 8038 Int < LastPromotedIntegralType; ++Int) { 8039 QualType IntTy = ArithmeticTypes[Int]; 8040 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8041 } 8042 8043 // Extension: We also add this operator for vector types. 8044 for (BuiltinCandidateTypeSet::iterator 8045 Vec = CandidateTypes[0].vector_begin(), 8046 VecEnd = CandidateTypes[0].vector_end(); 8047 Vec != VecEnd; ++Vec) { 8048 QualType VecTy = *Vec; 8049 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8050 } 8051 } 8052 8053 // C++ [over.match.oper]p16: 8054 // For every pointer to member type T or type std::nullptr_t, there 8055 // exist candidate operator functions of the form 8056 // 8057 // bool operator==(T,T); 8058 // bool operator!=(T,T); 8059 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8060 /// Set of (canonical) types that we've already handled. 8061 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8062 8063 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8064 for (BuiltinCandidateTypeSet::iterator 8065 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8066 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8067 MemPtr != MemPtrEnd; 8068 ++MemPtr) { 8069 // Don't add the same builtin candidate twice. 8070 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8071 continue; 8072 8073 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8074 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8075 } 8076 8077 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8078 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8079 if (AddedTypes.insert(NullPtrTy).second) { 8080 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8081 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8082 } 8083 } 8084 } 8085 } 8086 8087 // C++ [over.built]p15: 8088 // 8089 // For every T, where T is an enumeration type or a pointer type, 8090 // there exist candidate operator functions of the form 8091 // 8092 // bool operator<(T, T); 8093 // bool operator>(T, T); 8094 // bool operator<=(T, T); 8095 // bool operator>=(T, T); 8096 // bool operator==(T, T); 8097 // bool operator!=(T, T); 8098 // R operator<=>(T, T) 8099 void addGenericBinaryPointerOrEnumeralOverloads() { 8100 // C++ [over.match.oper]p3: 8101 // [...]the built-in candidates include all of the candidate operator 8102 // functions defined in 13.6 that, compared to the given operator, [...] 8103 // do not have the same parameter-type-list as any non-template non-member 8104 // candidate. 8105 // 8106 // Note that in practice, this only affects enumeration types because there 8107 // aren't any built-in candidates of record type, and a user-defined operator 8108 // must have an operand of record or enumeration type. Also, the only other 8109 // overloaded operator with enumeration arguments, operator=, 8110 // cannot be overloaded for enumeration types, so this is the only place 8111 // where we must suppress candidates like this. 8112 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8113 UserDefinedBinaryOperators; 8114 8115 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8116 if (CandidateTypes[ArgIdx].enumeration_begin() != 8117 CandidateTypes[ArgIdx].enumeration_end()) { 8118 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8119 CEnd = CandidateSet.end(); 8120 C != CEnd; ++C) { 8121 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8122 continue; 8123 8124 if (C->Function->isFunctionTemplateSpecialization()) 8125 continue; 8126 8127 QualType FirstParamType = 8128 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 8129 QualType SecondParamType = 8130 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 8131 8132 // Skip if either parameter isn't of enumeral type. 8133 if (!FirstParamType->isEnumeralType() || 8134 !SecondParamType->isEnumeralType()) 8135 continue; 8136 8137 // Add this operator to the set of known user-defined operators. 8138 UserDefinedBinaryOperators.insert( 8139 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8140 S.Context.getCanonicalType(SecondParamType))); 8141 } 8142 } 8143 } 8144 8145 /// Set of (canonical) types that we've already handled. 8146 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8147 8148 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8149 for (BuiltinCandidateTypeSet::iterator 8150 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8151 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8152 Ptr != PtrEnd; ++Ptr) { 8153 // Don't add the same builtin candidate twice. 8154 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8155 continue; 8156 8157 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8158 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8159 } 8160 for (BuiltinCandidateTypeSet::iterator 8161 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8162 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8163 Enum != EnumEnd; ++Enum) { 8164 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8165 8166 // Don't add the same builtin candidate twice, or if a user defined 8167 // candidate exists. 8168 if (!AddedTypes.insert(CanonType).second || 8169 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8170 CanonType))) 8171 continue; 8172 QualType ParamTypes[2] = { *Enum, *Enum }; 8173 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8174 } 8175 } 8176 } 8177 8178 // C++ [over.built]p13: 8179 // 8180 // For every cv-qualified or cv-unqualified object type T 8181 // there exist candidate operator functions of the form 8182 // 8183 // T* operator+(T*, ptrdiff_t); 8184 // T& operator[](T*, ptrdiff_t); [BELOW] 8185 // T* operator-(T*, ptrdiff_t); 8186 // T* operator+(ptrdiff_t, T*); 8187 // T& operator[](ptrdiff_t, T*); [BELOW] 8188 // 8189 // C++ [over.built]p14: 8190 // 8191 // For every T, where T is a pointer to object type, there 8192 // exist candidate operator functions of the form 8193 // 8194 // ptrdiff_t operator-(T, T); 8195 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8196 /// Set of (canonical) types that we've already handled. 8197 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8198 8199 for (int Arg = 0; Arg < 2; ++Arg) { 8200 QualType AsymmetricParamTypes[2] = { 8201 S.Context.getPointerDiffType(), 8202 S.Context.getPointerDiffType(), 8203 }; 8204 for (BuiltinCandidateTypeSet::iterator 8205 Ptr = CandidateTypes[Arg].pointer_begin(), 8206 PtrEnd = CandidateTypes[Arg].pointer_end(); 8207 Ptr != PtrEnd; ++Ptr) { 8208 QualType PointeeTy = (*Ptr)->getPointeeType(); 8209 if (!PointeeTy->isObjectType()) 8210 continue; 8211 8212 AsymmetricParamTypes[Arg] = *Ptr; 8213 if (Arg == 0 || Op == OO_Plus) { 8214 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8215 // T* operator+(ptrdiff_t, T*); 8216 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8217 } 8218 if (Op == OO_Minus) { 8219 // ptrdiff_t operator-(T, T); 8220 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8221 continue; 8222 8223 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8224 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8225 } 8226 } 8227 } 8228 } 8229 8230 // C++ [over.built]p12: 8231 // 8232 // For every pair of promoted arithmetic types L and R, there 8233 // exist candidate operator functions of the form 8234 // 8235 // LR operator*(L, R); 8236 // LR operator/(L, R); 8237 // LR operator+(L, R); 8238 // LR operator-(L, R); 8239 // bool operator<(L, R); 8240 // bool operator>(L, R); 8241 // bool operator<=(L, R); 8242 // bool operator>=(L, R); 8243 // bool operator==(L, R); 8244 // bool operator!=(L, R); 8245 // 8246 // where LR is the result of the usual arithmetic conversions 8247 // between types L and R. 8248 // 8249 // C++ [over.built]p24: 8250 // 8251 // For every pair of promoted arithmetic types L and R, there exist 8252 // candidate operator functions of the form 8253 // 8254 // LR operator?(bool, L, R); 8255 // 8256 // where LR is the result of the usual arithmetic conversions 8257 // between types L and R. 8258 // Our candidates ignore the first parameter. 8259 void addGenericBinaryArithmeticOverloads() { 8260 if (!HasArithmeticOrEnumeralCandidateType) 8261 return; 8262 8263 for (unsigned Left = FirstPromotedArithmeticType; 8264 Left < LastPromotedArithmeticType; ++Left) { 8265 for (unsigned Right = FirstPromotedArithmeticType; 8266 Right < LastPromotedArithmeticType; ++Right) { 8267 QualType LandR[2] = { ArithmeticTypes[Left], 8268 ArithmeticTypes[Right] }; 8269 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8270 } 8271 } 8272 8273 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8274 // conditional operator for vector types. 8275 for (BuiltinCandidateTypeSet::iterator 8276 Vec1 = CandidateTypes[0].vector_begin(), 8277 Vec1End = CandidateTypes[0].vector_end(); 8278 Vec1 != Vec1End; ++Vec1) { 8279 for (BuiltinCandidateTypeSet::iterator 8280 Vec2 = CandidateTypes[1].vector_begin(), 8281 Vec2End = CandidateTypes[1].vector_end(); 8282 Vec2 != Vec2End; ++Vec2) { 8283 QualType LandR[2] = { *Vec1, *Vec2 }; 8284 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8285 } 8286 } 8287 } 8288 8289 // C++2a [over.built]p14: 8290 // 8291 // For every integral type T there exists a candidate operator function 8292 // of the form 8293 // 8294 // std::strong_ordering operator<=>(T, T) 8295 // 8296 // C++2a [over.built]p15: 8297 // 8298 // For every pair of floating-point types L and R, there exists a candidate 8299 // operator function of the form 8300 // 8301 // std::partial_ordering operator<=>(L, R); 8302 // 8303 // FIXME: The current specification for integral types doesn't play nice with 8304 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8305 // comparisons. Under the current spec this can lead to ambiguity during 8306 // overload resolution. For example: 8307 // 8308 // enum A : int {a}; 8309 // auto x = (a <=> (long)42); 8310 // 8311 // error: call is ambiguous for arguments 'A' and 'long'. 8312 // note: candidate operator<=>(int, int) 8313 // note: candidate operator<=>(long, long) 8314 // 8315 // To avoid this error, this function deviates from the specification and adds 8316 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8317 // arithmetic types (the same as the generic relational overloads). 8318 // 8319 // For now this function acts as a placeholder. 8320 void addThreeWayArithmeticOverloads() { 8321 addGenericBinaryArithmeticOverloads(); 8322 } 8323 8324 // C++ [over.built]p17: 8325 // 8326 // For every pair of promoted integral types L and R, there 8327 // exist candidate operator functions of the form 8328 // 8329 // LR operator%(L, R); 8330 // LR operator&(L, R); 8331 // LR operator^(L, R); 8332 // LR operator|(L, R); 8333 // L operator<<(L, R); 8334 // L operator>>(L, R); 8335 // 8336 // where LR is the result of the usual arithmetic conversions 8337 // between types L and R. 8338 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8339 if (!HasArithmeticOrEnumeralCandidateType) 8340 return; 8341 8342 for (unsigned Left = FirstPromotedIntegralType; 8343 Left < LastPromotedIntegralType; ++Left) { 8344 for (unsigned Right = FirstPromotedIntegralType; 8345 Right < LastPromotedIntegralType; ++Right) { 8346 QualType LandR[2] = { ArithmeticTypes[Left], 8347 ArithmeticTypes[Right] }; 8348 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8349 } 8350 } 8351 } 8352 8353 // C++ [over.built]p20: 8354 // 8355 // For every pair (T, VQ), where T is an enumeration or 8356 // pointer to member type and VQ is either volatile or 8357 // empty, there exist candidate operator functions of the form 8358 // 8359 // VQ T& operator=(VQ T&, T); 8360 void addAssignmentMemberPointerOrEnumeralOverloads() { 8361 /// Set of (canonical) types that we've already handled. 8362 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8363 8364 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8365 for (BuiltinCandidateTypeSet::iterator 8366 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8367 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8368 Enum != EnumEnd; ++Enum) { 8369 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8370 continue; 8371 8372 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8373 } 8374 8375 for (BuiltinCandidateTypeSet::iterator 8376 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8377 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8378 MemPtr != MemPtrEnd; ++MemPtr) { 8379 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8380 continue; 8381 8382 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8383 } 8384 } 8385 } 8386 8387 // C++ [over.built]p19: 8388 // 8389 // For every pair (T, VQ), where T is any type and VQ is either 8390 // volatile or empty, there exist candidate operator functions 8391 // of the form 8392 // 8393 // T*VQ& operator=(T*VQ&, T*); 8394 // 8395 // C++ [over.built]p21: 8396 // 8397 // For every pair (T, VQ), where T is a cv-qualified or 8398 // cv-unqualified object type and VQ is either volatile or 8399 // empty, there exist candidate operator functions of the form 8400 // 8401 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8402 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8403 void addAssignmentPointerOverloads(bool isEqualOp) { 8404 /// Set of (canonical) types that we've already handled. 8405 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8406 8407 for (BuiltinCandidateTypeSet::iterator 8408 Ptr = CandidateTypes[0].pointer_begin(), 8409 PtrEnd = CandidateTypes[0].pointer_end(); 8410 Ptr != PtrEnd; ++Ptr) { 8411 // If this is operator=, keep track of the builtin candidates we added. 8412 if (isEqualOp) 8413 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8414 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8415 continue; 8416 8417 // non-volatile version 8418 QualType ParamTypes[2] = { 8419 S.Context.getLValueReferenceType(*Ptr), 8420 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8421 }; 8422 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8423 /*IsAssigmentOperator=*/ isEqualOp); 8424 8425 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8426 VisibleTypeConversionsQuals.hasVolatile(); 8427 if (NeedVolatile) { 8428 // volatile version 8429 ParamTypes[0] = 8430 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8431 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8432 /*IsAssigmentOperator=*/isEqualOp); 8433 } 8434 8435 if (!(*Ptr).isRestrictQualified() && 8436 VisibleTypeConversionsQuals.hasRestrict()) { 8437 // restrict version 8438 ParamTypes[0] 8439 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8440 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8441 /*IsAssigmentOperator=*/isEqualOp); 8442 8443 if (NeedVolatile) { 8444 // volatile restrict version 8445 ParamTypes[0] 8446 = S.Context.getLValueReferenceType( 8447 S.Context.getCVRQualifiedType(*Ptr, 8448 (Qualifiers::Volatile | 8449 Qualifiers::Restrict))); 8450 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8451 /*IsAssigmentOperator=*/isEqualOp); 8452 } 8453 } 8454 } 8455 8456 if (isEqualOp) { 8457 for (BuiltinCandidateTypeSet::iterator 8458 Ptr = CandidateTypes[1].pointer_begin(), 8459 PtrEnd = CandidateTypes[1].pointer_end(); 8460 Ptr != PtrEnd; ++Ptr) { 8461 // Make sure we don't add the same candidate twice. 8462 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8463 continue; 8464 8465 QualType ParamTypes[2] = { 8466 S.Context.getLValueReferenceType(*Ptr), 8467 *Ptr, 8468 }; 8469 8470 // non-volatile version 8471 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8472 /*IsAssigmentOperator=*/true); 8473 8474 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8475 VisibleTypeConversionsQuals.hasVolatile(); 8476 if (NeedVolatile) { 8477 // volatile version 8478 ParamTypes[0] = 8479 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8480 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8481 /*IsAssigmentOperator=*/true); 8482 } 8483 8484 if (!(*Ptr).isRestrictQualified() && 8485 VisibleTypeConversionsQuals.hasRestrict()) { 8486 // restrict version 8487 ParamTypes[0] 8488 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8489 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8490 /*IsAssigmentOperator=*/true); 8491 8492 if (NeedVolatile) { 8493 // volatile restrict version 8494 ParamTypes[0] 8495 = S.Context.getLValueReferenceType( 8496 S.Context.getCVRQualifiedType(*Ptr, 8497 (Qualifiers::Volatile | 8498 Qualifiers::Restrict))); 8499 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8500 /*IsAssigmentOperator=*/true); 8501 } 8502 } 8503 } 8504 } 8505 } 8506 8507 // C++ [over.built]p18: 8508 // 8509 // For every triple (L, VQ, R), where L is an arithmetic type, 8510 // VQ is either volatile or empty, and R is a promoted 8511 // arithmetic type, there exist candidate operator functions of 8512 // the form 8513 // 8514 // VQ L& operator=(VQ L&, R); 8515 // VQ L& operator*=(VQ L&, R); 8516 // VQ L& operator/=(VQ L&, R); 8517 // VQ L& operator+=(VQ L&, R); 8518 // VQ L& operator-=(VQ L&, R); 8519 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8520 if (!HasArithmeticOrEnumeralCandidateType) 8521 return; 8522 8523 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8524 for (unsigned Right = FirstPromotedArithmeticType; 8525 Right < LastPromotedArithmeticType; ++Right) { 8526 QualType ParamTypes[2]; 8527 ParamTypes[1] = ArithmeticTypes[Right]; 8528 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8529 S, ArithmeticTypes[Left], Args[0]); 8530 // Add this built-in operator as a candidate (VQ is empty). 8531 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8532 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8533 /*IsAssigmentOperator=*/isEqualOp); 8534 8535 // Add this built-in operator as a candidate (VQ is 'volatile'). 8536 if (VisibleTypeConversionsQuals.hasVolatile()) { 8537 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8538 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8539 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8540 /*IsAssigmentOperator=*/isEqualOp); 8541 } 8542 } 8543 } 8544 8545 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8546 for (BuiltinCandidateTypeSet::iterator 8547 Vec1 = CandidateTypes[0].vector_begin(), 8548 Vec1End = CandidateTypes[0].vector_end(); 8549 Vec1 != Vec1End; ++Vec1) { 8550 for (BuiltinCandidateTypeSet::iterator 8551 Vec2 = CandidateTypes[1].vector_begin(), 8552 Vec2End = CandidateTypes[1].vector_end(); 8553 Vec2 != Vec2End; ++Vec2) { 8554 QualType ParamTypes[2]; 8555 ParamTypes[1] = *Vec2; 8556 // Add this built-in operator as a candidate (VQ is empty). 8557 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8558 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8559 /*IsAssigmentOperator=*/isEqualOp); 8560 8561 // Add this built-in operator as a candidate (VQ is 'volatile'). 8562 if (VisibleTypeConversionsQuals.hasVolatile()) { 8563 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8564 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8565 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8566 /*IsAssigmentOperator=*/isEqualOp); 8567 } 8568 } 8569 } 8570 } 8571 8572 // C++ [over.built]p22: 8573 // 8574 // For every triple (L, VQ, R), where L is an integral type, VQ 8575 // is either volatile or empty, and R is a promoted integral 8576 // type, there exist candidate operator functions of the form 8577 // 8578 // VQ L& operator%=(VQ L&, R); 8579 // VQ L& operator<<=(VQ L&, R); 8580 // VQ L& operator>>=(VQ L&, R); 8581 // VQ L& operator&=(VQ L&, R); 8582 // VQ L& operator^=(VQ L&, R); 8583 // VQ L& operator|=(VQ L&, R); 8584 void addAssignmentIntegralOverloads() { 8585 if (!HasArithmeticOrEnumeralCandidateType) 8586 return; 8587 8588 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8589 for (unsigned Right = FirstPromotedIntegralType; 8590 Right < LastPromotedIntegralType; ++Right) { 8591 QualType ParamTypes[2]; 8592 ParamTypes[1] = ArithmeticTypes[Right]; 8593 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8594 S, ArithmeticTypes[Left], Args[0]); 8595 // Add this built-in operator as a candidate (VQ is empty). 8596 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8597 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8598 if (VisibleTypeConversionsQuals.hasVolatile()) { 8599 // Add this built-in operator as a candidate (VQ is 'volatile'). 8600 ParamTypes[0] = LeftBaseTy; 8601 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8602 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8603 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8604 } 8605 } 8606 } 8607 } 8608 8609 // C++ [over.operator]p23: 8610 // 8611 // There also exist candidate operator functions of the form 8612 // 8613 // bool operator!(bool); 8614 // bool operator&&(bool, bool); 8615 // bool operator||(bool, bool); 8616 void addExclaimOverload() { 8617 QualType ParamTy = S.Context.BoolTy; 8618 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8619 /*IsAssignmentOperator=*/false, 8620 /*NumContextualBoolArguments=*/1); 8621 } 8622 void addAmpAmpOrPipePipeOverload() { 8623 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8624 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8625 /*IsAssignmentOperator=*/false, 8626 /*NumContextualBoolArguments=*/2); 8627 } 8628 8629 // C++ [over.built]p13: 8630 // 8631 // For every cv-qualified or cv-unqualified object type T there 8632 // exist candidate operator functions of the form 8633 // 8634 // T* operator+(T*, ptrdiff_t); [ABOVE] 8635 // T& operator[](T*, ptrdiff_t); 8636 // T* operator-(T*, ptrdiff_t); [ABOVE] 8637 // T* operator+(ptrdiff_t, T*); [ABOVE] 8638 // T& operator[](ptrdiff_t, T*); 8639 void addSubscriptOverloads() { 8640 for (BuiltinCandidateTypeSet::iterator 8641 Ptr = CandidateTypes[0].pointer_begin(), 8642 PtrEnd = CandidateTypes[0].pointer_end(); 8643 Ptr != PtrEnd; ++Ptr) { 8644 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8645 QualType PointeeType = (*Ptr)->getPointeeType(); 8646 if (!PointeeType->isObjectType()) 8647 continue; 8648 8649 // T& operator[](T*, ptrdiff_t) 8650 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8651 } 8652 8653 for (BuiltinCandidateTypeSet::iterator 8654 Ptr = CandidateTypes[1].pointer_begin(), 8655 PtrEnd = CandidateTypes[1].pointer_end(); 8656 Ptr != PtrEnd; ++Ptr) { 8657 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8658 QualType PointeeType = (*Ptr)->getPointeeType(); 8659 if (!PointeeType->isObjectType()) 8660 continue; 8661 8662 // T& operator[](ptrdiff_t, T*) 8663 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8664 } 8665 } 8666 8667 // C++ [over.built]p11: 8668 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8669 // C1 is the same type as C2 or is a derived class of C2, T is an object 8670 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8671 // there exist candidate operator functions of the form 8672 // 8673 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8674 // 8675 // where CV12 is the union of CV1 and CV2. 8676 void addArrowStarOverloads() { 8677 for (BuiltinCandidateTypeSet::iterator 8678 Ptr = CandidateTypes[0].pointer_begin(), 8679 PtrEnd = CandidateTypes[0].pointer_end(); 8680 Ptr != PtrEnd; ++Ptr) { 8681 QualType C1Ty = (*Ptr); 8682 QualType C1; 8683 QualifierCollector Q1; 8684 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8685 if (!isa<RecordType>(C1)) 8686 continue; 8687 // heuristic to reduce number of builtin candidates in the set. 8688 // Add volatile/restrict version only if there are conversions to a 8689 // volatile/restrict type. 8690 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8691 continue; 8692 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8693 continue; 8694 for (BuiltinCandidateTypeSet::iterator 8695 MemPtr = CandidateTypes[1].member_pointer_begin(), 8696 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8697 MemPtr != MemPtrEnd; ++MemPtr) { 8698 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8699 QualType C2 = QualType(mptr->getClass(), 0); 8700 C2 = C2.getUnqualifiedType(); 8701 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8702 break; 8703 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8704 // build CV12 T& 8705 QualType T = mptr->getPointeeType(); 8706 if (!VisibleTypeConversionsQuals.hasVolatile() && 8707 T.isVolatileQualified()) 8708 continue; 8709 if (!VisibleTypeConversionsQuals.hasRestrict() && 8710 T.isRestrictQualified()) 8711 continue; 8712 T = Q1.apply(S.Context, T); 8713 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8714 } 8715 } 8716 } 8717 8718 // Note that we don't consider the first argument, since it has been 8719 // contextually converted to bool long ago. The candidates below are 8720 // therefore added as binary. 8721 // 8722 // C++ [over.built]p25: 8723 // For every type T, where T is a pointer, pointer-to-member, or scoped 8724 // enumeration type, there exist candidate operator functions of the form 8725 // 8726 // T operator?(bool, T, T); 8727 // 8728 void addConditionalOperatorOverloads() { 8729 /// Set of (canonical) types that we've already handled. 8730 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8731 8732 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8733 for (BuiltinCandidateTypeSet::iterator 8734 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8735 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8736 Ptr != PtrEnd; ++Ptr) { 8737 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8738 continue; 8739 8740 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8741 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8742 } 8743 8744 for (BuiltinCandidateTypeSet::iterator 8745 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8746 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8747 MemPtr != MemPtrEnd; ++MemPtr) { 8748 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8749 continue; 8750 8751 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8752 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8753 } 8754 8755 if (S.getLangOpts().CPlusPlus11) { 8756 for (BuiltinCandidateTypeSet::iterator 8757 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8758 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8759 Enum != EnumEnd; ++Enum) { 8760 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8761 continue; 8762 8763 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8764 continue; 8765 8766 QualType ParamTypes[2] = { *Enum, *Enum }; 8767 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8768 } 8769 } 8770 } 8771 } 8772 }; 8773 8774 } // end anonymous namespace 8775 8776 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8777 /// operator overloads to the candidate set (C++ [over.built]), based 8778 /// on the operator @p Op and the arguments given. For example, if the 8779 /// operator is a binary '+', this routine might add "int 8780 /// operator+(int, int)" to cover integer addition. 8781 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8782 SourceLocation OpLoc, 8783 ArrayRef<Expr *> Args, 8784 OverloadCandidateSet &CandidateSet) { 8785 // Find all of the types that the arguments can convert to, but only 8786 // if the operator we're looking at has built-in operator candidates 8787 // that make use of these types. Also record whether we encounter non-record 8788 // candidate types or either arithmetic or enumeral candidate types. 8789 Qualifiers VisibleTypeConversionsQuals; 8790 VisibleTypeConversionsQuals.addConst(); 8791 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8792 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8793 8794 bool HasNonRecordCandidateType = false; 8795 bool HasArithmeticOrEnumeralCandidateType = false; 8796 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8797 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8798 CandidateTypes.emplace_back(*this); 8799 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8800 OpLoc, 8801 true, 8802 (Op == OO_Exclaim || 8803 Op == OO_AmpAmp || 8804 Op == OO_PipePipe), 8805 VisibleTypeConversionsQuals); 8806 HasNonRecordCandidateType = HasNonRecordCandidateType || 8807 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8808 HasArithmeticOrEnumeralCandidateType = 8809 HasArithmeticOrEnumeralCandidateType || 8810 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8811 } 8812 8813 // Exit early when no non-record types have been added to the candidate set 8814 // for any of the arguments to the operator. 8815 // 8816 // We can't exit early for !, ||, or &&, since there we have always have 8817 // 'bool' overloads. 8818 if (!HasNonRecordCandidateType && 8819 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8820 return; 8821 8822 // Setup an object to manage the common state for building overloads. 8823 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8824 VisibleTypeConversionsQuals, 8825 HasArithmeticOrEnumeralCandidateType, 8826 CandidateTypes, CandidateSet); 8827 8828 // Dispatch over the operation to add in only those overloads which apply. 8829 switch (Op) { 8830 case OO_None: 8831 case NUM_OVERLOADED_OPERATORS: 8832 llvm_unreachable("Expected an overloaded operator"); 8833 8834 case OO_New: 8835 case OO_Delete: 8836 case OO_Array_New: 8837 case OO_Array_Delete: 8838 case OO_Call: 8839 llvm_unreachable( 8840 "Special operators don't use AddBuiltinOperatorCandidates"); 8841 8842 case OO_Comma: 8843 case OO_Arrow: 8844 case OO_Coawait: 8845 // C++ [over.match.oper]p3: 8846 // -- For the operator ',', the unary operator '&', the 8847 // operator '->', or the operator 'co_await', the 8848 // built-in candidates set is empty. 8849 break; 8850 8851 case OO_Plus: // '+' is either unary or binary 8852 if (Args.size() == 1) 8853 OpBuilder.addUnaryPlusPointerOverloads(); 8854 LLVM_FALLTHROUGH; 8855 8856 case OO_Minus: // '-' is either unary or binary 8857 if (Args.size() == 1) { 8858 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8859 } else { 8860 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8861 OpBuilder.addGenericBinaryArithmeticOverloads(); 8862 } 8863 break; 8864 8865 case OO_Star: // '*' is either unary or binary 8866 if (Args.size() == 1) 8867 OpBuilder.addUnaryStarPointerOverloads(); 8868 else 8869 OpBuilder.addGenericBinaryArithmeticOverloads(); 8870 break; 8871 8872 case OO_Slash: 8873 OpBuilder.addGenericBinaryArithmeticOverloads(); 8874 break; 8875 8876 case OO_PlusPlus: 8877 case OO_MinusMinus: 8878 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8879 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8880 break; 8881 8882 case OO_EqualEqual: 8883 case OO_ExclaimEqual: 8884 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8885 LLVM_FALLTHROUGH; 8886 8887 case OO_Less: 8888 case OO_Greater: 8889 case OO_LessEqual: 8890 case OO_GreaterEqual: 8891 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8892 OpBuilder.addGenericBinaryArithmeticOverloads(); 8893 break; 8894 8895 case OO_Spaceship: 8896 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8897 OpBuilder.addThreeWayArithmeticOverloads(); 8898 break; 8899 8900 case OO_Percent: 8901 case OO_Caret: 8902 case OO_Pipe: 8903 case OO_LessLess: 8904 case OO_GreaterGreater: 8905 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8906 break; 8907 8908 case OO_Amp: // '&' is either unary or binary 8909 if (Args.size() == 1) 8910 // C++ [over.match.oper]p3: 8911 // -- For the operator ',', the unary operator '&', or the 8912 // operator '->', the built-in candidates set is empty. 8913 break; 8914 8915 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8916 break; 8917 8918 case OO_Tilde: 8919 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8920 break; 8921 8922 case OO_Equal: 8923 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8924 LLVM_FALLTHROUGH; 8925 8926 case OO_PlusEqual: 8927 case OO_MinusEqual: 8928 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8929 LLVM_FALLTHROUGH; 8930 8931 case OO_StarEqual: 8932 case OO_SlashEqual: 8933 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8934 break; 8935 8936 case OO_PercentEqual: 8937 case OO_LessLessEqual: 8938 case OO_GreaterGreaterEqual: 8939 case OO_AmpEqual: 8940 case OO_CaretEqual: 8941 case OO_PipeEqual: 8942 OpBuilder.addAssignmentIntegralOverloads(); 8943 break; 8944 8945 case OO_Exclaim: 8946 OpBuilder.addExclaimOverload(); 8947 break; 8948 8949 case OO_AmpAmp: 8950 case OO_PipePipe: 8951 OpBuilder.addAmpAmpOrPipePipeOverload(); 8952 break; 8953 8954 case OO_Subscript: 8955 OpBuilder.addSubscriptOverloads(); 8956 break; 8957 8958 case OO_ArrowStar: 8959 OpBuilder.addArrowStarOverloads(); 8960 break; 8961 8962 case OO_Conditional: 8963 OpBuilder.addConditionalOperatorOverloads(); 8964 OpBuilder.addGenericBinaryArithmeticOverloads(); 8965 break; 8966 } 8967 } 8968 8969 /// Add function candidates found via argument-dependent lookup 8970 /// to the set of overloading candidates. 8971 /// 8972 /// This routine performs argument-dependent name lookup based on the 8973 /// given function name (which may also be an operator name) and adds 8974 /// all of the overload candidates found by ADL to the overload 8975 /// candidate set (C++ [basic.lookup.argdep]). 8976 void 8977 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8978 SourceLocation Loc, 8979 ArrayRef<Expr *> Args, 8980 TemplateArgumentListInfo *ExplicitTemplateArgs, 8981 OverloadCandidateSet& CandidateSet, 8982 bool PartialOverloading) { 8983 ADLResult Fns; 8984 8985 // FIXME: This approach for uniquing ADL results (and removing 8986 // redundant candidates from the set) relies on pointer-equality, 8987 // which means we need to key off the canonical decl. However, 8988 // always going back to the canonical decl might not get us the 8989 // right set of default arguments. What default arguments are 8990 // we supposed to consider on ADL candidates, anyway? 8991 8992 // FIXME: Pass in the explicit template arguments? 8993 ArgumentDependentLookup(Name, Loc, Args, Fns); 8994 8995 // Erase all of the candidates we already knew about. 8996 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8997 CandEnd = CandidateSet.end(); 8998 Cand != CandEnd; ++Cand) 8999 if (Cand->Function) { 9000 Fns.erase(Cand->Function); 9001 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9002 Fns.erase(FunTmpl); 9003 } 9004 9005 // For each of the ADL candidates we found, add it to the overload 9006 // set. 9007 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9008 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9009 9010 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9011 if (ExplicitTemplateArgs) 9012 continue; 9013 9014 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, 9015 /*SupressUserConversions=*/false, PartialOverloading, 9016 /*AllowExplicit*/ true, 9017 /*AllowExplicitConversions*/ false, 9018 ADLCallKind::UsesADL); 9019 } else { 9020 AddTemplateOverloadCandidate( 9021 cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args, 9022 CandidateSet, 9023 /*SuppressUserConversions=*/false, PartialOverloading, 9024 /*AllowExplicit*/true, ADLCallKind::UsesADL); 9025 } 9026 } 9027 } 9028 9029 namespace { 9030 enum class Comparison { Equal, Better, Worse }; 9031 } 9032 9033 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9034 /// overload resolution. 9035 /// 9036 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9037 /// Cand1's first N enable_if attributes have precisely the same conditions as 9038 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9039 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9040 /// 9041 /// Note that you can have a pair of candidates such that Cand1's enable_if 9042 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9043 /// worse than Cand1's. 9044 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9045 const FunctionDecl *Cand2) { 9046 // Common case: One (or both) decls don't have enable_if attrs. 9047 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9048 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9049 if (!Cand1Attr || !Cand2Attr) { 9050 if (Cand1Attr == Cand2Attr) 9051 return Comparison::Equal; 9052 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9053 } 9054 9055 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9056 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9057 9058 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9059 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9060 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9061 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9062 9063 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9064 // has fewer enable_if attributes than Cand2, and vice versa. 9065 if (!Cand1A) 9066 return Comparison::Worse; 9067 if (!Cand2A) 9068 return Comparison::Better; 9069 9070 Cand1ID.clear(); 9071 Cand2ID.clear(); 9072 9073 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9074 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9075 if (Cand1ID != Cand2ID) 9076 return Comparison::Worse; 9077 } 9078 9079 return Comparison::Equal; 9080 } 9081 9082 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9083 const OverloadCandidate &Cand2) { 9084 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9085 !Cand2.Function->isMultiVersion()) 9086 return false; 9087 9088 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9089 // is obviously better. 9090 if (Cand1.Function->isInvalidDecl()) return false; 9091 if (Cand2.Function->isInvalidDecl()) return true; 9092 9093 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9094 // cpu_dispatch, else arbitrarily based on the identifiers. 9095 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9096 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9097 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9098 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9099 9100 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9101 return false; 9102 9103 if (Cand1CPUDisp && !Cand2CPUDisp) 9104 return true; 9105 if (Cand2CPUDisp && !Cand1CPUDisp) 9106 return false; 9107 9108 if (Cand1CPUSpec && Cand2CPUSpec) { 9109 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9110 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9111 9112 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9113 FirstDiff = std::mismatch( 9114 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9115 Cand2CPUSpec->cpus_begin(), 9116 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9117 return LHS->getName() == RHS->getName(); 9118 }); 9119 9120 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9121 "Two different cpu-specific versions should not have the same " 9122 "identifier list, otherwise they'd be the same decl!"); 9123 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9124 } 9125 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9126 } 9127 9128 /// isBetterOverloadCandidate - Determines whether the first overload 9129 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9130 bool clang::isBetterOverloadCandidate( 9131 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9132 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9133 // Define viable functions to be better candidates than non-viable 9134 // functions. 9135 if (!Cand2.Viable) 9136 return Cand1.Viable; 9137 else if (!Cand1.Viable) 9138 return false; 9139 9140 // C++ [over.match.best]p1: 9141 // 9142 // -- if F is a static member function, ICS1(F) is defined such 9143 // that ICS1(F) is neither better nor worse than ICS1(G) for 9144 // any function G, and, symmetrically, ICS1(G) is neither 9145 // better nor worse than ICS1(F). 9146 unsigned StartArg = 0; 9147 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9148 StartArg = 1; 9149 9150 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9151 // We don't allow incompatible pointer conversions in C++. 9152 if (!S.getLangOpts().CPlusPlus) 9153 return ICS.isStandard() && 9154 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9155 9156 // The only ill-formed conversion we allow in C++ is the string literal to 9157 // char* conversion, which is only considered ill-formed after C++11. 9158 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9159 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9160 }; 9161 9162 // Define functions that don't require ill-formed conversions for a given 9163 // argument to be better candidates than functions that do. 9164 unsigned NumArgs = Cand1.Conversions.size(); 9165 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9166 bool HasBetterConversion = false; 9167 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9168 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9169 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9170 if (Cand1Bad != Cand2Bad) { 9171 if (Cand1Bad) 9172 return false; 9173 HasBetterConversion = true; 9174 } 9175 } 9176 9177 if (HasBetterConversion) 9178 return true; 9179 9180 // C++ [over.match.best]p1: 9181 // A viable function F1 is defined to be a better function than another 9182 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9183 // conversion sequence than ICSi(F2), and then... 9184 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9185 switch (CompareImplicitConversionSequences(S, Loc, 9186 Cand1.Conversions[ArgIdx], 9187 Cand2.Conversions[ArgIdx])) { 9188 case ImplicitConversionSequence::Better: 9189 // Cand1 has a better conversion sequence. 9190 HasBetterConversion = true; 9191 break; 9192 9193 case ImplicitConversionSequence::Worse: 9194 // Cand1 can't be better than Cand2. 9195 return false; 9196 9197 case ImplicitConversionSequence::Indistinguishable: 9198 // Do nothing. 9199 break; 9200 } 9201 } 9202 9203 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9204 // ICSj(F2), or, if not that, 9205 if (HasBetterConversion) 9206 return true; 9207 9208 // -- the context is an initialization by user-defined conversion 9209 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9210 // from the return type of F1 to the destination type (i.e., 9211 // the type of the entity being initialized) is a better 9212 // conversion sequence than the standard conversion sequence 9213 // from the return type of F2 to the destination type. 9214 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9215 Cand1.Function && Cand2.Function && 9216 isa<CXXConversionDecl>(Cand1.Function) && 9217 isa<CXXConversionDecl>(Cand2.Function)) { 9218 // First check whether we prefer one of the conversion functions over the 9219 // other. This only distinguishes the results in non-standard, extension 9220 // cases such as the conversion from a lambda closure type to a function 9221 // pointer or block. 9222 ImplicitConversionSequence::CompareKind Result = 9223 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9224 if (Result == ImplicitConversionSequence::Indistinguishable) 9225 Result = CompareStandardConversionSequences(S, Loc, 9226 Cand1.FinalConversion, 9227 Cand2.FinalConversion); 9228 9229 if (Result != ImplicitConversionSequence::Indistinguishable) 9230 return Result == ImplicitConversionSequence::Better; 9231 9232 // FIXME: Compare kind of reference binding if conversion functions 9233 // convert to a reference type used in direct reference binding, per 9234 // C++14 [over.match.best]p1 section 2 bullet 3. 9235 } 9236 9237 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9238 // as combined with the resolution to CWG issue 243. 9239 // 9240 // When the context is initialization by constructor ([over.match.ctor] or 9241 // either phase of [over.match.list]), a constructor is preferred over 9242 // a conversion function. 9243 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9244 Cand1.Function && Cand2.Function && 9245 isa<CXXConstructorDecl>(Cand1.Function) != 9246 isa<CXXConstructorDecl>(Cand2.Function)) 9247 return isa<CXXConstructorDecl>(Cand1.Function); 9248 9249 // -- F1 is a non-template function and F2 is a function template 9250 // specialization, or, if not that, 9251 bool Cand1IsSpecialization = Cand1.Function && 9252 Cand1.Function->getPrimaryTemplate(); 9253 bool Cand2IsSpecialization = Cand2.Function && 9254 Cand2.Function->getPrimaryTemplate(); 9255 if (Cand1IsSpecialization != Cand2IsSpecialization) 9256 return Cand2IsSpecialization; 9257 9258 // -- F1 and F2 are function template specializations, and the function 9259 // template for F1 is more specialized than the template for F2 9260 // according to the partial ordering rules described in 14.5.5.2, or, 9261 // if not that, 9262 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9263 if (FunctionTemplateDecl *BetterTemplate 9264 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9265 Cand2.Function->getPrimaryTemplate(), 9266 Loc, 9267 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9268 : TPOC_Call, 9269 Cand1.ExplicitCallArguments, 9270 Cand2.ExplicitCallArguments)) 9271 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9272 } 9273 9274 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9275 // A derived-class constructor beats an (inherited) base class constructor. 9276 bool Cand1IsInherited = 9277 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9278 bool Cand2IsInherited = 9279 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9280 if (Cand1IsInherited != Cand2IsInherited) 9281 return Cand2IsInherited; 9282 else if (Cand1IsInherited) { 9283 assert(Cand2IsInherited); 9284 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9285 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9286 if (Cand1Class->isDerivedFrom(Cand2Class)) 9287 return true; 9288 if (Cand2Class->isDerivedFrom(Cand1Class)) 9289 return false; 9290 // Inherited from sibling base classes: still ambiguous. 9291 } 9292 9293 // Check C++17 tie-breakers for deduction guides. 9294 { 9295 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9296 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9297 if (Guide1 && Guide2) { 9298 // -- F1 is generated from a deduction-guide and F2 is not 9299 if (Guide1->isImplicit() != Guide2->isImplicit()) 9300 return Guide2->isImplicit(); 9301 9302 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9303 if (Guide1->isCopyDeductionCandidate()) 9304 return true; 9305 } 9306 } 9307 9308 // Check for enable_if value-based overload resolution. 9309 if (Cand1.Function && Cand2.Function) { 9310 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9311 if (Cmp != Comparison::Equal) 9312 return Cmp == Comparison::Better; 9313 } 9314 9315 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9316 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9317 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9318 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9319 } 9320 9321 bool HasPS1 = Cand1.Function != nullptr && 9322 functionHasPassObjectSizeParams(Cand1.Function); 9323 bool HasPS2 = Cand2.Function != nullptr && 9324 functionHasPassObjectSizeParams(Cand2.Function); 9325 if (HasPS1 != HasPS2 && HasPS1) 9326 return true; 9327 9328 return isBetterMultiversionCandidate(Cand1, Cand2); 9329 } 9330 9331 /// Determine whether two declarations are "equivalent" for the purposes of 9332 /// name lookup and overload resolution. This applies when the same internal/no 9333 /// linkage entity is defined by two modules (probably by textually including 9334 /// the same header). In such a case, we don't consider the declarations to 9335 /// declare the same entity, but we also don't want lookups with both 9336 /// declarations visible to be ambiguous in some cases (this happens when using 9337 /// a modularized libstdc++). 9338 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9339 const NamedDecl *B) { 9340 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9341 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9342 if (!VA || !VB) 9343 return false; 9344 9345 // The declarations must be declaring the same name as an internal linkage 9346 // entity in different modules. 9347 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9348 VB->getDeclContext()->getRedeclContext()) || 9349 getOwningModule(const_cast<ValueDecl *>(VA)) == 9350 getOwningModule(const_cast<ValueDecl *>(VB)) || 9351 VA->isExternallyVisible() || VB->isExternallyVisible()) 9352 return false; 9353 9354 // Check that the declarations appear to be equivalent. 9355 // 9356 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9357 // For constants and functions, we should check the initializer or body is 9358 // the same. For non-constant variables, we shouldn't allow it at all. 9359 if (Context.hasSameType(VA->getType(), VB->getType())) 9360 return true; 9361 9362 // Enum constants within unnamed enumerations will have different types, but 9363 // may still be similar enough to be interchangeable for our purposes. 9364 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9365 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9366 // Only handle anonymous enums. If the enumerations were named and 9367 // equivalent, they would have been merged to the same type. 9368 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9369 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9370 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9371 !Context.hasSameType(EnumA->getIntegerType(), 9372 EnumB->getIntegerType())) 9373 return false; 9374 // Allow this only if the value is the same for both enumerators. 9375 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9376 } 9377 } 9378 9379 // Nothing else is sufficiently similar. 9380 return false; 9381 } 9382 9383 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9384 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9385 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9386 9387 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9388 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9389 << !M << (M ? M->getFullModuleName() : ""); 9390 9391 for (auto *E : Equiv) { 9392 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9393 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9394 << !M << (M ? M->getFullModuleName() : ""); 9395 } 9396 } 9397 9398 /// Computes the best viable function (C++ 13.3.3) 9399 /// within an overload candidate set. 9400 /// 9401 /// \param Loc The location of the function name (or operator symbol) for 9402 /// which overload resolution occurs. 9403 /// 9404 /// \param Best If overload resolution was successful or found a deleted 9405 /// function, \p Best points to the candidate function found. 9406 /// 9407 /// \returns The result of overload resolution. 9408 OverloadingResult 9409 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9410 iterator &Best) { 9411 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9412 std::transform(begin(), end(), std::back_inserter(Candidates), 9413 [](OverloadCandidate &Cand) { return &Cand; }); 9414 9415 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9416 // are accepted by both clang and NVCC. However, during a particular 9417 // compilation mode only one call variant is viable. We need to 9418 // exclude non-viable overload candidates from consideration based 9419 // only on their host/device attributes. Specifically, if one 9420 // candidate call is WrongSide and the other is SameSide, we ignore 9421 // the WrongSide candidate. 9422 if (S.getLangOpts().CUDA) { 9423 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9424 bool ContainsSameSideCandidate = 9425 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9426 return Cand->Function && 9427 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9428 Sema::CFP_SameSide; 9429 }); 9430 if (ContainsSameSideCandidate) { 9431 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9432 return Cand->Function && 9433 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9434 Sema::CFP_WrongSide; 9435 }; 9436 llvm::erase_if(Candidates, IsWrongSideCandidate); 9437 } 9438 } 9439 9440 // Find the best viable function. 9441 Best = end(); 9442 for (auto *Cand : Candidates) 9443 if (Cand->Viable) 9444 if (Best == end() || 9445 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9446 Best = Cand; 9447 9448 // If we didn't find any viable functions, abort. 9449 if (Best == end()) 9450 return OR_No_Viable_Function; 9451 9452 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9453 9454 // Make sure that this function is better than every other viable 9455 // function. If not, we have an ambiguity. 9456 for (auto *Cand : Candidates) { 9457 if (Cand->Viable && Cand != Best && 9458 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { 9459 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9460 Cand->Function)) { 9461 EquivalentCands.push_back(Cand->Function); 9462 continue; 9463 } 9464 9465 Best = end(); 9466 return OR_Ambiguous; 9467 } 9468 } 9469 9470 // Best is the best viable function. 9471 if (Best->Function && Best->Function->isDeleted()) 9472 return OR_Deleted; 9473 9474 if (!EquivalentCands.empty()) 9475 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9476 EquivalentCands); 9477 9478 return OR_Success; 9479 } 9480 9481 namespace { 9482 9483 enum OverloadCandidateKind { 9484 oc_function, 9485 oc_method, 9486 oc_constructor, 9487 oc_implicit_default_constructor, 9488 oc_implicit_copy_constructor, 9489 oc_implicit_move_constructor, 9490 oc_implicit_copy_assignment, 9491 oc_implicit_move_assignment, 9492 oc_inherited_constructor 9493 }; 9494 9495 enum OverloadCandidateSelect { 9496 ocs_non_template, 9497 ocs_template, 9498 ocs_described_template, 9499 }; 9500 9501 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9502 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9503 std::string &Description) { 9504 9505 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9506 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9507 isTemplate = true; 9508 Description = S.getTemplateArgumentBindingsText( 9509 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9510 } 9511 9512 OverloadCandidateSelect Select = [&]() { 9513 if (!Description.empty()) 9514 return ocs_described_template; 9515 return isTemplate ? ocs_template : ocs_non_template; 9516 }(); 9517 9518 OverloadCandidateKind Kind = [&]() { 9519 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9520 if (!Ctor->isImplicit()) { 9521 if (isa<ConstructorUsingShadowDecl>(Found)) 9522 return oc_inherited_constructor; 9523 else 9524 return oc_constructor; 9525 } 9526 9527 if (Ctor->isDefaultConstructor()) 9528 return oc_implicit_default_constructor; 9529 9530 if (Ctor->isMoveConstructor()) 9531 return oc_implicit_move_constructor; 9532 9533 assert(Ctor->isCopyConstructor() && 9534 "unexpected sort of implicit constructor"); 9535 return oc_implicit_copy_constructor; 9536 } 9537 9538 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9539 // This actually gets spelled 'candidate function' for now, but 9540 // it doesn't hurt to split it out. 9541 if (!Meth->isImplicit()) 9542 return oc_method; 9543 9544 if (Meth->isMoveAssignmentOperator()) 9545 return oc_implicit_move_assignment; 9546 9547 if (Meth->isCopyAssignmentOperator()) 9548 return oc_implicit_copy_assignment; 9549 9550 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9551 return oc_method; 9552 } 9553 9554 return oc_function; 9555 }(); 9556 9557 return std::make_pair(Kind, Select); 9558 } 9559 9560 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9561 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9562 // set. 9563 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9564 S.Diag(FoundDecl->getLocation(), 9565 diag::note_ovl_candidate_inherited_constructor) 9566 << Shadow->getNominatedBaseClass(); 9567 } 9568 9569 } // end anonymous namespace 9570 9571 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9572 const FunctionDecl *FD) { 9573 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9574 bool AlwaysTrue; 9575 if (EnableIf->getCond()->isValueDependent() || 9576 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9577 return false; 9578 if (!AlwaysTrue) 9579 return false; 9580 } 9581 return true; 9582 } 9583 9584 /// Returns true if we can take the address of the function. 9585 /// 9586 /// \param Complain - If true, we'll emit a diagnostic 9587 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9588 /// we in overload resolution? 9589 /// \param Loc - The location of the statement we're complaining about. Ignored 9590 /// if we're not complaining, or if we're in overload resolution. 9591 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9592 bool Complain, 9593 bool InOverloadResolution, 9594 SourceLocation Loc) { 9595 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9596 if (Complain) { 9597 if (InOverloadResolution) 9598 S.Diag(FD->getBeginLoc(), 9599 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9600 else 9601 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9602 } 9603 return false; 9604 } 9605 9606 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9607 return P->hasAttr<PassObjectSizeAttr>(); 9608 }); 9609 if (I == FD->param_end()) 9610 return true; 9611 9612 if (Complain) { 9613 // Add one to ParamNo because it's user-facing 9614 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9615 if (InOverloadResolution) 9616 S.Diag(FD->getLocation(), 9617 diag::note_ovl_candidate_has_pass_object_size_params) 9618 << ParamNo; 9619 else 9620 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9621 << FD << ParamNo; 9622 } 9623 return false; 9624 } 9625 9626 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9627 const FunctionDecl *FD) { 9628 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9629 /*InOverloadResolution=*/true, 9630 /*Loc=*/SourceLocation()); 9631 } 9632 9633 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9634 bool Complain, 9635 SourceLocation Loc) { 9636 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9637 /*InOverloadResolution=*/false, 9638 Loc); 9639 } 9640 9641 // Notes the location of an overload candidate. 9642 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9643 QualType DestType, bool TakingAddress) { 9644 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9645 return; 9646 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9647 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9648 return; 9649 9650 std::string FnDesc; 9651 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9652 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9653 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9654 << (unsigned)KSPair.first << (unsigned)KSPair.second 9655 << Fn << FnDesc; 9656 9657 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9658 Diag(Fn->getLocation(), PD); 9659 MaybeEmitInheritedConstructorNote(*this, Found); 9660 } 9661 9662 // Notes the location of all overload candidates designated through 9663 // OverloadedExpr 9664 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9665 bool TakingAddress) { 9666 assert(OverloadedExpr->getType() == Context.OverloadTy); 9667 9668 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9669 OverloadExpr *OvlExpr = Ovl.Expression; 9670 9671 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9672 IEnd = OvlExpr->decls_end(); 9673 I != IEnd; ++I) { 9674 if (FunctionTemplateDecl *FunTmpl = 9675 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9676 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9677 TakingAddress); 9678 } else if (FunctionDecl *Fun 9679 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9680 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9681 } 9682 } 9683 } 9684 9685 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9686 /// "lead" diagnostic; it will be given two arguments, the source and 9687 /// target types of the conversion. 9688 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9689 Sema &S, 9690 SourceLocation CaretLoc, 9691 const PartialDiagnostic &PDiag) const { 9692 S.Diag(CaretLoc, PDiag) 9693 << Ambiguous.getFromType() << Ambiguous.getToType(); 9694 // FIXME: The note limiting machinery is borrowed from 9695 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9696 // refactoring here. 9697 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9698 unsigned CandsShown = 0; 9699 AmbiguousConversionSequence::const_iterator I, E; 9700 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9701 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9702 break; 9703 ++CandsShown; 9704 S.NoteOverloadCandidate(I->first, I->second); 9705 } 9706 if (I != E) 9707 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9708 } 9709 9710 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9711 unsigned I, bool TakingCandidateAddress) { 9712 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9713 assert(Conv.isBad()); 9714 assert(Cand->Function && "for now, candidate must be a function"); 9715 FunctionDecl *Fn = Cand->Function; 9716 9717 // There's a conversion slot for the object argument if this is a 9718 // non-constructor method. Note that 'I' corresponds the 9719 // conversion-slot index. 9720 bool isObjectArgument = false; 9721 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9722 if (I == 0) 9723 isObjectArgument = true; 9724 else 9725 I--; 9726 } 9727 9728 std::string FnDesc; 9729 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9730 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9731 9732 Expr *FromExpr = Conv.Bad.FromExpr; 9733 QualType FromTy = Conv.Bad.getFromType(); 9734 QualType ToTy = Conv.Bad.getToType(); 9735 9736 if (FromTy == S.Context.OverloadTy) { 9737 assert(FromExpr && "overload set argument came from implicit argument?"); 9738 Expr *E = FromExpr->IgnoreParens(); 9739 if (isa<UnaryOperator>(E)) 9740 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9741 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9742 9743 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9744 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9745 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9746 << Name << I + 1; 9747 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9748 return; 9749 } 9750 9751 // Do some hand-waving analysis to see if the non-viability is due 9752 // to a qualifier mismatch. 9753 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9754 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9755 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9756 CToTy = RT->getPointeeType(); 9757 else { 9758 // TODO: detect and diagnose the full richness of const mismatches. 9759 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9760 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9761 CFromTy = FromPT->getPointeeType(); 9762 CToTy = ToPT->getPointeeType(); 9763 } 9764 } 9765 9766 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9767 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9768 Qualifiers FromQs = CFromTy.getQualifiers(); 9769 Qualifiers ToQs = CToTy.getQualifiers(); 9770 9771 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9772 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9773 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9774 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9775 << ToTy << (unsigned)isObjectArgument << I + 1; 9776 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9777 return; 9778 } 9779 9780 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9781 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9782 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9783 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9784 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9785 << (unsigned)isObjectArgument << I + 1; 9786 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9787 return; 9788 } 9789 9790 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9791 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9792 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9793 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9794 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9795 << (unsigned)isObjectArgument << I + 1; 9796 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9797 return; 9798 } 9799 9800 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9801 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9802 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9803 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9804 << FromQs.hasUnaligned() << I + 1; 9805 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9806 return; 9807 } 9808 9809 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9810 assert(CVR && "unexpected qualifiers mismatch"); 9811 9812 if (isObjectArgument) { 9813 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9814 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9815 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9816 << (CVR - 1); 9817 } else { 9818 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9819 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9820 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9821 << (CVR - 1) << I + 1; 9822 } 9823 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9824 return; 9825 } 9826 9827 // Special diagnostic for failure to convert an initializer list, since 9828 // telling the user that it has type void is not useful. 9829 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9830 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9831 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9832 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9833 << ToTy << (unsigned)isObjectArgument << I + 1; 9834 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9835 return; 9836 } 9837 9838 // Diagnose references or pointers to incomplete types differently, 9839 // since it's far from impossible that the incompleteness triggered 9840 // the failure. 9841 QualType TempFromTy = FromTy.getNonReferenceType(); 9842 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9843 TempFromTy = PTy->getPointeeType(); 9844 if (TempFromTy->isIncompleteType()) { 9845 // Emit the generic diagnostic and, optionally, add the hints to it. 9846 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9847 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9848 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9849 << ToTy << (unsigned)isObjectArgument << I + 1 9850 << (unsigned)(Cand->Fix.Kind); 9851 9852 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9853 return; 9854 } 9855 9856 // Diagnose base -> derived pointer conversions. 9857 unsigned BaseToDerivedConversion = 0; 9858 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9859 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9860 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9861 FromPtrTy->getPointeeType()) && 9862 !FromPtrTy->getPointeeType()->isIncompleteType() && 9863 !ToPtrTy->getPointeeType()->isIncompleteType() && 9864 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9865 FromPtrTy->getPointeeType())) 9866 BaseToDerivedConversion = 1; 9867 } 9868 } else if (const ObjCObjectPointerType *FromPtrTy 9869 = FromTy->getAs<ObjCObjectPointerType>()) { 9870 if (const ObjCObjectPointerType *ToPtrTy 9871 = ToTy->getAs<ObjCObjectPointerType>()) 9872 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9873 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9874 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9875 FromPtrTy->getPointeeType()) && 9876 FromIface->isSuperClassOf(ToIface)) 9877 BaseToDerivedConversion = 2; 9878 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9879 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9880 !FromTy->isIncompleteType() && 9881 !ToRefTy->getPointeeType()->isIncompleteType() && 9882 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9883 BaseToDerivedConversion = 3; 9884 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9885 ToTy.getNonReferenceType().getCanonicalType() == 9886 FromTy.getNonReferenceType().getCanonicalType()) { 9887 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9888 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9889 << (unsigned)isObjectArgument << I + 1 9890 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 9891 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9892 return; 9893 } 9894 } 9895 9896 if (BaseToDerivedConversion) { 9897 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 9898 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9899 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9900 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 9901 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9902 return; 9903 } 9904 9905 if (isa<ObjCObjectPointerType>(CFromTy) && 9906 isa<PointerType>(CToTy)) { 9907 Qualifiers FromQs = CFromTy.getQualifiers(); 9908 Qualifiers ToQs = CToTy.getQualifiers(); 9909 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9910 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9911 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9912 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9913 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 9914 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9915 return; 9916 } 9917 } 9918 9919 if (TakingCandidateAddress && 9920 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9921 return; 9922 9923 // Emit the generic diagnostic and, optionally, add the hints to it. 9924 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9925 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9926 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9927 << ToTy << (unsigned)isObjectArgument << I + 1 9928 << (unsigned)(Cand->Fix.Kind); 9929 9930 // If we can fix the conversion, suggest the FixIts. 9931 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9932 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9933 FDiag << *HI; 9934 S.Diag(Fn->getLocation(), FDiag); 9935 9936 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9937 } 9938 9939 /// Additional arity mismatch diagnosis specific to a function overload 9940 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9941 /// over a candidate in any candidate set. 9942 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9943 unsigned NumArgs) { 9944 FunctionDecl *Fn = Cand->Function; 9945 unsigned MinParams = Fn->getMinRequiredArguments(); 9946 9947 // With invalid overloaded operators, it's possible that we think we 9948 // have an arity mismatch when in fact it looks like we have the 9949 // right number of arguments, because only overloaded operators have 9950 // the weird behavior of overloading member and non-member functions. 9951 // Just don't report anything. 9952 if (Fn->isInvalidDecl() && 9953 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9954 return true; 9955 9956 if (NumArgs < MinParams) { 9957 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9958 (Cand->FailureKind == ovl_fail_bad_deduction && 9959 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9960 } else { 9961 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9962 (Cand->FailureKind == ovl_fail_bad_deduction && 9963 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9964 } 9965 9966 return false; 9967 } 9968 9969 /// General arity mismatch diagnosis over a candidate in a candidate set. 9970 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9971 unsigned NumFormalArgs) { 9972 assert(isa<FunctionDecl>(D) && 9973 "The templated declaration should at least be a function" 9974 " when diagnosing bad template argument deduction due to too many" 9975 " or too few arguments"); 9976 9977 FunctionDecl *Fn = cast<FunctionDecl>(D); 9978 9979 // TODO: treat calls to a missing default constructor as a special case 9980 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9981 unsigned MinParams = Fn->getMinRequiredArguments(); 9982 9983 // at least / at most / exactly 9984 unsigned mode, modeCount; 9985 if (NumFormalArgs < MinParams) { 9986 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9987 FnTy->isTemplateVariadic()) 9988 mode = 0; // "at least" 9989 else 9990 mode = 2; // "exactly" 9991 modeCount = MinParams; 9992 } else { 9993 if (MinParams != FnTy->getNumParams()) 9994 mode = 1; // "at most" 9995 else 9996 mode = 2; // "exactly" 9997 modeCount = FnTy->getNumParams(); 9998 } 9999 10000 std::string Description; 10001 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10002 ClassifyOverloadCandidate(S, Found, Fn, Description); 10003 10004 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10005 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10006 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10007 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10008 else 10009 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10010 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10011 << Description << mode << modeCount << NumFormalArgs; 10012 10013 MaybeEmitInheritedConstructorNote(S, Found); 10014 } 10015 10016 /// Arity mismatch diagnosis specific to a function overload candidate. 10017 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10018 unsigned NumFormalArgs) { 10019 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10020 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10021 } 10022 10023 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10024 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10025 return TD; 10026 llvm_unreachable("Unsupported: Getting the described template declaration" 10027 " for bad deduction diagnosis"); 10028 } 10029 10030 /// Diagnose a failed template-argument deduction. 10031 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10032 DeductionFailureInfo &DeductionFailure, 10033 unsigned NumArgs, 10034 bool TakingCandidateAddress) { 10035 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10036 NamedDecl *ParamD; 10037 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10038 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10039 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10040 switch (DeductionFailure.Result) { 10041 case Sema::TDK_Success: 10042 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10043 10044 case Sema::TDK_Incomplete: { 10045 assert(ParamD && "no parameter found for incomplete deduction result"); 10046 S.Diag(Templated->getLocation(), 10047 diag::note_ovl_candidate_incomplete_deduction) 10048 << ParamD->getDeclName(); 10049 MaybeEmitInheritedConstructorNote(S, Found); 10050 return; 10051 } 10052 10053 case Sema::TDK_IncompletePack: { 10054 assert(ParamD && "no parameter found for incomplete deduction result"); 10055 S.Diag(Templated->getLocation(), 10056 diag::note_ovl_candidate_incomplete_deduction_pack) 10057 << ParamD->getDeclName() 10058 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10059 << *DeductionFailure.getFirstArg(); 10060 MaybeEmitInheritedConstructorNote(S, Found); 10061 return; 10062 } 10063 10064 case Sema::TDK_Underqualified: { 10065 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10066 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10067 10068 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10069 10070 // Param will have been canonicalized, but it should just be a 10071 // qualified version of ParamD, so move the qualifiers to that. 10072 QualifierCollector Qs; 10073 Qs.strip(Param); 10074 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10075 assert(S.Context.hasSameType(Param, NonCanonParam)); 10076 10077 // Arg has also been canonicalized, but there's nothing we can do 10078 // about that. It also doesn't matter as much, because it won't 10079 // have any template parameters in it (because deduction isn't 10080 // done on dependent types). 10081 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10082 10083 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10084 << ParamD->getDeclName() << Arg << NonCanonParam; 10085 MaybeEmitInheritedConstructorNote(S, Found); 10086 return; 10087 } 10088 10089 case Sema::TDK_Inconsistent: { 10090 assert(ParamD && "no parameter found for inconsistent deduction result"); 10091 int which = 0; 10092 if (isa<TemplateTypeParmDecl>(ParamD)) 10093 which = 0; 10094 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10095 // Deduction might have failed because we deduced arguments of two 10096 // different types for a non-type template parameter. 10097 // FIXME: Use a different TDK value for this. 10098 QualType T1 = 10099 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10100 QualType T2 = 10101 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10102 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10103 S.Diag(Templated->getLocation(), 10104 diag::note_ovl_candidate_inconsistent_deduction_types) 10105 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10106 << *DeductionFailure.getSecondArg() << T2; 10107 MaybeEmitInheritedConstructorNote(S, Found); 10108 return; 10109 } 10110 10111 which = 1; 10112 } else { 10113 which = 2; 10114 } 10115 10116 S.Diag(Templated->getLocation(), 10117 diag::note_ovl_candidate_inconsistent_deduction) 10118 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10119 << *DeductionFailure.getSecondArg(); 10120 MaybeEmitInheritedConstructorNote(S, Found); 10121 return; 10122 } 10123 10124 case Sema::TDK_InvalidExplicitArguments: 10125 assert(ParamD && "no parameter found for invalid explicit arguments"); 10126 if (ParamD->getDeclName()) 10127 S.Diag(Templated->getLocation(), 10128 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10129 << ParamD->getDeclName(); 10130 else { 10131 int index = 0; 10132 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10133 index = TTP->getIndex(); 10134 else if (NonTypeTemplateParmDecl *NTTP 10135 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10136 index = NTTP->getIndex(); 10137 else 10138 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10139 S.Diag(Templated->getLocation(), 10140 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10141 << (index + 1); 10142 } 10143 MaybeEmitInheritedConstructorNote(S, Found); 10144 return; 10145 10146 case Sema::TDK_TooManyArguments: 10147 case Sema::TDK_TooFewArguments: 10148 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10149 return; 10150 10151 case Sema::TDK_InstantiationDepth: 10152 S.Diag(Templated->getLocation(), 10153 diag::note_ovl_candidate_instantiation_depth); 10154 MaybeEmitInheritedConstructorNote(S, Found); 10155 return; 10156 10157 case Sema::TDK_SubstitutionFailure: { 10158 // Format the template argument list into the argument string. 10159 SmallString<128> TemplateArgString; 10160 if (TemplateArgumentList *Args = 10161 DeductionFailure.getTemplateArgumentList()) { 10162 TemplateArgString = " "; 10163 TemplateArgString += S.getTemplateArgumentBindingsText( 10164 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10165 } 10166 10167 // If this candidate was disabled by enable_if, say so. 10168 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10169 if (PDiag && PDiag->second.getDiagID() == 10170 diag::err_typename_nested_not_found_enable_if) { 10171 // FIXME: Use the source range of the condition, and the fully-qualified 10172 // name of the enable_if template. These are both present in PDiag. 10173 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10174 << "'enable_if'" << TemplateArgString; 10175 return; 10176 } 10177 10178 // We found a specific requirement that disabled the enable_if. 10179 if (PDiag && PDiag->second.getDiagID() == 10180 diag::err_typename_nested_not_found_requirement) { 10181 S.Diag(Templated->getLocation(), 10182 diag::note_ovl_candidate_disabled_by_requirement) 10183 << PDiag->second.getStringArg(0) << TemplateArgString; 10184 return; 10185 } 10186 10187 // Format the SFINAE diagnostic into the argument string. 10188 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10189 // formatted message in another diagnostic. 10190 SmallString<128> SFINAEArgString; 10191 SourceRange R; 10192 if (PDiag) { 10193 SFINAEArgString = ": "; 10194 R = SourceRange(PDiag->first, PDiag->first); 10195 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10196 } 10197 10198 S.Diag(Templated->getLocation(), 10199 diag::note_ovl_candidate_substitution_failure) 10200 << TemplateArgString << SFINAEArgString << R; 10201 MaybeEmitInheritedConstructorNote(S, Found); 10202 return; 10203 } 10204 10205 case Sema::TDK_DeducedMismatch: 10206 case Sema::TDK_DeducedMismatchNested: { 10207 // Format the template argument list into the argument string. 10208 SmallString<128> TemplateArgString; 10209 if (TemplateArgumentList *Args = 10210 DeductionFailure.getTemplateArgumentList()) { 10211 TemplateArgString = " "; 10212 TemplateArgString += S.getTemplateArgumentBindingsText( 10213 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10214 } 10215 10216 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10217 << (*DeductionFailure.getCallArgIndex() + 1) 10218 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10219 << TemplateArgString 10220 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10221 break; 10222 } 10223 10224 case Sema::TDK_NonDeducedMismatch: { 10225 // FIXME: Provide a source location to indicate what we couldn't match. 10226 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10227 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10228 if (FirstTA.getKind() == TemplateArgument::Template && 10229 SecondTA.getKind() == TemplateArgument::Template) { 10230 TemplateName FirstTN = FirstTA.getAsTemplate(); 10231 TemplateName SecondTN = SecondTA.getAsTemplate(); 10232 if (FirstTN.getKind() == TemplateName::Template && 10233 SecondTN.getKind() == TemplateName::Template) { 10234 if (FirstTN.getAsTemplateDecl()->getName() == 10235 SecondTN.getAsTemplateDecl()->getName()) { 10236 // FIXME: This fixes a bad diagnostic where both templates are named 10237 // the same. This particular case is a bit difficult since: 10238 // 1) It is passed as a string to the diagnostic printer. 10239 // 2) The diagnostic printer only attempts to find a better 10240 // name for types, not decls. 10241 // Ideally, this should folded into the diagnostic printer. 10242 S.Diag(Templated->getLocation(), 10243 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10244 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10245 return; 10246 } 10247 } 10248 } 10249 10250 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10251 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10252 return; 10253 10254 // FIXME: For generic lambda parameters, check if the function is a lambda 10255 // call operator, and if so, emit a prettier and more informative 10256 // diagnostic that mentions 'auto' and lambda in addition to 10257 // (or instead of?) the canonical template type parameters. 10258 S.Diag(Templated->getLocation(), 10259 diag::note_ovl_candidate_non_deduced_mismatch) 10260 << FirstTA << SecondTA; 10261 return; 10262 } 10263 // TODO: diagnose these individually, then kill off 10264 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10265 case Sema::TDK_MiscellaneousDeductionFailure: 10266 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10267 MaybeEmitInheritedConstructorNote(S, Found); 10268 return; 10269 case Sema::TDK_CUDATargetMismatch: 10270 S.Diag(Templated->getLocation(), 10271 diag::note_cuda_ovl_candidate_target_mismatch); 10272 return; 10273 } 10274 } 10275 10276 /// Diagnose a failed template-argument deduction, for function calls. 10277 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10278 unsigned NumArgs, 10279 bool TakingCandidateAddress) { 10280 unsigned TDK = Cand->DeductionFailure.Result; 10281 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10282 if (CheckArityMismatch(S, Cand, NumArgs)) 10283 return; 10284 } 10285 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10286 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10287 } 10288 10289 /// CUDA: diagnose an invalid call across targets. 10290 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10291 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10292 FunctionDecl *Callee = Cand->Function; 10293 10294 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10295 CalleeTarget = S.IdentifyCUDATarget(Callee); 10296 10297 std::string FnDesc; 10298 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10299 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10300 10301 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10302 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10303 << FnDesc /* Ignored */ 10304 << CalleeTarget << CallerTarget; 10305 10306 // This could be an implicit constructor for which we could not infer the 10307 // target due to a collsion. Diagnose that case. 10308 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10309 if (Meth != nullptr && Meth->isImplicit()) { 10310 CXXRecordDecl *ParentClass = Meth->getParent(); 10311 Sema::CXXSpecialMember CSM; 10312 10313 switch (FnKindPair.first) { 10314 default: 10315 return; 10316 case oc_implicit_default_constructor: 10317 CSM = Sema::CXXDefaultConstructor; 10318 break; 10319 case oc_implicit_copy_constructor: 10320 CSM = Sema::CXXCopyConstructor; 10321 break; 10322 case oc_implicit_move_constructor: 10323 CSM = Sema::CXXMoveConstructor; 10324 break; 10325 case oc_implicit_copy_assignment: 10326 CSM = Sema::CXXCopyAssignment; 10327 break; 10328 case oc_implicit_move_assignment: 10329 CSM = Sema::CXXMoveAssignment; 10330 break; 10331 }; 10332 10333 bool ConstRHS = false; 10334 if (Meth->getNumParams()) { 10335 if (const ReferenceType *RT = 10336 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10337 ConstRHS = RT->getPointeeType().isConstQualified(); 10338 } 10339 } 10340 10341 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10342 /* ConstRHS */ ConstRHS, 10343 /* Diagnose */ true); 10344 } 10345 } 10346 10347 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10348 FunctionDecl *Callee = Cand->Function; 10349 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10350 10351 S.Diag(Callee->getLocation(), 10352 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10353 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10354 } 10355 10356 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10357 ExplicitSpecifier ES; 10358 const char *DeclName; 10359 switch (Cand->Function->getDeclKind()) { 10360 case Decl::Kind::CXXConstructor: 10361 ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier(); 10362 DeclName = "constructor"; 10363 break; 10364 case Decl::Kind::CXXConversion: 10365 ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier(); 10366 DeclName = "conversion operator"; 10367 break; 10368 case Decl::Kind::CXXDeductionGuide: 10369 ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier(); 10370 DeclName = "deductiong guide"; 10371 break; 10372 default: 10373 llvm_unreachable("invalid Decl"); 10374 } 10375 assert(ES.getExpr() && "null expression should be handled before"); 10376 S.Diag(Cand->Function->getLocation(), 10377 diag::note_ovl_candidate_explicit_forbidden) 10378 << DeclName; 10379 S.Diag(ES.getExpr()->getBeginLoc(), 10380 diag::note_explicit_bool_resolved_to_true); 10381 } 10382 10383 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10384 FunctionDecl *Callee = Cand->Function; 10385 10386 S.Diag(Callee->getLocation(), 10387 diag::note_ovl_candidate_disabled_by_extension) 10388 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10389 } 10390 10391 /// Generates a 'note' diagnostic for an overload candidate. We've 10392 /// already generated a primary error at the call site. 10393 /// 10394 /// It really does need to be a single diagnostic with its caret 10395 /// pointed at the candidate declaration. Yes, this creates some 10396 /// major challenges of technical writing. Yes, this makes pointing 10397 /// out problems with specific arguments quite awkward. It's still 10398 /// better than generating twenty screens of text for every failed 10399 /// overload. 10400 /// 10401 /// It would be great to be able to express per-candidate problems 10402 /// more richly for those diagnostic clients that cared, but we'd 10403 /// still have to be just as careful with the default diagnostics. 10404 /// \param CtorDestAS Addr space of object being constructed (for ctor 10405 /// candidates only). 10406 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10407 unsigned NumArgs, 10408 bool TakingCandidateAddress, 10409 LangAS CtorDestAS = LangAS::Default) { 10410 FunctionDecl *Fn = Cand->Function; 10411 10412 // Note deleted candidates, but only if they're viable. 10413 if (Cand->Viable) { 10414 if (Fn->isDeleted()) { 10415 std::string FnDesc; 10416 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10417 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10418 10419 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10420 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10421 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10422 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10423 return; 10424 } 10425 10426 // We don't really have anything else to say about viable candidates. 10427 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10428 return; 10429 } 10430 10431 switch (Cand->FailureKind) { 10432 case ovl_fail_too_many_arguments: 10433 case ovl_fail_too_few_arguments: 10434 return DiagnoseArityMismatch(S, Cand, NumArgs); 10435 10436 case ovl_fail_bad_deduction: 10437 return DiagnoseBadDeduction(S, Cand, NumArgs, 10438 TakingCandidateAddress); 10439 10440 case ovl_fail_illegal_constructor: { 10441 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10442 << (Fn->getPrimaryTemplate() ? 1 : 0); 10443 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10444 return; 10445 } 10446 10447 case ovl_fail_object_addrspace_mismatch: { 10448 Qualifiers QualsForPrinting; 10449 QualsForPrinting.setAddressSpace(CtorDestAS); 10450 S.Diag(Fn->getLocation(), 10451 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 10452 << QualsForPrinting; 10453 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10454 return; 10455 } 10456 10457 case ovl_fail_trivial_conversion: 10458 case ovl_fail_bad_final_conversion: 10459 case ovl_fail_final_conversion_not_exact: 10460 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10461 10462 case ovl_fail_bad_conversion: { 10463 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10464 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10465 if (Cand->Conversions[I].isBad()) 10466 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10467 10468 // FIXME: this currently happens when we're called from SemaInit 10469 // when user-conversion overload fails. Figure out how to handle 10470 // those conditions and diagnose them well. 10471 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10472 } 10473 10474 case ovl_fail_bad_target: 10475 return DiagnoseBadTarget(S, Cand); 10476 10477 case ovl_fail_enable_if: 10478 return DiagnoseFailedEnableIfAttr(S, Cand); 10479 10480 case ovl_fail_explicit_resolved: 10481 return DiagnoseFailedExplicitSpec(S, Cand); 10482 10483 case ovl_fail_ext_disabled: 10484 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10485 10486 case ovl_fail_inhctor_slice: 10487 // It's generally not interesting to note copy/move constructors here. 10488 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10489 return; 10490 S.Diag(Fn->getLocation(), 10491 diag::note_ovl_candidate_inherited_constructor_slice) 10492 << (Fn->getPrimaryTemplate() ? 1 : 0) 10493 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10494 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10495 return; 10496 10497 case ovl_fail_addr_not_available: { 10498 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10499 (void)Available; 10500 assert(!Available); 10501 break; 10502 } 10503 case ovl_non_default_multiversion_function: 10504 // Do nothing, these should simply be ignored. 10505 break; 10506 } 10507 } 10508 10509 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10510 // Desugar the type of the surrogate down to a function type, 10511 // retaining as many typedefs as possible while still showing 10512 // the function type (and, therefore, its parameter types). 10513 QualType FnType = Cand->Surrogate->getConversionType(); 10514 bool isLValueReference = false; 10515 bool isRValueReference = false; 10516 bool isPointer = false; 10517 if (const LValueReferenceType *FnTypeRef = 10518 FnType->getAs<LValueReferenceType>()) { 10519 FnType = FnTypeRef->getPointeeType(); 10520 isLValueReference = true; 10521 } else if (const RValueReferenceType *FnTypeRef = 10522 FnType->getAs<RValueReferenceType>()) { 10523 FnType = FnTypeRef->getPointeeType(); 10524 isRValueReference = true; 10525 } 10526 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10527 FnType = FnTypePtr->getPointeeType(); 10528 isPointer = true; 10529 } 10530 // Desugar down to a function type. 10531 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10532 // Reconstruct the pointer/reference as appropriate. 10533 if (isPointer) FnType = S.Context.getPointerType(FnType); 10534 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10535 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10536 10537 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10538 << FnType; 10539 } 10540 10541 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10542 SourceLocation OpLoc, 10543 OverloadCandidate *Cand) { 10544 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10545 std::string TypeStr("operator"); 10546 TypeStr += Opc; 10547 TypeStr += "("; 10548 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10549 if (Cand->Conversions.size() == 1) { 10550 TypeStr += ")"; 10551 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10552 } else { 10553 TypeStr += ", "; 10554 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10555 TypeStr += ")"; 10556 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10557 } 10558 } 10559 10560 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10561 OverloadCandidate *Cand) { 10562 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10563 if (ICS.isBad()) break; // all meaningless after first invalid 10564 if (!ICS.isAmbiguous()) continue; 10565 10566 ICS.DiagnoseAmbiguousConversion( 10567 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10568 } 10569 } 10570 10571 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10572 if (Cand->Function) 10573 return Cand->Function->getLocation(); 10574 if (Cand->IsSurrogate) 10575 return Cand->Surrogate->getLocation(); 10576 return SourceLocation(); 10577 } 10578 10579 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10580 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10581 case Sema::TDK_Success: 10582 case Sema::TDK_NonDependentConversionFailure: 10583 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10584 10585 case Sema::TDK_Invalid: 10586 case Sema::TDK_Incomplete: 10587 case Sema::TDK_IncompletePack: 10588 return 1; 10589 10590 case Sema::TDK_Underqualified: 10591 case Sema::TDK_Inconsistent: 10592 return 2; 10593 10594 case Sema::TDK_SubstitutionFailure: 10595 case Sema::TDK_DeducedMismatch: 10596 case Sema::TDK_DeducedMismatchNested: 10597 case Sema::TDK_NonDeducedMismatch: 10598 case Sema::TDK_MiscellaneousDeductionFailure: 10599 case Sema::TDK_CUDATargetMismatch: 10600 return 3; 10601 10602 case Sema::TDK_InstantiationDepth: 10603 return 4; 10604 10605 case Sema::TDK_InvalidExplicitArguments: 10606 return 5; 10607 10608 case Sema::TDK_TooManyArguments: 10609 case Sema::TDK_TooFewArguments: 10610 return 6; 10611 } 10612 llvm_unreachable("Unhandled deduction result"); 10613 } 10614 10615 namespace { 10616 struct CompareOverloadCandidatesForDisplay { 10617 Sema &S; 10618 SourceLocation Loc; 10619 size_t NumArgs; 10620 OverloadCandidateSet::CandidateSetKind CSK; 10621 10622 CompareOverloadCandidatesForDisplay( 10623 Sema &S, SourceLocation Loc, size_t NArgs, 10624 OverloadCandidateSet::CandidateSetKind CSK) 10625 : S(S), NumArgs(NArgs), CSK(CSK) {} 10626 10627 bool operator()(const OverloadCandidate *L, 10628 const OverloadCandidate *R) { 10629 // Fast-path this check. 10630 if (L == R) return false; 10631 10632 // Order first by viability. 10633 if (L->Viable) { 10634 if (!R->Viable) return true; 10635 10636 // TODO: introduce a tri-valued comparison for overload 10637 // candidates. Would be more worthwhile if we had a sort 10638 // that could exploit it. 10639 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10640 return true; 10641 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10642 return false; 10643 } else if (R->Viable) 10644 return false; 10645 10646 assert(L->Viable == R->Viable); 10647 10648 // Criteria by which we can sort non-viable candidates: 10649 if (!L->Viable) { 10650 // 1. Arity mismatches come after other candidates. 10651 if (L->FailureKind == ovl_fail_too_many_arguments || 10652 L->FailureKind == ovl_fail_too_few_arguments) { 10653 if (R->FailureKind == ovl_fail_too_many_arguments || 10654 R->FailureKind == ovl_fail_too_few_arguments) { 10655 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10656 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10657 if (LDist == RDist) { 10658 if (L->FailureKind == R->FailureKind) 10659 // Sort non-surrogates before surrogates. 10660 return !L->IsSurrogate && R->IsSurrogate; 10661 // Sort candidates requiring fewer parameters than there were 10662 // arguments given after candidates requiring more parameters 10663 // than there were arguments given. 10664 return L->FailureKind == ovl_fail_too_many_arguments; 10665 } 10666 return LDist < RDist; 10667 } 10668 return false; 10669 } 10670 if (R->FailureKind == ovl_fail_too_many_arguments || 10671 R->FailureKind == ovl_fail_too_few_arguments) 10672 return true; 10673 10674 // 2. Bad conversions come first and are ordered by the number 10675 // of bad conversions and quality of good conversions. 10676 if (L->FailureKind == ovl_fail_bad_conversion) { 10677 if (R->FailureKind != ovl_fail_bad_conversion) 10678 return true; 10679 10680 // The conversion that can be fixed with a smaller number of changes, 10681 // comes first. 10682 unsigned numLFixes = L->Fix.NumConversionsFixed; 10683 unsigned numRFixes = R->Fix.NumConversionsFixed; 10684 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10685 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10686 if (numLFixes != numRFixes) { 10687 return numLFixes < numRFixes; 10688 } 10689 10690 // If there's any ordering between the defined conversions... 10691 // FIXME: this might not be transitive. 10692 assert(L->Conversions.size() == R->Conversions.size()); 10693 10694 int leftBetter = 0; 10695 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10696 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10697 switch (CompareImplicitConversionSequences(S, Loc, 10698 L->Conversions[I], 10699 R->Conversions[I])) { 10700 case ImplicitConversionSequence::Better: 10701 leftBetter++; 10702 break; 10703 10704 case ImplicitConversionSequence::Worse: 10705 leftBetter--; 10706 break; 10707 10708 case ImplicitConversionSequence::Indistinguishable: 10709 break; 10710 } 10711 } 10712 if (leftBetter > 0) return true; 10713 if (leftBetter < 0) return false; 10714 10715 } else if (R->FailureKind == ovl_fail_bad_conversion) 10716 return false; 10717 10718 if (L->FailureKind == ovl_fail_bad_deduction) { 10719 if (R->FailureKind != ovl_fail_bad_deduction) 10720 return true; 10721 10722 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10723 return RankDeductionFailure(L->DeductionFailure) 10724 < RankDeductionFailure(R->DeductionFailure); 10725 } else if (R->FailureKind == ovl_fail_bad_deduction) 10726 return false; 10727 10728 // TODO: others? 10729 } 10730 10731 // Sort everything else by location. 10732 SourceLocation LLoc = GetLocationForCandidate(L); 10733 SourceLocation RLoc = GetLocationForCandidate(R); 10734 10735 // Put candidates without locations (e.g. builtins) at the end. 10736 if (LLoc.isInvalid()) return false; 10737 if (RLoc.isInvalid()) return true; 10738 10739 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10740 } 10741 }; 10742 } 10743 10744 /// CompleteNonViableCandidate - Normally, overload resolution only 10745 /// computes up to the first bad conversion. Produces the FixIt set if 10746 /// possible. 10747 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10748 ArrayRef<Expr *> Args) { 10749 assert(!Cand->Viable); 10750 10751 // Don't do anything on failures other than bad conversion. 10752 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10753 10754 // We only want the FixIts if all the arguments can be corrected. 10755 bool Unfixable = false; 10756 // Use a implicit copy initialization to check conversion fixes. 10757 Cand->Fix.setConversionChecker(TryCopyInitialization); 10758 10759 // Attempt to fix the bad conversion. 10760 unsigned ConvCount = Cand->Conversions.size(); 10761 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10762 ++ConvIdx) { 10763 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10764 if (Cand->Conversions[ConvIdx].isInitialized() && 10765 Cand->Conversions[ConvIdx].isBad()) { 10766 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10767 break; 10768 } 10769 } 10770 10771 // FIXME: this should probably be preserved from the overload 10772 // operation somehow. 10773 bool SuppressUserConversions = false; 10774 10775 unsigned ConvIdx = 0; 10776 ArrayRef<QualType> ParamTypes; 10777 10778 if (Cand->IsSurrogate) { 10779 QualType ConvType 10780 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10781 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10782 ConvType = ConvPtrType->getPointeeType(); 10783 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10784 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10785 ConvIdx = 1; 10786 } else if (Cand->Function) { 10787 ParamTypes = 10788 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10789 if (isa<CXXMethodDecl>(Cand->Function) && 10790 !isa<CXXConstructorDecl>(Cand->Function)) { 10791 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10792 ConvIdx = 1; 10793 } 10794 } else { 10795 // Builtin operator. 10796 assert(ConvCount <= 3); 10797 ParamTypes = Cand->BuiltinParamTypes; 10798 } 10799 10800 // Fill in the rest of the conversions. 10801 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10802 if (Cand->Conversions[ConvIdx].isInitialized()) { 10803 // We've already checked this conversion. 10804 } else if (ArgIdx < ParamTypes.size()) { 10805 if (ParamTypes[ArgIdx]->isDependentType()) 10806 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10807 Args[ArgIdx]->getType()); 10808 else { 10809 Cand->Conversions[ConvIdx] = 10810 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10811 SuppressUserConversions, 10812 /*InOverloadResolution=*/true, 10813 /*AllowObjCWritebackConversion=*/ 10814 S.getLangOpts().ObjCAutoRefCount); 10815 // Store the FixIt in the candidate if it exists. 10816 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10817 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10818 } 10819 } else 10820 Cand->Conversions[ConvIdx].setEllipsis(); 10821 } 10822 } 10823 10824 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 10825 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10826 SourceLocation OpLoc, 10827 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10828 // Sort the candidates by viability and position. Sorting directly would 10829 // be prohibitive, so we make a set of pointers and sort those. 10830 SmallVector<OverloadCandidate*, 32> Cands; 10831 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10832 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10833 if (!Filter(*Cand)) 10834 continue; 10835 if (Cand->Viable) 10836 Cands.push_back(Cand); 10837 else if (OCD == OCD_AllCandidates) { 10838 CompleteNonViableCandidate(S, Cand, Args); 10839 if (Cand->Function || Cand->IsSurrogate) 10840 Cands.push_back(Cand); 10841 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10842 // want to list every possible builtin candidate. 10843 } 10844 } 10845 10846 llvm::stable_sort( 10847 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 10848 10849 return Cands; 10850 } 10851 10852 /// When overload resolution fails, prints diagnostic messages containing the 10853 /// candidates in the candidate set. 10854 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 10855 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10856 StringRef Opc, SourceLocation OpLoc, 10857 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10858 10859 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 10860 10861 S.Diag(PD.first, PD.second); 10862 10863 NoteCandidates(S, Args, Cands, Opc, OpLoc); 10864 } 10865 10866 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 10867 ArrayRef<OverloadCandidate *> Cands, 10868 StringRef Opc, SourceLocation OpLoc) { 10869 bool ReportedAmbiguousConversions = false; 10870 10871 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10872 unsigned CandsShown = 0; 10873 auto I = Cands.begin(), E = Cands.end(); 10874 for (; I != E; ++I) { 10875 OverloadCandidate *Cand = *I; 10876 10877 // Set an arbitrary limit on the number of candidate functions we'll spam 10878 // the user with. FIXME: This limit should depend on details of the 10879 // candidate list. 10880 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10881 break; 10882 } 10883 ++CandsShown; 10884 10885 if (Cand->Function) 10886 NoteFunctionCandidate(S, Cand, Args.size(), 10887 /*TakingCandidateAddress=*/false, DestAS); 10888 else if (Cand->IsSurrogate) 10889 NoteSurrogateCandidate(S, Cand); 10890 else { 10891 assert(Cand->Viable && 10892 "Non-viable built-in candidates are not added to Cands."); 10893 // Generally we only see ambiguities including viable builtin 10894 // operators if overload resolution got screwed up by an 10895 // ambiguous user-defined conversion. 10896 // 10897 // FIXME: It's quite possible for different conversions to see 10898 // different ambiguities, though. 10899 if (!ReportedAmbiguousConversions) { 10900 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10901 ReportedAmbiguousConversions = true; 10902 } 10903 10904 // If this is a viable builtin, print it. 10905 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10906 } 10907 } 10908 10909 if (I != E) 10910 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10911 } 10912 10913 static SourceLocation 10914 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10915 return Cand->Specialization ? Cand->Specialization->getLocation() 10916 : SourceLocation(); 10917 } 10918 10919 namespace { 10920 struct CompareTemplateSpecCandidatesForDisplay { 10921 Sema &S; 10922 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10923 10924 bool operator()(const TemplateSpecCandidate *L, 10925 const TemplateSpecCandidate *R) { 10926 // Fast-path this check. 10927 if (L == R) 10928 return false; 10929 10930 // Assuming that both candidates are not matches... 10931 10932 // Sort by the ranking of deduction failures. 10933 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10934 return RankDeductionFailure(L->DeductionFailure) < 10935 RankDeductionFailure(R->DeductionFailure); 10936 10937 // Sort everything else by location. 10938 SourceLocation LLoc = GetLocationForCandidate(L); 10939 SourceLocation RLoc = GetLocationForCandidate(R); 10940 10941 // Put candidates without locations (e.g. builtins) at the end. 10942 if (LLoc.isInvalid()) 10943 return false; 10944 if (RLoc.isInvalid()) 10945 return true; 10946 10947 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10948 } 10949 }; 10950 } 10951 10952 /// Diagnose a template argument deduction failure. 10953 /// We are treating these failures as overload failures due to bad 10954 /// deductions. 10955 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10956 bool ForTakingAddress) { 10957 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10958 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10959 } 10960 10961 void TemplateSpecCandidateSet::destroyCandidates() { 10962 for (iterator i = begin(), e = end(); i != e; ++i) { 10963 i->DeductionFailure.Destroy(); 10964 } 10965 } 10966 10967 void TemplateSpecCandidateSet::clear() { 10968 destroyCandidates(); 10969 Candidates.clear(); 10970 } 10971 10972 /// NoteCandidates - When no template specialization match is found, prints 10973 /// diagnostic messages containing the non-matching specializations that form 10974 /// the candidate set. 10975 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10976 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10977 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10978 // Sort the candidates by position (assuming no candidate is a match). 10979 // Sorting directly would be prohibitive, so we make a set of pointers 10980 // and sort those. 10981 SmallVector<TemplateSpecCandidate *, 32> Cands; 10982 Cands.reserve(size()); 10983 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10984 if (Cand->Specialization) 10985 Cands.push_back(Cand); 10986 // Otherwise, this is a non-matching builtin candidate. We do not, 10987 // in general, want to list every possible builtin candidate. 10988 } 10989 10990 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 10991 10992 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10993 // for generalization purposes (?). 10994 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10995 10996 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10997 unsigned CandsShown = 0; 10998 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10999 TemplateSpecCandidate *Cand = *I; 11000 11001 // Set an arbitrary limit on the number of candidates we'll spam 11002 // the user with. FIXME: This limit should depend on details of the 11003 // candidate list. 11004 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11005 break; 11006 ++CandsShown; 11007 11008 assert(Cand->Specialization && 11009 "Non-matching built-in candidates are not added to Cands."); 11010 Cand->NoteDeductionFailure(S, ForTakingAddress); 11011 } 11012 11013 if (I != E) 11014 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11015 } 11016 11017 // [PossiblyAFunctionType] --> [Return] 11018 // NonFunctionType --> NonFunctionType 11019 // R (A) --> R(A) 11020 // R (*)(A) --> R (A) 11021 // R (&)(A) --> R (A) 11022 // R (S::*)(A) --> R (A) 11023 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11024 QualType Ret = PossiblyAFunctionType; 11025 if (const PointerType *ToTypePtr = 11026 PossiblyAFunctionType->getAs<PointerType>()) 11027 Ret = ToTypePtr->getPointeeType(); 11028 else if (const ReferenceType *ToTypeRef = 11029 PossiblyAFunctionType->getAs<ReferenceType>()) 11030 Ret = ToTypeRef->getPointeeType(); 11031 else if (const MemberPointerType *MemTypePtr = 11032 PossiblyAFunctionType->getAs<MemberPointerType>()) 11033 Ret = MemTypePtr->getPointeeType(); 11034 Ret = 11035 Context.getCanonicalType(Ret).getUnqualifiedType(); 11036 return Ret; 11037 } 11038 11039 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11040 bool Complain = true) { 11041 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11042 S.DeduceReturnType(FD, Loc, Complain)) 11043 return true; 11044 11045 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11046 if (S.getLangOpts().CPlusPlus17 && 11047 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11048 !S.ResolveExceptionSpec(Loc, FPT)) 11049 return true; 11050 11051 return false; 11052 } 11053 11054 namespace { 11055 // A helper class to help with address of function resolution 11056 // - allows us to avoid passing around all those ugly parameters 11057 class AddressOfFunctionResolver { 11058 Sema& S; 11059 Expr* SourceExpr; 11060 const QualType& TargetType; 11061 QualType TargetFunctionType; // Extracted function type from target type 11062 11063 bool Complain; 11064 //DeclAccessPair& ResultFunctionAccessPair; 11065 ASTContext& Context; 11066 11067 bool TargetTypeIsNonStaticMemberFunction; 11068 bool FoundNonTemplateFunction; 11069 bool StaticMemberFunctionFromBoundPointer; 11070 bool HasComplained; 11071 11072 OverloadExpr::FindResult OvlExprInfo; 11073 OverloadExpr *OvlExpr; 11074 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11075 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11076 TemplateSpecCandidateSet FailedCandidates; 11077 11078 public: 11079 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11080 const QualType &TargetType, bool Complain) 11081 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11082 Complain(Complain), Context(S.getASTContext()), 11083 TargetTypeIsNonStaticMemberFunction( 11084 !!TargetType->getAs<MemberPointerType>()), 11085 FoundNonTemplateFunction(false), 11086 StaticMemberFunctionFromBoundPointer(false), 11087 HasComplained(false), 11088 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11089 OvlExpr(OvlExprInfo.Expression), 11090 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11091 ExtractUnqualifiedFunctionTypeFromTargetType(); 11092 11093 if (TargetFunctionType->isFunctionType()) { 11094 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11095 if (!UME->isImplicitAccess() && 11096 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11097 StaticMemberFunctionFromBoundPointer = true; 11098 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11099 DeclAccessPair dap; 11100 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11101 OvlExpr, false, &dap)) { 11102 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11103 if (!Method->isStatic()) { 11104 // If the target type is a non-function type and the function found 11105 // is a non-static member function, pretend as if that was the 11106 // target, it's the only possible type to end up with. 11107 TargetTypeIsNonStaticMemberFunction = true; 11108 11109 // And skip adding the function if its not in the proper form. 11110 // We'll diagnose this due to an empty set of functions. 11111 if (!OvlExprInfo.HasFormOfMemberPointer) 11112 return; 11113 } 11114 11115 Matches.push_back(std::make_pair(dap, Fn)); 11116 } 11117 return; 11118 } 11119 11120 if (OvlExpr->hasExplicitTemplateArgs()) 11121 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11122 11123 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11124 // C++ [over.over]p4: 11125 // If more than one function is selected, [...] 11126 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11127 if (FoundNonTemplateFunction) 11128 EliminateAllTemplateMatches(); 11129 else 11130 EliminateAllExceptMostSpecializedTemplate(); 11131 } 11132 } 11133 11134 if (S.getLangOpts().CUDA && Matches.size() > 1) 11135 EliminateSuboptimalCudaMatches(); 11136 } 11137 11138 bool hasComplained() const { return HasComplained; } 11139 11140 private: 11141 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11142 QualType Discard; 11143 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11144 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11145 } 11146 11147 /// \return true if A is considered a better overload candidate for the 11148 /// desired type than B. 11149 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11150 // If A doesn't have exactly the correct type, we don't want to classify it 11151 // as "better" than anything else. This way, the user is required to 11152 // disambiguate for us if there are multiple candidates and no exact match. 11153 return candidateHasExactlyCorrectType(A) && 11154 (!candidateHasExactlyCorrectType(B) || 11155 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11156 } 11157 11158 /// \return true if we were able to eliminate all but one overload candidate, 11159 /// false otherwise. 11160 bool eliminiateSuboptimalOverloadCandidates() { 11161 // Same algorithm as overload resolution -- one pass to pick the "best", 11162 // another pass to be sure that nothing is better than the best. 11163 auto Best = Matches.begin(); 11164 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11165 if (isBetterCandidate(I->second, Best->second)) 11166 Best = I; 11167 11168 const FunctionDecl *BestFn = Best->second; 11169 auto IsBestOrInferiorToBest = [this, BestFn]( 11170 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11171 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11172 }; 11173 11174 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11175 // option, so we can potentially give the user a better error 11176 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11177 return false; 11178 Matches[0] = *Best; 11179 Matches.resize(1); 11180 return true; 11181 } 11182 11183 bool isTargetTypeAFunction() const { 11184 return TargetFunctionType->isFunctionType(); 11185 } 11186 11187 // [ToType] [Return] 11188 11189 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11190 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11191 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11192 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11193 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11194 } 11195 11196 // return true if any matching specializations were found 11197 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11198 const DeclAccessPair& CurAccessFunPair) { 11199 if (CXXMethodDecl *Method 11200 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11201 // Skip non-static function templates when converting to pointer, and 11202 // static when converting to member pointer. 11203 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11204 return false; 11205 } 11206 else if (TargetTypeIsNonStaticMemberFunction) 11207 return false; 11208 11209 // C++ [over.over]p2: 11210 // If the name is a function template, template argument deduction is 11211 // done (14.8.2.2), and if the argument deduction succeeds, the 11212 // resulting template argument list is used to generate a single 11213 // function template specialization, which is added to the set of 11214 // overloaded functions considered. 11215 FunctionDecl *Specialization = nullptr; 11216 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11217 if (Sema::TemplateDeductionResult Result 11218 = S.DeduceTemplateArguments(FunctionTemplate, 11219 &OvlExplicitTemplateArgs, 11220 TargetFunctionType, Specialization, 11221 Info, /*IsAddressOfFunction*/true)) { 11222 // Make a note of the failed deduction for diagnostics. 11223 FailedCandidates.addCandidate() 11224 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11225 MakeDeductionFailureInfo(Context, Result, Info)); 11226 return false; 11227 } 11228 11229 // Template argument deduction ensures that we have an exact match or 11230 // compatible pointer-to-function arguments that would be adjusted by ICS. 11231 // This function template specicalization works. 11232 assert(S.isSameOrCompatibleFunctionType( 11233 Context.getCanonicalType(Specialization->getType()), 11234 Context.getCanonicalType(TargetFunctionType))); 11235 11236 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11237 return false; 11238 11239 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11240 return true; 11241 } 11242 11243 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11244 const DeclAccessPair& CurAccessFunPair) { 11245 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11246 // Skip non-static functions when converting to pointer, and static 11247 // when converting to member pointer. 11248 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11249 return false; 11250 } 11251 else if (TargetTypeIsNonStaticMemberFunction) 11252 return false; 11253 11254 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11255 if (S.getLangOpts().CUDA) 11256 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11257 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11258 return false; 11259 if (FunDecl->isMultiVersion()) { 11260 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11261 if (TA && !TA->isDefaultVersion()) 11262 return false; 11263 } 11264 11265 // If any candidate has a placeholder return type, trigger its deduction 11266 // now. 11267 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11268 Complain)) { 11269 HasComplained |= Complain; 11270 return false; 11271 } 11272 11273 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11274 return false; 11275 11276 // If we're in C, we need to support types that aren't exactly identical. 11277 if (!S.getLangOpts().CPlusPlus || 11278 candidateHasExactlyCorrectType(FunDecl)) { 11279 Matches.push_back(std::make_pair( 11280 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11281 FoundNonTemplateFunction = true; 11282 return true; 11283 } 11284 } 11285 11286 return false; 11287 } 11288 11289 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11290 bool Ret = false; 11291 11292 // If the overload expression doesn't have the form of a pointer to 11293 // member, don't try to convert it to a pointer-to-member type. 11294 if (IsInvalidFormOfPointerToMemberFunction()) 11295 return false; 11296 11297 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11298 E = OvlExpr->decls_end(); 11299 I != E; ++I) { 11300 // Look through any using declarations to find the underlying function. 11301 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11302 11303 // C++ [over.over]p3: 11304 // Non-member functions and static member functions match 11305 // targets of type "pointer-to-function" or "reference-to-function." 11306 // Nonstatic member functions match targets of 11307 // type "pointer-to-member-function." 11308 // Note that according to DR 247, the containing class does not matter. 11309 if (FunctionTemplateDecl *FunctionTemplate 11310 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11311 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11312 Ret = true; 11313 } 11314 // If we have explicit template arguments supplied, skip non-templates. 11315 else if (!OvlExpr->hasExplicitTemplateArgs() && 11316 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11317 Ret = true; 11318 } 11319 assert(Ret || Matches.empty()); 11320 return Ret; 11321 } 11322 11323 void EliminateAllExceptMostSpecializedTemplate() { 11324 // [...] and any given function template specialization F1 is 11325 // eliminated if the set contains a second function template 11326 // specialization whose function template is more specialized 11327 // than the function template of F1 according to the partial 11328 // ordering rules of 14.5.5.2. 11329 11330 // The algorithm specified above is quadratic. We instead use a 11331 // two-pass algorithm (similar to the one used to identify the 11332 // best viable function in an overload set) that identifies the 11333 // best function template (if it exists). 11334 11335 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11336 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11337 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11338 11339 // TODO: It looks like FailedCandidates does not serve much purpose 11340 // here, since the no_viable diagnostic has index 0. 11341 UnresolvedSetIterator Result = S.getMostSpecialized( 11342 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11343 SourceExpr->getBeginLoc(), S.PDiag(), 11344 S.PDiag(diag::err_addr_ovl_ambiguous) 11345 << Matches[0].second->getDeclName(), 11346 S.PDiag(diag::note_ovl_candidate) 11347 << (unsigned)oc_function << (unsigned)ocs_described_template, 11348 Complain, TargetFunctionType); 11349 11350 if (Result != MatchesCopy.end()) { 11351 // Make it the first and only element 11352 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11353 Matches[0].second = cast<FunctionDecl>(*Result); 11354 Matches.resize(1); 11355 } else 11356 HasComplained |= Complain; 11357 } 11358 11359 void EliminateAllTemplateMatches() { 11360 // [...] any function template specializations in the set are 11361 // eliminated if the set also contains a non-template function, [...] 11362 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11363 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11364 ++I; 11365 else { 11366 Matches[I] = Matches[--N]; 11367 Matches.resize(N); 11368 } 11369 } 11370 } 11371 11372 void EliminateSuboptimalCudaMatches() { 11373 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11374 } 11375 11376 public: 11377 void ComplainNoMatchesFound() const { 11378 assert(Matches.empty()); 11379 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11380 << OvlExpr->getName() << TargetFunctionType 11381 << OvlExpr->getSourceRange(); 11382 if (FailedCandidates.empty()) 11383 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11384 /*TakingAddress=*/true); 11385 else { 11386 // We have some deduction failure messages. Use them to diagnose 11387 // the function templates, and diagnose the non-template candidates 11388 // normally. 11389 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11390 IEnd = OvlExpr->decls_end(); 11391 I != IEnd; ++I) 11392 if (FunctionDecl *Fun = 11393 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11394 if (!functionHasPassObjectSizeParams(Fun)) 11395 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11396 /*TakingAddress=*/true); 11397 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11398 } 11399 } 11400 11401 bool IsInvalidFormOfPointerToMemberFunction() const { 11402 return TargetTypeIsNonStaticMemberFunction && 11403 !OvlExprInfo.HasFormOfMemberPointer; 11404 } 11405 11406 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11407 // TODO: Should we condition this on whether any functions might 11408 // have matched, or is it more appropriate to do that in callers? 11409 // TODO: a fixit wouldn't hurt. 11410 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11411 << TargetType << OvlExpr->getSourceRange(); 11412 } 11413 11414 bool IsStaticMemberFunctionFromBoundPointer() const { 11415 return StaticMemberFunctionFromBoundPointer; 11416 } 11417 11418 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11419 S.Diag(OvlExpr->getBeginLoc(), 11420 diag::err_invalid_form_pointer_member_function) 11421 << OvlExpr->getSourceRange(); 11422 } 11423 11424 void ComplainOfInvalidConversion() const { 11425 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11426 << OvlExpr->getName() << TargetType; 11427 } 11428 11429 void ComplainMultipleMatchesFound() const { 11430 assert(Matches.size() > 1); 11431 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11432 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11433 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11434 /*TakingAddress=*/true); 11435 } 11436 11437 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11438 11439 int getNumMatches() const { return Matches.size(); } 11440 11441 FunctionDecl* getMatchingFunctionDecl() const { 11442 if (Matches.size() != 1) return nullptr; 11443 return Matches[0].second; 11444 } 11445 11446 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11447 if (Matches.size() != 1) return nullptr; 11448 return &Matches[0].first; 11449 } 11450 }; 11451 } 11452 11453 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11454 /// an overloaded function (C++ [over.over]), where @p From is an 11455 /// expression with overloaded function type and @p ToType is the type 11456 /// we're trying to resolve to. For example: 11457 /// 11458 /// @code 11459 /// int f(double); 11460 /// int f(int); 11461 /// 11462 /// int (*pfd)(double) = f; // selects f(double) 11463 /// @endcode 11464 /// 11465 /// This routine returns the resulting FunctionDecl if it could be 11466 /// resolved, and NULL otherwise. When @p Complain is true, this 11467 /// routine will emit diagnostics if there is an error. 11468 FunctionDecl * 11469 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11470 QualType TargetType, 11471 bool Complain, 11472 DeclAccessPair &FoundResult, 11473 bool *pHadMultipleCandidates) { 11474 assert(AddressOfExpr->getType() == Context.OverloadTy); 11475 11476 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11477 Complain); 11478 int NumMatches = Resolver.getNumMatches(); 11479 FunctionDecl *Fn = nullptr; 11480 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11481 if (NumMatches == 0 && ShouldComplain) { 11482 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11483 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11484 else 11485 Resolver.ComplainNoMatchesFound(); 11486 } 11487 else if (NumMatches > 1 && ShouldComplain) 11488 Resolver.ComplainMultipleMatchesFound(); 11489 else if (NumMatches == 1) { 11490 Fn = Resolver.getMatchingFunctionDecl(); 11491 assert(Fn); 11492 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11493 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11494 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11495 if (Complain) { 11496 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11497 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11498 else 11499 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11500 } 11501 } 11502 11503 if (pHadMultipleCandidates) 11504 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11505 return Fn; 11506 } 11507 11508 /// Given an expression that refers to an overloaded function, try to 11509 /// resolve that function to a single function that can have its address taken. 11510 /// This will modify `Pair` iff it returns non-null. 11511 /// 11512 /// This routine can only realistically succeed if all but one candidates in the 11513 /// overload set for SrcExpr cannot have their addresses taken. 11514 FunctionDecl * 11515 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11516 DeclAccessPair &Pair) { 11517 OverloadExpr::FindResult R = OverloadExpr::find(E); 11518 OverloadExpr *Ovl = R.Expression; 11519 FunctionDecl *Result = nullptr; 11520 DeclAccessPair DAP; 11521 // Don't use the AddressOfResolver because we're specifically looking for 11522 // cases where we have one overload candidate that lacks 11523 // enable_if/pass_object_size/... 11524 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11525 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11526 if (!FD) 11527 return nullptr; 11528 11529 if (!checkAddressOfFunctionIsAvailable(FD)) 11530 continue; 11531 11532 // We have more than one result; quit. 11533 if (Result) 11534 return nullptr; 11535 DAP = I.getPair(); 11536 Result = FD; 11537 } 11538 11539 if (Result) 11540 Pair = DAP; 11541 return Result; 11542 } 11543 11544 /// Given an overloaded function, tries to turn it into a non-overloaded 11545 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11546 /// will perform access checks, diagnose the use of the resultant decl, and, if 11547 /// requested, potentially perform a function-to-pointer decay. 11548 /// 11549 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11550 /// Otherwise, returns true. This may emit diagnostics and return true. 11551 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11552 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11553 Expr *E = SrcExpr.get(); 11554 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11555 11556 DeclAccessPair DAP; 11557 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11558 if (!Found || Found->isCPUDispatchMultiVersion() || 11559 Found->isCPUSpecificMultiVersion()) 11560 return false; 11561 11562 // Emitting multiple diagnostics for a function that is both inaccessible and 11563 // unavailable is consistent with our behavior elsewhere. So, always check 11564 // for both. 11565 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11566 CheckAddressOfMemberAccess(E, DAP); 11567 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11568 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11569 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11570 else 11571 SrcExpr = Fixed; 11572 return true; 11573 } 11574 11575 /// Given an expression that refers to an overloaded function, try to 11576 /// resolve that overloaded function expression down to a single function. 11577 /// 11578 /// This routine can only resolve template-ids that refer to a single function 11579 /// template, where that template-id refers to a single template whose template 11580 /// arguments are either provided by the template-id or have defaults, 11581 /// as described in C++0x [temp.arg.explicit]p3. 11582 /// 11583 /// If no template-ids are found, no diagnostics are emitted and NULL is 11584 /// returned. 11585 FunctionDecl * 11586 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11587 bool Complain, 11588 DeclAccessPair *FoundResult) { 11589 // C++ [over.over]p1: 11590 // [...] [Note: any redundant set of parentheses surrounding the 11591 // overloaded function name is ignored (5.1). ] 11592 // C++ [over.over]p1: 11593 // [...] The overloaded function name can be preceded by the & 11594 // operator. 11595 11596 // If we didn't actually find any template-ids, we're done. 11597 if (!ovl->hasExplicitTemplateArgs()) 11598 return nullptr; 11599 11600 TemplateArgumentListInfo ExplicitTemplateArgs; 11601 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11602 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11603 11604 // Look through all of the overloaded functions, searching for one 11605 // whose type matches exactly. 11606 FunctionDecl *Matched = nullptr; 11607 for (UnresolvedSetIterator I = ovl->decls_begin(), 11608 E = ovl->decls_end(); I != E; ++I) { 11609 // C++0x [temp.arg.explicit]p3: 11610 // [...] In contexts where deduction is done and fails, or in contexts 11611 // where deduction is not done, if a template argument list is 11612 // specified and it, along with any default template arguments, 11613 // identifies a single function template specialization, then the 11614 // template-id is an lvalue for the function template specialization. 11615 FunctionTemplateDecl *FunctionTemplate 11616 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11617 11618 // C++ [over.over]p2: 11619 // If the name is a function template, template argument deduction is 11620 // done (14.8.2.2), and if the argument deduction succeeds, the 11621 // resulting template argument list is used to generate a single 11622 // function template specialization, which is added to the set of 11623 // overloaded functions considered. 11624 FunctionDecl *Specialization = nullptr; 11625 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11626 if (TemplateDeductionResult Result 11627 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11628 Specialization, Info, 11629 /*IsAddressOfFunction*/true)) { 11630 // Make a note of the failed deduction for diagnostics. 11631 // TODO: Actually use the failed-deduction info? 11632 FailedCandidates.addCandidate() 11633 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11634 MakeDeductionFailureInfo(Context, Result, Info)); 11635 continue; 11636 } 11637 11638 assert(Specialization && "no specialization and no error?"); 11639 11640 // Multiple matches; we can't resolve to a single declaration. 11641 if (Matched) { 11642 if (Complain) { 11643 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11644 << ovl->getName(); 11645 NoteAllOverloadCandidates(ovl); 11646 } 11647 return nullptr; 11648 } 11649 11650 Matched = Specialization; 11651 if (FoundResult) *FoundResult = I.getPair(); 11652 } 11653 11654 if (Matched && 11655 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11656 return nullptr; 11657 11658 return Matched; 11659 } 11660 11661 // Resolve and fix an overloaded expression that can be resolved 11662 // because it identifies a single function template specialization. 11663 // 11664 // Last three arguments should only be supplied if Complain = true 11665 // 11666 // Return true if it was logically possible to so resolve the 11667 // expression, regardless of whether or not it succeeded. Always 11668 // returns true if 'complain' is set. 11669 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11670 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11671 bool complain, SourceRange OpRangeForComplaining, 11672 QualType DestTypeForComplaining, 11673 unsigned DiagIDForComplaining) { 11674 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11675 11676 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11677 11678 DeclAccessPair found; 11679 ExprResult SingleFunctionExpression; 11680 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11681 ovl.Expression, /*complain*/ false, &found)) { 11682 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11683 SrcExpr = ExprError(); 11684 return true; 11685 } 11686 11687 // It is only correct to resolve to an instance method if we're 11688 // resolving a form that's permitted to be a pointer to member. 11689 // Otherwise we'll end up making a bound member expression, which 11690 // is illegal in all the contexts we resolve like this. 11691 if (!ovl.HasFormOfMemberPointer && 11692 isa<CXXMethodDecl>(fn) && 11693 cast<CXXMethodDecl>(fn)->isInstance()) { 11694 if (!complain) return false; 11695 11696 Diag(ovl.Expression->getExprLoc(), 11697 diag::err_bound_member_function) 11698 << 0 << ovl.Expression->getSourceRange(); 11699 11700 // TODO: I believe we only end up here if there's a mix of 11701 // static and non-static candidates (otherwise the expression 11702 // would have 'bound member' type, not 'overload' type). 11703 // Ideally we would note which candidate was chosen and why 11704 // the static candidates were rejected. 11705 SrcExpr = ExprError(); 11706 return true; 11707 } 11708 11709 // Fix the expression to refer to 'fn'. 11710 SingleFunctionExpression = 11711 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11712 11713 // If desired, do function-to-pointer decay. 11714 if (doFunctionPointerConverion) { 11715 SingleFunctionExpression = 11716 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11717 if (SingleFunctionExpression.isInvalid()) { 11718 SrcExpr = ExprError(); 11719 return true; 11720 } 11721 } 11722 } 11723 11724 if (!SingleFunctionExpression.isUsable()) { 11725 if (complain) { 11726 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11727 << ovl.Expression->getName() 11728 << DestTypeForComplaining 11729 << OpRangeForComplaining 11730 << ovl.Expression->getQualifierLoc().getSourceRange(); 11731 NoteAllOverloadCandidates(SrcExpr.get()); 11732 11733 SrcExpr = ExprError(); 11734 return true; 11735 } 11736 11737 return false; 11738 } 11739 11740 SrcExpr = SingleFunctionExpression; 11741 return true; 11742 } 11743 11744 /// Add a single candidate to the overload set. 11745 static void AddOverloadedCallCandidate(Sema &S, 11746 DeclAccessPair FoundDecl, 11747 TemplateArgumentListInfo *ExplicitTemplateArgs, 11748 ArrayRef<Expr *> Args, 11749 OverloadCandidateSet &CandidateSet, 11750 bool PartialOverloading, 11751 bool KnownValid) { 11752 NamedDecl *Callee = FoundDecl.getDecl(); 11753 if (isa<UsingShadowDecl>(Callee)) 11754 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11755 11756 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11757 if (ExplicitTemplateArgs) { 11758 assert(!KnownValid && "Explicit template arguments?"); 11759 return; 11760 } 11761 // Prevent ill-formed function decls to be added as overload candidates. 11762 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11763 return; 11764 11765 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11766 /*SuppressUsedConversions=*/false, 11767 PartialOverloading); 11768 return; 11769 } 11770 11771 if (FunctionTemplateDecl *FuncTemplate 11772 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11773 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11774 ExplicitTemplateArgs, Args, CandidateSet, 11775 /*SuppressUsedConversions=*/false, 11776 PartialOverloading); 11777 return; 11778 } 11779 11780 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11781 } 11782 11783 /// Add the overload candidates named by callee and/or found by argument 11784 /// dependent lookup to the given overload set. 11785 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11786 ArrayRef<Expr *> Args, 11787 OverloadCandidateSet &CandidateSet, 11788 bool PartialOverloading) { 11789 11790 #ifndef NDEBUG 11791 // Verify that ArgumentDependentLookup is consistent with the rules 11792 // in C++0x [basic.lookup.argdep]p3: 11793 // 11794 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11795 // and let Y be the lookup set produced by argument dependent 11796 // lookup (defined as follows). If X contains 11797 // 11798 // -- a declaration of a class member, or 11799 // 11800 // -- a block-scope function declaration that is not a 11801 // using-declaration, or 11802 // 11803 // -- a declaration that is neither a function or a function 11804 // template 11805 // 11806 // then Y is empty. 11807 11808 if (ULE->requiresADL()) { 11809 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11810 E = ULE->decls_end(); I != E; ++I) { 11811 assert(!(*I)->getDeclContext()->isRecord()); 11812 assert(isa<UsingShadowDecl>(*I) || 11813 !(*I)->getDeclContext()->isFunctionOrMethod()); 11814 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11815 } 11816 } 11817 #endif 11818 11819 // It would be nice to avoid this copy. 11820 TemplateArgumentListInfo TABuffer; 11821 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11822 if (ULE->hasExplicitTemplateArgs()) { 11823 ULE->copyTemplateArgumentsInto(TABuffer); 11824 ExplicitTemplateArgs = &TABuffer; 11825 } 11826 11827 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11828 E = ULE->decls_end(); I != E; ++I) 11829 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11830 CandidateSet, PartialOverloading, 11831 /*KnownValid*/ true); 11832 11833 if (ULE->requiresADL()) 11834 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11835 Args, ExplicitTemplateArgs, 11836 CandidateSet, PartialOverloading); 11837 } 11838 11839 /// Determine whether a declaration with the specified name could be moved into 11840 /// a different namespace. 11841 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11842 switch (Name.getCXXOverloadedOperator()) { 11843 case OO_New: case OO_Array_New: 11844 case OO_Delete: case OO_Array_Delete: 11845 return false; 11846 11847 default: 11848 return true; 11849 } 11850 } 11851 11852 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11853 /// template, where the non-dependent name was declared after the template 11854 /// was defined. This is common in code written for a compilers which do not 11855 /// correctly implement two-stage name lookup. 11856 /// 11857 /// Returns true if a viable candidate was found and a diagnostic was issued. 11858 static bool 11859 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11860 const CXXScopeSpec &SS, LookupResult &R, 11861 OverloadCandidateSet::CandidateSetKind CSK, 11862 TemplateArgumentListInfo *ExplicitTemplateArgs, 11863 ArrayRef<Expr *> Args, 11864 bool *DoDiagnoseEmptyLookup = nullptr) { 11865 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 11866 return false; 11867 11868 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11869 if (DC->isTransparentContext()) 11870 continue; 11871 11872 SemaRef.LookupQualifiedName(R, DC); 11873 11874 if (!R.empty()) { 11875 R.suppressDiagnostics(); 11876 11877 if (isa<CXXRecordDecl>(DC)) { 11878 // Don't diagnose names we find in classes; we get much better 11879 // diagnostics for these from DiagnoseEmptyLookup. 11880 R.clear(); 11881 if (DoDiagnoseEmptyLookup) 11882 *DoDiagnoseEmptyLookup = true; 11883 return false; 11884 } 11885 11886 OverloadCandidateSet Candidates(FnLoc, CSK); 11887 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11888 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11889 ExplicitTemplateArgs, Args, 11890 Candidates, false, /*KnownValid*/ false); 11891 11892 OverloadCandidateSet::iterator Best; 11893 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11894 // No viable functions. Don't bother the user with notes for functions 11895 // which don't work and shouldn't be found anyway. 11896 R.clear(); 11897 return false; 11898 } 11899 11900 // Find the namespaces where ADL would have looked, and suggest 11901 // declaring the function there instead. 11902 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11903 Sema::AssociatedClassSet AssociatedClasses; 11904 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11905 AssociatedNamespaces, 11906 AssociatedClasses); 11907 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11908 if (canBeDeclaredInNamespace(R.getLookupName())) { 11909 DeclContext *Std = SemaRef.getStdNamespace(); 11910 for (Sema::AssociatedNamespaceSet::iterator 11911 it = AssociatedNamespaces.begin(), 11912 end = AssociatedNamespaces.end(); it != end; ++it) { 11913 // Never suggest declaring a function within namespace 'std'. 11914 if (Std && Std->Encloses(*it)) 11915 continue; 11916 11917 // Never suggest declaring a function within a namespace with a 11918 // reserved name, like __gnu_cxx. 11919 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11920 if (NS && 11921 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11922 continue; 11923 11924 SuggestedNamespaces.insert(*it); 11925 } 11926 } 11927 11928 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11929 << R.getLookupName(); 11930 if (SuggestedNamespaces.empty()) { 11931 SemaRef.Diag(Best->Function->getLocation(), 11932 diag::note_not_found_by_two_phase_lookup) 11933 << R.getLookupName() << 0; 11934 } else if (SuggestedNamespaces.size() == 1) { 11935 SemaRef.Diag(Best->Function->getLocation(), 11936 diag::note_not_found_by_two_phase_lookup) 11937 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11938 } else { 11939 // FIXME: It would be useful to list the associated namespaces here, 11940 // but the diagnostics infrastructure doesn't provide a way to produce 11941 // a localized representation of a list of items. 11942 SemaRef.Diag(Best->Function->getLocation(), 11943 diag::note_not_found_by_two_phase_lookup) 11944 << R.getLookupName() << 2; 11945 } 11946 11947 // Try to recover by calling this function. 11948 return true; 11949 } 11950 11951 R.clear(); 11952 } 11953 11954 return false; 11955 } 11956 11957 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11958 /// template, where the non-dependent operator was declared after the template 11959 /// was defined. 11960 /// 11961 /// Returns true if a viable candidate was found and a diagnostic was issued. 11962 static bool 11963 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11964 SourceLocation OpLoc, 11965 ArrayRef<Expr *> Args) { 11966 DeclarationName OpName = 11967 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11968 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11969 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11970 OverloadCandidateSet::CSK_Operator, 11971 /*ExplicitTemplateArgs=*/nullptr, Args); 11972 } 11973 11974 namespace { 11975 class BuildRecoveryCallExprRAII { 11976 Sema &SemaRef; 11977 public: 11978 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11979 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11980 SemaRef.IsBuildingRecoveryCallExpr = true; 11981 } 11982 11983 ~BuildRecoveryCallExprRAII() { 11984 SemaRef.IsBuildingRecoveryCallExpr = false; 11985 } 11986 }; 11987 11988 } 11989 11990 /// Attempts to recover from a call where no functions were found. 11991 /// 11992 /// Returns true if new candidates were found. 11993 static ExprResult 11994 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11995 UnresolvedLookupExpr *ULE, 11996 SourceLocation LParenLoc, 11997 MutableArrayRef<Expr *> Args, 11998 SourceLocation RParenLoc, 11999 bool EmptyLookup, bool AllowTypoCorrection) { 12000 // Do not try to recover if it is already building a recovery call. 12001 // This stops infinite loops for template instantiations like 12002 // 12003 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12004 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12005 // 12006 if (SemaRef.IsBuildingRecoveryCallExpr) 12007 return ExprError(); 12008 BuildRecoveryCallExprRAII RCE(SemaRef); 12009 12010 CXXScopeSpec SS; 12011 SS.Adopt(ULE->getQualifierLoc()); 12012 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12013 12014 TemplateArgumentListInfo TABuffer; 12015 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12016 if (ULE->hasExplicitTemplateArgs()) { 12017 ULE->copyTemplateArgumentsInto(TABuffer); 12018 ExplicitTemplateArgs = &TABuffer; 12019 } 12020 12021 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12022 Sema::LookupOrdinaryName); 12023 bool DoDiagnoseEmptyLookup = EmptyLookup; 12024 if (!DiagnoseTwoPhaseLookup( 12025 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12026 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12027 NoTypoCorrectionCCC NoTypoValidator{}; 12028 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12029 ExplicitTemplateArgs != nullptr, 12030 dyn_cast<MemberExpr>(Fn)); 12031 CorrectionCandidateCallback &Validator = 12032 AllowTypoCorrection 12033 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12034 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12035 if (!DoDiagnoseEmptyLookup || 12036 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12037 Args)) 12038 return ExprError(); 12039 } 12040 12041 assert(!R.empty() && "lookup results empty despite recovery"); 12042 12043 // If recovery created an ambiguity, just bail out. 12044 if (R.isAmbiguous()) { 12045 R.suppressDiagnostics(); 12046 return ExprError(); 12047 } 12048 12049 // Build an implicit member call if appropriate. Just drop the 12050 // casts and such from the call, we don't really care. 12051 ExprResult NewFn = ExprError(); 12052 if ((*R.begin())->isCXXClassMember()) 12053 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12054 ExplicitTemplateArgs, S); 12055 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12056 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12057 ExplicitTemplateArgs); 12058 else 12059 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12060 12061 if (NewFn.isInvalid()) 12062 return ExprError(); 12063 12064 // This shouldn't cause an infinite loop because we're giving it 12065 // an expression with viable lookup results, which should never 12066 // end up here. 12067 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12068 MultiExprArg(Args.data(), Args.size()), 12069 RParenLoc); 12070 } 12071 12072 /// Constructs and populates an OverloadedCandidateSet from 12073 /// the given function. 12074 /// \returns true when an the ExprResult output parameter has been set. 12075 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12076 UnresolvedLookupExpr *ULE, 12077 MultiExprArg Args, 12078 SourceLocation RParenLoc, 12079 OverloadCandidateSet *CandidateSet, 12080 ExprResult *Result) { 12081 #ifndef NDEBUG 12082 if (ULE->requiresADL()) { 12083 // To do ADL, we must have found an unqualified name. 12084 assert(!ULE->getQualifier() && "qualified name with ADL"); 12085 12086 // We don't perform ADL for implicit declarations of builtins. 12087 // Verify that this was correctly set up. 12088 FunctionDecl *F; 12089 if (ULE->decls_begin() != ULE->decls_end() && 12090 ULE->decls_begin() + 1 == ULE->decls_end() && 12091 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12092 F->getBuiltinID() && F->isImplicit()) 12093 llvm_unreachable("performing ADL for builtin"); 12094 12095 // We don't perform ADL in C. 12096 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12097 } 12098 #endif 12099 12100 UnbridgedCastsSet UnbridgedCasts; 12101 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12102 *Result = ExprError(); 12103 return true; 12104 } 12105 12106 // Add the functions denoted by the callee to the set of candidate 12107 // functions, including those from argument-dependent lookup. 12108 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12109 12110 if (getLangOpts().MSVCCompat && 12111 CurContext->isDependentContext() && !isSFINAEContext() && 12112 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12113 12114 OverloadCandidateSet::iterator Best; 12115 if (CandidateSet->empty() || 12116 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12117 OR_No_Viable_Function) { 12118 // In Microsoft mode, if we are inside a template class member function 12119 // then create a type dependent CallExpr. The goal is to postpone name 12120 // lookup to instantiation time to be able to search into type dependent 12121 // base classes. 12122 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12123 VK_RValue, RParenLoc); 12124 CE->setTypeDependent(true); 12125 CE->setValueDependent(true); 12126 CE->setInstantiationDependent(true); 12127 *Result = CE; 12128 return true; 12129 } 12130 } 12131 12132 if (CandidateSet->empty()) 12133 return false; 12134 12135 UnbridgedCasts.restore(); 12136 return false; 12137 } 12138 12139 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12140 /// the completed call expression. If overload resolution fails, emits 12141 /// diagnostics and returns ExprError() 12142 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12143 UnresolvedLookupExpr *ULE, 12144 SourceLocation LParenLoc, 12145 MultiExprArg Args, 12146 SourceLocation RParenLoc, 12147 Expr *ExecConfig, 12148 OverloadCandidateSet *CandidateSet, 12149 OverloadCandidateSet::iterator *Best, 12150 OverloadingResult OverloadResult, 12151 bool AllowTypoCorrection) { 12152 if (CandidateSet->empty()) 12153 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12154 RParenLoc, /*EmptyLookup=*/true, 12155 AllowTypoCorrection); 12156 12157 switch (OverloadResult) { 12158 case OR_Success: { 12159 FunctionDecl *FDecl = (*Best)->Function; 12160 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12161 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12162 return ExprError(); 12163 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12164 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12165 ExecConfig, /*IsExecConfig=*/false, 12166 (*Best)->IsADLCandidate); 12167 } 12168 12169 case OR_No_Viable_Function: { 12170 // Try to recover by looking for viable functions which the user might 12171 // have meant to call. 12172 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12173 Args, RParenLoc, 12174 /*EmptyLookup=*/false, 12175 AllowTypoCorrection); 12176 if (!Recovery.isInvalid()) 12177 return Recovery; 12178 12179 // If the user passes in a function that we can't take the address of, we 12180 // generally end up emitting really bad error messages. Here, we attempt to 12181 // emit better ones. 12182 for (const Expr *Arg : Args) { 12183 if (!Arg->getType()->isFunctionType()) 12184 continue; 12185 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12186 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12187 if (FD && 12188 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12189 Arg->getExprLoc())) 12190 return ExprError(); 12191 } 12192 } 12193 12194 CandidateSet->NoteCandidates( 12195 PartialDiagnosticAt( 12196 Fn->getBeginLoc(), 12197 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12198 << ULE->getName() << Fn->getSourceRange()), 12199 SemaRef, OCD_AllCandidates, Args); 12200 break; 12201 } 12202 12203 case OR_Ambiguous: 12204 CandidateSet->NoteCandidates( 12205 PartialDiagnosticAt(Fn->getBeginLoc(), 12206 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12207 << ULE->getName() << Fn->getSourceRange()), 12208 SemaRef, OCD_ViableCandidates, Args); 12209 break; 12210 12211 case OR_Deleted: { 12212 CandidateSet->NoteCandidates( 12213 PartialDiagnosticAt(Fn->getBeginLoc(), 12214 SemaRef.PDiag(diag::err_ovl_deleted_call) 12215 << ULE->getName() << Fn->getSourceRange()), 12216 SemaRef, OCD_AllCandidates, Args); 12217 12218 // We emitted an error for the unavailable/deleted function call but keep 12219 // the call in the AST. 12220 FunctionDecl *FDecl = (*Best)->Function; 12221 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12222 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12223 ExecConfig, /*IsExecConfig=*/false, 12224 (*Best)->IsADLCandidate); 12225 } 12226 } 12227 12228 // Overload resolution failed. 12229 return ExprError(); 12230 } 12231 12232 static void markUnaddressableCandidatesUnviable(Sema &S, 12233 OverloadCandidateSet &CS) { 12234 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12235 if (I->Viable && 12236 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12237 I->Viable = false; 12238 I->FailureKind = ovl_fail_addr_not_available; 12239 } 12240 } 12241 } 12242 12243 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12244 /// (which eventually refers to the declaration Func) and the call 12245 /// arguments Args/NumArgs, attempt to resolve the function call down 12246 /// to a specific function. If overload resolution succeeds, returns 12247 /// the call expression produced by overload resolution. 12248 /// Otherwise, emits diagnostics and returns ExprError. 12249 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12250 UnresolvedLookupExpr *ULE, 12251 SourceLocation LParenLoc, 12252 MultiExprArg Args, 12253 SourceLocation RParenLoc, 12254 Expr *ExecConfig, 12255 bool AllowTypoCorrection, 12256 bool CalleesAddressIsTaken) { 12257 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12258 OverloadCandidateSet::CSK_Normal); 12259 ExprResult result; 12260 12261 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12262 &result)) 12263 return result; 12264 12265 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12266 // functions that aren't addressible are considered unviable. 12267 if (CalleesAddressIsTaken) 12268 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12269 12270 OverloadCandidateSet::iterator Best; 12271 OverloadingResult OverloadResult = 12272 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12273 12274 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 12275 ExecConfig, &CandidateSet, &Best, 12276 OverloadResult, AllowTypoCorrection); 12277 } 12278 12279 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12280 return Functions.size() > 1 || 12281 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12282 } 12283 12284 /// Create a unary operation that may resolve to an overloaded 12285 /// operator. 12286 /// 12287 /// \param OpLoc The location of the operator itself (e.g., '*'). 12288 /// 12289 /// \param Opc The UnaryOperatorKind that describes this operator. 12290 /// 12291 /// \param Fns The set of non-member functions that will be 12292 /// considered by overload resolution. The caller needs to build this 12293 /// set based on the context using, e.g., 12294 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12295 /// set should not contain any member functions; those will be added 12296 /// by CreateOverloadedUnaryOp(). 12297 /// 12298 /// \param Input The input argument. 12299 ExprResult 12300 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12301 const UnresolvedSetImpl &Fns, 12302 Expr *Input, bool PerformADL) { 12303 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12304 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12305 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12306 // TODO: provide better source location info. 12307 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12308 12309 if (checkPlaceholderForOverload(*this, Input)) 12310 return ExprError(); 12311 12312 Expr *Args[2] = { Input, nullptr }; 12313 unsigned NumArgs = 1; 12314 12315 // For post-increment and post-decrement, add the implicit '0' as 12316 // the second argument, so that we know this is a post-increment or 12317 // post-decrement. 12318 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12319 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12320 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12321 SourceLocation()); 12322 NumArgs = 2; 12323 } 12324 12325 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12326 12327 if (Input->isTypeDependent()) { 12328 if (Fns.empty()) 12329 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12330 VK_RValue, OK_Ordinary, OpLoc, false); 12331 12332 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12333 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12334 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12335 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12336 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12337 Context.DependentTy, VK_RValue, OpLoc, 12338 FPOptions()); 12339 } 12340 12341 // Build an empty overload set. 12342 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12343 12344 // Add the candidates from the given function set. 12345 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 12346 12347 // Add operator candidates that are member functions. 12348 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12349 12350 // Add candidates from ADL. 12351 if (PerformADL) { 12352 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12353 /*ExplicitTemplateArgs*/nullptr, 12354 CandidateSet); 12355 } 12356 12357 // Add builtin operator candidates. 12358 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12359 12360 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12361 12362 // Perform overload resolution. 12363 OverloadCandidateSet::iterator Best; 12364 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12365 case OR_Success: { 12366 // We found a built-in operator or an overloaded operator. 12367 FunctionDecl *FnDecl = Best->Function; 12368 12369 if (FnDecl) { 12370 Expr *Base = nullptr; 12371 // We matched an overloaded operator. Build a call to that 12372 // operator. 12373 12374 // Convert the arguments. 12375 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12376 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12377 12378 ExprResult InputRes = 12379 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12380 Best->FoundDecl, Method); 12381 if (InputRes.isInvalid()) 12382 return ExprError(); 12383 Base = Input = InputRes.get(); 12384 } else { 12385 // Convert the arguments. 12386 ExprResult InputInit 12387 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12388 Context, 12389 FnDecl->getParamDecl(0)), 12390 SourceLocation(), 12391 Input); 12392 if (InputInit.isInvalid()) 12393 return ExprError(); 12394 Input = InputInit.get(); 12395 } 12396 12397 // Build the actual expression node. 12398 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12399 Base, HadMultipleCandidates, 12400 OpLoc); 12401 if (FnExpr.isInvalid()) 12402 return ExprError(); 12403 12404 // Determine the result type. 12405 QualType ResultTy = FnDecl->getReturnType(); 12406 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12407 ResultTy = ResultTy.getNonLValueExprType(Context); 12408 12409 Args[0] = Input; 12410 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12411 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 12412 FPOptions(), Best->IsADLCandidate); 12413 12414 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12415 return ExprError(); 12416 12417 if (CheckFunctionCall(FnDecl, TheCall, 12418 FnDecl->getType()->castAs<FunctionProtoType>())) 12419 return ExprError(); 12420 12421 return MaybeBindToTemporary(TheCall); 12422 } else { 12423 // We matched a built-in operator. Convert the arguments, then 12424 // break out so that we will build the appropriate built-in 12425 // operator node. 12426 ExprResult InputRes = PerformImplicitConversion( 12427 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12428 CCK_ForBuiltinOverloadedOp); 12429 if (InputRes.isInvalid()) 12430 return ExprError(); 12431 Input = InputRes.get(); 12432 break; 12433 } 12434 } 12435 12436 case OR_No_Viable_Function: 12437 // This is an erroneous use of an operator which can be overloaded by 12438 // a non-member function. Check for non-member operators which were 12439 // defined too late to be candidates. 12440 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12441 // FIXME: Recover by calling the found function. 12442 return ExprError(); 12443 12444 // No viable function; fall through to handling this as a 12445 // built-in operator, which will produce an error message for us. 12446 break; 12447 12448 case OR_Ambiguous: 12449 CandidateSet.NoteCandidates( 12450 PartialDiagnosticAt(OpLoc, 12451 PDiag(diag::err_ovl_ambiguous_oper_unary) 12452 << UnaryOperator::getOpcodeStr(Opc) 12453 << Input->getType() << Input->getSourceRange()), 12454 *this, OCD_ViableCandidates, ArgsArray, 12455 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12456 return ExprError(); 12457 12458 case OR_Deleted: 12459 CandidateSet.NoteCandidates( 12460 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 12461 << UnaryOperator::getOpcodeStr(Opc) 12462 << Input->getSourceRange()), 12463 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 12464 OpLoc); 12465 return ExprError(); 12466 } 12467 12468 // Either we found no viable overloaded operator or we matched a 12469 // built-in operator. In either case, fall through to trying to 12470 // build a built-in operation. 12471 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12472 } 12473 12474 /// Create a binary operation that may resolve to an overloaded 12475 /// operator. 12476 /// 12477 /// \param OpLoc The location of the operator itself (e.g., '+'). 12478 /// 12479 /// \param Opc The BinaryOperatorKind that describes this operator. 12480 /// 12481 /// \param Fns The set of non-member functions that will be 12482 /// considered by overload resolution. The caller needs to build this 12483 /// set based on the context using, e.g., 12484 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12485 /// set should not contain any member functions; those will be added 12486 /// by CreateOverloadedBinOp(). 12487 /// 12488 /// \param LHS Left-hand argument. 12489 /// \param RHS Right-hand argument. 12490 ExprResult 12491 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12492 BinaryOperatorKind Opc, 12493 const UnresolvedSetImpl &Fns, 12494 Expr *LHS, Expr *RHS, bool PerformADL) { 12495 Expr *Args[2] = { LHS, RHS }; 12496 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12497 12498 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12499 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12500 12501 // If either side is type-dependent, create an appropriate dependent 12502 // expression. 12503 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12504 if (Fns.empty()) { 12505 // If there are no functions to store, just build a dependent 12506 // BinaryOperator or CompoundAssignment. 12507 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12508 return new (Context) BinaryOperator( 12509 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12510 OpLoc, FPFeatures); 12511 12512 return new (Context) CompoundAssignOperator( 12513 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12514 Context.DependentTy, Context.DependentTy, OpLoc, 12515 FPFeatures); 12516 } 12517 12518 // FIXME: save results of ADL from here? 12519 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12520 // TODO: provide better source location info in DNLoc component. 12521 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12522 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12523 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12524 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12525 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 12526 Context.DependentTy, VK_RValue, OpLoc, 12527 FPFeatures); 12528 } 12529 12530 // Always do placeholder-like conversions on the RHS. 12531 if (checkPlaceholderForOverload(*this, Args[1])) 12532 return ExprError(); 12533 12534 // Do placeholder-like conversion on the LHS; note that we should 12535 // not get here with a PseudoObject LHS. 12536 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12537 if (checkPlaceholderForOverload(*this, Args[0])) 12538 return ExprError(); 12539 12540 // If this is the assignment operator, we only perform overload resolution 12541 // if the left-hand side is a class or enumeration type. This is actually 12542 // a hack. The standard requires that we do overload resolution between the 12543 // various built-in candidates, but as DR507 points out, this can lead to 12544 // problems. So we do it this way, which pretty much follows what GCC does. 12545 // Note that we go the traditional code path for compound assignment forms. 12546 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12547 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12548 12549 // If this is the .* operator, which is not overloadable, just 12550 // create a built-in binary operator. 12551 if (Opc == BO_PtrMemD) 12552 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12553 12554 // Build an empty overload set. 12555 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12556 12557 // Add the candidates from the given function set. 12558 AddFunctionCandidates(Fns, Args, CandidateSet); 12559 12560 // Add operator candidates that are member functions. 12561 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12562 12563 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12564 // performed for an assignment operator (nor for operator[] nor operator->, 12565 // which don't get here). 12566 if (Opc != BO_Assign && PerformADL) 12567 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12568 /*ExplicitTemplateArgs*/ nullptr, 12569 CandidateSet); 12570 12571 // Add builtin operator candidates. 12572 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12573 12574 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12575 12576 // Perform overload resolution. 12577 OverloadCandidateSet::iterator Best; 12578 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12579 case OR_Success: { 12580 // We found a built-in operator or an overloaded operator. 12581 FunctionDecl *FnDecl = Best->Function; 12582 12583 if (FnDecl) { 12584 Expr *Base = nullptr; 12585 // We matched an overloaded operator. Build a call to that 12586 // operator. 12587 12588 // Convert the arguments. 12589 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12590 // Best->Access is only meaningful for class members. 12591 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12592 12593 ExprResult Arg1 = 12594 PerformCopyInitialization( 12595 InitializedEntity::InitializeParameter(Context, 12596 FnDecl->getParamDecl(0)), 12597 SourceLocation(), Args[1]); 12598 if (Arg1.isInvalid()) 12599 return ExprError(); 12600 12601 ExprResult Arg0 = 12602 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12603 Best->FoundDecl, Method); 12604 if (Arg0.isInvalid()) 12605 return ExprError(); 12606 Base = Args[0] = Arg0.getAs<Expr>(); 12607 Args[1] = RHS = Arg1.getAs<Expr>(); 12608 } else { 12609 // Convert the arguments. 12610 ExprResult Arg0 = PerformCopyInitialization( 12611 InitializedEntity::InitializeParameter(Context, 12612 FnDecl->getParamDecl(0)), 12613 SourceLocation(), Args[0]); 12614 if (Arg0.isInvalid()) 12615 return ExprError(); 12616 12617 ExprResult Arg1 = 12618 PerformCopyInitialization( 12619 InitializedEntity::InitializeParameter(Context, 12620 FnDecl->getParamDecl(1)), 12621 SourceLocation(), Args[1]); 12622 if (Arg1.isInvalid()) 12623 return ExprError(); 12624 Args[0] = LHS = Arg0.getAs<Expr>(); 12625 Args[1] = RHS = Arg1.getAs<Expr>(); 12626 } 12627 12628 // Build the actual expression node. 12629 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12630 Best->FoundDecl, Base, 12631 HadMultipleCandidates, OpLoc); 12632 if (FnExpr.isInvalid()) 12633 return ExprError(); 12634 12635 // Determine the result type. 12636 QualType ResultTy = FnDecl->getReturnType(); 12637 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12638 ResultTy = ResultTy.getNonLValueExprType(Context); 12639 12640 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 12641 Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures, 12642 Best->IsADLCandidate); 12643 12644 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12645 FnDecl)) 12646 return ExprError(); 12647 12648 ArrayRef<const Expr *> ArgsArray(Args, 2); 12649 const Expr *ImplicitThis = nullptr; 12650 // Cut off the implicit 'this'. 12651 if (isa<CXXMethodDecl>(FnDecl)) { 12652 ImplicitThis = ArgsArray[0]; 12653 ArgsArray = ArgsArray.slice(1); 12654 } 12655 12656 // Check for a self move. 12657 if (Op == OO_Equal) 12658 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12659 12660 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12661 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12662 VariadicDoesNotApply); 12663 12664 return MaybeBindToTemporary(TheCall); 12665 } else { 12666 // We matched a built-in operator. Convert the arguments, then 12667 // break out so that we will build the appropriate built-in 12668 // operator node. 12669 ExprResult ArgsRes0 = PerformImplicitConversion( 12670 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12671 AA_Passing, CCK_ForBuiltinOverloadedOp); 12672 if (ArgsRes0.isInvalid()) 12673 return ExprError(); 12674 Args[0] = ArgsRes0.get(); 12675 12676 ExprResult ArgsRes1 = PerformImplicitConversion( 12677 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12678 AA_Passing, CCK_ForBuiltinOverloadedOp); 12679 if (ArgsRes1.isInvalid()) 12680 return ExprError(); 12681 Args[1] = ArgsRes1.get(); 12682 break; 12683 } 12684 } 12685 12686 case OR_No_Viable_Function: { 12687 // C++ [over.match.oper]p9: 12688 // If the operator is the operator , [...] and there are no 12689 // viable functions, then the operator is assumed to be the 12690 // built-in operator and interpreted according to clause 5. 12691 if (Opc == BO_Comma) 12692 break; 12693 12694 // For class as left operand for assignment or compound assignment 12695 // operator do not fall through to handling in built-in, but report that 12696 // no overloaded assignment operator found 12697 ExprResult Result = ExprError(); 12698 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 12699 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 12700 Args, OpLoc); 12701 if (Args[0]->getType()->isRecordType() && 12702 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12703 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12704 << BinaryOperator::getOpcodeStr(Opc) 12705 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12706 if (Args[0]->getType()->isIncompleteType()) { 12707 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12708 << Args[0]->getType() 12709 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12710 } 12711 } else { 12712 // This is an erroneous use of an operator which can be overloaded by 12713 // a non-member function. Check for non-member operators which were 12714 // defined too late to be candidates. 12715 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12716 // FIXME: Recover by calling the found function. 12717 return ExprError(); 12718 12719 // No viable function; try to create a built-in operation, which will 12720 // produce an error. Then, show the non-viable candidates. 12721 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12722 } 12723 assert(Result.isInvalid() && 12724 "C++ binary operator overloading is missing candidates!"); 12725 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 12726 return Result; 12727 } 12728 12729 case OR_Ambiguous: 12730 CandidateSet.NoteCandidates( 12731 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 12732 << BinaryOperator::getOpcodeStr(Opc) 12733 << Args[0]->getType() 12734 << Args[1]->getType() 12735 << Args[0]->getSourceRange() 12736 << Args[1]->getSourceRange()), 12737 *this, OCD_ViableCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 12738 OpLoc); 12739 return ExprError(); 12740 12741 case OR_Deleted: 12742 if (isImplicitlyDeleted(Best->Function)) { 12743 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12744 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12745 << Context.getRecordType(Method->getParent()) 12746 << getSpecialMember(Method); 12747 12748 // The user probably meant to call this special member. Just 12749 // explain why it's deleted. 12750 NoteDeletedFunction(Method); 12751 return ExprError(); 12752 } 12753 CandidateSet.NoteCandidates( 12754 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 12755 << BinaryOperator::getOpcodeStr(Opc) 12756 << Args[0]->getSourceRange() 12757 << Args[1]->getSourceRange()), 12758 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 12759 OpLoc); 12760 return ExprError(); 12761 } 12762 12763 // We matched a built-in operator; build it. 12764 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12765 } 12766 12767 ExprResult 12768 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12769 SourceLocation RLoc, 12770 Expr *Base, Expr *Idx) { 12771 Expr *Args[2] = { Base, Idx }; 12772 DeclarationName OpName = 12773 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12774 12775 // If either side is type-dependent, create an appropriate dependent 12776 // expression. 12777 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12778 12779 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12780 // CHECKME: no 'operator' keyword? 12781 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12782 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12783 UnresolvedLookupExpr *Fn 12784 = UnresolvedLookupExpr::Create(Context, NamingClass, 12785 NestedNameSpecifierLoc(), OpNameInfo, 12786 /*ADL*/ true, /*Overloaded*/ false, 12787 UnresolvedSetIterator(), 12788 UnresolvedSetIterator()); 12789 // Can't add any actual overloads yet 12790 12791 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 12792 Context.DependentTy, VK_RValue, RLoc, 12793 FPOptions()); 12794 } 12795 12796 // Handle placeholders on both operands. 12797 if (checkPlaceholderForOverload(*this, Args[0])) 12798 return ExprError(); 12799 if (checkPlaceholderForOverload(*this, Args[1])) 12800 return ExprError(); 12801 12802 // Build an empty overload set. 12803 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12804 12805 // Subscript can only be overloaded as a member function. 12806 12807 // Add operator candidates that are member functions. 12808 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12809 12810 // Add builtin operator candidates. 12811 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12812 12813 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12814 12815 // Perform overload resolution. 12816 OverloadCandidateSet::iterator Best; 12817 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12818 case OR_Success: { 12819 // We found a built-in operator or an overloaded operator. 12820 FunctionDecl *FnDecl = Best->Function; 12821 12822 if (FnDecl) { 12823 // We matched an overloaded operator. Build a call to that 12824 // operator. 12825 12826 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12827 12828 // Convert the arguments. 12829 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12830 ExprResult Arg0 = 12831 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12832 Best->FoundDecl, Method); 12833 if (Arg0.isInvalid()) 12834 return ExprError(); 12835 Args[0] = Arg0.get(); 12836 12837 // Convert the arguments. 12838 ExprResult InputInit 12839 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12840 Context, 12841 FnDecl->getParamDecl(0)), 12842 SourceLocation(), 12843 Args[1]); 12844 if (InputInit.isInvalid()) 12845 return ExprError(); 12846 12847 Args[1] = InputInit.getAs<Expr>(); 12848 12849 // Build the actual expression node. 12850 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12851 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12852 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12853 Best->FoundDecl, 12854 Base, 12855 HadMultipleCandidates, 12856 OpLocInfo.getLoc(), 12857 OpLocInfo.getInfo()); 12858 if (FnExpr.isInvalid()) 12859 return ExprError(); 12860 12861 // Determine the result type 12862 QualType ResultTy = FnDecl->getReturnType(); 12863 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12864 ResultTy = ResultTy.getNonLValueExprType(Context); 12865 12866 CXXOperatorCallExpr *TheCall = 12867 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 12868 Args, ResultTy, VK, RLoc, FPOptions()); 12869 12870 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12871 return ExprError(); 12872 12873 if (CheckFunctionCall(Method, TheCall, 12874 Method->getType()->castAs<FunctionProtoType>())) 12875 return ExprError(); 12876 12877 return MaybeBindToTemporary(TheCall); 12878 } else { 12879 // We matched a built-in operator. Convert the arguments, then 12880 // break out so that we will build the appropriate built-in 12881 // operator node. 12882 ExprResult ArgsRes0 = PerformImplicitConversion( 12883 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12884 AA_Passing, CCK_ForBuiltinOverloadedOp); 12885 if (ArgsRes0.isInvalid()) 12886 return ExprError(); 12887 Args[0] = ArgsRes0.get(); 12888 12889 ExprResult ArgsRes1 = PerformImplicitConversion( 12890 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12891 AA_Passing, CCK_ForBuiltinOverloadedOp); 12892 if (ArgsRes1.isInvalid()) 12893 return ExprError(); 12894 Args[1] = ArgsRes1.get(); 12895 12896 break; 12897 } 12898 } 12899 12900 case OR_No_Viable_Function: { 12901 PartialDiagnostic PD = CandidateSet.empty() 12902 ? (PDiag(diag::err_ovl_no_oper) 12903 << Args[0]->getType() << /*subscript*/ 0 12904 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 12905 : (PDiag(diag::err_ovl_no_viable_subscript) 12906 << Args[0]->getType() << Args[0]->getSourceRange() 12907 << Args[1]->getSourceRange()); 12908 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 12909 OCD_AllCandidates, Args, "[]", LLoc); 12910 return ExprError(); 12911 } 12912 12913 case OR_Ambiguous: 12914 CandidateSet.NoteCandidates( 12915 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 12916 << "[]" << Args[0]->getType() 12917 << Args[1]->getType() 12918 << Args[0]->getSourceRange() 12919 << Args[1]->getSourceRange()), 12920 *this, OCD_ViableCandidates, Args, "[]", LLoc); 12921 return ExprError(); 12922 12923 case OR_Deleted: 12924 CandidateSet.NoteCandidates( 12925 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 12926 << "[]" << Args[0]->getSourceRange() 12927 << Args[1]->getSourceRange()), 12928 *this, OCD_AllCandidates, Args, "[]", LLoc); 12929 return ExprError(); 12930 } 12931 12932 // We matched a built-in operator; build it. 12933 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12934 } 12935 12936 /// BuildCallToMemberFunction - Build a call to a member 12937 /// function. MemExpr is the expression that refers to the member 12938 /// function (and includes the object parameter), Args/NumArgs are the 12939 /// arguments to the function call (not including the object 12940 /// parameter). The caller needs to validate that the member 12941 /// expression refers to a non-static member function or an overloaded 12942 /// member function. 12943 ExprResult 12944 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12945 SourceLocation LParenLoc, 12946 MultiExprArg Args, 12947 SourceLocation RParenLoc) { 12948 assert(MemExprE->getType() == Context.BoundMemberTy || 12949 MemExprE->getType() == Context.OverloadTy); 12950 12951 // Dig out the member expression. This holds both the object 12952 // argument and the member function we're referring to. 12953 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12954 12955 // Determine whether this is a call to a pointer-to-member function. 12956 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12957 assert(op->getType() == Context.BoundMemberTy); 12958 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12959 12960 QualType fnType = 12961 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12962 12963 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12964 QualType resultType = proto->getCallResultType(Context); 12965 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12966 12967 // Check that the object type isn't more qualified than the 12968 // member function we're calling. 12969 Qualifiers funcQuals = proto->getMethodQuals(); 12970 12971 QualType objectType = op->getLHS()->getType(); 12972 if (op->getOpcode() == BO_PtrMemI) 12973 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12974 Qualifiers objectQuals = objectType.getQualifiers(); 12975 12976 Qualifiers difference = objectQuals - funcQuals; 12977 difference.removeObjCGCAttr(); 12978 difference.removeAddressSpace(); 12979 if (difference) { 12980 std::string qualsString = difference.getAsString(); 12981 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12982 << fnType.getUnqualifiedType() 12983 << qualsString 12984 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12985 } 12986 12987 CXXMemberCallExpr *call = 12988 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 12989 valueKind, RParenLoc, proto->getNumParams()); 12990 12991 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 12992 call, nullptr)) 12993 return ExprError(); 12994 12995 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12996 return ExprError(); 12997 12998 if (CheckOtherCall(call, proto)) 12999 return ExprError(); 13000 13001 return MaybeBindToTemporary(call); 13002 } 13003 13004 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 13005 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 13006 RParenLoc); 13007 13008 UnbridgedCastsSet UnbridgedCasts; 13009 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13010 return ExprError(); 13011 13012 MemberExpr *MemExpr; 13013 CXXMethodDecl *Method = nullptr; 13014 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 13015 NestedNameSpecifier *Qualifier = nullptr; 13016 if (isa<MemberExpr>(NakedMemExpr)) { 13017 MemExpr = cast<MemberExpr>(NakedMemExpr); 13018 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 13019 FoundDecl = MemExpr->getFoundDecl(); 13020 Qualifier = MemExpr->getQualifier(); 13021 UnbridgedCasts.restore(); 13022 } else { 13023 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 13024 Qualifier = UnresExpr->getQualifier(); 13025 13026 QualType ObjectType = UnresExpr->getBaseType(); 13027 Expr::Classification ObjectClassification 13028 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 13029 : UnresExpr->getBase()->Classify(Context); 13030 13031 // Add overload candidates 13032 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 13033 OverloadCandidateSet::CSK_Normal); 13034 13035 // FIXME: avoid copy. 13036 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13037 if (UnresExpr->hasExplicitTemplateArgs()) { 13038 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13039 TemplateArgs = &TemplateArgsBuffer; 13040 } 13041 13042 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 13043 E = UnresExpr->decls_end(); I != E; ++I) { 13044 13045 NamedDecl *Func = *I; 13046 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 13047 if (isa<UsingShadowDecl>(Func)) 13048 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 13049 13050 13051 // Microsoft supports direct constructor calls. 13052 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 13053 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 13054 CandidateSet, 13055 /*SuppressUserConversions*/ false); 13056 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 13057 // If explicit template arguments were provided, we can't call a 13058 // non-template member function. 13059 if (TemplateArgs) 13060 continue; 13061 13062 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 13063 ObjectClassification, Args, CandidateSet, 13064 /*SuppressUserConversions=*/false); 13065 } else { 13066 AddMethodTemplateCandidate( 13067 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 13068 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 13069 /*SuppressUsedConversions=*/false); 13070 } 13071 } 13072 13073 DeclarationName DeclName = UnresExpr->getMemberName(); 13074 13075 UnbridgedCasts.restore(); 13076 13077 OverloadCandidateSet::iterator Best; 13078 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 13079 Best)) { 13080 case OR_Success: 13081 Method = cast<CXXMethodDecl>(Best->Function); 13082 FoundDecl = Best->FoundDecl; 13083 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13084 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13085 return ExprError(); 13086 // If FoundDecl is different from Method (such as if one is a template 13087 // and the other a specialization), make sure DiagnoseUseOfDecl is 13088 // called on both. 13089 // FIXME: This would be more comprehensively addressed by modifying 13090 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13091 // being used. 13092 if (Method != FoundDecl.getDecl() && 13093 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13094 return ExprError(); 13095 break; 13096 13097 case OR_No_Viable_Function: 13098 CandidateSet.NoteCandidates( 13099 PartialDiagnosticAt( 13100 UnresExpr->getMemberLoc(), 13101 PDiag(diag::err_ovl_no_viable_member_function_in_call) 13102 << DeclName << MemExprE->getSourceRange()), 13103 *this, OCD_AllCandidates, Args); 13104 // FIXME: Leaking incoming expressions! 13105 return ExprError(); 13106 13107 case OR_Ambiguous: 13108 CandidateSet.NoteCandidates( 13109 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13110 PDiag(diag::err_ovl_ambiguous_member_call) 13111 << DeclName << MemExprE->getSourceRange()), 13112 *this, OCD_AllCandidates, Args); 13113 // FIXME: Leaking incoming expressions! 13114 return ExprError(); 13115 13116 case OR_Deleted: 13117 CandidateSet.NoteCandidates( 13118 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13119 PDiag(diag::err_ovl_deleted_member_call) 13120 << DeclName << MemExprE->getSourceRange()), 13121 *this, OCD_AllCandidates, Args); 13122 // FIXME: Leaking incoming expressions! 13123 return ExprError(); 13124 } 13125 13126 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13127 13128 // If overload resolution picked a static member, build a 13129 // non-member call based on that function. 13130 if (Method->isStatic()) { 13131 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13132 RParenLoc); 13133 } 13134 13135 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13136 } 13137 13138 QualType ResultType = Method->getReturnType(); 13139 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13140 ResultType = ResultType.getNonLValueExprType(Context); 13141 13142 assert(Method && "Member call to something that isn't a method?"); 13143 const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); 13144 CXXMemberCallExpr *TheCall = 13145 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13146 RParenLoc, Proto->getNumParams()); 13147 13148 // Check for a valid return type. 13149 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13150 TheCall, Method)) 13151 return ExprError(); 13152 13153 // Convert the object argument (for a non-static member function call). 13154 // We only need to do this if there was actually an overload; otherwise 13155 // it was done at lookup. 13156 if (!Method->isStatic()) { 13157 ExprResult ObjectArg = 13158 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13159 FoundDecl, Method); 13160 if (ObjectArg.isInvalid()) 13161 return ExprError(); 13162 MemExpr->setBase(ObjectArg.get()); 13163 } 13164 13165 // Convert the rest of the arguments 13166 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13167 RParenLoc)) 13168 return ExprError(); 13169 13170 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13171 13172 if (CheckFunctionCall(Method, TheCall, Proto)) 13173 return ExprError(); 13174 13175 // In the case the method to call was not selected by the overloading 13176 // resolution process, we still need to handle the enable_if attribute. Do 13177 // that here, so it will not hide previous -- and more relevant -- errors. 13178 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13179 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13180 Diag(MemE->getMemberLoc(), 13181 diag::err_ovl_no_viable_member_function_in_call) 13182 << Method << Method->getSourceRange(); 13183 Diag(Method->getLocation(), 13184 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13185 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13186 return ExprError(); 13187 } 13188 } 13189 13190 if ((isa<CXXConstructorDecl>(CurContext) || 13191 isa<CXXDestructorDecl>(CurContext)) && 13192 TheCall->getMethodDecl()->isPure()) { 13193 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13194 13195 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13196 MemExpr->performsVirtualDispatch(getLangOpts())) { 13197 Diag(MemExpr->getBeginLoc(), 13198 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13199 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13200 << MD->getParent()->getDeclName(); 13201 13202 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13203 if (getLangOpts().AppleKext) 13204 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13205 << MD->getParent()->getDeclName() << MD->getDeclName(); 13206 } 13207 } 13208 13209 if (CXXDestructorDecl *DD = 13210 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13211 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13212 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13213 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13214 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13215 MemExpr->getMemberLoc()); 13216 } 13217 13218 return MaybeBindToTemporary(TheCall); 13219 } 13220 13221 /// BuildCallToObjectOfClassType - Build a call to an object of class 13222 /// type (C++ [over.call.object]), which can end up invoking an 13223 /// overloaded function call operator (@c operator()) or performing a 13224 /// user-defined conversion on the object argument. 13225 ExprResult 13226 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13227 SourceLocation LParenLoc, 13228 MultiExprArg Args, 13229 SourceLocation RParenLoc) { 13230 if (checkPlaceholderForOverload(*this, Obj)) 13231 return ExprError(); 13232 ExprResult Object = Obj; 13233 13234 UnbridgedCastsSet UnbridgedCasts; 13235 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13236 return ExprError(); 13237 13238 assert(Object.get()->getType()->isRecordType() && 13239 "Requires object type argument"); 13240 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13241 13242 // C++ [over.call.object]p1: 13243 // If the primary-expression E in the function call syntax 13244 // evaluates to a class object of type "cv T", then the set of 13245 // candidate functions includes at least the function call 13246 // operators of T. The function call operators of T are obtained by 13247 // ordinary lookup of the name operator() in the context of 13248 // (E).operator(). 13249 OverloadCandidateSet CandidateSet(LParenLoc, 13250 OverloadCandidateSet::CSK_Operator); 13251 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13252 13253 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13254 diag::err_incomplete_object_call, Object.get())) 13255 return true; 13256 13257 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13258 LookupQualifiedName(R, Record->getDecl()); 13259 R.suppressDiagnostics(); 13260 13261 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13262 Oper != OperEnd; ++Oper) { 13263 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13264 Object.get()->Classify(Context), Args, CandidateSet, 13265 /*SuppressUserConversions=*/false); 13266 } 13267 13268 // C++ [over.call.object]p2: 13269 // In addition, for each (non-explicit in C++0x) conversion function 13270 // declared in T of the form 13271 // 13272 // operator conversion-type-id () cv-qualifier; 13273 // 13274 // where cv-qualifier is the same cv-qualification as, or a 13275 // greater cv-qualification than, cv, and where conversion-type-id 13276 // denotes the type "pointer to function of (P1,...,Pn) returning 13277 // R", or the type "reference to pointer to function of 13278 // (P1,...,Pn) returning R", or the type "reference to function 13279 // of (P1,...,Pn) returning R", a surrogate call function [...] 13280 // is also considered as a candidate function. Similarly, 13281 // surrogate call functions are added to the set of candidate 13282 // functions for each conversion function declared in an 13283 // accessible base class provided the function is not hidden 13284 // within T by another intervening declaration. 13285 const auto &Conversions = 13286 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13287 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13288 NamedDecl *D = *I; 13289 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13290 if (isa<UsingShadowDecl>(D)) 13291 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13292 13293 // Skip over templated conversion functions; they aren't 13294 // surrogates. 13295 if (isa<FunctionTemplateDecl>(D)) 13296 continue; 13297 13298 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13299 if (!Conv->isExplicit()) { 13300 // Strip the reference type (if any) and then the pointer type (if 13301 // any) to get down to what might be a function type. 13302 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13303 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13304 ConvType = ConvPtrType->getPointeeType(); 13305 13306 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13307 { 13308 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13309 Object.get(), Args, CandidateSet); 13310 } 13311 } 13312 } 13313 13314 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13315 13316 // Perform overload resolution. 13317 OverloadCandidateSet::iterator Best; 13318 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13319 Best)) { 13320 case OR_Success: 13321 // Overload resolution succeeded; we'll build the appropriate call 13322 // below. 13323 break; 13324 13325 case OR_No_Viable_Function: { 13326 PartialDiagnostic PD = 13327 CandidateSet.empty() 13328 ? (PDiag(diag::err_ovl_no_oper) 13329 << Object.get()->getType() << /*call*/ 1 13330 << Object.get()->getSourceRange()) 13331 : (PDiag(diag::err_ovl_no_viable_object_call) 13332 << Object.get()->getType() << Object.get()->getSourceRange()); 13333 CandidateSet.NoteCandidates( 13334 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 13335 OCD_AllCandidates, Args); 13336 break; 13337 } 13338 case OR_Ambiguous: 13339 CandidateSet.NoteCandidates( 13340 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13341 PDiag(diag::err_ovl_ambiguous_object_call) 13342 << Object.get()->getType() 13343 << Object.get()->getSourceRange()), 13344 *this, OCD_ViableCandidates, Args); 13345 break; 13346 13347 case OR_Deleted: 13348 CandidateSet.NoteCandidates( 13349 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13350 PDiag(diag::err_ovl_deleted_object_call) 13351 << Object.get()->getType() 13352 << Object.get()->getSourceRange()), 13353 *this, OCD_AllCandidates, Args); 13354 break; 13355 } 13356 13357 if (Best == CandidateSet.end()) 13358 return true; 13359 13360 UnbridgedCasts.restore(); 13361 13362 if (Best->Function == nullptr) { 13363 // Since there is no function declaration, this is one of the 13364 // surrogate candidates. Dig out the conversion function. 13365 CXXConversionDecl *Conv 13366 = cast<CXXConversionDecl>( 13367 Best->Conversions[0].UserDefined.ConversionFunction); 13368 13369 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13370 Best->FoundDecl); 13371 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13372 return ExprError(); 13373 assert(Conv == Best->FoundDecl.getDecl() && 13374 "Found Decl & conversion-to-functionptr should be same, right?!"); 13375 // We selected one of the surrogate functions that converts the 13376 // object parameter to a function pointer. Perform the conversion 13377 // on the object argument, then let BuildCallExpr finish the job. 13378 13379 // Create an implicit member expr to refer to the conversion operator. 13380 // and then call it. 13381 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13382 Conv, HadMultipleCandidates); 13383 if (Call.isInvalid()) 13384 return ExprError(); 13385 // Record usage of conversion in an implicit cast. 13386 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13387 CK_UserDefinedConversion, Call.get(), 13388 nullptr, VK_RValue); 13389 13390 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13391 } 13392 13393 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13394 13395 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13396 // that calls this method, using Object for the implicit object 13397 // parameter and passing along the remaining arguments. 13398 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13399 13400 // An error diagnostic has already been printed when parsing the declaration. 13401 if (Method->isInvalidDecl()) 13402 return ExprError(); 13403 13404 const FunctionProtoType *Proto = 13405 Method->getType()->getAs<FunctionProtoType>(); 13406 13407 unsigned NumParams = Proto->getNumParams(); 13408 13409 DeclarationNameInfo OpLocInfo( 13410 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13411 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13412 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13413 Obj, HadMultipleCandidates, 13414 OpLocInfo.getLoc(), 13415 OpLocInfo.getInfo()); 13416 if (NewFn.isInvalid()) 13417 return true; 13418 13419 // The number of argument slots to allocate in the call. If we have default 13420 // arguments we need to allocate space for them as well. We additionally 13421 // need one more slot for the object parameter. 13422 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 13423 13424 // Build the full argument list for the method call (the implicit object 13425 // parameter is placed at the beginning of the list). 13426 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 13427 13428 bool IsError = false; 13429 13430 // Initialize the implicit object parameter. 13431 ExprResult ObjRes = 13432 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13433 Best->FoundDecl, Method); 13434 if (ObjRes.isInvalid()) 13435 IsError = true; 13436 else 13437 Object = ObjRes; 13438 MethodArgs[0] = Object.get(); 13439 13440 // Check the argument types. 13441 for (unsigned i = 0; i != NumParams; i++) { 13442 Expr *Arg; 13443 if (i < Args.size()) { 13444 Arg = Args[i]; 13445 13446 // Pass the argument. 13447 13448 ExprResult InputInit 13449 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13450 Context, 13451 Method->getParamDecl(i)), 13452 SourceLocation(), Arg); 13453 13454 IsError |= InputInit.isInvalid(); 13455 Arg = InputInit.getAs<Expr>(); 13456 } else { 13457 ExprResult DefArg 13458 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13459 if (DefArg.isInvalid()) { 13460 IsError = true; 13461 break; 13462 } 13463 13464 Arg = DefArg.getAs<Expr>(); 13465 } 13466 13467 MethodArgs[i + 1] = Arg; 13468 } 13469 13470 // If this is a variadic call, handle args passed through "...". 13471 if (Proto->isVariadic()) { 13472 // Promote the arguments (C99 6.5.2.2p7). 13473 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13474 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13475 nullptr); 13476 IsError |= Arg.isInvalid(); 13477 MethodArgs[i + 1] = Arg.get(); 13478 } 13479 } 13480 13481 if (IsError) 13482 return true; 13483 13484 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13485 13486 // Once we've built TheCall, all of the expressions are properly owned. 13487 QualType ResultTy = Method->getReturnType(); 13488 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13489 ResultTy = ResultTy.getNonLValueExprType(Context); 13490 13491 CXXOperatorCallExpr *TheCall = 13492 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 13493 ResultTy, VK, RParenLoc, FPOptions()); 13494 13495 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13496 return true; 13497 13498 if (CheckFunctionCall(Method, TheCall, Proto)) 13499 return true; 13500 13501 return MaybeBindToTemporary(TheCall); 13502 } 13503 13504 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13505 /// (if one exists), where @c Base is an expression of class type and 13506 /// @c Member is the name of the member we're trying to find. 13507 ExprResult 13508 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13509 bool *NoArrowOperatorFound) { 13510 assert(Base->getType()->isRecordType() && 13511 "left-hand side must have class type"); 13512 13513 if (checkPlaceholderForOverload(*this, Base)) 13514 return ExprError(); 13515 13516 SourceLocation Loc = Base->getExprLoc(); 13517 13518 // C++ [over.ref]p1: 13519 // 13520 // [...] An expression x->m is interpreted as (x.operator->())->m 13521 // for a class object x of type T if T::operator->() exists and if 13522 // the operator is selected as the best match function by the 13523 // overload resolution mechanism (13.3). 13524 DeclarationName OpName = 13525 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13526 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13527 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13528 13529 if (RequireCompleteType(Loc, Base->getType(), 13530 diag::err_typecheck_incomplete_tag, Base)) 13531 return ExprError(); 13532 13533 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13534 LookupQualifiedName(R, BaseRecord->getDecl()); 13535 R.suppressDiagnostics(); 13536 13537 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13538 Oper != OperEnd; ++Oper) { 13539 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13540 None, CandidateSet, /*SuppressUserConversions=*/false); 13541 } 13542 13543 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13544 13545 // Perform overload resolution. 13546 OverloadCandidateSet::iterator Best; 13547 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13548 case OR_Success: 13549 // Overload resolution succeeded; we'll build the call below. 13550 break; 13551 13552 case OR_No_Viable_Function: { 13553 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 13554 if (CandidateSet.empty()) { 13555 QualType BaseType = Base->getType(); 13556 if (NoArrowOperatorFound) { 13557 // Report this specific error to the caller instead of emitting a 13558 // diagnostic, as requested. 13559 *NoArrowOperatorFound = true; 13560 return ExprError(); 13561 } 13562 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13563 << BaseType << Base->getSourceRange(); 13564 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13565 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13566 << FixItHint::CreateReplacement(OpLoc, "."); 13567 } 13568 } else 13569 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13570 << "operator->" << Base->getSourceRange(); 13571 CandidateSet.NoteCandidates(*this, Base, Cands); 13572 return ExprError(); 13573 } 13574 case OR_Ambiguous: 13575 CandidateSet.NoteCandidates( 13576 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 13577 << "->" << Base->getType() 13578 << Base->getSourceRange()), 13579 *this, OCD_ViableCandidates, Base); 13580 return ExprError(); 13581 13582 case OR_Deleted: 13583 CandidateSet.NoteCandidates( 13584 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13585 << "->" << Base->getSourceRange()), 13586 *this, OCD_AllCandidates, Base); 13587 return ExprError(); 13588 } 13589 13590 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13591 13592 // Convert the object parameter. 13593 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13594 ExprResult BaseResult = 13595 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13596 Best->FoundDecl, Method); 13597 if (BaseResult.isInvalid()) 13598 return ExprError(); 13599 Base = BaseResult.get(); 13600 13601 // Build the operator call. 13602 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13603 Base, HadMultipleCandidates, OpLoc); 13604 if (FnExpr.isInvalid()) 13605 return ExprError(); 13606 13607 QualType ResultTy = Method->getReturnType(); 13608 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13609 ResultTy = ResultTy.getNonLValueExprType(Context); 13610 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13611 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 13612 13613 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13614 return ExprError(); 13615 13616 if (CheckFunctionCall(Method, TheCall, 13617 Method->getType()->castAs<FunctionProtoType>())) 13618 return ExprError(); 13619 13620 return MaybeBindToTemporary(TheCall); 13621 } 13622 13623 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13624 /// a literal operator described by the provided lookup results. 13625 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13626 DeclarationNameInfo &SuffixInfo, 13627 ArrayRef<Expr*> Args, 13628 SourceLocation LitEndLoc, 13629 TemplateArgumentListInfo *TemplateArgs) { 13630 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13631 13632 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13633 OverloadCandidateSet::CSK_Normal); 13634 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13635 /*SuppressUserConversions=*/true); 13636 13637 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13638 13639 // Perform overload resolution. This will usually be trivial, but might need 13640 // to perform substitutions for a literal operator template. 13641 OverloadCandidateSet::iterator Best; 13642 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13643 case OR_Success: 13644 case OR_Deleted: 13645 break; 13646 13647 case OR_No_Viable_Function: 13648 CandidateSet.NoteCandidates( 13649 PartialDiagnosticAt(UDSuffixLoc, 13650 PDiag(diag::err_ovl_no_viable_function_in_call) 13651 << R.getLookupName()), 13652 *this, OCD_AllCandidates, Args); 13653 return ExprError(); 13654 13655 case OR_Ambiguous: 13656 CandidateSet.NoteCandidates( 13657 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 13658 << R.getLookupName()), 13659 *this, OCD_ViableCandidates, Args); 13660 return ExprError(); 13661 } 13662 13663 FunctionDecl *FD = Best->Function; 13664 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13665 nullptr, HadMultipleCandidates, 13666 SuffixInfo.getLoc(), 13667 SuffixInfo.getInfo()); 13668 if (Fn.isInvalid()) 13669 return true; 13670 13671 // Check the argument types. This should almost always be a no-op, except 13672 // that array-to-pointer decay is applied to string literals. 13673 Expr *ConvArgs[2]; 13674 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13675 ExprResult InputInit = PerformCopyInitialization( 13676 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13677 SourceLocation(), Args[ArgIdx]); 13678 if (InputInit.isInvalid()) 13679 return true; 13680 ConvArgs[ArgIdx] = InputInit.get(); 13681 } 13682 13683 QualType ResultTy = FD->getReturnType(); 13684 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13685 ResultTy = ResultTy.getNonLValueExprType(Context); 13686 13687 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 13688 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 13689 VK, LitEndLoc, UDSuffixLoc); 13690 13691 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13692 return ExprError(); 13693 13694 if (CheckFunctionCall(FD, UDL, nullptr)) 13695 return ExprError(); 13696 13697 return MaybeBindToTemporary(UDL); 13698 } 13699 13700 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13701 /// given LookupResult is non-empty, it is assumed to describe a member which 13702 /// will be invoked. Otherwise, the function will be found via argument 13703 /// dependent lookup. 13704 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13705 /// otherwise CallExpr is set to ExprError() and some non-success value 13706 /// is returned. 13707 Sema::ForRangeStatus 13708 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13709 SourceLocation RangeLoc, 13710 const DeclarationNameInfo &NameInfo, 13711 LookupResult &MemberLookup, 13712 OverloadCandidateSet *CandidateSet, 13713 Expr *Range, ExprResult *CallExpr) { 13714 Scope *S = nullptr; 13715 13716 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 13717 if (!MemberLookup.empty()) { 13718 ExprResult MemberRef = 13719 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13720 /*IsPtr=*/false, CXXScopeSpec(), 13721 /*TemplateKWLoc=*/SourceLocation(), 13722 /*FirstQualifierInScope=*/nullptr, 13723 MemberLookup, 13724 /*TemplateArgs=*/nullptr, S); 13725 if (MemberRef.isInvalid()) { 13726 *CallExpr = ExprError(); 13727 return FRS_DiagnosticIssued; 13728 } 13729 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13730 if (CallExpr->isInvalid()) { 13731 *CallExpr = ExprError(); 13732 return FRS_DiagnosticIssued; 13733 } 13734 } else { 13735 UnresolvedSet<0> FoundNames; 13736 UnresolvedLookupExpr *Fn = 13737 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13738 NestedNameSpecifierLoc(), NameInfo, 13739 /*NeedsADL=*/true, /*Overloaded=*/false, 13740 FoundNames.begin(), FoundNames.end()); 13741 13742 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13743 CandidateSet, CallExpr); 13744 if (CandidateSet->empty() || CandidateSetError) { 13745 *CallExpr = ExprError(); 13746 return FRS_NoViableFunction; 13747 } 13748 OverloadCandidateSet::iterator Best; 13749 OverloadingResult OverloadResult = 13750 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 13751 13752 if (OverloadResult == OR_No_Viable_Function) { 13753 *CallExpr = ExprError(); 13754 return FRS_NoViableFunction; 13755 } 13756 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13757 Loc, nullptr, CandidateSet, &Best, 13758 OverloadResult, 13759 /*AllowTypoCorrection=*/false); 13760 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13761 *CallExpr = ExprError(); 13762 return FRS_DiagnosticIssued; 13763 } 13764 } 13765 return FRS_Success; 13766 } 13767 13768 13769 /// FixOverloadedFunctionReference - E is an expression that refers to 13770 /// a C++ overloaded function (possibly with some parentheses and 13771 /// perhaps a '&' around it). We have resolved the overloaded function 13772 /// to the function declaration Fn, so patch up the expression E to 13773 /// refer (possibly indirectly) to Fn. Returns the new expr. 13774 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13775 FunctionDecl *Fn) { 13776 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13777 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13778 Found, Fn); 13779 if (SubExpr == PE->getSubExpr()) 13780 return PE; 13781 13782 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13783 } 13784 13785 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13786 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13787 Found, Fn); 13788 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13789 SubExpr->getType()) && 13790 "Implicit cast type cannot be determined from overload"); 13791 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13792 if (SubExpr == ICE->getSubExpr()) 13793 return ICE; 13794 13795 return ImplicitCastExpr::Create(Context, ICE->getType(), 13796 ICE->getCastKind(), 13797 SubExpr, nullptr, 13798 ICE->getValueKind()); 13799 } 13800 13801 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13802 if (!GSE->isResultDependent()) { 13803 Expr *SubExpr = 13804 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13805 if (SubExpr == GSE->getResultExpr()) 13806 return GSE; 13807 13808 // Replace the resulting type information before rebuilding the generic 13809 // selection expression. 13810 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13811 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13812 unsigned ResultIdx = GSE->getResultIndex(); 13813 AssocExprs[ResultIdx] = SubExpr; 13814 13815 return GenericSelectionExpr::Create( 13816 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13817 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13818 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13819 ResultIdx); 13820 } 13821 // Rather than fall through to the unreachable, return the original generic 13822 // selection expression. 13823 return GSE; 13824 } 13825 13826 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13827 assert(UnOp->getOpcode() == UO_AddrOf && 13828 "Can only take the address of an overloaded function"); 13829 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13830 if (Method->isStatic()) { 13831 // Do nothing: static member functions aren't any different 13832 // from non-member functions. 13833 } else { 13834 // Fix the subexpression, which really has to be an 13835 // UnresolvedLookupExpr holding an overloaded member function 13836 // or template. 13837 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13838 Found, Fn); 13839 if (SubExpr == UnOp->getSubExpr()) 13840 return UnOp; 13841 13842 assert(isa<DeclRefExpr>(SubExpr) 13843 && "fixed to something other than a decl ref"); 13844 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13845 && "fixed to a member ref with no nested name qualifier"); 13846 13847 // We have taken the address of a pointer to member 13848 // function. Perform the computation here so that we get the 13849 // appropriate pointer to member type. 13850 QualType ClassType 13851 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13852 QualType MemPtrType 13853 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13854 // Under the MS ABI, lock down the inheritance model now. 13855 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13856 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13857 13858 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13859 VK_RValue, OK_Ordinary, 13860 UnOp->getOperatorLoc(), false); 13861 } 13862 } 13863 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13864 Found, Fn); 13865 if (SubExpr == UnOp->getSubExpr()) 13866 return UnOp; 13867 13868 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13869 Context.getPointerType(SubExpr->getType()), 13870 VK_RValue, OK_Ordinary, 13871 UnOp->getOperatorLoc(), false); 13872 } 13873 13874 // C++ [except.spec]p17: 13875 // An exception-specification is considered to be needed when: 13876 // - in an expression the function is the unique lookup result or the 13877 // selected member of a set of overloaded functions 13878 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13879 ResolveExceptionSpec(E->getExprLoc(), FPT); 13880 13881 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13882 // FIXME: avoid copy. 13883 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13884 if (ULE->hasExplicitTemplateArgs()) { 13885 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13886 TemplateArgs = &TemplateArgsBuffer; 13887 } 13888 13889 DeclRefExpr *DRE = 13890 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 13891 ULE->getQualifierLoc(), Found.getDecl(), 13892 ULE->getTemplateKeywordLoc(), TemplateArgs); 13893 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13894 return DRE; 13895 } 13896 13897 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13898 // FIXME: avoid copy. 13899 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13900 if (MemExpr->hasExplicitTemplateArgs()) { 13901 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13902 TemplateArgs = &TemplateArgsBuffer; 13903 } 13904 13905 Expr *Base; 13906 13907 // If we're filling in a static method where we used to have an 13908 // implicit member access, rewrite to a simple decl ref. 13909 if (MemExpr->isImplicitAccess()) { 13910 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13911 DeclRefExpr *DRE = BuildDeclRefExpr( 13912 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 13913 MemExpr->getQualifierLoc(), Found.getDecl(), 13914 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 13915 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13916 return DRE; 13917 } else { 13918 SourceLocation Loc = MemExpr->getMemberLoc(); 13919 if (MemExpr->getQualifier()) 13920 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13921 Base = 13922 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*isImplicit=*/true); 13923 } 13924 } else 13925 Base = MemExpr->getBase(); 13926 13927 ExprValueKind valueKind; 13928 QualType type; 13929 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13930 valueKind = VK_LValue; 13931 type = Fn->getType(); 13932 } else { 13933 valueKind = VK_RValue; 13934 type = Context.BoundMemberTy; 13935 } 13936 13937 return BuildMemberExpr( 13938 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13939 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13940 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 13941 type, valueKind, OK_Ordinary, TemplateArgs); 13942 } 13943 13944 llvm_unreachable("Invalid reference to overloaded function"); 13945 } 13946 13947 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13948 DeclAccessPair Found, 13949 FunctionDecl *Fn) { 13950 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13951 } 13952