1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/ADT/Optional.h" 33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/SmallString.h" 36 #include <algorithm> 37 #include <cstdlib> 38 39 using namespace clang; 40 using namespace sema; 41 42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 43 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 44 return P->hasAttr<PassObjectSizeAttr>(); 45 }); 46 } 47 48 /// A convenience routine for creating a decayed reference to a function. 49 static ExprResult 50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 51 bool HadMultipleCandidates, 52 SourceLocation Loc = SourceLocation(), 53 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 54 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 55 return ExprError(); 56 // If FoundDecl is different from Fn (such as if one is a template 57 // and the other a specialization), make sure DiagnoseUseOfDecl is 58 // called on both. 59 // FIXME: This would be more comprehensively addressed by modifying 60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 61 // being used. 62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 63 return ExprError(); 64 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 65 S.ResolveExceptionSpec(Loc, FPT); 66 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 67 VK_LValue, Loc, LocInfo); 68 if (HadMultipleCandidates) 69 DRE->setHadMultipleCandidates(true); 70 71 S.MarkDeclRefReferenced(DRE); 72 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 73 CK_FunctionToPointerDecay); 74 } 75 76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 77 bool InOverloadResolution, 78 StandardConversionSequence &SCS, 79 bool CStyle, 80 bool AllowObjCWritebackConversion); 81 82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 83 QualType &ToType, 84 bool InOverloadResolution, 85 StandardConversionSequence &SCS, 86 bool CStyle); 87 static OverloadingResult 88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 89 UserDefinedConversionSequence& User, 90 OverloadCandidateSet& Conversions, 91 bool AllowExplicit, 92 bool AllowObjCConversionOnExplicit); 93 94 95 static ImplicitConversionSequence::CompareKind 96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 97 const StandardConversionSequence& SCS1, 98 const StandardConversionSequence& SCS2); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareQualificationConversions(Sema &S, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 static ImplicitConversionSequence::CompareKind 106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 107 const StandardConversionSequence& SCS1, 108 const StandardConversionSequence& SCS2); 109 110 /// GetConversionRank - Retrieve the implicit conversion rank 111 /// corresponding to the given implicit conversion kind. 112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 113 static const ImplicitConversionRank 114 Rank[(int)ICK_Num_Conversion_Kinds] = { 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Exact_Match, 121 ICR_Promotion, 122 ICR_Promotion, 123 ICR_Promotion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Complex_Real_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Writeback_Conversion, 139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 140 // it was omitted by the patch that added 141 // ICK_Zero_Event_Conversion 142 ICR_C_Conversion, 143 ICR_C_Conversion_Extension 144 }; 145 return Rank[(int)Kind]; 146 } 147 148 /// GetImplicitConversionName - Return the name of this kind of 149 /// implicit conversion. 150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 152 "No conversion", 153 "Lvalue-to-rvalue", 154 "Array-to-pointer", 155 "Function-to-pointer", 156 "Function pointer conversion", 157 "Qualification", 158 "Integral promotion", 159 "Floating point promotion", 160 "Complex promotion", 161 "Integral conversion", 162 "Floating conversion", 163 "Complex conversion", 164 "Floating-integral conversion", 165 "Pointer conversion", 166 "Pointer-to-member conversion", 167 "Boolean conversion", 168 "Compatible-types conversion", 169 "Derived-to-base conversion", 170 "Vector conversion", 171 "Vector splat", 172 "Complex-real conversion", 173 "Block Pointer conversion", 174 "Transparent Union Conversion", 175 "Writeback conversion", 176 "OpenCL Zero Event Conversion", 177 "C specific type conversion", 178 "Incompatible pointer conversion" 179 }; 180 return Name[Kind]; 181 } 182 183 /// StandardConversionSequence - Set the standard conversion 184 /// sequence to the identity conversion. 185 void StandardConversionSequence::setAsIdentityConversion() { 186 First = ICK_Identity; 187 Second = ICK_Identity; 188 Third = ICK_Identity; 189 DeprecatedStringLiteralToCharPtr = false; 190 QualificationIncludesObjCLifetime = false; 191 ReferenceBinding = false; 192 DirectBinding = false; 193 IsLvalueReference = true; 194 BindsToFunctionLvalue = false; 195 BindsToRvalue = false; 196 BindsImplicitObjectArgumentWithoutRefQualifier = false; 197 ObjCLifetimeConversionBinding = false; 198 CopyConstructor = nullptr; 199 } 200 201 /// getRank - Retrieve the rank of this standard conversion sequence 202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 203 /// implicit conversions. 204 ImplicitConversionRank StandardConversionSequence::getRank() const { 205 ImplicitConversionRank Rank = ICR_Exact_Match; 206 if (GetConversionRank(First) > Rank) 207 Rank = GetConversionRank(First); 208 if (GetConversionRank(Second) > Rank) 209 Rank = GetConversionRank(Second); 210 if (GetConversionRank(Third) > Rank) 211 Rank = GetConversionRank(Third); 212 return Rank; 213 } 214 215 /// isPointerConversionToBool - Determines whether this conversion is 216 /// a conversion of a pointer or pointer-to-member to bool. This is 217 /// used as part of the ranking of standard conversion sequences 218 /// (C++ 13.3.3.2p4). 219 bool StandardConversionSequence::isPointerConversionToBool() const { 220 // Note that FromType has not necessarily been transformed by the 221 // array-to-pointer or function-to-pointer implicit conversions, so 222 // check for their presence as well as checking whether FromType is 223 // a pointer. 224 if (getToType(1)->isBooleanType() && 225 (getFromType()->isPointerType() || 226 getFromType()->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 NarrowingKind 292 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 293 const Expr *Converted, 294 APValue &ConstantValue, 295 QualType &ConstantType) 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->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 331 llvm::APSInt IntConstantValue; 332 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 333 334 // If it's value-dependent, we can't tell whether it's narrowing. 335 if (Initializer->isValueDependent()) 336 return NK_Dependent_Narrowing; 337 338 if (Initializer && 339 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 340 // Convert the integer to the floating type. 341 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 342 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 343 llvm::APFloat::rmNearestTiesToEven); 344 // And back. 345 llvm::APSInt ConvertedValue = IntConstantValue; 346 bool ignored; 347 Result.convertToInteger(ConvertedValue, 348 llvm::APFloat::rmTowardZero, &ignored); 349 // If the resulting value is different, this was a narrowing conversion. 350 if (IntConstantValue != ConvertedValue) { 351 ConstantValue = APValue(IntConstantValue); 352 ConstantType = Initializer->getType(); 353 return NK_Constant_Narrowing; 354 } 355 } else { 356 // Variables are always narrowings. 357 return NK_Variable_Narrowing; 358 } 359 } 360 return NK_Not_Narrowing; 361 362 // -- from long double to double or float, or from double to float, except 363 // where the source is a constant expression and the actual value after 364 // conversion is within the range of values that can be represented (even 365 // if it cannot be represented exactly), or 366 case ICK_Floating_Conversion: 367 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 368 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 369 // FromType is larger than ToType. 370 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 371 372 // If it's value-dependent, we can't tell whether it's narrowing. 373 if (Initializer->isValueDependent()) 374 return NK_Dependent_Narrowing; 375 376 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 377 // Constant! 378 assert(ConstantValue.isFloat()); 379 llvm::APFloat FloatVal = ConstantValue.getFloat(); 380 // Convert the source value into the target type. 381 bool ignored; 382 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 383 Ctx.getFloatTypeSemantics(ToType), 384 llvm::APFloat::rmNearestTiesToEven, &ignored); 385 // If there was no overflow, the source value is within the range of 386 // values that can be represented. 387 if (ConvertStatus & llvm::APFloat::opOverflow) { 388 ConstantType = Initializer->getType(); 389 return NK_Constant_Narrowing; 390 } 391 } else { 392 return NK_Variable_Narrowing; 393 } 394 } 395 return NK_Not_Narrowing; 396 397 // -- from an integer type or unscoped enumeration type to an integer type 398 // that cannot represent all the values of the original type, except where 399 // the source is a constant expression and the actual value after 400 // conversion will fit into the target type and will produce the original 401 // value when converted back to the original type. 402 case ICK_Integral_Conversion: 403 IntegralConversion: { 404 assert(FromType->isIntegralOrUnscopedEnumerationType()); 405 assert(ToType->isIntegralOrUnscopedEnumerationType()); 406 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 407 const unsigned FromWidth = Ctx.getIntWidth(FromType); 408 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 409 const unsigned ToWidth = Ctx.getIntWidth(ToType); 410 411 if (FromWidth > ToWidth || 412 (FromWidth == ToWidth && FromSigned != ToSigned) || 413 (FromSigned && !ToSigned)) { 414 // Not all values of FromType can be represented in ToType. 415 llvm::APSInt InitializerValue; 416 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 417 418 // If it's value-dependent, we can't tell whether it's narrowing. 419 if (Initializer->isValueDependent()) 420 return NK_Dependent_Narrowing; 421 422 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 423 // Such conversions on variables are always narrowing. 424 return NK_Variable_Narrowing; 425 } 426 bool Narrowing = false; 427 if (FromWidth < ToWidth) { 428 // Negative -> unsigned is narrowing. Otherwise, more bits is never 429 // narrowing. 430 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 431 Narrowing = true; 432 } else { 433 // Add a bit to the InitializerValue so we don't have to worry about 434 // signed vs. unsigned comparisons. 435 InitializerValue = InitializerValue.extend( 436 InitializerValue.getBitWidth() + 1); 437 // Convert the initializer to and from the target width and signed-ness. 438 llvm::APSInt ConvertedValue = InitializerValue; 439 ConvertedValue = ConvertedValue.trunc(ToWidth); 440 ConvertedValue.setIsSigned(ToSigned); 441 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 442 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 443 // If the result is different, this was a narrowing conversion. 444 if (ConvertedValue != InitializerValue) 445 Narrowing = true; 446 } 447 if (Narrowing) { 448 ConstantType = Initializer->getType(); 449 ConstantValue = APValue(InitializerValue); 450 return NK_Constant_Narrowing; 451 } 452 } 453 return NK_Not_Narrowing; 454 } 455 456 default: 457 // Other kinds of conversions are not narrowings. 458 return NK_Not_Narrowing; 459 } 460 } 461 462 /// dump - Print this standard conversion sequence to standard 463 /// error. Useful for debugging overloading issues. 464 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 465 raw_ostream &OS = llvm::errs(); 466 bool PrintedSomething = false; 467 if (First != ICK_Identity) { 468 OS << GetImplicitConversionName(First); 469 PrintedSomething = true; 470 } 471 472 if (Second != ICK_Identity) { 473 if (PrintedSomething) { 474 OS << " -> "; 475 } 476 OS << GetImplicitConversionName(Second); 477 478 if (CopyConstructor) { 479 OS << " (by copy constructor)"; 480 } else if (DirectBinding) { 481 OS << " (direct reference binding)"; 482 } else if (ReferenceBinding) { 483 OS << " (reference binding)"; 484 } 485 PrintedSomething = true; 486 } 487 488 if (Third != ICK_Identity) { 489 if (PrintedSomething) { 490 OS << " -> "; 491 } 492 OS << GetImplicitConversionName(Third); 493 PrintedSomething = true; 494 } 495 496 if (!PrintedSomething) { 497 OS << "No conversions required"; 498 } 499 } 500 501 /// dump - Print this user-defined conversion sequence to standard 502 /// error. Useful for debugging overloading issues. 503 void UserDefinedConversionSequence::dump() const { 504 raw_ostream &OS = llvm::errs(); 505 if (Before.First || Before.Second || Before.Third) { 506 Before.dump(); 507 OS << " -> "; 508 } 509 if (ConversionFunction) 510 OS << '\'' << *ConversionFunction << '\''; 511 else 512 OS << "aggregate initialization"; 513 if (After.First || After.Second || After.Third) { 514 OS << " -> "; 515 After.dump(); 516 } 517 } 518 519 /// dump - Print this implicit conversion sequence to standard 520 /// error. Useful for debugging overloading issues. 521 void ImplicitConversionSequence::dump() const { 522 raw_ostream &OS = llvm::errs(); 523 if (isStdInitializerListElement()) 524 OS << "Worst std::initializer_list element conversion: "; 525 switch (ConversionKind) { 526 case StandardConversion: 527 OS << "Standard conversion: "; 528 Standard.dump(); 529 break; 530 case UserDefinedConversion: 531 OS << "User-defined conversion: "; 532 UserDefined.dump(); 533 break; 534 case EllipsisConversion: 535 OS << "Ellipsis conversion"; 536 break; 537 case AmbiguousConversion: 538 OS << "Ambiguous conversion"; 539 break; 540 case BadConversion: 541 OS << "Bad conversion"; 542 break; 543 } 544 545 OS << "\n"; 546 } 547 548 void AmbiguousConversionSequence::construct() { 549 new (&conversions()) ConversionSet(); 550 } 551 552 void AmbiguousConversionSequence::destruct() { 553 conversions().~ConversionSet(); 554 } 555 556 void 557 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 558 FromTypePtr = O.FromTypePtr; 559 ToTypePtr = O.ToTypePtr; 560 new (&conversions()) ConversionSet(O.conversions()); 561 } 562 563 namespace { 564 // Structure used by DeductionFailureInfo to store 565 // template argument information. 566 struct DFIArguments { 567 TemplateArgument FirstArg; 568 TemplateArgument SecondArg; 569 }; 570 // Structure used by DeductionFailureInfo to store 571 // template parameter and template argument information. 572 struct DFIParamWithArguments : DFIArguments { 573 TemplateParameter Param; 574 }; 575 // Structure used by DeductionFailureInfo to store template argument 576 // information and the index of the problematic call argument. 577 struct DFIDeducedMismatchArgs : DFIArguments { 578 TemplateArgumentList *TemplateArgs; 579 unsigned CallArgIndex; 580 }; 581 } 582 583 /// \brief Convert from Sema's representation of template deduction information 584 /// to the form used in overload-candidate information. 585 DeductionFailureInfo 586 clang::MakeDeductionFailureInfo(ASTContext &Context, 587 Sema::TemplateDeductionResult TDK, 588 TemplateDeductionInfo &Info) { 589 DeductionFailureInfo Result; 590 Result.Result = static_cast<unsigned>(TDK); 591 Result.HasDiagnostic = false; 592 switch (TDK) { 593 case Sema::TDK_Invalid: 594 case Sema::TDK_InstantiationDepth: 595 case Sema::TDK_TooManyArguments: 596 case Sema::TDK_TooFewArguments: 597 case Sema::TDK_MiscellaneousDeductionFailure: 598 case Sema::TDK_CUDATargetMismatch: 599 Result.Data = nullptr; 600 break; 601 602 case Sema::TDK_Incomplete: 603 case Sema::TDK_InvalidExplicitArguments: 604 Result.Data = Info.Param.getOpaqueValue(); 605 break; 606 607 case Sema::TDK_DeducedMismatch: 608 case Sema::TDK_DeducedMismatchNested: { 609 // FIXME: Should allocate from normal heap so that we can free this later. 610 auto *Saved = new (Context) DFIDeducedMismatchArgs; 611 Saved->FirstArg = Info.FirstArg; 612 Saved->SecondArg = Info.SecondArg; 613 Saved->TemplateArgs = Info.take(); 614 Saved->CallArgIndex = Info.CallArgIndex; 615 Result.Data = Saved; 616 break; 617 } 618 619 case Sema::TDK_NonDeducedMismatch: { 620 // FIXME: Should allocate from normal heap so that we can free this later. 621 DFIArguments *Saved = new (Context) DFIArguments; 622 Saved->FirstArg = Info.FirstArg; 623 Saved->SecondArg = Info.SecondArg; 624 Result.Data = Saved; 625 break; 626 } 627 628 case Sema::TDK_Inconsistent: 629 case Sema::TDK_Underqualified: { 630 // FIXME: Should allocate from normal heap so that we can free this later. 631 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 632 Saved->Param = Info.Param; 633 Saved->FirstArg = Info.FirstArg; 634 Saved->SecondArg = Info.SecondArg; 635 Result.Data = Saved; 636 break; 637 } 638 639 case Sema::TDK_SubstitutionFailure: 640 Result.Data = Info.take(); 641 if (Info.hasSFINAEDiagnostic()) { 642 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 643 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 644 Info.takeSFINAEDiagnostic(*Diag); 645 Result.HasDiagnostic = true; 646 } 647 break; 648 649 case Sema::TDK_Success: 650 case Sema::TDK_NonDependentConversionFailure: 651 llvm_unreachable("not a deduction failure"); 652 } 653 654 return Result; 655 } 656 657 void DeductionFailureInfo::Destroy() { 658 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 659 case Sema::TDK_Success: 660 case Sema::TDK_Invalid: 661 case Sema::TDK_InstantiationDepth: 662 case Sema::TDK_Incomplete: 663 case Sema::TDK_TooManyArguments: 664 case Sema::TDK_TooFewArguments: 665 case Sema::TDK_InvalidExplicitArguments: 666 case Sema::TDK_CUDATargetMismatch: 667 case Sema::TDK_NonDependentConversionFailure: 668 break; 669 670 case Sema::TDK_Inconsistent: 671 case Sema::TDK_Underqualified: 672 case Sema::TDK_DeducedMismatch: 673 case Sema::TDK_DeducedMismatchNested: 674 case Sema::TDK_NonDeducedMismatch: 675 // FIXME: Destroy the data? 676 Data = nullptr; 677 break; 678 679 case Sema::TDK_SubstitutionFailure: 680 // FIXME: Destroy the template argument list? 681 Data = nullptr; 682 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 683 Diag->~PartialDiagnosticAt(); 684 HasDiagnostic = false; 685 } 686 break; 687 688 // Unhandled 689 case Sema::TDK_MiscellaneousDeductionFailure: 690 break; 691 } 692 } 693 694 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 695 if (HasDiagnostic) 696 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 697 return nullptr; 698 } 699 700 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 702 case Sema::TDK_Success: 703 case Sema::TDK_Invalid: 704 case Sema::TDK_InstantiationDepth: 705 case Sema::TDK_TooManyArguments: 706 case Sema::TDK_TooFewArguments: 707 case Sema::TDK_SubstitutionFailure: 708 case Sema::TDK_DeducedMismatch: 709 case Sema::TDK_DeducedMismatchNested: 710 case Sema::TDK_NonDeducedMismatch: 711 case Sema::TDK_CUDATargetMismatch: 712 case Sema::TDK_NonDependentConversionFailure: 713 return TemplateParameter(); 714 715 case Sema::TDK_Incomplete: 716 case Sema::TDK_InvalidExplicitArguments: 717 return TemplateParameter::getFromOpaqueValue(Data); 718 719 case Sema::TDK_Inconsistent: 720 case Sema::TDK_Underqualified: 721 return static_cast<DFIParamWithArguments*>(Data)->Param; 722 723 // Unhandled 724 case Sema::TDK_MiscellaneousDeductionFailure: 725 break; 726 } 727 728 return TemplateParameter(); 729 } 730 731 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 733 case Sema::TDK_Success: 734 case Sema::TDK_Invalid: 735 case Sema::TDK_InstantiationDepth: 736 case Sema::TDK_TooManyArguments: 737 case Sema::TDK_TooFewArguments: 738 case Sema::TDK_Incomplete: 739 case Sema::TDK_InvalidExplicitArguments: 740 case Sema::TDK_Inconsistent: 741 case Sema::TDK_Underqualified: 742 case Sema::TDK_NonDeducedMismatch: 743 case Sema::TDK_CUDATargetMismatch: 744 case Sema::TDK_NonDependentConversionFailure: 745 return nullptr; 746 747 case Sema::TDK_DeducedMismatch: 748 case Sema::TDK_DeducedMismatchNested: 749 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 750 751 case Sema::TDK_SubstitutionFailure: 752 return static_cast<TemplateArgumentList*>(Data); 753 754 // Unhandled 755 case Sema::TDK_MiscellaneousDeductionFailure: 756 break; 757 } 758 759 return nullptr; 760 } 761 762 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 763 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 764 case Sema::TDK_Success: 765 case Sema::TDK_Invalid: 766 case Sema::TDK_InstantiationDepth: 767 case Sema::TDK_Incomplete: 768 case Sema::TDK_TooManyArguments: 769 case Sema::TDK_TooFewArguments: 770 case Sema::TDK_InvalidExplicitArguments: 771 case Sema::TDK_SubstitutionFailure: 772 case Sema::TDK_CUDATargetMismatch: 773 case Sema::TDK_NonDependentConversionFailure: 774 return nullptr; 775 776 case Sema::TDK_Inconsistent: 777 case Sema::TDK_Underqualified: 778 case Sema::TDK_DeducedMismatch: 779 case Sema::TDK_DeducedMismatchNested: 780 case Sema::TDK_NonDeducedMismatch: 781 return &static_cast<DFIArguments*>(Data)->FirstArg; 782 783 // Unhandled 784 case Sema::TDK_MiscellaneousDeductionFailure: 785 break; 786 } 787 788 return nullptr; 789 } 790 791 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 792 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 793 case Sema::TDK_Success: 794 case Sema::TDK_Invalid: 795 case Sema::TDK_InstantiationDepth: 796 case Sema::TDK_Incomplete: 797 case Sema::TDK_TooManyArguments: 798 case Sema::TDK_TooFewArguments: 799 case Sema::TDK_InvalidExplicitArguments: 800 case Sema::TDK_SubstitutionFailure: 801 case Sema::TDK_CUDATargetMismatch: 802 case Sema::TDK_NonDependentConversionFailure: 803 return nullptr; 804 805 case Sema::TDK_Inconsistent: 806 case Sema::TDK_Underqualified: 807 case Sema::TDK_DeducedMismatch: 808 case Sema::TDK_DeducedMismatchNested: 809 case Sema::TDK_NonDeducedMismatch: 810 return &static_cast<DFIArguments*>(Data)->SecondArg; 811 812 // Unhandled 813 case Sema::TDK_MiscellaneousDeductionFailure: 814 break; 815 } 816 817 return nullptr; 818 } 819 820 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 821 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 822 case Sema::TDK_DeducedMismatch: 823 case Sema::TDK_DeducedMismatchNested: 824 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 825 826 default: 827 return llvm::None; 828 } 829 } 830 831 void OverloadCandidateSet::destroyCandidates() { 832 for (iterator i = begin(), e = end(); i != e; ++i) { 833 for (auto &C : i->Conversions) 834 C.~ImplicitConversionSequence(); 835 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 836 i->DeductionFailure.Destroy(); 837 } 838 } 839 840 void OverloadCandidateSet::clear() { 841 destroyCandidates(); 842 // DiagnoseIfAttrs are just pointers, so we don't need to destroy them. 843 SlabAllocator.Reset(); 844 NumInlineBytesUsed = 0; 845 Candidates.clear(); 846 Functions.clear(); 847 } 848 849 DiagnoseIfAttr ** 850 OverloadCandidateSet::addDiagnoseIfComplaints(ArrayRef<DiagnoseIfAttr *> CA) { 851 auto *DIA = slabAllocate<DiagnoseIfAttr *>(CA.size()); 852 std::uninitialized_copy(CA.begin(), CA.end(), DIA); 853 return DIA; 854 } 855 856 namespace { 857 class UnbridgedCastsSet { 858 struct Entry { 859 Expr **Addr; 860 Expr *Saved; 861 }; 862 SmallVector<Entry, 2> Entries; 863 864 public: 865 void save(Sema &S, Expr *&E) { 866 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 867 Entry entry = { &E, E }; 868 Entries.push_back(entry); 869 E = S.stripARCUnbridgedCast(E); 870 } 871 872 void restore() { 873 for (SmallVectorImpl<Entry>::iterator 874 i = Entries.begin(), e = Entries.end(); i != e; ++i) 875 *i->Addr = i->Saved; 876 } 877 }; 878 } 879 880 /// checkPlaceholderForOverload - Do any interesting placeholder-like 881 /// preprocessing on the given expression. 882 /// 883 /// \param unbridgedCasts a collection to which to add unbridged casts; 884 /// without this, they will be immediately diagnosed as errors 885 /// 886 /// Return true on unrecoverable error. 887 static bool 888 checkPlaceholderForOverload(Sema &S, Expr *&E, 889 UnbridgedCastsSet *unbridgedCasts = nullptr) { 890 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 891 // We can't handle overloaded expressions here because overload 892 // resolution might reasonably tweak them. 893 if (placeholder->getKind() == BuiltinType::Overload) return false; 894 895 // If the context potentially accepts unbridged ARC casts, strip 896 // the unbridged cast and add it to the collection for later restoration. 897 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 898 unbridgedCasts) { 899 unbridgedCasts->save(S, E); 900 return false; 901 } 902 903 // Go ahead and check everything else. 904 ExprResult result = S.CheckPlaceholderExpr(E); 905 if (result.isInvalid()) 906 return true; 907 908 E = result.get(); 909 return false; 910 } 911 912 // Nothing to do. 913 return false; 914 } 915 916 /// checkArgPlaceholdersForOverload - Check a set of call operands for 917 /// placeholders. 918 static bool checkArgPlaceholdersForOverload(Sema &S, 919 MultiExprArg Args, 920 UnbridgedCastsSet &unbridged) { 921 for (unsigned i = 0, e = Args.size(); i != e; ++i) 922 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 923 return true; 924 925 return false; 926 } 927 928 // IsOverload - Determine whether the given New declaration is an 929 // overload of the declarations in Old. This routine returns false if 930 // New and Old cannot be overloaded, e.g., if New has the same 931 // signature as some function in Old (C++ 1.3.10) or if the Old 932 // declarations aren't functions (or function templates) at all. When 933 // it does return false, MatchedDecl will point to the decl that New 934 // cannot be overloaded with. This decl may be a UsingShadowDecl on 935 // top of the underlying declaration. 936 // 937 // Example: Given the following input: 938 // 939 // void f(int, float); // #1 940 // void f(int, int); // #2 941 // int f(int, int); // #3 942 // 943 // When we process #1, there is no previous declaration of "f", 944 // so IsOverload will not be used. 945 // 946 // When we process #2, Old contains only the FunctionDecl for #1. By 947 // comparing the parameter types, we see that #1 and #2 are overloaded 948 // (since they have different signatures), so this routine returns 949 // false; MatchedDecl is unchanged. 950 // 951 // When we process #3, Old is an overload set containing #1 and #2. We 952 // compare the signatures of #3 to #1 (they're overloaded, so we do 953 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 954 // identical (return types of functions are not part of the 955 // signature), IsOverload returns false and MatchedDecl will be set to 956 // point to the FunctionDecl for #2. 957 // 958 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 959 // into a class by a using declaration. The rules for whether to hide 960 // shadow declarations ignore some properties which otherwise figure 961 // into a function template's signature. 962 Sema::OverloadKind 963 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 964 NamedDecl *&Match, bool NewIsUsingDecl) { 965 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 966 I != E; ++I) { 967 NamedDecl *OldD = *I; 968 969 bool OldIsUsingDecl = false; 970 if (isa<UsingShadowDecl>(OldD)) { 971 OldIsUsingDecl = true; 972 973 // We can always introduce two using declarations into the same 974 // context, even if they have identical signatures. 975 if (NewIsUsingDecl) continue; 976 977 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 978 } 979 980 // A using-declaration does not conflict with another declaration 981 // if one of them is hidden. 982 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 983 continue; 984 985 // If either declaration was introduced by a using declaration, 986 // we'll need to use slightly different rules for matching. 987 // Essentially, these rules are the normal rules, except that 988 // function templates hide function templates with different 989 // return types or template parameter lists. 990 bool UseMemberUsingDeclRules = 991 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 992 !New->getFriendObjectKind(); 993 994 if (FunctionDecl *OldF = OldD->getAsFunction()) { 995 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 996 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 997 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 998 continue; 999 } 1000 1001 if (!isa<FunctionTemplateDecl>(OldD) && 1002 !shouldLinkPossiblyHiddenDecl(*I, New)) 1003 continue; 1004 1005 Match = *I; 1006 return Ovl_Match; 1007 } 1008 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1009 // We can overload with these, which can show up when doing 1010 // redeclaration checks for UsingDecls. 1011 assert(Old.getLookupKind() == LookupUsingDeclName); 1012 } else if (isa<TagDecl>(OldD)) { 1013 // We can always overload with tags by hiding them. 1014 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1015 // Optimistically assume that an unresolved using decl will 1016 // overload; if it doesn't, we'll have to diagnose during 1017 // template instantiation. 1018 // 1019 // Exception: if the scope is dependent and this is not a class 1020 // member, the using declaration can only introduce an enumerator. 1021 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1022 Match = *I; 1023 return Ovl_NonFunction; 1024 } 1025 } else { 1026 // (C++ 13p1): 1027 // Only function declarations can be overloaded; object and type 1028 // declarations cannot be overloaded. 1029 Match = *I; 1030 return Ovl_NonFunction; 1031 } 1032 } 1033 1034 return Ovl_Overload; 1035 } 1036 1037 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1038 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1039 // C++ [basic.start.main]p2: This function shall not be overloaded. 1040 if (New->isMain()) 1041 return false; 1042 1043 // MSVCRT user defined entry points cannot be overloaded. 1044 if (New->isMSVCRTEntryPoint()) 1045 return false; 1046 1047 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1048 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1049 1050 // C++ [temp.fct]p2: 1051 // A function template can be overloaded with other function templates 1052 // and with normal (non-template) functions. 1053 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1054 return true; 1055 1056 // Is the function New an overload of the function Old? 1057 QualType OldQType = Context.getCanonicalType(Old->getType()); 1058 QualType NewQType = Context.getCanonicalType(New->getType()); 1059 1060 // Compare the signatures (C++ 1.3.10) of the two functions to 1061 // determine whether they are overloads. If we find any mismatch 1062 // in the signature, they are overloads. 1063 1064 // If either of these functions is a K&R-style function (no 1065 // prototype), then we consider them to have matching signatures. 1066 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1067 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1068 return false; 1069 1070 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1071 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1072 1073 // The signature of a function includes the types of its 1074 // parameters (C++ 1.3.10), which includes the presence or absence 1075 // of the ellipsis; see C++ DR 357). 1076 if (OldQType != NewQType && 1077 (OldType->getNumParams() != NewType->getNumParams() || 1078 OldType->isVariadic() != NewType->isVariadic() || 1079 !FunctionParamTypesAreEqual(OldType, NewType))) 1080 return true; 1081 1082 // C++ [temp.over.link]p4: 1083 // The signature of a function template consists of its function 1084 // signature, its return type and its template parameter list. The names 1085 // of the template parameters are significant only for establishing the 1086 // relationship between the template parameters and the rest of the 1087 // signature. 1088 // 1089 // We check the return type and template parameter lists for function 1090 // templates first; the remaining checks follow. 1091 // 1092 // However, we don't consider either of these when deciding whether 1093 // a member introduced by a shadow declaration is hidden. 1094 if (!UseMemberUsingDeclRules && NewTemplate && 1095 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1096 OldTemplate->getTemplateParameters(), 1097 false, TPL_TemplateMatch) || 1098 OldType->getReturnType() != NewType->getReturnType())) 1099 return true; 1100 1101 // If the function is a class member, its signature includes the 1102 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1103 // 1104 // As part of this, also check whether one of the member functions 1105 // is static, in which case they are not overloads (C++ 1106 // 13.1p2). While not part of the definition of the signature, 1107 // this check is important to determine whether these functions 1108 // can be overloaded. 1109 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1110 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1111 if (OldMethod && NewMethod && 1112 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1113 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1114 if (!UseMemberUsingDeclRules && 1115 (OldMethod->getRefQualifier() == RQ_None || 1116 NewMethod->getRefQualifier() == RQ_None)) { 1117 // C++0x [over.load]p2: 1118 // - Member function declarations with the same name and the same 1119 // parameter-type-list as well as member function template 1120 // declarations with the same name, the same parameter-type-list, and 1121 // the same template parameter lists cannot be overloaded if any of 1122 // them, but not all, have a ref-qualifier (8.3.5). 1123 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1124 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1125 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1126 } 1127 return true; 1128 } 1129 1130 // We may not have applied the implicit const for a constexpr member 1131 // function yet (because we haven't yet resolved whether this is a static 1132 // or non-static member function). Add it now, on the assumption that this 1133 // is a redeclaration of OldMethod. 1134 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1135 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1136 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1137 !isa<CXXConstructorDecl>(NewMethod)) 1138 NewQuals |= Qualifiers::Const; 1139 1140 // We do not allow overloading based off of '__restrict'. 1141 OldQuals &= ~Qualifiers::Restrict; 1142 NewQuals &= ~Qualifiers::Restrict; 1143 if (OldQuals != NewQuals) 1144 return true; 1145 } 1146 1147 // Though pass_object_size is placed on parameters and takes an argument, we 1148 // consider it to be a function-level modifier for the sake of function 1149 // identity. Either the function has one or more parameters with 1150 // pass_object_size or it doesn't. 1151 if (functionHasPassObjectSizeParams(New) != 1152 functionHasPassObjectSizeParams(Old)) 1153 return true; 1154 1155 // enable_if attributes are an order-sensitive part of the signature. 1156 for (specific_attr_iterator<EnableIfAttr> 1157 NewI = New->specific_attr_begin<EnableIfAttr>(), 1158 NewE = New->specific_attr_end<EnableIfAttr>(), 1159 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1160 OldE = Old->specific_attr_end<EnableIfAttr>(); 1161 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1162 if (NewI == NewE || OldI == OldE) 1163 return true; 1164 llvm::FoldingSetNodeID NewID, OldID; 1165 NewI->getCond()->Profile(NewID, Context, true); 1166 OldI->getCond()->Profile(OldID, Context, true); 1167 if (NewID != OldID) 1168 return true; 1169 } 1170 1171 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1172 // Don't allow overloading of destructors. (In theory we could, but it 1173 // would be a giant change to clang.) 1174 if (isa<CXXDestructorDecl>(New)) 1175 return false; 1176 1177 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1178 OldTarget = IdentifyCUDATarget(Old); 1179 if (NewTarget == CFT_InvalidTarget) 1180 return false; 1181 1182 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1183 1184 // Allow overloading of functions with same signature and different CUDA 1185 // target attributes. 1186 return NewTarget != OldTarget; 1187 } 1188 1189 // The signatures match; this is not an overload. 1190 return false; 1191 } 1192 1193 /// \brief Checks availability of the function depending on the current 1194 /// function context. Inside an unavailable function, unavailability is ignored. 1195 /// 1196 /// \returns true if \arg FD is unavailable and current context is inside 1197 /// an available function, false otherwise. 1198 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1199 if (!FD->isUnavailable()) 1200 return false; 1201 1202 // Walk up the context of the caller. 1203 Decl *C = cast<Decl>(CurContext); 1204 do { 1205 if (C->isUnavailable()) 1206 return false; 1207 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1208 return true; 1209 } 1210 1211 /// \brief Tries a user-defined conversion from From to ToType. 1212 /// 1213 /// Produces an implicit conversion sequence for when a standard conversion 1214 /// is not an option. See TryImplicitConversion for more information. 1215 static ImplicitConversionSequence 1216 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1217 bool SuppressUserConversions, 1218 bool AllowExplicit, 1219 bool InOverloadResolution, 1220 bool CStyle, 1221 bool AllowObjCWritebackConversion, 1222 bool AllowObjCConversionOnExplicit) { 1223 ImplicitConversionSequence ICS; 1224 1225 if (SuppressUserConversions) { 1226 // We're not in the case above, so there is no conversion that 1227 // we can perform. 1228 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1229 return ICS; 1230 } 1231 1232 // Attempt user-defined conversion. 1233 OverloadCandidateSet Conversions(From->getExprLoc(), 1234 OverloadCandidateSet::CSK_Normal); 1235 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1236 Conversions, AllowExplicit, 1237 AllowObjCConversionOnExplicit)) { 1238 case OR_Success: 1239 case OR_Deleted: 1240 ICS.setUserDefined(); 1241 // C++ [over.ics.user]p4: 1242 // A conversion of an expression of class type to the same class 1243 // type is given Exact Match rank, and a conversion of an 1244 // expression of class type to a base class of that type is 1245 // given Conversion rank, in spite of the fact that a copy 1246 // constructor (i.e., a user-defined conversion function) is 1247 // called for those cases. 1248 if (CXXConstructorDecl *Constructor 1249 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1250 QualType FromCanon 1251 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1252 QualType ToCanon 1253 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1254 if (Constructor->isCopyConstructor() && 1255 (FromCanon == ToCanon || 1256 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1257 // Turn this into a "standard" conversion sequence, so that it 1258 // gets ranked with standard conversion sequences. 1259 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1260 ICS.setStandard(); 1261 ICS.Standard.setAsIdentityConversion(); 1262 ICS.Standard.setFromType(From->getType()); 1263 ICS.Standard.setAllToTypes(ToType); 1264 ICS.Standard.CopyConstructor = Constructor; 1265 ICS.Standard.FoundCopyConstructor = Found; 1266 if (ToCanon != FromCanon) 1267 ICS.Standard.Second = ICK_Derived_To_Base; 1268 } 1269 } 1270 break; 1271 1272 case OR_Ambiguous: 1273 ICS.setAmbiguous(); 1274 ICS.Ambiguous.setFromType(From->getType()); 1275 ICS.Ambiguous.setToType(ToType); 1276 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1277 Cand != Conversions.end(); ++Cand) 1278 if (Cand->Viable) 1279 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1280 break; 1281 1282 // Fall through. 1283 case OR_No_Viable_Function: 1284 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1285 break; 1286 } 1287 1288 return ICS; 1289 } 1290 1291 /// TryImplicitConversion - Attempt to perform an implicit conversion 1292 /// from the given expression (Expr) to the given type (ToType). This 1293 /// function returns an implicit conversion sequence that can be used 1294 /// to perform the initialization. Given 1295 /// 1296 /// void f(float f); 1297 /// void g(int i) { f(i); } 1298 /// 1299 /// this routine would produce an implicit conversion sequence to 1300 /// describe the initialization of f from i, which will be a standard 1301 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1302 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1303 // 1304 /// Note that this routine only determines how the conversion can be 1305 /// performed; it does not actually perform the conversion. As such, 1306 /// it will not produce any diagnostics if no conversion is available, 1307 /// but will instead return an implicit conversion sequence of kind 1308 /// "BadConversion". 1309 /// 1310 /// If @p SuppressUserConversions, then user-defined conversions are 1311 /// not permitted. 1312 /// If @p AllowExplicit, then explicit user-defined conversions are 1313 /// permitted. 1314 /// 1315 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1316 /// writeback conversion, which allows __autoreleasing id* parameters to 1317 /// be initialized with __strong id* or __weak id* arguments. 1318 static ImplicitConversionSequence 1319 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1320 bool SuppressUserConversions, 1321 bool AllowExplicit, 1322 bool InOverloadResolution, 1323 bool CStyle, 1324 bool AllowObjCWritebackConversion, 1325 bool AllowObjCConversionOnExplicit) { 1326 ImplicitConversionSequence ICS; 1327 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1328 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1329 ICS.setStandard(); 1330 return ICS; 1331 } 1332 1333 if (!S.getLangOpts().CPlusPlus) { 1334 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1335 return ICS; 1336 } 1337 1338 // C++ [over.ics.user]p4: 1339 // A conversion of an expression of class type to the same class 1340 // type is given Exact Match rank, and a conversion of an 1341 // expression of class type to a base class of that type is 1342 // given Conversion rank, in spite of the fact that a copy/move 1343 // constructor (i.e., a user-defined conversion function) is 1344 // called for those cases. 1345 QualType FromType = From->getType(); 1346 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1347 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1348 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1349 ICS.setStandard(); 1350 ICS.Standard.setAsIdentityConversion(); 1351 ICS.Standard.setFromType(FromType); 1352 ICS.Standard.setAllToTypes(ToType); 1353 1354 // We don't actually check at this point whether there is a valid 1355 // copy/move constructor, since overloading just assumes that it 1356 // exists. When we actually perform initialization, we'll find the 1357 // appropriate constructor to copy the returned object, if needed. 1358 ICS.Standard.CopyConstructor = nullptr; 1359 1360 // Determine whether this is considered a derived-to-base conversion. 1361 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1362 ICS.Standard.Second = ICK_Derived_To_Base; 1363 1364 return ICS; 1365 } 1366 1367 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1368 AllowExplicit, InOverloadResolution, CStyle, 1369 AllowObjCWritebackConversion, 1370 AllowObjCConversionOnExplicit); 1371 } 1372 1373 ImplicitConversionSequence 1374 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1375 bool SuppressUserConversions, 1376 bool AllowExplicit, 1377 bool InOverloadResolution, 1378 bool CStyle, 1379 bool AllowObjCWritebackConversion) { 1380 return ::TryImplicitConversion(*this, From, ToType, 1381 SuppressUserConversions, AllowExplicit, 1382 InOverloadResolution, CStyle, 1383 AllowObjCWritebackConversion, 1384 /*AllowObjCConversionOnExplicit=*/false); 1385 } 1386 1387 /// PerformImplicitConversion - Perform an implicit conversion of the 1388 /// expression From to the type ToType. Returns the 1389 /// converted expression. Flavor is the kind of conversion we're 1390 /// performing, used in the error message. If @p AllowExplicit, 1391 /// explicit user-defined conversions are permitted. 1392 ExprResult 1393 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1394 AssignmentAction Action, bool AllowExplicit) { 1395 ImplicitConversionSequence ICS; 1396 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1397 } 1398 1399 ExprResult 1400 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1401 AssignmentAction Action, bool AllowExplicit, 1402 ImplicitConversionSequence& ICS) { 1403 if (checkPlaceholderForOverload(*this, From)) 1404 return ExprError(); 1405 1406 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1407 bool AllowObjCWritebackConversion 1408 = getLangOpts().ObjCAutoRefCount && 1409 (Action == AA_Passing || Action == AA_Sending); 1410 if (getLangOpts().ObjC1) 1411 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1412 ToType, From->getType(), From); 1413 ICS = ::TryImplicitConversion(*this, From, ToType, 1414 /*SuppressUserConversions=*/false, 1415 AllowExplicit, 1416 /*InOverloadResolution=*/false, 1417 /*CStyle=*/false, 1418 AllowObjCWritebackConversion, 1419 /*AllowObjCConversionOnExplicit=*/false); 1420 return PerformImplicitConversion(From, ToType, ICS, Action); 1421 } 1422 1423 /// \brief Determine whether the conversion from FromType to ToType is a valid 1424 /// conversion that strips "noexcept" or "noreturn" off the nested function 1425 /// type. 1426 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1427 QualType &ResultTy) { 1428 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1429 return false; 1430 1431 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1432 // or F(t noexcept) -> F(t) 1433 // where F adds one of the following at most once: 1434 // - a pointer 1435 // - a member pointer 1436 // - a block pointer 1437 // Changes here need matching changes in FindCompositePointerType. 1438 CanQualType CanTo = Context.getCanonicalType(ToType); 1439 CanQualType CanFrom = Context.getCanonicalType(FromType); 1440 Type::TypeClass TyClass = CanTo->getTypeClass(); 1441 if (TyClass != CanFrom->getTypeClass()) return false; 1442 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1443 if (TyClass == Type::Pointer) { 1444 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1445 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1446 } else if (TyClass == Type::BlockPointer) { 1447 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1448 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1449 } else if (TyClass == Type::MemberPointer) { 1450 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1451 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1452 // A function pointer conversion cannot change the class of the function. 1453 if (ToMPT->getClass() != FromMPT->getClass()) 1454 return false; 1455 CanTo = ToMPT->getPointeeType(); 1456 CanFrom = FromMPT->getPointeeType(); 1457 } else { 1458 return false; 1459 } 1460 1461 TyClass = CanTo->getTypeClass(); 1462 if (TyClass != CanFrom->getTypeClass()) return false; 1463 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1464 return false; 1465 } 1466 1467 const auto *FromFn = cast<FunctionType>(CanFrom); 1468 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1469 1470 const auto *ToFn = cast<FunctionType>(CanTo); 1471 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1472 1473 bool Changed = false; 1474 1475 // Drop 'noreturn' if not present in target type. 1476 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1477 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1478 Changed = true; 1479 } 1480 1481 // Drop 'noexcept' if not present in target type. 1482 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1483 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1484 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) { 1485 FromFn = cast<FunctionType>( 1486 Context.getFunctionType(FromFPT->getReturnType(), 1487 FromFPT->getParamTypes(), 1488 FromFPT->getExtProtoInfo().withExceptionSpec( 1489 FunctionProtoType::ExceptionSpecInfo())) 1490 .getTypePtr()); 1491 Changed = true; 1492 } 1493 } 1494 1495 if (!Changed) 1496 return false; 1497 1498 assert(QualType(FromFn, 0).isCanonical()); 1499 if (QualType(FromFn, 0) != CanTo) return false; 1500 1501 ResultTy = ToType; 1502 return true; 1503 } 1504 1505 /// \brief Determine whether the conversion from FromType to ToType is a valid 1506 /// vector conversion. 1507 /// 1508 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1509 /// conversion. 1510 static bool IsVectorConversion(Sema &S, QualType FromType, 1511 QualType ToType, ImplicitConversionKind &ICK) { 1512 // We need at least one of these types to be a vector type to have a vector 1513 // conversion. 1514 if (!ToType->isVectorType() && !FromType->isVectorType()) 1515 return false; 1516 1517 // Identical types require no conversions. 1518 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1519 return false; 1520 1521 // There are no conversions between extended vector types, only identity. 1522 if (ToType->isExtVectorType()) { 1523 // There are no conversions between extended vector types other than the 1524 // identity conversion. 1525 if (FromType->isExtVectorType()) 1526 return false; 1527 1528 // Vector splat from any arithmetic type to a vector. 1529 if (FromType->isArithmeticType()) { 1530 ICK = ICK_Vector_Splat; 1531 return true; 1532 } 1533 } 1534 1535 // We can perform the conversion between vector types in the following cases: 1536 // 1)vector types are equivalent AltiVec and GCC vector types 1537 // 2)lax vector conversions are permitted and the vector types are of the 1538 // same size 1539 if (ToType->isVectorType() && FromType->isVectorType()) { 1540 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1541 S.isLaxVectorConversion(FromType, ToType)) { 1542 ICK = ICK_Vector_Conversion; 1543 return true; 1544 } 1545 } 1546 1547 return false; 1548 } 1549 1550 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1551 bool InOverloadResolution, 1552 StandardConversionSequence &SCS, 1553 bool CStyle); 1554 1555 /// IsStandardConversion - Determines whether there is a standard 1556 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1557 /// expression From to the type ToType. Standard conversion sequences 1558 /// only consider non-class types; for conversions that involve class 1559 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1560 /// contain the standard conversion sequence required to perform this 1561 /// conversion and this routine will return true. Otherwise, this 1562 /// routine will return false and the value of SCS is unspecified. 1563 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1564 bool InOverloadResolution, 1565 StandardConversionSequence &SCS, 1566 bool CStyle, 1567 bool AllowObjCWritebackConversion) { 1568 QualType FromType = From->getType(); 1569 1570 // Standard conversions (C++ [conv]) 1571 SCS.setAsIdentityConversion(); 1572 SCS.IncompatibleObjC = false; 1573 SCS.setFromType(FromType); 1574 SCS.CopyConstructor = nullptr; 1575 1576 // There are no standard conversions for class types in C++, so 1577 // abort early. When overloading in C, however, we do permit them. 1578 if (S.getLangOpts().CPlusPlus && 1579 (FromType->isRecordType() || ToType->isRecordType())) 1580 return false; 1581 1582 // The first conversion can be an lvalue-to-rvalue conversion, 1583 // array-to-pointer conversion, or function-to-pointer conversion 1584 // (C++ 4p1). 1585 1586 if (FromType == S.Context.OverloadTy) { 1587 DeclAccessPair AccessPair; 1588 if (FunctionDecl *Fn 1589 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1590 AccessPair)) { 1591 // We were able to resolve the address of the overloaded function, 1592 // so we can convert to the type of that function. 1593 FromType = Fn->getType(); 1594 SCS.setFromType(FromType); 1595 1596 // we can sometimes resolve &foo<int> regardless of ToType, so check 1597 // if the type matches (identity) or we are converting to bool 1598 if (!S.Context.hasSameUnqualifiedType( 1599 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1600 QualType resultTy; 1601 // if the function type matches except for [[noreturn]], it's ok 1602 if (!S.IsFunctionConversion(FromType, 1603 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1604 // otherwise, only a boolean conversion is standard 1605 if (!ToType->isBooleanType()) 1606 return false; 1607 } 1608 1609 // Check if the "from" expression is taking the address of an overloaded 1610 // function and recompute the FromType accordingly. Take advantage of the 1611 // fact that non-static member functions *must* have such an address-of 1612 // expression. 1613 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1614 if (Method && !Method->isStatic()) { 1615 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1616 "Non-unary operator on non-static member address"); 1617 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1618 == UO_AddrOf && 1619 "Non-address-of operator on non-static member address"); 1620 const Type *ClassType 1621 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1622 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1623 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1624 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1625 UO_AddrOf && 1626 "Non-address-of operator for overloaded function expression"); 1627 FromType = S.Context.getPointerType(FromType); 1628 } 1629 1630 // Check that we've computed the proper type after overload resolution. 1631 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1632 // be calling it from within an NDEBUG block. 1633 assert(S.Context.hasSameType( 1634 FromType, 1635 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1636 } else { 1637 return false; 1638 } 1639 } 1640 // Lvalue-to-rvalue conversion (C++11 4.1): 1641 // A glvalue (3.10) of a non-function, non-array type T can 1642 // be converted to a prvalue. 1643 bool argIsLValue = From->isGLValue(); 1644 if (argIsLValue && 1645 !FromType->isFunctionType() && !FromType->isArrayType() && 1646 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1647 SCS.First = ICK_Lvalue_To_Rvalue; 1648 1649 // C11 6.3.2.1p2: 1650 // ... if the lvalue has atomic type, the value has the non-atomic version 1651 // of the type of the lvalue ... 1652 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1653 FromType = Atomic->getValueType(); 1654 1655 // If T is a non-class type, the type of the rvalue is the 1656 // cv-unqualified version of T. Otherwise, the type of the rvalue 1657 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1658 // just strip the qualifiers because they don't matter. 1659 FromType = FromType.getUnqualifiedType(); 1660 } else if (FromType->isArrayType()) { 1661 // Array-to-pointer conversion (C++ 4.2) 1662 SCS.First = ICK_Array_To_Pointer; 1663 1664 // An lvalue or rvalue of type "array of N T" or "array of unknown 1665 // bound of T" can be converted to an rvalue of type "pointer to 1666 // T" (C++ 4.2p1). 1667 FromType = S.Context.getArrayDecayedType(FromType); 1668 1669 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1670 // This conversion is deprecated in C++03 (D.4) 1671 SCS.DeprecatedStringLiteralToCharPtr = true; 1672 1673 // For the purpose of ranking in overload resolution 1674 // (13.3.3.1.1), this conversion is considered an 1675 // array-to-pointer conversion followed by a qualification 1676 // conversion (4.4). (C++ 4.2p2) 1677 SCS.Second = ICK_Identity; 1678 SCS.Third = ICK_Qualification; 1679 SCS.QualificationIncludesObjCLifetime = false; 1680 SCS.setAllToTypes(FromType); 1681 return true; 1682 } 1683 } else if (FromType->isFunctionType() && argIsLValue) { 1684 // Function-to-pointer conversion (C++ 4.3). 1685 SCS.First = ICK_Function_To_Pointer; 1686 1687 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1688 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1689 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1690 return false; 1691 1692 // An lvalue of function type T can be converted to an rvalue of 1693 // type "pointer to T." The result is a pointer to the 1694 // function. (C++ 4.3p1). 1695 FromType = S.Context.getPointerType(FromType); 1696 } else { 1697 // We don't require any conversions for the first step. 1698 SCS.First = ICK_Identity; 1699 } 1700 SCS.setToType(0, FromType); 1701 1702 // The second conversion can be an integral promotion, floating 1703 // point promotion, integral conversion, floating point conversion, 1704 // floating-integral conversion, pointer conversion, 1705 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1706 // For overloading in C, this can also be a "compatible-type" 1707 // conversion. 1708 bool IncompatibleObjC = false; 1709 ImplicitConversionKind SecondICK = ICK_Identity; 1710 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1711 // The unqualified versions of the types are the same: there's no 1712 // conversion to do. 1713 SCS.Second = ICK_Identity; 1714 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1715 // Integral promotion (C++ 4.5). 1716 SCS.Second = ICK_Integral_Promotion; 1717 FromType = ToType.getUnqualifiedType(); 1718 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1719 // Floating point promotion (C++ 4.6). 1720 SCS.Second = ICK_Floating_Promotion; 1721 FromType = ToType.getUnqualifiedType(); 1722 } else if (S.IsComplexPromotion(FromType, ToType)) { 1723 // Complex promotion (Clang extension) 1724 SCS.Second = ICK_Complex_Promotion; 1725 FromType = ToType.getUnqualifiedType(); 1726 } else if (ToType->isBooleanType() && 1727 (FromType->isArithmeticType() || 1728 FromType->isAnyPointerType() || 1729 FromType->isBlockPointerType() || 1730 FromType->isMemberPointerType() || 1731 FromType->isNullPtrType())) { 1732 // Boolean conversions (C++ 4.12). 1733 SCS.Second = ICK_Boolean_Conversion; 1734 FromType = S.Context.BoolTy; 1735 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1736 ToType->isIntegralType(S.Context)) { 1737 // Integral conversions (C++ 4.7). 1738 SCS.Second = ICK_Integral_Conversion; 1739 FromType = ToType.getUnqualifiedType(); 1740 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1741 // Complex conversions (C99 6.3.1.6) 1742 SCS.Second = ICK_Complex_Conversion; 1743 FromType = ToType.getUnqualifiedType(); 1744 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1745 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1746 // Complex-real conversions (C99 6.3.1.7) 1747 SCS.Second = ICK_Complex_Real; 1748 FromType = ToType.getUnqualifiedType(); 1749 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1750 // FIXME: disable conversions between long double and __float128 if 1751 // their representation is different until there is back end support 1752 // We of course allow this conversion if long double is really double. 1753 if (&S.Context.getFloatTypeSemantics(FromType) != 1754 &S.Context.getFloatTypeSemantics(ToType)) { 1755 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1756 ToType == S.Context.LongDoubleTy) || 1757 (FromType == S.Context.LongDoubleTy && 1758 ToType == S.Context.Float128Ty)); 1759 if (Float128AndLongDouble && 1760 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1761 &llvm::APFloat::IEEEdouble())) 1762 return false; 1763 } 1764 // Floating point conversions (C++ 4.8). 1765 SCS.Second = ICK_Floating_Conversion; 1766 FromType = ToType.getUnqualifiedType(); 1767 } else if ((FromType->isRealFloatingType() && 1768 ToType->isIntegralType(S.Context)) || 1769 (FromType->isIntegralOrUnscopedEnumerationType() && 1770 ToType->isRealFloatingType())) { 1771 // Floating-integral conversions (C++ 4.9). 1772 SCS.Second = ICK_Floating_Integral; 1773 FromType = ToType.getUnqualifiedType(); 1774 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1775 SCS.Second = ICK_Block_Pointer_Conversion; 1776 } else if (AllowObjCWritebackConversion && 1777 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1778 SCS.Second = ICK_Writeback_Conversion; 1779 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1780 FromType, IncompatibleObjC)) { 1781 // Pointer conversions (C++ 4.10). 1782 SCS.Second = ICK_Pointer_Conversion; 1783 SCS.IncompatibleObjC = IncompatibleObjC; 1784 FromType = FromType.getUnqualifiedType(); 1785 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1786 InOverloadResolution, FromType)) { 1787 // Pointer to member conversions (4.11). 1788 SCS.Second = ICK_Pointer_Member; 1789 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1790 SCS.Second = SecondICK; 1791 FromType = ToType.getUnqualifiedType(); 1792 } else if (!S.getLangOpts().CPlusPlus && 1793 S.Context.typesAreCompatible(ToType, FromType)) { 1794 // Compatible conversions (Clang extension for C function overloading) 1795 SCS.Second = ICK_Compatible_Conversion; 1796 FromType = ToType.getUnqualifiedType(); 1797 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1798 InOverloadResolution, 1799 SCS, CStyle)) { 1800 SCS.Second = ICK_TransparentUnionConversion; 1801 FromType = ToType; 1802 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1803 CStyle)) { 1804 // tryAtomicConversion has updated the standard conversion sequence 1805 // appropriately. 1806 return true; 1807 } else if (ToType->isEventT() && 1808 From->isIntegerConstantExpr(S.getASTContext()) && 1809 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1810 SCS.Second = ICK_Zero_Event_Conversion; 1811 FromType = ToType; 1812 } else if (ToType->isQueueT() && 1813 From->isIntegerConstantExpr(S.getASTContext()) && 1814 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1815 SCS.Second = ICK_Zero_Queue_Conversion; 1816 FromType = ToType; 1817 } else { 1818 // No second conversion required. 1819 SCS.Second = ICK_Identity; 1820 } 1821 SCS.setToType(1, FromType); 1822 1823 // The third conversion can be a function pointer conversion or a 1824 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1825 bool ObjCLifetimeConversion; 1826 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1827 // Function pointer conversions (removing 'noexcept') including removal of 1828 // 'noreturn' (Clang extension). 1829 SCS.Third = ICK_Function_Conversion; 1830 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1831 ObjCLifetimeConversion)) { 1832 SCS.Third = ICK_Qualification; 1833 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1834 FromType = ToType; 1835 } else { 1836 // No conversion required 1837 SCS.Third = ICK_Identity; 1838 } 1839 1840 // C++ [over.best.ics]p6: 1841 // [...] Any difference in top-level cv-qualification is 1842 // subsumed by the initialization itself and does not constitute 1843 // a conversion. [...] 1844 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1845 QualType CanonTo = S.Context.getCanonicalType(ToType); 1846 if (CanonFrom.getLocalUnqualifiedType() 1847 == CanonTo.getLocalUnqualifiedType() && 1848 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1849 FromType = ToType; 1850 CanonFrom = CanonTo; 1851 } 1852 1853 SCS.setToType(2, FromType); 1854 1855 if (CanonFrom == CanonTo) 1856 return true; 1857 1858 // If we have not converted the argument type to the parameter type, 1859 // this is a bad conversion sequence, unless we're resolving an overload in C. 1860 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1861 return false; 1862 1863 ExprResult ER = ExprResult{From}; 1864 Sema::AssignConvertType Conv = 1865 S.CheckSingleAssignmentConstraints(ToType, ER, 1866 /*Diagnose=*/false, 1867 /*DiagnoseCFAudited=*/false, 1868 /*ConvertRHS=*/false); 1869 ImplicitConversionKind SecondConv; 1870 switch (Conv) { 1871 case Sema::Compatible: 1872 SecondConv = ICK_C_Only_Conversion; 1873 break; 1874 // For our purposes, discarding qualifiers is just as bad as using an 1875 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1876 // qualifiers, as well. 1877 case Sema::CompatiblePointerDiscardsQualifiers: 1878 case Sema::IncompatiblePointer: 1879 case Sema::IncompatiblePointerSign: 1880 SecondConv = ICK_Incompatible_Pointer_Conversion; 1881 break; 1882 default: 1883 return false; 1884 } 1885 1886 // First can only be an lvalue conversion, so we pretend that this was the 1887 // second conversion. First should already be valid from earlier in the 1888 // function. 1889 SCS.Second = SecondConv; 1890 SCS.setToType(1, ToType); 1891 1892 // Third is Identity, because Second should rank us worse than any other 1893 // conversion. This could also be ICK_Qualification, but it's simpler to just 1894 // lump everything in with the second conversion, and we don't gain anything 1895 // from making this ICK_Qualification. 1896 SCS.Third = ICK_Identity; 1897 SCS.setToType(2, ToType); 1898 return true; 1899 } 1900 1901 static bool 1902 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1903 QualType &ToType, 1904 bool InOverloadResolution, 1905 StandardConversionSequence &SCS, 1906 bool CStyle) { 1907 1908 const RecordType *UT = ToType->getAsUnionType(); 1909 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1910 return false; 1911 // The field to initialize within the transparent union. 1912 RecordDecl *UD = UT->getDecl(); 1913 // It's compatible if the expression matches any of the fields. 1914 for (const auto *it : UD->fields()) { 1915 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1916 CStyle, /*ObjCWritebackConversion=*/false)) { 1917 ToType = it->getType(); 1918 return true; 1919 } 1920 } 1921 return false; 1922 } 1923 1924 /// IsIntegralPromotion - Determines whether the conversion from the 1925 /// expression From (whose potentially-adjusted type is FromType) to 1926 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1927 /// sets PromotedType to the promoted type. 1928 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1929 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1930 // All integers are built-in. 1931 if (!To) { 1932 return false; 1933 } 1934 1935 // An rvalue of type char, signed char, unsigned char, short int, or 1936 // unsigned short int can be converted to an rvalue of type int if 1937 // int can represent all the values of the source type; otherwise, 1938 // the source rvalue can be converted to an rvalue of type unsigned 1939 // int (C++ 4.5p1). 1940 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1941 !FromType->isEnumeralType()) { 1942 if (// We can promote any signed, promotable integer type to an int 1943 (FromType->isSignedIntegerType() || 1944 // We can promote any unsigned integer type whose size is 1945 // less than int to an int. 1946 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1947 return To->getKind() == BuiltinType::Int; 1948 } 1949 1950 return To->getKind() == BuiltinType::UInt; 1951 } 1952 1953 // C++11 [conv.prom]p3: 1954 // A prvalue of an unscoped enumeration type whose underlying type is not 1955 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1956 // following types that can represent all the values of the enumeration 1957 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1958 // unsigned int, long int, unsigned long int, long long int, or unsigned 1959 // long long int. If none of the types in that list can represent all the 1960 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1961 // type can be converted to an rvalue a prvalue of the extended integer type 1962 // with lowest integer conversion rank (4.13) greater than the rank of long 1963 // long in which all the values of the enumeration can be represented. If 1964 // there are two such extended types, the signed one is chosen. 1965 // C++11 [conv.prom]p4: 1966 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1967 // can be converted to a prvalue of its underlying type. Moreover, if 1968 // integral promotion can be applied to its underlying type, a prvalue of an 1969 // unscoped enumeration type whose underlying type is fixed can also be 1970 // converted to a prvalue of the promoted underlying type. 1971 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1972 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1973 // provided for a scoped enumeration. 1974 if (FromEnumType->getDecl()->isScoped()) 1975 return false; 1976 1977 // We can perform an integral promotion to the underlying type of the enum, 1978 // even if that's not the promoted type. Note that the check for promoting 1979 // the underlying type is based on the type alone, and does not consider 1980 // the bitfield-ness of the actual source expression. 1981 if (FromEnumType->getDecl()->isFixed()) { 1982 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1983 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1984 IsIntegralPromotion(nullptr, Underlying, ToType); 1985 } 1986 1987 // We have already pre-calculated the promotion type, so this is trivial. 1988 if (ToType->isIntegerType() && 1989 isCompleteType(From->getLocStart(), FromType)) 1990 return Context.hasSameUnqualifiedType( 1991 ToType, FromEnumType->getDecl()->getPromotionType()); 1992 } 1993 1994 // C++0x [conv.prom]p2: 1995 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1996 // to an rvalue a prvalue of the first of the following types that can 1997 // represent all the values of its underlying type: int, unsigned int, 1998 // long int, unsigned long int, long long int, or unsigned long long int. 1999 // If none of the types in that list can represent all the values of its 2000 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2001 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2002 // type. 2003 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2004 ToType->isIntegerType()) { 2005 // Determine whether the type we're converting from is signed or 2006 // unsigned. 2007 bool FromIsSigned = FromType->isSignedIntegerType(); 2008 uint64_t FromSize = Context.getTypeSize(FromType); 2009 2010 // The types we'll try to promote to, in the appropriate 2011 // order. Try each of these types. 2012 QualType PromoteTypes[6] = { 2013 Context.IntTy, Context.UnsignedIntTy, 2014 Context.LongTy, Context.UnsignedLongTy , 2015 Context.LongLongTy, Context.UnsignedLongLongTy 2016 }; 2017 for (int Idx = 0; Idx < 6; ++Idx) { 2018 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2019 if (FromSize < ToSize || 2020 (FromSize == ToSize && 2021 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2022 // We found the type that we can promote to. If this is the 2023 // type we wanted, we have a promotion. Otherwise, no 2024 // promotion. 2025 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2026 } 2027 } 2028 } 2029 2030 // An rvalue for an integral bit-field (9.6) can be converted to an 2031 // rvalue of type int if int can represent all the values of the 2032 // bit-field; otherwise, it can be converted to unsigned int if 2033 // unsigned int can represent all the values of the bit-field. If 2034 // the bit-field is larger yet, no integral promotion applies to 2035 // it. If the bit-field has an enumerated type, it is treated as any 2036 // other value of that type for promotion purposes (C++ 4.5p3). 2037 // FIXME: We should delay checking of bit-fields until we actually perform the 2038 // conversion. 2039 if (From) { 2040 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2041 llvm::APSInt BitWidth; 2042 if (FromType->isIntegralType(Context) && 2043 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2044 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2045 ToSize = Context.getTypeSize(ToType); 2046 2047 // Are we promoting to an int from a bitfield that fits in an int? 2048 if (BitWidth < ToSize || 2049 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2050 return To->getKind() == BuiltinType::Int; 2051 } 2052 2053 // Are we promoting to an unsigned int from an unsigned bitfield 2054 // that fits into an unsigned int? 2055 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2056 return To->getKind() == BuiltinType::UInt; 2057 } 2058 2059 return false; 2060 } 2061 } 2062 } 2063 2064 // An rvalue of type bool can be converted to an rvalue of type int, 2065 // with false becoming zero and true becoming one (C++ 4.5p4). 2066 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2067 return true; 2068 } 2069 2070 return false; 2071 } 2072 2073 /// IsFloatingPointPromotion - Determines whether the conversion from 2074 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2075 /// returns true and sets PromotedType to the promoted type. 2076 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2077 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2078 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2079 /// An rvalue of type float can be converted to an rvalue of type 2080 /// double. (C++ 4.6p1). 2081 if (FromBuiltin->getKind() == BuiltinType::Float && 2082 ToBuiltin->getKind() == BuiltinType::Double) 2083 return true; 2084 2085 // C99 6.3.1.5p1: 2086 // When a float is promoted to double or long double, or a 2087 // double is promoted to long double [...]. 2088 if (!getLangOpts().CPlusPlus && 2089 (FromBuiltin->getKind() == BuiltinType::Float || 2090 FromBuiltin->getKind() == BuiltinType::Double) && 2091 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2092 ToBuiltin->getKind() == BuiltinType::Float128)) 2093 return true; 2094 2095 // Half can be promoted to float. 2096 if (!getLangOpts().NativeHalfType && 2097 FromBuiltin->getKind() == BuiltinType::Half && 2098 ToBuiltin->getKind() == BuiltinType::Float) 2099 return true; 2100 } 2101 2102 return false; 2103 } 2104 2105 /// \brief Determine if a conversion is a complex promotion. 2106 /// 2107 /// A complex promotion is defined as a complex -> complex conversion 2108 /// where the conversion between the underlying real types is a 2109 /// floating-point or integral promotion. 2110 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2111 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2112 if (!FromComplex) 2113 return false; 2114 2115 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2116 if (!ToComplex) 2117 return false; 2118 2119 return IsFloatingPointPromotion(FromComplex->getElementType(), 2120 ToComplex->getElementType()) || 2121 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2122 ToComplex->getElementType()); 2123 } 2124 2125 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2126 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2127 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2128 /// if non-empty, will be a pointer to ToType that may or may not have 2129 /// the right set of qualifiers on its pointee. 2130 /// 2131 static QualType 2132 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2133 QualType ToPointee, QualType ToType, 2134 ASTContext &Context, 2135 bool StripObjCLifetime = false) { 2136 assert((FromPtr->getTypeClass() == Type::Pointer || 2137 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2138 "Invalid similarly-qualified pointer type"); 2139 2140 /// Conversions to 'id' subsume cv-qualifier conversions. 2141 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2142 return ToType.getUnqualifiedType(); 2143 2144 QualType CanonFromPointee 2145 = Context.getCanonicalType(FromPtr->getPointeeType()); 2146 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2147 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2148 2149 if (StripObjCLifetime) 2150 Quals.removeObjCLifetime(); 2151 2152 // Exact qualifier match -> return the pointer type we're converting to. 2153 if (CanonToPointee.getLocalQualifiers() == Quals) { 2154 // ToType is exactly what we need. Return it. 2155 if (!ToType.isNull()) 2156 return ToType.getUnqualifiedType(); 2157 2158 // Build a pointer to ToPointee. It has the right qualifiers 2159 // already. 2160 if (isa<ObjCObjectPointerType>(ToType)) 2161 return Context.getObjCObjectPointerType(ToPointee); 2162 return Context.getPointerType(ToPointee); 2163 } 2164 2165 // Just build a canonical type that has the right qualifiers. 2166 QualType QualifiedCanonToPointee 2167 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2168 2169 if (isa<ObjCObjectPointerType>(ToType)) 2170 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2171 return Context.getPointerType(QualifiedCanonToPointee); 2172 } 2173 2174 static bool isNullPointerConstantForConversion(Expr *Expr, 2175 bool InOverloadResolution, 2176 ASTContext &Context) { 2177 // Handle value-dependent integral null pointer constants correctly. 2178 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2179 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2180 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2181 return !InOverloadResolution; 2182 2183 return Expr->isNullPointerConstant(Context, 2184 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2185 : Expr::NPC_ValueDependentIsNull); 2186 } 2187 2188 /// IsPointerConversion - Determines whether the conversion of the 2189 /// expression From, which has the (possibly adjusted) type FromType, 2190 /// can be converted to the type ToType via a pointer conversion (C++ 2191 /// 4.10). If so, returns true and places the converted type (that 2192 /// might differ from ToType in its cv-qualifiers at some level) into 2193 /// ConvertedType. 2194 /// 2195 /// This routine also supports conversions to and from block pointers 2196 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2197 /// pointers to interfaces. FIXME: Once we've determined the 2198 /// appropriate overloading rules for Objective-C, we may want to 2199 /// split the Objective-C checks into a different routine; however, 2200 /// GCC seems to consider all of these conversions to be pointer 2201 /// conversions, so for now they live here. IncompatibleObjC will be 2202 /// set if the conversion is an allowed Objective-C conversion that 2203 /// should result in a warning. 2204 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2205 bool InOverloadResolution, 2206 QualType& ConvertedType, 2207 bool &IncompatibleObjC) { 2208 IncompatibleObjC = false; 2209 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2210 IncompatibleObjC)) 2211 return true; 2212 2213 // Conversion from a null pointer constant to any Objective-C pointer type. 2214 if (ToType->isObjCObjectPointerType() && 2215 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2216 ConvertedType = ToType; 2217 return true; 2218 } 2219 2220 // Blocks: Block pointers can be converted to void*. 2221 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2222 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2223 ConvertedType = ToType; 2224 return true; 2225 } 2226 // Blocks: A null pointer constant can be converted to a block 2227 // pointer type. 2228 if (ToType->isBlockPointerType() && 2229 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2230 ConvertedType = ToType; 2231 return true; 2232 } 2233 2234 // If the left-hand-side is nullptr_t, the right side can be a null 2235 // pointer constant. 2236 if (ToType->isNullPtrType() && 2237 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2238 ConvertedType = ToType; 2239 return true; 2240 } 2241 2242 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2243 if (!ToTypePtr) 2244 return false; 2245 2246 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2247 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2248 ConvertedType = ToType; 2249 return true; 2250 } 2251 2252 // Beyond this point, both types need to be pointers 2253 // , including objective-c pointers. 2254 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2255 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2256 !getLangOpts().ObjCAutoRefCount) { 2257 ConvertedType = BuildSimilarlyQualifiedPointerType( 2258 FromType->getAs<ObjCObjectPointerType>(), 2259 ToPointeeType, 2260 ToType, Context); 2261 return true; 2262 } 2263 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2264 if (!FromTypePtr) 2265 return false; 2266 2267 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2268 2269 // If the unqualified pointee types are the same, this can't be a 2270 // pointer conversion, so don't do all of the work below. 2271 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2272 return false; 2273 2274 // An rvalue of type "pointer to cv T," where T is an object type, 2275 // can be converted to an rvalue of type "pointer to cv void" (C++ 2276 // 4.10p2). 2277 if (FromPointeeType->isIncompleteOrObjectType() && 2278 ToPointeeType->isVoidType()) { 2279 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2280 ToPointeeType, 2281 ToType, Context, 2282 /*StripObjCLifetime=*/true); 2283 return true; 2284 } 2285 2286 // MSVC allows implicit function to void* type conversion. 2287 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2288 ToPointeeType->isVoidType()) { 2289 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2290 ToPointeeType, 2291 ToType, Context); 2292 return true; 2293 } 2294 2295 // When we're overloading in C, we allow a special kind of pointer 2296 // conversion for compatible-but-not-identical pointee types. 2297 if (!getLangOpts().CPlusPlus && 2298 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2299 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2300 ToPointeeType, 2301 ToType, Context); 2302 return true; 2303 } 2304 2305 // C++ [conv.ptr]p3: 2306 // 2307 // An rvalue of type "pointer to cv D," where D is a class type, 2308 // can be converted to an rvalue of type "pointer to cv B," where 2309 // B is a base class (clause 10) of D. If B is an inaccessible 2310 // (clause 11) or ambiguous (10.2) base class of D, a program that 2311 // necessitates this conversion is ill-formed. The result of the 2312 // conversion is a pointer to the base class sub-object of the 2313 // derived class object. The null pointer value is converted to 2314 // the null pointer value of the destination type. 2315 // 2316 // Note that we do not check for ambiguity or inaccessibility 2317 // here. That is handled by CheckPointerConversion. 2318 if (getLangOpts().CPlusPlus && 2319 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2320 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2321 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2322 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2323 ToPointeeType, 2324 ToType, Context); 2325 return true; 2326 } 2327 2328 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2329 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2330 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2331 ToPointeeType, 2332 ToType, Context); 2333 return true; 2334 } 2335 2336 return false; 2337 } 2338 2339 /// \brief Adopt the given qualifiers for the given type. 2340 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2341 Qualifiers TQs = T.getQualifiers(); 2342 2343 // Check whether qualifiers already match. 2344 if (TQs == Qs) 2345 return T; 2346 2347 if (Qs.compatiblyIncludes(TQs)) 2348 return Context.getQualifiedType(T, Qs); 2349 2350 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2351 } 2352 2353 /// isObjCPointerConversion - Determines whether this is an 2354 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2355 /// with the same arguments and return values. 2356 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2357 QualType& ConvertedType, 2358 bool &IncompatibleObjC) { 2359 if (!getLangOpts().ObjC1) 2360 return false; 2361 2362 // The set of qualifiers on the type we're converting from. 2363 Qualifiers FromQualifiers = FromType.getQualifiers(); 2364 2365 // First, we handle all conversions on ObjC object pointer types. 2366 const ObjCObjectPointerType* ToObjCPtr = 2367 ToType->getAs<ObjCObjectPointerType>(); 2368 const ObjCObjectPointerType *FromObjCPtr = 2369 FromType->getAs<ObjCObjectPointerType>(); 2370 2371 if (ToObjCPtr && FromObjCPtr) { 2372 // If the pointee types are the same (ignoring qualifications), 2373 // then this is not a pointer conversion. 2374 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2375 FromObjCPtr->getPointeeType())) 2376 return false; 2377 2378 // Conversion between Objective-C pointers. 2379 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2380 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2381 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2382 if (getLangOpts().CPlusPlus && LHS && RHS && 2383 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2384 FromObjCPtr->getPointeeType())) 2385 return false; 2386 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2387 ToObjCPtr->getPointeeType(), 2388 ToType, Context); 2389 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2390 return true; 2391 } 2392 2393 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2394 // Okay: this is some kind of implicit downcast of Objective-C 2395 // interfaces, which is permitted. However, we're going to 2396 // complain about it. 2397 IncompatibleObjC = true; 2398 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2399 ToObjCPtr->getPointeeType(), 2400 ToType, Context); 2401 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2402 return true; 2403 } 2404 } 2405 // Beyond this point, both types need to be C pointers or block pointers. 2406 QualType ToPointeeType; 2407 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2408 ToPointeeType = ToCPtr->getPointeeType(); 2409 else if (const BlockPointerType *ToBlockPtr = 2410 ToType->getAs<BlockPointerType>()) { 2411 // Objective C++: We're able to convert from a pointer to any object 2412 // to a block pointer type. 2413 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2414 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2415 return true; 2416 } 2417 ToPointeeType = ToBlockPtr->getPointeeType(); 2418 } 2419 else if (FromType->getAs<BlockPointerType>() && 2420 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2421 // Objective C++: We're able to convert from a block pointer type to a 2422 // pointer to any object. 2423 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2424 return true; 2425 } 2426 else 2427 return false; 2428 2429 QualType FromPointeeType; 2430 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2431 FromPointeeType = FromCPtr->getPointeeType(); 2432 else if (const BlockPointerType *FromBlockPtr = 2433 FromType->getAs<BlockPointerType>()) 2434 FromPointeeType = FromBlockPtr->getPointeeType(); 2435 else 2436 return false; 2437 2438 // If we have pointers to pointers, recursively check whether this 2439 // is an Objective-C conversion. 2440 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2441 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2442 IncompatibleObjC)) { 2443 // We always complain about this conversion. 2444 IncompatibleObjC = true; 2445 ConvertedType = Context.getPointerType(ConvertedType); 2446 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2447 return true; 2448 } 2449 // Allow conversion of pointee being objective-c pointer to another one; 2450 // as in I* to id. 2451 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2452 ToPointeeType->getAs<ObjCObjectPointerType>() && 2453 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2454 IncompatibleObjC)) { 2455 2456 ConvertedType = Context.getPointerType(ConvertedType); 2457 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2458 return true; 2459 } 2460 2461 // If we have pointers to functions or blocks, check whether the only 2462 // differences in the argument and result types are in Objective-C 2463 // pointer conversions. If so, we permit the conversion (but 2464 // complain about it). 2465 const FunctionProtoType *FromFunctionType 2466 = FromPointeeType->getAs<FunctionProtoType>(); 2467 const FunctionProtoType *ToFunctionType 2468 = ToPointeeType->getAs<FunctionProtoType>(); 2469 if (FromFunctionType && ToFunctionType) { 2470 // If the function types are exactly the same, this isn't an 2471 // Objective-C pointer conversion. 2472 if (Context.getCanonicalType(FromPointeeType) 2473 == Context.getCanonicalType(ToPointeeType)) 2474 return false; 2475 2476 // Perform the quick checks that will tell us whether these 2477 // function types are obviously different. 2478 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2479 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2480 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2481 return false; 2482 2483 bool HasObjCConversion = false; 2484 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2485 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2486 // Okay, the types match exactly. Nothing to do. 2487 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2488 ToFunctionType->getReturnType(), 2489 ConvertedType, IncompatibleObjC)) { 2490 // Okay, we have an Objective-C pointer conversion. 2491 HasObjCConversion = true; 2492 } else { 2493 // Function types are too different. Abort. 2494 return false; 2495 } 2496 2497 // Check argument types. 2498 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2499 ArgIdx != NumArgs; ++ArgIdx) { 2500 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2501 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2502 if (Context.getCanonicalType(FromArgType) 2503 == Context.getCanonicalType(ToArgType)) { 2504 // Okay, the types match exactly. Nothing to do. 2505 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2506 ConvertedType, IncompatibleObjC)) { 2507 // Okay, we have an Objective-C pointer conversion. 2508 HasObjCConversion = true; 2509 } else { 2510 // Argument types are too different. Abort. 2511 return false; 2512 } 2513 } 2514 2515 if (HasObjCConversion) { 2516 // We had an Objective-C conversion. Allow this pointer 2517 // conversion, but complain about it. 2518 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2519 IncompatibleObjC = true; 2520 return true; 2521 } 2522 } 2523 2524 return false; 2525 } 2526 2527 /// \brief Determine whether this is an Objective-C writeback conversion, 2528 /// used for parameter passing when performing automatic reference counting. 2529 /// 2530 /// \param FromType The type we're converting form. 2531 /// 2532 /// \param ToType The type we're converting to. 2533 /// 2534 /// \param ConvertedType The type that will be produced after applying 2535 /// this conversion. 2536 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2537 QualType &ConvertedType) { 2538 if (!getLangOpts().ObjCAutoRefCount || 2539 Context.hasSameUnqualifiedType(FromType, ToType)) 2540 return false; 2541 2542 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2543 QualType ToPointee; 2544 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2545 ToPointee = ToPointer->getPointeeType(); 2546 else 2547 return false; 2548 2549 Qualifiers ToQuals = ToPointee.getQualifiers(); 2550 if (!ToPointee->isObjCLifetimeType() || 2551 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2552 !ToQuals.withoutObjCLifetime().empty()) 2553 return false; 2554 2555 // Argument must be a pointer to __strong to __weak. 2556 QualType FromPointee; 2557 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2558 FromPointee = FromPointer->getPointeeType(); 2559 else 2560 return false; 2561 2562 Qualifiers FromQuals = FromPointee.getQualifiers(); 2563 if (!FromPointee->isObjCLifetimeType() || 2564 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2565 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2566 return false; 2567 2568 // Make sure that we have compatible qualifiers. 2569 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2570 if (!ToQuals.compatiblyIncludes(FromQuals)) 2571 return false; 2572 2573 // Remove qualifiers from the pointee type we're converting from; they 2574 // aren't used in the compatibility check belong, and we'll be adding back 2575 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2576 FromPointee = FromPointee.getUnqualifiedType(); 2577 2578 // The unqualified form of the pointee types must be compatible. 2579 ToPointee = ToPointee.getUnqualifiedType(); 2580 bool IncompatibleObjC; 2581 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2582 FromPointee = ToPointee; 2583 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2584 IncompatibleObjC)) 2585 return false; 2586 2587 /// \brief Construct the type we're converting to, which is a pointer to 2588 /// __autoreleasing pointee. 2589 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2590 ConvertedType = Context.getPointerType(FromPointee); 2591 return true; 2592 } 2593 2594 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2595 QualType& ConvertedType) { 2596 QualType ToPointeeType; 2597 if (const BlockPointerType *ToBlockPtr = 2598 ToType->getAs<BlockPointerType>()) 2599 ToPointeeType = ToBlockPtr->getPointeeType(); 2600 else 2601 return false; 2602 2603 QualType FromPointeeType; 2604 if (const BlockPointerType *FromBlockPtr = 2605 FromType->getAs<BlockPointerType>()) 2606 FromPointeeType = FromBlockPtr->getPointeeType(); 2607 else 2608 return false; 2609 // We have pointer to blocks, check whether the only 2610 // differences in the argument and result types are in Objective-C 2611 // pointer conversions. If so, we permit the conversion. 2612 2613 const FunctionProtoType *FromFunctionType 2614 = FromPointeeType->getAs<FunctionProtoType>(); 2615 const FunctionProtoType *ToFunctionType 2616 = ToPointeeType->getAs<FunctionProtoType>(); 2617 2618 if (!FromFunctionType || !ToFunctionType) 2619 return false; 2620 2621 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2622 return true; 2623 2624 // Perform the quick checks that will tell us whether these 2625 // function types are obviously different. 2626 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2627 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2628 return false; 2629 2630 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2631 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2632 if (FromEInfo != ToEInfo) 2633 return false; 2634 2635 bool IncompatibleObjC = false; 2636 if (Context.hasSameType(FromFunctionType->getReturnType(), 2637 ToFunctionType->getReturnType())) { 2638 // Okay, the types match exactly. Nothing to do. 2639 } else { 2640 QualType RHS = FromFunctionType->getReturnType(); 2641 QualType LHS = ToFunctionType->getReturnType(); 2642 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2643 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2644 LHS = LHS.getUnqualifiedType(); 2645 2646 if (Context.hasSameType(RHS,LHS)) { 2647 // OK exact match. 2648 } else if (isObjCPointerConversion(RHS, LHS, 2649 ConvertedType, IncompatibleObjC)) { 2650 if (IncompatibleObjC) 2651 return false; 2652 // Okay, we have an Objective-C pointer conversion. 2653 } 2654 else 2655 return false; 2656 } 2657 2658 // Check argument types. 2659 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2660 ArgIdx != NumArgs; ++ArgIdx) { 2661 IncompatibleObjC = false; 2662 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2663 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2664 if (Context.hasSameType(FromArgType, ToArgType)) { 2665 // Okay, the types match exactly. Nothing to do. 2666 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2667 ConvertedType, IncompatibleObjC)) { 2668 if (IncompatibleObjC) 2669 return false; 2670 // Okay, we have an Objective-C pointer conversion. 2671 } else 2672 // Argument types are too different. Abort. 2673 return false; 2674 } 2675 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType, 2676 ToFunctionType)) 2677 return false; 2678 2679 ConvertedType = ToType; 2680 return true; 2681 } 2682 2683 enum { 2684 ft_default, 2685 ft_different_class, 2686 ft_parameter_arity, 2687 ft_parameter_mismatch, 2688 ft_return_type, 2689 ft_qualifer_mismatch, 2690 ft_noexcept 2691 }; 2692 2693 /// Attempts to get the FunctionProtoType from a Type. Handles 2694 /// MemberFunctionPointers properly. 2695 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2696 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2697 return FPT; 2698 2699 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2700 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2701 2702 return nullptr; 2703 } 2704 2705 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2706 /// function types. Catches different number of parameter, mismatch in 2707 /// parameter types, and different return types. 2708 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2709 QualType FromType, QualType ToType) { 2710 // If either type is not valid, include no extra info. 2711 if (FromType.isNull() || ToType.isNull()) { 2712 PDiag << ft_default; 2713 return; 2714 } 2715 2716 // Get the function type from the pointers. 2717 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2718 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2719 *ToMember = ToType->getAs<MemberPointerType>(); 2720 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2721 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2722 << QualType(FromMember->getClass(), 0); 2723 return; 2724 } 2725 FromType = FromMember->getPointeeType(); 2726 ToType = ToMember->getPointeeType(); 2727 } 2728 2729 if (FromType->isPointerType()) 2730 FromType = FromType->getPointeeType(); 2731 if (ToType->isPointerType()) 2732 ToType = ToType->getPointeeType(); 2733 2734 // Remove references. 2735 FromType = FromType.getNonReferenceType(); 2736 ToType = ToType.getNonReferenceType(); 2737 2738 // Don't print extra info for non-specialized template functions. 2739 if (FromType->isInstantiationDependentType() && 2740 !FromType->getAs<TemplateSpecializationType>()) { 2741 PDiag << ft_default; 2742 return; 2743 } 2744 2745 // No extra info for same types. 2746 if (Context.hasSameType(FromType, ToType)) { 2747 PDiag << ft_default; 2748 return; 2749 } 2750 2751 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2752 *ToFunction = tryGetFunctionProtoType(ToType); 2753 2754 // Both types need to be function types. 2755 if (!FromFunction || !ToFunction) { 2756 PDiag << ft_default; 2757 return; 2758 } 2759 2760 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2761 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2762 << FromFunction->getNumParams(); 2763 return; 2764 } 2765 2766 // Handle different parameter types. 2767 unsigned ArgPos; 2768 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2769 PDiag << ft_parameter_mismatch << ArgPos + 1 2770 << ToFunction->getParamType(ArgPos) 2771 << FromFunction->getParamType(ArgPos); 2772 return; 2773 } 2774 2775 // Handle different return type. 2776 if (!Context.hasSameType(FromFunction->getReturnType(), 2777 ToFunction->getReturnType())) { 2778 PDiag << ft_return_type << ToFunction->getReturnType() 2779 << FromFunction->getReturnType(); 2780 return; 2781 } 2782 2783 unsigned FromQuals = FromFunction->getTypeQuals(), 2784 ToQuals = ToFunction->getTypeQuals(); 2785 if (FromQuals != ToQuals) { 2786 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2787 return; 2788 } 2789 2790 // Handle exception specification differences on canonical type (in C++17 2791 // onwards). 2792 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2793 ->isNothrow(Context) != 2794 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2795 ->isNothrow(Context)) { 2796 PDiag << ft_noexcept; 2797 return; 2798 } 2799 2800 // Unable to find a difference, so add no extra info. 2801 PDiag << ft_default; 2802 } 2803 2804 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2805 /// for equality of their argument types. Caller has already checked that 2806 /// they have same number of arguments. If the parameters are different, 2807 /// ArgPos will have the parameter index of the first different parameter. 2808 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2809 const FunctionProtoType *NewType, 2810 unsigned *ArgPos) { 2811 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2812 N = NewType->param_type_begin(), 2813 E = OldType->param_type_end(); 2814 O && (O != E); ++O, ++N) { 2815 if (!Context.hasSameType(O->getUnqualifiedType(), 2816 N->getUnqualifiedType())) { 2817 if (ArgPos) 2818 *ArgPos = O - OldType->param_type_begin(); 2819 return false; 2820 } 2821 } 2822 return true; 2823 } 2824 2825 /// CheckPointerConversion - Check the pointer conversion from the 2826 /// expression From to the type ToType. This routine checks for 2827 /// ambiguous or inaccessible derived-to-base pointer 2828 /// conversions for which IsPointerConversion has already returned 2829 /// true. It returns true and produces a diagnostic if there was an 2830 /// error, or returns false otherwise. 2831 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2832 CastKind &Kind, 2833 CXXCastPath& BasePath, 2834 bool IgnoreBaseAccess, 2835 bool Diagnose) { 2836 QualType FromType = From->getType(); 2837 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2838 2839 Kind = CK_BitCast; 2840 2841 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2842 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2843 Expr::NPCK_ZeroExpression) { 2844 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2845 DiagRuntimeBehavior(From->getExprLoc(), From, 2846 PDiag(diag::warn_impcast_bool_to_null_pointer) 2847 << ToType << From->getSourceRange()); 2848 else if (!isUnevaluatedContext()) 2849 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2850 << ToType << From->getSourceRange(); 2851 } 2852 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2853 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2854 QualType FromPointeeType = FromPtrType->getPointeeType(), 2855 ToPointeeType = ToPtrType->getPointeeType(); 2856 2857 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2858 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2859 // We must have a derived-to-base conversion. Check an 2860 // ambiguous or inaccessible conversion. 2861 unsigned InaccessibleID = 0; 2862 unsigned AmbigiousID = 0; 2863 if (Diagnose) { 2864 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2865 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2866 } 2867 if (CheckDerivedToBaseConversion( 2868 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2869 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2870 &BasePath, IgnoreBaseAccess)) 2871 return true; 2872 2873 // The conversion was successful. 2874 Kind = CK_DerivedToBase; 2875 } 2876 2877 if (Diagnose && !IsCStyleOrFunctionalCast && 2878 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2879 assert(getLangOpts().MSVCCompat && 2880 "this should only be possible with MSVCCompat!"); 2881 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2882 << From->getSourceRange(); 2883 } 2884 } 2885 } else if (const ObjCObjectPointerType *ToPtrType = 2886 ToType->getAs<ObjCObjectPointerType>()) { 2887 if (const ObjCObjectPointerType *FromPtrType = 2888 FromType->getAs<ObjCObjectPointerType>()) { 2889 // Objective-C++ conversions are always okay. 2890 // FIXME: We should have a different class of conversions for the 2891 // Objective-C++ implicit conversions. 2892 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2893 return false; 2894 } else if (FromType->isBlockPointerType()) { 2895 Kind = CK_BlockPointerToObjCPointerCast; 2896 } else { 2897 Kind = CK_CPointerToObjCPointerCast; 2898 } 2899 } else if (ToType->isBlockPointerType()) { 2900 if (!FromType->isBlockPointerType()) 2901 Kind = CK_AnyPointerToBlockPointerCast; 2902 } 2903 2904 // We shouldn't fall into this case unless it's valid for other 2905 // reasons. 2906 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2907 Kind = CK_NullToPointer; 2908 2909 return false; 2910 } 2911 2912 /// IsMemberPointerConversion - Determines whether the conversion of the 2913 /// expression From, which has the (possibly adjusted) type FromType, can be 2914 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2915 /// If so, returns true and places the converted type (that might differ from 2916 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2917 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2918 QualType ToType, 2919 bool InOverloadResolution, 2920 QualType &ConvertedType) { 2921 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2922 if (!ToTypePtr) 2923 return false; 2924 2925 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2926 if (From->isNullPointerConstant(Context, 2927 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2928 : Expr::NPC_ValueDependentIsNull)) { 2929 ConvertedType = ToType; 2930 return true; 2931 } 2932 2933 // Otherwise, both types have to be member pointers. 2934 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2935 if (!FromTypePtr) 2936 return false; 2937 2938 // A pointer to member of B can be converted to a pointer to member of D, 2939 // where D is derived from B (C++ 4.11p2). 2940 QualType FromClass(FromTypePtr->getClass(), 0); 2941 QualType ToClass(ToTypePtr->getClass(), 0); 2942 2943 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2944 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2945 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2946 ToClass.getTypePtr()); 2947 return true; 2948 } 2949 2950 return false; 2951 } 2952 2953 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2954 /// expression From to the type ToType. This routine checks for ambiguous or 2955 /// virtual or inaccessible base-to-derived member pointer conversions 2956 /// for which IsMemberPointerConversion has already returned true. It returns 2957 /// true and produces a diagnostic if there was an error, or returns false 2958 /// otherwise. 2959 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2960 CastKind &Kind, 2961 CXXCastPath &BasePath, 2962 bool IgnoreBaseAccess) { 2963 QualType FromType = From->getType(); 2964 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2965 if (!FromPtrType) { 2966 // This must be a null pointer to member pointer conversion 2967 assert(From->isNullPointerConstant(Context, 2968 Expr::NPC_ValueDependentIsNull) && 2969 "Expr must be null pointer constant!"); 2970 Kind = CK_NullToMemberPointer; 2971 return false; 2972 } 2973 2974 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2975 assert(ToPtrType && "No member pointer cast has a target type " 2976 "that is not a member pointer."); 2977 2978 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2979 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2980 2981 // FIXME: What about dependent types? 2982 assert(FromClass->isRecordType() && "Pointer into non-class."); 2983 assert(ToClass->isRecordType() && "Pointer into non-class."); 2984 2985 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2986 /*DetectVirtual=*/true); 2987 bool DerivationOkay = 2988 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2989 assert(DerivationOkay && 2990 "Should not have been called if derivation isn't OK."); 2991 (void)DerivationOkay; 2992 2993 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2994 getUnqualifiedType())) { 2995 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2996 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2997 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2998 return true; 2999 } 3000 3001 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3002 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3003 << FromClass << ToClass << QualType(VBase, 0) 3004 << From->getSourceRange(); 3005 return true; 3006 } 3007 3008 if (!IgnoreBaseAccess) 3009 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3010 Paths.front(), 3011 diag::err_downcast_from_inaccessible_base); 3012 3013 // Must be a base to derived member conversion. 3014 BuildBasePathArray(Paths, BasePath); 3015 Kind = CK_BaseToDerivedMemberPointer; 3016 return false; 3017 } 3018 3019 /// Determine whether the lifetime conversion between the two given 3020 /// qualifiers sets is nontrivial. 3021 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3022 Qualifiers ToQuals) { 3023 // Converting anything to const __unsafe_unretained is trivial. 3024 if (ToQuals.hasConst() && 3025 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3026 return false; 3027 3028 return true; 3029 } 3030 3031 /// IsQualificationConversion - Determines whether the conversion from 3032 /// an rvalue of type FromType to ToType is a qualification conversion 3033 /// (C++ 4.4). 3034 /// 3035 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3036 /// when the qualification conversion involves a change in the Objective-C 3037 /// object lifetime. 3038 bool 3039 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3040 bool CStyle, bool &ObjCLifetimeConversion) { 3041 FromType = Context.getCanonicalType(FromType); 3042 ToType = Context.getCanonicalType(ToType); 3043 ObjCLifetimeConversion = false; 3044 3045 // If FromType and ToType are the same type, this is not a 3046 // qualification conversion. 3047 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3048 return false; 3049 3050 // (C++ 4.4p4): 3051 // A conversion can add cv-qualifiers at levels other than the first 3052 // in multi-level pointers, subject to the following rules: [...] 3053 bool PreviousToQualsIncludeConst = true; 3054 bool UnwrappedAnyPointer = false; 3055 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 3056 // Within each iteration of the loop, we check the qualifiers to 3057 // determine if this still looks like a qualification 3058 // conversion. Then, if all is well, we unwrap one more level of 3059 // pointers or pointers-to-members and do it all again 3060 // until there are no more pointers or pointers-to-members left to 3061 // unwrap. 3062 UnwrappedAnyPointer = true; 3063 3064 Qualifiers FromQuals = FromType.getQualifiers(); 3065 Qualifiers ToQuals = ToType.getQualifiers(); 3066 3067 // Ignore __unaligned qualifier if this type is void. 3068 if (ToType.getUnqualifiedType()->isVoidType()) 3069 FromQuals.removeUnaligned(); 3070 3071 // Objective-C ARC: 3072 // Check Objective-C lifetime conversions. 3073 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3074 UnwrappedAnyPointer) { 3075 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3076 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3077 ObjCLifetimeConversion = true; 3078 FromQuals.removeObjCLifetime(); 3079 ToQuals.removeObjCLifetime(); 3080 } else { 3081 // Qualification conversions cannot cast between different 3082 // Objective-C lifetime qualifiers. 3083 return false; 3084 } 3085 } 3086 3087 // Allow addition/removal of GC attributes but not changing GC attributes. 3088 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3089 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3090 FromQuals.removeObjCGCAttr(); 3091 ToQuals.removeObjCGCAttr(); 3092 } 3093 3094 // -- for every j > 0, if const is in cv 1,j then const is in cv 3095 // 2,j, and similarly for volatile. 3096 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3097 return false; 3098 3099 // -- if the cv 1,j and cv 2,j are different, then const is in 3100 // every cv for 0 < k < j. 3101 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3102 && !PreviousToQualsIncludeConst) 3103 return false; 3104 3105 // Keep track of whether all prior cv-qualifiers in the "to" type 3106 // include const. 3107 PreviousToQualsIncludeConst 3108 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3109 } 3110 3111 // We are left with FromType and ToType being the pointee types 3112 // after unwrapping the original FromType and ToType the same number 3113 // of types. If we unwrapped any pointers, and if FromType and 3114 // ToType have the same unqualified type (since we checked 3115 // qualifiers above), then this is a qualification conversion. 3116 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3117 } 3118 3119 /// \brief - Determine whether this is a conversion from a scalar type to an 3120 /// atomic type. 3121 /// 3122 /// If successful, updates \c SCS's second and third steps in the conversion 3123 /// sequence to finish the conversion. 3124 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3125 bool InOverloadResolution, 3126 StandardConversionSequence &SCS, 3127 bool CStyle) { 3128 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3129 if (!ToAtomic) 3130 return false; 3131 3132 StandardConversionSequence InnerSCS; 3133 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3134 InOverloadResolution, InnerSCS, 3135 CStyle, /*AllowObjCWritebackConversion=*/false)) 3136 return false; 3137 3138 SCS.Second = InnerSCS.Second; 3139 SCS.setToType(1, InnerSCS.getToType(1)); 3140 SCS.Third = InnerSCS.Third; 3141 SCS.QualificationIncludesObjCLifetime 3142 = InnerSCS.QualificationIncludesObjCLifetime; 3143 SCS.setToType(2, InnerSCS.getToType(2)); 3144 return true; 3145 } 3146 3147 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3148 CXXConstructorDecl *Constructor, 3149 QualType Type) { 3150 const FunctionProtoType *CtorType = 3151 Constructor->getType()->getAs<FunctionProtoType>(); 3152 if (CtorType->getNumParams() > 0) { 3153 QualType FirstArg = CtorType->getParamType(0); 3154 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3155 return true; 3156 } 3157 return false; 3158 } 3159 3160 static OverloadingResult 3161 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3162 CXXRecordDecl *To, 3163 UserDefinedConversionSequence &User, 3164 OverloadCandidateSet &CandidateSet, 3165 bool AllowExplicit) { 3166 for (auto *D : S.LookupConstructors(To)) { 3167 auto Info = getConstructorInfo(D); 3168 if (!Info) 3169 continue; 3170 3171 bool Usable = !Info.Constructor->isInvalidDecl() && 3172 S.isInitListConstructor(Info.Constructor) && 3173 (AllowExplicit || !Info.Constructor->isExplicit()); 3174 if (Usable) { 3175 // If the first argument is (a reference to) the target type, 3176 // suppress conversions. 3177 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3178 S.Context, Info.Constructor, ToType); 3179 if (Info.ConstructorTmpl) 3180 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3181 /*ExplicitArgs*/ nullptr, From, 3182 CandidateSet, SuppressUserConversions); 3183 else 3184 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3185 CandidateSet, SuppressUserConversions); 3186 } 3187 } 3188 3189 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3190 3191 OverloadCandidateSet::iterator Best; 3192 switch (auto Result = 3193 CandidateSet.BestViableFunction(S, From->getLocStart(), 3194 Best, true)) { 3195 case OR_Deleted: 3196 case OR_Success: { 3197 // Record the standard conversion we used and the conversion function. 3198 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3199 QualType ThisType = Constructor->getThisType(S.Context); 3200 // Initializer lists don't have conversions as such. 3201 User.Before.setAsIdentityConversion(); 3202 User.HadMultipleCandidates = HadMultipleCandidates; 3203 User.ConversionFunction = Constructor; 3204 User.FoundConversionFunction = Best->FoundDecl; 3205 User.After.setAsIdentityConversion(); 3206 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3207 User.After.setAllToTypes(ToType); 3208 return Result; 3209 } 3210 3211 case OR_No_Viable_Function: 3212 return OR_No_Viable_Function; 3213 case OR_Ambiguous: 3214 return OR_Ambiguous; 3215 } 3216 3217 llvm_unreachable("Invalid OverloadResult!"); 3218 } 3219 3220 /// Determines whether there is a user-defined conversion sequence 3221 /// (C++ [over.ics.user]) that converts expression From to the type 3222 /// ToType. If such a conversion exists, User will contain the 3223 /// user-defined conversion sequence that performs such a conversion 3224 /// and this routine will return true. Otherwise, this routine returns 3225 /// false and User is unspecified. 3226 /// 3227 /// \param AllowExplicit true if the conversion should consider C++0x 3228 /// "explicit" conversion functions as well as non-explicit conversion 3229 /// functions (C++0x [class.conv.fct]p2). 3230 /// 3231 /// \param AllowObjCConversionOnExplicit true if the conversion should 3232 /// allow an extra Objective-C pointer conversion on uses of explicit 3233 /// constructors. Requires \c AllowExplicit to also be set. 3234 static OverloadingResult 3235 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3236 UserDefinedConversionSequence &User, 3237 OverloadCandidateSet &CandidateSet, 3238 bool AllowExplicit, 3239 bool AllowObjCConversionOnExplicit) { 3240 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3241 3242 // Whether we will only visit constructors. 3243 bool ConstructorsOnly = false; 3244 3245 // If the type we are conversion to is a class type, enumerate its 3246 // constructors. 3247 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3248 // C++ [over.match.ctor]p1: 3249 // When objects of class type are direct-initialized (8.5), or 3250 // copy-initialized from an expression of the same or a 3251 // derived class type (8.5), overload resolution selects the 3252 // constructor. [...] For copy-initialization, the candidate 3253 // functions are all the converting constructors (12.3.1) of 3254 // that class. The argument list is the expression-list within 3255 // the parentheses of the initializer. 3256 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3257 (From->getType()->getAs<RecordType>() && 3258 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3259 ConstructorsOnly = true; 3260 3261 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3262 // We're not going to find any constructors. 3263 } else if (CXXRecordDecl *ToRecordDecl 3264 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3265 3266 Expr **Args = &From; 3267 unsigned NumArgs = 1; 3268 bool ListInitializing = false; 3269 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3270 // But first, see if there is an init-list-constructor that will work. 3271 OverloadingResult Result = IsInitializerListConstructorConversion( 3272 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3273 if (Result != OR_No_Viable_Function) 3274 return Result; 3275 // Never mind. 3276 CandidateSet.clear(); 3277 3278 // If we're list-initializing, we pass the individual elements as 3279 // arguments, not the entire list. 3280 Args = InitList->getInits(); 3281 NumArgs = InitList->getNumInits(); 3282 ListInitializing = true; 3283 } 3284 3285 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3286 auto Info = getConstructorInfo(D); 3287 if (!Info) 3288 continue; 3289 3290 bool Usable = !Info.Constructor->isInvalidDecl(); 3291 if (ListInitializing) 3292 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3293 else 3294 Usable = Usable && 3295 Info.Constructor->isConvertingConstructor(AllowExplicit); 3296 if (Usable) { 3297 bool SuppressUserConversions = !ConstructorsOnly; 3298 if (SuppressUserConversions && ListInitializing) { 3299 SuppressUserConversions = false; 3300 if (NumArgs == 1) { 3301 // If the first argument is (a reference to) the target type, 3302 // suppress conversions. 3303 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3304 S.Context, Info.Constructor, ToType); 3305 } 3306 } 3307 if (Info.ConstructorTmpl) 3308 S.AddTemplateOverloadCandidate( 3309 Info.ConstructorTmpl, Info.FoundDecl, 3310 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3311 CandidateSet, SuppressUserConversions); 3312 else 3313 // Allow one user-defined conversion when user specifies a 3314 // From->ToType conversion via an static cast (c-style, etc). 3315 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3316 llvm::makeArrayRef(Args, NumArgs), 3317 CandidateSet, SuppressUserConversions); 3318 } 3319 } 3320 } 3321 } 3322 3323 // Enumerate conversion functions, if we're allowed to. 3324 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3325 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3326 // No conversion functions from incomplete types. 3327 } else if (const RecordType *FromRecordType 3328 = From->getType()->getAs<RecordType>()) { 3329 if (CXXRecordDecl *FromRecordDecl 3330 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3331 // Add all of the conversion functions as candidates. 3332 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3333 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3334 DeclAccessPair FoundDecl = I.getPair(); 3335 NamedDecl *D = FoundDecl.getDecl(); 3336 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3337 if (isa<UsingShadowDecl>(D)) 3338 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3339 3340 CXXConversionDecl *Conv; 3341 FunctionTemplateDecl *ConvTemplate; 3342 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3343 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3344 else 3345 Conv = cast<CXXConversionDecl>(D); 3346 3347 if (AllowExplicit || !Conv->isExplicit()) { 3348 if (ConvTemplate) 3349 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3350 ActingContext, From, ToType, 3351 CandidateSet, 3352 AllowObjCConversionOnExplicit); 3353 else 3354 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3355 From, ToType, CandidateSet, 3356 AllowObjCConversionOnExplicit); 3357 } 3358 } 3359 } 3360 } 3361 3362 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3363 3364 OverloadCandidateSet::iterator Best; 3365 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3366 Best, true)) { 3367 case OR_Success: 3368 case OR_Deleted: 3369 // Record the standard conversion we used and the conversion function. 3370 if (CXXConstructorDecl *Constructor 3371 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3372 // C++ [over.ics.user]p1: 3373 // If the user-defined conversion is specified by a 3374 // constructor (12.3.1), the initial standard conversion 3375 // sequence converts the source type to the type required by 3376 // the argument of the constructor. 3377 // 3378 QualType ThisType = Constructor->getThisType(S.Context); 3379 if (isa<InitListExpr>(From)) { 3380 // Initializer lists don't have conversions as such. 3381 User.Before.setAsIdentityConversion(); 3382 } else { 3383 if (Best->Conversions[0].isEllipsis()) 3384 User.EllipsisConversion = true; 3385 else { 3386 User.Before = Best->Conversions[0].Standard; 3387 User.EllipsisConversion = false; 3388 } 3389 } 3390 User.HadMultipleCandidates = HadMultipleCandidates; 3391 User.ConversionFunction = Constructor; 3392 User.FoundConversionFunction = Best->FoundDecl; 3393 User.After.setAsIdentityConversion(); 3394 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3395 User.After.setAllToTypes(ToType); 3396 return Result; 3397 } 3398 if (CXXConversionDecl *Conversion 3399 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3400 // C++ [over.ics.user]p1: 3401 // 3402 // [...] If the user-defined conversion is specified by a 3403 // conversion function (12.3.2), the initial standard 3404 // conversion sequence converts the source type to the 3405 // implicit object parameter of the conversion function. 3406 User.Before = Best->Conversions[0].Standard; 3407 User.HadMultipleCandidates = HadMultipleCandidates; 3408 User.ConversionFunction = Conversion; 3409 User.FoundConversionFunction = Best->FoundDecl; 3410 User.EllipsisConversion = false; 3411 3412 // C++ [over.ics.user]p2: 3413 // The second standard conversion sequence converts the 3414 // result of the user-defined conversion to the target type 3415 // for the sequence. Since an implicit conversion sequence 3416 // is an initialization, the special rules for 3417 // initialization by user-defined conversion apply when 3418 // selecting the best user-defined conversion for a 3419 // user-defined conversion sequence (see 13.3.3 and 3420 // 13.3.3.1). 3421 User.After = Best->FinalConversion; 3422 return Result; 3423 } 3424 llvm_unreachable("Not a constructor or conversion function?"); 3425 3426 case OR_No_Viable_Function: 3427 return OR_No_Viable_Function; 3428 3429 case OR_Ambiguous: 3430 return OR_Ambiguous; 3431 } 3432 3433 llvm_unreachable("Invalid OverloadResult!"); 3434 } 3435 3436 bool 3437 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3438 ImplicitConversionSequence ICS; 3439 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3440 OverloadCandidateSet::CSK_Normal); 3441 OverloadingResult OvResult = 3442 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3443 CandidateSet, false, false); 3444 if (OvResult == OR_Ambiguous) 3445 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3446 << From->getType() << ToType << From->getSourceRange(); 3447 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3448 if (!RequireCompleteType(From->getLocStart(), ToType, 3449 diag::err_typecheck_nonviable_condition_incomplete, 3450 From->getType(), From->getSourceRange())) 3451 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3452 << false << From->getType() << From->getSourceRange() << ToType; 3453 } else 3454 return false; 3455 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3456 return true; 3457 } 3458 3459 /// \brief Compare the user-defined conversion functions or constructors 3460 /// of two user-defined conversion sequences to determine whether any ordering 3461 /// is possible. 3462 static ImplicitConversionSequence::CompareKind 3463 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3464 FunctionDecl *Function2) { 3465 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3466 return ImplicitConversionSequence::Indistinguishable; 3467 3468 // Objective-C++: 3469 // If both conversion functions are implicitly-declared conversions from 3470 // a lambda closure type to a function pointer and a block pointer, 3471 // respectively, always prefer the conversion to a function pointer, 3472 // because the function pointer is more lightweight and is more likely 3473 // to keep code working. 3474 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3475 if (!Conv1) 3476 return ImplicitConversionSequence::Indistinguishable; 3477 3478 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3479 if (!Conv2) 3480 return ImplicitConversionSequence::Indistinguishable; 3481 3482 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3483 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3484 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3485 if (Block1 != Block2) 3486 return Block1 ? ImplicitConversionSequence::Worse 3487 : ImplicitConversionSequence::Better; 3488 } 3489 3490 return ImplicitConversionSequence::Indistinguishable; 3491 } 3492 3493 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3494 const ImplicitConversionSequence &ICS) { 3495 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3496 (ICS.isUserDefined() && 3497 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3498 } 3499 3500 /// CompareImplicitConversionSequences - Compare two implicit 3501 /// conversion sequences to determine whether one is better than the 3502 /// other or if they are indistinguishable (C++ 13.3.3.2). 3503 static ImplicitConversionSequence::CompareKind 3504 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3505 const ImplicitConversionSequence& ICS1, 3506 const ImplicitConversionSequence& ICS2) 3507 { 3508 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3509 // conversion sequences (as defined in 13.3.3.1) 3510 // -- a standard conversion sequence (13.3.3.1.1) is a better 3511 // conversion sequence than a user-defined conversion sequence or 3512 // an ellipsis conversion sequence, and 3513 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3514 // conversion sequence than an ellipsis conversion sequence 3515 // (13.3.3.1.3). 3516 // 3517 // C++0x [over.best.ics]p10: 3518 // For the purpose of ranking implicit conversion sequences as 3519 // described in 13.3.3.2, the ambiguous conversion sequence is 3520 // treated as a user-defined sequence that is indistinguishable 3521 // from any other user-defined conversion sequence. 3522 3523 // String literal to 'char *' conversion has been deprecated in C++03. It has 3524 // been removed from C++11. We still accept this conversion, if it happens at 3525 // the best viable function. Otherwise, this conversion is considered worse 3526 // than ellipsis conversion. Consider this as an extension; this is not in the 3527 // standard. For example: 3528 // 3529 // int &f(...); // #1 3530 // void f(char*); // #2 3531 // void g() { int &r = f("foo"); } 3532 // 3533 // In C++03, we pick #2 as the best viable function. 3534 // In C++11, we pick #1 as the best viable function, because ellipsis 3535 // conversion is better than string-literal to char* conversion (since there 3536 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3537 // convert arguments, #2 would be the best viable function in C++11. 3538 // If the best viable function has this conversion, a warning will be issued 3539 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3540 3541 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3542 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3543 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3544 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3545 ? ImplicitConversionSequence::Worse 3546 : ImplicitConversionSequence::Better; 3547 3548 if (ICS1.getKindRank() < ICS2.getKindRank()) 3549 return ImplicitConversionSequence::Better; 3550 if (ICS2.getKindRank() < ICS1.getKindRank()) 3551 return ImplicitConversionSequence::Worse; 3552 3553 // The following checks require both conversion sequences to be of 3554 // the same kind. 3555 if (ICS1.getKind() != ICS2.getKind()) 3556 return ImplicitConversionSequence::Indistinguishable; 3557 3558 ImplicitConversionSequence::CompareKind Result = 3559 ImplicitConversionSequence::Indistinguishable; 3560 3561 // Two implicit conversion sequences of the same form are 3562 // indistinguishable conversion sequences unless one of the 3563 // following rules apply: (C++ 13.3.3.2p3): 3564 3565 // List-initialization sequence L1 is a better conversion sequence than 3566 // list-initialization sequence L2 if: 3567 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3568 // if not that, 3569 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3570 // and N1 is smaller than N2., 3571 // even if one of the other rules in this paragraph would otherwise apply. 3572 if (!ICS1.isBad()) { 3573 if (ICS1.isStdInitializerListElement() && 3574 !ICS2.isStdInitializerListElement()) 3575 return ImplicitConversionSequence::Better; 3576 if (!ICS1.isStdInitializerListElement() && 3577 ICS2.isStdInitializerListElement()) 3578 return ImplicitConversionSequence::Worse; 3579 } 3580 3581 if (ICS1.isStandard()) 3582 // Standard conversion sequence S1 is a better conversion sequence than 3583 // standard conversion sequence S2 if [...] 3584 Result = CompareStandardConversionSequences(S, Loc, 3585 ICS1.Standard, ICS2.Standard); 3586 else if (ICS1.isUserDefined()) { 3587 // User-defined conversion sequence U1 is a better conversion 3588 // sequence than another user-defined conversion sequence U2 if 3589 // they contain the same user-defined conversion function or 3590 // constructor and if the second standard conversion sequence of 3591 // U1 is better than the second standard conversion sequence of 3592 // U2 (C++ 13.3.3.2p3). 3593 if (ICS1.UserDefined.ConversionFunction == 3594 ICS2.UserDefined.ConversionFunction) 3595 Result = CompareStandardConversionSequences(S, Loc, 3596 ICS1.UserDefined.After, 3597 ICS2.UserDefined.After); 3598 else 3599 Result = compareConversionFunctions(S, 3600 ICS1.UserDefined.ConversionFunction, 3601 ICS2.UserDefined.ConversionFunction); 3602 } 3603 3604 return Result; 3605 } 3606 3607 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3608 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3609 Qualifiers Quals; 3610 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3611 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3612 } 3613 3614 return Context.hasSameUnqualifiedType(T1, T2); 3615 } 3616 3617 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3618 // determine if one is a proper subset of the other. 3619 static ImplicitConversionSequence::CompareKind 3620 compareStandardConversionSubsets(ASTContext &Context, 3621 const StandardConversionSequence& SCS1, 3622 const StandardConversionSequence& SCS2) { 3623 ImplicitConversionSequence::CompareKind Result 3624 = ImplicitConversionSequence::Indistinguishable; 3625 3626 // the identity conversion sequence is considered to be a subsequence of 3627 // any non-identity conversion sequence 3628 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3629 return ImplicitConversionSequence::Better; 3630 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3631 return ImplicitConversionSequence::Worse; 3632 3633 if (SCS1.Second != SCS2.Second) { 3634 if (SCS1.Second == ICK_Identity) 3635 Result = ImplicitConversionSequence::Better; 3636 else if (SCS2.Second == ICK_Identity) 3637 Result = ImplicitConversionSequence::Worse; 3638 else 3639 return ImplicitConversionSequence::Indistinguishable; 3640 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3641 return ImplicitConversionSequence::Indistinguishable; 3642 3643 if (SCS1.Third == SCS2.Third) { 3644 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3645 : ImplicitConversionSequence::Indistinguishable; 3646 } 3647 3648 if (SCS1.Third == ICK_Identity) 3649 return Result == ImplicitConversionSequence::Worse 3650 ? ImplicitConversionSequence::Indistinguishable 3651 : ImplicitConversionSequence::Better; 3652 3653 if (SCS2.Third == ICK_Identity) 3654 return Result == ImplicitConversionSequence::Better 3655 ? ImplicitConversionSequence::Indistinguishable 3656 : ImplicitConversionSequence::Worse; 3657 3658 return ImplicitConversionSequence::Indistinguishable; 3659 } 3660 3661 /// \brief Determine whether one of the given reference bindings is better 3662 /// than the other based on what kind of bindings they are. 3663 static bool 3664 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3665 const StandardConversionSequence &SCS2) { 3666 // C++0x [over.ics.rank]p3b4: 3667 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3668 // implicit object parameter of a non-static member function declared 3669 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3670 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3671 // lvalue reference to a function lvalue and S2 binds an rvalue 3672 // reference*. 3673 // 3674 // FIXME: Rvalue references. We're going rogue with the above edits, 3675 // because the semantics in the current C++0x working paper (N3225 at the 3676 // time of this writing) break the standard definition of std::forward 3677 // and std::reference_wrapper when dealing with references to functions. 3678 // Proposed wording changes submitted to CWG for consideration. 3679 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3680 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3681 return false; 3682 3683 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3684 SCS2.IsLvalueReference) || 3685 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3686 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3687 } 3688 3689 /// CompareStandardConversionSequences - Compare two standard 3690 /// conversion sequences to determine whether one is better than the 3691 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3692 static ImplicitConversionSequence::CompareKind 3693 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3694 const StandardConversionSequence& SCS1, 3695 const StandardConversionSequence& SCS2) 3696 { 3697 // Standard conversion sequence S1 is a better conversion sequence 3698 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3699 3700 // -- S1 is a proper subsequence of S2 (comparing the conversion 3701 // sequences in the canonical form defined by 13.3.3.1.1, 3702 // excluding any Lvalue Transformation; the identity conversion 3703 // sequence is considered to be a subsequence of any 3704 // non-identity conversion sequence) or, if not that, 3705 if (ImplicitConversionSequence::CompareKind CK 3706 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3707 return CK; 3708 3709 // -- the rank of S1 is better than the rank of S2 (by the rules 3710 // defined below), or, if not that, 3711 ImplicitConversionRank Rank1 = SCS1.getRank(); 3712 ImplicitConversionRank Rank2 = SCS2.getRank(); 3713 if (Rank1 < Rank2) 3714 return ImplicitConversionSequence::Better; 3715 else if (Rank2 < Rank1) 3716 return ImplicitConversionSequence::Worse; 3717 3718 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3719 // are indistinguishable unless one of the following rules 3720 // applies: 3721 3722 // A conversion that is not a conversion of a pointer, or 3723 // pointer to member, to bool is better than another conversion 3724 // that is such a conversion. 3725 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3726 return SCS2.isPointerConversionToBool() 3727 ? ImplicitConversionSequence::Better 3728 : ImplicitConversionSequence::Worse; 3729 3730 // C++ [over.ics.rank]p4b2: 3731 // 3732 // If class B is derived directly or indirectly from class A, 3733 // conversion of B* to A* is better than conversion of B* to 3734 // void*, and conversion of A* to void* is better than conversion 3735 // of B* to void*. 3736 bool SCS1ConvertsToVoid 3737 = SCS1.isPointerConversionToVoidPointer(S.Context); 3738 bool SCS2ConvertsToVoid 3739 = SCS2.isPointerConversionToVoidPointer(S.Context); 3740 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3741 // Exactly one of the conversion sequences is a conversion to 3742 // a void pointer; it's the worse conversion. 3743 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3744 : ImplicitConversionSequence::Worse; 3745 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3746 // Neither conversion sequence converts to a void pointer; compare 3747 // their derived-to-base conversions. 3748 if (ImplicitConversionSequence::CompareKind DerivedCK 3749 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3750 return DerivedCK; 3751 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3752 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3753 // Both conversion sequences are conversions to void 3754 // pointers. Compare the source types to determine if there's an 3755 // inheritance relationship in their sources. 3756 QualType FromType1 = SCS1.getFromType(); 3757 QualType FromType2 = SCS2.getFromType(); 3758 3759 // Adjust the types we're converting from via the array-to-pointer 3760 // conversion, if we need to. 3761 if (SCS1.First == ICK_Array_To_Pointer) 3762 FromType1 = S.Context.getArrayDecayedType(FromType1); 3763 if (SCS2.First == ICK_Array_To_Pointer) 3764 FromType2 = S.Context.getArrayDecayedType(FromType2); 3765 3766 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3767 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3768 3769 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3770 return ImplicitConversionSequence::Better; 3771 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3772 return ImplicitConversionSequence::Worse; 3773 3774 // Objective-C++: If one interface is more specific than the 3775 // other, it is the better one. 3776 const ObjCObjectPointerType* FromObjCPtr1 3777 = FromType1->getAs<ObjCObjectPointerType>(); 3778 const ObjCObjectPointerType* FromObjCPtr2 3779 = FromType2->getAs<ObjCObjectPointerType>(); 3780 if (FromObjCPtr1 && FromObjCPtr2) { 3781 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3782 FromObjCPtr2); 3783 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3784 FromObjCPtr1); 3785 if (AssignLeft != AssignRight) { 3786 return AssignLeft? ImplicitConversionSequence::Better 3787 : ImplicitConversionSequence::Worse; 3788 } 3789 } 3790 } 3791 3792 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3793 // bullet 3). 3794 if (ImplicitConversionSequence::CompareKind QualCK 3795 = CompareQualificationConversions(S, SCS1, SCS2)) 3796 return QualCK; 3797 3798 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3799 // Check for a better reference binding based on the kind of bindings. 3800 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3801 return ImplicitConversionSequence::Better; 3802 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3803 return ImplicitConversionSequence::Worse; 3804 3805 // C++ [over.ics.rank]p3b4: 3806 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3807 // which the references refer are the same type except for 3808 // top-level cv-qualifiers, and the type to which the reference 3809 // initialized by S2 refers is more cv-qualified than the type 3810 // to which the reference initialized by S1 refers. 3811 QualType T1 = SCS1.getToType(2); 3812 QualType T2 = SCS2.getToType(2); 3813 T1 = S.Context.getCanonicalType(T1); 3814 T2 = S.Context.getCanonicalType(T2); 3815 Qualifiers T1Quals, T2Quals; 3816 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3817 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3818 if (UnqualT1 == UnqualT2) { 3819 // Objective-C++ ARC: If the references refer to objects with different 3820 // lifetimes, prefer bindings that don't change lifetime. 3821 if (SCS1.ObjCLifetimeConversionBinding != 3822 SCS2.ObjCLifetimeConversionBinding) { 3823 return SCS1.ObjCLifetimeConversionBinding 3824 ? ImplicitConversionSequence::Worse 3825 : ImplicitConversionSequence::Better; 3826 } 3827 3828 // If the type is an array type, promote the element qualifiers to the 3829 // type for comparison. 3830 if (isa<ArrayType>(T1) && T1Quals) 3831 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3832 if (isa<ArrayType>(T2) && T2Quals) 3833 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3834 if (T2.isMoreQualifiedThan(T1)) 3835 return ImplicitConversionSequence::Better; 3836 else if (T1.isMoreQualifiedThan(T2)) 3837 return ImplicitConversionSequence::Worse; 3838 } 3839 } 3840 3841 // In Microsoft mode, prefer an integral conversion to a 3842 // floating-to-integral conversion if the integral conversion 3843 // is between types of the same size. 3844 // For example: 3845 // void f(float); 3846 // void f(int); 3847 // int main { 3848 // long a; 3849 // f(a); 3850 // } 3851 // Here, MSVC will call f(int) instead of generating a compile error 3852 // as clang will do in standard mode. 3853 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3854 SCS2.Second == ICK_Floating_Integral && 3855 S.Context.getTypeSize(SCS1.getFromType()) == 3856 S.Context.getTypeSize(SCS1.getToType(2))) 3857 return ImplicitConversionSequence::Better; 3858 3859 return ImplicitConversionSequence::Indistinguishable; 3860 } 3861 3862 /// CompareQualificationConversions - Compares two standard conversion 3863 /// sequences to determine whether they can be ranked based on their 3864 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3865 static ImplicitConversionSequence::CompareKind 3866 CompareQualificationConversions(Sema &S, 3867 const StandardConversionSequence& SCS1, 3868 const StandardConversionSequence& SCS2) { 3869 // C++ 13.3.3.2p3: 3870 // -- S1 and S2 differ only in their qualification conversion and 3871 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3872 // cv-qualification signature of type T1 is a proper subset of 3873 // the cv-qualification signature of type T2, and S1 is not the 3874 // deprecated string literal array-to-pointer conversion (4.2). 3875 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3876 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3877 return ImplicitConversionSequence::Indistinguishable; 3878 3879 // FIXME: the example in the standard doesn't use a qualification 3880 // conversion (!) 3881 QualType T1 = SCS1.getToType(2); 3882 QualType T2 = SCS2.getToType(2); 3883 T1 = S.Context.getCanonicalType(T1); 3884 T2 = S.Context.getCanonicalType(T2); 3885 Qualifiers T1Quals, T2Quals; 3886 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3887 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3888 3889 // If the types are the same, we won't learn anything by unwrapped 3890 // them. 3891 if (UnqualT1 == UnqualT2) 3892 return ImplicitConversionSequence::Indistinguishable; 3893 3894 // If the type is an array type, promote the element qualifiers to the type 3895 // for comparison. 3896 if (isa<ArrayType>(T1) && T1Quals) 3897 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3898 if (isa<ArrayType>(T2) && T2Quals) 3899 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3900 3901 ImplicitConversionSequence::CompareKind Result 3902 = ImplicitConversionSequence::Indistinguishable; 3903 3904 // Objective-C++ ARC: 3905 // Prefer qualification conversions not involving a change in lifetime 3906 // to qualification conversions that do not change lifetime. 3907 if (SCS1.QualificationIncludesObjCLifetime != 3908 SCS2.QualificationIncludesObjCLifetime) { 3909 Result = SCS1.QualificationIncludesObjCLifetime 3910 ? ImplicitConversionSequence::Worse 3911 : ImplicitConversionSequence::Better; 3912 } 3913 3914 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3915 // Within each iteration of the loop, we check the qualifiers to 3916 // determine if this still looks like a qualification 3917 // conversion. Then, if all is well, we unwrap one more level of 3918 // pointers or pointers-to-members and do it all again 3919 // until there are no more pointers or pointers-to-members left 3920 // to unwrap. This essentially mimics what 3921 // IsQualificationConversion does, but here we're checking for a 3922 // strict subset of qualifiers. 3923 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3924 // The qualifiers are the same, so this doesn't tell us anything 3925 // about how the sequences rank. 3926 ; 3927 else if (T2.isMoreQualifiedThan(T1)) { 3928 // T1 has fewer qualifiers, so it could be the better sequence. 3929 if (Result == ImplicitConversionSequence::Worse) 3930 // Neither has qualifiers that are a subset of the other's 3931 // qualifiers. 3932 return ImplicitConversionSequence::Indistinguishable; 3933 3934 Result = ImplicitConversionSequence::Better; 3935 } else if (T1.isMoreQualifiedThan(T2)) { 3936 // T2 has fewer qualifiers, so it could be the better sequence. 3937 if (Result == ImplicitConversionSequence::Better) 3938 // Neither has qualifiers that are a subset of the other's 3939 // qualifiers. 3940 return ImplicitConversionSequence::Indistinguishable; 3941 3942 Result = ImplicitConversionSequence::Worse; 3943 } else { 3944 // Qualifiers are disjoint. 3945 return ImplicitConversionSequence::Indistinguishable; 3946 } 3947 3948 // If the types after this point are equivalent, we're done. 3949 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3950 break; 3951 } 3952 3953 // Check that the winning standard conversion sequence isn't using 3954 // the deprecated string literal array to pointer conversion. 3955 switch (Result) { 3956 case ImplicitConversionSequence::Better: 3957 if (SCS1.DeprecatedStringLiteralToCharPtr) 3958 Result = ImplicitConversionSequence::Indistinguishable; 3959 break; 3960 3961 case ImplicitConversionSequence::Indistinguishable: 3962 break; 3963 3964 case ImplicitConversionSequence::Worse: 3965 if (SCS2.DeprecatedStringLiteralToCharPtr) 3966 Result = ImplicitConversionSequence::Indistinguishable; 3967 break; 3968 } 3969 3970 return Result; 3971 } 3972 3973 /// CompareDerivedToBaseConversions - Compares two standard conversion 3974 /// sequences to determine whether they can be ranked based on their 3975 /// various kinds of derived-to-base conversions (C++ 3976 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3977 /// conversions between Objective-C interface types. 3978 static ImplicitConversionSequence::CompareKind 3979 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3980 const StandardConversionSequence& SCS1, 3981 const StandardConversionSequence& SCS2) { 3982 QualType FromType1 = SCS1.getFromType(); 3983 QualType ToType1 = SCS1.getToType(1); 3984 QualType FromType2 = SCS2.getFromType(); 3985 QualType ToType2 = SCS2.getToType(1); 3986 3987 // Adjust the types we're converting from via the array-to-pointer 3988 // conversion, if we need to. 3989 if (SCS1.First == ICK_Array_To_Pointer) 3990 FromType1 = S.Context.getArrayDecayedType(FromType1); 3991 if (SCS2.First == ICK_Array_To_Pointer) 3992 FromType2 = S.Context.getArrayDecayedType(FromType2); 3993 3994 // Canonicalize all of the types. 3995 FromType1 = S.Context.getCanonicalType(FromType1); 3996 ToType1 = S.Context.getCanonicalType(ToType1); 3997 FromType2 = S.Context.getCanonicalType(FromType2); 3998 ToType2 = S.Context.getCanonicalType(ToType2); 3999 4000 // C++ [over.ics.rank]p4b3: 4001 // 4002 // If class B is derived directly or indirectly from class A and 4003 // class C is derived directly or indirectly from B, 4004 // 4005 // Compare based on pointer conversions. 4006 if (SCS1.Second == ICK_Pointer_Conversion && 4007 SCS2.Second == ICK_Pointer_Conversion && 4008 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4009 FromType1->isPointerType() && FromType2->isPointerType() && 4010 ToType1->isPointerType() && ToType2->isPointerType()) { 4011 QualType FromPointee1 4012 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4013 QualType ToPointee1 4014 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4015 QualType FromPointee2 4016 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4017 QualType ToPointee2 4018 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4019 4020 // -- conversion of C* to B* is better than conversion of C* to A*, 4021 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4022 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4023 return ImplicitConversionSequence::Better; 4024 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4025 return ImplicitConversionSequence::Worse; 4026 } 4027 4028 // -- conversion of B* to A* is better than conversion of C* to A*, 4029 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4030 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4031 return ImplicitConversionSequence::Better; 4032 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4033 return ImplicitConversionSequence::Worse; 4034 } 4035 } else if (SCS1.Second == ICK_Pointer_Conversion && 4036 SCS2.Second == ICK_Pointer_Conversion) { 4037 const ObjCObjectPointerType *FromPtr1 4038 = FromType1->getAs<ObjCObjectPointerType>(); 4039 const ObjCObjectPointerType *FromPtr2 4040 = FromType2->getAs<ObjCObjectPointerType>(); 4041 const ObjCObjectPointerType *ToPtr1 4042 = ToType1->getAs<ObjCObjectPointerType>(); 4043 const ObjCObjectPointerType *ToPtr2 4044 = ToType2->getAs<ObjCObjectPointerType>(); 4045 4046 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4047 // Apply the same conversion ranking rules for Objective-C pointer types 4048 // that we do for C++ pointers to class types. However, we employ the 4049 // Objective-C pseudo-subtyping relationship used for assignment of 4050 // Objective-C pointer types. 4051 bool FromAssignLeft 4052 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4053 bool FromAssignRight 4054 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4055 bool ToAssignLeft 4056 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4057 bool ToAssignRight 4058 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4059 4060 // A conversion to an a non-id object pointer type or qualified 'id' 4061 // type is better than a conversion to 'id'. 4062 if (ToPtr1->isObjCIdType() && 4063 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4064 return ImplicitConversionSequence::Worse; 4065 if (ToPtr2->isObjCIdType() && 4066 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4067 return ImplicitConversionSequence::Better; 4068 4069 // A conversion to a non-id object pointer type is better than a 4070 // conversion to a qualified 'id' type 4071 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4072 return ImplicitConversionSequence::Worse; 4073 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4074 return ImplicitConversionSequence::Better; 4075 4076 // A conversion to an a non-Class object pointer type or qualified 'Class' 4077 // type is better than a conversion to 'Class'. 4078 if (ToPtr1->isObjCClassType() && 4079 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4080 return ImplicitConversionSequence::Worse; 4081 if (ToPtr2->isObjCClassType() && 4082 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4083 return ImplicitConversionSequence::Better; 4084 4085 // A conversion to a non-Class object pointer type is better than a 4086 // conversion to a qualified 'Class' type. 4087 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4088 return ImplicitConversionSequence::Worse; 4089 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4090 return ImplicitConversionSequence::Better; 4091 4092 // -- "conversion of C* to B* is better than conversion of C* to A*," 4093 if (S.Context.hasSameType(FromType1, FromType2) && 4094 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4095 (ToAssignLeft != ToAssignRight)) 4096 return ToAssignLeft? ImplicitConversionSequence::Worse 4097 : ImplicitConversionSequence::Better; 4098 4099 // -- "conversion of B* to A* is better than conversion of C* to A*," 4100 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4101 (FromAssignLeft != FromAssignRight)) 4102 return FromAssignLeft? ImplicitConversionSequence::Better 4103 : ImplicitConversionSequence::Worse; 4104 } 4105 } 4106 4107 // Ranking of member-pointer types. 4108 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4109 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4110 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4111 const MemberPointerType * FromMemPointer1 = 4112 FromType1->getAs<MemberPointerType>(); 4113 const MemberPointerType * ToMemPointer1 = 4114 ToType1->getAs<MemberPointerType>(); 4115 const MemberPointerType * FromMemPointer2 = 4116 FromType2->getAs<MemberPointerType>(); 4117 const MemberPointerType * ToMemPointer2 = 4118 ToType2->getAs<MemberPointerType>(); 4119 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4120 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4121 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4122 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4123 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4124 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4125 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4126 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4127 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4128 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4129 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4130 return ImplicitConversionSequence::Worse; 4131 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4132 return ImplicitConversionSequence::Better; 4133 } 4134 // conversion of B::* to C::* is better than conversion of A::* to C::* 4135 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4136 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4137 return ImplicitConversionSequence::Better; 4138 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4139 return ImplicitConversionSequence::Worse; 4140 } 4141 } 4142 4143 if (SCS1.Second == ICK_Derived_To_Base) { 4144 // -- conversion of C to B is better than conversion of C to A, 4145 // -- binding of an expression of type C to a reference of type 4146 // B& is better than binding an expression of type C to a 4147 // reference of type A&, 4148 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4149 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4150 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4151 return ImplicitConversionSequence::Better; 4152 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4153 return ImplicitConversionSequence::Worse; 4154 } 4155 4156 // -- conversion of B to A is better than conversion of C to A. 4157 // -- binding of an expression of type B to a reference of type 4158 // A& is better than binding an expression of type C to a 4159 // reference of type A&, 4160 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4161 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4162 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4163 return ImplicitConversionSequence::Better; 4164 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4165 return ImplicitConversionSequence::Worse; 4166 } 4167 } 4168 4169 return ImplicitConversionSequence::Indistinguishable; 4170 } 4171 4172 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4173 /// C++ class. 4174 static bool isTypeValid(QualType T) { 4175 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4176 return !Record->isInvalidDecl(); 4177 4178 return true; 4179 } 4180 4181 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4182 /// determine whether they are reference-related, 4183 /// reference-compatible, reference-compatible with added 4184 /// qualification, or incompatible, for use in C++ initialization by 4185 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4186 /// type, and the first type (T1) is the pointee type of the reference 4187 /// type being initialized. 4188 Sema::ReferenceCompareResult 4189 Sema::CompareReferenceRelationship(SourceLocation Loc, 4190 QualType OrigT1, QualType OrigT2, 4191 bool &DerivedToBase, 4192 bool &ObjCConversion, 4193 bool &ObjCLifetimeConversion) { 4194 assert(!OrigT1->isReferenceType() && 4195 "T1 must be the pointee type of the reference type"); 4196 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4197 4198 QualType T1 = Context.getCanonicalType(OrigT1); 4199 QualType T2 = Context.getCanonicalType(OrigT2); 4200 Qualifiers T1Quals, T2Quals; 4201 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4202 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4203 4204 // C++ [dcl.init.ref]p4: 4205 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4206 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4207 // T1 is a base class of T2. 4208 DerivedToBase = false; 4209 ObjCConversion = false; 4210 ObjCLifetimeConversion = false; 4211 QualType ConvertedT2; 4212 if (UnqualT1 == UnqualT2) { 4213 // Nothing to do. 4214 } else if (isCompleteType(Loc, OrigT2) && 4215 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4216 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4217 DerivedToBase = true; 4218 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4219 UnqualT2->isObjCObjectOrInterfaceType() && 4220 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4221 ObjCConversion = true; 4222 else if (UnqualT2->isFunctionType() && 4223 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4224 // C++1z [dcl.init.ref]p4: 4225 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4226 // function" and T1 is "function" 4227 // 4228 // We extend this to also apply to 'noreturn', so allow any function 4229 // conversion between function types. 4230 return Ref_Compatible; 4231 else 4232 return Ref_Incompatible; 4233 4234 // At this point, we know that T1 and T2 are reference-related (at 4235 // least). 4236 4237 // If the type is an array type, promote the element qualifiers to the type 4238 // for comparison. 4239 if (isa<ArrayType>(T1) && T1Quals) 4240 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4241 if (isa<ArrayType>(T2) && T2Quals) 4242 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4243 4244 // C++ [dcl.init.ref]p4: 4245 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4246 // reference-related to T2 and cv1 is the same cv-qualification 4247 // as, or greater cv-qualification than, cv2. For purposes of 4248 // overload resolution, cases for which cv1 is greater 4249 // cv-qualification than cv2 are identified as 4250 // reference-compatible with added qualification (see 13.3.3.2). 4251 // 4252 // Note that we also require equivalence of Objective-C GC and address-space 4253 // qualifiers when performing these computations, so that e.g., an int in 4254 // address space 1 is not reference-compatible with an int in address 4255 // space 2. 4256 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4257 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4258 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4259 ObjCLifetimeConversion = true; 4260 4261 T1Quals.removeObjCLifetime(); 4262 T2Quals.removeObjCLifetime(); 4263 } 4264 4265 // MS compiler ignores __unaligned qualifier for references; do the same. 4266 T1Quals.removeUnaligned(); 4267 T2Quals.removeUnaligned(); 4268 4269 if (T1Quals.compatiblyIncludes(T2Quals)) 4270 return Ref_Compatible; 4271 else 4272 return Ref_Related; 4273 } 4274 4275 /// \brief Look for a user-defined conversion to an value reference-compatible 4276 /// with DeclType. Return true if something definite is found. 4277 static bool 4278 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4279 QualType DeclType, SourceLocation DeclLoc, 4280 Expr *Init, QualType T2, bool AllowRvalues, 4281 bool AllowExplicit) { 4282 assert(T2->isRecordType() && "Can only find conversions of record types."); 4283 CXXRecordDecl *T2RecordDecl 4284 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4285 4286 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4287 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4288 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4289 NamedDecl *D = *I; 4290 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4291 if (isa<UsingShadowDecl>(D)) 4292 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4293 4294 FunctionTemplateDecl *ConvTemplate 4295 = dyn_cast<FunctionTemplateDecl>(D); 4296 CXXConversionDecl *Conv; 4297 if (ConvTemplate) 4298 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4299 else 4300 Conv = cast<CXXConversionDecl>(D); 4301 4302 // If this is an explicit conversion, and we're not allowed to consider 4303 // explicit conversions, skip it. 4304 if (!AllowExplicit && Conv->isExplicit()) 4305 continue; 4306 4307 if (AllowRvalues) { 4308 bool DerivedToBase = false; 4309 bool ObjCConversion = false; 4310 bool ObjCLifetimeConversion = false; 4311 4312 // If we are initializing an rvalue reference, don't permit conversion 4313 // functions that return lvalues. 4314 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4315 const ReferenceType *RefType 4316 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4317 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4318 continue; 4319 } 4320 4321 if (!ConvTemplate && 4322 S.CompareReferenceRelationship( 4323 DeclLoc, 4324 Conv->getConversionType().getNonReferenceType() 4325 .getUnqualifiedType(), 4326 DeclType.getNonReferenceType().getUnqualifiedType(), 4327 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4328 Sema::Ref_Incompatible) 4329 continue; 4330 } else { 4331 // If the conversion function doesn't return a reference type, 4332 // it can't be considered for this conversion. An rvalue reference 4333 // is only acceptable if its referencee is a function type. 4334 4335 const ReferenceType *RefType = 4336 Conv->getConversionType()->getAs<ReferenceType>(); 4337 if (!RefType || 4338 (!RefType->isLValueReferenceType() && 4339 !RefType->getPointeeType()->isFunctionType())) 4340 continue; 4341 } 4342 4343 if (ConvTemplate) 4344 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4345 Init, DeclType, CandidateSet, 4346 /*AllowObjCConversionOnExplicit=*/false); 4347 else 4348 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4349 DeclType, CandidateSet, 4350 /*AllowObjCConversionOnExplicit=*/false); 4351 } 4352 4353 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4354 4355 OverloadCandidateSet::iterator Best; 4356 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4357 case OR_Success: 4358 // C++ [over.ics.ref]p1: 4359 // 4360 // [...] If the parameter binds directly to the result of 4361 // applying a conversion function to the argument 4362 // expression, the implicit conversion sequence is a 4363 // user-defined conversion sequence (13.3.3.1.2), with the 4364 // second standard conversion sequence either an identity 4365 // conversion or, if the conversion function returns an 4366 // entity of a type that is a derived class of the parameter 4367 // type, a derived-to-base Conversion. 4368 if (!Best->FinalConversion.DirectBinding) 4369 return false; 4370 4371 ICS.setUserDefined(); 4372 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4373 ICS.UserDefined.After = Best->FinalConversion; 4374 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4375 ICS.UserDefined.ConversionFunction = Best->Function; 4376 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4377 ICS.UserDefined.EllipsisConversion = false; 4378 assert(ICS.UserDefined.After.ReferenceBinding && 4379 ICS.UserDefined.After.DirectBinding && 4380 "Expected a direct reference binding!"); 4381 return true; 4382 4383 case OR_Ambiguous: 4384 ICS.setAmbiguous(); 4385 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4386 Cand != CandidateSet.end(); ++Cand) 4387 if (Cand->Viable) 4388 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4389 return true; 4390 4391 case OR_No_Viable_Function: 4392 case OR_Deleted: 4393 // There was no suitable conversion, or we found a deleted 4394 // conversion; continue with other checks. 4395 return false; 4396 } 4397 4398 llvm_unreachable("Invalid OverloadResult!"); 4399 } 4400 4401 /// \brief Compute an implicit conversion sequence for reference 4402 /// initialization. 4403 static ImplicitConversionSequence 4404 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4405 SourceLocation DeclLoc, 4406 bool SuppressUserConversions, 4407 bool AllowExplicit) { 4408 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4409 4410 // Most paths end in a failed conversion. 4411 ImplicitConversionSequence ICS; 4412 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4413 4414 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4415 QualType T2 = Init->getType(); 4416 4417 // If the initializer is the address of an overloaded function, try 4418 // to resolve the overloaded function. If all goes well, T2 is the 4419 // type of the resulting function. 4420 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4421 DeclAccessPair Found; 4422 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4423 false, Found)) 4424 T2 = Fn->getType(); 4425 } 4426 4427 // Compute some basic properties of the types and the initializer. 4428 bool isRValRef = DeclType->isRValueReferenceType(); 4429 bool DerivedToBase = false; 4430 bool ObjCConversion = false; 4431 bool ObjCLifetimeConversion = false; 4432 Expr::Classification InitCategory = Init->Classify(S.Context); 4433 Sema::ReferenceCompareResult RefRelationship 4434 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4435 ObjCConversion, ObjCLifetimeConversion); 4436 4437 4438 // C++0x [dcl.init.ref]p5: 4439 // A reference to type "cv1 T1" is initialized by an expression 4440 // of type "cv2 T2" as follows: 4441 4442 // -- If reference is an lvalue reference and the initializer expression 4443 if (!isRValRef) { 4444 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4445 // reference-compatible with "cv2 T2," or 4446 // 4447 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4448 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4449 // C++ [over.ics.ref]p1: 4450 // When a parameter of reference type binds directly (8.5.3) 4451 // to an argument expression, the implicit conversion sequence 4452 // is the identity conversion, unless the argument expression 4453 // has a type that is a derived class of the parameter type, 4454 // in which case the implicit conversion sequence is a 4455 // derived-to-base Conversion (13.3.3.1). 4456 ICS.setStandard(); 4457 ICS.Standard.First = ICK_Identity; 4458 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4459 : ObjCConversion? ICK_Compatible_Conversion 4460 : ICK_Identity; 4461 ICS.Standard.Third = ICK_Identity; 4462 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4463 ICS.Standard.setToType(0, T2); 4464 ICS.Standard.setToType(1, T1); 4465 ICS.Standard.setToType(2, T1); 4466 ICS.Standard.ReferenceBinding = true; 4467 ICS.Standard.DirectBinding = true; 4468 ICS.Standard.IsLvalueReference = !isRValRef; 4469 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4470 ICS.Standard.BindsToRvalue = false; 4471 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4472 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4473 ICS.Standard.CopyConstructor = nullptr; 4474 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4475 4476 // Nothing more to do: the inaccessibility/ambiguity check for 4477 // derived-to-base conversions is suppressed when we're 4478 // computing the implicit conversion sequence (C++ 4479 // [over.best.ics]p2). 4480 return ICS; 4481 } 4482 4483 // -- has a class type (i.e., T2 is a class type), where T1 is 4484 // not reference-related to T2, and can be implicitly 4485 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4486 // is reference-compatible with "cv3 T3" 92) (this 4487 // conversion is selected by enumerating the applicable 4488 // conversion functions (13.3.1.6) and choosing the best 4489 // one through overload resolution (13.3)), 4490 if (!SuppressUserConversions && T2->isRecordType() && 4491 S.isCompleteType(DeclLoc, T2) && 4492 RefRelationship == Sema::Ref_Incompatible) { 4493 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4494 Init, T2, /*AllowRvalues=*/false, 4495 AllowExplicit)) 4496 return ICS; 4497 } 4498 } 4499 4500 // -- Otherwise, the reference shall be an lvalue reference to a 4501 // non-volatile const type (i.e., cv1 shall be const), or the reference 4502 // shall be an rvalue reference. 4503 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4504 return ICS; 4505 4506 // -- If the initializer expression 4507 // 4508 // -- is an xvalue, class prvalue, array prvalue or function 4509 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4510 if (RefRelationship == Sema::Ref_Compatible && 4511 (InitCategory.isXValue() || 4512 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4513 (InitCategory.isLValue() && T2->isFunctionType()))) { 4514 ICS.setStandard(); 4515 ICS.Standard.First = ICK_Identity; 4516 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4517 : ObjCConversion? ICK_Compatible_Conversion 4518 : ICK_Identity; 4519 ICS.Standard.Third = ICK_Identity; 4520 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4521 ICS.Standard.setToType(0, T2); 4522 ICS.Standard.setToType(1, T1); 4523 ICS.Standard.setToType(2, T1); 4524 ICS.Standard.ReferenceBinding = true; 4525 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4526 // binding unless we're binding to a class prvalue. 4527 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4528 // allow the use of rvalue references in C++98/03 for the benefit of 4529 // standard library implementors; therefore, we need the xvalue check here. 4530 ICS.Standard.DirectBinding = 4531 S.getLangOpts().CPlusPlus11 || 4532 !(InitCategory.isPRValue() || T2->isRecordType()); 4533 ICS.Standard.IsLvalueReference = !isRValRef; 4534 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4535 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4536 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4537 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4538 ICS.Standard.CopyConstructor = nullptr; 4539 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4540 return ICS; 4541 } 4542 4543 // -- has a class type (i.e., T2 is a class type), where T1 is not 4544 // reference-related to T2, and can be implicitly converted to 4545 // an xvalue, class prvalue, or function lvalue of type 4546 // "cv3 T3", where "cv1 T1" is reference-compatible with 4547 // "cv3 T3", 4548 // 4549 // then the reference is bound to the value of the initializer 4550 // expression in the first case and to the result of the conversion 4551 // in the second case (or, in either case, to an appropriate base 4552 // class subobject). 4553 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4554 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4555 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4556 Init, T2, /*AllowRvalues=*/true, 4557 AllowExplicit)) { 4558 // In the second case, if the reference is an rvalue reference 4559 // and the second standard conversion sequence of the 4560 // user-defined conversion sequence includes an lvalue-to-rvalue 4561 // conversion, the program is ill-formed. 4562 if (ICS.isUserDefined() && isRValRef && 4563 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4564 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4565 4566 return ICS; 4567 } 4568 4569 // A temporary of function type cannot be created; don't even try. 4570 if (T1->isFunctionType()) 4571 return ICS; 4572 4573 // -- Otherwise, a temporary of type "cv1 T1" is created and 4574 // initialized from the initializer expression using the 4575 // rules for a non-reference copy initialization (8.5). The 4576 // reference is then bound to the temporary. If T1 is 4577 // reference-related to T2, cv1 must be the same 4578 // cv-qualification as, or greater cv-qualification than, 4579 // cv2; otherwise, the program is ill-formed. 4580 if (RefRelationship == Sema::Ref_Related) { 4581 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4582 // we would be reference-compatible or reference-compatible with 4583 // added qualification. But that wasn't the case, so the reference 4584 // initialization fails. 4585 // 4586 // Note that we only want to check address spaces and cvr-qualifiers here. 4587 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4588 Qualifiers T1Quals = T1.getQualifiers(); 4589 Qualifiers T2Quals = T2.getQualifiers(); 4590 T1Quals.removeObjCGCAttr(); 4591 T1Quals.removeObjCLifetime(); 4592 T2Quals.removeObjCGCAttr(); 4593 T2Quals.removeObjCLifetime(); 4594 // MS compiler ignores __unaligned qualifier for references; do the same. 4595 T1Quals.removeUnaligned(); 4596 T2Quals.removeUnaligned(); 4597 if (!T1Quals.compatiblyIncludes(T2Quals)) 4598 return ICS; 4599 } 4600 4601 // If at least one of the types is a class type, the types are not 4602 // related, and we aren't allowed any user conversions, the 4603 // reference binding fails. This case is important for breaking 4604 // recursion, since TryImplicitConversion below will attempt to 4605 // create a temporary through the use of a copy constructor. 4606 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4607 (T1->isRecordType() || T2->isRecordType())) 4608 return ICS; 4609 4610 // If T1 is reference-related to T2 and the reference is an rvalue 4611 // reference, the initializer expression shall not be an lvalue. 4612 if (RefRelationship >= Sema::Ref_Related && 4613 isRValRef && Init->Classify(S.Context).isLValue()) 4614 return ICS; 4615 4616 // C++ [over.ics.ref]p2: 4617 // When a parameter of reference type is not bound directly to 4618 // an argument expression, the conversion sequence is the one 4619 // required to convert the argument expression to the 4620 // underlying type of the reference according to 4621 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4622 // to copy-initializing a temporary of the underlying type with 4623 // the argument expression. Any difference in top-level 4624 // cv-qualification is subsumed by the initialization itself 4625 // and does not constitute a conversion. 4626 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4627 /*AllowExplicit=*/false, 4628 /*InOverloadResolution=*/false, 4629 /*CStyle=*/false, 4630 /*AllowObjCWritebackConversion=*/false, 4631 /*AllowObjCConversionOnExplicit=*/false); 4632 4633 // Of course, that's still a reference binding. 4634 if (ICS.isStandard()) { 4635 ICS.Standard.ReferenceBinding = true; 4636 ICS.Standard.IsLvalueReference = !isRValRef; 4637 ICS.Standard.BindsToFunctionLvalue = false; 4638 ICS.Standard.BindsToRvalue = true; 4639 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4640 ICS.Standard.ObjCLifetimeConversionBinding = false; 4641 } else if (ICS.isUserDefined()) { 4642 const ReferenceType *LValRefType = 4643 ICS.UserDefined.ConversionFunction->getReturnType() 4644 ->getAs<LValueReferenceType>(); 4645 4646 // C++ [over.ics.ref]p3: 4647 // Except for an implicit object parameter, for which see 13.3.1, a 4648 // standard conversion sequence cannot be formed if it requires [...] 4649 // binding an rvalue reference to an lvalue other than a function 4650 // lvalue. 4651 // Note that the function case is not possible here. 4652 if (DeclType->isRValueReferenceType() && LValRefType) { 4653 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4654 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4655 // reference to an rvalue! 4656 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4657 return ICS; 4658 } 4659 4660 ICS.UserDefined.After.ReferenceBinding = true; 4661 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4662 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4663 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4664 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4665 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4666 } 4667 4668 return ICS; 4669 } 4670 4671 static ImplicitConversionSequence 4672 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4673 bool SuppressUserConversions, 4674 bool InOverloadResolution, 4675 bool AllowObjCWritebackConversion, 4676 bool AllowExplicit = false); 4677 4678 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4679 /// initializer list From. 4680 static ImplicitConversionSequence 4681 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4682 bool SuppressUserConversions, 4683 bool InOverloadResolution, 4684 bool AllowObjCWritebackConversion) { 4685 // C++11 [over.ics.list]p1: 4686 // When an argument is an initializer list, it is not an expression and 4687 // special rules apply for converting it to a parameter type. 4688 4689 ImplicitConversionSequence Result; 4690 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4691 4692 // We need a complete type for what follows. Incomplete types can never be 4693 // initialized from init lists. 4694 if (!S.isCompleteType(From->getLocStart(), ToType)) 4695 return Result; 4696 4697 // Per DR1467: 4698 // If the parameter type is a class X and the initializer list has a single 4699 // element of type cv U, where U is X or a class derived from X, the 4700 // implicit conversion sequence is the one required to convert the element 4701 // to the parameter type. 4702 // 4703 // Otherwise, if the parameter type is a character array [... ] 4704 // and the initializer list has a single element that is an 4705 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4706 // implicit conversion sequence is the identity conversion. 4707 if (From->getNumInits() == 1) { 4708 if (ToType->isRecordType()) { 4709 QualType InitType = From->getInit(0)->getType(); 4710 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4711 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4712 return TryCopyInitialization(S, From->getInit(0), ToType, 4713 SuppressUserConversions, 4714 InOverloadResolution, 4715 AllowObjCWritebackConversion); 4716 } 4717 // FIXME: Check the other conditions here: array of character type, 4718 // initializer is a string literal. 4719 if (ToType->isArrayType()) { 4720 InitializedEntity Entity = 4721 InitializedEntity::InitializeParameter(S.Context, ToType, 4722 /*Consumed=*/false); 4723 if (S.CanPerformCopyInitialization(Entity, From)) { 4724 Result.setStandard(); 4725 Result.Standard.setAsIdentityConversion(); 4726 Result.Standard.setFromType(ToType); 4727 Result.Standard.setAllToTypes(ToType); 4728 return Result; 4729 } 4730 } 4731 } 4732 4733 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4734 // C++11 [over.ics.list]p2: 4735 // If the parameter type is std::initializer_list<X> or "array of X" and 4736 // all the elements can be implicitly converted to X, the implicit 4737 // conversion sequence is the worst conversion necessary to convert an 4738 // element of the list to X. 4739 // 4740 // C++14 [over.ics.list]p3: 4741 // Otherwise, if the parameter type is "array of N X", if the initializer 4742 // list has exactly N elements or if it has fewer than N elements and X is 4743 // default-constructible, and if all the elements of the initializer list 4744 // can be implicitly converted to X, the implicit conversion sequence is 4745 // the worst conversion necessary to convert an element of the list to X. 4746 // 4747 // FIXME: We're missing a lot of these checks. 4748 bool toStdInitializerList = false; 4749 QualType X; 4750 if (ToType->isArrayType()) 4751 X = S.Context.getAsArrayType(ToType)->getElementType(); 4752 else 4753 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4754 if (!X.isNull()) { 4755 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4756 Expr *Init = From->getInit(i); 4757 ImplicitConversionSequence ICS = 4758 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4759 InOverloadResolution, 4760 AllowObjCWritebackConversion); 4761 // If a single element isn't convertible, fail. 4762 if (ICS.isBad()) { 4763 Result = ICS; 4764 break; 4765 } 4766 // Otherwise, look for the worst conversion. 4767 if (Result.isBad() || 4768 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4769 Result) == 4770 ImplicitConversionSequence::Worse) 4771 Result = ICS; 4772 } 4773 4774 // For an empty list, we won't have computed any conversion sequence. 4775 // Introduce the identity conversion sequence. 4776 if (From->getNumInits() == 0) { 4777 Result.setStandard(); 4778 Result.Standard.setAsIdentityConversion(); 4779 Result.Standard.setFromType(ToType); 4780 Result.Standard.setAllToTypes(ToType); 4781 } 4782 4783 Result.setStdInitializerListElement(toStdInitializerList); 4784 return Result; 4785 } 4786 4787 // C++14 [over.ics.list]p4: 4788 // C++11 [over.ics.list]p3: 4789 // Otherwise, if the parameter is a non-aggregate class X and overload 4790 // resolution chooses a single best constructor [...] the implicit 4791 // conversion sequence is a user-defined conversion sequence. If multiple 4792 // constructors are viable but none is better than the others, the 4793 // implicit conversion sequence is a user-defined conversion sequence. 4794 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4795 // This function can deal with initializer lists. 4796 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4797 /*AllowExplicit=*/false, 4798 InOverloadResolution, /*CStyle=*/false, 4799 AllowObjCWritebackConversion, 4800 /*AllowObjCConversionOnExplicit=*/false); 4801 } 4802 4803 // C++14 [over.ics.list]p5: 4804 // C++11 [over.ics.list]p4: 4805 // Otherwise, if the parameter has an aggregate type which can be 4806 // initialized from the initializer list [...] the implicit conversion 4807 // sequence is a user-defined conversion sequence. 4808 if (ToType->isAggregateType()) { 4809 // Type is an aggregate, argument is an init list. At this point it comes 4810 // down to checking whether the initialization works. 4811 // FIXME: Find out whether this parameter is consumed or not. 4812 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4813 // need to call into the initialization code here; overload resolution 4814 // should not be doing that. 4815 InitializedEntity Entity = 4816 InitializedEntity::InitializeParameter(S.Context, ToType, 4817 /*Consumed=*/false); 4818 if (S.CanPerformCopyInitialization(Entity, From)) { 4819 Result.setUserDefined(); 4820 Result.UserDefined.Before.setAsIdentityConversion(); 4821 // Initializer lists don't have a type. 4822 Result.UserDefined.Before.setFromType(QualType()); 4823 Result.UserDefined.Before.setAllToTypes(QualType()); 4824 4825 Result.UserDefined.After.setAsIdentityConversion(); 4826 Result.UserDefined.After.setFromType(ToType); 4827 Result.UserDefined.After.setAllToTypes(ToType); 4828 Result.UserDefined.ConversionFunction = nullptr; 4829 } 4830 return Result; 4831 } 4832 4833 // C++14 [over.ics.list]p6: 4834 // C++11 [over.ics.list]p5: 4835 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4836 if (ToType->isReferenceType()) { 4837 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4838 // mention initializer lists in any way. So we go by what list- 4839 // initialization would do and try to extrapolate from that. 4840 4841 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4842 4843 // If the initializer list has a single element that is reference-related 4844 // to the parameter type, we initialize the reference from that. 4845 if (From->getNumInits() == 1) { 4846 Expr *Init = From->getInit(0); 4847 4848 QualType T2 = Init->getType(); 4849 4850 // If the initializer is the address of an overloaded function, try 4851 // to resolve the overloaded function. If all goes well, T2 is the 4852 // type of the resulting function. 4853 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4854 DeclAccessPair Found; 4855 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4856 Init, ToType, false, Found)) 4857 T2 = Fn->getType(); 4858 } 4859 4860 // Compute some basic properties of the types and the initializer. 4861 bool dummy1 = false; 4862 bool dummy2 = false; 4863 bool dummy3 = false; 4864 Sema::ReferenceCompareResult RefRelationship 4865 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4866 dummy2, dummy3); 4867 4868 if (RefRelationship >= Sema::Ref_Related) { 4869 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4870 SuppressUserConversions, 4871 /*AllowExplicit=*/false); 4872 } 4873 } 4874 4875 // Otherwise, we bind the reference to a temporary created from the 4876 // initializer list. 4877 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4878 InOverloadResolution, 4879 AllowObjCWritebackConversion); 4880 if (Result.isFailure()) 4881 return Result; 4882 assert(!Result.isEllipsis() && 4883 "Sub-initialization cannot result in ellipsis conversion."); 4884 4885 // Can we even bind to a temporary? 4886 if (ToType->isRValueReferenceType() || 4887 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4888 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4889 Result.UserDefined.After; 4890 SCS.ReferenceBinding = true; 4891 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4892 SCS.BindsToRvalue = true; 4893 SCS.BindsToFunctionLvalue = false; 4894 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4895 SCS.ObjCLifetimeConversionBinding = false; 4896 } else 4897 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4898 From, ToType); 4899 return Result; 4900 } 4901 4902 // C++14 [over.ics.list]p7: 4903 // C++11 [over.ics.list]p6: 4904 // Otherwise, if the parameter type is not a class: 4905 if (!ToType->isRecordType()) { 4906 // - if the initializer list has one element that is not itself an 4907 // initializer list, the implicit conversion sequence is the one 4908 // required to convert the element to the parameter type. 4909 unsigned NumInits = From->getNumInits(); 4910 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4911 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4912 SuppressUserConversions, 4913 InOverloadResolution, 4914 AllowObjCWritebackConversion); 4915 // - if the initializer list has no elements, the implicit conversion 4916 // sequence is the identity conversion. 4917 else if (NumInits == 0) { 4918 Result.setStandard(); 4919 Result.Standard.setAsIdentityConversion(); 4920 Result.Standard.setFromType(ToType); 4921 Result.Standard.setAllToTypes(ToType); 4922 } 4923 return Result; 4924 } 4925 4926 // C++14 [over.ics.list]p8: 4927 // C++11 [over.ics.list]p7: 4928 // In all cases other than those enumerated above, no conversion is possible 4929 return Result; 4930 } 4931 4932 /// TryCopyInitialization - Try to copy-initialize a value of type 4933 /// ToType from the expression From. Return the implicit conversion 4934 /// sequence required to pass this argument, which may be a bad 4935 /// conversion sequence (meaning that the argument cannot be passed to 4936 /// a parameter of this type). If @p SuppressUserConversions, then we 4937 /// do not permit any user-defined conversion sequences. 4938 static ImplicitConversionSequence 4939 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4940 bool SuppressUserConversions, 4941 bool InOverloadResolution, 4942 bool AllowObjCWritebackConversion, 4943 bool AllowExplicit) { 4944 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4945 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4946 InOverloadResolution,AllowObjCWritebackConversion); 4947 4948 if (ToType->isReferenceType()) 4949 return TryReferenceInit(S, From, ToType, 4950 /*FIXME:*/From->getLocStart(), 4951 SuppressUserConversions, 4952 AllowExplicit); 4953 4954 return TryImplicitConversion(S, From, ToType, 4955 SuppressUserConversions, 4956 /*AllowExplicit=*/false, 4957 InOverloadResolution, 4958 /*CStyle=*/false, 4959 AllowObjCWritebackConversion, 4960 /*AllowObjCConversionOnExplicit=*/false); 4961 } 4962 4963 static bool TryCopyInitialization(const CanQualType FromQTy, 4964 const CanQualType ToQTy, 4965 Sema &S, 4966 SourceLocation Loc, 4967 ExprValueKind FromVK) { 4968 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4969 ImplicitConversionSequence ICS = 4970 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4971 4972 return !ICS.isBad(); 4973 } 4974 4975 /// TryObjectArgumentInitialization - Try to initialize the object 4976 /// parameter of the given member function (@c Method) from the 4977 /// expression @p From. 4978 static ImplicitConversionSequence 4979 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4980 Expr::Classification FromClassification, 4981 CXXMethodDecl *Method, 4982 CXXRecordDecl *ActingContext) { 4983 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4984 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4985 // const volatile object. 4986 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4987 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4988 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4989 4990 // Set up the conversion sequence as a "bad" conversion, to allow us 4991 // to exit early. 4992 ImplicitConversionSequence ICS; 4993 4994 // We need to have an object of class type. 4995 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4996 FromType = PT->getPointeeType(); 4997 4998 // When we had a pointer, it's implicitly dereferenced, so we 4999 // better have an lvalue. 5000 assert(FromClassification.isLValue()); 5001 } 5002 5003 assert(FromType->isRecordType()); 5004 5005 // C++0x [over.match.funcs]p4: 5006 // For non-static member functions, the type of the implicit object 5007 // parameter is 5008 // 5009 // - "lvalue reference to cv X" for functions declared without a 5010 // ref-qualifier or with the & ref-qualifier 5011 // - "rvalue reference to cv X" for functions declared with the && 5012 // ref-qualifier 5013 // 5014 // where X is the class of which the function is a member and cv is the 5015 // cv-qualification on the member function declaration. 5016 // 5017 // However, when finding an implicit conversion sequence for the argument, we 5018 // are not allowed to perform user-defined conversions 5019 // (C++ [over.match.funcs]p5). We perform a simplified version of 5020 // reference binding here, that allows class rvalues to bind to 5021 // non-constant references. 5022 5023 // First check the qualifiers. 5024 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5025 if (ImplicitParamType.getCVRQualifiers() 5026 != FromTypeCanon.getLocalCVRQualifiers() && 5027 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5028 ICS.setBad(BadConversionSequence::bad_qualifiers, 5029 FromType, ImplicitParamType); 5030 return ICS; 5031 } 5032 5033 // Check that we have either the same type or a derived type. It 5034 // affects the conversion rank. 5035 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5036 ImplicitConversionKind SecondKind; 5037 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5038 SecondKind = ICK_Identity; 5039 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5040 SecondKind = ICK_Derived_To_Base; 5041 else { 5042 ICS.setBad(BadConversionSequence::unrelated_class, 5043 FromType, ImplicitParamType); 5044 return ICS; 5045 } 5046 5047 // Check the ref-qualifier. 5048 switch (Method->getRefQualifier()) { 5049 case RQ_None: 5050 // Do nothing; we don't care about lvalueness or rvalueness. 5051 break; 5052 5053 case RQ_LValue: 5054 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 5055 // non-const lvalue reference cannot bind to an rvalue 5056 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5057 ImplicitParamType); 5058 return ICS; 5059 } 5060 break; 5061 5062 case RQ_RValue: 5063 if (!FromClassification.isRValue()) { 5064 // rvalue reference cannot bind to an lvalue 5065 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5066 ImplicitParamType); 5067 return ICS; 5068 } 5069 break; 5070 } 5071 5072 // Success. Mark this as a reference binding. 5073 ICS.setStandard(); 5074 ICS.Standard.setAsIdentityConversion(); 5075 ICS.Standard.Second = SecondKind; 5076 ICS.Standard.setFromType(FromType); 5077 ICS.Standard.setAllToTypes(ImplicitParamType); 5078 ICS.Standard.ReferenceBinding = true; 5079 ICS.Standard.DirectBinding = true; 5080 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5081 ICS.Standard.BindsToFunctionLvalue = false; 5082 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5083 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5084 = (Method->getRefQualifier() == RQ_None); 5085 return ICS; 5086 } 5087 5088 /// PerformObjectArgumentInitialization - Perform initialization of 5089 /// the implicit object parameter for the given Method with the given 5090 /// expression. 5091 ExprResult 5092 Sema::PerformObjectArgumentInitialization(Expr *From, 5093 NestedNameSpecifier *Qualifier, 5094 NamedDecl *FoundDecl, 5095 CXXMethodDecl *Method) { 5096 QualType FromRecordType, DestType; 5097 QualType ImplicitParamRecordType = 5098 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5099 5100 Expr::Classification FromClassification; 5101 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5102 FromRecordType = PT->getPointeeType(); 5103 DestType = Method->getThisType(Context); 5104 FromClassification = Expr::Classification::makeSimpleLValue(); 5105 } else { 5106 FromRecordType = From->getType(); 5107 DestType = ImplicitParamRecordType; 5108 FromClassification = From->Classify(Context); 5109 } 5110 5111 // Note that we always use the true parent context when performing 5112 // the actual argument initialization. 5113 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5114 *this, From->getLocStart(), From->getType(), FromClassification, Method, 5115 Method->getParent()); 5116 if (ICS.isBad()) { 5117 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 5118 Qualifiers FromQs = FromRecordType.getQualifiers(); 5119 Qualifiers ToQs = DestType.getQualifiers(); 5120 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5121 if (CVR) { 5122 Diag(From->getLocStart(), 5123 diag::err_member_function_call_bad_cvr) 5124 << Method->getDeclName() << FromRecordType << (CVR - 1) 5125 << From->getSourceRange(); 5126 Diag(Method->getLocation(), diag::note_previous_decl) 5127 << Method->getDeclName(); 5128 return ExprError(); 5129 } 5130 } 5131 5132 return Diag(From->getLocStart(), 5133 diag::err_implicit_object_parameter_init) 5134 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5135 } 5136 5137 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5138 ExprResult FromRes = 5139 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5140 if (FromRes.isInvalid()) 5141 return ExprError(); 5142 From = FromRes.get(); 5143 } 5144 5145 if (!Context.hasSameType(From->getType(), DestType)) 5146 From = ImpCastExprToType(From, DestType, CK_NoOp, 5147 From->getValueKind()).get(); 5148 return From; 5149 } 5150 5151 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5152 /// expression From to bool (C++0x [conv]p3). 5153 static ImplicitConversionSequence 5154 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5155 return TryImplicitConversion(S, From, S.Context.BoolTy, 5156 /*SuppressUserConversions=*/false, 5157 /*AllowExplicit=*/true, 5158 /*InOverloadResolution=*/false, 5159 /*CStyle=*/false, 5160 /*AllowObjCWritebackConversion=*/false, 5161 /*AllowObjCConversionOnExplicit=*/false); 5162 } 5163 5164 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5165 /// of the expression From to bool (C++0x [conv]p3). 5166 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5167 if (checkPlaceholderForOverload(*this, From)) 5168 return ExprError(); 5169 5170 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5171 if (!ICS.isBad()) 5172 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5173 5174 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5175 return Diag(From->getLocStart(), 5176 diag::err_typecheck_bool_condition) 5177 << From->getType() << From->getSourceRange(); 5178 return ExprError(); 5179 } 5180 5181 /// Check that the specified conversion is permitted in a converted constant 5182 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5183 /// is acceptable. 5184 static bool CheckConvertedConstantConversions(Sema &S, 5185 StandardConversionSequence &SCS) { 5186 // Since we know that the target type is an integral or unscoped enumeration 5187 // type, most conversion kinds are impossible. All possible First and Third 5188 // conversions are fine. 5189 switch (SCS.Second) { 5190 case ICK_Identity: 5191 case ICK_Function_Conversion: 5192 case ICK_Integral_Promotion: 5193 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5194 case ICK_Zero_Queue_Conversion: 5195 return true; 5196 5197 case ICK_Boolean_Conversion: 5198 // Conversion from an integral or unscoped enumeration type to bool is 5199 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5200 // conversion, so we allow it in a converted constant expression. 5201 // 5202 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5203 // a lot of popular code. We should at least add a warning for this 5204 // (non-conforming) extension. 5205 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5206 SCS.getToType(2)->isBooleanType(); 5207 5208 case ICK_Pointer_Conversion: 5209 case ICK_Pointer_Member: 5210 // C++1z: null pointer conversions and null member pointer conversions are 5211 // only permitted if the source type is std::nullptr_t. 5212 return SCS.getFromType()->isNullPtrType(); 5213 5214 case ICK_Floating_Promotion: 5215 case ICK_Complex_Promotion: 5216 case ICK_Floating_Conversion: 5217 case ICK_Complex_Conversion: 5218 case ICK_Floating_Integral: 5219 case ICK_Compatible_Conversion: 5220 case ICK_Derived_To_Base: 5221 case ICK_Vector_Conversion: 5222 case ICK_Vector_Splat: 5223 case ICK_Complex_Real: 5224 case ICK_Block_Pointer_Conversion: 5225 case ICK_TransparentUnionConversion: 5226 case ICK_Writeback_Conversion: 5227 case ICK_Zero_Event_Conversion: 5228 case ICK_C_Only_Conversion: 5229 case ICK_Incompatible_Pointer_Conversion: 5230 return false; 5231 5232 case ICK_Lvalue_To_Rvalue: 5233 case ICK_Array_To_Pointer: 5234 case ICK_Function_To_Pointer: 5235 llvm_unreachable("found a first conversion kind in Second"); 5236 5237 case ICK_Qualification: 5238 llvm_unreachable("found a third conversion kind in Second"); 5239 5240 case ICK_Num_Conversion_Kinds: 5241 break; 5242 } 5243 5244 llvm_unreachable("unknown conversion kind"); 5245 } 5246 5247 /// CheckConvertedConstantExpression - Check that the expression From is a 5248 /// converted constant expression of type T, perform the conversion and produce 5249 /// the converted expression, per C++11 [expr.const]p3. 5250 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5251 QualType T, APValue &Value, 5252 Sema::CCEKind CCE, 5253 bool RequireInt) { 5254 assert(S.getLangOpts().CPlusPlus11 && 5255 "converted constant expression outside C++11"); 5256 5257 if (checkPlaceholderForOverload(S, From)) 5258 return ExprError(); 5259 5260 // C++1z [expr.const]p3: 5261 // A converted constant expression of type T is an expression, 5262 // implicitly converted to type T, where the converted 5263 // expression is a constant expression and the implicit conversion 5264 // sequence contains only [... list of conversions ...]. 5265 // C++1z [stmt.if]p2: 5266 // If the if statement is of the form if constexpr, the value of the 5267 // condition shall be a contextually converted constant expression of type 5268 // bool. 5269 ImplicitConversionSequence ICS = 5270 CCE == Sema::CCEK_ConstexprIf 5271 ? TryContextuallyConvertToBool(S, From) 5272 : TryCopyInitialization(S, From, T, 5273 /*SuppressUserConversions=*/false, 5274 /*InOverloadResolution=*/false, 5275 /*AllowObjcWritebackConversion=*/false, 5276 /*AllowExplicit=*/false); 5277 StandardConversionSequence *SCS = nullptr; 5278 switch (ICS.getKind()) { 5279 case ImplicitConversionSequence::StandardConversion: 5280 SCS = &ICS.Standard; 5281 break; 5282 case ImplicitConversionSequence::UserDefinedConversion: 5283 // We are converting to a non-class type, so the Before sequence 5284 // must be trivial. 5285 SCS = &ICS.UserDefined.After; 5286 break; 5287 case ImplicitConversionSequence::AmbiguousConversion: 5288 case ImplicitConversionSequence::BadConversion: 5289 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5290 return S.Diag(From->getLocStart(), 5291 diag::err_typecheck_converted_constant_expression) 5292 << From->getType() << From->getSourceRange() << T; 5293 return ExprError(); 5294 5295 case ImplicitConversionSequence::EllipsisConversion: 5296 llvm_unreachable("ellipsis conversion in converted constant expression"); 5297 } 5298 5299 // Check that we would only use permitted conversions. 5300 if (!CheckConvertedConstantConversions(S, *SCS)) { 5301 return S.Diag(From->getLocStart(), 5302 diag::err_typecheck_converted_constant_expression_disallowed) 5303 << From->getType() << From->getSourceRange() << T; 5304 } 5305 // [...] and where the reference binding (if any) binds directly. 5306 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5307 return S.Diag(From->getLocStart(), 5308 diag::err_typecheck_converted_constant_expression_indirect) 5309 << From->getType() << From->getSourceRange() << T; 5310 } 5311 5312 ExprResult Result = 5313 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5314 if (Result.isInvalid()) 5315 return Result; 5316 5317 // Check for a narrowing implicit conversion. 5318 APValue PreNarrowingValue; 5319 QualType PreNarrowingType; 5320 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5321 PreNarrowingType)) { 5322 case NK_Dependent_Narrowing: 5323 // Implicit conversion to a narrower type, but the expression is 5324 // value-dependent so we can't tell whether it's actually narrowing. 5325 case NK_Variable_Narrowing: 5326 // Implicit conversion to a narrower type, and the value is not a constant 5327 // expression. We'll diagnose this in a moment. 5328 case NK_Not_Narrowing: 5329 break; 5330 5331 case NK_Constant_Narrowing: 5332 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5333 << CCE << /*Constant*/1 5334 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5335 break; 5336 5337 case NK_Type_Narrowing: 5338 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5339 << CCE << /*Constant*/0 << From->getType() << T; 5340 break; 5341 } 5342 5343 if (Result.get()->isValueDependent()) { 5344 Value = APValue(); 5345 return Result; 5346 } 5347 5348 // Check the expression is a constant expression. 5349 SmallVector<PartialDiagnosticAt, 8> Notes; 5350 Expr::EvalResult Eval; 5351 Eval.Diag = &Notes; 5352 5353 if ((T->isReferenceType() 5354 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5355 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5356 (RequireInt && !Eval.Val.isInt())) { 5357 // The expression can't be folded, so we can't keep it at this position in 5358 // the AST. 5359 Result = ExprError(); 5360 } else { 5361 Value = Eval.Val; 5362 5363 if (Notes.empty()) { 5364 // It's a constant expression. 5365 return Result; 5366 } 5367 } 5368 5369 // It's not a constant expression. Produce an appropriate diagnostic. 5370 if (Notes.size() == 1 && 5371 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5372 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5373 else { 5374 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5375 << CCE << From->getSourceRange(); 5376 for (unsigned I = 0; I < Notes.size(); ++I) 5377 S.Diag(Notes[I].first, Notes[I].second); 5378 } 5379 return ExprError(); 5380 } 5381 5382 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5383 APValue &Value, CCEKind CCE) { 5384 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5385 } 5386 5387 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5388 llvm::APSInt &Value, 5389 CCEKind CCE) { 5390 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5391 5392 APValue V; 5393 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5394 if (!R.isInvalid() && !R.get()->isValueDependent()) 5395 Value = V.getInt(); 5396 return R; 5397 } 5398 5399 5400 /// dropPointerConversions - If the given standard conversion sequence 5401 /// involves any pointer conversions, remove them. This may change 5402 /// the result type of the conversion sequence. 5403 static void dropPointerConversion(StandardConversionSequence &SCS) { 5404 if (SCS.Second == ICK_Pointer_Conversion) { 5405 SCS.Second = ICK_Identity; 5406 SCS.Third = ICK_Identity; 5407 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5408 } 5409 } 5410 5411 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5412 /// convert the expression From to an Objective-C pointer type. 5413 static ImplicitConversionSequence 5414 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5415 // Do an implicit conversion to 'id'. 5416 QualType Ty = S.Context.getObjCIdType(); 5417 ImplicitConversionSequence ICS 5418 = TryImplicitConversion(S, From, Ty, 5419 // FIXME: Are these flags correct? 5420 /*SuppressUserConversions=*/false, 5421 /*AllowExplicit=*/true, 5422 /*InOverloadResolution=*/false, 5423 /*CStyle=*/false, 5424 /*AllowObjCWritebackConversion=*/false, 5425 /*AllowObjCConversionOnExplicit=*/true); 5426 5427 // Strip off any final conversions to 'id'. 5428 switch (ICS.getKind()) { 5429 case ImplicitConversionSequence::BadConversion: 5430 case ImplicitConversionSequence::AmbiguousConversion: 5431 case ImplicitConversionSequence::EllipsisConversion: 5432 break; 5433 5434 case ImplicitConversionSequence::UserDefinedConversion: 5435 dropPointerConversion(ICS.UserDefined.After); 5436 break; 5437 5438 case ImplicitConversionSequence::StandardConversion: 5439 dropPointerConversion(ICS.Standard); 5440 break; 5441 } 5442 5443 return ICS; 5444 } 5445 5446 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5447 /// conversion of the expression From to an Objective-C pointer type. 5448 /// Returns a valid but null ExprResult if no conversion sequence exists. 5449 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5450 if (checkPlaceholderForOverload(*this, From)) 5451 return ExprError(); 5452 5453 QualType Ty = Context.getObjCIdType(); 5454 ImplicitConversionSequence ICS = 5455 TryContextuallyConvertToObjCPointer(*this, From); 5456 if (!ICS.isBad()) 5457 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5458 return ExprResult(); 5459 } 5460 5461 /// Determine whether the provided type is an integral type, or an enumeration 5462 /// type of a permitted flavor. 5463 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5464 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5465 : T->isIntegralOrUnscopedEnumerationType(); 5466 } 5467 5468 static ExprResult 5469 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5470 Sema::ContextualImplicitConverter &Converter, 5471 QualType T, UnresolvedSetImpl &ViableConversions) { 5472 5473 if (Converter.Suppress) 5474 return ExprError(); 5475 5476 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5477 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5478 CXXConversionDecl *Conv = 5479 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5480 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5481 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5482 } 5483 return From; 5484 } 5485 5486 static bool 5487 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5488 Sema::ContextualImplicitConverter &Converter, 5489 QualType T, bool HadMultipleCandidates, 5490 UnresolvedSetImpl &ExplicitConversions) { 5491 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5492 DeclAccessPair Found = ExplicitConversions[0]; 5493 CXXConversionDecl *Conversion = 5494 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5495 5496 // The user probably meant to invoke the given explicit 5497 // conversion; use it. 5498 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5499 std::string TypeStr; 5500 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5501 5502 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5503 << FixItHint::CreateInsertion(From->getLocStart(), 5504 "static_cast<" + TypeStr + ">(") 5505 << FixItHint::CreateInsertion( 5506 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5507 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5508 5509 // If we aren't in a SFINAE context, build a call to the 5510 // explicit conversion function. 5511 if (SemaRef.isSFINAEContext()) 5512 return true; 5513 5514 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5515 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5516 HadMultipleCandidates); 5517 if (Result.isInvalid()) 5518 return true; 5519 // Record usage of conversion in an implicit cast. 5520 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5521 CK_UserDefinedConversion, Result.get(), 5522 nullptr, Result.get()->getValueKind()); 5523 } 5524 return false; 5525 } 5526 5527 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5528 Sema::ContextualImplicitConverter &Converter, 5529 QualType T, bool HadMultipleCandidates, 5530 DeclAccessPair &Found) { 5531 CXXConversionDecl *Conversion = 5532 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5533 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5534 5535 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5536 if (!Converter.SuppressConversion) { 5537 if (SemaRef.isSFINAEContext()) 5538 return true; 5539 5540 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5541 << From->getSourceRange(); 5542 } 5543 5544 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5545 HadMultipleCandidates); 5546 if (Result.isInvalid()) 5547 return true; 5548 // Record usage of conversion in an implicit cast. 5549 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5550 CK_UserDefinedConversion, Result.get(), 5551 nullptr, Result.get()->getValueKind()); 5552 return false; 5553 } 5554 5555 static ExprResult finishContextualImplicitConversion( 5556 Sema &SemaRef, SourceLocation Loc, Expr *From, 5557 Sema::ContextualImplicitConverter &Converter) { 5558 if (!Converter.match(From->getType()) && !Converter.Suppress) 5559 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5560 << From->getSourceRange(); 5561 5562 return SemaRef.DefaultLvalueConversion(From); 5563 } 5564 5565 static void 5566 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5567 UnresolvedSetImpl &ViableConversions, 5568 OverloadCandidateSet &CandidateSet) { 5569 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5570 DeclAccessPair FoundDecl = ViableConversions[I]; 5571 NamedDecl *D = FoundDecl.getDecl(); 5572 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5573 if (isa<UsingShadowDecl>(D)) 5574 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5575 5576 CXXConversionDecl *Conv; 5577 FunctionTemplateDecl *ConvTemplate; 5578 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5579 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5580 else 5581 Conv = cast<CXXConversionDecl>(D); 5582 5583 if (ConvTemplate) 5584 SemaRef.AddTemplateConversionCandidate( 5585 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5586 /*AllowObjCConversionOnExplicit=*/false); 5587 else 5588 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5589 ToType, CandidateSet, 5590 /*AllowObjCConversionOnExplicit=*/false); 5591 } 5592 } 5593 5594 /// \brief Attempt to convert the given expression to a type which is accepted 5595 /// by the given converter. 5596 /// 5597 /// This routine will attempt to convert an expression of class type to a 5598 /// type accepted by the specified converter. In C++11 and before, the class 5599 /// must have a single non-explicit conversion function converting to a matching 5600 /// type. In C++1y, there can be multiple such conversion functions, but only 5601 /// one target type. 5602 /// 5603 /// \param Loc The source location of the construct that requires the 5604 /// conversion. 5605 /// 5606 /// \param From The expression we're converting from. 5607 /// 5608 /// \param Converter Used to control and diagnose the conversion process. 5609 /// 5610 /// \returns The expression, converted to an integral or enumeration type if 5611 /// successful. 5612 ExprResult Sema::PerformContextualImplicitConversion( 5613 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5614 // We can't perform any more checking for type-dependent expressions. 5615 if (From->isTypeDependent()) 5616 return From; 5617 5618 // Process placeholders immediately. 5619 if (From->hasPlaceholderType()) { 5620 ExprResult result = CheckPlaceholderExpr(From); 5621 if (result.isInvalid()) 5622 return result; 5623 From = result.get(); 5624 } 5625 5626 // If the expression already has a matching type, we're golden. 5627 QualType T = From->getType(); 5628 if (Converter.match(T)) 5629 return DefaultLvalueConversion(From); 5630 5631 // FIXME: Check for missing '()' if T is a function type? 5632 5633 // We can only perform contextual implicit conversions on objects of class 5634 // type. 5635 const RecordType *RecordTy = T->getAs<RecordType>(); 5636 if (!RecordTy || !getLangOpts().CPlusPlus) { 5637 if (!Converter.Suppress) 5638 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5639 return From; 5640 } 5641 5642 // We must have a complete class type. 5643 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5644 ContextualImplicitConverter &Converter; 5645 Expr *From; 5646 5647 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5648 : Converter(Converter), From(From) {} 5649 5650 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5651 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5652 } 5653 } IncompleteDiagnoser(Converter, From); 5654 5655 if (Converter.Suppress ? !isCompleteType(Loc, T) 5656 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5657 return From; 5658 5659 // Look for a conversion to an integral or enumeration type. 5660 UnresolvedSet<4> 5661 ViableConversions; // These are *potentially* viable in C++1y. 5662 UnresolvedSet<4> ExplicitConversions; 5663 const auto &Conversions = 5664 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5665 5666 bool HadMultipleCandidates = 5667 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5668 5669 // To check that there is only one target type, in C++1y: 5670 QualType ToType; 5671 bool HasUniqueTargetType = true; 5672 5673 // Collect explicit or viable (potentially in C++1y) conversions. 5674 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5675 NamedDecl *D = (*I)->getUnderlyingDecl(); 5676 CXXConversionDecl *Conversion; 5677 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5678 if (ConvTemplate) { 5679 if (getLangOpts().CPlusPlus14) 5680 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5681 else 5682 continue; // C++11 does not consider conversion operator templates(?). 5683 } else 5684 Conversion = cast<CXXConversionDecl>(D); 5685 5686 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5687 "Conversion operator templates are considered potentially " 5688 "viable in C++1y"); 5689 5690 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5691 if (Converter.match(CurToType) || ConvTemplate) { 5692 5693 if (Conversion->isExplicit()) { 5694 // FIXME: For C++1y, do we need this restriction? 5695 // cf. diagnoseNoViableConversion() 5696 if (!ConvTemplate) 5697 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5698 } else { 5699 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5700 if (ToType.isNull()) 5701 ToType = CurToType.getUnqualifiedType(); 5702 else if (HasUniqueTargetType && 5703 (CurToType.getUnqualifiedType() != ToType)) 5704 HasUniqueTargetType = false; 5705 } 5706 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5707 } 5708 } 5709 } 5710 5711 if (getLangOpts().CPlusPlus14) { 5712 // C++1y [conv]p6: 5713 // ... An expression e of class type E appearing in such a context 5714 // is said to be contextually implicitly converted to a specified 5715 // type T and is well-formed if and only if e can be implicitly 5716 // converted to a type T that is determined as follows: E is searched 5717 // for conversion functions whose return type is cv T or reference to 5718 // cv T such that T is allowed by the context. There shall be 5719 // exactly one such T. 5720 5721 // If no unique T is found: 5722 if (ToType.isNull()) { 5723 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5724 HadMultipleCandidates, 5725 ExplicitConversions)) 5726 return ExprError(); 5727 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5728 } 5729 5730 // If more than one unique Ts are found: 5731 if (!HasUniqueTargetType) 5732 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5733 ViableConversions); 5734 5735 // If one unique T is found: 5736 // First, build a candidate set from the previously recorded 5737 // potentially viable conversions. 5738 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5739 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5740 CandidateSet); 5741 5742 // Then, perform overload resolution over the candidate set. 5743 OverloadCandidateSet::iterator Best; 5744 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5745 case OR_Success: { 5746 // Apply this conversion. 5747 DeclAccessPair Found = 5748 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5749 if (recordConversion(*this, Loc, From, Converter, T, 5750 HadMultipleCandidates, Found)) 5751 return ExprError(); 5752 break; 5753 } 5754 case OR_Ambiguous: 5755 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5756 ViableConversions); 5757 case OR_No_Viable_Function: 5758 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5759 HadMultipleCandidates, 5760 ExplicitConversions)) 5761 return ExprError(); 5762 // fall through 'OR_Deleted' case. 5763 case OR_Deleted: 5764 // We'll complain below about a non-integral condition type. 5765 break; 5766 } 5767 } else { 5768 switch (ViableConversions.size()) { 5769 case 0: { 5770 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5771 HadMultipleCandidates, 5772 ExplicitConversions)) 5773 return ExprError(); 5774 5775 // We'll complain below about a non-integral condition type. 5776 break; 5777 } 5778 case 1: { 5779 // Apply this conversion. 5780 DeclAccessPair Found = ViableConversions[0]; 5781 if (recordConversion(*this, Loc, From, Converter, T, 5782 HadMultipleCandidates, Found)) 5783 return ExprError(); 5784 break; 5785 } 5786 default: 5787 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5788 ViableConversions); 5789 } 5790 } 5791 5792 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5793 } 5794 5795 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5796 /// an acceptable non-member overloaded operator for a call whose 5797 /// arguments have types T1 (and, if non-empty, T2). This routine 5798 /// implements the check in C++ [over.match.oper]p3b2 concerning 5799 /// enumeration types. 5800 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5801 FunctionDecl *Fn, 5802 ArrayRef<Expr *> Args) { 5803 QualType T1 = Args[0]->getType(); 5804 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5805 5806 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5807 return true; 5808 5809 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5810 return true; 5811 5812 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5813 if (Proto->getNumParams() < 1) 5814 return false; 5815 5816 if (T1->isEnumeralType()) { 5817 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5818 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5819 return true; 5820 } 5821 5822 if (Proto->getNumParams() < 2) 5823 return false; 5824 5825 if (!T2.isNull() && T2->isEnumeralType()) { 5826 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5827 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5828 return true; 5829 } 5830 5831 return false; 5832 } 5833 5834 static void initDiagnoseIfComplaint(Sema &S, OverloadCandidateSet &CandidateSet, 5835 OverloadCandidate &Candidate, 5836 FunctionDecl *Function, 5837 ArrayRef<Expr *> Args, 5838 bool MissingImplicitThis = false, 5839 Expr *ExplicitThis = nullptr) { 5840 SmallVector<DiagnoseIfAttr *, 8> Results; 5841 if (DiagnoseIfAttr *DIA = S.checkArgDependentDiagnoseIf( 5842 Function, Args, Results, MissingImplicitThis, ExplicitThis)) { 5843 Results.clear(); 5844 Results.push_back(DIA); 5845 } 5846 5847 Candidate.NumTriggeredDiagnoseIfs = Results.size(); 5848 if (Results.empty()) 5849 Candidate.DiagnoseIfInfo = nullptr; 5850 else if (Results.size() == 1) 5851 Candidate.DiagnoseIfInfo = Results[0]; 5852 else 5853 Candidate.DiagnoseIfInfo = CandidateSet.addDiagnoseIfComplaints(Results); 5854 } 5855 5856 /// AddOverloadCandidate - Adds the given function to the set of 5857 /// candidate functions, using the given function call arguments. If 5858 /// @p SuppressUserConversions, then don't allow user-defined 5859 /// conversions via constructors or conversion operators. 5860 /// 5861 /// \param PartialOverloading true if we are performing "partial" overloading 5862 /// based on an incomplete set of function arguments. This feature is used by 5863 /// code completion. 5864 void 5865 Sema::AddOverloadCandidate(FunctionDecl *Function, 5866 DeclAccessPair FoundDecl, 5867 ArrayRef<Expr *> Args, 5868 OverloadCandidateSet &CandidateSet, 5869 bool SuppressUserConversions, 5870 bool PartialOverloading, 5871 bool AllowExplicit, 5872 ConversionSequenceList EarlyConversions) { 5873 const FunctionProtoType *Proto 5874 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5875 assert(Proto && "Functions without a prototype cannot be overloaded"); 5876 assert(!Function->getDescribedFunctionTemplate() && 5877 "Use AddTemplateOverloadCandidate for function templates"); 5878 5879 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5880 if (!isa<CXXConstructorDecl>(Method)) { 5881 // If we get here, it's because we're calling a member function 5882 // that is named without a member access expression (e.g., 5883 // "this->f") that was either written explicitly or created 5884 // implicitly. This can happen with a qualified call to a member 5885 // function, e.g., X::f(). We use an empty type for the implied 5886 // object argument (C++ [over.call.func]p3), and the acting context 5887 // is irrelevant. 5888 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 5889 Expr::Classification::makeSimpleLValue(), 5890 /*ThisArg=*/nullptr, Args, CandidateSet, 5891 SuppressUserConversions, PartialOverloading, 5892 EarlyConversions); 5893 return; 5894 } 5895 // We treat a constructor like a non-member function, since its object 5896 // argument doesn't participate in overload resolution. 5897 } 5898 5899 if (!CandidateSet.isNewCandidate(Function)) 5900 return; 5901 5902 // C++ [over.match.oper]p3: 5903 // if no operand has a class type, only those non-member functions in the 5904 // lookup set that have a first parameter of type T1 or "reference to 5905 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5906 // is a right operand) a second parameter of type T2 or "reference to 5907 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5908 // candidate functions. 5909 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5910 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5911 return; 5912 5913 // C++11 [class.copy]p11: [DR1402] 5914 // A defaulted move constructor that is defined as deleted is ignored by 5915 // overload resolution. 5916 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5917 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5918 Constructor->isMoveConstructor()) 5919 return; 5920 5921 // Overload resolution is always an unevaluated context. 5922 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5923 5924 // Add this candidate 5925 OverloadCandidate &Candidate = 5926 CandidateSet.addCandidate(Args.size(), EarlyConversions); 5927 Candidate.FoundDecl = FoundDecl; 5928 Candidate.Function = Function; 5929 Candidate.Viable = true; 5930 Candidate.IsSurrogate = false; 5931 Candidate.IgnoreObjectArgument = false; 5932 Candidate.ExplicitCallArguments = Args.size(); 5933 5934 if (Constructor) { 5935 // C++ [class.copy]p3: 5936 // A member function template is never instantiated to perform the copy 5937 // of a class object to an object of its class type. 5938 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5939 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5940 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5941 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5942 ClassType))) { 5943 Candidate.Viable = false; 5944 Candidate.FailureKind = ovl_fail_illegal_constructor; 5945 return; 5946 } 5947 } 5948 5949 unsigned NumParams = Proto->getNumParams(); 5950 5951 // (C++ 13.3.2p2): A candidate function having fewer than m 5952 // parameters is viable only if it has an ellipsis in its parameter 5953 // list (8.3.5). 5954 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5955 !Proto->isVariadic()) { 5956 Candidate.Viable = false; 5957 Candidate.FailureKind = ovl_fail_too_many_arguments; 5958 return; 5959 } 5960 5961 // (C++ 13.3.2p2): A candidate function having more than m parameters 5962 // is viable only if the (m+1)st parameter has a default argument 5963 // (8.3.6). For the purposes of overload resolution, the 5964 // parameter list is truncated on the right, so that there are 5965 // exactly m parameters. 5966 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5967 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5968 // Not enough arguments. 5969 Candidate.Viable = false; 5970 Candidate.FailureKind = ovl_fail_too_few_arguments; 5971 return; 5972 } 5973 5974 // (CUDA B.1): Check for invalid calls between targets. 5975 if (getLangOpts().CUDA) 5976 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5977 // Skip the check for callers that are implicit members, because in this 5978 // case we may not yet know what the member's target is; the target is 5979 // inferred for the member automatically, based on the bases and fields of 5980 // the class. 5981 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 5982 Candidate.Viable = false; 5983 Candidate.FailureKind = ovl_fail_bad_target; 5984 return; 5985 } 5986 5987 // Determine the implicit conversion sequences for each of the 5988 // arguments. 5989 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5990 if (Candidate.Conversions[ArgIdx].isInitialized()) { 5991 // We already formed a conversion sequence for this parameter during 5992 // template argument deduction. 5993 } else if (ArgIdx < NumParams) { 5994 // (C++ 13.3.2p3): for F to be a viable function, there shall 5995 // exist for each argument an implicit conversion sequence 5996 // (13.3.3.1) that converts that argument to the corresponding 5997 // parameter of F. 5998 QualType ParamType = Proto->getParamType(ArgIdx); 5999 Candidate.Conversions[ArgIdx] 6000 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6001 SuppressUserConversions, 6002 /*InOverloadResolution=*/true, 6003 /*AllowObjCWritebackConversion=*/ 6004 getLangOpts().ObjCAutoRefCount, 6005 AllowExplicit); 6006 if (Candidate.Conversions[ArgIdx].isBad()) { 6007 Candidate.Viable = false; 6008 Candidate.FailureKind = ovl_fail_bad_conversion; 6009 return; 6010 } 6011 } else { 6012 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6013 // argument for which there is no corresponding parameter is 6014 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6015 Candidate.Conversions[ArgIdx].setEllipsis(); 6016 } 6017 } 6018 6019 // C++ [over.best.ics]p4+: (proposed DR resolution) 6020 // If the target is the first parameter of an inherited constructor when 6021 // constructing an object of type C with an argument list that has exactly 6022 // one expression, an implicit conversion sequence cannot be formed if C is 6023 // reference-related to the type that the argument would have after the 6024 // application of the user-defined conversion (if any) and before the final 6025 // standard conversion sequence. 6026 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6027 if (Shadow && Args.size() == 1 && !isa<InitListExpr>(Args.front())) { 6028 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion; 6029 QualType ConvertedArgumentType = Args.front()->getType(); 6030 if (Candidate.Conversions[0].isUserDefined()) 6031 ConvertedArgumentType = 6032 Candidate.Conversions[0].UserDefined.After.getFromType(); 6033 if (CompareReferenceRelationship(Args.front()->getLocStart(), 6034 Context.getRecordType(Shadow->getParent()), 6035 ConvertedArgumentType, DerivedToBase, 6036 ObjCConversion, 6037 ObjCLifetimeConversion) >= Ref_Related) { 6038 Candidate.Viable = false; 6039 Candidate.FailureKind = ovl_fail_inhctor_slice; 6040 return; 6041 } 6042 } 6043 6044 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6045 Candidate.Viable = false; 6046 Candidate.FailureKind = ovl_fail_enable_if; 6047 Candidate.DeductionFailure.Data = FailedAttr; 6048 return; 6049 } 6050 6051 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6052 Candidate.Viable = false; 6053 Candidate.FailureKind = ovl_fail_ext_disabled; 6054 return; 6055 } 6056 6057 initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Function, Args); 6058 } 6059 6060 ObjCMethodDecl * 6061 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6062 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6063 if (Methods.size() <= 1) 6064 return nullptr; 6065 6066 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6067 bool Match = true; 6068 ObjCMethodDecl *Method = Methods[b]; 6069 unsigned NumNamedArgs = Sel.getNumArgs(); 6070 // Method might have more arguments than selector indicates. This is due 6071 // to addition of c-style arguments in method. 6072 if (Method->param_size() > NumNamedArgs) 6073 NumNamedArgs = Method->param_size(); 6074 if (Args.size() < NumNamedArgs) 6075 continue; 6076 6077 for (unsigned i = 0; i < NumNamedArgs; i++) { 6078 // We can't do any type-checking on a type-dependent argument. 6079 if (Args[i]->isTypeDependent()) { 6080 Match = false; 6081 break; 6082 } 6083 6084 ParmVarDecl *param = Method->parameters()[i]; 6085 Expr *argExpr = Args[i]; 6086 assert(argExpr && "SelectBestMethod(): missing expression"); 6087 6088 // Strip the unbridged-cast placeholder expression off unless it's 6089 // a consumed argument. 6090 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6091 !param->hasAttr<CFConsumedAttr>()) 6092 argExpr = stripARCUnbridgedCast(argExpr); 6093 6094 // If the parameter is __unknown_anytype, move on to the next method. 6095 if (param->getType() == Context.UnknownAnyTy) { 6096 Match = false; 6097 break; 6098 } 6099 6100 ImplicitConversionSequence ConversionState 6101 = TryCopyInitialization(*this, argExpr, param->getType(), 6102 /*SuppressUserConversions*/false, 6103 /*InOverloadResolution=*/true, 6104 /*AllowObjCWritebackConversion=*/ 6105 getLangOpts().ObjCAutoRefCount, 6106 /*AllowExplicit*/false); 6107 // This function looks for a reasonably-exact match, so we consider 6108 // incompatible pointer conversions to be a failure here. 6109 if (ConversionState.isBad() || 6110 (ConversionState.isStandard() && 6111 ConversionState.Standard.Second == 6112 ICK_Incompatible_Pointer_Conversion)) { 6113 Match = false; 6114 break; 6115 } 6116 } 6117 // Promote additional arguments to variadic methods. 6118 if (Match && Method->isVariadic()) { 6119 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6120 if (Args[i]->isTypeDependent()) { 6121 Match = false; 6122 break; 6123 } 6124 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6125 nullptr); 6126 if (Arg.isInvalid()) { 6127 Match = false; 6128 break; 6129 } 6130 } 6131 } else { 6132 // Check for extra arguments to non-variadic methods. 6133 if (Args.size() != NumNamedArgs) 6134 Match = false; 6135 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6136 // Special case when selectors have no argument. In this case, select 6137 // one with the most general result type of 'id'. 6138 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6139 QualType ReturnT = Methods[b]->getReturnType(); 6140 if (ReturnT->isObjCIdType()) 6141 return Methods[b]; 6142 } 6143 } 6144 } 6145 6146 if (Match) 6147 return Method; 6148 } 6149 return nullptr; 6150 } 6151 6152 // specific_attr_iterator iterates over enable_if attributes in reverse, and 6153 // enable_if is order-sensitive. As a result, we need to reverse things 6154 // sometimes. Size of 4 elements is arbitrary. 6155 static SmallVector<EnableIfAttr *, 4> 6156 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 6157 SmallVector<EnableIfAttr *, 4> Result; 6158 if (!Function->hasAttrs()) 6159 return Result; 6160 6161 const auto &FuncAttrs = Function->getAttrs(); 6162 for (Attr *Attr : FuncAttrs) 6163 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 6164 Result.push_back(EnableIf); 6165 6166 std::reverse(Result.begin(), Result.end()); 6167 return Result; 6168 } 6169 6170 static bool 6171 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6172 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6173 bool MissingImplicitThis, Expr *&ConvertedThis, 6174 SmallVectorImpl<Expr *> &ConvertedArgs) { 6175 if (ThisArg) { 6176 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6177 assert(!isa<CXXConstructorDecl>(Method) && 6178 "Shouldn't have `this` for ctors!"); 6179 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6180 ExprResult R = S.PerformObjectArgumentInitialization( 6181 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6182 if (R.isInvalid()) 6183 return false; 6184 ConvertedThis = R.get(); 6185 } else { 6186 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6187 (void)MD; 6188 assert((MissingImplicitThis || MD->isStatic() || 6189 isa<CXXConstructorDecl>(MD)) && 6190 "Expected `this` for non-ctor instance methods"); 6191 } 6192 ConvertedThis = nullptr; 6193 } 6194 6195 // Ignore any variadic arguments. Converting them is pointless, since the 6196 // user can't refer to them in the function condition. 6197 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6198 6199 // Convert the arguments. 6200 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6201 ExprResult R; 6202 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6203 S.Context, Function->getParamDecl(I)), 6204 SourceLocation(), Args[I]); 6205 6206 if (R.isInvalid()) 6207 return false; 6208 6209 ConvertedArgs.push_back(R.get()); 6210 } 6211 6212 if (Trap.hasErrorOccurred()) 6213 return false; 6214 6215 // Push default arguments if needed. 6216 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6217 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6218 ParmVarDecl *P = Function->getParamDecl(i); 6219 ExprResult R = S.PerformCopyInitialization( 6220 InitializedEntity::InitializeParameter(S.Context, 6221 Function->getParamDecl(i)), 6222 SourceLocation(), 6223 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6224 : P->getDefaultArg()); 6225 if (R.isInvalid()) 6226 return false; 6227 ConvertedArgs.push_back(R.get()); 6228 } 6229 6230 if (Trap.hasErrorOccurred()) 6231 return false; 6232 } 6233 return true; 6234 } 6235 6236 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6237 bool MissingImplicitThis) { 6238 SmallVector<EnableIfAttr *, 4> EnableIfAttrs = 6239 getOrderedEnableIfAttrs(Function); 6240 if (EnableIfAttrs.empty()) 6241 return nullptr; 6242 6243 SFINAETrap Trap(*this); 6244 SmallVector<Expr *, 16> ConvertedArgs; 6245 // FIXME: We should look into making enable_if late-parsed. 6246 Expr *DiscardedThis; 6247 if (!convertArgsForAvailabilityChecks( 6248 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6249 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6250 return EnableIfAttrs[0]; 6251 6252 for (auto *EIA : EnableIfAttrs) { 6253 APValue Result; 6254 // FIXME: This doesn't consider value-dependent cases, because doing so is 6255 // very difficult. Ideally, we should handle them more gracefully. 6256 if (!EIA->getCond()->EvaluateWithSubstitution( 6257 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6258 return EIA; 6259 6260 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6261 return EIA; 6262 } 6263 return nullptr; 6264 } 6265 6266 static bool gatherDiagnoseIfAttrs(FunctionDecl *Function, bool ArgDependent, 6267 SmallVectorImpl<DiagnoseIfAttr *> &Errors, 6268 SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal) { 6269 for (auto *DIA : Function->specific_attrs<DiagnoseIfAttr>()) 6270 if (ArgDependent == DIA->getArgDependent()) { 6271 if (DIA->isError()) 6272 Errors.push_back(DIA); 6273 else 6274 Nonfatal.push_back(DIA); 6275 } 6276 6277 return !Errors.empty() || !Nonfatal.empty(); 6278 } 6279 6280 template <typename CheckFn> 6281 static DiagnoseIfAttr * 6282 checkDiagnoseIfAttrsWith(const SmallVectorImpl<DiagnoseIfAttr *> &Errors, 6283 SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal, 6284 CheckFn &&IsSuccessful) { 6285 // Note that diagnose_if attributes are late-parsed, so they appear in the 6286 // correct order (unlike enable_if attributes). 6287 auto ErrAttr = llvm::find_if(Errors, IsSuccessful); 6288 if (ErrAttr != Errors.end()) 6289 return *ErrAttr; 6290 6291 llvm::erase_if(Nonfatal, [&](DiagnoseIfAttr *A) { return !IsSuccessful(A); }); 6292 return nullptr; 6293 } 6294 6295 DiagnoseIfAttr * 6296 Sema::checkArgDependentDiagnoseIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6297 SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal, 6298 bool MissingImplicitThis, 6299 Expr *ThisArg) { 6300 SmallVector<DiagnoseIfAttr *, 4> Errors; 6301 if (!gatherDiagnoseIfAttrs(Function, /*ArgDependent=*/true, Errors, Nonfatal)) 6302 return nullptr; 6303 6304 SFINAETrap Trap(*this); 6305 SmallVector<Expr *, 16> ConvertedArgs; 6306 Expr *ConvertedThis; 6307 if (!convertArgsForAvailabilityChecks(*this, Function, ThisArg, Args, Trap, 6308 MissingImplicitThis, ConvertedThis, 6309 ConvertedArgs)) 6310 return nullptr; 6311 6312 return checkDiagnoseIfAttrsWith(Errors, Nonfatal, [&](DiagnoseIfAttr *DIA) { 6313 APValue Result; 6314 // It's sane to use the same ConvertedArgs for any redecl of this function, 6315 // since EvaluateWithSubstitution only cares about the position of each 6316 // argument in the arg list, not the ParmVarDecl* it maps to. 6317 if (!DIA->getCond()->EvaluateWithSubstitution( 6318 Result, Context, DIA->getParent(), ConvertedArgs, ConvertedThis)) 6319 return false; 6320 return Result.isInt() && Result.getInt().getBoolValue(); 6321 }); 6322 } 6323 6324 DiagnoseIfAttr *Sema::checkArgIndependentDiagnoseIf( 6325 FunctionDecl *Function, SmallVectorImpl<DiagnoseIfAttr *> &Nonfatal) { 6326 SmallVector<DiagnoseIfAttr *, 4> Errors; 6327 if (!gatherDiagnoseIfAttrs(Function, /*ArgDependent=*/false, Errors, 6328 Nonfatal)) 6329 return nullptr; 6330 6331 return checkDiagnoseIfAttrsWith(Errors, Nonfatal, [&](DiagnoseIfAttr *DIA) { 6332 bool Result; 6333 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6334 Result; 6335 }); 6336 } 6337 6338 void Sema::emitDiagnoseIfDiagnostic(SourceLocation Loc, 6339 const DiagnoseIfAttr *DIA) { 6340 auto Code = DIA->isError() ? diag::err_diagnose_if_succeeded 6341 : diag::warn_diagnose_if_succeeded; 6342 Diag(Loc, Code) << DIA->getMessage(); 6343 Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6344 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6345 } 6346 6347 /// \brief Add all of the function declarations in the given function set to 6348 /// the overload candidate set. 6349 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6350 ArrayRef<Expr *> Args, 6351 OverloadCandidateSet& CandidateSet, 6352 TemplateArgumentListInfo *ExplicitTemplateArgs, 6353 bool SuppressUserConversions, 6354 bool PartialOverloading) { 6355 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6356 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6357 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6358 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6359 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6360 cast<CXXMethodDecl>(FD)->getParent(), 6361 Args[0]->getType(), Args[0]->Classify(Context), 6362 Args[0], Args.slice(1), CandidateSet, 6363 SuppressUserConversions, PartialOverloading); 6364 else 6365 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6366 SuppressUserConversions, PartialOverloading); 6367 } else { 6368 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6369 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6370 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6371 AddMethodTemplateCandidate( 6372 FunTmpl, F.getPair(), 6373 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6374 ExplicitTemplateArgs, Args[0]->getType(), 6375 Args[0]->Classify(Context), Args[0], Args.slice(1), CandidateSet, 6376 SuppressUserConversions, PartialOverloading); 6377 else 6378 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6379 ExplicitTemplateArgs, Args, 6380 CandidateSet, SuppressUserConversions, 6381 PartialOverloading); 6382 } 6383 } 6384 } 6385 6386 /// AddMethodCandidate - Adds a named decl (which is some kind of 6387 /// method) as a method candidate to the given overload set. 6388 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6389 QualType ObjectType, 6390 Expr::Classification ObjectClassification, 6391 Expr *ThisArg, 6392 ArrayRef<Expr *> Args, 6393 OverloadCandidateSet& CandidateSet, 6394 bool SuppressUserConversions) { 6395 NamedDecl *Decl = FoundDecl.getDecl(); 6396 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6397 6398 if (isa<UsingShadowDecl>(Decl)) 6399 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6400 6401 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6402 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6403 "Expected a member function template"); 6404 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6405 /*ExplicitArgs*/ nullptr, 6406 ObjectType, ObjectClassification, 6407 ThisArg, Args, CandidateSet, 6408 SuppressUserConversions); 6409 } else { 6410 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6411 ObjectType, ObjectClassification, 6412 ThisArg, Args, 6413 CandidateSet, SuppressUserConversions); 6414 } 6415 } 6416 6417 /// AddMethodCandidate - Adds the given C++ member function to the set 6418 /// of candidate functions, using the given function call arguments 6419 /// and the object argument (@c Object). For example, in a call 6420 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6421 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6422 /// allow user-defined conversions via constructors or conversion 6423 /// operators. 6424 void 6425 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6426 CXXRecordDecl *ActingContext, QualType ObjectType, 6427 Expr::Classification ObjectClassification, 6428 Expr *ThisArg, ArrayRef<Expr *> Args, 6429 OverloadCandidateSet &CandidateSet, 6430 bool SuppressUserConversions, 6431 bool PartialOverloading, 6432 ConversionSequenceList EarlyConversions) { 6433 const FunctionProtoType *Proto 6434 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6435 assert(Proto && "Methods without a prototype cannot be overloaded"); 6436 assert(!isa<CXXConstructorDecl>(Method) && 6437 "Use AddOverloadCandidate for constructors"); 6438 6439 if (!CandidateSet.isNewCandidate(Method)) 6440 return; 6441 6442 // C++11 [class.copy]p23: [DR1402] 6443 // A defaulted move assignment operator that is defined as deleted is 6444 // ignored by overload resolution. 6445 if (Method->isDefaulted() && Method->isDeleted() && 6446 Method->isMoveAssignmentOperator()) 6447 return; 6448 6449 // Overload resolution is always an unevaluated context. 6450 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6451 6452 // Add this candidate 6453 OverloadCandidate &Candidate = 6454 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6455 Candidate.FoundDecl = FoundDecl; 6456 Candidate.Function = Method; 6457 Candidate.IsSurrogate = false; 6458 Candidate.IgnoreObjectArgument = false; 6459 Candidate.ExplicitCallArguments = Args.size(); 6460 6461 unsigned NumParams = Proto->getNumParams(); 6462 6463 // (C++ 13.3.2p2): A candidate function having fewer than m 6464 // parameters is viable only if it has an ellipsis in its parameter 6465 // list (8.3.5). 6466 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6467 !Proto->isVariadic()) { 6468 Candidate.Viable = false; 6469 Candidate.FailureKind = ovl_fail_too_many_arguments; 6470 return; 6471 } 6472 6473 // (C++ 13.3.2p2): A candidate function having more than m parameters 6474 // is viable only if the (m+1)st parameter has a default argument 6475 // (8.3.6). For the purposes of overload resolution, the 6476 // parameter list is truncated on the right, so that there are 6477 // exactly m parameters. 6478 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6479 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6480 // Not enough arguments. 6481 Candidate.Viable = false; 6482 Candidate.FailureKind = ovl_fail_too_few_arguments; 6483 return; 6484 } 6485 6486 Candidate.Viable = true; 6487 6488 if (Method->isStatic() || ObjectType.isNull()) 6489 // The implicit object argument is ignored. 6490 Candidate.IgnoreObjectArgument = true; 6491 else { 6492 // Determine the implicit conversion sequence for the object 6493 // parameter. 6494 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6495 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6496 Method, ActingContext); 6497 if (Candidate.Conversions[0].isBad()) { 6498 Candidate.Viable = false; 6499 Candidate.FailureKind = ovl_fail_bad_conversion; 6500 return; 6501 } 6502 } 6503 6504 // (CUDA B.1): Check for invalid calls between targets. 6505 if (getLangOpts().CUDA) 6506 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6507 if (!IsAllowedCUDACall(Caller, Method)) { 6508 Candidate.Viable = false; 6509 Candidate.FailureKind = ovl_fail_bad_target; 6510 return; 6511 } 6512 6513 // Determine the implicit conversion sequences for each of the 6514 // arguments. 6515 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6516 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6517 // We already formed a conversion sequence for this parameter during 6518 // template argument deduction. 6519 } else if (ArgIdx < NumParams) { 6520 // (C++ 13.3.2p3): for F to be a viable function, there shall 6521 // exist for each argument an implicit conversion sequence 6522 // (13.3.3.1) that converts that argument to the corresponding 6523 // parameter of F. 6524 QualType ParamType = Proto->getParamType(ArgIdx); 6525 Candidate.Conversions[ArgIdx + 1] 6526 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6527 SuppressUserConversions, 6528 /*InOverloadResolution=*/true, 6529 /*AllowObjCWritebackConversion=*/ 6530 getLangOpts().ObjCAutoRefCount); 6531 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6532 Candidate.Viable = false; 6533 Candidate.FailureKind = ovl_fail_bad_conversion; 6534 return; 6535 } 6536 } else { 6537 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6538 // argument for which there is no corresponding parameter is 6539 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6540 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6541 } 6542 } 6543 6544 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6545 Candidate.Viable = false; 6546 Candidate.FailureKind = ovl_fail_enable_if; 6547 Candidate.DeductionFailure.Data = FailedAttr; 6548 return; 6549 } 6550 6551 initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Method, Args, 6552 /*MissingImplicitThis=*/!ThisArg, ThisArg); 6553 } 6554 6555 /// \brief Add a C++ member function template as a candidate to the candidate 6556 /// set, using template argument deduction to produce an appropriate member 6557 /// function template specialization. 6558 void 6559 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6560 DeclAccessPair FoundDecl, 6561 CXXRecordDecl *ActingContext, 6562 TemplateArgumentListInfo *ExplicitTemplateArgs, 6563 QualType ObjectType, 6564 Expr::Classification ObjectClassification, 6565 Expr *ThisArg, 6566 ArrayRef<Expr *> Args, 6567 OverloadCandidateSet& CandidateSet, 6568 bool SuppressUserConversions, 6569 bool PartialOverloading) { 6570 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6571 return; 6572 6573 // C++ [over.match.funcs]p7: 6574 // In each case where a candidate is a function template, candidate 6575 // function template specializations are generated using template argument 6576 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6577 // candidate functions in the usual way.113) A given name can refer to one 6578 // or more function templates and also to a set of overloaded non-template 6579 // functions. In such a case, the candidate functions generated from each 6580 // function template are combined with the set of non-template candidate 6581 // functions. 6582 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6583 FunctionDecl *Specialization = nullptr; 6584 ConversionSequenceList Conversions; 6585 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6586 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6587 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6588 return CheckNonDependentConversions( 6589 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6590 SuppressUserConversions, ActingContext, ObjectType, 6591 ObjectClassification); 6592 })) { 6593 OverloadCandidate &Candidate = 6594 CandidateSet.addCandidate(Conversions.size(), Conversions); 6595 Candidate.FoundDecl = FoundDecl; 6596 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6597 Candidate.Viable = false; 6598 Candidate.IsSurrogate = false; 6599 Candidate.IgnoreObjectArgument = false; 6600 Candidate.ExplicitCallArguments = Args.size(); 6601 if (Result == TDK_NonDependentConversionFailure) 6602 Candidate.FailureKind = ovl_fail_bad_conversion; 6603 else { 6604 Candidate.FailureKind = ovl_fail_bad_deduction; 6605 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6606 Info); 6607 } 6608 return; 6609 } 6610 6611 // Add the function template specialization produced by template argument 6612 // deduction as a candidate. 6613 assert(Specialization && "Missing member function template specialization?"); 6614 assert(isa<CXXMethodDecl>(Specialization) && 6615 "Specialization is not a member function?"); 6616 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6617 ActingContext, ObjectType, ObjectClassification, 6618 /*ThisArg=*/ThisArg, Args, CandidateSet, 6619 SuppressUserConversions, PartialOverloading, Conversions); 6620 } 6621 6622 /// \brief Add a C++ function template specialization as a candidate 6623 /// in the candidate set, using template argument deduction to produce 6624 /// an appropriate function template specialization. 6625 void 6626 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6627 DeclAccessPair FoundDecl, 6628 TemplateArgumentListInfo *ExplicitTemplateArgs, 6629 ArrayRef<Expr *> Args, 6630 OverloadCandidateSet& CandidateSet, 6631 bool SuppressUserConversions, 6632 bool PartialOverloading) { 6633 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6634 return; 6635 6636 // C++ [over.match.funcs]p7: 6637 // In each case where a candidate is a function template, candidate 6638 // function template specializations are generated using template argument 6639 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6640 // candidate functions in the usual way.113) A given name can refer to one 6641 // or more function templates and also to a set of overloaded non-template 6642 // functions. In such a case, the candidate functions generated from each 6643 // function template are combined with the set of non-template candidate 6644 // functions. 6645 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6646 FunctionDecl *Specialization = nullptr; 6647 ConversionSequenceList Conversions; 6648 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6649 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6650 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6651 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6652 Args, CandidateSet, Conversions, 6653 SuppressUserConversions); 6654 })) { 6655 OverloadCandidate &Candidate = 6656 CandidateSet.addCandidate(Conversions.size(), Conversions); 6657 Candidate.FoundDecl = FoundDecl; 6658 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6659 Candidate.Viable = false; 6660 Candidate.IsSurrogate = false; 6661 Candidate.IgnoreObjectArgument = false; 6662 Candidate.ExplicitCallArguments = Args.size(); 6663 if (Result == TDK_NonDependentConversionFailure) 6664 Candidate.FailureKind = ovl_fail_bad_conversion; 6665 else { 6666 Candidate.FailureKind = ovl_fail_bad_deduction; 6667 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6668 Info); 6669 } 6670 return; 6671 } 6672 6673 // Add the function template specialization produced by template argument 6674 // deduction as a candidate. 6675 assert(Specialization && "Missing function template specialization?"); 6676 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6677 SuppressUserConversions, PartialOverloading, 6678 /*AllowExplicit*/false, Conversions); 6679 } 6680 6681 /// Check that implicit conversion sequences can be formed for each argument 6682 /// whose corresponding parameter has a non-dependent type, per DR1391's 6683 /// [temp.deduct.call]p10. 6684 bool Sema::CheckNonDependentConversions( 6685 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6686 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6687 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6688 CXXRecordDecl *ActingContext, QualType ObjectType, 6689 Expr::Classification ObjectClassification) { 6690 // FIXME: The cases in which we allow explicit conversions for constructor 6691 // arguments never consider calling a constructor template. It's not clear 6692 // that is correct. 6693 const bool AllowExplicit = false; 6694 6695 auto *FD = FunctionTemplate->getTemplatedDecl(); 6696 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6697 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6698 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6699 6700 Conversions = 6701 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6702 6703 // Overload resolution is always an unevaluated context. 6704 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6705 6706 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6707 // require that, but this check should never result in a hard error, and 6708 // overload resolution is permitted to sidestep instantiations. 6709 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6710 !ObjectType.isNull()) { 6711 Conversions[0] = TryObjectArgumentInitialization( 6712 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6713 Method, ActingContext); 6714 if (Conversions[0].isBad()) 6715 return true; 6716 } 6717 6718 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6719 ++I) { 6720 QualType ParamType = ParamTypes[I]; 6721 if (!ParamType->isDependentType()) { 6722 Conversions[ThisConversions + I] 6723 = TryCopyInitialization(*this, Args[I], ParamType, 6724 SuppressUserConversions, 6725 /*InOverloadResolution=*/true, 6726 /*AllowObjCWritebackConversion=*/ 6727 getLangOpts().ObjCAutoRefCount, 6728 AllowExplicit); 6729 if (Conversions[ThisConversions + I].isBad()) 6730 return true; 6731 } 6732 } 6733 6734 return false; 6735 } 6736 6737 /// Determine whether this is an allowable conversion from the result 6738 /// of an explicit conversion operator to the expected type, per C++ 6739 /// [over.match.conv]p1 and [over.match.ref]p1. 6740 /// 6741 /// \param ConvType The return type of the conversion function. 6742 /// 6743 /// \param ToType The type we are converting to. 6744 /// 6745 /// \param AllowObjCPointerConversion Allow a conversion from one 6746 /// Objective-C pointer to another. 6747 /// 6748 /// \returns true if the conversion is allowable, false otherwise. 6749 static bool isAllowableExplicitConversion(Sema &S, 6750 QualType ConvType, QualType ToType, 6751 bool AllowObjCPointerConversion) { 6752 QualType ToNonRefType = ToType.getNonReferenceType(); 6753 6754 // Easy case: the types are the same. 6755 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6756 return true; 6757 6758 // Allow qualification conversions. 6759 bool ObjCLifetimeConversion; 6760 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6761 ObjCLifetimeConversion)) 6762 return true; 6763 6764 // If we're not allowed to consider Objective-C pointer conversions, 6765 // we're done. 6766 if (!AllowObjCPointerConversion) 6767 return false; 6768 6769 // Is this an Objective-C pointer conversion? 6770 bool IncompatibleObjC = false; 6771 QualType ConvertedType; 6772 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6773 IncompatibleObjC); 6774 } 6775 6776 /// AddConversionCandidate - Add a C++ conversion function as a 6777 /// candidate in the candidate set (C++ [over.match.conv], 6778 /// C++ [over.match.copy]). From is the expression we're converting from, 6779 /// and ToType is the type that we're eventually trying to convert to 6780 /// (which may or may not be the same type as the type that the 6781 /// conversion function produces). 6782 void 6783 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6784 DeclAccessPair FoundDecl, 6785 CXXRecordDecl *ActingContext, 6786 Expr *From, QualType ToType, 6787 OverloadCandidateSet& CandidateSet, 6788 bool AllowObjCConversionOnExplicit) { 6789 assert(!Conversion->getDescribedFunctionTemplate() && 6790 "Conversion function templates use AddTemplateConversionCandidate"); 6791 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6792 if (!CandidateSet.isNewCandidate(Conversion)) 6793 return; 6794 6795 // If the conversion function has an undeduced return type, trigger its 6796 // deduction now. 6797 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6798 if (DeduceReturnType(Conversion, From->getExprLoc())) 6799 return; 6800 ConvType = Conversion->getConversionType().getNonReferenceType(); 6801 } 6802 6803 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6804 // operator is only a candidate if its return type is the target type or 6805 // can be converted to the target type with a qualification conversion. 6806 if (Conversion->isExplicit() && 6807 !isAllowableExplicitConversion(*this, ConvType, ToType, 6808 AllowObjCConversionOnExplicit)) 6809 return; 6810 6811 // Overload resolution is always an unevaluated context. 6812 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6813 6814 // Add this candidate 6815 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6816 Candidate.FoundDecl = FoundDecl; 6817 Candidate.Function = Conversion; 6818 Candidate.IsSurrogate = false; 6819 Candidate.IgnoreObjectArgument = false; 6820 Candidate.FinalConversion.setAsIdentityConversion(); 6821 Candidate.FinalConversion.setFromType(ConvType); 6822 Candidate.FinalConversion.setAllToTypes(ToType); 6823 Candidate.Viable = true; 6824 Candidate.ExplicitCallArguments = 1; 6825 6826 // C++ [over.match.funcs]p4: 6827 // For conversion functions, the function is considered to be a member of 6828 // the class of the implicit implied object argument for the purpose of 6829 // defining the type of the implicit object parameter. 6830 // 6831 // Determine the implicit conversion sequence for the implicit 6832 // object parameter. 6833 QualType ImplicitParamType = From->getType(); 6834 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6835 ImplicitParamType = FromPtrType->getPointeeType(); 6836 CXXRecordDecl *ConversionContext 6837 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6838 6839 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6840 *this, CandidateSet.getLocation(), From->getType(), 6841 From->Classify(Context), Conversion, ConversionContext); 6842 6843 if (Candidate.Conversions[0].isBad()) { 6844 Candidate.Viable = false; 6845 Candidate.FailureKind = ovl_fail_bad_conversion; 6846 return; 6847 } 6848 6849 // We won't go through a user-defined type conversion function to convert a 6850 // derived to base as such conversions are given Conversion Rank. They only 6851 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6852 QualType FromCanon 6853 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6854 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6855 if (FromCanon == ToCanon || 6856 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6857 Candidate.Viable = false; 6858 Candidate.FailureKind = ovl_fail_trivial_conversion; 6859 return; 6860 } 6861 6862 // To determine what the conversion from the result of calling the 6863 // conversion function to the type we're eventually trying to 6864 // convert to (ToType), we need to synthesize a call to the 6865 // conversion function and attempt copy initialization from it. This 6866 // makes sure that we get the right semantics with respect to 6867 // lvalues/rvalues and the type. Fortunately, we can allocate this 6868 // call on the stack and we don't need its arguments to be 6869 // well-formed. 6870 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6871 VK_LValue, From->getLocStart()); 6872 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6873 Context.getPointerType(Conversion->getType()), 6874 CK_FunctionToPointerDecay, 6875 &ConversionRef, VK_RValue); 6876 6877 QualType ConversionType = Conversion->getConversionType(); 6878 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6879 Candidate.Viable = false; 6880 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6881 return; 6882 } 6883 6884 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6885 6886 // Note that it is safe to allocate CallExpr on the stack here because 6887 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6888 // allocator). 6889 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6890 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6891 From->getLocStart()); 6892 ImplicitConversionSequence ICS = 6893 TryCopyInitialization(*this, &Call, ToType, 6894 /*SuppressUserConversions=*/true, 6895 /*InOverloadResolution=*/false, 6896 /*AllowObjCWritebackConversion=*/false); 6897 6898 switch (ICS.getKind()) { 6899 case ImplicitConversionSequence::StandardConversion: 6900 Candidate.FinalConversion = ICS.Standard; 6901 6902 // C++ [over.ics.user]p3: 6903 // If the user-defined conversion is specified by a specialization of a 6904 // conversion function template, the second standard conversion sequence 6905 // shall have exact match rank. 6906 if (Conversion->getPrimaryTemplate() && 6907 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6908 Candidate.Viable = false; 6909 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6910 return; 6911 } 6912 6913 // C++0x [dcl.init.ref]p5: 6914 // In the second case, if the reference is an rvalue reference and 6915 // the second standard conversion sequence of the user-defined 6916 // conversion sequence includes an lvalue-to-rvalue conversion, the 6917 // program is ill-formed. 6918 if (ToType->isRValueReferenceType() && 6919 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6920 Candidate.Viable = false; 6921 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6922 return; 6923 } 6924 break; 6925 6926 case ImplicitConversionSequence::BadConversion: 6927 Candidate.Viable = false; 6928 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6929 return; 6930 6931 default: 6932 llvm_unreachable( 6933 "Can only end up with a standard conversion sequence or failure"); 6934 } 6935 6936 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6937 Candidate.Viable = false; 6938 Candidate.FailureKind = ovl_fail_enable_if; 6939 Candidate.DeductionFailure.Data = FailedAttr; 6940 return; 6941 } 6942 6943 initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Conversion, None, false, From); 6944 } 6945 6946 /// \brief Adds a conversion function template specialization 6947 /// candidate to the overload set, using template argument deduction 6948 /// to deduce the template arguments of the conversion function 6949 /// template from the type that we are converting to (C++ 6950 /// [temp.deduct.conv]). 6951 void 6952 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6953 DeclAccessPair FoundDecl, 6954 CXXRecordDecl *ActingDC, 6955 Expr *From, QualType ToType, 6956 OverloadCandidateSet &CandidateSet, 6957 bool AllowObjCConversionOnExplicit) { 6958 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6959 "Only conversion function templates permitted here"); 6960 6961 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6962 return; 6963 6964 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6965 CXXConversionDecl *Specialization = nullptr; 6966 if (TemplateDeductionResult Result 6967 = DeduceTemplateArguments(FunctionTemplate, ToType, 6968 Specialization, Info)) { 6969 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6970 Candidate.FoundDecl = FoundDecl; 6971 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6972 Candidate.Viable = false; 6973 Candidate.FailureKind = ovl_fail_bad_deduction; 6974 Candidate.IsSurrogate = false; 6975 Candidate.IgnoreObjectArgument = false; 6976 Candidate.ExplicitCallArguments = 1; 6977 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6978 Info); 6979 return; 6980 } 6981 6982 // Add the conversion function template specialization produced by 6983 // template argument deduction as a candidate. 6984 assert(Specialization && "Missing function template specialization?"); 6985 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6986 CandidateSet, AllowObjCConversionOnExplicit); 6987 } 6988 6989 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6990 /// converts the given @c Object to a function pointer via the 6991 /// conversion function @c Conversion, and then attempts to call it 6992 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6993 /// the type of function that we'll eventually be calling. 6994 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6995 DeclAccessPair FoundDecl, 6996 CXXRecordDecl *ActingContext, 6997 const FunctionProtoType *Proto, 6998 Expr *Object, 6999 ArrayRef<Expr *> Args, 7000 OverloadCandidateSet& CandidateSet) { 7001 if (!CandidateSet.isNewCandidate(Conversion)) 7002 return; 7003 7004 // Overload resolution is always an unevaluated context. 7005 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 7006 7007 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7008 Candidate.FoundDecl = FoundDecl; 7009 Candidate.Function = nullptr; 7010 Candidate.Surrogate = Conversion; 7011 Candidate.Viable = true; 7012 Candidate.IsSurrogate = true; 7013 Candidate.IgnoreObjectArgument = false; 7014 Candidate.ExplicitCallArguments = Args.size(); 7015 7016 // Determine the implicit conversion sequence for the implicit 7017 // object parameter. 7018 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7019 *this, CandidateSet.getLocation(), Object->getType(), 7020 Object->Classify(Context), Conversion, ActingContext); 7021 if (ObjectInit.isBad()) { 7022 Candidate.Viable = false; 7023 Candidate.FailureKind = ovl_fail_bad_conversion; 7024 Candidate.Conversions[0] = ObjectInit; 7025 return; 7026 } 7027 7028 // The first conversion is actually a user-defined conversion whose 7029 // first conversion is ObjectInit's standard conversion (which is 7030 // effectively a reference binding). Record it as such. 7031 Candidate.Conversions[0].setUserDefined(); 7032 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7033 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7034 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7035 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7036 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7037 Candidate.Conversions[0].UserDefined.After 7038 = Candidate.Conversions[0].UserDefined.Before; 7039 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7040 7041 // Find the 7042 unsigned NumParams = Proto->getNumParams(); 7043 7044 // (C++ 13.3.2p2): A candidate function having fewer than m 7045 // parameters is viable only if it has an ellipsis in its parameter 7046 // list (8.3.5). 7047 if (Args.size() > NumParams && !Proto->isVariadic()) { 7048 Candidate.Viable = false; 7049 Candidate.FailureKind = ovl_fail_too_many_arguments; 7050 return; 7051 } 7052 7053 // Function types don't have any default arguments, so just check if 7054 // we have enough arguments. 7055 if (Args.size() < NumParams) { 7056 // Not enough arguments. 7057 Candidate.Viable = false; 7058 Candidate.FailureKind = ovl_fail_too_few_arguments; 7059 return; 7060 } 7061 7062 // Determine the implicit conversion sequences for each of the 7063 // arguments. 7064 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7065 if (ArgIdx < NumParams) { 7066 // (C++ 13.3.2p3): for F to be a viable function, there shall 7067 // exist for each argument an implicit conversion sequence 7068 // (13.3.3.1) that converts that argument to the corresponding 7069 // parameter of F. 7070 QualType ParamType = Proto->getParamType(ArgIdx); 7071 Candidate.Conversions[ArgIdx + 1] 7072 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7073 /*SuppressUserConversions=*/false, 7074 /*InOverloadResolution=*/false, 7075 /*AllowObjCWritebackConversion=*/ 7076 getLangOpts().ObjCAutoRefCount); 7077 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7078 Candidate.Viable = false; 7079 Candidate.FailureKind = ovl_fail_bad_conversion; 7080 return; 7081 } 7082 } else { 7083 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7084 // argument for which there is no corresponding parameter is 7085 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7086 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7087 } 7088 } 7089 7090 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7091 Candidate.Viable = false; 7092 Candidate.FailureKind = ovl_fail_enable_if; 7093 Candidate.DeductionFailure.Data = FailedAttr; 7094 return; 7095 } 7096 7097 initDiagnoseIfComplaint(*this, CandidateSet, Candidate, Conversion, None); 7098 } 7099 7100 /// \brief Add overload candidates for overloaded operators that are 7101 /// member functions. 7102 /// 7103 /// Add the overloaded operator candidates that are member functions 7104 /// for the operator Op that was used in an operator expression such 7105 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7106 /// CandidateSet will store the added overload candidates. (C++ 7107 /// [over.match.oper]). 7108 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7109 SourceLocation OpLoc, 7110 ArrayRef<Expr *> Args, 7111 OverloadCandidateSet& CandidateSet, 7112 SourceRange OpRange) { 7113 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7114 7115 // C++ [over.match.oper]p3: 7116 // For a unary operator @ with an operand of a type whose 7117 // cv-unqualified version is T1, and for a binary operator @ with 7118 // a left operand of a type whose cv-unqualified version is T1 and 7119 // a right operand of a type whose cv-unqualified version is T2, 7120 // three sets of candidate functions, designated member 7121 // candidates, non-member candidates and built-in candidates, are 7122 // constructed as follows: 7123 QualType T1 = Args[0]->getType(); 7124 7125 // -- If T1 is a complete class type or a class currently being 7126 // defined, the set of member candidates is the result of the 7127 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7128 // the set of member candidates is empty. 7129 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7130 // Complete the type if it can be completed. 7131 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7132 return; 7133 // If the type is neither complete nor being defined, bail out now. 7134 if (!T1Rec->getDecl()->getDefinition()) 7135 return; 7136 7137 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7138 LookupQualifiedName(Operators, T1Rec->getDecl()); 7139 Operators.suppressDiagnostics(); 7140 7141 for (LookupResult::iterator Oper = Operators.begin(), 7142 OperEnd = Operators.end(); 7143 Oper != OperEnd; 7144 ++Oper) 7145 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7146 Args[0]->Classify(Context), Args[0], Args.slice(1), 7147 CandidateSet, /*SuppressUserConversions=*/false); 7148 } 7149 } 7150 7151 /// AddBuiltinCandidate - Add a candidate for a built-in 7152 /// operator. ResultTy and ParamTys are the result and parameter types 7153 /// of the built-in candidate, respectively. Args and NumArgs are the 7154 /// arguments being passed to the candidate. IsAssignmentOperator 7155 /// should be true when this built-in candidate is an assignment 7156 /// operator. NumContextualBoolArguments is the number of arguments 7157 /// (at the beginning of the argument list) that will be contextually 7158 /// converted to bool. 7159 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 7160 ArrayRef<Expr *> Args, 7161 OverloadCandidateSet& CandidateSet, 7162 bool IsAssignmentOperator, 7163 unsigned NumContextualBoolArguments) { 7164 // Overload resolution is always an unevaluated context. 7165 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 7166 7167 // Add this candidate 7168 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7169 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7170 Candidate.Function = nullptr; 7171 Candidate.IsSurrogate = false; 7172 Candidate.IgnoreObjectArgument = false; 7173 Candidate.BuiltinTypes.ResultTy = ResultTy; 7174 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7175 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 7176 7177 // Determine the implicit conversion sequences for each of the 7178 // arguments. 7179 Candidate.Viable = true; 7180 Candidate.ExplicitCallArguments = Args.size(); 7181 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7182 // C++ [over.match.oper]p4: 7183 // For the built-in assignment operators, conversions of the 7184 // left operand are restricted as follows: 7185 // -- no temporaries are introduced to hold the left operand, and 7186 // -- no user-defined conversions are applied to the left 7187 // operand to achieve a type match with the left-most 7188 // parameter of a built-in candidate. 7189 // 7190 // We block these conversions by turning off user-defined 7191 // conversions, since that is the only way that initialization of 7192 // a reference to a non-class type can occur from something that 7193 // is not of the same type. 7194 if (ArgIdx < NumContextualBoolArguments) { 7195 assert(ParamTys[ArgIdx] == Context.BoolTy && 7196 "Contextual conversion to bool requires bool type"); 7197 Candidate.Conversions[ArgIdx] 7198 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7199 } else { 7200 Candidate.Conversions[ArgIdx] 7201 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7202 ArgIdx == 0 && IsAssignmentOperator, 7203 /*InOverloadResolution=*/false, 7204 /*AllowObjCWritebackConversion=*/ 7205 getLangOpts().ObjCAutoRefCount); 7206 } 7207 if (Candidate.Conversions[ArgIdx].isBad()) { 7208 Candidate.Viable = false; 7209 Candidate.FailureKind = ovl_fail_bad_conversion; 7210 break; 7211 } 7212 } 7213 } 7214 7215 namespace { 7216 7217 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7218 /// candidate operator functions for built-in operators (C++ 7219 /// [over.built]). The types are separated into pointer types and 7220 /// enumeration types. 7221 class BuiltinCandidateTypeSet { 7222 /// TypeSet - A set of types. 7223 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7224 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7225 7226 /// PointerTypes - The set of pointer types that will be used in the 7227 /// built-in candidates. 7228 TypeSet PointerTypes; 7229 7230 /// MemberPointerTypes - The set of member pointer types that will be 7231 /// used in the built-in candidates. 7232 TypeSet MemberPointerTypes; 7233 7234 /// EnumerationTypes - The set of enumeration types that will be 7235 /// used in the built-in candidates. 7236 TypeSet EnumerationTypes; 7237 7238 /// \brief The set of vector types that will be used in the built-in 7239 /// candidates. 7240 TypeSet VectorTypes; 7241 7242 /// \brief A flag indicating non-record types are viable candidates 7243 bool HasNonRecordTypes; 7244 7245 /// \brief A flag indicating whether either arithmetic or enumeration types 7246 /// were present in the candidate set. 7247 bool HasArithmeticOrEnumeralTypes; 7248 7249 /// \brief A flag indicating whether the nullptr type was present in the 7250 /// candidate set. 7251 bool HasNullPtrType; 7252 7253 /// Sema - The semantic analysis instance where we are building the 7254 /// candidate type set. 7255 Sema &SemaRef; 7256 7257 /// Context - The AST context in which we will build the type sets. 7258 ASTContext &Context; 7259 7260 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7261 const Qualifiers &VisibleQuals); 7262 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7263 7264 public: 7265 /// iterator - Iterates through the types that are part of the set. 7266 typedef TypeSet::iterator iterator; 7267 7268 BuiltinCandidateTypeSet(Sema &SemaRef) 7269 : HasNonRecordTypes(false), 7270 HasArithmeticOrEnumeralTypes(false), 7271 HasNullPtrType(false), 7272 SemaRef(SemaRef), 7273 Context(SemaRef.Context) { } 7274 7275 void AddTypesConvertedFrom(QualType Ty, 7276 SourceLocation Loc, 7277 bool AllowUserConversions, 7278 bool AllowExplicitConversions, 7279 const Qualifiers &VisibleTypeConversionsQuals); 7280 7281 /// pointer_begin - First pointer type found; 7282 iterator pointer_begin() { return PointerTypes.begin(); } 7283 7284 /// pointer_end - Past the last pointer type found; 7285 iterator pointer_end() { return PointerTypes.end(); } 7286 7287 /// member_pointer_begin - First member pointer type found; 7288 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7289 7290 /// member_pointer_end - Past the last member pointer type found; 7291 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7292 7293 /// enumeration_begin - First enumeration type found; 7294 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7295 7296 /// enumeration_end - Past the last enumeration type found; 7297 iterator enumeration_end() { return EnumerationTypes.end(); } 7298 7299 iterator vector_begin() { return VectorTypes.begin(); } 7300 iterator vector_end() { return VectorTypes.end(); } 7301 7302 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7303 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7304 bool hasNullPtrType() const { return HasNullPtrType; } 7305 }; 7306 7307 } // end anonymous namespace 7308 7309 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7310 /// the set of pointer types along with any more-qualified variants of 7311 /// that type. For example, if @p Ty is "int const *", this routine 7312 /// will add "int const *", "int const volatile *", "int const 7313 /// restrict *", and "int const volatile restrict *" to the set of 7314 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7315 /// false otherwise. 7316 /// 7317 /// FIXME: what to do about extended qualifiers? 7318 bool 7319 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7320 const Qualifiers &VisibleQuals) { 7321 7322 // Insert this type. 7323 if (!PointerTypes.insert(Ty)) 7324 return false; 7325 7326 QualType PointeeTy; 7327 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7328 bool buildObjCPtr = false; 7329 if (!PointerTy) { 7330 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7331 PointeeTy = PTy->getPointeeType(); 7332 buildObjCPtr = true; 7333 } else { 7334 PointeeTy = PointerTy->getPointeeType(); 7335 } 7336 7337 // Don't add qualified variants of arrays. For one, they're not allowed 7338 // (the qualifier would sink to the element type), and for another, the 7339 // only overload situation where it matters is subscript or pointer +- int, 7340 // and those shouldn't have qualifier variants anyway. 7341 if (PointeeTy->isArrayType()) 7342 return true; 7343 7344 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7345 bool hasVolatile = VisibleQuals.hasVolatile(); 7346 bool hasRestrict = VisibleQuals.hasRestrict(); 7347 7348 // Iterate through all strict supersets of BaseCVR. 7349 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7350 if ((CVR | BaseCVR) != CVR) continue; 7351 // Skip over volatile if no volatile found anywhere in the types. 7352 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7353 7354 // Skip over restrict if no restrict found anywhere in the types, or if 7355 // the type cannot be restrict-qualified. 7356 if ((CVR & Qualifiers::Restrict) && 7357 (!hasRestrict || 7358 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7359 continue; 7360 7361 // Build qualified pointee type. 7362 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7363 7364 // Build qualified pointer type. 7365 QualType QPointerTy; 7366 if (!buildObjCPtr) 7367 QPointerTy = Context.getPointerType(QPointeeTy); 7368 else 7369 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7370 7371 // Insert qualified pointer type. 7372 PointerTypes.insert(QPointerTy); 7373 } 7374 7375 return true; 7376 } 7377 7378 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7379 /// to the set of pointer types along with any more-qualified variants of 7380 /// that type. For example, if @p Ty is "int const *", this routine 7381 /// will add "int const *", "int const volatile *", "int const 7382 /// restrict *", and "int const volatile restrict *" to the set of 7383 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7384 /// false otherwise. 7385 /// 7386 /// FIXME: what to do about extended qualifiers? 7387 bool 7388 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7389 QualType Ty) { 7390 // Insert this type. 7391 if (!MemberPointerTypes.insert(Ty)) 7392 return false; 7393 7394 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7395 assert(PointerTy && "type was not a member pointer type!"); 7396 7397 QualType PointeeTy = PointerTy->getPointeeType(); 7398 // Don't add qualified variants of arrays. For one, they're not allowed 7399 // (the qualifier would sink to the element type), and for another, the 7400 // only overload situation where it matters is subscript or pointer +- int, 7401 // and those shouldn't have qualifier variants anyway. 7402 if (PointeeTy->isArrayType()) 7403 return true; 7404 const Type *ClassTy = PointerTy->getClass(); 7405 7406 // Iterate through all strict supersets of the pointee type's CVR 7407 // qualifiers. 7408 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7409 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7410 if ((CVR | BaseCVR) != CVR) continue; 7411 7412 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7413 MemberPointerTypes.insert( 7414 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7415 } 7416 7417 return true; 7418 } 7419 7420 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7421 /// Ty can be implicit converted to the given set of @p Types. We're 7422 /// primarily interested in pointer types and enumeration types. We also 7423 /// take member pointer types, for the conditional operator. 7424 /// AllowUserConversions is true if we should look at the conversion 7425 /// functions of a class type, and AllowExplicitConversions if we 7426 /// should also include the explicit conversion functions of a class 7427 /// type. 7428 void 7429 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7430 SourceLocation Loc, 7431 bool AllowUserConversions, 7432 bool AllowExplicitConversions, 7433 const Qualifiers &VisibleQuals) { 7434 // Only deal with canonical types. 7435 Ty = Context.getCanonicalType(Ty); 7436 7437 // Look through reference types; they aren't part of the type of an 7438 // expression for the purposes of conversions. 7439 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7440 Ty = RefTy->getPointeeType(); 7441 7442 // If we're dealing with an array type, decay to the pointer. 7443 if (Ty->isArrayType()) 7444 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7445 7446 // Otherwise, we don't care about qualifiers on the type. 7447 Ty = Ty.getLocalUnqualifiedType(); 7448 7449 // Flag if we ever add a non-record type. 7450 const RecordType *TyRec = Ty->getAs<RecordType>(); 7451 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7452 7453 // Flag if we encounter an arithmetic type. 7454 HasArithmeticOrEnumeralTypes = 7455 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7456 7457 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7458 PointerTypes.insert(Ty); 7459 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7460 // Insert our type, and its more-qualified variants, into the set 7461 // of types. 7462 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7463 return; 7464 } else if (Ty->isMemberPointerType()) { 7465 // Member pointers are far easier, since the pointee can't be converted. 7466 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7467 return; 7468 } else if (Ty->isEnumeralType()) { 7469 HasArithmeticOrEnumeralTypes = true; 7470 EnumerationTypes.insert(Ty); 7471 } else if (Ty->isVectorType()) { 7472 // We treat vector types as arithmetic types in many contexts as an 7473 // extension. 7474 HasArithmeticOrEnumeralTypes = true; 7475 VectorTypes.insert(Ty); 7476 } else if (Ty->isNullPtrType()) { 7477 HasNullPtrType = true; 7478 } else if (AllowUserConversions && TyRec) { 7479 // No conversion functions in incomplete types. 7480 if (!SemaRef.isCompleteType(Loc, Ty)) 7481 return; 7482 7483 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7484 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7485 if (isa<UsingShadowDecl>(D)) 7486 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7487 7488 // Skip conversion function templates; they don't tell us anything 7489 // about which builtin types we can convert to. 7490 if (isa<FunctionTemplateDecl>(D)) 7491 continue; 7492 7493 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7494 if (AllowExplicitConversions || !Conv->isExplicit()) { 7495 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7496 VisibleQuals); 7497 } 7498 } 7499 } 7500 } 7501 7502 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7503 /// the volatile- and non-volatile-qualified assignment operators for the 7504 /// given type to the candidate set. 7505 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7506 QualType T, 7507 ArrayRef<Expr *> Args, 7508 OverloadCandidateSet &CandidateSet) { 7509 QualType ParamTypes[2]; 7510 7511 // T& operator=(T&, T) 7512 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7513 ParamTypes[1] = T; 7514 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7515 /*IsAssignmentOperator=*/true); 7516 7517 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7518 // volatile T& operator=(volatile T&, T) 7519 ParamTypes[0] 7520 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7521 ParamTypes[1] = T; 7522 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7523 /*IsAssignmentOperator=*/true); 7524 } 7525 } 7526 7527 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7528 /// if any, found in visible type conversion functions found in ArgExpr's type. 7529 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7530 Qualifiers VRQuals; 7531 const RecordType *TyRec; 7532 if (const MemberPointerType *RHSMPType = 7533 ArgExpr->getType()->getAs<MemberPointerType>()) 7534 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7535 else 7536 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7537 if (!TyRec) { 7538 // Just to be safe, assume the worst case. 7539 VRQuals.addVolatile(); 7540 VRQuals.addRestrict(); 7541 return VRQuals; 7542 } 7543 7544 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7545 if (!ClassDecl->hasDefinition()) 7546 return VRQuals; 7547 7548 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7549 if (isa<UsingShadowDecl>(D)) 7550 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7551 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7552 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7553 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7554 CanTy = ResTypeRef->getPointeeType(); 7555 // Need to go down the pointer/mempointer chain and add qualifiers 7556 // as see them. 7557 bool done = false; 7558 while (!done) { 7559 if (CanTy.isRestrictQualified()) 7560 VRQuals.addRestrict(); 7561 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7562 CanTy = ResTypePtr->getPointeeType(); 7563 else if (const MemberPointerType *ResTypeMPtr = 7564 CanTy->getAs<MemberPointerType>()) 7565 CanTy = ResTypeMPtr->getPointeeType(); 7566 else 7567 done = true; 7568 if (CanTy.isVolatileQualified()) 7569 VRQuals.addVolatile(); 7570 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7571 return VRQuals; 7572 } 7573 } 7574 } 7575 return VRQuals; 7576 } 7577 7578 namespace { 7579 7580 /// \brief Helper class to manage the addition of builtin operator overload 7581 /// candidates. It provides shared state and utility methods used throughout 7582 /// the process, as well as a helper method to add each group of builtin 7583 /// operator overloads from the standard to a candidate set. 7584 class BuiltinOperatorOverloadBuilder { 7585 // Common instance state available to all overload candidate addition methods. 7586 Sema &S; 7587 ArrayRef<Expr *> Args; 7588 Qualifiers VisibleTypeConversionsQuals; 7589 bool HasArithmeticOrEnumeralCandidateType; 7590 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7591 OverloadCandidateSet &CandidateSet; 7592 7593 // Define some constants used to index and iterate over the arithemetic types 7594 // provided via the getArithmeticType() method below. 7595 // The "promoted arithmetic types" are the arithmetic 7596 // types are that preserved by promotion (C++ [over.built]p2). 7597 static const unsigned FirstIntegralType = 4; 7598 static const unsigned LastIntegralType = 21; 7599 static const unsigned FirstPromotedIntegralType = 4, 7600 LastPromotedIntegralType = 12; 7601 static const unsigned FirstPromotedArithmeticType = 0, 7602 LastPromotedArithmeticType = 12; 7603 static const unsigned NumArithmeticTypes = 21; 7604 7605 /// \brief Get the canonical type for a given arithmetic type index. 7606 CanQualType getArithmeticType(unsigned index) { 7607 assert(index < NumArithmeticTypes); 7608 static CanQualType ASTContext::* const 7609 ArithmeticTypes[NumArithmeticTypes] = { 7610 // Start of promoted types. 7611 &ASTContext::FloatTy, 7612 &ASTContext::DoubleTy, 7613 &ASTContext::LongDoubleTy, 7614 &ASTContext::Float128Ty, 7615 7616 // Start of integral types. 7617 &ASTContext::IntTy, 7618 &ASTContext::LongTy, 7619 &ASTContext::LongLongTy, 7620 &ASTContext::Int128Ty, 7621 &ASTContext::UnsignedIntTy, 7622 &ASTContext::UnsignedLongTy, 7623 &ASTContext::UnsignedLongLongTy, 7624 &ASTContext::UnsignedInt128Ty, 7625 // End of promoted types. 7626 7627 &ASTContext::BoolTy, 7628 &ASTContext::CharTy, 7629 &ASTContext::WCharTy, 7630 &ASTContext::Char16Ty, 7631 &ASTContext::Char32Ty, 7632 &ASTContext::SignedCharTy, 7633 &ASTContext::ShortTy, 7634 &ASTContext::UnsignedCharTy, 7635 &ASTContext::UnsignedShortTy, 7636 // End of integral types. 7637 // FIXME: What about complex? What about half? 7638 }; 7639 return S.Context.*ArithmeticTypes[index]; 7640 } 7641 7642 /// \brief Gets the canonical type resulting from the usual arithemetic 7643 /// converions for the given arithmetic types. 7644 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7645 // Accelerator table for performing the usual arithmetic conversions. 7646 // The rules are basically: 7647 // - if either is floating-point, use the wider floating-point 7648 // - if same signedness, use the higher rank 7649 // - if same size, use unsigned of the higher rank 7650 // - use the larger type 7651 // These rules, together with the axiom that higher ranks are 7652 // never smaller, are sufficient to precompute all of these results 7653 // *except* when dealing with signed types of higher rank. 7654 // (we could precompute SLL x UI for all known platforms, but it's 7655 // better not to make any assumptions). 7656 // We assume that int128 has a higher rank than long long on all platforms. 7657 enum PromotedType : int8_t { 7658 Dep=-1, 7659 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7660 }; 7661 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7662 [LastPromotedArithmeticType] = { 7663 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7664 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7665 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7666 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7667 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7668 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7669 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7670 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7671 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7672 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7673 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7674 }; 7675 7676 assert(L < LastPromotedArithmeticType); 7677 assert(R < LastPromotedArithmeticType); 7678 int Idx = ConversionsTable[L][R]; 7679 7680 // Fast path: the table gives us a concrete answer. 7681 if (Idx != Dep) return getArithmeticType(Idx); 7682 7683 // Slow path: we need to compare widths. 7684 // An invariant is that the signed type has higher rank. 7685 CanQualType LT = getArithmeticType(L), 7686 RT = getArithmeticType(R); 7687 unsigned LW = S.Context.getIntWidth(LT), 7688 RW = S.Context.getIntWidth(RT); 7689 7690 // If they're different widths, use the signed type. 7691 if (LW > RW) return LT; 7692 else if (LW < RW) return RT; 7693 7694 // Otherwise, use the unsigned type of the signed type's rank. 7695 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7696 assert(L == SLL || R == SLL); 7697 return S.Context.UnsignedLongLongTy; 7698 } 7699 7700 /// \brief Helper method to factor out the common pattern of adding overloads 7701 /// for '++' and '--' builtin operators. 7702 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7703 bool HasVolatile, 7704 bool HasRestrict) { 7705 QualType ParamTypes[2] = { 7706 S.Context.getLValueReferenceType(CandidateTy), 7707 S.Context.IntTy 7708 }; 7709 7710 // Non-volatile version. 7711 if (Args.size() == 1) 7712 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7713 else 7714 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7715 7716 // Use a heuristic to reduce number of builtin candidates in the set: 7717 // add volatile version only if there are conversions to a volatile type. 7718 if (HasVolatile) { 7719 ParamTypes[0] = 7720 S.Context.getLValueReferenceType( 7721 S.Context.getVolatileType(CandidateTy)); 7722 if (Args.size() == 1) 7723 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7724 else 7725 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7726 } 7727 7728 // Add restrict version only if there are conversions to a restrict type 7729 // and our candidate type is a non-restrict-qualified pointer. 7730 if (HasRestrict && CandidateTy->isAnyPointerType() && 7731 !CandidateTy.isRestrictQualified()) { 7732 ParamTypes[0] 7733 = S.Context.getLValueReferenceType( 7734 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7735 if (Args.size() == 1) 7736 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7737 else 7738 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7739 7740 if (HasVolatile) { 7741 ParamTypes[0] 7742 = S.Context.getLValueReferenceType( 7743 S.Context.getCVRQualifiedType(CandidateTy, 7744 (Qualifiers::Volatile | 7745 Qualifiers::Restrict))); 7746 if (Args.size() == 1) 7747 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7748 else 7749 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7750 } 7751 } 7752 7753 } 7754 7755 public: 7756 BuiltinOperatorOverloadBuilder( 7757 Sema &S, ArrayRef<Expr *> Args, 7758 Qualifiers VisibleTypeConversionsQuals, 7759 bool HasArithmeticOrEnumeralCandidateType, 7760 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7761 OverloadCandidateSet &CandidateSet) 7762 : S(S), Args(Args), 7763 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7764 HasArithmeticOrEnumeralCandidateType( 7765 HasArithmeticOrEnumeralCandidateType), 7766 CandidateTypes(CandidateTypes), 7767 CandidateSet(CandidateSet) { 7768 // Validate some of our static helper constants in debug builds. 7769 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7770 "Invalid first promoted integral type"); 7771 assert(getArithmeticType(LastPromotedIntegralType - 1) 7772 == S.Context.UnsignedInt128Ty && 7773 "Invalid last promoted integral type"); 7774 assert(getArithmeticType(FirstPromotedArithmeticType) 7775 == S.Context.FloatTy && 7776 "Invalid first promoted arithmetic type"); 7777 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7778 == S.Context.UnsignedInt128Ty && 7779 "Invalid last promoted arithmetic type"); 7780 } 7781 7782 // C++ [over.built]p3: 7783 // 7784 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7785 // is either volatile or empty, there exist candidate operator 7786 // functions of the form 7787 // 7788 // VQ T& operator++(VQ T&); 7789 // T operator++(VQ T&, int); 7790 // 7791 // C++ [over.built]p4: 7792 // 7793 // For every pair (T, VQ), where T is an arithmetic type other 7794 // than bool, and VQ is either volatile or empty, there exist 7795 // candidate operator functions of the form 7796 // 7797 // VQ T& operator--(VQ T&); 7798 // T operator--(VQ T&, int); 7799 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7800 if (!HasArithmeticOrEnumeralCandidateType) 7801 return; 7802 7803 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7804 Arith < NumArithmeticTypes; ++Arith) { 7805 addPlusPlusMinusMinusStyleOverloads( 7806 getArithmeticType(Arith), 7807 VisibleTypeConversionsQuals.hasVolatile(), 7808 VisibleTypeConversionsQuals.hasRestrict()); 7809 } 7810 } 7811 7812 // C++ [over.built]p5: 7813 // 7814 // For every pair (T, VQ), where T is a cv-qualified or 7815 // cv-unqualified object type, and VQ is either volatile or 7816 // empty, there exist candidate operator functions of the form 7817 // 7818 // T*VQ& operator++(T*VQ&); 7819 // T*VQ& operator--(T*VQ&); 7820 // T* operator++(T*VQ&, int); 7821 // T* operator--(T*VQ&, int); 7822 void addPlusPlusMinusMinusPointerOverloads() { 7823 for (BuiltinCandidateTypeSet::iterator 7824 Ptr = CandidateTypes[0].pointer_begin(), 7825 PtrEnd = CandidateTypes[0].pointer_end(); 7826 Ptr != PtrEnd; ++Ptr) { 7827 // Skip pointer types that aren't pointers to object types. 7828 if (!(*Ptr)->getPointeeType()->isObjectType()) 7829 continue; 7830 7831 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7832 (!(*Ptr).isVolatileQualified() && 7833 VisibleTypeConversionsQuals.hasVolatile()), 7834 (!(*Ptr).isRestrictQualified() && 7835 VisibleTypeConversionsQuals.hasRestrict())); 7836 } 7837 } 7838 7839 // C++ [over.built]p6: 7840 // For every cv-qualified or cv-unqualified object type T, there 7841 // exist candidate operator functions of the form 7842 // 7843 // T& operator*(T*); 7844 // 7845 // C++ [over.built]p7: 7846 // For every function type T that does not have cv-qualifiers or a 7847 // ref-qualifier, there exist candidate operator functions of the form 7848 // T& operator*(T*); 7849 void addUnaryStarPointerOverloads() { 7850 for (BuiltinCandidateTypeSet::iterator 7851 Ptr = CandidateTypes[0].pointer_begin(), 7852 PtrEnd = CandidateTypes[0].pointer_end(); 7853 Ptr != PtrEnd; ++Ptr) { 7854 QualType ParamTy = *Ptr; 7855 QualType PointeeTy = ParamTy->getPointeeType(); 7856 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7857 continue; 7858 7859 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7860 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7861 continue; 7862 7863 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7864 &ParamTy, Args, CandidateSet); 7865 } 7866 } 7867 7868 // C++ [over.built]p9: 7869 // For every promoted arithmetic type T, there exist candidate 7870 // operator functions of the form 7871 // 7872 // T operator+(T); 7873 // T operator-(T); 7874 void addUnaryPlusOrMinusArithmeticOverloads() { 7875 if (!HasArithmeticOrEnumeralCandidateType) 7876 return; 7877 7878 for (unsigned Arith = FirstPromotedArithmeticType; 7879 Arith < LastPromotedArithmeticType; ++Arith) { 7880 QualType ArithTy = getArithmeticType(Arith); 7881 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7882 } 7883 7884 // Extension: We also add these operators for vector types. 7885 for (BuiltinCandidateTypeSet::iterator 7886 Vec = CandidateTypes[0].vector_begin(), 7887 VecEnd = CandidateTypes[0].vector_end(); 7888 Vec != VecEnd; ++Vec) { 7889 QualType VecTy = *Vec; 7890 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7891 } 7892 } 7893 7894 // C++ [over.built]p8: 7895 // For every type T, there exist candidate operator functions of 7896 // the form 7897 // 7898 // T* operator+(T*); 7899 void addUnaryPlusPointerOverloads() { 7900 for (BuiltinCandidateTypeSet::iterator 7901 Ptr = CandidateTypes[0].pointer_begin(), 7902 PtrEnd = CandidateTypes[0].pointer_end(); 7903 Ptr != PtrEnd; ++Ptr) { 7904 QualType ParamTy = *Ptr; 7905 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7906 } 7907 } 7908 7909 // C++ [over.built]p10: 7910 // For every promoted integral type T, there exist candidate 7911 // operator functions of the form 7912 // 7913 // T operator~(T); 7914 void addUnaryTildePromotedIntegralOverloads() { 7915 if (!HasArithmeticOrEnumeralCandidateType) 7916 return; 7917 7918 for (unsigned Int = FirstPromotedIntegralType; 7919 Int < LastPromotedIntegralType; ++Int) { 7920 QualType IntTy = getArithmeticType(Int); 7921 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7922 } 7923 7924 // Extension: We also add this operator for vector types. 7925 for (BuiltinCandidateTypeSet::iterator 7926 Vec = CandidateTypes[0].vector_begin(), 7927 VecEnd = CandidateTypes[0].vector_end(); 7928 Vec != VecEnd; ++Vec) { 7929 QualType VecTy = *Vec; 7930 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7931 } 7932 } 7933 7934 // C++ [over.match.oper]p16: 7935 // For every pointer to member type T or type std::nullptr_t, there 7936 // exist candidate operator functions of the form 7937 // 7938 // bool operator==(T,T); 7939 // bool operator!=(T,T); 7940 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 7941 /// Set of (canonical) types that we've already handled. 7942 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7943 7944 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7945 for (BuiltinCandidateTypeSet::iterator 7946 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7947 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7948 MemPtr != MemPtrEnd; 7949 ++MemPtr) { 7950 // Don't add the same builtin candidate twice. 7951 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7952 continue; 7953 7954 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7955 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7956 } 7957 7958 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7959 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7960 if (AddedTypes.insert(NullPtrTy).second) { 7961 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7962 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7963 CandidateSet); 7964 } 7965 } 7966 } 7967 } 7968 7969 // C++ [over.built]p15: 7970 // 7971 // For every T, where T is an enumeration type or a pointer type, 7972 // there exist candidate operator functions of the form 7973 // 7974 // bool operator<(T, T); 7975 // bool operator>(T, T); 7976 // bool operator<=(T, T); 7977 // bool operator>=(T, T); 7978 // bool operator==(T, T); 7979 // bool operator!=(T, T); 7980 void addRelationalPointerOrEnumeralOverloads() { 7981 // C++ [over.match.oper]p3: 7982 // [...]the built-in candidates include all of the candidate operator 7983 // functions defined in 13.6 that, compared to the given operator, [...] 7984 // do not have the same parameter-type-list as any non-template non-member 7985 // candidate. 7986 // 7987 // Note that in practice, this only affects enumeration types because there 7988 // aren't any built-in candidates of record type, and a user-defined operator 7989 // must have an operand of record or enumeration type. Also, the only other 7990 // overloaded operator with enumeration arguments, operator=, 7991 // cannot be overloaded for enumeration types, so this is the only place 7992 // where we must suppress candidates like this. 7993 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7994 UserDefinedBinaryOperators; 7995 7996 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7997 if (CandidateTypes[ArgIdx].enumeration_begin() != 7998 CandidateTypes[ArgIdx].enumeration_end()) { 7999 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8000 CEnd = CandidateSet.end(); 8001 C != CEnd; ++C) { 8002 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8003 continue; 8004 8005 if (C->Function->isFunctionTemplateSpecialization()) 8006 continue; 8007 8008 QualType FirstParamType = 8009 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 8010 QualType SecondParamType = 8011 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 8012 8013 // Skip if either parameter isn't of enumeral type. 8014 if (!FirstParamType->isEnumeralType() || 8015 !SecondParamType->isEnumeralType()) 8016 continue; 8017 8018 // Add this operator to the set of known user-defined operators. 8019 UserDefinedBinaryOperators.insert( 8020 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8021 S.Context.getCanonicalType(SecondParamType))); 8022 } 8023 } 8024 } 8025 8026 /// Set of (canonical) types that we've already handled. 8027 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8028 8029 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8030 for (BuiltinCandidateTypeSet::iterator 8031 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8032 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8033 Ptr != PtrEnd; ++Ptr) { 8034 // Don't add the same builtin candidate twice. 8035 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8036 continue; 8037 8038 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8039 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 8040 } 8041 for (BuiltinCandidateTypeSet::iterator 8042 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8043 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8044 Enum != EnumEnd; ++Enum) { 8045 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8046 8047 // Don't add the same builtin candidate twice, or if a user defined 8048 // candidate exists. 8049 if (!AddedTypes.insert(CanonType).second || 8050 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8051 CanonType))) 8052 continue; 8053 8054 QualType ParamTypes[2] = { *Enum, *Enum }; 8055 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 8056 } 8057 } 8058 } 8059 8060 // C++ [over.built]p13: 8061 // 8062 // For every cv-qualified or cv-unqualified object type T 8063 // there exist candidate operator functions of the form 8064 // 8065 // T* operator+(T*, ptrdiff_t); 8066 // T& operator[](T*, ptrdiff_t); [BELOW] 8067 // T* operator-(T*, ptrdiff_t); 8068 // T* operator+(ptrdiff_t, T*); 8069 // T& operator[](ptrdiff_t, T*); [BELOW] 8070 // 8071 // C++ [over.built]p14: 8072 // 8073 // For every T, where T is a pointer to object type, there 8074 // exist candidate operator functions of the form 8075 // 8076 // ptrdiff_t operator-(T, T); 8077 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8078 /// Set of (canonical) types that we've already handled. 8079 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8080 8081 for (int Arg = 0; Arg < 2; ++Arg) { 8082 QualType AsymmetricParamTypes[2] = { 8083 S.Context.getPointerDiffType(), 8084 S.Context.getPointerDiffType(), 8085 }; 8086 for (BuiltinCandidateTypeSet::iterator 8087 Ptr = CandidateTypes[Arg].pointer_begin(), 8088 PtrEnd = CandidateTypes[Arg].pointer_end(); 8089 Ptr != PtrEnd; ++Ptr) { 8090 QualType PointeeTy = (*Ptr)->getPointeeType(); 8091 if (!PointeeTy->isObjectType()) 8092 continue; 8093 8094 AsymmetricParamTypes[Arg] = *Ptr; 8095 if (Arg == 0 || Op == OO_Plus) { 8096 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8097 // T* operator+(ptrdiff_t, T*); 8098 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 8099 } 8100 if (Op == OO_Minus) { 8101 // ptrdiff_t operator-(T, T); 8102 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8103 continue; 8104 8105 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8106 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 8107 Args, CandidateSet); 8108 } 8109 } 8110 } 8111 } 8112 8113 // C++ [over.built]p12: 8114 // 8115 // For every pair of promoted arithmetic types L and R, there 8116 // exist candidate operator functions of the form 8117 // 8118 // LR operator*(L, R); 8119 // LR operator/(L, R); 8120 // LR operator+(L, R); 8121 // LR operator-(L, R); 8122 // bool operator<(L, R); 8123 // bool operator>(L, R); 8124 // bool operator<=(L, R); 8125 // bool operator>=(L, R); 8126 // bool operator==(L, R); 8127 // bool operator!=(L, R); 8128 // 8129 // where LR is the result of the usual arithmetic conversions 8130 // between types L and R. 8131 // 8132 // C++ [over.built]p24: 8133 // 8134 // For every pair of promoted arithmetic types L and R, there exist 8135 // candidate operator functions of the form 8136 // 8137 // LR operator?(bool, L, R); 8138 // 8139 // where LR is the result of the usual arithmetic conversions 8140 // between types L and R. 8141 // Our candidates ignore the first parameter. 8142 void addGenericBinaryArithmeticOverloads(bool isComparison) { 8143 if (!HasArithmeticOrEnumeralCandidateType) 8144 return; 8145 8146 for (unsigned Left = FirstPromotedArithmeticType; 8147 Left < LastPromotedArithmeticType; ++Left) { 8148 for (unsigned Right = FirstPromotedArithmeticType; 8149 Right < LastPromotedArithmeticType; ++Right) { 8150 QualType LandR[2] = { getArithmeticType(Left), 8151 getArithmeticType(Right) }; 8152 QualType Result = 8153 isComparison ? S.Context.BoolTy 8154 : getUsualArithmeticConversions(Left, Right); 8155 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 8156 } 8157 } 8158 8159 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8160 // conditional operator for vector types. 8161 for (BuiltinCandidateTypeSet::iterator 8162 Vec1 = CandidateTypes[0].vector_begin(), 8163 Vec1End = CandidateTypes[0].vector_end(); 8164 Vec1 != Vec1End; ++Vec1) { 8165 for (BuiltinCandidateTypeSet::iterator 8166 Vec2 = CandidateTypes[1].vector_begin(), 8167 Vec2End = CandidateTypes[1].vector_end(); 8168 Vec2 != Vec2End; ++Vec2) { 8169 QualType LandR[2] = { *Vec1, *Vec2 }; 8170 QualType Result = S.Context.BoolTy; 8171 if (!isComparison) { 8172 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 8173 Result = *Vec1; 8174 else 8175 Result = *Vec2; 8176 } 8177 8178 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 8179 } 8180 } 8181 } 8182 8183 // C++ [over.built]p17: 8184 // 8185 // For every pair of promoted integral types L and R, there 8186 // exist candidate operator functions of the form 8187 // 8188 // LR operator%(L, R); 8189 // LR operator&(L, R); 8190 // LR operator^(L, R); 8191 // LR operator|(L, R); 8192 // L operator<<(L, R); 8193 // L operator>>(L, R); 8194 // 8195 // where LR is the result of the usual arithmetic conversions 8196 // between types L and R. 8197 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8198 if (!HasArithmeticOrEnumeralCandidateType) 8199 return; 8200 8201 for (unsigned Left = FirstPromotedIntegralType; 8202 Left < LastPromotedIntegralType; ++Left) { 8203 for (unsigned Right = FirstPromotedIntegralType; 8204 Right < LastPromotedIntegralType; ++Right) { 8205 QualType LandR[2] = { getArithmeticType(Left), 8206 getArithmeticType(Right) }; 8207 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 8208 ? LandR[0] 8209 : getUsualArithmeticConversions(Left, Right); 8210 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 8211 } 8212 } 8213 } 8214 8215 // C++ [over.built]p20: 8216 // 8217 // For every pair (T, VQ), where T is an enumeration or 8218 // pointer to member type and VQ is either volatile or 8219 // empty, there exist candidate operator functions of the form 8220 // 8221 // VQ T& operator=(VQ T&, T); 8222 void addAssignmentMemberPointerOrEnumeralOverloads() { 8223 /// Set of (canonical) types that we've already handled. 8224 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8225 8226 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8227 for (BuiltinCandidateTypeSet::iterator 8228 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8229 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8230 Enum != EnumEnd; ++Enum) { 8231 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8232 continue; 8233 8234 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8235 } 8236 8237 for (BuiltinCandidateTypeSet::iterator 8238 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8239 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8240 MemPtr != MemPtrEnd; ++MemPtr) { 8241 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8242 continue; 8243 8244 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8245 } 8246 } 8247 } 8248 8249 // C++ [over.built]p19: 8250 // 8251 // For every pair (T, VQ), where T is any type and VQ is either 8252 // volatile or empty, there exist candidate operator functions 8253 // of the form 8254 // 8255 // T*VQ& operator=(T*VQ&, T*); 8256 // 8257 // C++ [over.built]p21: 8258 // 8259 // For every pair (T, VQ), where T is a cv-qualified or 8260 // cv-unqualified object type and VQ is either volatile or 8261 // empty, there exist candidate operator functions of the form 8262 // 8263 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8264 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8265 void addAssignmentPointerOverloads(bool isEqualOp) { 8266 /// Set of (canonical) types that we've already handled. 8267 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8268 8269 for (BuiltinCandidateTypeSet::iterator 8270 Ptr = CandidateTypes[0].pointer_begin(), 8271 PtrEnd = CandidateTypes[0].pointer_end(); 8272 Ptr != PtrEnd; ++Ptr) { 8273 // If this is operator=, keep track of the builtin candidates we added. 8274 if (isEqualOp) 8275 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8276 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8277 continue; 8278 8279 // non-volatile version 8280 QualType ParamTypes[2] = { 8281 S.Context.getLValueReferenceType(*Ptr), 8282 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8283 }; 8284 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8285 /*IsAssigmentOperator=*/ isEqualOp); 8286 8287 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8288 VisibleTypeConversionsQuals.hasVolatile(); 8289 if (NeedVolatile) { 8290 // volatile version 8291 ParamTypes[0] = 8292 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8293 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8294 /*IsAssigmentOperator=*/isEqualOp); 8295 } 8296 8297 if (!(*Ptr).isRestrictQualified() && 8298 VisibleTypeConversionsQuals.hasRestrict()) { 8299 // restrict version 8300 ParamTypes[0] 8301 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8302 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8303 /*IsAssigmentOperator=*/isEqualOp); 8304 8305 if (NeedVolatile) { 8306 // volatile restrict version 8307 ParamTypes[0] 8308 = S.Context.getLValueReferenceType( 8309 S.Context.getCVRQualifiedType(*Ptr, 8310 (Qualifiers::Volatile | 8311 Qualifiers::Restrict))); 8312 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8313 /*IsAssigmentOperator=*/isEqualOp); 8314 } 8315 } 8316 } 8317 8318 if (isEqualOp) { 8319 for (BuiltinCandidateTypeSet::iterator 8320 Ptr = CandidateTypes[1].pointer_begin(), 8321 PtrEnd = CandidateTypes[1].pointer_end(); 8322 Ptr != PtrEnd; ++Ptr) { 8323 // Make sure we don't add the same candidate twice. 8324 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8325 continue; 8326 8327 QualType ParamTypes[2] = { 8328 S.Context.getLValueReferenceType(*Ptr), 8329 *Ptr, 8330 }; 8331 8332 // non-volatile version 8333 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8334 /*IsAssigmentOperator=*/true); 8335 8336 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8337 VisibleTypeConversionsQuals.hasVolatile(); 8338 if (NeedVolatile) { 8339 // volatile version 8340 ParamTypes[0] = 8341 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8342 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8343 /*IsAssigmentOperator=*/true); 8344 } 8345 8346 if (!(*Ptr).isRestrictQualified() && 8347 VisibleTypeConversionsQuals.hasRestrict()) { 8348 // restrict version 8349 ParamTypes[0] 8350 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8351 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8352 /*IsAssigmentOperator=*/true); 8353 8354 if (NeedVolatile) { 8355 // volatile restrict version 8356 ParamTypes[0] 8357 = S.Context.getLValueReferenceType( 8358 S.Context.getCVRQualifiedType(*Ptr, 8359 (Qualifiers::Volatile | 8360 Qualifiers::Restrict))); 8361 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8362 /*IsAssigmentOperator=*/true); 8363 } 8364 } 8365 } 8366 } 8367 } 8368 8369 // C++ [over.built]p18: 8370 // 8371 // For every triple (L, VQ, R), where L is an arithmetic type, 8372 // VQ is either volatile or empty, and R is a promoted 8373 // arithmetic type, there exist candidate operator functions of 8374 // the form 8375 // 8376 // VQ L& operator=(VQ L&, R); 8377 // VQ L& operator*=(VQ L&, R); 8378 // VQ L& operator/=(VQ L&, R); 8379 // VQ L& operator+=(VQ L&, R); 8380 // VQ L& operator-=(VQ L&, R); 8381 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8382 if (!HasArithmeticOrEnumeralCandidateType) 8383 return; 8384 8385 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8386 for (unsigned Right = FirstPromotedArithmeticType; 8387 Right < LastPromotedArithmeticType; ++Right) { 8388 QualType ParamTypes[2]; 8389 ParamTypes[1] = getArithmeticType(Right); 8390 8391 // Add this built-in operator as a candidate (VQ is empty). 8392 ParamTypes[0] = 8393 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8394 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8395 /*IsAssigmentOperator=*/isEqualOp); 8396 8397 // Add this built-in operator as a candidate (VQ is 'volatile'). 8398 if (VisibleTypeConversionsQuals.hasVolatile()) { 8399 ParamTypes[0] = 8400 S.Context.getVolatileType(getArithmeticType(Left)); 8401 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8402 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8403 /*IsAssigmentOperator=*/isEqualOp); 8404 } 8405 } 8406 } 8407 8408 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8409 for (BuiltinCandidateTypeSet::iterator 8410 Vec1 = CandidateTypes[0].vector_begin(), 8411 Vec1End = CandidateTypes[0].vector_end(); 8412 Vec1 != Vec1End; ++Vec1) { 8413 for (BuiltinCandidateTypeSet::iterator 8414 Vec2 = CandidateTypes[1].vector_begin(), 8415 Vec2End = CandidateTypes[1].vector_end(); 8416 Vec2 != Vec2End; ++Vec2) { 8417 QualType ParamTypes[2]; 8418 ParamTypes[1] = *Vec2; 8419 // Add this built-in operator as a candidate (VQ is empty). 8420 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8421 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8422 /*IsAssigmentOperator=*/isEqualOp); 8423 8424 // Add this built-in operator as a candidate (VQ is 'volatile'). 8425 if (VisibleTypeConversionsQuals.hasVolatile()) { 8426 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8427 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8428 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8429 /*IsAssigmentOperator=*/isEqualOp); 8430 } 8431 } 8432 } 8433 } 8434 8435 // C++ [over.built]p22: 8436 // 8437 // For every triple (L, VQ, R), where L is an integral type, VQ 8438 // is either volatile or empty, and R is a promoted integral 8439 // type, there exist candidate operator functions of the form 8440 // 8441 // VQ L& operator%=(VQ L&, R); 8442 // VQ L& operator<<=(VQ L&, R); 8443 // VQ L& operator>>=(VQ L&, R); 8444 // VQ L& operator&=(VQ L&, R); 8445 // VQ L& operator^=(VQ L&, R); 8446 // VQ L& operator|=(VQ L&, R); 8447 void addAssignmentIntegralOverloads() { 8448 if (!HasArithmeticOrEnumeralCandidateType) 8449 return; 8450 8451 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8452 for (unsigned Right = FirstPromotedIntegralType; 8453 Right < LastPromotedIntegralType; ++Right) { 8454 QualType ParamTypes[2]; 8455 ParamTypes[1] = getArithmeticType(Right); 8456 8457 // Add this built-in operator as a candidate (VQ is empty). 8458 ParamTypes[0] = 8459 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8460 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8461 if (VisibleTypeConversionsQuals.hasVolatile()) { 8462 // Add this built-in operator as a candidate (VQ is 'volatile'). 8463 ParamTypes[0] = getArithmeticType(Left); 8464 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8465 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8466 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8467 } 8468 } 8469 } 8470 } 8471 8472 // C++ [over.operator]p23: 8473 // 8474 // There also exist candidate operator functions of the form 8475 // 8476 // bool operator!(bool); 8477 // bool operator&&(bool, bool); 8478 // bool operator||(bool, bool); 8479 void addExclaimOverload() { 8480 QualType ParamTy = S.Context.BoolTy; 8481 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8482 /*IsAssignmentOperator=*/false, 8483 /*NumContextualBoolArguments=*/1); 8484 } 8485 void addAmpAmpOrPipePipeOverload() { 8486 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8487 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8488 /*IsAssignmentOperator=*/false, 8489 /*NumContextualBoolArguments=*/2); 8490 } 8491 8492 // C++ [over.built]p13: 8493 // 8494 // For every cv-qualified or cv-unqualified object type T there 8495 // exist candidate operator functions of the form 8496 // 8497 // T* operator+(T*, ptrdiff_t); [ABOVE] 8498 // T& operator[](T*, ptrdiff_t); 8499 // T* operator-(T*, ptrdiff_t); [ABOVE] 8500 // T* operator+(ptrdiff_t, T*); [ABOVE] 8501 // T& operator[](ptrdiff_t, T*); 8502 void addSubscriptOverloads() { 8503 for (BuiltinCandidateTypeSet::iterator 8504 Ptr = CandidateTypes[0].pointer_begin(), 8505 PtrEnd = CandidateTypes[0].pointer_end(); 8506 Ptr != PtrEnd; ++Ptr) { 8507 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8508 QualType PointeeType = (*Ptr)->getPointeeType(); 8509 if (!PointeeType->isObjectType()) 8510 continue; 8511 8512 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8513 8514 // T& operator[](T*, ptrdiff_t) 8515 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8516 } 8517 8518 for (BuiltinCandidateTypeSet::iterator 8519 Ptr = CandidateTypes[1].pointer_begin(), 8520 PtrEnd = CandidateTypes[1].pointer_end(); 8521 Ptr != PtrEnd; ++Ptr) { 8522 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8523 QualType PointeeType = (*Ptr)->getPointeeType(); 8524 if (!PointeeType->isObjectType()) 8525 continue; 8526 8527 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8528 8529 // T& operator[](ptrdiff_t, T*) 8530 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8531 } 8532 } 8533 8534 // C++ [over.built]p11: 8535 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8536 // C1 is the same type as C2 or is a derived class of C2, T is an object 8537 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8538 // there exist candidate operator functions of the form 8539 // 8540 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8541 // 8542 // where CV12 is the union of CV1 and CV2. 8543 void addArrowStarOverloads() { 8544 for (BuiltinCandidateTypeSet::iterator 8545 Ptr = CandidateTypes[0].pointer_begin(), 8546 PtrEnd = CandidateTypes[0].pointer_end(); 8547 Ptr != PtrEnd; ++Ptr) { 8548 QualType C1Ty = (*Ptr); 8549 QualType C1; 8550 QualifierCollector Q1; 8551 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8552 if (!isa<RecordType>(C1)) 8553 continue; 8554 // heuristic to reduce number of builtin candidates in the set. 8555 // Add volatile/restrict version only if there are conversions to a 8556 // volatile/restrict type. 8557 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8558 continue; 8559 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8560 continue; 8561 for (BuiltinCandidateTypeSet::iterator 8562 MemPtr = CandidateTypes[1].member_pointer_begin(), 8563 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8564 MemPtr != MemPtrEnd; ++MemPtr) { 8565 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8566 QualType C2 = QualType(mptr->getClass(), 0); 8567 C2 = C2.getUnqualifiedType(); 8568 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8569 break; 8570 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8571 // build CV12 T& 8572 QualType T = mptr->getPointeeType(); 8573 if (!VisibleTypeConversionsQuals.hasVolatile() && 8574 T.isVolatileQualified()) 8575 continue; 8576 if (!VisibleTypeConversionsQuals.hasRestrict() && 8577 T.isRestrictQualified()) 8578 continue; 8579 T = Q1.apply(S.Context, T); 8580 QualType ResultTy = S.Context.getLValueReferenceType(T); 8581 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8582 } 8583 } 8584 } 8585 8586 // Note that we don't consider the first argument, since it has been 8587 // contextually converted to bool long ago. The candidates below are 8588 // therefore added as binary. 8589 // 8590 // C++ [over.built]p25: 8591 // For every type T, where T is a pointer, pointer-to-member, or scoped 8592 // enumeration type, there exist candidate operator functions of the form 8593 // 8594 // T operator?(bool, T, T); 8595 // 8596 void addConditionalOperatorOverloads() { 8597 /// Set of (canonical) types that we've already handled. 8598 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8599 8600 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8601 for (BuiltinCandidateTypeSet::iterator 8602 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8603 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8604 Ptr != PtrEnd; ++Ptr) { 8605 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8606 continue; 8607 8608 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8609 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8610 } 8611 8612 for (BuiltinCandidateTypeSet::iterator 8613 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8614 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8615 MemPtr != MemPtrEnd; ++MemPtr) { 8616 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8617 continue; 8618 8619 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8620 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8621 } 8622 8623 if (S.getLangOpts().CPlusPlus11) { 8624 for (BuiltinCandidateTypeSet::iterator 8625 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8626 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8627 Enum != EnumEnd; ++Enum) { 8628 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8629 continue; 8630 8631 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8632 continue; 8633 8634 QualType ParamTypes[2] = { *Enum, *Enum }; 8635 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8636 } 8637 } 8638 } 8639 } 8640 }; 8641 8642 } // end anonymous namespace 8643 8644 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8645 /// operator overloads to the candidate set (C++ [over.built]), based 8646 /// on the operator @p Op and the arguments given. For example, if the 8647 /// operator is a binary '+', this routine might add "int 8648 /// operator+(int, int)" to cover integer addition. 8649 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8650 SourceLocation OpLoc, 8651 ArrayRef<Expr *> Args, 8652 OverloadCandidateSet &CandidateSet) { 8653 // Find all of the types that the arguments can convert to, but only 8654 // if the operator we're looking at has built-in operator candidates 8655 // that make use of these types. Also record whether we encounter non-record 8656 // candidate types or either arithmetic or enumeral candidate types. 8657 Qualifiers VisibleTypeConversionsQuals; 8658 VisibleTypeConversionsQuals.addConst(); 8659 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8660 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8661 8662 bool HasNonRecordCandidateType = false; 8663 bool HasArithmeticOrEnumeralCandidateType = false; 8664 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8665 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8666 CandidateTypes.emplace_back(*this); 8667 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8668 OpLoc, 8669 true, 8670 (Op == OO_Exclaim || 8671 Op == OO_AmpAmp || 8672 Op == OO_PipePipe), 8673 VisibleTypeConversionsQuals); 8674 HasNonRecordCandidateType = HasNonRecordCandidateType || 8675 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8676 HasArithmeticOrEnumeralCandidateType = 8677 HasArithmeticOrEnumeralCandidateType || 8678 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8679 } 8680 8681 // Exit early when no non-record types have been added to the candidate set 8682 // for any of the arguments to the operator. 8683 // 8684 // We can't exit early for !, ||, or &&, since there we have always have 8685 // 'bool' overloads. 8686 if (!HasNonRecordCandidateType && 8687 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8688 return; 8689 8690 // Setup an object to manage the common state for building overloads. 8691 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8692 VisibleTypeConversionsQuals, 8693 HasArithmeticOrEnumeralCandidateType, 8694 CandidateTypes, CandidateSet); 8695 8696 // Dispatch over the operation to add in only those overloads which apply. 8697 switch (Op) { 8698 case OO_None: 8699 case NUM_OVERLOADED_OPERATORS: 8700 llvm_unreachable("Expected an overloaded operator"); 8701 8702 case OO_New: 8703 case OO_Delete: 8704 case OO_Array_New: 8705 case OO_Array_Delete: 8706 case OO_Call: 8707 llvm_unreachable( 8708 "Special operators don't use AddBuiltinOperatorCandidates"); 8709 8710 case OO_Comma: 8711 case OO_Arrow: 8712 case OO_Coawait: 8713 // C++ [over.match.oper]p3: 8714 // -- For the operator ',', the unary operator '&', the 8715 // operator '->', or the operator 'co_await', the 8716 // built-in candidates set is empty. 8717 break; 8718 8719 case OO_Plus: // '+' is either unary or binary 8720 if (Args.size() == 1) 8721 OpBuilder.addUnaryPlusPointerOverloads(); 8722 // Fall through. 8723 8724 case OO_Minus: // '-' is either unary or binary 8725 if (Args.size() == 1) { 8726 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8727 } else { 8728 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8729 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8730 } 8731 break; 8732 8733 case OO_Star: // '*' is either unary or binary 8734 if (Args.size() == 1) 8735 OpBuilder.addUnaryStarPointerOverloads(); 8736 else 8737 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8738 break; 8739 8740 case OO_Slash: 8741 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8742 break; 8743 8744 case OO_PlusPlus: 8745 case OO_MinusMinus: 8746 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8747 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8748 break; 8749 8750 case OO_EqualEqual: 8751 case OO_ExclaimEqual: 8752 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8753 // Fall through. 8754 8755 case OO_Less: 8756 case OO_Greater: 8757 case OO_LessEqual: 8758 case OO_GreaterEqual: 8759 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8760 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8761 break; 8762 8763 case OO_Percent: 8764 case OO_Caret: 8765 case OO_Pipe: 8766 case OO_LessLess: 8767 case OO_GreaterGreater: 8768 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8769 break; 8770 8771 case OO_Amp: // '&' is either unary or binary 8772 if (Args.size() == 1) 8773 // C++ [over.match.oper]p3: 8774 // -- For the operator ',', the unary operator '&', or the 8775 // operator '->', the built-in candidates set is empty. 8776 break; 8777 8778 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8779 break; 8780 8781 case OO_Tilde: 8782 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8783 break; 8784 8785 case OO_Equal: 8786 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8787 // Fall through. 8788 8789 case OO_PlusEqual: 8790 case OO_MinusEqual: 8791 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8792 // Fall through. 8793 8794 case OO_StarEqual: 8795 case OO_SlashEqual: 8796 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8797 break; 8798 8799 case OO_PercentEqual: 8800 case OO_LessLessEqual: 8801 case OO_GreaterGreaterEqual: 8802 case OO_AmpEqual: 8803 case OO_CaretEqual: 8804 case OO_PipeEqual: 8805 OpBuilder.addAssignmentIntegralOverloads(); 8806 break; 8807 8808 case OO_Exclaim: 8809 OpBuilder.addExclaimOverload(); 8810 break; 8811 8812 case OO_AmpAmp: 8813 case OO_PipePipe: 8814 OpBuilder.addAmpAmpOrPipePipeOverload(); 8815 break; 8816 8817 case OO_Subscript: 8818 OpBuilder.addSubscriptOverloads(); 8819 break; 8820 8821 case OO_ArrowStar: 8822 OpBuilder.addArrowStarOverloads(); 8823 break; 8824 8825 case OO_Conditional: 8826 OpBuilder.addConditionalOperatorOverloads(); 8827 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8828 break; 8829 } 8830 } 8831 8832 /// \brief Add function candidates found via argument-dependent lookup 8833 /// to the set of overloading candidates. 8834 /// 8835 /// This routine performs argument-dependent name lookup based on the 8836 /// given function name (which may also be an operator name) and adds 8837 /// all of the overload candidates found by ADL to the overload 8838 /// candidate set (C++ [basic.lookup.argdep]). 8839 void 8840 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8841 SourceLocation Loc, 8842 ArrayRef<Expr *> Args, 8843 TemplateArgumentListInfo *ExplicitTemplateArgs, 8844 OverloadCandidateSet& CandidateSet, 8845 bool PartialOverloading) { 8846 ADLResult Fns; 8847 8848 // FIXME: This approach for uniquing ADL results (and removing 8849 // redundant candidates from the set) relies on pointer-equality, 8850 // which means we need to key off the canonical decl. However, 8851 // always going back to the canonical decl might not get us the 8852 // right set of default arguments. What default arguments are 8853 // we supposed to consider on ADL candidates, anyway? 8854 8855 // FIXME: Pass in the explicit template arguments? 8856 ArgumentDependentLookup(Name, Loc, Args, Fns); 8857 8858 // Erase all of the candidates we already knew about. 8859 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8860 CandEnd = CandidateSet.end(); 8861 Cand != CandEnd; ++Cand) 8862 if (Cand->Function) { 8863 Fns.erase(Cand->Function); 8864 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8865 Fns.erase(FunTmpl); 8866 } 8867 8868 // For each of the ADL candidates we found, add it to the overload 8869 // set. 8870 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8871 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8872 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8873 if (ExplicitTemplateArgs) 8874 continue; 8875 8876 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8877 PartialOverloading); 8878 } else 8879 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8880 FoundDecl, ExplicitTemplateArgs, 8881 Args, CandidateSet, PartialOverloading); 8882 } 8883 } 8884 8885 namespace { 8886 enum class Comparison { Equal, Better, Worse }; 8887 } 8888 8889 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8890 /// overload resolution. 8891 /// 8892 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8893 /// Cand1's first N enable_if attributes have precisely the same conditions as 8894 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8895 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8896 /// 8897 /// Note that you can have a pair of candidates such that Cand1's enable_if 8898 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8899 /// worse than Cand1's. 8900 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8901 const FunctionDecl *Cand2) { 8902 // Common case: One (or both) decls don't have enable_if attrs. 8903 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8904 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8905 if (!Cand1Attr || !Cand2Attr) { 8906 if (Cand1Attr == Cand2Attr) 8907 return Comparison::Equal; 8908 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8909 } 8910 8911 // FIXME: The next several lines are just 8912 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8913 // instead of reverse order which is how they're stored in the AST. 8914 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8915 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8916 8917 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8918 // has fewer enable_if attributes than Cand2. 8919 if (Cand1Attrs.size() < Cand2Attrs.size()) 8920 return Comparison::Worse; 8921 8922 auto Cand1I = Cand1Attrs.begin(); 8923 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8924 for (auto &Cand2A : Cand2Attrs) { 8925 Cand1ID.clear(); 8926 Cand2ID.clear(); 8927 8928 auto &Cand1A = *Cand1I++; 8929 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8930 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8931 if (Cand1ID != Cand2ID) 8932 return Comparison::Worse; 8933 } 8934 8935 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8936 } 8937 8938 /// isBetterOverloadCandidate - Determines whether the first overload 8939 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8940 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8941 const OverloadCandidate &Cand2, 8942 SourceLocation Loc, 8943 bool UserDefinedConversion) { 8944 // Define viable functions to be better candidates than non-viable 8945 // functions. 8946 if (!Cand2.Viable) 8947 return Cand1.Viable; 8948 else if (!Cand1.Viable) 8949 return false; 8950 8951 // C++ [over.match.best]p1: 8952 // 8953 // -- if F is a static member function, ICS1(F) is defined such 8954 // that ICS1(F) is neither better nor worse than ICS1(G) for 8955 // any function G, and, symmetrically, ICS1(G) is neither 8956 // better nor worse than ICS1(F). 8957 unsigned StartArg = 0; 8958 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8959 StartArg = 1; 8960 8961 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 8962 // We don't allow incompatible pointer conversions in C++. 8963 if (!S.getLangOpts().CPlusPlus) 8964 return ICS.isStandard() && 8965 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 8966 8967 // The only ill-formed conversion we allow in C++ is the string literal to 8968 // char* conversion, which is only considered ill-formed after C++11. 8969 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 8970 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 8971 }; 8972 8973 // Define functions that don't require ill-formed conversions for a given 8974 // argument to be better candidates than functions that do. 8975 unsigned NumArgs = Cand1.Conversions.size(); 8976 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 8977 bool HasBetterConversion = false; 8978 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8979 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 8980 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 8981 if (Cand1Bad != Cand2Bad) { 8982 if (Cand1Bad) 8983 return false; 8984 HasBetterConversion = true; 8985 } 8986 } 8987 8988 if (HasBetterConversion) 8989 return true; 8990 8991 // C++ [over.match.best]p1: 8992 // A viable function F1 is defined to be a better function than another 8993 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8994 // conversion sequence than ICSi(F2), and then... 8995 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8996 switch (CompareImplicitConversionSequences(S, Loc, 8997 Cand1.Conversions[ArgIdx], 8998 Cand2.Conversions[ArgIdx])) { 8999 case ImplicitConversionSequence::Better: 9000 // Cand1 has a better conversion sequence. 9001 HasBetterConversion = true; 9002 break; 9003 9004 case ImplicitConversionSequence::Worse: 9005 // Cand1 can't be better than Cand2. 9006 return false; 9007 9008 case ImplicitConversionSequence::Indistinguishable: 9009 // Do nothing. 9010 break; 9011 } 9012 } 9013 9014 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9015 // ICSj(F2), or, if not that, 9016 if (HasBetterConversion) 9017 return true; 9018 9019 // -- the context is an initialization by user-defined conversion 9020 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9021 // from the return type of F1 to the destination type (i.e., 9022 // the type of the entity being initialized) is a better 9023 // conversion sequence than the standard conversion sequence 9024 // from the return type of F2 to the destination type. 9025 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 9026 isa<CXXConversionDecl>(Cand1.Function) && 9027 isa<CXXConversionDecl>(Cand2.Function)) { 9028 // First check whether we prefer one of the conversion functions over the 9029 // other. This only distinguishes the results in non-standard, extension 9030 // cases such as the conversion from a lambda closure type to a function 9031 // pointer or block. 9032 ImplicitConversionSequence::CompareKind Result = 9033 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9034 if (Result == ImplicitConversionSequence::Indistinguishable) 9035 Result = CompareStandardConversionSequences(S, Loc, 9036 Cand1.FinalConversion, 9037 Cand2.FinalConversion); 9038 9039 if (Result != ImplicitConversionSequence::Indistinguishable) 9040 return Result == ImplicitConversionSequence::Better; 9041 9042 // FIXME: Compare kind of reference binding if conversion functions 9043 // convert to a reference type used in direct reference binding, per 9044 // C++14 [over.match.best]p1 section 2 bullet 3. 9045 } 9046 9047 // -- F1 is a non-template function and F2 is a function template 9048 // specialization, or, if not that, 9049 bool Cand1IsSpecialization = Cand1.Function && 9050 Cand1.Function->getPrimaryTemplate(); 9051 bool Cand2IsSpecialization = Cand2.Function && 9052 Cand2.Function->getPrimaryTemplate(); 9053 if (Cand1IsSpecialization != Cand2IsSpecialization) 9054 return Cand2IsSpecialization; 9055 9056 // -- F1 and F2 are function template specializations, and the function 9057 // template for F1 is more specialized than the template for F2 9058 // according to the partial ordering rules described in 14.5.5.2, or, 9059 // if not that, 9060 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9061 if (FunctionTemplateDecl *BetterTemplate 9062 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9063 Cand2.Function->getPrimaryTemplate(), 9064 Loc, 9065 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9066 : TPOC_Call, 9067 Cand1.ExplicitCallArguments, 9068 Cand2.ExplicitCallArguments)) 9069 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9070 } 9071 9072 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9073 // A derived-class constructor beats an (inherited) base class constructor. 9074 bool Cand1IsInherited = 9075 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9076 bool Cand2IsInherited = 9077 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9078 if (Cand1IsInherited != Cand2IsInherited) 9079 return Cand2IsInherited; 9080 else if (Cand1IsInherited) { 9081 assert(Cand2IsInherited); 9082 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9083 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9084 if (Cand1Class->isDerivedFrom(Cand2Class)) 9085 return true; 9086 if (Cand2Class->isDerivedFrom(Cand1Class)) 9087 return false; 9088 // Inherited from sibling base classes: still ambiguous. 9089 } 9090 9091 // Check for enable_if value-based overload resolution. 9092 if (Cand1.Function && Cand2.Function) { 9093 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9094 if (Cmp != Comparison::Equal) 9095 return Cmp == Comparison::Better; 9096 } 9097 9098 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9099 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9100 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9101 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9102 } 9103 9104 bool HasPS1 = Cand1.Function != nullptr && 9105 functionHasPassObjectSizeParams(Cand1.Function); 9106 bool HasPS2 = Cand2.Function != nullptr && 9107 functionHasPassObjectSizeParams(Cand2.Function); 9108 return HasPS1 != HasPS2 && HasPS1; 9109 } 9110 9111 /// Determine whether two declarations are "equivalent" for the purposes of 9112 /// name lookup and overload resolution. This applies when the same internal/no 9113 /// linkage entity is defined by two modules (probably by textually including 9114 /// the same header). In such a case, we don't consider the declarations to 9115 /// declare the same entity, but we also don't want lookups with both 9116 /// declarations visible to be ambiguous in some cases (this happens when using 9117 /// a modularized libstdc++). 9118 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9119 const NamedDecl *B) { 9120 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9121 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9122 if (!VA || !VB) 9123 return false; 9124 9125 // The declarations must be declaring the same name as an internal linkage 9126 // entity in different modules. 9127 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9128 VB->getDeclContext()->getRedeclContext()) || 9129 getOwningModule(const_cast<ValueDecl *>(VA)) == 9130 getOwningModule(const_cast<ValueDecl *>(VB)) || 9131 VA->isExternallyVisible() || VB->isExternallyVisible()) 9132 return false; 9133 9134 // Check that the declarations appear to be equivalent. 9135 // 9136 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9137 // For constants and functions, we should check the initializer or body is 9138 // the same. For non-constant variables, we shouldn't allow it at all. 9139 if (Context.hasSameType(VA->getType(), VB->getType())) 9140 return true; 9141 9142 // Enum constants within unnamed enumerations will have different types, but 9143 // may still be similar enough to be interchangeable for our purposes. 9144 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9145 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9146 // Only handle anonymous enums. If the enumerations were named and 9147 // equivalent, they would have been merged to the same type. 9148 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9149 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9150 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9151 !Context.hasSameType(EnumA->getIntegerType(), 9152 EnumB->getIntegerType())) 9153 return false; 9154 // Allow this only if the value is the same for both enumerators. 9155 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9156 } 9157 } 9158 9159 // Nothing else is sufficiently similar. 9160 return false; 9161 } 9162 9163 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9164 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9165 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9166 9167 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9168 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9169 << !M << (M ? M->getFullModuleName() : ""); 9170 9171 for (auto *E : Equiv) { 9172 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9173 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9174 << !M << (M ? M->getFullModuleName() : ""); 9175 } 9176 } 9177 9178 static bool isCandidateUnavailableDueToDiagnoseIf(const OverloadCandidate &OC) { 9179 ArrayRef<DiagnoseIfAttr *> Info = OC.getDiagnoseIfInfo(); 9180 if (!Info.empty() && Info[0]->isError()) 9181 return true; 9182 9183 assert(llvm::all_of(Info, 9184 [](const DiagnoseIfAttr *A) { return !A->isError(); }) && 9185 "DiagnoseIf info shouldn't have mixed warnings and errors."); 9186 return false; 9187 } 9188 9189 /// \brief Computes the best viable function (C++ 13.3.3) 9190 /// within an overload candidate set. 9191 /// 9192 /// \param Loc The location of the function name (or operator symbol) for 9193 /// which overload resolution occurs. 9194 /// 9195 /// \param Best If overload resolution was successful or found a deleted 9196 /// function, \p Best points to the candidate function found. 9197 /// 9198 /// \returns The result of overload resolution. 9199 OverloadingResult 9200 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9201 iterator &Best, 9202 bool UserDefinedConversion) { 9203 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9204 std::transform(begin(), end(), std::back_inserter(Candidates), 9205 [](OverloadCandidate &Cand) { return &Cand; }); 9206 9207 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9208 // are accepted by both clang and NVCC. However, during a particular 9209 // compilation mode only one call variant is viable. We need to 9210 // exclude non-viable overload candidates from consideration based 9211 // only on their host/device attributes. Specifically, if one 9212 // candidate call is WrongSide and the other is SameSide, we ignore 9213 // the WrongSide candidate. 9214 if (S.getLangOpts().CUDA) { 9215 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9216 bool ContainsSameSideCandidate = 9217 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9218 return Cand->Function && 9219 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9220 Sema::CFP_SameSide; 9221 }); 9222 if (ContainsSameSideCandidate) { 9223 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9224 return Cand->Function && 9225 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9226 Sema::CFP_WrongSide; 9227 }; 9228 llvm::erase_if(Candidates, IsWrongSideCandidate); 9229 } 9230 } 9231 9232 // Find the best viable function. 9233 Best = end(); 9234 for (auto *Cand : Candidates) 9235 if (Cand->Viable) 9236 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 9237 UserDefinedConversion)) 9238 Best = Cand; 9239 9240 // If we didn't find any viable functions, abort. 9241 if (Best == end()) 9242 return OR_No_Viable_Function; 9243 9244 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9245 9246 // Make sure that this function is better than every other viable 9247 // function. If not, we have an ambiguity. 9248 for (auto *Cand : Candidates) { 9249 if (Cand->Viable && 9250 Cand != Best && 9251 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 9252 UserDefinedConversion)) { 9253 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9254 Cand->Function)) { 9255 EquivalentCands.push_back(Cand->Function); 9256 continue; 9257 } 9258 9259 Best = end(); 9260 return OR_Ambiguous; 9261 } 9262 } 9263 9264 // Best is the best viable function. 9265 if (Best->Function && 9266 (Best->Function->isDeleted() || 9267 S.isFunctionConsideredUnavailable(Best->Function) || 9268 isCandidateUnavailableDueToDiagnoseIf(*Best))) 9269 return OR_Deleted; 9270 9271 if (!EquivalentCands.empty()) 9272 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9273 EquivalentCands); 9274 9275 for (const auto *W : Best->getDiagnoseIfInfo()) { 9276 assert(W->isWarning() && "Errors should've been caught earlier!"); 9277 S.emitDiagnoseIfDiagnostic(Loc, W); 9278 } 9279 9280 return OR_Success; 9281 } 9282 9283 namespace { 9284 9285 enum OverloadCandidateKind { 9286 oc_function, 9287 oc_method, 9288 oc_constructor, 9289 oc_function_template, 9290 oc_method_template, 9291 oc_constructor_template, 9292 oc_implicit_default_constructor, 9293 oc_implicit_copy_constructor, 9294 oc_implicit_move_constructor, 9295 oc_implicit_copy_assignment, 9296 oc_implicit_move_assignment, 9297 oc_inherited_constructor, 9298 oc_inherited_constructor_template 9299 }; 9300 9301 static OverloadCandidateKind 9302 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9303 std::string &Description) { 9304 bool isTemplate = false; 9305 9306 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9307 isTemplate = true; 9308 Description = S.getTemplateArgumentBindingsText( 9309 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9310 } 9311 9312 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9313 if (!Ctor->isImplicit()) { 9314 if (isa<ConstructorUsingShadowDecl>(Found)) 9315 return isTemplate ? oc_inherited_constructor_template 9316 : oc_inherited_constructor; 9317 else 9318 return isTemplate ? oc_constructor_template : oc_constructor; 9319 } 9320 9321 if (Ctor->isDefaultConstructor()) 9322 return oc_implicit_default_constructor; 9323 9324 if (Ctor->isMoveConstructor()) 9325 return oc_implicit_move_constructor; 9326 9327 assert(Ctor->isCopyConstructor() && 9328 "unexpected sort of implicit constructor"); 9329 return oc_implicit_copy_constructor; 9330 } 9331 9332 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9333 // This actually gets spelled 'candidate function' for now, but 9334 // it doesn't hurt to split it out. 9335 if (!Meth->isImplicit()) 9336 return isTemplate ? oc_method_template : oc_method; 9337 9338 if (Meth->isMoveAssignmentOperator()) 9339 return oc_implicit_move_assignment; 9340 9341 if (Meth->isCopyAssignmentOperator()) 9342 return oc_implicit_copy_assignment; 9343 9344 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9345 return oc_method; 9346 } 9347 9348 return isTemplate ? oc_function_template : oc_function; 9349 } 9350 9351 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9352 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9353 // set. 9354 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9355 S.Diag(FoundDecl->getLocation(), 9356 diag::note_ovl_candidate_inherited_constructor) 9357 << Shadow->getNominatedBaseClass(); 9358 } 9359 9360 } // end anonymous namespace 9361 9362 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9363 const FunctionDecl *FD) { 9364 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9365 bool AlwaysTrue; 9366 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9367 return false; 9368 if (!AlwaysTrue) 9369 return false; 9370 } 9371 return true; 9372 } 9373 9374 /// \brief Returns true if we can take the address of the function. 9375 /// 9376 /// \param Complain - If true, we'll emit a diagnostic 9377 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9378 /// we in overload resolution? 9379 /// \param Loc - The location of the statement we're complaining about. Ignored 9380 /// if we're not complaining, or if we're in overload resolution. 9381 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9382 bool Complain, 9383 bool InOverloadResolution, 9384 SourceLocation Loc) { 9385 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9386 if (Complain) { 9387 if (InOverloadResolution) 9388 S.Diag(FD->getLocStart(), 9389 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9390 else 9391 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9392 } 9393 return false; 9394 } 9395 9396 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9397 return P->hasAttr<PassObjectSizeAttr>(); 9398 }); 9399 if (I == FD->param_end()) 9400 return true; 9401 9402 if (Complain) { 9403 // Add one to ParamNo because it's user-facing 9404 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9405 if (InOverloadResolution) 9406 S.Diag(FD->getLocation(), 9407 diag::note_ovl_candidate_has_pass_object_size_params) 9408 << ParamNo; 9409 else 9410 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9411 << FD << ParamNo; 9412 } 9413 return false; 9414 } 9415 9416 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9417 const FunctionDecl *FD) { 9418 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9419 /*InOverloadResolution=*/true, 9420 /*Loc=*/SourceLocation()); 9421 } 9422 9423 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9424 bool Complain, 9425 SourceLocation Loc) { 9426 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9427 /*InOverloadResolution=*/false, 9428 Loc); 9429 } 9430 9431 // Notes the location of an overload candidate. 9432 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9433 QualType DestType, bool TakingAddress) { 9434 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9435 return; 9436 9437 std::string FnDesc; 9438 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9439 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9440 << (unsigned) K << Fn << FnDesc; 9441 9442 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9443 Diag(Fn->getLocation(), PD); 9444 MaybeEmitInheritedConstructorNote(*this, Found); 9445 } 9446 9447 // Notes the location of all overload candidates designated through 9448 // OverloadedExpr 9449 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9450 bool TakingAddress) { 9451 assert(OverloadedExpr->getType() == Context.OverloadTy); 9452 9453 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9454 OverloadExpr *OvlExpr = Ovl.Expression; 9455 9456 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9457 IEnd = OvlExpr->decls_end(); 9458 I != IEnd; ++I) { 9459 if (FunctionTemplateDecl *FunTmpl = 9460 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9461 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9462 TakingAddress); 9463 } else if (FunctionDecl *Fun 9464 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9465 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9466 } 9467 } 9468 } 9469 9470 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9471 /// "lead" diagnostic; it will be given two arguments, the source and 9472 /// target types of the conversion. 9473 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9474 Sema &S, 9475 SourceLocation CaretLoc, 9476 const PartialDiagnostic &PDiag) const { 9477 S.Diag(CaretLoc, PDiag) 9478 << Ambiguous.getFromType() << Ambiguous.getToType(); 9479 // FIXME: The note limiting machinery is borrowed from 9480 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9481 // refactoring here. 9482 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9483 unsigned CandsShown = 0; 9484 AmbiguousConversionSequence::const_iterator I, E; 9485 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9486 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9487 break; 9488 ++CandsShown; 9489 S.NoteOverloadCandidate(I->first, I->second); 9490 } 9491 if (I != E) 9492 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9493 } 9494 9495 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9496 unsigned I, bool TakingCandidateAddress) { 9497 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9498 assert(Conv.isBad()); 9499 assert(Cand->Function && "for now, candidate must be a function"); 9500 FunctionDecl *Fn = Cand->Function; 9501 9502 // There's a conversion slot for the object argument if this is a 9503 // non-constructor method. Note that 'I' corresponds the 9504 // conversion-slot index. 9505 bool isObjectArgument = false; 9506 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9507 if (I == 0) 9508 isObjectArgument = true; 9509 else 9510 I--; 9511 } 9512 9513 std::string FnDesc; 9514 OverloadCandidateKind FnKind = 9515 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9516 9517 Expr *FromExpr = Conv.Bad.FromExpr; 9518 QualType FromTy = Conv.Bad.getFromType(); 9519 QualType ToTy = Conv.Bad.getToType(); 9520 9521 if (FromTy == S.Context.OverloadTy) { 9522 assert(FromExpr && "overload set argument came from implicit argument?"); 9523 Expr *E = FromExpr->IgnoreParens(); 9524 if (isa<UnaryOperator>(E)) 9525 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9526 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9527 9528 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9529 << (unsigned) FnKind << FnDesc 9530 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9531 << ToTy << Name << I+1; 9532 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9533 return; 9534 } 9535 9536 // Do some hand-waving analysis to see if the non-viability is due 9537 // to a qualifier mismatch. 9538 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9539 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9540 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9541 CToTy = RT->getPointeeType(); 9542 else { 9543 // TODO: detect and diagnose the full richness of const mismatches. 9544 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9545 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9546 CFromTy = FromPT->getPointeeType(); 9547 CToTy = ToPT->getPointeeType(); 9548 } 9549 } 9550 9551 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9552 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9553 Qualifiers FromQs = CFromTy.getQualifiers(); 9554 Qualifiers ToQs = CToTy.getQualifiers(); 9555 9556 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9557 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9558 << (unsigned) FnKind << FnDesc 9559 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9560 << FromTy 9561 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9562 << (unsigned) isObjectArgument << I+1; 9563 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9564 return; 9565 } 9566 9567 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9568 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9569 << (unsigned) FnKind << FnDesc 9570 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9571 << FromTy 9572 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9573 << (unsigned) isObjectArgument << I+1; 9574 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9575 return; 9576 } 9577 9578 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9579 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9580 << (unsigned) FnKind << FnDesc 9581 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9582 << FromTy 9583 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9584 << (unsigned) isObjectArgument << I+1; 9585 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9586 return; 9587 } 9588 9589 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9590 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9591 << (unsigned) FnKind << FnDesc 9592 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9593 << FromTy << FromQs.hasUnaligned() << I+1; 9594 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9595 return; 9596 } 9597 9598 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9599 assert(CVR && "unexpected qualifiers mismatch"); 9600 9601 if (isObjectArgument) { 9602 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9603 << (unsigned) FnKind << FnDesc 9604 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9605 << FromTy << (CVR - 1); 9606 } else { 9607 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9608 << (unsigned) FnKind << FnDesc 9609 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9610 << FromTy << (CVR - 1) << I+1; 9611 } 9612 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9613 return; 9614 } 9615 9616 // Special diagnostic for failure to convert an initializer list, since 9617 // telling the user that it has type void is not useful. 9618 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9619 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9620 << (unsigned) FnKind << FnDesc 9621 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9622 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9623 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9624 return; 9625 } 9626 9627 // Diagnose references or pointers to incomplete types differently, 9628 // since it's far from impossible that the incompleteness triggered 9629 // the failure. 9630 QualType TempFromTy = FromTy.getNonReferenceType(); 9631 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9632 TempFromTy = PTy->getPointeeType(); 9633 if (TempFromTy->isIncompleteType()) { 9634 // Emit the generic diagnostic and, optionally, add the hints to it. 9635 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9636 << (unsigned) FnKind << FnDesc 9637 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9638 << FromTy << ToTy << (unsigned) isObjectArgument << I+1 9639 << (unsigned) (Cand->Fix.Kind); 9640 9641 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9642 return; 9643 } 9644 9645 // Diagnose base -> derived pointer conversions. 9646 unsigned BaseToDerivedConversion = 0; 9647 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9648 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9649 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9650 FromPtrTy->getPointeeType()) && 9651 !FromPtrTy->getPointeeType()->isIncompleteType() && 9652 !ToPtrTy->getPointeeType()->isIncompleteType() && 9653 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9654 FromPtrTy->getPointeeType())) 9655 BaseToDerivedConversion = 1; 9656 } 9657 } else if (const ObjCObjectPointerType *FromPtrTy 9658 = FromTy->getAs<ObjCObjectPointerType>()) { 9659 if (const ObjCObjectPointerType *ToPtrTy 9660 = ToTy->getAs<ObjCObjectPointerType>()) 9661 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9662 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9663 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9664 FromPtrTy->getPointeeType()) && 9665 FromIface->isSuperClassOf(ToIface)) 9666 BaseToDerivedConversion = 2; 9667 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9668 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9669 !FromTy->isIncompleteType() && 9670 !ToRefTy->getPointeeType()->isIncompleteType() && 9671 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9672 BaseToDerivedConversion = 3; 9673 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9674 ToTy.getNonReferenceType().getCanonicalType() == 9675 FromTy.getNonReferenceType().getCanonicalType()) { 9676 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9677 << (unsigned) FnKind << FnDesc 9678 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9679 << (unsigned) isObjectArgument << I + 1; 9680 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9681 return; 9682 } 9683 } 9684 9685 if (BaseToDerivedConversion) { 9686 S.Diag(Fn->getLocation(), 9687 diag::note_ovl_candidate_bad_base_to_derived_conv) 9688 << (unsigned) FnKind << FnDesc 9689 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9690 << (BaseToDerivedConversion - 1) 9691 << FromTy << ToTy << I+1; 9692 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9693 return; 9694 } 9695 9696 if (isa<ObjCObjectPointerType>(CFromTy) && 9697 isa<PointerType>(CToTy)) { 9698 Qualifiers FromQs = CFromTy.getQualifiers(); 9699 Qualifiers ToQs = CToTy.getQualifiers(); 9700 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9701 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9702 << (unsigned) FnKind << FnDesc 9703 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9704 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9705 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9706 return; 9707 } 9708 } 9709 9710 if (TakingCandidateAddress && 9711 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9712 return; 9713 9714 // Emit the generic diagnostic and, optionally, add the hints to it. 9715 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9716 FDiag << (unsigned) FnKind << FnDesc 9717 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9718 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9719 << (unsigned) (Cand->Fix.Kind); 9720 9721 // If we can fix the conversion, suggest the FixIts. 9722 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9723 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9724 FDiag << *HI; 9725 S.Diag(Fn->getLocation(), FDiag); 9726 9727 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9728 } 9729 9730 /// Additional arity mismatch diagnosis specific to a function overload 9731 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9732 /// over a candidate in any candidate set. 9733 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9734 unsigned NumArgs) { 9735 FunctionDecl *Fn = Cand->Function; 9736 unsigned MinParams = Fn->getMinRequiredArguments(); 9737 9738 // With invalid overloaded operators, it's possible that we think we 9739 // have an arity mismatch when in fact it looks like we have the 9740 // right number of arguments, because only overloaded operators have 9741 // the weird behavior of overloading member and non-member functions. 9742 // Just don't report anything. 9743 if (Fn->isInvalidDecl() && 9744 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9745 return true; 9746 9747 if (NumArgs < MinParams) { 9748 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9749 (Cand->FailureKind == ovl_fail_bad_deduction && 9750 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9751 } else { 9752 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9753 (Cand->FailureKind == ovl_fail_bad_deduction && 9754 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9755 } 9756 9757 return false; 9758 } 9759 9760 /// General arity mismatch diagnosis over a candidate in a candidate set. 9761 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9762 unsigned NumFormalArgs) { 9763 assert(isa<FunctionDecl>(D) && 9764 "The templated declaration should at least be a function" 9765 " when diagnosing bad template argument deduction due to too many" 9766 " or too few arguments"); 9767 9768 FunctionDecl *Fn = cast<FunctionDecl>(D); 9769 9770 // TODO: treat calls to a missing default constructor as a special case 9771 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9772 unsigned MinParams = Fn->getMinRequiredArguments(); 9773 9774 // at least / at most / exactly 9775 unsigned mode, modeCount; 9776 if (NumFormalArgs < MinParams) { 9777 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9778 FnTy->isTemplateVariadic()) 9779 mode = 0; // "at least" 9780 else 9781 mode = 2; // "exactly" 9782 modeCount = MinParams; 9783 } else { 9784 if (MinParams != FnTy->getNumParams()) 9785 mode = 1; // "at most" 9786 else 9787 mode = 2; // "exactly" 9788 modeCount = FnTy->getNumParams(); 9789 } 9790 9791 std::string Description; 9792 OverloadCandidateKind FnKind = 9793 ClassifyOverloadCandidate(S, Found, Fn, Description); 9794 9795 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9796 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9797 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9798 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9799 else 9800 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9801 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9802 << mode << modeCount << NumFormalArgs; 9803 MaybeEmitInheritedConstructorNote(S, Found); 9804 } 9805 9806 /// Arity mismatch diagnosis specific to a function overload candidate. 9807 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9808 unsigned NumFormalArgs) { 9809 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9810 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9811 } 9812 9813 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9814 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9815 return TD; 9816 llvm_unreachable("Unsupported: Getting the described template declaration" 9817 " for bad deduction diagnosis"); 9818 } 9819 9820 /// Diagnose a failed template-argument deduction. 9821 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9822 DeductionFailureInfo &DeductionFailure, 9823 unsigned NumArgs, 9824 bool TakingCandidateAddress) { 9825 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9826 NamedDecl *ParamD; 9827 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9828 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9829 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9830 switch (DeductionFailure.Result) { 9831 case Sema::TDK_Success: 9832 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9833 9834 case Sema::TDK_Incomplete: { 9835 assert(ParamD && "no parameter found for incomplete deduction result"); 9836 S.Diag(Templated->getLocation(), 9837 diag::note_ovl_candidate_incomplete_deduction) 9838 << ParamD->getDeclName(); 9839 MaybeEmitInheritedConstructorNote(S, Found); 9840 return; 9841 } 9842 9843 case Sema::TDK_Underqualified: { 9844 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9845 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9846 9847 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9848 9849 // Param will have been canonicalized, but it should just be a 9850 // qualified version of ParamD, so move the qualifiers to that. 9851 QualifierCollector Qs; 9852 Qs.strip(Param); 9853 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9854 assert(S.Context.hasSameType(Param, NonCanonParam)); 9855 9856 // Arg has also been canonicalized, but there's nothing we can do 9857 // about that. It also doesn't matter as much, because it won't 9858 // have any template parameters in it (because deduction isn't 9859 // done on dependent types). 9860 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9861 9862 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9863 << ParamD->getDeclName() << Arg << NonCanonParam; 9864 MaybeEmitInheritedConstructorNote(S, Found); 9865 return; 9866 } 9867 9868 case Sema::TDK_Inconsistent: { 9869 assert(ParamD && "no parameter found for inconsistent deduction result"); 9870 int which = 0; 9871 if (isa<TemplateTypeParmDecl>(ParamD)) 9872 which = 0; 9873 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 9874 // Deduction might have failed because we deduced arguments of two 9875 // different types for a non-type template parameter. 9876 // FIXME: Use a different TDK value for this. 9877 QualType T1 = 9878 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 9879 QualType T2 = 9880 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 9881 if (!S.Context.hasSameType(T1, T2)) { 9882 S.Diag(Templated->getLocation(), 9883 diag::note_ovl_candidate_inconsistent_deduction_types) 9884 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 9885 << *DeductionFailure.getSecondArg() << T2; 9886 MaybeEmitInheritedConstructorNote(S, Found); 9887 return; 9888 } 9889 9890 which = 1; 9891 } else { 9892 which = 2; 9893 } 9894 9895 S.Diag(Templated->getLocation(), 9896 diag::note_ovl_candidate_inconsistent_deduction) 9897 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9898 << *DeductionFailure.getSecondArg(); 9899 MaybeEmitInheritedConstructorNote(S, Found); 9900 return; 9901 } 9902 9903 case Sema::TDK_InvalidExplicitArguments: 9904 assert(ParamD && "no parameter found for invalid explicit arguments"); 9905 if (ParamD->getDeclName()) 9906 S.Diag(Templated->getLocation(), 9907 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9908 << ParamD->getDeclName(); 9909 else { 9910 int index = 0; 9911 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9912 index = TTP->getIndex(); 9913 else if (NonTypeTemplateParmDecl *NTTP 9914 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9915 index = NTTP->getIndex(); 9916 else 9917 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9918 S.Diag(Templated->getLocation(), 9919 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9920 << (index + 1); 9921 } 9922 MaybeEmitInheritedConstructorNote(S, Found); 9923 return; 9924 9925 case Sema::TDK_TooManyArguments: 9926 case Sema::TDK_TooFewArguments: 9927 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 9928 return; 9929 9930 case Sema::TDK_InstantiationDepth: 9931 S.Diag(Templated->getLocation(), 9932 diag::note_ovl_candidate_instantiation_depth); 9933 MaybeEmitInheritedConstructorNote(S, Found); 9934 return; 9935 9936 case Sema::TDK_SubstitutionFailure: { 9937 // Format the template argument list into the argument string. 9938 SmallString<128> TemplateArgString; 9939 if (TemplateArgumentList *Args = 9940 DeductionFailure.getTemplateArgumentList()) { 9941 TemplateArgString = " "; 9942 TemplateArgString += S.getTemplateArgumentBindingsText( 9943 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9944 } 9945 9946 // If this candidate was disabled by enable_if, say so. 9947 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9948 if (PDiag && PDiag->second.getDiagID() == 9949 diag::err_typename_nested_not_found_enable_if) { 9950 // FIXME: Use the source range of the condition, and the fully-qualified 9951 // name of the enable_if template. These are both present in PDiag. 9952 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9953 << "'enable_if'" << TemplateArgString; 9954 return; 9955 } 9956 9957 // Format the SFINAE diagnostic into the argument string. 9958 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9959 // formatted message in another diagnostic. 9960 SmallString<128> SFINAEArgString; 9961 SourceRange R; 9962 if (PDiag) { 9963 SFINAEArgString = ": "; 9964 R = SourceRange(PDiag->first, PDiag->first); 9965 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9966 } 9967 9968 S.Diag(Templated->getLocation(), 9969 diag::note_ovl_candidate_substitution_failure) 9970 << TemplateArgString << SFINAEArgString << R; 9971 MaybeEmitInheritedConstructorNote(S, Found); 9972 return; 9973 } 9974 9975 case Sema::TDK_DeducedMismatch: 9976 case Sema::TDK_DeducedMismatchNested: { 9977 // Format the template argument list into the argument string. 9978 SmallString<128> TemplateArgString; 9979 if (TemplateArgumentList *Args = 9980 DeductionFailure.getTemplateArgumentList()) { 9981 TemplateArgString = " "; 9982 TemplateArgString += S.getTemplateArgumentBindingsText( 9983 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9984 } 9985 9986 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9987 << (*DeductionFailure.getCallArgIndex() + 1) 9988 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9989 << TemplateArgString 9990 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 9991 break; 9992 } 9993 9994 case Sema::TDK_NonDeducedMismatch: { 9995 // FIXME: Provide a source location to indicate what we couldn't match. 9996 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9997 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9998 if (FirstTA.getKind() == TemplateArgument::Template && 9999 SecondTA.getKind() == TemplateArgument::Template) { 10000 TemplateName FirstTN = FirstTA.getAsTemplate(); 10001 TemplateName SecondTN = SecondTA.getAsTemplate(); 10002 if (FirstTN.getKind() == TemplateName::Template && 10003 SecondTN.getKind() == TemplateName::Template) { 10004 if (FirstTN.getAsTemplateDecl()->getName() == 10005 SecondTN.getAsTemplateDecl()->getName()) { 10006 // FIXME: This fixes a bad diagnostic where both templates are named 10007 // the same. This particular case is a bit difficult since: 10008 // 1) It is passed as a string to the diagnostic printer. 10009 // 2) The diagnostic printer only attempts to find a better 10010 // name for types, not decls. 10011 // Ideally, this should folded into the diagnostic printer. 10012 S.Diag(Templated->getLocation(), 10013 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10014 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10015 return; 10016 } 10017 } 10018 } 10019 10020 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10021 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10022 return; 10023 10024 // FIXME: For generic lambda parameters, check if the function is a lambda 10025 // call operator, and if so, emit a prettier and more informative 10026 // diagnostic that mentions 'auto' and lambda in addition to 10027 // (or instead of?) the canonical template type parameters. 10028 S.Diag(Templated->getLocation(), 10029 diag::note_ovl_candidate_non_deduced_mismatch) 10030 << FirstTA << SecondTA; 10031 return; 10032 } 10033 // TODO: diagnose these individually, then kill off 10034 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10035 case Sema::TDK_MiscellaneousDeductionFailure: 10036 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10037 MaybeEmitInheritedConstructorNote(S, Found); 10038 return; 10039 case Sema::TDK_CUDATargetMismatch: 10040 S.Diag(Templated->getLocation(), 10041 diag::note_cuda_ovl_candidate_target_mismatch); 10042 return; 10043 } 10044 } 10045 10046 /// Diagnose a failed template-argument deduction, for function calls. 10047 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10048 unsigned NumArgs, 10049 bool TakingCandidateAddress) { 10050 unsigned TDK = Cand->DeductionFailure.Result; 10051 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10052 if (CheckArityMismatch(S, Cand, NumArgs)) 10053 return; 10054 } 10055 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10056 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10057 } 10058 10059 /// CUDA: diagnose an invalid call across targets. 10060 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10061 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10062 FunctionDecl *Callee = Cand->Function; 10063 10064 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10065 CalleeTarget = S.IdentifyCUDATarget(Callee); 10066 10067 std::string FnDesc; 10068 OverloadCandidateKind FnKind = 10069 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10070 10071 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10072 << (unsigned)FnKind << CalleeTarget << CallerTarget; 10073 10074 // This could be an implicit constructor for which we could not infer the 10075 // target due to a collsion. Diagnose that case. 10076 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10077 if (Meth != nullptr && Meth->isImplicit()) { 10078 CXXRecordDecl *ParentClass = Meth->getParent(); 10079 Sema::CXXSpecialMember CSM; 10080 10081 switch (FnKind) { 10082 default: 10083 return; 10084 case oc_implicit_default_constructor: 10085 CSM = Sema::CXXDefaultConstructor; 10086 break; 10087 case oc_implicit_copy_constructor: 10088 CSM = Sema::CXXCopyConstructor; 10089 break; 10090 case oc_implicit_move_constructor: 10091 CSM = Sema::CXXMoveConstructor; 10092 break; 10093 case oc_implicit_copy_assignment: 10094 CSM = Sema::CXXCopyAssignment; 10095 break; 10096 case oc_implicit_move_assignment: 10097 CSM = Sema::CXXMoveAssignment; 10098 break; 10099 }; 10100 10101 bool ConstRHS = false; 10102 if (Meth->getNumParams()) { 10103 if (const ReferenceType *RT = 10104 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10105 ConstRHS = RT->getPointeeType().isConstQualified(); 10106 } 10107 } 10108 10109 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10110 /* ConstRHS */ ConstRHS, 10111 /* Diagnose */ true); 10112 } 10113 } 10114 10115 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10116 FunctionDecl *Callee = Cand->Function; 10117 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10118 10119 S.Diag(Callee->getLocation(), 10120 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10121 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10122 } 10123 10124 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10125 FunctionDecl *Callee = Cand->Function; 10126 10127 S.Diag(Callee->getLocation(), 10128 diag::note_ovl_candidate_disabled_by_extension); 10129 } 10130 10131 /// Generates a 'note' diagnostic for an overload candidate. We've 10132 /// already generated a primary error at the call site. 10133 /// 10134 /// It really does need to be a single diagnostic with its caret 10135 /// pointed at the candidate declaration. Yes, this creates some 10136 /// major challenges of technical writing. Yes, this makes pointing 10137 /// out problems with specific arguments quite awkward. It's still 10138 /// better than generating twenty screens of text for every failed 10139 /// overload. 10140 /// 10141 /// It would be great to be able to express per-candidate problems 10142 /// more richly for those diagnostic clients that cared, but we'd 10143 /// still have to be just as careful with the default diagnostics. 10144 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10145 unsigned NumArgs, 10146 bool TakingCandidateAddress) { 10147 FunctionDecl *Fn = Cand->Function; 10148 10149 // Note deleted candidates, but only if they're viable. 10150 if (Cand->Viable) { 10151 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) { 10152 std::string FnDesc; 10153 OverloadCandidateKind FnKind = 10154 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10155 10156 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10157 << FnKind << FnDesc 10158 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10159 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10160 return; 10161 } 10162 if (isCandidateUnavailableDueToDiagnoseIf(*Cand)) { 10163 auto *A = Cand->DiagnoseIfInfo.get<DiagnoseIfAttr *>(); 10164 assert(A->isError() && "Non-error diagnose_if disables a candidate?"); 10165 S.Diag(Cand->Function->getLocation(), 10166 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10167 << A->getCond()->getSourceRange() << A->getMessage(); 10168 return; 10169 } 10170 10171 // We don't really have anything else to say about viable candidates. 10172 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10173 return; 10174 } 10175 10176 switch (Cand->FailureKind) { 10177 case ovl_fail_too_many_arguments: 10178 case ovl_fail_too_few_arguments: 10179 return DiagnoseArityMismatch(S, Cand, NumArgs); 10180 10181 case ovl_fail_bad_deduction: 10182 return DiagnoseBadDeduction(S, Cand, NumArgs, 10183 TakingCandidateAddress); 10184 10185 case ovl_fail_illegal_constructor: { 10186 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10187 << (Fn->getPrimaryTemplate() ? 1 : 0); 10188 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10189 return; 10190 } 10191 10192 case ovl_fail_trivial_conversion: 10193 case ovl_fail_bad_final_conversion: 10194 case ovl_fail_final_conversion_not_exact: 10195 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10196 10197 case ovl_fail_bad_conversion: { 10198 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10199 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10200 if (Cand->Conversions[I].isBad()) 10201 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10202 10203 // FIXME: this currently happens when we're called from SemaInit 10204 // when user-conversion overload fails. Figure out how to handle 10205 // those conditions and diagnose them well. 10206 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10207 } 10208 10209 case ovl_fail_bad_target: 10210 return DiagnoseBadTarget(S, Cand); 10211 10212 case ovl_fail_enable_if: 10213 return DiagnoseFailedEnableIfAttr(S, Cand); 10214 10215 case ovl_fail_ext_disabled: 10216 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10217 10218 case ovl_fail_inhctor_slice: 10219 S.Diag(Fn->getLocation(), 10220 diag::note_ovl_candidate_inherited_constructor_slice); 10221 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10222 return; 10223 10224 case ovl_fail_addr_not_available: { 10225 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10226 (void)Available; 10227 assert(!Available); 10228 break; 10229 } 10230 } 10231 } 10232 10233 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10234 // Desugar the type of the surrogate down to a function type, 10235 // retaining as many typedefs as possible while still showing 10236 // the function type (and, therefore, its parameter types). 10237 QualType FnType = Cand->Surrogate->getConversionType(); 10238 bool isLValueReference = false; 10239 bool isRValueReference = false; 10240 bool isPointer = false; 10241 if (const LValueReferenceType *FnTypeRef = 10242 FnType->getAs<LValueReferenceType>()) { 10243 FnType = FnTypeRef->getPointeeType(); 10244 isLValueReference = true; 10245 } else if (const RValueReferenceType *FnTypeRef = 10246 FnType->getAs<RValueReferenceType>()) { 10247 FnType = FnTypeRef->getPointeeType(); 10248 isRValueReference = true; 10249 } 10250 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10251 FnType = FnTypePtr->getPointeeType(); 10252 isPointer = true; 10253 } 10254 // Desugar down to a function type. 10255 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10256 // Reconstruct the pointer/reference as appropriate. 10257 if (isPointer) FnType = S.Context.getPointerType(FnType); 10258 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10259 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10260 10261 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10262 << FnType; 10263 } 10264 10265 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10266 SourceLocation OpLoc, 10267 OverloadCandidate *Cand) { 10268 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10269 std::string TypeStr("operator"); 10270 TypeStr += Opc; 10271 TypeStr += "("; 10272 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 10273 if (Cand->Conversions.size() == 1) { 10274 TypeStr += ")"; 10275 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10276 } else { 10277 TypeStr += ", "; 10278 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 10279 TypeStr += ")"; 10280 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10281 } 10282 } 10283 10284 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10285 OverloadCandidate *Cand) { 10286 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10287 if (ICS.isBad()) break; // all meaningless after first invalid 10288 if (!ICS.isAmbiguous()) continue; 10289 10290 ICS.DiagnoseAmbiguousConversion( 10291 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10292 } 10293 } 10294 10295 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10296 if (Cand->Function) 10297 return Cand->Function->getLocation(); 10298 if (Cand->IsSurrogate) 10299 return Cand->Surrogate->getLocation(); 10300 return SourceLocation(); 10301 } 10302 10303 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10304 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10305 case Sema::TDK_Success: 10306 case Sema::TDK_NonDependentConversionFailure: 10307 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10308 10309 case Sema::TDK_Invalid: 10310 case Sema::TDK_Incomplete: 10311 return 1; 10312 10313 case Sema::TDK_Underqualified: 10314 case Sema::TDK_Inconsistent: 10315 return 2; 10316 10317 case Sema::TDK_SubstitutionFailure: 10318 case Sema::TDK_DeducedMismatch: 10319 case Sema::TDK_DeducedMismatchNested: 10320 case Sema::TDK_NonDeducedMismatch: 10321 case Sema::TDK_MiscellaneousDeductionFailure: 10322 case Sema::TDK_CUDATargetMismatch: 10323 return 3; 10324 10325 case Sema::TDK_InstantiationDepth: 10326 return 4; 10327 10328 case Sema::TDK_InvalidExplicitArguments: 10329 return 5; 10330 10331 case Sema::TDK_TooManyArguments: 10332 case Sema::TDK_TooFewArguments: 10333 return 6; 10334 } 10335 llvm_unreachable("Unhandled deduction result"); 10336 } 10337 10338 namespace { 10339 struct CompareOverloadCandidatesForDisplay { 10340 Sema &S; 10341 SourceLocation Loc; 10342 size_t NumArgs; 10343 10344 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 10345 : S(S), NumArgs(nArgs) {} 10346 10347 bool operator()(const OverloadCandidate *L, 10348 const OverloadCandidate *R) { 10349 // Fast-path this check. 10350 if (L == R) return false; 10351 10352 // Order first by viability. 10353 if (L->Viable) { 10354 if (!R->Viable) return true; 10355 10356 // TODO: introduce a tri-valued comparison for overload 10357 // candidates. Would be more worthwhile if we had a sort 10358 // that could exploit it. 10359 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 10360 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 10361 } else if (R->Viable) 10362 return false; 10363 10364 assert(L->Viable == R->Viable); 10365 10366 // Criteria by which we can sort non-viable candidates: 10367 if (!L->Viable) { 10368 // 1. Arity mismatches come after other candidates. 10369 if (L->FailureKind == ovl_fail_too_many_arguments || 10370 L->FailureKind == ovl_fail_too_few_arguments) { 10371 if (R->FailureKind == ovl_fail_too_many_arguments || 10372 R->FailureKind == ovl_fail_too_few_arguments) { 10373 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10374 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10375 if (LDist == RDist) { 10376 if (L->FailureKind == R->FailureKind) 10377 // Sort non-surrogates before surrogates. 10378 return !L->IsSurrogate && R->IsSurrogate; 10379 // Sort candidates requiring fewer parameters than there were 10380 // arguments given after candidates requiring more parameters 10381 // than there were arguments given. 10382 return L->FailureKind == ovl_fail_too_many_arguments; 10383 } 10384 return LDist < RDist; 10385 } 10386 return false; 10387 } 10388 if (R->FailureKind == ovl_fail_too_many_arguments || 10389 R->FailureKind == ovl_fail_too_few_arguments) 10390 return true; 10391 10392 // 2. Bad conversions come first and are ordered by the number 10393 // of bad conversions and quality of good conversions. 10394 if (L->FailureKind == ovl_fail_bad_conversion) { 10395 if (R->FailureKind != ovl_fail_bad_conversion) 10396 return true; 10397 10398 // The conversion that can be fixed with a smaller number of changes, 10399 // comes first. 10400 unsigned numLFixes = L->Fix.NumConversionsFixed; 10401 unsigned numRFixes = R->Fix.NumConversionsFixed; 10402 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10403 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10404 if (numLFixes != numRFixes) { 10405 return numLFixes < numRFixes; 10406 } 10407 10408 // If there's any ordering between the defined conversions... 10409 // FIXME: this might not be transitive. 10410 assert(L->Conversions.size() == R->Conversions.size()); 10411 10412 int leftBetter = 0; 10413 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10414 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10415 switch (CompareImplicitConversionSequences(S, Loc, 10416 L->Conversions[I], 10417 R->Conversions[I])) { 10418 case ImplicitConversionSequence::Better: 10419 leftBetter++; 10420 break; 10421 10422 case ImplicitConversionSequence::Worse: 10423 leftBetter--; 10424 break; 10425 10426 case ImplicitConversionSequence::Indistinguishable: 10427 break; 10428 } 10429 } 10430 if (leftBetter > 0) return true; 10431 if (leftBetter < 0) return false; 10432 10433 } else if (R->FailureKind == ovl_fail_bad_conversion) 10434 return false; 10435 10436 if (L->FailureKind == ovl_fail_bad_deduction) { 10437 if (R->FailureKind != ovl_fail_bad_deduction) 10438 return true; 10439 10440 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10441 return RankDeductionFailure(L->DeductionFailure) 10442 < RankDeductionFailure(R->DeductionFailure); 10443 } else if (R->FailureKind == ovl_fail_bad_deduction) 10444 return false; 10445 10446 // TODO: others? 10447 } 10448 10449 // Sort everything else by location. 10450 SourceLocation LLoc = GetLocationForCandidate(L); 10451 SourceLocation RLoc = GetLocationForCandidate(R); 10452 10453 // Put candidates without locations (e.g. builtins) at the end. 10454 if (LLoc.isInvalid()) return false; 10455 if (RLoc.isInvalid()) return true; 10456 10457 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10458 } 10459 }; 10460 } 10461 10462 /// CompleteNonViableCandidate - Normally, overload resolution only 10463 /// computes up to the first bad conversion. Produces the FixIt set if 10464 /// possible. 10465 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10466 ArrayRef<Expr *> Args) { 10467 assert(!Cand->Viable); 10468 10469 // Don't do anything on failures other than bad conversion. 10470 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10471 10472 // We only want the FixIts if all the arguments can be corrected. 10473 bool Unfixable = false; 10474 // Use a implicit copy initialization to check conversion fixes. 10475 Cand->Fix.setConversionChecker(TryCopyInitialization); 10476 10477 // Attempt to fix the bad conversion. 10478 unsigned ConvCount = Cand->Conversions.size(); 10479 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10480 ++ConvIdx) { 10481 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10482 if (Cand->Conversions[ConvIdx].isInitialized() && 10483 Cand->Conversions[ConvIdx].isBad()) { 10484 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10485 break; 10486 } 10487 } 10488 10489 // FIXME: this should probably be preserved from the overload 10490 // operation somehow. 10491 bool SuppressUserConversions = false; 10492 10493 const FunctionProtoType *Proto; 10494 unsigned ArgIdx = 0; 10495 10496 if (Cand->IsSurrogate) { 10497 QualType ConvType 10498 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10499 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10500 ConvType = ConvPtrType->getPointeeType(); 10501 Proto = ConvType->getAs<FunctionProtoType>(); 10502 ArgIdx = 1; 10503 } else if (Cand->Function) { 10504 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 10505 if (isa<CXXMethodDecl>(Cand->Function) && 10506 !isa<CXXConstructorDecl>(Cand->Function)) 10507 ArgIdx = 1; 10508 } else { 10509 // Builtin binary operator with a bad first conversion. 10510 assert(ConvCount <= 3); 10511 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 10512 ConvIdx != ConvCount; ++ConvIdx) { 10513 if (Cand->Conversions[ConvIdx].isInitialized()) 10514 continue; 10515 if (Cand->BuiltinTypes.ParamTypes[ConvIdx]->isDependentType()) 10516 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10517 Args[ConvIdx]->getType()); 10518 else 10519 Cand->Conversions[ConvIdx] = TryCopyInitialization( 10520 S, Args[ConvIdx], Cand->BuiltinTypes.ParamTypes[ConvIdx], 10521 SuppressUserConversions, 10522 /*InOverloadResolution*/ true, 10523 /*AllowObjCWritebackConversion=*/ 10524 S.getLangOpts().ObjCAutoRefCount); 10525 // FIXME: If the conversion is bad, try to fix it. 10526 } 10527 return; 10528 } 10529 10530 // Fill in the rest of the conversions. 10531 unsigned NumParams = Proto->getNumParams(); 10532 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 10533 ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10534 if (Cand->Conversions[ConvIdx].isInitialized()) { 10535 // Found the bad conversion. 10536 } else if (ArgIdx < NumParams) { 10537 if (Proto->getParamType(ArgIdx)->isDependentType()) 10538 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10539 Args[ArgIdx]->getType()); 10540 else { 10541 Cand->Conversions[ConvIdx] = 10542 TryCopyInitialization(S, Args[ArgIdx], Proto->getParamType(ArgIdx), 10543 SuppressUserConversions, 10544 /*InOverloadResolution=*/true, 10545 /*AllowObjCWritebackConversion=*/ 10546 S.getLangOpts().ObjCAutoRefCount); 10547 // Store the FixIt in the candidate if it exists. 10548 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10549 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10550 } 10551 } else 10552 Cand->Conversions[ConvIdx].setEllipsis(); 10553 } 10554 } 10555 10556 /// PrintOverloadCandidates - When overload resolution fails, prints 10557 /// diagnostic messages containing the candidates in the candidate 10558 /// set. 10559 void OverloadCandidateSet::NoteCandidates( 10560 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10561 StringRef Opc, SourceLocation OpLoc, 10562 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10563 // Sort the candidates by viability and position. Sorting directly would 10564 // be prohibitive, so we make a set of pointers and sort those. 10565 SmallVector<OverloadCandidate*, 32> Cands; 10566 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10567 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10568 if (!Filter(*Cand)) 10569 continue; 10570 if (Cand->Viable) 10571 Cands.push_back(Cand); 10572 else if (OCD == OCD_AllCandidates) { 10573 CompleteNonViableCandidate(S, Cand, Args); 10574 if (Cand->Function || Cand->IsSurrogate) 10575 Cands.push_back(Cand); 10576 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10577 // want to list every possible builtin candidate. 10578 } 10579 } 10580 10581 std::sort(Cands.begin(), Cands.end(), 10582 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10583 10584 bool ReportedAmbiguousConversions = false; 10585 10586 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10587 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10588 unsigned CandsShown = 0; 10589 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10590 OverloadCandidate *Cand = *I; 10591 10592 // Set an arbitrary limit on the number of candidate functions we'll spam 10593 // the user with. FIXME: This limit should depend on details of the 10594 // candidate list. 10595 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10596 break; 10597 } 10598 ++CandsShown; 10599 10600 if (Cand->Function) 10601 NoteFunctionCandidate(S, Cand, Args.size(), 10602 /*TakingCandidateAddress=*/false); 10603 else if (Cand->IsSurrogate) 10604 NoteSurrogateCandidate(S, Cand); 10605 else { 10606 assert(Cand->Viable && 10607 "Non-viable built-in candidates are not added to Cands."); 10608 // Generally we only see ambiguities including viable builtin 10609 // operators if overload resolution got screwed up by an 10610 // ambiguous user-defined conversion. 10611 // 10612 // FIXME: It's quite possible for different conversions to see 10613 // different ambiguities, though. 10614 if (!ReportedAmbiguousConversions) { 10615 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10616 ReportedAmbiguousConversions = true; 10617 } 10618 10619 // If this is a viable builtin, print it. 10620 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10621 } 10622 } 10623 10624 if (I != E) 10625 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10626 } 10627 10628 static SourceLocation 10629 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10630 return Cand->Specialization ? Cand->Specialization->getLocation() 10631 : SourceLocation(); 10632 } 10633 10634 namespace { 10635 struct CompareTemplateSpecCandidatesForDisplay { 10636 Sema &S; 10637 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10638 10639 bool operator()(const TemplateSpecCandidate *L, 10640 const TemplateSpecCandidate *R) { 10641 // Fast-path this check. 10642 if (L == R) 10643 return false; 10644 10645 // Assuming that both candidates are not matches... 10646 10647 // Sort by the ranking of deduction failures. 10648 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10649 return RankDeductionFailure(L->DeductionFailure) < 10650 RankDeductionFailure(R->DeductionFailure); 10651 10652 // Sort everything else by location. 10653 SourceLocation LLoc = GetLocationForCandidate(L); 10654 SourceLocation RLoc = GetLocationForCandidate(R); 10655 10656 // Put candidates without locations (e.g. builtins) at the end. 10657 if (LLoc.isInvalid()) 10658 return false; 10659 if (RLoc.isInvalid()) 10660 return true; 10661 10662 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10663 } 10664 }; 10665 } 10666 10667 /// Diagnose a template argument deduction failure. 10668 /// We are treating these failures as overload failures due to bad 10669 /// deductions. 10670 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10671 bool ForTakingAddress) { 10672 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10673 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10674 } 10675 10676 void TemplateSpecCandidateSet::destroyCandidates() { 10677 for (iterator i = begin(), e = end(); i != e; ++i) { 10678 i->DeductionFailure.Destroy(); 10679 } 10680 } 10681 10682 void TemplateSpecCandidateSet::clear() { 10683 destroyCandidates(); 10684 Candidates.clear(); 10685 } 10686 10687 /// NoteCandidates - When no template specialization match is found, prints 10688 /// diagnostic messages containing the non-matching specializations that form 10689 /// the candidate set. 10690 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10691 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10692 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10693 // Sort the candidates by position (assuming no candidate is a match). 10694 // Sorting directly would be prohibitive, so we make a set of pointers 10695 // and sort those. 10696 SmallVector<TemplateSpecCandidate *, 32> Cands; 10697 Cands.reserve(size()); 10698 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10699 if (Cand->Specialization) 10700 Cands.push_back(Cand); 10701 // Otherwise, this is a non-matching builtin candidate. We do not, 10702 // in general, want to list every possible builtin candidate. 10703 } 10704 10705 std::sort(Cands.begin(), Cands.end(), 10706 CompareTemplateSpecCandidatesForDisplay(S)); 10707 10708 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10709 // for generalization purposes (?). 10710 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10711 10712 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10713 unsigned CandsShown = 0; 10714 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10715 TemplateSpecCandidate *Cand = *I; 10716 10717 // Set an arbitrary limit on the number of candidates we'll spam 10718 // the user with. FIXME: This limit should depend on details of the 10719 // candidate list. 10720 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10721 break; 10722 ++CandsShown; 10723 10724 assert(Cand->Specialization && 10725 "Non-matching built-in candidates are not added to Cands."); 10726 Cand->NoteDeductionFailure(S, ForTakingAddress); 10727 } 10728 10729 if (I != E) 10730 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10731 } 10732 10733 // [PossiblyAFunctionType] --> [Return] 10734 // NonFunctionType --> NonFunctionType 10735 // R (A) --> R(A) 10736 // R (*)(A) --> R (A) 10737 // R (&)(A) --> R (A) 10738 // R (S::*)(A) --> R (A) 10739 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10740 QualType Ret = PossiblyAFunctionType; 10741 if (const PointerType *ToTypePtr = 10742 PossiblyAFunctionType->getAs<PointerType>()) 10743 Ret = ToTypePtr->getPointeeType(); 10744 else if (const ReferenceType *ToTypeRef = 10745 PossiblyAFunctionType->getAs<ReferenceType>()) 10746 Ret = ToTypeRef->getPointeeType(); 10747 else if (const MemberPointerType *MemTypePtr = 10748 PossiblyAFunctionType->getAs<MemberPointerType>()) 10749 Ret = MemTypePtr->getPointeeType(); 10750 Ret = 10751 Context.getCanonicalType(Ret).getUnqualifiedType(); 10752 return Ret; 10753 } 10754 10755 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10756 bool Complain = true) { 10757 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10758 S.DeduceReturnType(FD, Loc, Complain)) 10759 return true; 10760 10761 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10762 if (S.getLangOpts().CPlusPlus1z && 10763 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10764 !S.ResolveExceptionSpec(Loc, FPT)) 10765 return true; 10766 10767 return false; 10768 } 10769 10770 namespace { 10771 // A helper class to help with address of function resolution 10772 // - allows us to avoid passing around all those ugly parameters 10773 class AddressOfFunctionResolver { 10774 Sema& S; 10775 Expr* SourceExpr; 10776 const QualType& TargetType; 10777 QualType TargetFunctionType; // Extracted function type from target type 10778 10779 bool Complain; 10780 //DeclAccessPair& ResultFunctionAccessPair; 10781 ASTContext& Context; 10782 10783 bool TargetTypeIsNonStaticMemberFunction; 10784 bool FoundNonTemplateFunction; 10785 bool StaticMemberFunctionFromBoundPointer; 10786 bool HasComplained; 10787 10788 OverloadExpr::FindResult OvlExprInfo; 10789 OverloadExpr *OvlExpr; 10790 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10791 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10792 TemplateSpecCandidateSet FailedCandidates; 10793 10794 public: 10795 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10796 const QualType &TargetType, bool Complain) 10797 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10798 Complain(Complain), Context(S.getASTContext()), 10799 TargetTypeIsNonStaticMemberFunction( 10800 !!TargetType->getAs<MemberPointerType>()), 10801 FoundNonTemplateFunction(false), 10802 StaticMemberFunctionFromBoundPointer(false), 10803 HasComplained(false), 10804 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10805 OvlExpr(OvlExprInfo.Expression), 10806 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10807 ExtractUnqualifiedFunctionTypeFromTargetType(); 10808 10809 if (TargetFunctionType->isFunctionType()) { 10810 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10811 if (!UME->isImplicitAccess() && 10812 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10813 StaticMemberFunctionFromBoundPointer = true; 10814 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10815 DeclAccessPair dap; 10816 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10817 OvlExpr, false, &dap)) { 10818 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10819 if (!Method->isStatic()) { 10820 // If the target type is a non-function type and the function found 10821 // is a non-static member function, pretend as if that was the 10822 // target, it's the only possible type to end up with. 10823 TargetTypeIsNonStaticMemberFunction = true; 10824 10825 // And skip adding the function if its not in the proper form. 10826 // We'll diagnose this due to an empty set of functions. 10827 if (!OvlExprInfo.HasFormOfMemberPointer) 10828 return; 10829 } 10830 10831 Matches.push_back(std::make_pair(dap, Fn)); 10832 } 10833 return; 10834 } 10835 10836 if (OvlExpr->hasExplicitTemplateArgs()) 10837 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10838 10839 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10840 // C++ [over.over]p4: 10841 // If more than one function is selected, [...] 10842 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10843 if (FoundNonTemplateFunction) 10844 EliminateAllTemplateMatches(); 10845 else 10846 EliminateAllExceptMostSpecializedTemplate(); 10847 } 10848 } 10849 10850 if (S.getLangOpts().CUDA && Matches.size() > 1) 10851 EliminateSuboptimalCudaMatches(); 10852 } 10853 10854 bool hasComplained() const { return HasComplained; } 10855 10856 private: 10857 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10858 QualType Discard; 10859 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10860 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 10861 } 10862 10863 /// \return true if A is considered a better overload candidate for the 10864 /// desired type than B. 10865 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10866 // If A doesn't have exactly the correct type, we don't want to classify it 10867 // as "better" than anything else. This way, the user is required to 10868 // disambiguate for us if there are multiple candidates and no exact match. 10869 return candidateHasExactlyCorrectType(A) && 10870 (!candidateHasExactlyCorrectType(B) || 10871 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10872 } 10873 10874 /// \return true if we were able to eliminate all but one overload candidate, 10875 /// false otherwise. 10876 bool eliminiateSuboptimalOverloadCandidates() { 10877 // Same algorithm as overload resolution -- one pass to pick the "best", 10878 // another pass to be sure that nothing is better than the best. 10879 auto Best = Matches.begin(); 10880 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10881 if (isBetterCandidate(I->second, Best->second)) 10882 Best = I; 10883 10884 const FunctionDecl *BestFn = Best->second; 10885 auto IsBestOrInferiorToBest = [this, BestFn]( 10886 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10887 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10888 }; 10889 10890 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10891 // option, so we can potentially give the user a better error 10892 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10893 return false; 10894 Matches[0] = *Best; 10895 Matches.resize(1); 10896 return true; 10897 } 10898 10899 bool isTargetTypeAFunction() const { 10900 return TargetFunctionType->isFunctionType(); 10901 } 10902 10903 // [ToType] [Return] 10904 10905 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10906 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10907 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10908 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10909 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10910 } 10911 10912 // return true if any matching specializations were found 10913 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10914 const DeclAccessPair& CurAccessFunPair) { 10915 if (CXXMethodDecl *Method 10916 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10917 // Skip non-static function templates when converting to pointer, and 10918 // static when converting to member pointer. 10919 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10920 return false; 10921 } 10922 else if (TargetTypeIsNonStaticMemberFunction) 10923 return false; 10924 10925 // C++ [over.over]p2: 10926 // If the name is a function template, template argument deduction is 10927 // done (14.8.2.2), and if the argument deduction succeeds, the 10928 // resulting template argument list is used to generate a single 10929 // function template specialization, which is added to the set of 10930 // overloaded functions considered. 10931 FunctionDecl *Specialization = nullptr; 10932 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10933 if (Sema::TemplateDeductionResult Result 10934 = S.DeduceTemplateArguments(FunctionTemplate, 10935 &OvlExplicitTemplateArgs, 10936 TargetFunctionType, Specialization, 10937 Info, /*IsAddressOfFunction*/true)) { 10938 // Make a note of the failed deduction for diagnostics. 10939 FailedCandidates.addCandidate() 10940 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 10941 MakeDeductionFailureInfo(Context, Result, Info)); 10942 return false; 10943 } 10944 10945 // Template argument deduction ensures that we have an exact match or 10946 // compatible pointer-to-function arguments that would be adjusted by ICS. 10947 // This function template specicalization works. 10948 assert(S.isSameOrCompatibleFunctionType( 10949 Context.getCanonicalType(Specialization->getType()), 10950 Context.getCanonicalType(TargetFunctionType))); 10951 10952 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10953 return false; 10954 10955 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10956 return true; 10957 } 10958 10959 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10960 const DeclAccessPair& CurAccessFunPair) { 10961 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10962 // Skip non-static functions when converting to pointer, and static 10963 // when converting to member pointer. 10964 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10965 return false; 10966 } 10967 else if (TargetTypeIsNonStaticMemberFunction) 10968 return false; 10969 10970 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10971 if (S.getLangOpts().CUDA) 10972 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10973 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 10974 return false; 10975 10976 // If any candidate has a placeholder return type, trigger its deduction 10977 // now. 10978 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(), 10979 Complain)) { 10980 HasComplained |= Complain; 10981 return false; 10982 } 10983 10984 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10985 return false; 10986 10987 // If we're in C, we need to support types that aren't exactly identical. 10988 if (!S.getLangOpts().CPlusPlus || 10989 candidateHasExactlyCorrectType(FunDecl)) { 10990 Matches.push_back(std::make_pair( 10991 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10992 FoundNonTemplateFunction = true; 10993 return true; 10994 } 10995 } 10996 10997 return false; 10998 } 10999 11000 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11001 bool Ret = false; 11002 11003 // If the overload expression doesn't have the form of a pointer to 11004 // member, don't try to convert it to a pointer-to-member type. 11005 if (IsInvalidFormOfPointerToMemberFunction()) 11006 return false; 11007 11008 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11009 E = OvlExpr->decls_end(); 11010 I != E; ++I) { 11011 // Look through any using declarations to find the underlying function. 11012 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11013 11014 // C++ [over.over]p3: 11015 // Non-member functions and static member functions match 11016 // targets of type "pointer-to-function" or "reference-to-function." 11017 // Nonstatic member functions match targets of 11018 // type "pointer-to-member-function." 11019 // Note that according to DR 247, the containing class does not matter. 11020 if (FunctionTemplateDecl *FunctionTemplate 11021 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11022 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11023 Ret = true; 11024 } 11025 // If we have explicit template arguments supplied, skip non-templates. 11026 else if (!OvlExpr->hasExplicitTemplateArgs() && 11027 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11028 Ret = true; 11029 } 11030 assert(Ret || Matches.empty()); 11031 return Ret; 11032 } 11033 11034 void EliminateAllExceptMostSpecializedTemplate() { 11035 // [...] and any given function template specialization F1 is 11036 // eliminated if the set contains a second function template 11037 // specialization whose function template is more specialized 11038 // than the function template of F1 according to the partial 11039 // ordering rules of 14.5.5.2. 11040 11041 // The algorithm specified above is quadratic. We instead use a 11042 // two-pass algorithm (similar to the one used to identify the 11043 // best viable function in an overload set) that identifies the 11044 // best function template (if it exists). 11045 11046 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11047 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11048 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11049 11050 // TODO: It looks like FailedCandidates does not serve much purpose 11051 // here, since the no_viable diagnostic has index 0. 11052 UnresolvedSetIterator Result = S.getMostSpecialized( 11053 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11054 SourceExpr->getLocStart(), S.PDiag(), 11055 S.PDiag(diag::err_addr_ovl_ambiguous) 11056 << Matches[0].second->getDeclName(), 11057 S.PDiag(diag::note_ovl_candidate) 11058 << (unsigned)oc_function_template, 11059 Complain, TargetFunctionType); 11060 11061 if (Result != MatchesCopy.end()) { 11062 // Make it the first and only element 11063 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11064 Matches[0].second = cast<FunctionDecl>(*Result); 11065 Matches.resize(1); 11066 } else 11067 HasComplained |= Complain; 11068 } 11069 11070 void EliminateAllTemplateMatches() { 11071 // [...] any function template specializations in the set are 11072 // eliminated if the set also contains a non-template function, [...] 11073 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11074 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11075 ++I; 11076 else { 11077 Matches[I] = Matches[--N]; 11078 Matches.resize(N); 11079 } 11080 } 11081 } 11082 11083 void EliminateSuboptimalCudaMatches() { 11084 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11085 } 11086 11087 public: 11088 void ComplainNoMatchesFound() const { 11089 assert(Matches.empty()); 11090 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 11091 << OvlExpr->getName() << TargetFunctionType 11092 << OvlExpr->getSourceRange(); 11093 if (FailedCandidates.empty()) 11094 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11095 /*TakingAddress=*/true); 11096 else { 11097 // We have some deduction failure messages. Use them to diagnose 11098 // the function templates, and diagnose the non-template candidates 11099 // normally. 11100 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11101 IEnd = OvlExpr->decls_end(); 11102 I != IEnd; ++I) 11103 if (FunctionDecl *Fun = 11104 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11105 if (!functionHasPassObjectSizeParams(Fun)) 11106 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11107 /*TakingAddress=*/true); 11108 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 11109 } 11110 } 11111 11112 bool IsInvalidFormOfPointerToMemberFunction() const { 11113 return TargetTypeIsNonStaticMemberFunction && 11114 !OvlExprInfo.HasFormOfMemberPointer; 11115 } 11116 11117 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11118 // TODO: Should we condition this on whether any functions might 11119 // have matched, or is it more appropriate to do that in callers? 11120 // TODO: a fixit wouldn't hurt. 11121 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11122 << TargetType << OvlExpr->getSourceRange(); 11123 } 11124 11125 bool IsStaticMemberFunctionFromBoundPointer() const { 11126 return StaticMemberFunctionFromBoundPointer; 11127 } 11128 11129 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11130 S.Diag(OvlExpr->getLocStart(), 11131 diag::err_invalid_form_pointer_member_function) 11132 << OvlExpr->getSourceRange(); 11133 } 11134 11135 void ComplainOfInvalidConversion() const { 11136 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 11137 << OvlExpr->getName() << TargetType; 11138 } 11139 11140 void ComplainMultipleMatchesFound() const { 11141 assert(Matches.size() > 1); 11142 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 11143 << OvlExpr->getName() 11144 << OvlExpr->getSourceRange(); 11145 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11146 /*TakingAddress=*/true); 11147 } 11148 11149 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11150 11151 int getNumMatches() const { return Matches.size(); } 11152 11153 FunctionDecl* getMatchingFunctionDecl() const { 11154 if (Matches.size() != 1) return nullptr; 11155 return Matches[0].second; 11156 } 11157 11158 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11159 if (Matches.size() != 1) return nullptr; 11160 return &Matches[0].first; 11161 } 11162 }; 11163 } 11164 11165 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11166 /// an overloaded function (C++ [over.over]), where @p From is an 11167 /// expression with overloaded function type and @p ToType is the type 11168 /// we're trying to resolve to. For example: 11169 /// 11170 /// @code 11171 /// int f(double); 11172 /// int f(int); 11173 /// 11174 /// int (*pfd)(double) = f; // selects f(double) 11175 /// @endcode 11176 /// 11177 /// This routine returns the resulting FunctionDecl if it could be 11178 /// resolved, and NULL otherwise. When @p Complain is true, this 11179 /// routine will emit diagnostics if there is an error. 11180 FunctionDecl * 11181 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11182 QualType TargetType, 11183 bool Complain, 11184 DeclAccessPair &FoundResult, 11185 bool *pHadMultipleCandidates) { 11186 assert(AddressOfExpr->getType() == Context.OverloadTy); 11187 11188 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11189 Complain); 11190 int NumMatches = Resolver.getNumMatches(); 11191 FunctionDecl *Fn = nullptr; 11192 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11193 if (NumMatches == 0 && ShouldComplain) { 11194 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11195 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11196 else 11197 Resolver.ComplainNoMatchesFound(); 11198 } 11199 else if (NumMatches > 1 && ShouldComplain) 11200 Resolver.ComplainMultipleMatchesFound(); 11201 else if (NumMatches == 1) { 11202 Fn = Resolver.getMatchingFunctionDecl(); 11203 assert(Fn); 11204 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11205 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11206 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11207 if (Complain) { 11208 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11209 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11210 else 11211 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11212 } 11213 } 11214 11215 if (pHadMultipleCandidates) 11216 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11217 return Fn; 11218 } 11219 11220 /// \brief Given an expression that refers to an overloaded function, try to 11221 /// resolve that function to a single function that can have its address taken. 11222 /// This will modify `Pair` iff it returns non-null. 11223 /// 11224 /// This routine can only realistically succeed if all but one candidates in the 11225 /// overload set for SrcExpr cannot have their addresses taken. 11226 FunctionDecl * 11227 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11228 DeclAccessPair &Pair) { 11229 OverloadExpr::FindResult R = OverloadExpr::find(E); 11230 OverloadExpr *Ovl = R.Expression; 11231 FunctionDecl *Result = nullptr; 11232 DeclAccessPair DAP; 11233 // Don't use the AddressOfResolver because we're specifically looking for 11234 // cases where we have one overload candidate that lacks 11235 // enable_if/pass_object_size/... 11236 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11237 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11238 if (!FD) 11239 return nullptr; 11240 11241 if (!checkAddressOfFunctionIsAvailable(FD)) 11242 continue; 11243 11244 // We have more than one result; quit. 11245 if (Result) 11246 return nullptr; 11247 DAP = I.getPair(); 11248 Result = FD; 11249 } 11250 11251 if (Result) 11252 Pair = DAP; 11253 return Result; 11254 } 11255 11256 /// \brief Given an overloaded function, tries to turn it into a non-overloaded 11257 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11258 /// will perform access checks, diagnose the use of the resultant decl, and, if 11259 /// necessary, perform a function-to-pointer decay. 11260 /// 11261 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11262 /// Otherwise, returns true. This may emit diagnostics and return true. 11263 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11264 ExprResult &SrcExpr) { 11265 Expr *E = SrcExpr.get(); 11266 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11267 11268 DeclAccessPair DAP; 11269 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11270 if (!Found) 11271 return false; 11272 11273 // Emitting multiple diagnostics for a function that is both inaccessible and 11274 // unavailable is consistent with our behavior elsewhere. So, always check 11275 // for both. 11276 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11277 CheckAddressOfMemberAccess(E, DAP); 11278 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11279 if (Fixed->getType()->isFunctionType()) 11280 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11281 else 11282 SrcExpr = Fixed; 11283 return true; 11284 } 11285 11286 /// \brief Given an expression that refers to an overloaded function, try to 11287 /// resolve that overloaded function expression down to a single function. 11288 /// 11289 /// This routine can only resolve template-ids that refer to a single function 11290 /// template, where that template-id refers to a single template whose template 11291 /// arguments are either provided by the template-id or have defaults, 11292 /// as described in C++0x [temp.arg.explicit]p3. 11293 /// 11294 /// If no template-ids are found, no diagnostics are emitted and NULL is 11295 /// returned. 11296 FunctionDecl * 11297 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11298 bool Complain, 11299 DeclAccessPair *FoundResult) { 11300 // C++ [over.over]p1: 11301 // [...] [Note: any redundant set of parentheses surrounding the 11302 // overloaded function name is ignored (5.1). ] 11303 // C++ [over.over]p1: 11304 // [...] The overloaded function name can be preceded by the & 11305 // operator. 11306 11307 // If we didn't actually find any template-ids, we're done. 11308 if (!ovl->hasExplicitTemplateArgs()) 11309 return nullptr; 11310 11311 TemplateArgumentListInfo ExplicitTemplateArgs; 11312 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11313 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11314 11315 // Look through all of the overloaded functions, searching for one 11316 // whose type matches exactly. 11317 FunctionDecl *Matched = nullptr; 11318 for (UnresolvedSetIterator I = ovl->decls_begin(), 11319 E = ovl->decls_end(); I != E; ++I) { 11320 // C++0x [temp.arg.explicit]p3: 11321 // [...] In contexts where deduction is done and fails, or in contexts 11322 // where deduction is not done, if a template argument list is 11323 // specified and it, along with any default template arguments, 11324 // identifies a single function template specialization, then the 11325 // template-id is an lvalue for the function template specialization. 11326 FunctionTemplateDecl *FunctionTemplate 11327 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11328 11329 // C++ [over.over]p2: 11330 // If the name is a function template, template argument deduction is 11331 // done (14.8.2.2), and if the argument deduction succeeds, the 11332 // resulting template argument list is used to generate a single 11333 // function template specialization, which is added to the set of 11334 // overloaded functions considered. 11335 FunctionDecl *Specialization = nullptr; 11336 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11337 if (TemplateDeductionResult Result 11338 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11339 Specialization, Info, 11340 /*IsAddressOfFunction*/true)) { 11341 // Make a note of the failed deduction for diagnostics. 11342 // TODO: Actually use the failed-deduction info? 11343 FailedCandidates.addCandidate() 11344 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11345 MakeDeductionFailureInfo(Context, Result, Info)); 11346 continue; 11347 } 11348 11349 assert(Specialization && "no specialization and no error?"); 11350 11351 // Multiple matches; we can't resolve to a single declaration. 11352 if (Matched) { 11353 if (Complain) { 11354 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11355 << ovl->getName(); 11356 NoteAllOverloadCandidates(ovl); 11357 } 11358 return nullptr; 11359 } 11360 11361 Matched = Specialization; 11362 if (FoundResult) *FoundResult = I.getPair(); 11363 } 11364 11365 if (Matched && 11366 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11367 return nullptr; 11368 11369 return Matched; 11370 } 11371 11372 11373 11374 11375 // Resolve and fix an overloaded expression that can be resolved 11376 // because it identifies a single function template specialization. 11377 // 11378 // Last three arguments should only be supplied if Complain = true 11379 // 11380 // Return true if it was logically possible to so resolve the 11381 // expression, regardless of whether or not it succeeded. Always 11382 // returns true if 'complain' is set. 11383 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11384 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11385 bool complain, SourceRange OpRangeForComplaining, 11386 QualType DestTypeForComplaining, 11387 unsigned DiagIDForComplaining) { 11388 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11389 11390 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11391 11392 DeclAccessPair found; 11393 ExprResult SingleFunctionExpression; 11394 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11395 ovl.Expression, /*complain*/ false, &found)) { 11396 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 11397 SrcExpr = ExprError(); 11398 return true; 11399 } 11400 11401 // It is only correct to resolve to an instance method if we're 11402 // resolving a form that's permitted to be a pointer to member. 11403 // Otherwise we'll end up making a bound member expression, which 11404 // is illegal in all the contexts we resolve like this. 11405 if (!ovl.HasFormOfMemberPointer && 11406 isa<CXXMethodDecl>(fn) && 11407 cast<CXXMethodDecl>(fn)->isInstance()) { 11408 if (!complain) return false; 11409 11410 Diag(ovl.Expression->getExprLoc(), 11411 diag::err_bound_member_function) 11412 << 0 << ovl.Expression->getSourceRange(); 11413 11414 // TODO: I believe we only end up here if there's a mix of 11415 // static and non-static candidates (otherwise the expression 11416 // would have 'bound member' type, not 'overload' type). 11417 // Ideally we would note which candidate was chosen and why 11418 // the static candidates were rejected. 11419 SrcExpr = ExprError(); 11420 return true; 11421 } 11422 11423 // Fix the expression to refer to 'fn'. 11424 SingleFunctionExpression = 11425 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11426 11427 // If desired, do function-to-pointer decay. 11428 if (doFunctionPointerConverion) { 11429 SingleFunctionExpression = 11430 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11431 if (SingleFunctionExpression.isInvalid()) { 11432 SrcExpr = ExprError(); 11433 return true; 11434 } 11435 } 11436 } 11437 11438 if (!SingleFunctionExpression.isUsable()) { 11439 if (complain) { 11440 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11441 << ovl.Expression->getName() 11442 << DestTypeForComplaining 11443 << OpRangeForComplaining 11444 << ovl.Expression->getQualifierLoc().getSourceRange(); 11445 NoteAllOverloadCandidates(SrcExpr.get()); 11446 11447 SrcExpr = ExprError(); 11448 return true; 11449 } 11450 11451 return false; 11452 } 11453 11454 SrcExpr = SingleFunctionExpression; 11455 return true; 11456 } 11457 11458 /// \brief Add a single candidate to the overload set. 11459 static void AddOverloadedCallCandidate(Sema &S, 11460 DeclAccessPair FoundDecl, 11461 TemplateArgumentListInfo *ExplicitTemplateArgs, 11462 ArrayRef<Expr *> Args, 11463 OverloadCandidateSet &CandidateSet, 11464 bool PartialOverloading, 11465 bool KnownValid) { 11466 NamedDecl *Callee = FoundDecl.getDecl(); 11467 if (isa<UsingShadowDecl>(Callee)) 11468 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11469 11470 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11471 if (ExplicitTemplateArgs) { 11472 assert(!KnownValid && "Explicit template arguments?"); 11473 return; 11474 } 11475 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11476 /*SuppressUsedConversions=*/false, 11477 PartialOverloading); 11478 return; 11479 } 11480 11481 if (FunctionTemplateDecl *FuncTemplate 11482 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11483 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11484 ExplicitTemplateArgs, Args, CandidateSet, 11485 /*SuppressUsedConversions=*/false, 11486 PartialOverloading); 11487 return; 11488 } 11489 11490 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11491 } 11492 11493 /// \brief Add the overload candidates named by callee and/or found by argument 11494 /// dependent lookup to the given overload set. 11495 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11496 ArrayRef<Expr *> Args, 11497 OverloadCandidateSet &CandidateSet, 11498 bool PartialOverloading) { 11499 11500 #ifndef NDEBUG 11501 // Verify that ArgumentDependentLookup is consistent with the rules 11502 // in C++0x [basic.lookup.argdep]p3: 11503 // 11504 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11505 // and let Y be the lookup set produced by argument dependent 11506 // lookup (defined as follows). If X contains 11507 // 11508 // -- a declaration of a class member, or 11509 // 11510 // -- a block-scope function declaration that is not a 11511 // using-declaration, or 11512 // 11513 // -- a declaration that is neither a function or a function 11514 // template 11515 // 11516 // then Y is empty. 11517 11518 if (ULE->requiresADL()) { 11519 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11520 E = ULE->decls_end(); I != E; ++I) { 11521 assert(!(*I)->getDeclContext()->isRecord()); 11522 assert(isa<UsingShadowDecl>(*I) || 11523 !(*I)->getDeclContext()->isFunctionOrMethod()); 11524 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11525 } 11526 } 11527 #endif 11528 11529 // It would be nice to avoid this copy. 11530 TemplateArgumentListInfo TABuffer; 11531 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11532 if (ULE->hasExplicitTemplateArgs()) { 11533 ULE->copyTemplateArgumentsInto(TABuffer); 11534 ExplicitTemplateArgs = &TABuffer; 11535 } 11536 11537 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11538 E = ULE->decls_end(); I != E; ++I) 11539 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11540 CandidateSet, PartialOverloading, 11541 /*KnownValid*/ true); 11542 11543 if (ULE->requiresADL()) 11544 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11545 Args, ExplicitTemplateArgs, 11546 CandidateSet, PartialOverloading); 11547 } 11548 11549 /// Determine whether a declaration with the specified name could be moved into 11550 /// a different namespace. 11551 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11552 switch (Name.getCXXOverloadedOperator()) { 11553 case OO_New: case OO_Array_New: 11554 case OO_Delete: case OO_Array_Delete: 11555 return false; 11556 11557 default: 11558 return true; 11559 } 11560 } 11561 11562 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11563 /// template, where the non-dependent name was declared after the template 11564 /// was defined. This is common in code written for a compilers which do not 11565 /// correctly implement two-stage name lookup. 11566 /// 11567 /// Returns true if a viable candidate was found and a diagnostic was issued. 11568 static bool 11569 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11570 const CXXScopeSpec &SS, LookupResult &R, 11571 OverloadCandidateSet::CandidateSetKind CSK, 11572 TemplateArgumentListInfo *ExplicitTemplateArgs, 11573 ArrayRef<Expr *> Args, 11574 bool *DoDiagnoseEmptyLookup = nullptr) { 11575 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 11576 return false; 11577 11578 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11579 if (DC->isTransparentContext()) 11580 continue; 11581 11582 SemaRef.LookupQualifiedName(R, DC); 11583 11584 if (!R.empty()) { 11585 R.suppressDiagnostics(); 11586 11587 if (isa<CXXRecordDecl>(DC)) { 11588 // Don't diagnose names we find in classes; we get much better 11589 // diagnostics for these from DiagnoseEmptyLookup. 11590 R.clear(); 11591 if (DoDiagnoseEmptyLookup) 11592 *DoDiagnoseEmptyLookup = true; 11593 return false; 11594 } 11595 11596 OverloadCandidateSet Candidates(FnLoc, CSK); 11597 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11598 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11599 ExplicitTemplateArgs, Args, 11600 Candidates, false, /*KnownValid*/ false); 11601 11602 OverloadCandidateSet::iterator Best; 11603 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11604 // No viable functions. Don't bother the user with notes for functions 11605 // which don't work and shouldn't be found anyway. 11606 R.clear(); 11607 return false; 11608 } 11609 11610 // Find the namespaces where ADL would have looked, and suggest 11611 // declaring the function there instead. 11612 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11613 Sema::AssociatedClassSet AssociatedClasses; 11614 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11615 AssociatedNamespaces, 11616 AssociatedClasses); 11617 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11618 if (canBeDeclaredInNamespace(R.getLookupName())) { 11619 DeclContext *Std = SemaRef.getStdNamespace(); 11620 for (Sema::AssociatedNamespaceSet::iterator 11621 it = AssociatedNamespaces.begin(), 11622 end = AssociatedNamespaces.end(); it != end; ++it) { 11623 // Never suggest declaring a function within namespace 'std'. 11624 if (Std && Std->Encloses(*it)) 11625 continue; 11626 11627 // Never suggest declaring a function within a namespace with a 11628 // reserved name, like __gnu_cxx. 11629 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11630 if (NS && 11631 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11632 continue; 11633 11634 SuggestedNamespaces.insert(*it); 11635 } 11636 } 11637 11638 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11639 << R.getLookupName(); 11640 if (SuggestedNamespaces.empty()) { 11641 SemaRef.Diag(Best->Function->getLocation(), 11642 diag::note_not_found_by_two_phase_lookup) 11643 << R.getLookupName() << 0; 11644 } else if (SuggestedNamespaces.size() == 1) { 11645 SemaRef.Diag(Best->Function->getLocation(), 11646 diag::note_not_found_by_two_phase_lookup) 11647 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11648 } else { 11649 // FIXME: It would be useful to list the associated namespaces here, 11650 // but the diagnostics infrastructure doesn't provide a way to produce 11651 // a localized representation of a list of items. 11652 SemaRef.Diag(Best->Function->getLocation(), 11653 diag::note_not_found_by_two_phase_lookup) 11654 << R.getLookupName() << 2; 11655 } 11656 11657 // Try to recover by calling this function. 11658 return true; 11659 } 11660 11661 R.clear(); 11662 } 11663 11664 return false; 11665 } 11666 11667 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11668 /// template, where the non-dependent operator was declared after the template 11669 /// was defined. 11670 /// 11671 /// Returns true if a viable candidate was found and a diagnostic was issued. 11672 static bool 11673 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11674 SourceLocation OpLoc, 11675 ArrayRef<Expr *> Args) { 11676 DeclarationName OpName = 11677 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11678 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11679 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11680 OverloadCandidateSet::CSK_Operator, 11681 /*ExplicitTemplateArgs=*/nullptr, Args); 11682 } 11683 11684 namespace { 11685 class BuildRecoveryCallExprRAII { 11686 Sema &SemaRef; 11687 public: 11688 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11689 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11690 SemaRef.IsBuildingRecoveryCallExpr = true; 11691 } 11692 11693 ~BuildRecoveryCallExprRAII() { 11694 SemaRef.IsBuildingRecoveryCallExpr = false; 11695 } 11696 }; 11697 11698 } 11699 11700 static std::unique_ptr<CorrectionCandidateCallback> 11701 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11702 bool HasTemplateArgs, bool AllowTypoCorrection) { 11703 if (!AllowTypoCorrection) 11704 return llvm::make_unique<NoTypoCorrectionCCC>(); 11705 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11706 HasTemplateArgs, ME); 11707 } 11708 11709 /// Attempts to recover from a call where no functions were found. 11710 /// 11711 /// Returns true if new candidates were found. 11712 static ExprResult 11713 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11714 UnresolvedLookupExpr *ULE, 11715 SourceLocation LParenLoc, 11716 MutableArrayRef<Expr *> Args, 11717 SourceLocation RParenLoc, 11718 bool EmptyLookup, bool AllowTypoCorrection) { 11719 // Do not try to recover if it is already building a recovery call. 11720 // This stops infinite loops for template instantiations like 11721 // 11722 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11723 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11724 // 11725 if (SemaRef.IsBuildingRecoveryCallExpr) 11726 return ExprError(); 11727 BuildRecoveryCallExprRAII RCE(SemaRef); 11728 11729 CXXScopeSpec SS; 11730 SS.Adopt(ULE->getQualifierLoc()); 11731 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11732 11733 TemplateArgumentListInfo TABuffer; 11734 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11735 if (ULE->hasExplicitTemplateArgs()) { 11736 ULE->copyTemplateArgumentsInto(TABuffer); 11737 ExplicitTemplateArgs = &TABuffer; 11738 } 11739 11740 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11741 Sema::LookupOrdinaryName); 11742 bool DoDiagnoseEmptyLookup = EmptyLookup; 11743 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11744 OverloadCandidateSet::CSK_Normal, 11745 ExplicitTemplateArgs, Args, 11746 &DoDiagnoseEmptyLookup) && 11747 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11748 S, SS, R, 11749 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11750 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11751 ExplicitTemplateArgs, Args))) 11752 return ExprError(); 11753 11754 assert(!R.empty() && "lookup results empty despite recovery"); 11755 11756 // If recovery created an ambiguity, just bail out. 11757 if (R.isAmbiguous()) { 11758 R.suppressDiagnostics(); 11759 return ExprError(); 11760 } 11761 11762 // Build an implicit member call if appropriate. Just drop the 11763 // casts and such from the call, we don't really care. 11764 ExprResult NewFn = ExprError(); 11765 if ((*R.begin())->isCXXClassMember()) 11766 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11767 ExplicitTemplateArgs, S); 11768 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11769 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11770 ExplicitTemplateArgs); 11771 else 11772 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11773 11774 if (NewFn.isInvalid()) 11775 return ExprError(); 11776 11777 // This shouldn't cause an infinite loop because we're giving it 11778 // an expression with viable lookup results, which should never 11779 // end up here. 11780 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11781 MultiExprArg(Args.data(), Args.size()), 11782 RParenLoc); 11783 } 11784 11785 /// \brief Constructs and populates an OverloadedCandidateSet from 11786 /// the given function. 11787 /// \returns true when an the ExprResult output parameter has been set. 11788 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11789 UnresolvedLookupExpr *ULE, 11790 MultiExprArg Args, 11791 SourceLocation RParenLoc, 11792 OverloadCandidateSet *CandidateSet, 11793 ExprResult *Result) { 11794 #ifndef NDEBUG 11795 if (ULE->requiresADL()) { 11796 // To do ADL, we must have found an unqualified name. 11797 assert(!ULE->getQualifier() && "qualified name with ADL"); 11798 11799 // We don't perform ADL for implicit declarations of builtins. 11800 // Verify that this was correctly set up. 11801 FunctionDecl *F; 11802 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11803 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11804 F->getBuiltinID() && F->isImplicit()) 11805 llvm_unreachable("performing ADL for builtin"); 11806 11807 // We don't perform ADL in C. 11808 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11809 } 11810 #endif 11811 11812 UnbridgedCastsSet UnbridgedCasts; 11813 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11814 *Result = ExprError(); 11815 return true; 11816 } 11817 11818 // Add the functions denoted by the callee to the set of candidate 11819 // functions, including those from argument-dependent lookup. 11820 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11821 11822 if (getLangOpts().MSVCCompat && 11823 CurContext->isDependentContext() && !isSFINAEContext() && 11824 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11825 11826 OverloadCandidateSet::iterator Best; 11827 if (CandidateSet->empty() || 11828 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11829 OR_No_Viable_Function) { 11830 // In Microsoft mode, if we are inside a template class member function then 11831 // create a type dependent CallExpr. The goal is to postpone name lookup 11832 // to instantiation time to be able to search into type dependent base 11833 // classes. 11834 CallExpr *CE = new (Context) CallExpr( 11835 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11836 CE->setTypeDependent(true); 11837 CE->setValueDependent(true); 11838 CE->setInstantiationDependent(true); 11839 *Result = CE; 11840 return true; 11841 } 11842 } 11843 11844 if (CandidateSet->empty()) 11845 return false; 11846 11847 UnbridgedCasts.restore(); 11848 return false; 11849 } 11850 11851 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11852 /// the completed call expression. If overload resolution fails, emits 11853 /// diagnostics and returns ExprError() 11854 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11855 UnresolvedLookupExpr *ULE, 11856 SourceLocation LParenLoc, 11857 MultiExprArg Args, 11858 SourceLocation RParenLoc, 11859 Expr *ExecConfig, 11860 OverloadCandidateSet *CandidateSet, 11861 OverloadCandidateSet::iterator *Best, 11862 OverloadingResult OverloadResult, 11863 bool AllowTypoCorrection) { 11864 if (CandidateSet->empty()) 11865 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11866 RParenLoc, /*EmptyLookup=*/true, 11867 AllowTypoCorrection); 11868 11869 switch (OverloadResult) { 11870 case OR_Success: { 11871 FunctionDecl *FDecl = (*Best)->Function; 11872 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11873 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11874 return ExprError(); 11875 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11876 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11877 ExecConfig); 11878 } 11879 11880 case OR_No_Viable_Function: { 11881 // Try to recover by looking for viable functions which the user might 11882 // have meant to call. 11883 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11884 Args, RParenLoc, 11885 /*EmptyLookup=*/false, 11886 AllowTypoCorrection); 11887 if (!Recovery.isInvalid()) 11888 return Recovery; 11889 11890 // If the user passes in a function that we can't take the address of, we 11891 // generally end up emitting really bad error messages. Here, we attempt to 11892 // emit better ones. 11893 for (const Expr *Arg : Args) { 11894 if (!Arg->getType()->isFunctionType()) 11895 continue; 11896 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11897 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11898 if (FD && 11899 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11900 Arg->getExprLoc())) 11901 return ExprError(); 11902 } 11903 } 11904 11905 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11906 << ULE->getName() << Fn->getSourceRange(); 11907 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11908 break; 11909 } 11910 11911 case OR_Ambiguous: 11912 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11913 << ULE->getName() << Fn->getSourceRange(); 11914 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11915 break; 11916 11917 case OR_Deleted: { 11918 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11919 << (*Best)->Function->isDeleted() 11920 << ULE->getName() 11921 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11922 << Fn->getSourceRange(); 11923 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11924 11925 // We emitted an error for the unvailable/deleted function call but keep 11926 // the call in the AST. 11927 FunctionDecl *FDecl = (*Best)->Function; 11928 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11929 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11930 ExecConfig); 11931 } 11932 } 11933 11934 // Overload resolution failed. 11935 return ExprError(); 11936 } 11937 11938 static void markUnaddressableCandidatesUnviable(Sema &S, 11939 OverloadCandidateSet &CS) { 11940 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11941 if (I->Viable && 11942 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11943 I->Viable = false; 11944 I->FailureKind = ovl_fail_addr_not_available; 11945 } 11946 } 11947 } 11948 11949 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11950 /// (which eventually refers to the declaration Func) and the call 11951 /// arguments Args/NumArgs, attempt to resolve the function call down 11952 /// to a specific function. If overload resolution succeeds, returns 11953 /// the call expression produced by overload resolution. 11954 /// Otherwise, emits diagnostics and returns ExprError. 11955 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11956 UnresolvedLookupExpr *ULE, 11957 SourceLocation LParenLoc, 11958 MultiExprArg Args, 11959 SourceLocation RParenLoc, 11960 Expr *ExecConfig, 11961 bool AllowTypoCorrection, 11962 bool CalleesAddressIsTaken) { 11963 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11964 OverloadCandidateSet::CSK_Normal); 11965 ExprResult result; 11966 11967 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11968 &result)) 11969 return result; 11970 11971 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11972 // functions that aren't addressible are considered unviable. 11973 if (CalleesAddressIsTaken) 11974 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11975 11976 OverloadCandidateSet::iterator Best; 11977 OverloadingResult OverloadResult = 11978 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11979 11980 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11981 RParenLoc, ExecConfig, &CandidateSet, 11982 &Best, OverloadResult, 11983 AllowTypoCorrection); 11984 } 11985 11986 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11987 return Functions.size() > 1 || 11988 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11989 } 11990 11991 /// \brief Create a unary operation that may resolve to an overloaded 11992 /// operator. 11993 /// 11994 /// \param OpLoc The location of the operator itself (e.g., '*'). 11995 /// 11996 /// \param Opc The UnaryOperatorKind that describes this operator. 11997 /// 11998 /// \param Fns The set of non-member functions that will be 11999 /// considered by overload resolution. The caller needs to build this 12000 /// set based on the context using, e.g., 12001 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12002 /// set should not contain any member functions; those will be added 12003 /// by CreateOverloadedUnaryOp(). 12004 /// 12005 /// \param Input The input argument. 12006 ExprResult 12007 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12008 const UnresolvedSetImpl &Fns, 12009 Expr *Input) { 12010 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12011 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12012 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12013 // TODO: provide better source location info. 12014 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12015 12016 if (checkPlaceholderForOverload(*this, Input)) 12017 return ExprError(); 12018 12019 Expr *Args[2] = { Input, nullptr }; 12020 unsigned NumArgs = 1; 12021 12022 // For post-increment and post-decrement, add the implicit '0' as 12023 // the second argument, so that we know this is a post-increment or 12024 // post-decrement. 12025 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12026 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12027 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12028 SourceLocation()); 12029 NumArgs = 2; 12030 } 12031 12032 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12033 12034 if (Input->isTypeDependent()) { 12035 if (Fns.empty()) 12036 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12037 VK_RValue, OK_Ordinary, OpLoc); 12038 12039 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12040 UnresolvedLookupExpr *Fn 12041 = UnresolvedLookupExpr::Create(Context, NamingClass, 12042 NestedNameSpecifierLoc(), OpNameInfo, 12043 /*ADL*/ true, IsOverloaded(Fns), 12044 Fns.begin(), Fns.end()); 12045 return new (Context) 12046 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 12047 VK_RValue, OpLoc, false); 12048 } 12049 12050 // Build an empty overload set. 12051 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12052 12053 // Add the candidates from the given function set. 12054 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 12055 12056 // Add operator candidates that are member functions. 12057 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12058 12059 // Add candidates from ADL. 12060 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12061 /*ExplicitTemplateArgs*/nullptr, 12062 CandidateSet); 12063 12064 // Add builtin operator candidates. 12065 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12066 12067 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12068 12069 // Perform overload resolution. 12070 OverloadCandidateSet::iterator Best; 12071 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12072 case OR_Success: { 12073 // We found a built-in operator or an overloaded operator. 12074 FunctionDecl *FnDecl = Best->Function; 12075 12076 if (FnDecl) { 12077 // We matched an overloaded operator. Build a call to that 12078 // operator. 12079 12080 // Convert the arguments. 12081 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12082 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12083 12084 ExprResult InputRes = 12085 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12086 Best->FoundDecl, Method); 12087 if (InputRes.isInvalid()) 12088 return ExprError(); 12089 Input = InputRes.get(); 12090 } else { 12091 // Convert the arguments. 12092 ExprResult InputInit 12093 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12094 Context, 12095 FnDecl->getParamDecl(0)), 12096 SourceLocation(), 12097 Input); 12098 if (InputInit.isInvalid()) 12099 return ExprError(); 12100 Input = InputInit.get(); 12101 } 12102 12103 // Build the actual expression node. 12104 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12105 HadMultipleCandidates, OpLoc); 12106 if (FnExpr.isInvalid()) 12107 return ExprError(); 12108 12109 // Determine the result type. 12110 QualType ResultTy = FnDecl->getReturnType(); 12111 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12112 ResultTy = ResultTy.getNonLValueExprType(Context); 12113 12114 Args[0] = Input; 12115 CallExpr *TheCall = 12116 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 12117 ResultTy, VK, OpLoc, false); 12118 12119 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12120 return ExprError(); 12121 12122 return MaybeBindToTemporary(TheCall); 12123 } else { 12124 // We matched a built-in operator. Convert the arguments, then 12125 // break out so that we will build the appropriate built-in 12126 // operator node. 12127 ExprResult InputRes = 12128 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 12129 Best->Conversions[0], AA_Passing); 12130 if (InputRes.isInvalid()) 12131 return ExprError(); 12132 Input = InputRes.get(); 12133 break; 12134 } 12135 } 12136 12137 case OR_No_Viable_Function: 12138 // This is an erroneous use of an operator which can be overloaded by 12139 // a non-member function. Check for non-member operators which were 12140 // defined too late to be candidates. 12141 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12142 // FIXME: Recover by calling the found function. 12143 return ExprError(); 12144 12145 // No viable function; fall through to handling this as a 12146 // built-in operator, which will produce an error message for us. 12147 break; 12148 12149 case OR_Ambiguous: 12150 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12151 << UnaryOperator::getOpcodeStr(Opc) 12152 << Input->getType() 12153 << Input->getSourceRange(); 12154 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 12155 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12156 return ExprError(); 12157 12158 case OR_Deleted: 12159 Diag(OpLoc, diag::err_ovl_deleted_oper) 12160 << Best->Function->isDeleted() 12161 << UnaryOperator::getOpcodeStr(Opc) 12162 << getDeletedOrUnavailableSuffix(Best->Function) 12163 << Input->getSourceRange(); 12164 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 12165 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12166 return ExprError(); 12167 } 12168 12169 // Either we found no viable overloaded operator or we matched a 12170 // built-in operator. In either case, fall through to trying to 12171 // build a built-in operation. 12172 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12173 } 12174 12175 /// \brief Create a binary operation that may resolve to an overloaded 12176 /// operator. 12177 /// 12178 /// \param OpLoc The location of the operator itself (e.g., '+'). 12179 /// 12180 /// \param Opc The BinaryOperatorKind that describes this operator. 12181 /// 12182 /// \param Fns The set of non-member functions that will be 12183 /// considered by overload resolution. The caller needs to build this 12184 /// set based on the context using, e.g., 12185 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12186 /// set should not contain any member functions; those will be added 12187 /// by CreateOverloadedBinOp(). 12188 /// 12189 /// \param LHS Left-hand argument. 12190 /// \param RHS Right-hand argument. 12191 ExprResult 12192 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12193 BinaryOperatorKind Opc, 12194 const UnresolvedSetImpl &Fns, 12195 Expr *LHS, Expr *RHS) { 12196 Expr *Args[2] = { LHS, RHS }; 12197 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12198 12199 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12200 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12201 12202 // If either side is type-dependent, create an appropriate dependent 12203 // expression. 12204 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12205 if (Fns.empty()) { 12206 // If there are no functions to store, just build a dependent 12207 // BinaryOperator or CompoundAssignment. 12208 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12209 return new (Context) BinaryOperator( 12210 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12211 OpLoc, FPFeatures.fp_contract); 12212 12213 return new (Context) CompoundAssignOperator( 12214 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12215 Context.DependentTy, Context.DependentTy, OpLoc, 12216 FPFeatures.fp_contract); 12217 } 12218 12219 // FIXME: save results of ADL from here? 12220 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12221 // TODO: provide better source location info in DNLoc component. 12222 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12223 UnresolvedLookupExpr *Fn 12224 = UnresolvedLookupExpr::Create(Context, NamingClass, 12225 NestedNameSpecifierLoc(), OpNameInfo, 12226 /*ADL*/ true, IsOverloaded(Fns), 12227 Fns.begin(), Fns.end()); 12228 return new (Context) 12229 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 12230 VK_RValue, OpLoc, FPFeatures.fp_contract); 12231 } 12232 12233 // Always do placeholder-like conversions on the RHS. 12234 if (checkPlaceholderForOverload(*this, Args[1])) 12235 return ExprError(); 12236 12237 // Do placeholder-like conversion on the LHS; note that we should 12238 // not get here with a PseudoObject LHS. 12239 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12240 if (checkPlaceholderForOverload(*this, Args[0])) 12241 return ExprError(); 12242 12243 // If this is the assignment operator, we only perform overload resolution 12244 // if the left-hand side is a class or enumeration type. This is actually 12245 // a hack. The standard requires that we do overload resolution between the 12246 // various built-in candidates, but as DR507 points out, this can lead to 12247 // problems. So we do it this way, which pretty much follows what GCC does. 12248 // Note that we go the traditional code path for compound assignment forms. 12249 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12250 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12251 12252 // If this is the .* operator, which is not overloadable, just 12253 // create a built-in binary operator. 12254 if (Opc == BO_PtrMemD) 12255 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12256 12257 // Build an empty overload set. 12258 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12259 12260 // Add the candidates from the given function set. 12261 AddFunctionCandidates(Fns, Args, CandidateSet); 12262 12263 // Add operator candidates that are member functions. 12264 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12265 12266 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12267 // performed for an assignment operator (nor for operator[] nor operator->, 12268 // which don't get here). 12269 if (Opc != BO_Assign) 12270 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12271 /*ExplicitTemplateArgs*/ nullptr, 12272 CandidateSet); 12273 12274 // Add builtin operator candidates. 12275 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12276 12277 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12278 12279 // Perform overload resolution. 12280 OverloadCandidateSet::iterator Best; 12281 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12282 case OR_Success: { 12283 // We found a built-in operator or an overloaded operator. 12284 FunctionDecl *FnDecl = Best->Function; 12285 12286 if (FnDecl) { 12287 // We matched an overloaded operator. Build a call to that 12288 // operator. 12289 12290 // Convert the arguments. 12291 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12292 // Best->Access is only meaningful for class members. 12293 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12294 12295 ExprResult Arg1 = 12296 PerformCopyInitialization( 12297 InitializedEntity::InitializeParameter(Context, 12298 FnDecl->getParamDecl(0)), 12299 SourceLocation(), Args[1]); 12300 if (Arg1.isInvalid()) 12301 return ExprError(); 12302 12303 ExprResult Arg0 = 12304 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12305 Best->FoundDecl, Method); 12306 if (Arg0.isInvalid()) 12307 return ExprError(); 12308 Args[0] = Arg0.getAs<Expr>(); 12309 Args[1] = RHS = Arg1.getAs<Expr>(); 12310 } else { 12311 // Convert the arguments. 12312 ExprResult Arg0 = PerformCopyInitialization( 12313 InitializedEntity::InitializeParameter(Context, 12314 FnDecl->getParamDecl(0)), 12315 SourceLocation(), Args[0]); 12316 if (Arg0.isInvalid()) 12317 return ExprError(); 12318 12319 ExprResult Arg1 = 12320 PerformCopyInitialization( 12321 InitializedEntity::InitializeParameter(Context, 12322 FnDecl->getParamDecl(1)), 12323 SourceLocation(), Args[1]); 12324 if (Arg1.isInvalid()) 12325 return ExprError(); 12326 Args[0] = LHS = Arg0.getAs<Expr>(); 12327 Args[1] = RHS = Arg1.getAs<Expr>(); 12328 } 12329 12330 // Build the actual expression node. 12331 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12332 Best->FoundDecl, 12333 HadMultipleCandidates, OpLoc); 12334 if (FnExpr.isInvalid()) 12335 return ExprError(); 12336 12337 // Determine the result type. 12338 QualType ResultTy = FnDecl->getReturnType(); 12339 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12340 ResultTy = ResultTy.getNonLValueExprType(Context); 12341 12342 CXXOperatorCallExpr *TheCall = 12343 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 12344 Args, ResultTy, VK, OpLoc, 12345 FPFeatures.fp_contract); 12346 12347 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12348 FnDecl)) 12349 return ExprError(); 12350 12351 ArrayRef<const Expr *> ArgsArray(Args, 2); 12352 // Cut off the implicit 'this'. 12353 if (isa<CXXMethodDecl>(FnDecl)) 12354 ArgsArray = ArgsArray.slice(1); 12355 12356 // Check for a self move. 12357 if (Op == OO_Equal) 12358 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12359 12360 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 12361 TheCall->getSourceRange(), VariadicDoesNotApply); 12362 12363 return MaybeBindToTemporary(TheCall); 12364 } else { 12365 // We matched a built-in operator. Convert the arguments, then 12366 // break out so that we will build the appropriate built-in 12367 // operator node. 12368 ExprResult ArgsRes0 = 12369 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12370 Best->Conversions[0], AA_Passing); 12371 if (ArgsRes0.isInvalid()) 12372 return ExprError(); 12373 Args[0] = ArgsRes0.get(); 12374 12375 ExprResult ArgsRes1 = 12376 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12377 Best->Conversions[1], AA_Passing); 12378 if (ArgsRes1.isInvalid()) 12379 return ExprError(); 12380 Args[1] = ArgsRes1.get(); 12381 break; 12382 } 12383 } 12384 12385 case OR_No_Viable_Function: { 12386 // C++ [over.match.oper]p9: 12387 // If the operator is the operator , [...] and there are no 12388 // viable functions, then the operator is assumed to be the 12389 // built-in operator and interpreted according to clause 5. 12390 if (Opc == BO_Comma) 12391 break; 12392 12393 // For class as left operand for assignment or compound assigment 12394 // operator do not fall through to handling in built-in, but report that 12395 // no overloaded assignment operator found 12396 ExprResult Result = ExprError(); 12397 if (Args[0]->getType()->isRecordType() && 12398 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12399 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12400 << BinaryOperator::getOpcodeStr(Opc) 12401 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12402 if (Args[0]->getType()->isIncompleteType()) { 12403 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12404 << Args[0]->getType() 12405 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12406 } 12407 } else { 12408 // This is an erroneous use of an operator which can be overloaded by 12409 // a non-member function. Check for non-member operators which were 12410 // defined too late to be candidates. 12411 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12412 // FIXME: Recover by calling the found function. 12413 return ExprError(); 12414 12415 // No viable function; try to create a built-in operation, which will 12416 // produce an error. Then, show the non-viable candidates. 12417 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12418 } 12419 assert(Result.isInvalid() && 12420 "C++ binary operator overloading is missing candidates!"); 12421 if (Result.isInvalid()) 12422 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12423 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12424 return Result; 12425 } 12426 12427 case OR_Ambiguous: 12428 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12429 << BinaryOperator::getOpcodeStr(Opc) 12430 << Args[0]->getType() << Args[1]->getType() 12431 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12432 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12433 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12434 return ExprError(); 12435 12436 case OR_Deleted: 12437 if (isImplicitlyDeleted(Best->Function)) { 12438 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12439 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12440 << Context.getRecordType(Method->getParent()) 12441 << getSpecialMember(Method); 12442 12443 // The user probably meant to call this special member. Just 12444 // explain why it's deleted. 12445 NoteDeletedFunction(Method); 12446 return ExprError(); 12447 } else { 12448 Diag(OpLoc, diag::err_ovl_deleted_oper) 12449 << Best->Function->isDeleted() 12450 << BinaryOperator::getOpcodeStr(Opc) 12451 << getDeletedOrUnavailableSuffix(Best->Function) 12452 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12453 } 12454 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12455 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12456 return ExprError(); 12457 } 12458 12459 // We matched a built-in operator; build it. 12460 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12461 } 12462 12463 ExprResult 12464 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12465 SourceLocation RLoc, 12466 Expr *Base, Expr *Idx) { 12467 Expr *Args[2] = { Base, Idx }; 12468 DeclarationName OpName = 12469 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12470 12471 // If either side is type-dependent, create an appropriate dependent 12472 // expression. 12473 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12474 12475 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12476 // CHECKME: no 'operator' keyword? 12477 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12478 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12479 UnresolvedLookupExpr *Fn 12480 = UnresolvedLookupExpr::Create(Context, NamingClass, 12481 NestedNameSpecifierLoc(), OpNameInfo, 12482 /*ADL*/ true, /*Overloaded*/ false, 12483 UnresolvedSetIterator(), 12484 UnresolvedSetIterator()); 12485 // Can't add any actual overloads yet 12486 12487 return new (Context) 12488 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12489 Context.DependentTy, VK_RValue, RLoc, false); 12490 } 12491 12492 // Handle placeholders on both operands. 12493 if (checkPlaceholderForOverload(*this, Args[0])) 12494 return ExprError(); 12495 if (checkPlaceholderForOverload(*this, Args[1])) 12496 return ExprError(); 12497 12498 // Build an empty overload set. 12499 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12500 12501 // Subscript can only be overloaded as a member function. 12502 12503 // Add operator candidates that are member functions. 12504 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12505 12506 // Add builtin operator candidates. 12507 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12508 12509 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12510 12511 // Perform overload resolution. 12512 OverloadCandidateSet::iterator Best; 12513 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12514 case OR_Success: { 12515 // We found a built-in operator or an overloaded operator. 12516 FunctionDecl *FnDecl = Best->Function; 12517 12518 if (FnDecl) { 12519 // We matched an overloaded operator. Build a call to that 12520 // operator. 12521 12522 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12523 12524 // Convert the arguments. 12525 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12526 ExprResult Arg0 = 12527 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12528 Best->FoundDecl, Method); 12529 if (Arg0.isInvalid()) 12530 return ExprError(); 12531 Args[0] = Arg0.get(); 12532 12533 // Convert the arguments. 12534 ExprResult InputInit 12535 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12536 Context, 12537 FnDecl->getParamDecl(0)), 12538 SourceLocation(), 12539 Args[1]); 12540 if (InputInit.isInvalid()) 12541 return ExprError(); 12542 12543 Args[1] = InputInit.getAs<Expr>(); 12544 12545 // Build the actual expression node. 12546 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12547 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12548 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12549 Best->FoundDecl, 12550 HadMultipleCandidates, 12551 OpLocInfo.getLoc(), 12552 OpLocInfo.getInfo()); 12553 if (FnExpr.isInvalid()) 12554 return ExprError(); 12555 12556 // Determine the result type 12557 QualType ResultTy = FnDecl->getReturnType(); 12558 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12559 ResultTy = ResultTy.getNonLValueExprType(Context); 12560 12561 CXXOperatorCallExpr *TheCall = 12562 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12563 FnExpr.get(), Args, 12564 ResultTy, VK, RLoc, 12565 false); 12566 12567 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12568 return ExprError(); 12569 12570 return MaybeBindToTemporary(TheCall); 12571 } else { 12572 // We matched a built-in operator. Convert the arguments, then 12573 // break out so that we will build the appropriate built-in 12574 // operator node. 12575 ExprResult ArgsRes0 = 12576 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12577 Best->Conversions[0], AA_Passing); 12578 if (ArgsRes0.isInvalid()) 12579 return ExprError(); 12580 Args[0] = ArgsRes0.get(); 12581 12582 ExprResult ArgsRes1 = 12583 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12584 Best->Conversions[1], AA_Passing); 12585 if (ArgsRes1.isInvalid()) 12586 return ExprError(); 12587 Args[1] = ArgsRes1.get(); 12588 12589 break; 12590 } 12591 } 12592 12593 case OR_No_Viable_Function: { 12594 if (CandidateSet.empty()) 12595 Diag(LLoc, diag::err_ovl_no_oper) 12596 << Args[0]->getType() << /*subscript*/ 0 12597 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12598 else 12599 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12600 << Args[0]->getType() 12601 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12602 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12603 "[]", LLoc); 12604 return ExprError(); 12605 } 12606 12607 case OR_Ambiguous: 12608 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12609 << "[]" 12610 << Args[0]->getType() << Args[1]->getType() 12611 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12612 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12613 "[]", LLoc); 12614 return ExprError(); 12615 12616 case OR_Deleted: 12617 Diag(LLoc, diag::err_ovl_deleted_oper) 12618 << Best->Function->isDeleted() << "[]" 12619 << getDeletedOrUnavailableSuffix(Best->Function) 12620 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12621 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12622 "[]", LLoc); 12623 return ExprError(); 12624 } 12625 12626 // We matched a built-in operator; build it. 12627 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12628 } 12629 12630 /// BuildCallToMemberFunction - Build a call to a member 12631 /// function. MemExpr is the expression that refers to the member 12632 /// function (and includes the object parameter), Args/NumArgs are the 12633 /// arguments to the function call (not including the object 12634 /// parameter). The caller needs to validate that the member 12635 /// expression refers to a non-static member function or an overloaded 12636 /// member function. 12637 ExprResult 12638 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12639 SourceLocation LParenLoc, 12640 MultiExprArg Args, 12641 SourceLocation RParenLoc) { 12642 assert(MemExprE->getType() == Context.BoundMemberTy || 12643 MemExprE->getType() == Context.OverloadTy); 12644 12645 // Dig out the member expression. This holds both the object 12646 // argument and the member function we're referring to. 12647 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12648 12649 // Determine whether this is a call to a pointer-to-member function. 12650 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12651 assert(op->getType() == Context.BoundMemberTy); 12652 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12653 12654 QualType fnType = 12655 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12656 12657 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12658 QualType resultType = proto->getCallResultType(Context); 12659 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12660 12661 // Check that the object type isn't more qualified than the 12662 // member function we're calling. 12663 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12664 12665 QualType objectType = op->getLHS()->getType(); 12666 if (op->getOpcode() == BO_PtrMemI) 12667 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12668 Qualifiers objectQuals = objectType.getQualifiers(); 12669 12670 Qualifiers difference = objectQuals - funcQuals; 12671 difference.removeObjCGCAttr(); 12672 difference.removeAddressSpace(); 12673 if (difference) { 12674 std::string qualsString = difference.getAsString(); 12675 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12676 << fnType.getUnqualifiedType() 12677 << qualsString 12678 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12679 } 12680 12681 CXXMemberCallExpr *call 12682 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12683 resultType, valueKind, RParenLoc); 12684 12685 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12686 call, nullptr)) 12687 return ExprError(); 12688 12689 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12690 return ExprError(); 12691 12692 if (CheckOtherCall(call, proto)) 12693 return ExprError(); 12694 12695 return MaybeBindToTemporary(call); 12696 } 12697 12698 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12699 return new (Context) 12700 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12701 12702 UnbridgedCastsSet UnbridgedCasts; 12703 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12704 return ExprError(); 12705 12706 MemberExpr *MemExpr; 12707 CXXMethodDecl *Method = nullptr; 12708 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12709 NestedNameSpecifier *Qualifier = nullptr; 12710 if (isa<MemberExpr>(NakedMemExpr)) { 12711 MemExpr = cast<MemberExpr>(NakedMemExpr); 12712 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12713 FoundDecl = MemExpr->getFoundDecl(); 12714 Qualifier = MemExpr->getQualifier(); 12715 UnbridgedCasts.restore(); 12716 } else { 12717 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12718 Qualifier = UnresExpr->getQualifier(); 12719 12720 QualType ObjectType = UnresExpr->getBaseType(); 12721 Expr::Classification ObjectClassification 12722 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12723 : UnresExpr->getBase()->Classify(Context); 12724 12725 // Add overload candidates 12726 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12727 OverloadCandidateSet::CSK_Normal); 12728 12729 // FIXME: avoid copy. 12730 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12731 if (UnresExpr->hasExplicitTemplateArgs()) { 12732 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12733 TemplateArgs = &TemplateArgsBuffer; 12734 } 12735 12736 // Poor-programmer's Lazy<Expr *>; isImplicitAccess requires stripping 12737 // parens/casts, which would be nice to avoid potentially doing multiple 12738 // times. 12739 llvm::Optional<Expr *> UnresolvedBase; 12740 auto GetUnresolvedBase = [&] { 12741 if (!UnresolvedBase.hasValue()) 12742 UnresolvedBase = 12743 UnresExpr->isImplicitAccess() ? nullptr : UnresExpr->getBase(); 12744 return *UnresolvedBase; 12745 }; 12746 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12747 E = UnresExpr->decls_end(); I != E; ++I) { 12748 12749 NamedDecl *Func = *I; 12750 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12751 if (isa<UsingShadowDecl>(Func)) 12752 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12753 12754 12755 // Microsoft supports direct constructor calls. 12756 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12757 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12758 Args, CandidateSet); 12759 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12760 // If explicit template arguments were provided, we can't call a 12761 // non-template member function. 12762 if (TemplateArgs) 12763 continue; 12764 12765 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12766 ObjectClassification, 12767 /*ThisArg=*/GetUnresolvedBase(), Args, CandidateSet, 12768 /*SuppressUserConversions=*/false); 12769 } else { 12770 AddMethodTemplateCandidate( 12771 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 12772 TemplateArgs, ObjectType, ObjectClassification, 12773 /*ThisArg=*/GetUnresolvedBase(), Args, CandidateSet, 12774 /*SuppressUsedConversions=*/false); 12775 } 12776 } 12777 12778 DeclarationName DeclName = UnresExpr->getMemberName(); 12779 12780 UnbridgedCasts.restore(); 12781 12782 OverloadCandidateSet::iterator Best; 12783 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12784 Best)) { 12785 case OR_Success: 12786 Method = cast<CXXMethodDecl>(Best->Function); 12787 FoundDecl = Best->FoundDecl; 12788 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12789 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12790 return ExprError(); 12791 // If FoundDecl is different from Method (such as if one is a template 12792 // and the other a specialization), make sure DiagnoseUseOfDecl is 12793 // called on both. 12794 // FIXME: This would be more comprehensively addressed by modifying 12795 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12796 // being used. 12797 if (Method != FoundDecl.getDecl() && 12798 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12799 return ExprError(); 12800 break; 12801 12802 case OR_No_Viable_Function: 12803 Diag(UnresExpr->getMemberLoc(), 12804 diag::err_ovl_no_viable_member_function_in_call) 12805 << DeclName << MemExprE->getSourceRange(); 12806 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12807 // FIXME: Leaking incoming expressions! 12808 return ExprError(); 12809 12810 case OR_Ambiguous: 12811 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12812 << DeclName << MemExprE->getSourceRange(); 12813 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12814 // FIXME: Leaking incoming expressions! 12815 return ExprError(); 12816 12817 case OR_Deleted: 12818 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12819 << Best->Function->isDeleted() 12820 << DeclName 12821 << getDeletedOrUnavailableSuffix(Best->Function) 12822 << MemExprE->getSourceRange(); 12823 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12824 // FIXME: Leaking incoming expressions! 12825 return ExprError(); 12826 } 12827 12828 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12829 12830 // If overload resolution picked a static member, build a 12831 // non-member call based on that function. 12832 if (Method->isStatic()) { 12833 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12834 RParenLoc); 12835 } 12836 12837 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12838 } 12839 12840 QualType ResultType = Method->getReturnType(); 12841 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12842 ResultType = ResultType.getNonLValueExprType(Context); 12843 12844 assert(Method && "Member call to something that isn't a method?"); 12845 CXXMemberCallExpr *TheCall = 12846 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12847 ResultType, VK, RParenLoc); 12848 12849 // Check for a valid return type. 12850 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12851 TheCall, Method)) 12852 return ExprError(); 12853 12854 // Convert the object argument (for a non-static member function call). 12855 // We only need to do this if there was actually an overload; otherwise 12856 // it was done at lookup. 12857 if (!Method->isStatic()) { 12858 ExprResult ObjectArg = 12859 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12860 FoundDecl, Method); 12861 if (ObjectArg.isInvalid()) 12862 return ExprError(); 12863 MemExpr->setBase(ObjectArg.get()); 12864 } 12865 12866 // Convert the rest of the arguments 12867 const FunctionProtoType *Proto = 12868 Method->getType()->getAs<FunctionProtoType>(); 12869 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12870 RParenLoc)) 12871 return ExprError(); 12872 12873 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12874 12875 if (CheckFunctionCall(Method, TheCall, Proto)) 12876 return ExprError(); 12877 12878 // In the case the method to call was not selected by the overloading 12879 // resolution process, we still need to handle the enable_if attribute. Do 12880 // that here, so it will not hide previous -- and more relevant -- errors. 12881 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 12882 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12883 Diag(MemE->getMemberLoc(), 12884 diag::err_ovl_no_viable_member_function_in_call) 12885 << Method << Method->getSourceRange(); 12886 Diag(Method->getLocation(), 12887 diag::note_ovl_candidate_disabled_by_function_cond_attr) 12888 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12889 return ExprError(); 12890 } 12891 12892 SmallVector<DiagnoseIfAttr *, 4> Nonfatal; 12893 if (const DiagnoseIfAttr *Attr = checkArgDependentDiagnoseIf( 12894 Method, Args, Nonfatal, false, MemE->getBase())) { 12895 emitDiagnoseIfDiagnostic(MemE->getMemberLoc(), Attr); 12896 return ExprError(); 12897 } 12898 12899 for (const auto *Attr : Nonfatal) 12900 emitDiagnoseIfDiagnostic(MemE->getMemberLoc(), Attr); 12901 } 12902 12903 if ((isa<CXXConstructorDecl>(CurContext) || 12904 isa<CXXDestructorDecl>(CurContext)) && 12905 TheCall->getMethodDecl()->isPure()) { 12906 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12907 12908 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12909 MemExpr->performsVirtualDispatch(getLangOpts())) { 12910 Diag(MemExpr->getLocStart(), 12911 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12912 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12913 << MD->getParent()->getDeclName(); 12914 12915 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12916 if (getLangOpts().AppleKext) 12917 Diag(MemExpr->getLocStart(), 12918 diag::note_pure_qualified_call_kext) 12919 << MD->getParent()->getDeclName() 12920 << MD->getDeclName(); 12921 } 12922 } 12923 12924 if (CXXDestructorDecl *DD = 12925 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12926 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12927 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 12928 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12929 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12930 MemExpr->getMemberLoc()); 12931 } 12932 12933 return MaybeBindToTemporary(TheCall); 12934 } 12935 12936 /// BuildCallToObjectOfClassType - Build a call to an object of class 12937 /// type (C++ [over.call.object]), which can end up invoking an 12938 /// overloaded function call operator (@c operator()) or performing a 12939 /// user-defined conversion on the object argument. 12940 ExprResult 12941 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12942 SourceLocation LParenLoc, 12943 MultiExprArg Args, 12944 SourceLocation RParenLoc) { 12945 if (checkPlaceholderForOverload(*this, Obj)) 12946 return ExprError(); 12947 ExprResult Object = Obj; 12948 12949 UnbridgedCastsSet UnbridgedCasts; 12950 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12951 return ExprError(); 12952 12953 assert(Object.get()->getType()->isRecordType() && 12954 "Requires object type argument"); 12955 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12956 12957 // C++ [over.call.object]p1: 12958 // If the primary-expression E in the function call syntax 12959 // evaluates to a class object of type "cv T", then the set of 12960 // candidate functions includes at least the function call 12961 // operators of T. The function call operators of T are obtained by 12962 // ordinary lookup of the name operator() in the context of 12963 // (E).operator(). 12964 OverloadCandidateSet CandidateSet(LParenLoc, 12965 OverloadCandidateSet::CSK_Operator); 12966 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12967 12968 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12969 diag::err_incomplete_object_call, Object.get())) 12970 return true; 12971 12972 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12973 LookupQualifiedName(R, Record->getDecl()); 12974 R.suppressDiagnostics(); 12975 12976 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12977 Oper != OperEnd; ++Oper) { 12978 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12979 Object.get()->Classify(Context), 12980 Object.get(), Args, CandidateSet, 12981 /*SuppressUserConversions=*/ false); 12982 } 12983 12984 // C++ [over.call.object]p2: 12985 // In addition, for each (non-explicit in C++0x) conversion function 12986 // declared in T of the form 12987 // 12988 // operator conversion-type-id () cv-qualifier; 12989 // 12990 // where cv-qualifier is the same cv-qualification as, or a 12991 // greater cv-qualification than, cv, and where conversion-type-id 12992 // denotes the type "pointer to function of (P1,...,Pn) returning 12993 // R", or the type "reference to pointer to function of 12994 // (P1,...,Pn) returning R", or the type "reference to function 12995 // of (P1,...,Pn) returning R", a surrogate call function [...] 12996 // is also considered as a candidate function. Similarly, 12997 // surrogate call functions are added to the set of candidate 12998 // functions for each conversion function declared in an 12999 // accessible base class provided the function is not hidden 13000 // within T by another intervening declaration. 13001 const auto &Conversions = 13002 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13003 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13004 NamedDecl *D = *I; 13005 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13006 if (isa<UsingShadowDecl>(D)) 13007 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13008 13009 // Skip over templated conversion functions; they aren't 13010 // surrogates. 13011 if (isa<FunctionTemplateDecl>(D)) 13012 continue; 13013 13014 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13015 if (!Conv->isExplicit()) { 13016 // Strip the reference type (if any) and then the pointer type (if 13017 // any) to get down to what might be a function type. 13018 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13019 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13020 ConvType = ConvPtrType->getPointeeType(); 13021 13022 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13023 { 13024 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13025 Object.get(), Args, CandidateSet); 13026 } 13027 } 13028 } 13029 13030 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13031 13032 // Perform overload resolution. 13033 OverloadCandidateSet::iterator Best; 13034 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 13035 Best)) { 13036 case OR_Success: 13037 // Overload resolution succeeded; we'll build the appropriate call 13038 // below. 13039 break; 13040 13041 case OR_No_Viable_Function: 13042 if (CandidateSet.empty()) 13043 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 13044 << Object.get()->getType() << /*call*/ 1 13045 << Object.get()->getSourceRange(); 13046 else 13047 Diag(Object.get()->getLocStart(), 13048 diag::err_ovl_no_viable_object_call) 13049 << Object.get()->getType() << Object.get()->getSourceRange(); 13050 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13051 break; 13052 13053 case OR_Ambiguous: 13054 Diag(Object.get()->getLocStart(), 13055 diag::err_ovl_ambiguous_object_call) 13056 << Object.get()->getType() << Object.get()->getSourceRange(); 13057 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13058 break; 13059 13060 case OR_Deleted: 13061 Diag(Object.get()->getLocStart(), 13062 diag::err_ovl_deleted_object_call) 13063 << Best->Function->isDeleted() 13064 << Object.get()->getType() 13065 << getDeletedOrUnavailableSuffix(Best->Function) 13066 << Object.get()->getSourceRange(); 13067 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13068 break; 13069 } 13070 13071 if (Best == CandidateSet.end()) 13072 return true; 13073 13074 UnbridgedCasts.restore(); 13075 13076 if (Best->Function == nullptr) { 13077 // Since there is no function declaration, this is one of the 13078 // surrogate candidates. Dig out the conversion function. 13079 CXXConversionDecl *Conv 13080 = cast<CXXConversionDecl>( 13081 Best->Conversions[0].UserDefined.ConversionFunction); 13082 13083 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13084 Best->FoundDecl); 13085 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13086 return ExprError(); 13087 assert(Conv == Best->FoundDecl.getDecl() && 13088 "Found Decl & conversion-to-functionptr should be same, right?!"); 13089 // We selected one of the surrogate functions that converts the 13090 // object parameter to a function pointer. Perform the conversion 13091 // on the object argument, then let ActOnCallExpr finish the job. 13092 13093 // Create an implicit member expr to refer to the conversion operator. 13094 // and then call it. 13095 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13096 Conv, HadMultipleCandidates); 13097 if (Call.isInvalid()) 13098 return ExprError(); 13099 // Record usage of conversion in an implicit cast. 13100 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13101 CK_UserDefinedConversion, Call.get(), 13102 nullptr, VK_RValue); 13103 13104 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13105 } 13106 13107 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13108 13109 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13110 // that calls this method, using Object for the implicit object 13111 // parameter and passing along the remaining arguments. 13112 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13113 13114 // An error diagnostic has already been printed when parsing the declaration. 13115 if (Method->isInvalidDecl()) 13116 return ExprError(); 13117 13118 const FunctionProtoType *Proto = 13119 Method->getType()->getAs<FunctionProtoType>(); 13120 13121 unsigned NumParams = Proto->getNumParams(); 13122 13123 DeclarationNameInfo OpLocInfo( 13124 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13125 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13126 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13127 HadMultipleCandidates, 13128 OpLocInfo.getLoc(), 13129 OpLocInfo.getInfo()); 13130 if (NewFn.isInvalid()) 13131 return true; 13132 13133 // Build the full argument list for the method call (the implicit object 13134 // parameter is placed at the beginning of the list). 13135 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1); 13136 MethodArgs[0] = Object.get(); 13137 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1); 13138 13139 // Once we've built TheCall, all of the expressions are properly 13140 // owned. 13141 QualType ResultTy = Method->getReturnType(); 13142 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13143 ResultTy = ResultTy.getNonLValueExprType(Context); 13144 13145 CXXOperatorCallExpr *TheCall = new (Context) 13146 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, 13147 VK, RParenLoc, false); 13148 13149 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13150 return true; 13151 13152 // We may have default arguments. If so, we need to allocate more 13153 // slots in the call for them. 13154 if (Args.size() < NumParams) 13155 TheCall->setNumArgs(Context, NumParams + 1); 13156 13157 bool IsError = false; 13158 13159 // Initialize the implicit object parameter. 13160 ExprResult ObjRes = 13161 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13162 Best->FoundDecl, Method); 13163 if (ObjRes.isInvalid()) 13164 IsError = true; 13165 else 13166 Object = ObjRes; 13167 TheCall->setArg(0, Object.get()); 13168 13169 // Check the argument types. 13170 for (unsigned i = 0; i != NumParams; i++) { 13171 Expr *Arg; 13172 if (i < Args.size()) { 13173 Arg = Args[i]; 13174 13175 // Pass the argument. 13176 13177 ExprResult InputInit 13178 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13179 Context, 13180 Method->getParamDecl(i)), 13181 SourceLocation(), Arg); 13182 13183 IsError |= InputInit.isInvalid(); 13184 Arg = InputInit.getAs<Expr>(); 13185 } else { 13186 ExprResult DefArg 13187 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13188 if (DefArg.isInvalid()) { 13189 IsError = true; 13190 break; 13191 } 13192 13193 Arg = DefArg.getAs<Expr>(); 13194 } 13195 13196 TheCall->setArg(i + 1, Arg); 13197 } 13198 13199 // If this is a variadic call, handle args passed through "...". 13200 if (Proto->isVariadic()) { 13201 // Promote the arguments (C99 6.5.2.2p7). 13202 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13203 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13204 nullptr); 13205 IsError |= Arg.isInvalid(); 13206 TheCall->setArg(i + 1, Arg.get()); 13207 } 13208 } 13209 13210 if (IsError) return true; 13211 13212 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13213 13214 if (CheckFunctionCall(Method, TheCall, Proto)) 13215 return true; 13216 13217 return MaybeBindToTemporary(TheCall); 13218 } 13219 13220 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13221 /// (if one exists), where @c Base is an expression of class type and 13222 /// @c Member is the name of the member we're trying to find. 13223 ExprResult 13224 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13225 bool *NoArrowOperatorFound) { 13226 assert(Base->getType()->isRecordType() && 13227 "left-hand side must have class type"); 13228 13229 if (checkPlaceholderForOverload(*this, Base)) 13230 return ExprError(); 13231 13232 SourceLocation Loc = Base->getExprLoc(); 13233 13234 // C++ [over.ref]p1: 13235 // 13236 // [...] An expression x->m is interpreted as (x.operator->())->m 13237 // for a class object x of type T if T::operator->() exists and if 13238 // the operator is selected as the best match function by the 13239 // overload resolution mechanism (13.3). 13240 DeclarationName OpName = 13241 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13242 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13243 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13244 13245 if (RequireCompleteType(Loc, Base->getType(), 13246 diag::err_typecheck_incomplete_tag, Base)) 13247 return ExprError(); 13248 13249 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13250 LookupQualifiedName(R, BaseRecord->getDecl()); 13251 R.suppressDiagnostics(); 13252 13253 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13254 Oper != OperEnd; ++Oper) { 13255 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13256 Base, None, CandidateSet, 13257 /*SuppressUserConversions=*/false); 13258 } 13259 13260 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13261 13262 // Perform overload resolution. 13263 OverloadCandidateSet::iterator Best; 13264 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13265 case OR_Success: 13266 // Overload resolution succeeded; we'll build the call below. 13267 break; 13268 13269 case OR_No_Viable_Function: 13270 if (CandidateSet.empty()) { 13271 QualType BaseType = Base->getType(); 13272 if (NoArrowOperatorFound) { 13273 // Report this specific error to the caller instead of emitting a 13274 // diagnostic, as requested. 13275 *NoArrowOperatorFound = true; 13276 return ExprError(); 13277 } 13278 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13279 << BaseType << Base->getSourceRange(); 13280 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13281 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13282 << FixItHint::CreateReplacement(OpLoc, "."); 13283 } 13284 } else 13285 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13286 << "operator->" << Base->getSourceRange(); 13287 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13288 return ExprError(); 13289 13290 case OR_Ambiguous: 13291 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 13292 << "->" << Base->getType() << Base->getSourceRange(); 13293 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 13294 return ExprError(); 13295 13296 case OR_Deleted: 13297 Diag(OpLoc, diag::err_ovl_deleted_oper) 13298 << Best->Function->isDeleted() 13299 << "->" 13300 << getDeletedOrUnavailableSuffix(Best->Function) 13301 << Base->getSourceRange(); 13302 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13303 return ExprError(); 13304 } 13305 13306 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13307 13308 // Convert the object parameter. 13309 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13310 ExprResult BaseResult = 13311 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13312 Best->FoundDecl, Method); 13313 if (BaseResult.isInvalid()) 13314 return ExprError(); 13315 Base = BaseResult.get(); 13316 13317 // Build the operator call. 13318 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13319 HadMultipleCandidates, OpLoc); 13320 if (FnExpr.isInvalid()) 13321 return ExprError(); 13322 13323 QualType ResultTy = Method->getReturnType(); 13324 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13325 ResultTy = ResultTy.getNonLValueExprType(Context); 13326 CXXOperatorCallExpr *TheCall = 13327 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 13328 Base, ResultTy, VK, OpLoc, false); 13329 13330 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13331 return ExprError(); 13332 13333 return MaybeBindToTemporary(TheCall); 13334 } 13335 13336 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13337 /// a literal operator described by the provided lookup results. 13338 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13339 DeclarationNameInfo &SuffixInfo, 13340 ArrayRef<Expr*> Args, 13341 SourceLocation LitEndLoc, 13342 TemplateArgumentListInfo *TemplateArgs) { 13343 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13344 13345 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13346 OverloadCandidateSet::CSK_Normal); 13347 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13348 /*SuppressUserConversions=*/true); 13349 13350 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13351 13352 // Perform overload resolution. This will usually be trivial, but might need 13353 // to perform substitutions for a literal operator template. 13354 OverloadCandidateSet::iterator Best; 13355 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13356 case OR_Success: 13357 case OR_Deleted: 13358 break; 13359 13360 case OR_No_Viable_Function: 13361 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13362 << R.getLookupName(); 13363 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13364 return ExprError(); 13365 13366 case OR_Ambiguous: 13367 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13368 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13369 return ExprError(); 13370 } 13371 13372 FunctionDecl *FD = Best->Function; 13373 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13374 HadMultipleCandidates, 13375 SuffixInfo.getLoc(), 13376 SuffixInfo.getInfo()); 13377 if (Fn.isInvalid()) 13378 return true; 13379 13380 // Check the argument types. This should almost always be a no-op, except 13381 // that array-to-pointer decay is applied to string literals. 13382 Expr *ConvArgs[2]; 13383 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13384 ExprResult InputInit = PerformCopyInitialization( 13385 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13386 SourceLocation(), Args[ArgIdx]); 13387 if (InputInit.isInvalid()) 13388 return true; 13389 ConvArgs[ArgIdx] = InputInit.get(); 13390 } 13391 13392 QualType ResultTy = FD->getReturnType(); 13393 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13394 ResultTy = ResultTy.getNonLValueExprType(Context); 13395 13396 UserDefinedLiteral *UDL = 13397 new (Context) UserDefinedLiteral(Context, Fn.get(), 13398 llvm::makeArrayRef(ConvArgs, Args.size()), 13399 ResultTy, VK, LitEndLoc, UDSuffixLoc); 13400 13401 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13402 return ExprError(); 13403 13404 if (CheckFunctionCall(FD, UDL, nullptr)) 13405 return ExprError(); 13406 13407 return MaybeBindToTemporary(UDL); 13408 } 13409 13410 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13411 /// given LookupResult is non-empty, it is assumed to describe a member which 13412 /// will be invoked. Otherwise, the function will be found via argument 13413 /// dependent lookup. 13414 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13415 /// otherwise CallExpr is set to ExprError() and some non-success value 13416 /// is returned. 13417 Sema::ForRangeStatus 13418 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13419 SourceLocation RangeLoc, 13420 const DeclarationNameInfo &NameInfo, 13421 LookupResult &MemberLookup, 13422 OverloadCandidateSet *CandidateSet, 13423 Expr *Range, ExprResult *CallExpr) { 13424 Scope *S = nullptr; 13425 13426 CandidateSet->clear(); 13427 if (!MemberLookup.empty()) { 13428 ExprResult MemberRef = 13429 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13430 /*IsPtr=*/false, CXXScopeSpec(), 13431 /*TemplateKWLoc=*/SourceLocation(), 13432 /*FirstQualifierInScope=*/nullptr, 13433 MemberLookup, 13434 /*TemplateArgs=*/nullptr, S); 13435 if (MemberRef.isInvalid()) { 13436 *CallExpr = ExprError(); 13437 return FRS_DiagnosticIssued; 13438 } 13439 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13440 if (CallExpr->isInvalid()) { 13441 *CallExpr = ExprError(); 13442 return FRS_DiagnosticIssued; 13443 } 13444 } else { 13445 UnresolvedSet<0> FoundNames; 13446 UnresolvedLookupExpr *Fn = 13447 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13448 NestedNameSpecifierLoc(), NameInfo, 13449 /*NeedsADL=*/true, /*Overloaded=*/false, 13450 FoundNames.begin(), FoundNames.end()); 13451 13452 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13453 CandidateSet, CallExpr); 13454 if (CandidateSet->empty() || CandidateSetError) { 13455 *CallExpr = ExprError(); 13456 return FRS_NoViableFunction; 13457 } 13458 OverloadCandidateSet::iterator Best; 13459 OverloadingResult OverloadResult = 13460 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 13461 13462 if (OverloadResult == OR_No_Viable_Function) { 13463 *CallExpr = ExprError(); 13464 return FRS_NoViableFunction; 13465 } 13466 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13467 Loc, nullptr, CandidateSet, &Best, 13468 OverloadResult, 13469 /*AllowTypoCorrection=*/false); 13470 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13471 *CallExpr = ExprError(); 13472 return FRS_DiagnosticIssued; 13473 } 13474 } 13475 return FRS_Success; 13476 } 13477 13478 13479 /// FixOverloadedFunctionReference - E is an expression that refers to 13480 /// a C++ overloaded function (possibly with some parentheses and 13481 /// perhaps a '&' around it). We have resolved the overloaded function 13482 /// to the function declaration Fn, so patch up the expression E to 13483 /// refer (possibly indirectly) to Fn. Returns the new expr. 13484 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13485 FunctionDecl *Fn) { 13486 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13487 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13488 Found, Fn); 13489 if (SubExpr == PE->getSubExpr()) 13490 return PE; 13491 13492 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13493 } 13494 13495 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13496 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13497 Found, Fn); 13498 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13499 SubExpr->getType()) && 13500 "Implicit cast type cannot be determined from overload"); 13501 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13502 if (SubExpr == ICE->getSubExpr()) 13503 return ICE; 13504 13505 return ImplicitCastExpr::Create(Context, ICE->getType(), 13506 ICE->getCastKind(), 13507 SubExpr, nullptr, 13508 ICE->getValueKind()); 13509 } 13510 13511 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13512 if (!GSE->isResultDependent()) { 13513 Expr *SubExpr = 13514 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13515 if (SubExpr == GSE->getResultExpr()) 13516 return GSE; 13517 13518 // Replace the resulting type information before rebuilding the generic 13519 // selection expression. 13520 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13521 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13522 unsigned ResultIdx = GSE->getResultIndex(); 13523 AssocExprs[ResultIdx] = SubExpr; 13524 13525 return new (Context) GenericSelectionExpr( 13526 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13527 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13528 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13529 ResultIdx); 13530 } 13531 // Rather than fall through to the unreachable, return the original generic 13532 // selection expression. 13533 return GSE; 13534 } 13535 13536 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13537 assert(UnOp->getOpcode() == UO_AddrOf && 13538 "Can only take the address of an overloaded function"); 13539 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13540 if (Method->isStatic()) { 13541 // Do nothing: static member functions aren't any different 13542 // from non-member functions. 13543 } else { 13544 // Fix the subexpression, which really has to be an 13545 // UnresolvedLookupExpr holding an overloaded member function 13546 // or template. 13547 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13548 Found, Fn); 13549 if (SubExpr == UnOp->getSubExpr()) 13550 return UnOp; 13551 13552 assert(isa<DeclRefExpr>(SubExpr) 13553 && "fixed to something other than a decl ref"); 13554 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13555 && "fixed to a member ref with no nested name qualifier"); 13556 13557 // We have taken the address of a pointer to member 13558 // function. Perform the computation here so that we get the 13559 // appropriate pointer to member type. 13560 QualType ClassType 13561 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13562 QualType MemPtrType 13563 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13564 // Under the MS ABI, lock down the inheritance model now. 13565 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13566 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13567 13568 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13569 VK_RValue, OK_Ordinary, 13570 UnOp->getOperatorLoc()); 13571 } 13572 } 13573 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13574 Found, Fn); 13575 if (SubExpr == UnOp->getSubExpr()) 13576 return UnOp; 13577 13578 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13579 Context.getPointerType(SubExpr->getType()), 13580 VK_RValue, OK_Ordinary, 13581 UnOp->getOperatorLoc()); 13582 } 13583 13584 // C++ [except.spec]p17: 13585 // An exception-specification is considered to be needed when: 13586 // - in an expression the function is the unique lookup result or the 13587 // selected member of a set of overloaded functions 13588 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13589 ResolveExceptionSpec(E->getExprLoc(), FPT); 13590 13591 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13592 // FIXME: avoid copy. 13593 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13594 if (ULE->hasExplicitTemplateArgs()) { 13595 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13596 TemplateArgs = &TemplateArgsBuffer; 13597 } 13598 13599 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13600 ULE->getQualifierLoc(), 13601 ULE->getTemplateKeywordLoc(), 13602 Fn, 13603 /*enclosing*/ false, // FIXME? 13604 ULE->getNameLoc(), 13605 Fn->getType(), 13606 VK_LValue, 13607 Found.getDecl(), 13608 TemplateArgs); 13609 MarkDeclRefReferenced(DRE); 13610 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13611 return DRE; 13612 } 13613 13614 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13615 // FIXME: avoid copy. 13616 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13617 if (MemExpr->hasExplicitTemplateArgs()) { 13618 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13619 TemplateArgs = &TemplateArgsBuffer; 13620 } 13621 13622 Expr *Base; 13623 13624 // If we're filling in a static method where we used to have an 13625 // implicit member access, rewrite to a simple decl ref. 13626 if (MemExpr->isImplicitAccess()) { 13627 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13628 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13629 MemExpr->getQualifierLoc(), 13630 MemExpr->getTemplateKeywordLoc(), 13631 Fn, 13632 /*enclosing*/ false, 13633 MemExpr->getMemberLoc(), 13634 Fn->getType(), 13635 VK_LValue, 13636 Found.getDecl(), 13637 TemplateArgs); 13638 MarkDeclRefReferenced(DRE); 13639 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13640 return DRE; 13641 } else { 13642 SourceLocation Loc = MemExpr->getMemberLoc(); 13643 if (MemExpr->getQualifier()) 13644 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13645 CheckCXXThisCapture(Loc); 13646 Base = new (Context) CXXThisExpr(Loc, 13647 MemExpr->getBaseType(), 13648 /*isImplicit=*/true); 13649 } 13650 } else 13651 Base = MemExpr->getBase(); 13652 13653 ExprValueKind valueKind; 13654 QualType type; 13655 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13656 valueKind = VK_LValue; 13657 type = Fn->getType(); 13658 } else { 13659 valueKind = VK_RValue; 13660 type = Context.BoundMemberTy; 13661 } 13662 13663 MemberExpr *ME = MemberExpr::Create( 13664 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13665 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13666 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13667 OK_Ordinary); 13668 ME->setHadMultipleCandidates(true); 13669 MarkMemberReferenced(ME); 13670 return ME; 13671 } 13672 13673 llvm_unreachable("Invalid reference to overloaded function"); 13674 } 13675 13676 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13677 DeclAccessPair Found, 13678 FunctionDecl *Fn) { 13679 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13680 } 13681