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 SlabAllocator.Reset(); 843 NumInlineBytesUsed = 0; 844 Candidates.clear(); 845 Functions.clear(); 846 } 847 848 namespace { 849 class UnbridgedCastsSet { 850 struct Entry { 851 Expr **Addr; 852 Expr *Saved; 853 }; 854 SmallVector<Entry, 2> Entries; 855 856 public: 857 void save(Sema &S, Expr *&E) { 858 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 859 Entry entry = { &E, E }; 860 Entries.push_back(entry); 861 E = S.stripARCUnbridgedCast(E); 862 } 863 864 void restore() { 865 for (SmallVectorImpl<Entry>::iterator 866 i = Entries.begin(), e = Entries.end(); i != e; ++i) 867 *i->Addr = i->Saved; 868 } 869 }; 870 } 871 872 /// checkPlaceholderForOverload - Do any interesting placeholder-like 873 /// preprocessing on the given expression. 874 /// 875 /// \param unbridgedCasts a collection to which to add unbridged casts; 876 /// without this, they will be immediately diagnosed as errors 877 /// 878 /// Return true on unrecoverable error. 879 static bool 880 checkPlaceholderForOverload(Sema &S, Expr *&E, 881 UnbridgedCastsSet *unbridgedCasts = nullptr) { 882 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 883 // We can't handle overloaded expressions here because overload 884 // resolution might reasonably tweak them. 885 if (placeholder->getKind() == BuiltinType::Overload) return false; 886 887 // If the context potentially accepts unbridged ARC casts, strip 888 // the unbridged cast and add it to the collection for later restoration. 889 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 890 unbridgedCasts) { 891 unbridgedCasts->save(S, E); 892 return false; 893 } 894 895 // Go ahead and check everything else. 896 ExprResult result = S.CheckPlaceholderExpr(E); 897 if (result.isInvalid()) 898 return true; 899 900 E = result.get(); 901 return false; 902 } 903 904 // Nothing to do. 905 return false; 906 } 907 908 /// checkArgPlaceholdersForOverload - Check a set of call operands for 909 /// placeholders. 910 static bool checkArgPlaceholdersForOverload(Sema &S, 911 MultiExprArg Args, 912 UnbridgedCastsSet &unbridged) { 913 for (unsigned i = 0, e = Args.size(); i != e; ++i) 914 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 915 return true; 916 917 return false; 918 } 919 920 // IsOverload - Determine whether the given New declaration is an 921 // overload of the declarations in Old. This routine returns false if 922 // New and Old cannot be overloaded, e.g., if New has the same 923 // signature as some function in Old (C++ 1.3.10) or if the Old 924 // declarations aren't functions (or function templates) at all. When 925 // it does return false, MatchedDecl will point to the decl that New 926 // cannot be overloaded with. This decl may be a UsingShadowDecl on 927 // top of the underlying declaration. 928 // 929 // Example: Given the following input: 930 // 931 // void f(int, float); // #1 932 // void f(int, int); // #2 933 // int f(int, int); // #3 934 // 935 // When we process #1, there is no previous declaration of "f", 936 // so IsOverload will not be used. 937 // 938 // When we process #2, Old contains only the FunctionDecl for #1. By 939 // comparing the parameter types, we see that #1 and #2 are overloaded 940 // (since they have different signatures), so this routine returns 941 // false; MatchedDecl is unchanged. 942 // 943 // When we process #3, Old is an overload set containing #1 and #2. We 944 // compare the signatures of #3 to #1 (they're overloaded, so we do 945 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 946 // identical (return types of functions are not part of the 947 // signature), IsOverload returns false and MatchedDecl will be set to 948 // point to the FunctionDecl for #2. 949 // 950 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 951 // into a class by a using declaration. The rules for whether to hide 952 // shadow declarations ignore some properties which otherwise figure 953 // into a function template's signature. 954 Sema::OverloadKind 955 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 956 NamedDecl *&Match, bool NewIsUsingDecl) { 957 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 958 I != E; ++I) { 959 NamedDecl *OldD = *I; 960 961 bool OldIsUsingDecl = false; 962 if (isa<UsingShadowDecl>(OldD)) { 963 OldIsUsingDecl = true; 964 965 // We can always introduce two using declarations into the same 966 // context, even if they have identical signatures. 967 if (NewIsUsingDecl) continue; 968 969 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 970 } 971 972 // A using-declaration does not conflict with another declaration 973 // if one of them is hidden. 974 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 975 continue; 976 977 // If either declaration was introduced by a using declaration, 978 // we'll need to use slightly different rules for matching. 979 // Essentially, these rules are the normal rules, except that 980 // function templates hide function templates with different 981 // return types or template parameter lists. 982 bool UseMemberUsingDeclRules = 983 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 984 !New->getFriendObjectKind(); 985 986 if (FunctionDecl *OldF = OldD->getAsFunction()) { 987 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 988 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 989 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 990 continue; 991 } 992 993 if (!isa<FunctionTemplateDecl>(OldD) && 994 !shouldLinkPossiblyHiddenDecl(*I, New)) 995 continue; 996 997 Match = *I; 998 return Ovl_Match; 999 } 1000 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1001 // We can overload with these, which can show up when doing 1002 // redeclaration checks for UsingDecls. 1003 assert(Old.getLookupKind() == LookupUsingDeclName); 1004 } else if (isa<TagDecl>(OldD)) { 1005 // We can always overload with tags by hiding them. 1006 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1007 // Optimistically assume that an unresolved using decl will 1008 // overload; if it doesn't, we'll have to diagnose during 1009 // template instantiation. 1010 // 1011 // Exception: if the scope is dependent and this is not a class 1012 // member, the using declaration can only introduce an enumerator. 1013 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1014 Match = *I; 1015 return Ovl_NonFunction; 1016 } 1017 } else { 1018 // (C++ 13p1): 1019 // Only function declarations can be overloaded; object and type 1020 // declarations cannot be overloaded. 1021 Match = *I; 1022 return Ovl_NonFunction; 1023 } 1024 } 1025 1026 return Ovl_Overload; 1027 } 1028 1029 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1030 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1031 // C++ [basic.start.main]p2: This function shall not be overloaded. 1032 if (New->isMain()) 1033 return false; 1034 1035 // MSVCRT user defined entry points cannot be overloaded. 1036 if (New->isMSVCRTEntryPoint()) 1037 return false; 1038 1039 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1040 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1041 1042 // C++ [temp.fct]p2: 1043 // A function template can be overloaded with other function templates 1044 // and with normal (non-template) functions. 1045 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1046 return true; 1047 1048 // Is the function New an overload of the function Old? 1049 QualType OldQType = Context.getCanonicalType(Old->getType()); 1050 QualType NewQType = Context.getCanonicalType(New->getType()); 1051 1052 // Compare the signatures (C++ 1.3.10) of the two functions to 1053 // determine whether they are overloads. If we find any mismatch 1054 // in the signature, they are overloads. 1055 1056 // If either of these functions is a K&R-style function (no 1057 // prototype), then we consider them to have matching signatures. 1058 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1059 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1060 return false; 1061 1062 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1063 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1064 1065 // The signature of a function includes the types of its 1066 // parameters (C++ 1.3.10), which includes the presence or absence 1067 // of the ellipsis; see C++ DR 357). 1068 if (OldQType != NewQType && 1069 (OldType->getNumParams() != NewType->getNumParams() || 1070 OldType->isVariadic() != NewType->isVariadic() || 1071 !FunctionParamTypesAreEqual(OldType, NewType))) 1072 return true; 1073 1074 // C++ [temp.over.link]p4: 1075 // The signature of a function template consists of its function 1076 // signature, its return type and its template parameter list. The names 1077 // of the template parameters are significant only for establishing the 1078 // relationship between the template parameters and the rest of the 1079 // signature. 1080 // 1081 // We check the return type and template parameter lists for function 1082 // templates first; the remaining checks follow. 1083 // 1084 // However, we don't consider either of these when deciding whether 1085 // a member introduced by a shadow declaration is hidden. 1086 if (!UseMemberUsingDeclRules && NewTemplate && 1087 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1088 OldTemplate->getTemplateParameters(), 1089 false, TPL_TemplateMatch) || 1090 OldType->getReturnType() != NewType->getReturnType())) 1091 return true; 1092 1093 // If the function is a class member, its signature includes the 1094 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1095 // 1096 // As part of this, also check whether one of the member functions 1097 // is static, in which case they are not overloads (C++ 1098 // 13.1p2). While not part of the definition of the signature, 1099 // this check is important to determine whether these functions 1100 // can be overloaded. 1101 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1102 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1103 if (OldMethod && NewMethod && 1104 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1105 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1106 if (!UseMemberUsingDeclRules && 1107 (OldMethod->getRefQualifier() == RQ_None || 1108 NewMethod->getRefQualifier() == RQ_None)) { 1109 // C++0x [over.load]p2: 1110 // - Member function declarations with the same name and the same 1111 // parameter-type-list as well as member function template 1112 // declarations with the same name, the same parameter-type-list, and 1113 // the same template parameter lists cannot be overloaded if any of 1114 // them, but not all, have a ref-qualifier (8.3.5). 1115 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1116 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1117 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1118 } 1119 return true; 1120 } 1121 1122 // We may not have applied the implicit const for a constexpr member 1123 // function yet (because we haven't yet resolved whether this is a static 1124 // or non-static member function). Add it now, on the assumption that this 1125 // is a redeclaration of OldMethod. 1126 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1127 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1128 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1129 !isa<CXXConstructorDecl>(NewMethod)) 1130 NewQuals |= Qualifiers::Const; 1131 1132 // We do not allow overloading based off of '__restrict'. 1133 OldQuals &= ~Qualifiers::Restrict; 1134 NewQuals &= ~Qualifiers::Restrict; 1135 if (OldQuals != NewQuals) 1136 return true; 1137 } 1138 1139 // Though pass_object_size is placed on parameters and takes an argument, we 1140 // consider it to be a function-level modifier for the sake of function 1141 // identity. Either the function has one or more parameters with 1142 // pass_object_size or it doesn't. 1143 if (functionHasPassObjectSizeParams(New) != 1144 functionHasPassObjectSizeParams(Old)) 1145 return true; 1146 1147 // enable_if attributes are an order-sensitive part of the signature. 1148 for (specific_attr_iterator<EnableIfAttr> 1149 NewI = New->specific_attr_begin<EnableIfAttr>(), 1150 NewE = New->specific_attr_end<EnableIfAttr>(), 1151 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1152 OldE = Old->specific_attr_end<EnableIfAttr>(); 1153 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1154 if (NewI == NewE || OldI == OldE) 1155 return true; 1156 llvm::FoldingSetNodeID NewID, OldID; 1157 NewI->getCond()->Profile(NewID, Context, true); 1158 OldI->getCond()->Profile(OldID, Context, true); 1159 if (NewID != OldID) 1160 return true; 1161 } 1162 1163 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1164 // Don't allow overloading of destructors. (In theory we could, but it 1165 // would be a giant change to clang.) 1166 if (isa<CXXDestructorDecl>(New)) 1167 return false; 1168 1169 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1170 OldTarget = IdentifyCUDATarget(Old); 1171 if (NewTarget == CFT_InvalidTarget) 1172 return false; 1173 1174 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1175 1176 // Allow overloading of functions with same signature and different CUDA 1177 // target attributes. 1178 return NewTarget != OldTarget; 1179 } 1180 1181 // The signatures match; this is not an overload. 1182 return false; 1183 } 1184 1185 /// \brief Checks availability of the function depending on the current 1186 /// function context. Inside an unavailable function, unavailability is ignored. 1187 /// 1188 /// \returns true if \arg FD is unavailable and current context is inside 1189 /// an available function, false otherwise. 1190 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1191 if (!FD->isUnavailable()) 1192 return false; 1193 1194 // Walk up the context of the caller. 1195 Decl *C = cast<Decl>(CurContext); 1196 do { 1197 if (C->isUnavailable()) 1198 return false; 1199 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1200 return true; 1201 } 1202 1203 /// \brief Tries a user-defined conversion from From to ToType. 1204 /// 1205 /// Produces an implicit conversion sequence for when a standard conversion 1206 /// is not an option. See TryImplicitConversion for more information. 1207 static ImplicitConversionSequence 1208 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1209 bool SuppressUserConversions, 1210 bool AllowExplicit, 1211 bool InOverloadResolution, 1212 bool CStyle, 1213 bool AllowObjCWritebackConversion, 1214 bool AllowObjCConversionOnExplicit) { 1215 ImplicitConversionSequence ICS; 1216 1217 if (SuppressUserConversions) { 1218 // We're not in the case above, so there is no conversion that 1219 // we can perform. 1220 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1221 return ICS; 1222 } 1223 1224 // Attempt user-defined conversion. 1225 OverloadCandidateSet Conversions(From->getExprLoc(), 1226 OverloadCandidateSet::CSK_Normal); 1227 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1228 Conversions, AllowExplicit, 1229 AllowObjCConversionOnExplicit)) { 1230 case OR_Success: 1231 case OR_Deleted: 1232 ICS.setUserDefined(); 1233 // C++ [over.ics.user]p4: 1234 // A conversion of an expression of class type to the same class 1235 // type is given Exact Match rank, and a conversion of an 1236 // expression of class type to a base class of that type is 1237 // given Conversion rank, in spite of the fact that a copy 1238 // constructor (i.e., a user-defined conversion function) is 1239 // called for those cases. 1240 if (CXXConstructorDecl *Constructor 1241 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1242 QualType FromCanon 1243 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1244 QualType ToCanon 1245 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1246 if (Constructor->isCopyConstructor() && 1247 (FromCanon == ToCanon || 1248 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1249 // Turn this into a "standard" conversion sequence, so that it 1250 // gets ranked with standard conversion sequences. 1251 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1252 ICS.setStandard(); 1253 ICS.Standard.setAsIdentityConversion(); 1254 ICS.Standard.setFromType(From->getType()); 1255 ICS.Standard.setAllToTypes(ToType); 1256 ICS.Standard.CopyConstructor = Constructor; 1257 ICS.Standard.FoundCopyConstructor = Found; 1258 if (ToCanon != FromCanon) 1259 ICS.Standard.Second = ICK_Derived_To_Base; 1260 } 1261 } 1262 break; 1263 1264 case OR_Ambiguous: 1265 ICS.setAmbiguous(); 1266 ICS.Ambiguous.setFromType(From->getType()); 1267 ICS.Ambiguous.setToType(ToType); 1268 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1269 Cand != Conversions.end(); ++Cand) 1270 if (Cand->Viable) 1271 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1272 break; 1273 1274 // Fall through. 1275 case OR_No_Viable_Function: 1276 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1277 break; 1278 } 1279 1280 return ICS; 1281 } 1282 1283 /// TryImplicitConversion - Attempt to perform an implicit conversion 1284 /// from the given expression (Expr) to the given type (ToType). This 1285 /// function returns an implicit conversion sequence that can be used 1286 /// to perform the initialization. Given 1287 /// 1288 /// void f(float f); 1289 /// void g(int i) { f(i); } 1290 /// 1291 /// this routine would produce an implicit conversion sequence to 1292 /// describe the initialization of f from i, which will be a standard 1293 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1294 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1295 // 1296 /// Note that this routine only determines how the conversion can be 1297 /// performed; it does not actually perform the conversion. As such, 1298 /// it will not produce any diagnostics if no conversion is available, 1299 /// but will instead return an implicit conversion sequence of kind 1300 /// "BadConversion". 1301 /// 1302 /// If @p SuppressUserConversions, then user-defined conversions are 1303 /// not permitted. 1304 /// If @p AllowExplicit, then explicit user-defined conversions are 1305 /// permitted. 1306 /// 1307 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1308 /// writeback conversion, which allows __autoreleasing id* parameters to 1309 /// be initialized with __strong id* or __weak id* arguments. 1310 static ImplicitConversionSequence 1311 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1312 bool SuppressUserConversions, 1313 bool AllowExplicit, 1314 bool InOverloadResolution, 1315 bool CStyle, 1316 bool AllowObjCWritebackConversion, 1317 bool AllowObjCConversionOnExplicit) { 1318 ImplicitConversionSequence ICS; 1319 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1320 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1321 ICS.setStandard(); 1322 return ICS; 1323 } 1324 1325 if (!S.getLangOpts().CPlusPlus) { 1326 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1327 return ICS; 1328 } 1329 1330 // C++ [over.ics.user]p4: 1331 // A conversion of an expression of class type to the same class 1332 // type is given Exact Match rank, and a conversion of an 1333 // expression of class type to a base class of that type is 1334 // given Conversion rank, in spite of the fact that a copy/move 1335 // constructor (i.e., a user-defined conversion function) is 1336 // called for those cases. 1337 QualType FromType = From->getType(); 1338 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1339 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1340 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1341 ICS.setStandard(); 1342 ICS.Standard.setAsIdentityConversion(); 1343 ICS.Standard.setFromType(FromType); 1344 ICS.Standard.setAllToTypes(ToType); 1345 1346 // We don't actually check at this point whether there is a valid 1347 // copy/move constructor, since overloading just assumes that it 1348 // exists. When we actually perform initialization, we'll find the 1349 // appropriate constructor to copy the returned object, if needed. 1350 ICS.Standard.CopyConstructor = nullptr; 1351 1352 // Determine whether this is considered a derived-to-base conversion. 1353 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1354 ICS.Standard.Second = ICK_Derived_To_Base; 1355 1356 return ICS; 1357 } 1358 1359 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1360 AllowExplicit, InOverloadResolution, CStyle, 1361 AllowObjCWritebackConversion, 1362 AllowObjCConversionOnExplicit); 1363 } 1364 1365 ImplicitConversionSequence 1366 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1367 bool SuppressUserConversions, 1368 bool AllowExplicit, 1369 bool InOverloadResolution, 1370 bool CStyle, 1371 bool AllowObjCWritebackConversion) { 1372 return ::TryImplicitConversion(*this, From, ToType, 1373 SuppressUserConversions, AllowExplicit, 1374 InOverloadResolution, CStyle, 1375 AllowObjCWritebackConversion, 1376 /*AllowObjCConversionOnExplicit=*/false); 1377 } 1378 1379 /// PerformImplicitConversion - Perform an implicit conversion of the 1380 /// expression From to the type ToType. Returns the 1381 /// converted expression. Flavor is the kind of conversion we're 1382 /// performing, used in the error message. If @p AllowExplicit, 1383 /// explicit user-defined conversions are permitted. 1384 ExprResult 1385 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1386 AssignmentAction Action, bool AllowExplicit) { 1387 ImplicitConversionSequence ICS; 1388 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1389 } 1390 1391 ExprResult 1392 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1393 AssignmentAction Action, bool AllowExplicit, 1394 ImplicitConversionSequence& ICS) { 1395 if (checkPlaceholderForOverload(*this, From)) 1396 return ExprError(); 1397 1398 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1399 bool AllowObjCWritebackConversion 1400 = getLangOpts().ObjCAutoRefCount && 1401 (Action == AA_Passing || Action == AA_Sending); 1402 if (getLangOpts().ObjC1) 1403 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1404 ToType, From->getType(), From); 1405 ICS = ::TryImplicitConversion(*this, From, ToType, 1406 /*SuppressUserConversions=*/false, 1407 AllowExplicit, 1408 /*InOverloadResolution=*/false, 1409 /*CStyle=*/false, 1410 AllowObjCWritebackConversion, 1411 /*AllowObjCConversionOnExplicit=*/false); 1412 return PerformImplicitConversion(From, ToType, ICS, Action); 1413 } 1414 1415 /// \brief Determine whether the conversion from FromType to ToType is a valid 1416 /// conversion that strips "noexcept" or "noreturn" off the nested function 1417 /// type. 1418 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1419 QualType &ResultTy) { 1420 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1421 return false; 1422 1423 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1424 // or F(t noexcept) -> F(t) 1425 // where F adds one of the following at most once: 1426 // - a pointer 1427 // - a member pointer 1428 // - a block pointer 1429 // Changes here need matching changes in FindCompositePointerType. 1430 CanQualType CanTo = Context.getCanonicalType(ToType); 1431 CanQualType CanFrom = Context.getCanonicalType(FromType); 1432 Type::TypeClass TyClass = CanTo->getTypeClass(); 1433 if (TyClass != CanFrom->getTypeClass()) return false; 1434 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1435 if (TyClass == Type::Pointer) { 1436 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1437 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1438 } else if (TyClass == Type::BlockPointer) { 1439 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1440 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1441 } else if (TyClass == Type::MemberPointer) { 1442 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1443 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1444 // A function pointer conversion cannot change the class of the function. 1445 if (ToMPT->getClass() != FromMPT->getClass()) 1446 return false; 1447 CanTo = ToMPT->getPointeeType(); 1448 CanFrom = FromMPT->getPointeeType(); 1449 } else { 1450 return false; 1451 } 1452 1453 TyClass = CanTo->getTypeClass(); 1454 if (TyClass != CanFrom->getTypeClass()) return false; 1455 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1456 return false; 1457 } 1458 1459 const auto *FromFn = cast<FunctionType>(CanFrom); 1460 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1461 1462 const auto *ToFn = cast<FunctionType>(CanTo); 1463 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1464 1465 bool Changed = false; 1466 1467 // Drop 'noreturn' if not present in target type. 1468 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1469 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1470 Changed = true; 1471 } 1472 1473 // Drop 'noexcept' if not present in target type. 1474 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1475 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1476 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) { 1477 FromFn = cast<FunctionType>( 1478 Context.getFunctionType(FromFPT->getReturnType(), 1479 FromFPT->getParamTypes(), 1480 FromFPT->getExtProtoInfo().withExceptionSpec( 1481 FunctionProtoType::ExceptionSpecInfo())) 1482 .getTypePtr()); 1483 Changed = true; 1484 } 1485 } 1486 1487 if (!Changed) 1488 return false; 1489 1490 assert(QualType(FromFn, 0).isCanonical()); 1491 if (QualType(FromFn, 0) != CanTo) return false; 1492 1493 ResultTy = ToType; 1494 return true; 1495 } 1496 1497 /// \brief Determine whether the conversion from FromType to ToType is a valid 1498 /// vector conversion. 1499 /// 1500 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1501 /// conversion. 1502 static bool IsVectorConversion(Sema &S, QualType FromType, 1503 QualType ToType, ImplicitConversionKind &ICK) { 1504 // We need at least one of these types to be a vector type to have a vector 1505 // conversion. 1506 if (!ToType->isVectorType() && !FromType->isVectorType()) 1507 return false; 1508 1509 // Identical types require no conversions. 1510 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1511 return false; 1512 1513 // There are no conversions between extended vector types, only identity. 1514 if (ToType->isExtVectorType()) { 1515 // There are no conversions between extended vector types other than the 1516 // identity conversion. 1517 if (FromType->isExtVectorType()) 1518 return false; 1519 1520 // Vector splat from any arithmetic type to a vector. 1521 if (FromType->isArithmeticType()) { 1522 ICK = ICK_Vector_Splat; 1523 return true; 1524 } 1525 } 1526 1527 // We can perform the conversion between vector types in the following cases: 1528 // 1)vector types are equivalent AltiVec and GCC vector types 1529 // 2)lax vector conversions are permitted and the vector types are of the 1530 // same size 1531 if (ToType->isVectorType() && FromType->isVectorType()) { 1532 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1533 S.isLaxVectorConversion(FromType, ToType)) { 1534 ICK = ICK_Vector_Conversion; 1535 return true; 1536 } 1537 } 1538 1539 return false; 1540 } 1541 1542 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1543 bool InOverloadResolution, 1544 StandardConversionSequence &SCS, 1545 bool CStyle); 1546 1547 /// IsStandardConversion - Determines whether there is a standard 1548 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1549 /// expression From to the type ToType. Standard conversion sequences 1550 /// only consider non-class types; for conversions that involve class 1551 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1552 /// contain the standard conversion sequence required to perform this 1553 /// conversion and this routine will return true. Otherwise, this 1554 /// routine will return false and the value of SCS is unspecified. 1555 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1556 bool InOverloadResolution, 1557 StandardConversionSequence &SCS, 1558 bool CStyle, 1559 bool AllowObjCWritebackConversion) { 1560 QualType FromType = From->getType(); 1561 1562 // Standard conversions (C++ [conv]) 1563 SCS.setAsIdentityConversion(); 1564 SCS.IncompatibleObjC = false; 1565 SCS.setFromType(FromType); 1566 SCS.CopyConstructor = nullptr; 1567 1568 // There are no standard conversions for class types in C++, so 1569 // abort early. When overloading in C, however, we do permit them. 1570 if (S.getLangOpts().CPlusPlus && 1571 (FromType->isRecordType() || ToType->isRecordType())) 1572 return false; 1573 1574 // The first conversion can be an lvalue-to-rvalue conversion, 1575 // array-to-pointer conversion, or function-to-pointer conversion 1576 // (C++ 4p1). 1577 1578 if (FromType == S.Context.OverloadTy) { 1579 DeclAccessPair AccessPair; 1580 if (FunctionDecl *Fn 1581 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1582 AccessPair)) { 1583 // We were able to resolve the address of the overloaded function, 1584 // so we can convert to the type of that function. 1585 FromType = Fn->getType(); 1586 SCS.setFromType(FromType); 1587 1588 // we can sometimes resolve &foo<int> regardless of ToType, so check 1589 // if the type matches (identity) or we are converting to bool 1590 if (!S.Context.hasSameUnqualifiedType( 1591 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1592 QualType resultTy; 1593 // if the function type matches except for [[noreturn]], it's ok 1594 if (!S.IsFunctionConversion(FromType, 1595 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1596 // otherwise, only a boolean conversion is standard 1597 if (!ToType->isBooleanType()) 1598 return false; 1599 } 1600 1601 // Check if the "from" expression is taking the address of an overloaded 1602 // function and recompute the FromType accordingly. Take advantage of the 1603 // fact that non-static member functions *must* have such an address-of 1604 // expression. 1605 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1606 if (Method && !Method->isStatic()) { 1607 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1608 "Non-unary operator on non-static member address"); 1609 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1610 == UO_AddrOf && 1611 "Non-address-of operator on non-static member address"); 1612 const Type *ClassType 1613 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1614 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1615 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1616 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1617 UO_AddrOf && 1618 "Non-address-of operator for overloaded function expression"); 1619 FromType = S.Context.getPointerType(FromType); 1620 } 1621 1622 // Check that we've computed the proper type after overload resolution. 1623 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1624 // be calling it from within an NDEBUG block. 1625 assert(S.Context.hasSameType( 1626 FromType, 1627 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1628 } else { 1629 return false; 1630 } 1631 } 1632 // Lvalue-to-rvalue conversion (C++11 4.1): 1633 // A glvalue (3.10) of a non-function, non-array type T can 1634 // be converted to a prvalue. 1635 bool argIsLValue = From->isGLValue(); 1636 if (argIsLValue && 1637 !FromType->isFunctionType() && !FromType->isArrayType() && 1638 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1639 SCS.First = ICK_Lvalue_To_Rvalue; 1640 1641 // C11 6.3.2.1p2: 1642 // ... if the lvalue has atomic type, the value has the non-atomic version 1643 // of the type of the lvalue ... 1644 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1645 FromType = Atomic->getValueType(); 1646 1647 // If T is a non-class type, the type of the rvalue is the 1648 // cv-unqualified version of T. Otherwise, the type of the rvalue 1649 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1650 // just strip the qualifiers because they don't matter. 1651 FromType = FromType.getUnqualifiedType(); 1652 } else if (FromType->isArrayType()) { 1653 // Array-to-pointer conversion (C++ 4.2) 1654 SCS.First = ICK_Array_To_Pointer; 1655 1656 // An lvalue or rvalue of type "array of N T" or "array of unknown 1657 // bound of T" can be converted to an rvalue of type "pointer to 1658 // T" (C++ 4.2p1). 1659 FromType = S.Context.getArrayDecayedType(FromType); 1660 1661 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1662 // This conversion is deprecated in C++03 (D.4) 1663 SCS.DeprecatedStringLiteralToCharPtr = true; 1664 1665 // For the purpose of ranking in overload resolution 1666 // (13.3.3.1.1), this conversion is considered an 1667 // array-to-pointer conversion followed by a qualification 1668 // conversion (4.4). (C++ 4.2p2) 1669 SCS.Second = ICK_Identity; 1670 SCS.Third = ICK_Qualification; 1671 SCS.QualificationIncludesObjCLifetime = false; 1672 SCS.setAllToTypes(FromType); 1673 return true; 1674 } 1675 } else if (FromType->isFunctionType() && argIsLValue) { 1676 // Function-to-pointer conversion (C++ 4.3). 1677 SCS.First = ICK_Function_To_Pointer; 1678 1679 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1680 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1681 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1682 return false; 1683 1684 // An lvalue of function type T can be converted to an rvalue of 1685 // type "pointer to T." The result is a pointer to the 1686 // function. (C++ 4.3p1). 1687 FromType = S.Context.getPointerType(FromType); 1688 } else { 1689 // We don't require any conversions for the first step. 1690 SCS.First = ICK_Identity; 1691 } 1692 SCS.setToType(0, FromType); 1693 1694 // The second conversion can be an integral promotion, floating 1695 // point promotion, integral conversion, floating point conversion, 1696 // floating-integral conversion, pointer conversion, 1697 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1698 // For overloading in C, this can also be a "compatible-type" 1699 // conversion. 1700 bool IncompatibleObjC = false; 1701 ImplicitConversionKind SecondICK = ICK_Identity; 1702 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1703 // The unqualified versions of the types are the same: there's no 1704 // conversion to do. 1705 SCS.Second = ICK_Identity; 1706 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1707 // Integral promotion (C++ 4.5). 1708 SCS.Second = ICK_Integral_Promotion; 1709 FromType = ToType.getUnqualifiedType(); 1710 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1711 // Floating point promotion (C++ 4.6). 1712 SCS.Second = ICK_Floating_Promotion; 1713 FromType = ToType.getUnqualifiedType(); 1714 } else if (S.IsComplexPromotion(FromType, ToType)) { 1715 // Complex promotion (Clang extension) 1716 SCS.Second = ICK_Complex_Promotion; 1717 FromType = ToType.getUnqualifiedType(); 1718 } else if (ToType->isBooleanType() && 1719 (FromType->isArithmeticType() || 1720 FromType->isAnyPointerType() || 1721 FromType->isBlockPointerType() || 1722 FromType->isMemberPointerType() || 1723 FromType->isNullPtrType())) { 1724 // Boolean conversions (C++ 4.12). 1725 SCS.Second = ICK_Boolean_Conversion; 1726 FromType = S.Context.BoolTy; 1727 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1728 ToType->isIntegralType(S.Context)) { 1729 // Integral conversions (C++ 4.7). 1730 SCS.Second = ICK_Integral_Conversion; 1731 FromType = ToType.getUnqualifiedType(); 1732 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1733 // Complex conversions (C99 6.3.1.6) 1734 SCS.Second = ICK_Complex_Conversion; 1735 FromType = ToType.getUnqualifiedType(); 1736 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1737 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1738 // Complex-real conversions (C99 6.3.1.7) 1739 SCS.Second = ICK_Complex_Real; 1740 FromType = ToType.getUnqualifiedType(); 1741 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1742 // FIXME: disable conversions between long double and __float128 if 1743 // their representation is different until there is back end support 1744 // We of course allow this conversion if long double is really double. 1745 if (&S.Context.getFloatTypeSemantics(FromType) != 1746 &S.Context.getFloatTypeSemantics(ToType)) { 1747 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1748 ToType == S.Context.LongDoubleTy) || 1749 (FromType == S.Context.LongDoubleTy && 1750 ToType == S.Context.Float128Ty)); 1751 if (Float128AndLongDouble && 1752 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1753 &llvm::APFloat::IEEEdouble())) 1754 return false; 1755 } 1756 // Floating point conversions (C++ 4.8). 1757 SCS.Second = ICK_Floating_Conversion; 1758 FromType = ToType.getUnqualifiedType(); 1759 } else if ((FromType->isRealFloatingType() && 1760 ToType->isIntegralType(S.Context)) || 1761 (FromType->isIntegralOrUnscopedEnumerationType() && 1762 ToType->isRealFloatingType())) { 1763 // Floating-integral conversions (C++ 4.9). 1764 SCS.Second = ICK_Floating_Integral; 1765 FromType = ToType.getUnqualifiedType(); 1766 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1767 SCS.Second = ICK_Block_Pointer_Conversion; 1768 } else if (AllowObjCWritebackConversion && 1769 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1770 SCS.Second = ICK_Writeback_Conversion; 1771 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1772 FromType, IncompatibleObjC)) { 1773 // Pointer conversions (C++ 4.10). 1774 SCS.Second = ICK_Pointer_Conversion; 1775 SCS.IncompatibleObjC = IncompatibleObjC; 1776 FromType = FromType.getUnqualifiedType(); 1777 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1778 InOverloadResolution, FromType)) { 1779 // Pointer to member conversions (4.11). 1780 SCS.Second = ICK_Pointer_Member; 1781 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1782 SCS.Second = SecondICK; 1783 FromType = ToType.getUnqualifiedType(); 1784 } else if (!S.getLangOpts().CPlusPlus && 1785 S.Context.typesAreCompatible(ToType, FromType)) { 1786 // Compatible conversions (Clang extension for C function overloading) 1787 SCS.Second = ICK_Compatible_Conversion; 1788 FromType = ToType.getUnqualifiedType(); 1789 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1790 InOverloadResolution, 1791 SCS, CStyle)) { 1792 SCS.Second = ICK_TransparentUnionConversion; 1793 FromType = ToType; 1794 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1795 CStyle)) { 1796 // tryAtomicConversion has updated the standard conversion sequence 1797 // appropriately. 1798 return true; 1799 } else if (ToType->isEventT() && 1800 From->isIntegerConstantExpr(S.getASTContext()) && 1801 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1802 SCS.Second = ICK_Zero_Event_Conversion; 1803 FromType = ToType; 1804 } else if (ToType->isQueueT() && 1805 From->isIntegerConstantExpr(S.getASTContext()) && 1806 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1807 SCS.Second = ICK_Zero_Queue_Conversion; 1808 FromType = ToType; 1809 } else { 1810 // No second conversion required. 1811 SCS.Second = ICK_Identity; 1812 } 1813 SCS.setToType(1, FromType); 1814 1815 // The third conversion can be a function pointer conversion or a 1816 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1817 bool ObjCLifetimeConversion; 1818 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1819 // Function pointer conversions (removing 'noexcept') including removal of 1820 // 'noreturn' (Clang extension). 1821 SCS.Third = ICK_Function_Conversion; 1822 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1823 ObjCLifetimeConversion)) { 1824 SCS.Third = ICK_Qualification; 1825 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1826 FromType = ToType; 1827 } else { 1828 // No conversion required 1829 SCS.Third = ICK_Identity; 1830 } 1831 1832 // C++ [over.best.ics]p6: 1833 // [...] Any difference in top-level cv-qualification is 1834 // subsumed by the initialization itself and does not constitute 1835 // a conversion. [...] 1836 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1837 QualType CanonTo = S.Context.getCanonicalType(ToType); 1838 if (CanonFrom.getLocalUnqualifiedType() 1839 == CanonTo.getLocalUnqualifiedType() && 1840 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1841 FromType = ToType; 1842 CanonFrom = CanonTo; 1843 } 1844 1845 SCS.setToType(2, FromType); 1846 1847 if (CanonFrom == CanonTo) 1848 return true; 1849 1850 // If we have not converted the argument type to the parameter type, 1851 // this is a bad conversion sequence, unless we're resolving an overload in C. 1852 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1853 return false; 1854 1855 ExprResult ER = ExprResult{From}; 1856 Sema::AssignConvertType Conv = 1857 S.CheckSingleAssignmentConstraints(ToType, ER, 1858 /*Diagnose=*/false, 1859 /*DiagnoseCFAudited=*/false, 1860 /*ConvertRHS=*/false); 1861 ImplicitConversionKind SecondConv; 1862 switch (Conv) { 1863 case Sema::Compatible: 1864 SecondConv = ICK_C_Only_Conversion; 1865 break; 1866 // For our purposes, discarding qualifiers is just as bad as using an 1867 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1868 // qualifiers, as well. 1869 case Sema::CompatiblePointerDiscardsQualifiers: 1870 case Sema::IncompatiblePointer: 1871 case Sema::IncompatiblePointerSign: 1872 SecondConv = ICK_Incompatible_Pointer_Conversion; 1873 break; 1874 default: 1875 return false; 1876 } 1877 1878 // First can only be an lvalue conversion, so we pretend that this was the 1879 // second conversion. First should already be valid from earlier in the 1880 // function. 1881 SCS.Second = SecondConv; 1882 SCS.setToType(1, ToType); 1883 1884 // Third is Identity, because Second should rank us worse than any other 1885 // conversion. This could also be ICK_Qualification, but it's simpler to just 1886 // lump everything in with the second conversion, and we don't gain anything 1887 // from making this ICK_Qualification. 1888 SCS.Third = ICK_Identity; 1889 SCS.setToType(2, ToType); 1890 return true; 1891 } 1892 1893 static bool 1894 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1895 QualType &ToType, 1896 bool InOverloadResolution, 1897 StandardConversionSequence &SCS, 1898 bool CStyle) { 1899 1900 const RecordType *UT = ToType->getAsUnionType(); 1901 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1902 return false; 1903 // The field to initialize within the transparent union. 1904 RecordDecl *UD = UT->getDecl(); 1905 // It's compatible if the expression matches any of the fields. 1906 for (const auto *it : UD->fields()) { 1907 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1908 CStyle, /*ObjCWritebackConversion=*/false)) { 1909 ToType = it->getType(); 1910 return true; 1911 } 1912 } 1913 return false; 1914 } 1915 1916 /// IsIntegralPromotion - Determines whether the conversion from the 1917 /// expression From (whose potentially-adjusted type is FromType) to 1918 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1919 /// sets PromotedType to the promoted type. 1920 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1921 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1922 // All integers are built-in. 1923 if (!To) { 1924 return false; 1925 } 1926 1927 // An rvalue of type char, signed char, unsigned char, short int, or 1928 // unsigned short int can be converted to an rvalue of type int if 1929 // int can represent all the values of the source type; otherwise, 1930 // the source rvalue can be converted to an rvalue of type unsigned 1931 // int (C++ 4.5p1). 1932 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1933 !FromType->isEnumeralType()) { 1934 if (// We can promote any signed, promotable integer type to an int 1935 (FromType->isSignedIntegerType() || 1936 // We can promote any unsigned integer type whose size is 1937 // less than int to an int. 1938 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1939 return To->getKind() == BuiltinType::Int; 1940 } 1941 1942 return To->getKind() == BuiltinType::UInt; 1943 } 1944 1945 // C++11 [conv.prom]p3: 1946 // A prvalue of an unscoped enumeration type whose underlying type is not 1947 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1948 // following types that can represent all the values of the enumeration 1949 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1950 // unsigned int, long int, unsigned long int, long long int, or unsigned 1951 // long long int. If none of the types in that list can represent all the 1952 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1953 // type can be converted to an rvalue a prvalue of the extended integer type 1954 // with lowest integer conversion rank (4.13) greater than the rank of long 1955 // long in which all the values of the enumeration can be represented. If 1956 // there are two such extended types, the signed one is chosen. 1957 // C++11 [conv.prom]p4: 1958 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1959 // can be converted to a prvalue of its underlying type. Moreover, if 1960 // integral promotion can be applied to its underlying type, a prvalue of an 1961 // unscoped enumeration type whose underlying type is fixed can also be 1962 // converted to a prvalue of the promoted underlying type. 1963 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1964 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1965 // provided for a scoped enumeration. 1966 if (FromEnumType->getDecl()->isScoped()) 1967 return false; 1968 1969 // We can perform an integral promotion to the underlying type of the enum, 1970 // even if that's not the promoted type. Note that the check for promoting 1971 // the underlying type is based on the type alone, and does not consider 1972 // the bitfield-ness of the actual source expression. 1973 if (FromEnumType->getDecl()->isFixed()) { 1974 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1975 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1976 IsIntegralPromotion(nullptr, Underlying, ToType); 1977 } 1978 1979 // We have already pre-calculated the promotion type, so this is trivial. 1980 if (ToType->isIntegerType() && 1981 isCompleteType(From->getLocStart(), FromType)) 1982 return Context.hasSameUnqualifiedType( 1983 ToType, FromEnumType->getDecl()->getPromotionType()); 1984 } 1985 1986 // C++0x [conv.prom]p2: 1987 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1988 // to an rvalue a prvalue of the first of the following types that can 1989 // represent all the values of its underlying type: int, unsigned int, 1990 // long int, unsigned long int, long long int, or unsigned long long int. 1991 // If none of the types in that list can represent all the values of its 1992 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1993 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1994 // type. 1995 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1996 ToType->isIntegerType()) { 1997 // Determine whether the type we're converting from is signed or 1998 // unsigned. 1999 bool FromIsSigned = FromType->isSignedIntegerType(); 2000 uint64_t FromSize = Context.getTypeSize(FromType); 2001 2002 // The types we'll try to promote to, in the appropriate 2003 // order. Try each of these types. 2004 QualType PromoteTypes[6] = { 2005 Context.IntTy, Context.UnsignedIntTy, 2006 Context.LongTy, Context.UnsignedLongTy , 2007 Context.LongLongTy, Context.UnsignedLongLongTy 2008 }; 2009 for (int Idx = 0; Idx < 6; ++Idx) { 2010 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2011 if (FromSize < ToSize || 2012 (FromSize == ToSize && 2013 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2014 // We found the type that we can promote to. If this is the 2015 // type we wanted, we have a promotion. Otherwise, no 2016 // promotion. 2017 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2018 } 2019 } 2020 } 2021 2022 // An rvalue for an integral bit-field (9.6) can be converted to an 2023 // rvalue of type int if int can represent all the values of the 2024 // bit-field; otherwise, it can be converted to unsigned int if 2025 // unsigned int can represent all the values of the bit-field. If 2026 // the bit-field is larger yet, no integral promotion applies to 2027 // it. If the bit-field has an enumerated type, it is treated as any 2028 // other value of that type for promotion purposes (C++ 4.5p3). 2029 // FIXME: We should delay checking of bit-fields until we actually perform the 2030 // conversion. 2031 if (From) { 2032 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2033 llvm::APSInt BitWidth; 2034 if (FromType->isIntegralType(Context) && 2035 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2036 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2037 ToSize = Context.getTypeSize(ToType); 2038 2039 // Are we promoting to an int from a bitfield that fits in an int? 2040 if (BitWidth < ToSize || 2041 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2042 return To->getKind() == BuiltinType::Int; 2043 } 2044 2045 // Are we promoting to an unsigned int from an unsigned bitfield 2046 // that fits into an unsigned int? 2047 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2048 return To->getKind() == BuiltinType::UInt; 2049 } 2050 2051 return false; 2052 } 2053 } 2054 } 2055 2056 // An rvalue of type bool can be converted to an rvalue of type int, 2057 // with false becoming zero and true becoming one (C++ 4.5p4). 2058 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2059 return true; 2060 } 2061 2062 return false; 2063 } 2064 2065 /// IsFloatingPointPromotion - Determines whether the conversion from 2066 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2067 /// returns true and sets PromotedType to the promoted type. 2068 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2069 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2070 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2071 /// An rvalue of type float can be converted to an rvalue of type 2072 /// double. (C++ 4.6p1). 2073 if (FromBuiltin->getKind() == BuiltinType::Float && 2074 ToBuiltin->getKind() == BuiltinType::Double) 2075 return true; 2076 2077 // C99 6.3.1.5p1: 2078 // When a float is promoted to double or long double, or a 2079 // double is promoted to long double [...]. 2080 if (!getLangOpts().CPlusPlus && 2081 (FromBuiltin->getKind() == BuiltinType::Float || 2082 FromBuiltin->getKind() == BuiltinType::Double) && 2083 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2084 ToBuiltin->getKind() == BuiltinType::Float128)) 2085 return true; 2086 2087 // Half can be promoted to float. 2088 if (!getLangOpts().NativeHalfType && 2089 FromBuiltin->getKind() == BuiltinType::Half && 2090 ToBuiltin->getKind() == BuiltinType::Float) 2091 return true; 2092 } 2093 2094 return false; 2095 } 2096 2097 /// \brief Determine if a conversion is a complex promotion. 2098 /// 2099 /// A complex promotion is defined as a complex -> complex conversion 2100 /// where the conversion between the underlying real types is a 2101 /// floating-point or integral promotion. 2102 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2103 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2104 if (!FromComplex) 2105 return false; 2106 2107 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2108 if (!ToComplex) 2109 return false; 2110 2111 return IsFloatingPointPromotion(FromComplex->getElementType(), 2112 ToComplex->getElementType()) || 2113 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2114 ToComplex->getElementType()); 2115 } 2116 2117 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2118 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2119 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2120 /// if non-empty, will be a pointer to ToType that may or may not have 2121 /// the right set of qualifiers on its pointee. 2122 /// 2123 static QualType 2124 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2125 QualType ToPointee, QualType ToType, 2126 ASTContext &Context, 2127 bool StripObjCLifetime = false) { 2128 assert((FromPtr->getTypeClass() == Type::Pointer || 2129 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2130 "Invalid similarly-qualified pointer type"); 2131 2132 /// Conversions to 'id' subsume cv-qualifier conversions. 2133 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2134 return ToType.getUnqualifiedType(); 2135 2136 QualType CanonFromPointee 2137 = Context.getCanonicalType(FromPtr->getPointeeType()); 2138 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2139 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2140 2141 if (StripObjCLifetime) 2142 Quals.removeObjCLifetime(); 2143 2144 // Exact qualifier match -> return the pointer type we're converting to. 2145 if (CanonToPointee.getLocalQualifiers() == Quals) { 2146 // ToType is exactly what we need. Return it. 2147 if (!ToType.isNull()) 2148 return ToType.getUnqualifiedType(); 2149 2150 // Build a pointer to ToPointee. It has the right qualifiers 2151 // already. 2152 if (isa<ObjCObjectPointerType>(ToType)) 2153 return Context.getObjCObjectPointerType(ToPointee); 2154 return Context.getPointerType(ToPointee); 2155 } 2156 2157 // Just build a canonical type that has the right qualifiers. 2158 QualType QualifiedCanonToPointee 2159 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2160 2161 if (isa<ObjCObjectPointerType>(ToType)) 2162 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2163 return Context.getPointerType(QualifiedCanonToPointee); 2164 } 2165 2166 static bool isNullPointerConstantForConversion(Expr *Expr, 2167 bool InOverloadResolution, 2168 ASTContext &Context) { 2169 // Handle value-dependent integral null pointer constants correctly. 2170 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2171 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2172 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2173 return !InOverloadResolution; 2174 2175 return Expr->isNullPointerConstant(Context, 2176 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2177 : Expr::NPC_ValueDependentIsNull); 2178 } 2179 2180 /// IsPointerConversion - Determines whether the conversion of the 2181 /// expression From, which has the (possibly adjusted) type FromType, 2182 /// can be converted to the type ToType via a pointer conversion (C++ 2183 /// 4.10). If so, returns true and places the converted type (that 2184 /// might differ from ToType in its cv-qualifiers at some level) into 2185 /// ConvertedType. 2186 /// 2187 /// This routine also supports conversions to and from block pointers 2188 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2189 /// pointers to interfaces. FIXME: Once we've determined the 2190 /// appropriate overloading rules for Objective-C, we may want to 2191 /// split the Objective-C checks into a different routine; however, 2192 /// GCC seems to consider all of these conversions to be pointer 2193 /// conversions, so for now they live here. IncompatibleObjC will be 2194 /// set if the conversion is an allowed Objective-C conversion that 2195 /// should result in a warning. 2196 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2197 bool InOverloadResolution, 2198 QualType& ConvertedType, 2199 bool &IncompatibleObjC) { 2200 IncompatibleObjC = false; 2201 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2202 IncompatibleObjC)) 2203 return true; 2204 2205 // Conversion from a null pointer constant to any Objective-C pointer type. 2206 if (ToType->isObjCObjectPointerType() && 2207 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2208 ConvertedType = ToType; 2209 return true; 2210 } 2211 2212 // Blocks: Block pointers can be converted to void*. 2213 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2214 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2215 ConvertedType = ToType; 2216 return true; 2217 } 2218 // Blocks: A null pointer constant can be converted to a block 2219 // pointer type. 2220 if (ToType->isBlockPointerType() && 2221 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2222 ConvertedType = ToType; 2223 return true; 2224 } 2225 2226 // If the left-hand-side is nullptr_t, the right side can be a null 2227 // pointer constant. 2228 if (ToType->isNullPtrType() && 2229 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2230 ConvertedType = ToType; 2231 return true; 2232 } 2233 2234 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2235 if (!ToTypePtr) 2236 return false; 2237 2238 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2239 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2240 ConvertedType = ToType; 2241 return true; 2242 } 2243 2244 // Beyond this point, both types need to be pointers 2245 // , including objective-c pointers. 2246 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2247 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2248 !getLangOpts().ObjCAutoRefCount) { 2249 ConvertedType = BuildSimilarlyQualifiedPointerType( 2250 FromType->getAs<ObjCObjectPointerType>(), 2251 ToPointeeType, 2252 ToType, Context); 2253 return true; 2254 } 2255 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2256 if (!FromTypePtr) 2257 return false; 2258 2259 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2260 2261 // If the unqualified pointee types are the same, this can't be a 2262 // pointer conversion, so don't do all of the work below. 2263 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2264 return false; 2265 2266 // An rvalue of type "pointer to cv T," where T is an object type, 2267 // can be converted to an rvalue of type "pointer to cv void" (C++ 2268 // 4.10p2). 2269 if (FromPointeeType->isIncompleteOrObjectType() && 2270 ToPointeeType->isVoidType()) { 2271 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2272 ToPointeeType, 2273 ToType, Context, 2274 /*StripObjCLifetime=*/true); 2275 return true; 2276 } 2277 2278 // MSVC allows implicit function to void* type conversion. 2279 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2280 ToPointeeType->isVoidType()) { 2281 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2282 ToPointeeType, 2283 ToType, Context); 2284 return true; 2285 } 2286 2287 // When we're overloading in C, we allow a special kind of pointer 2288 // conversion for compatible-but-not-identical pointee types. 2289 if (!getLangOpts().CPlusPlus && 2290 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2291 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2292 ToPointeeType, 2293 ToType, Context); 2294 return true; 2295 } 2296 2297 // C++ [conv.ptr]p3: 2298 // 2299 // An rvalue of type "pointer to cv D," where D is a class type, 2300 // can be converted to an rvalue of type "pointer to cv B," where 2301 // B is a base class (clause 10) of D. If B is an inaccessible 2302 // (clause 11) or ambiguous (10.2) base class of D, a program that 2303 // necessitates this conversion is ill-formed. The result of the 2304 // conversion is a pointer to the base class sub-object of the 2305 // derived class object. The null pointer value is converted to 2306 // the null pointer value of the destination type. 2307 // 2308 // Note that we do not check for ambiguity or inaccessibility 2309 // here. That is handled by CheckPointerConversion. 2310 if (getLangOpts().CPlusPlus && 2311 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2312 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2313 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2314 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2315 ToPointeeType, 2316 ToType, Context); 2317 return true; 2318 } 2319 2320 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2321 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2322 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2323 ToPointeeType, 2324 ToType, Context); 2325 return true; 2326 } 2327 2328 return false; 2329 } 2330 2331 /// \brief Adopt the given qualifiers for the given type. 2332 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2333 Qualifiers TQs = T.getQualifiers(); 2334 2335 // Check whether qualifiers already match. 2336 if (TQs == Qs) 2337 return T; 2338 2339 if (Qs.compatiblyIncludes(TQs)) 2340 return Context.getQualifiedType(T, Qs); 2341 2342 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2343 } 2344 2345 /// isObjCPointerConversion - Determines whether this is an 2346 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2347 /// with the same arguments and return values. 2348 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2349 QualType& ConvertedType, 2350 bool &IncompatibleObjC) { 2351 if (!getLangOpts().ObjC1) 2352 return false; 2353 2354 // The set of qualifiers on the type we're converting from. 2355 Qualifiers FromQualifiers = FromType.getQualifiers(); 2356 2357 // First, we handle all conversions on ObjC object pointer types. 2358 const ObjCObjectPointerType* ToObjCPtr = 2359 ToType->getAs<ObjCObjectPointerType>(); 2360 const ObjCObjectPointerType *FromObjCPtr = 2361 FromType->getAs<ObjCObjectPointerType>(); 2362 2363 if (ToObjCPtr && FromObjCPtr) { 2364 // If the pointee types are the same (ignoring qualifications), 2365 // then this is not a pointer conversion. 2366 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2367 FromObjCPtr->getPointeeType())) 2368 return false; 2369 2370 // Conversion between Objective-C pointers. 2371 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2372 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2373 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2374 if (getLangOpts().CPlusPlus && LHS && RHS && 2375 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2376 FromObjCPtr->getPointeeType())) 2377 return false; 2378 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2379 ToObjCPtr->getPointeeType(), 2380 ToType, Context); 2381 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2382 return true; 2383 } 2384 2385 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2386 // Okay: this is some kind of implicit downcast of Objective-C 2387 // interfaces, which is permitted. However, we're going to 2388 // complain about it. 2389 IncompatibleObjC = true; 2390 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2391 ToObjCPtr->getPointeeType(), 2392 ToType, Context); 2393 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2394 return true; 2395 } 2396 } 2397 // Beyond this point, both types need to be C pointers or block pointers. 2398 QualType ToPointeeType; 2399 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2400 ToPointeeType = ToCPtr->getPointeeType(); 2401 else if (const BlockPointerType *ToBlockPtr = 2402 ToType->getAs<BlockPointerType>()) { 2403 // Objective C++: We're able to convert from a pointer to any object 2404 // to a block pointer type. 2405 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2406 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2407 return true; 2408 } 2409 ToPointeeType = ToBlockPtr->getPointeeType(); 2410 } 2411 else if (FromType->getAs<BlockPointerType>() && 2412 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2413 // Objective C++: We're able to convert from a block pointer type to a 2414 // pointer to any object. 2415 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2416 return true; 2417 } 2418 else 2419 return false; 2420 2421 QualType FromPointeeType; 2422 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2423 FromPointeeType = FromCPtr->getPointeeType(); 2424 else if (const BlockPointerType *FromBlockPtr = 2425 FromType->getAs<BlockPointerType>()) 2426 FromPointeeType = FromBlockPtr->getPointeeType(); 2427 else 2428 return false; 2429 2430 // If we have pointers to pointers, recursively check whether this 2431 // is an Objective-C conversion. 2432 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2433 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2434 IncompatibleObjC)) { 2435 // We always complain about this conversion. 2436 IncompatibleObjC = true; 2437 ConvertedType = Context.getPointerType(ConvertedType); 2438 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2439 return true; 2440 } 2441 // Allow conversion of pointee being objective-c pointer to another one; 2442 // as in I* to id. 2443 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2444 ToPointeeType->getAs<ObjCObjectPointerType>() && 2445 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2446 IncompatibleObjC)) { 2447 2448 ConvertedType = Context.getPointerType(ConvertedType); 2449 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2450 return true; 2451 } 2452 2453 // If we have pointers to functions or blocks, check whether the only 2454 // differences in the argument and result types are in Objective-C 2455 // pointer conversions. If so, we permit the conversion (but 2456 // complain about it). 2457 const FunctionProtoType *FromFunctionType 2458 = FromPointeeType->getAs<FunctionProtoType>(); 2459 const FunctionProtoType *ToFunctionType 2460 = ToPointeeType->getAs<FunctionProtoType>(); 2461 if (FromFunctionType && ToFunctionType) { 2462 // If the function types are exactly the same, this isn't an 2463 // Objective-C pointer conversion. 2464 if (Context.getCanonicalType(FromPointeeType) 2465 == Context.getCanonicalType(ToPointeeType)) 2466 return false; 2467 2468 // Perform the quick checks that will tell us whether these 2469 // function types are obviously different. 2470 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2471 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2472 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2473 return false; 2474 2475 bool HasObjCConversion = false; 2476 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2477 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2478 // Okay, the types match exactly. Nothing to do. 2479 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2480 ToFunctionType->getReturnType(), 2481 ConvertedType, IncompatibleObjC)) { 2482 // Okay, we have an Objective-C pointer conversion. 2483 HasObjCConversion = true; 2484 } else { 2485 // Function types are too different. Abort. 2486 return false; 2487 } 2488 2489 // Check argument types. 2490 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2491 ArgIdx != NumArgs; ++ArgIdx) { 2492 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2493 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2494 if (Context.getCanonicalType(FromArgType) 2495 == Context.getCanonicalType(ToArgType)) { 2496 // Okay, the types match exactly. Nothing to do. 2497 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2498 ConvertedType, IncompatibleObjC)) { 2499 // Okay, we have an Objective-C pointer conversion. 2500 HasObjCConversion = true; 2501 } else { 2502 // Argument types are too different. Abort. 2503 return false; 2504 } 2505 } 2506 2507 if (HasObjCConversion) { 2508 // We had an Objective-C conversion. Allow this pointer 2509 // conversion, but complain about it. 2510 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2511 IncompatibleObjC = true; 2512 return true; 2513 } 2514 } 2515 2516 return false; 2517 } 2518 2519 /// \brief Determine whether this is an Objective-C writeback conversion, 2520 /// used for parameter passing when performing automatic reference counting. 2521 /// 2522 /// \param FromType The type we're converting form. 2523 /// 2524 /// \param ToType The type we're converting to. 2525 /// 2526 /// \param ConvertedType The type that will be produced after applying 2527 /// this conversion. 2528 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2529 QualType &ConvertedType) { 2530 if (!getLangOpts().ObjCAutoRefCount || 2531 Context.hasSameUnqualifiedType(FromType, ToType)) 2532 return false; 2533 2534 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2535 QualType ToPointee; 2536 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2537 ToPointee = ToPointer->getPointeeType(); 2538 else 2539 return false; 2540 2541 Qualifiers ToQuals = ToPointee.getQualifiers(); 2542 if (!ToPointee->isObjCLifetimeType() || 2543 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2544 !ToQuals.withoutObjCLifetime().empty()) 2545 return false; 2546 2547 // Argument must be a pointer to __strong to __weak. 2548 QualType FromPointee; 2549 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2550 FromPointee = FromPointer->getPointeeType(); 2551 else 2552 return false; 2553 2554 Qualifiers FromQuals = FromPointee.getQualifiers(); 2555 if (!FromPointee->isObjCLifetimeType() || 2556 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2557 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2558 return false; 2559 2560 // Make sure that we have compatible qualifiers. 2561 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2562 if (!ToQuals.compatiblyIncludes(FromQuals)) 2563 return false; 2564 2565 // Remove qualifiers from the pointee type we're converting from; they 2566 // aren't used in the compatibility check belong, and we'll be adding back 2567 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2568 FromPointee = FromPointee.getUnqualifiedType(); 2569 2570 // The unqualified form of the pointee types must be compatible. 2571 ToPointee = ToPointee.getUnqualifiedType(); 2572 bool IncompatibleObjC; 2573 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2574 FromPointee = ToPointee; 2575 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2576 IncompatibleObjC)) 2577 return false; 2578 2579 /// \brief Construct the type we're converting to, which is a pointer to 2580 /// __autoreleasing pointee. 2581 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2582 ConvertedType = Context.getPointerType(FromPointee); 2583 return true; 2584 } 2585 2586 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2587 QualType& ConvertedType) { 2588 QualType ToPointeeType; 2589 if (const BlockPointerType *ToBlockPtr = 2590 ToType->getAs<BlockPointerType>()) 2591 ToPointeeType = ToBlockPtr->getPointeeType(); 2592 else 2593 return false; 2594 2595 QualType FromPointeeType; 2596 if (const BlockPointerType *FromBlockPtr = 2597 FromType->getAs<BlockPointerType>()) 2598 FromPointeeType = FromBlockPtr->getPointeeType(); 2599 else 2600 return false; 2601 // We have pointer to blocks, check whether the only 2602 // differences in the argument and result types are in Objective-C 2603 // pointer conversions. If so, we permit the conversion. 2604 2605 const FunctionProtoType *FromFunctionType 2606 = FromPointeeType->getAs<FunctionProtoType>(); 2607 const FunctionProtoType *ToFunctionType 2608 = ToPointeeType->getAs<FunctionProtoType>(); 2609 2610 if (!FromFunctionType || !ToFunctionType) 2611 return false; 2612 2613 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2614 return true; 2615 2616 // Perform the quick checks that will tell us whether these 2617 // function types are obviously different. 2618 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2619 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2620 return false; 2621 2622 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2623 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2624 if (FromEInfo != ToEInfo) 2625 return false; 2626 2627 bool IncompatibleObjC = false; 2628 if (Context.hasSameType(FromFunctionType->getReturnType(), 2629 ToFunctionType->getReturnType())) { 2630 // Okay, the types match exactly. Nothing to do. 2631 } else { 2632 QualType RHS = FromFunctionType->getReturnType(); 2633 QualType LHS = ToFunctionType->getReturnType(); 2634 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2635 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2636 LHS = LHS.getUnqualifiedType(); 2637 2638 if (Context.hasSameType(RHS,LHS)) { 2639 // OK exact match. 2640 } else if (isObjCPointerConversion(RHS, LHS, 2641 ConvertedType, IncompatibleObjC)) { 2642 if (IncompatibleObjC) 2643 return false; 2644 // Okay, we have an Objective-C pointer conversion. 2645 } 2646 else 2647 return false; 2648 } 2649 2650 // Check argument types. 2651 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2652 ArgIdx != NumArgs; ++ArgIdx) { 2653 IncompatibleObjC = false; 2654 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2655 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2656 if (Context.hasSameType(FromArgType, ToArgType)) { 2657 // Okay, the types match exactly. Nothing to do. 2658 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2659 ConvertedType, IncompatibleObjC)) { 2660 if (IncompatibleObjC) 2661 return false; 2662 // Okay, we have an Objective-C pointer conversion. 2663 } else 2664 // Argument types are too different. Abort. 2665 return false; 2666 } 2667 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType, 2668 ToFunctionType)) 2669 return false; 2670 2671 ConvertedType = ToType; 2672 return true; 2673 } 2674 2675 enum { 2676 ft_default, 2677 ft_different_class, 2678 ft_parameter_arity, 2679 ft_parameter_mismatch, 2680 ft_return_type, 2681 ft_qualifer_mismatch, 2682 ft_noexcept 2683 }; 2684 2685 /// Attempts to get the FunctionProtoType from a Type. Handles 2686 /// MemberFunctionPointers properly. 2687 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2688 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2689 return FPT; 2690 2691 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2692 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2693 2694 return nullptr; 2695 } 2696 2697 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2698 /// function types. Catches different number of parameter, mismatch in 2699 /// parameter types, and different return types. 2700 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2701 QualType FromType, QualType ToType) { 2702 // If either type is not valid, include no extra info. 2703 if (FromType.isNull() || ToType.isNull()) { 2704 PDiag << ft_default; 2705 return; 2706 } 2707 2708 // Get the function type from the pointers. 2709 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2710 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2711 *ToMember = ToType->getAs<MemberPointerType>(); 2712 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2713 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2714 << QualType(FromMember->getClass(), 0); 2715 return; 2716 } 2717 FromType = FromMember->getPointeeType(); 2718 ToType = ToMember->getPointeeType(); 2719 } 2720 2721 if (FromType->isPointerType()) 2722 FromType = FromType->getPointeeType(); 2723 if (ToType->isPointerType()) 2724 ToType = ToType->getPointeeType(); 2725 2726 // Remove references. 2727 FromType = FromType.getNonReferenceType(); 2728 ToType = ToType.getNonReferenceType(); 2729 2730 // Don't print extra info for non-specialized template functions. 2731 if (FromType->isInstantiationDependentType() && 2732 !FromType->getAs<TemplateSpecializationType>()) { 2733 PDiag << ft_default; 2734 return; 2735 } 2736 2737 // No extra info for same types. 2738 if (Context.hasSameType(FromType, ToType)) { 2739 PDiag << ft_default; 2740 return; 2741 } 2742 2743 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2744 *ToFunction = tryGetFunctionProtoType(ToType); 2745 2746 // Both types need to be function types. 2747 if (!FromFunction || !ToFunction) { 2748 PDiag << ft_default; 2749 return; 2750 } 2751 2752 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2753 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2754 << FromFunction->getNumParams(); 2755 return; 2756 } 2757 2758 // Handle different parameter types. 2759 unsigned ArgPos; 2760 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2761 PDiag << ft_parameter_mismatch << ArgPos + 1 2762 << ToFunction->getParamType(ArgPos) 2763 << FromFunction->getParamType(ArgPos); 2764 return; 2765 } 2766 2767 // Handle different return type. 2768 if (!Context.hasSameType(FromFunction->getReturnType(), 2769 ToFunction->getReturnType())) { 2770 PDiag << ft_return_type << ToFunction->getReturnType() 2771 << FromFunction->getReturnType(); 2772 return; 2773 } 2774 2775 unsigned FromQuals = FromFunction->getTypeQuals(), 2776 ToQuals = ToFunction->getTypeQuals(); 2777 if (FromQuals != ToQuals) { 2778 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2779 return; 2780 } 2781 2782 // Handle exception specification differences on canonical type (in C++17 2783 // onwards). 2784 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2785 ->isNothrow(Context) != 2786 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2787 ->isNothrow(Context)) { 2788 PDiag << ft_noexcept; 2789 return; 2790 } 2791 2792 // Unable to find a difference, so add no extra info. 2793 PDiag << ft_default; 2794 } 2795 2796 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2797 /// for equality of their argument types. Caller has already checked that 2798 /// they have same number of arguments. If the parameters are different, 2799 /// ArgPos will have the parameter index of the first different parameter. 2800 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2801 const FunctionProtoType *NewType, 2802 unsigned *ArgPos) { 2803 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2804 N = NewType->param_type_begin(), 2805 E = OldType->param_type_end(); 2806 O && (O != E); ++O, ++N) { 2807 if (!Context.hasSameType(O->getUnqualifiedType(), 2808 N->getUnqualifiedType())) { 2809 if (ArgPos) 2810 *ArgPos = O - OldType->param_type_begin(); 2811 return false; 2812 } 2813 } 2814 return true; 2815 } 2816 2817 /// CheckPointerConversion - Check the pointer conversion from the 2818 /// expression From to the type ToType. This routine checks for 2819 /// ambiguous or inaccessible derived-to-base pointer 2820 /// conversions for which IsPointerConversion has already returned 2821 /// true. It returns true and produces a diagnostic if there was an 2822 /// error, or returns false otherwise. 2823 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2824 CastKind &Kind, 2825 CXXCastPath& BasePath, 2826 bool IgnoreBaseAccess, 2827 bool Diagnose) { 2828 QualType FromType = From->getType(); 2829 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2830 2831 Kind = CK_BitCast; 2832 2833 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2834 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2835 Expr::NPCK_ZeroExpression) { 2836 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2837 DiagRuntimeBehavior(From->getExprLoc(), From, 2838 PDiag(diag::warn_impcast_bool_to_null_pointer) 2839 << ToType << From->getSourceRange()); 2840 else if (!isUnevaluatedContext()) 2841 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2842 << ToType << From->getSourceRange(); 2843 } 2844 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2845 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2846 QualType FromPointeeType = FromPtrType->getPointeeType(), 2847 ToPointeeType = ToPtrType->getPointeeType(); 2848 2849 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2850 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2851 // We must have a derived-to-base conversion. Check an 2852 // ambiguous or inaccessible conversion. 2853 unsigned InaccessibleID = 0; 2854 unsigned AmbigiousID = 0; 2855 if (Diagnose) { 2856 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2857 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2858 } 2859 if (CheckDerivedToBaseConversion( 2860 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2861 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2862 &BasePath, IgnoreBaseAccess)) 2863 return true; 2864 2865 // The conversion was successful. 2866 Kind = CK_DerivedToBase; 2867 } 2868 2869 if (Diagnose && !IsCStyleOrFunctionalCast && 2870 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2871 assert(getLangOpts().MSVCCompat && 2872 "this should only be possible with MSVCCompat!"); 2873 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2874 << From->getSourceRange(); 2875 } 2876 } 2877 } else if (const ObjCObjectPointerType *ToPtrType = 2878 ToType->getAs<ObjCObjectPointerType>()) { 2879 if (const ObjCObjectPointerType *FromPtrType = 2880 FromType->getAs<ObjCObjectPointerType>()) { 2881 // Objective-C++ conversions are always okay. 2882 // FIXME: We should have a different class of conversions for the 2883 // Objective-C++ implicit conversions. 2884 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2885 return false; 2886 } else if (FromType->isBlockPointerType()) { 2887 Kind = CK_BlockPointerToObjCPointerCast; 2888 } else { 2889 Kind = CK_CPointerToObjCPointerCast; 2890 } 2891 } else if (ToType->isBlockPointerType()) { 2892 if (!FromType->isBlockPointerType()) 2893 Kind = CK_AnyPointerToBlockPointerCast; 2894 } 2895 2896 // We shouldn't fall into this case unless it's valid for other 2897 // reasons. 2898 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2899 Kind = CK_NullToPointer; 2900 2901 return false; 2902 } 2903 2904 /// IsMemberPointerConversion - Determines whether the conversion of the 2905 /// expression From, which has the (possibly adjusted) type FromType, can be 2906 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2907 /// If so, returns true and places the converted type (that might differ from 2908 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2909 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2910 QualType ToType, 2911 bool InOverloadResolution, 2912 QualType &ConvertedType) { 2913 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2914 if (!ToTypePtr) 2915 return false; 2916 2917 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2918 if (From->isNullPointerConstant(Context, 2919 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2920 : Expr::NPC_ValueDependentIsNull)) { 2921 ConvertedType = ToType; 2922 return true; 2923 } 2924 2925 // Otherwise, both types have to be member pointers. 2926 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2927 if (!FromTypePtr) 2928 return false; 2929 2930 // A pointer to member of B can be converted to a pointer to member of D, 2931 // where D is derived from B (C++ 4.11p2). 2932 QualType FromClass(FromTypePtr->getClass(), 0); 2933 QualType ToClass(ToTypePtr->getClass(), 0); 2934 2935 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2936 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2937 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2938 ToClass.getTypePtr()); 2939 return true; 2940 } 2941 2942 return false; 2943 } 2944 2945 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2946 /// expression From to the type ToType. This routine checks for ambiguous or 2947 /// virtual or inaccessible base-to-derived member pointer conversions 2948 /// for which IsMemberPointerConversion has already returned true. It returns 2949 /// true and produces a diagnostic if there was an error, or returns false 2950 /// otherwise. 2951 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2952 CastKind &Kind, 2953 CXXCastPath &BasePath, 2954 bool IgnoreBaseAccess) { 2955 QualType FromType = From->getType(); 2956 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2957 if (!FromPtrType) { 2958 // This must be a null pointer to member pointer conversion 2959 assert(From->isNullPointerConstant(Context, 2960 Expr::NPC_ValueDependentIsNull) && 2961 "Expr must be null pointer constant!"); 2962 Kind = CK_NullToMemberPointer; 2963 return false; 2964 } 2965 2966 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2967 assert(ToPtrType && "No member pointer cast has a target type " 2968 "that is not a member pointer."); 2969 2970 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2971 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2972 2973 // FIXME: What about dependent types? 2974 assert(FromClass->isRecordType() && "Pointer into non-class."); 2975 assert(ToClass->isRecordType() && "Pointer into non-class."); 2976 2977 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2978 /*DetectVirtual=*/true); 2979 bool DerivationOkay = 2980 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2981 assert(DerivationOkay && 2982 "Should not have been called if derivation isn't OK."); 2983 (void)DerivationOkay; 2984 2985 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2986 getUnqualifiedType())) { 2987 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2988 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2989 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2990 return true; 2991 } 2992 2993 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2994 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2995 << FromClass << ToClass << QualType(VBase, 0) 2996 << From->getSourceRange(); 2997 return true; 2998 } 2999 3000 if (!IgnoreBaseAccess) 3001 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3002 Paths.front(), 3003 diag::err_downcast_from_inaccessible_base); 3004 3005 // Must be a base to derived member conversion. 3006 BuildBasePathArray(Paths, BasePath); 3007 Kind = CK_BaseToDerivedMemberPointer; 3008 return false; 3009 } 3010 3011 /// Determine whether the lifetime conversion between the two given 3012 /// qualifiers sets is nontrivial. 3013 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3014 Qualifiers ToQuals) { 3015 // Converting anything to const __unsafe_unretained is trivial. 3016 if (ToQuals.hasConst() && 3017 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3018 return false; 3019 3020 return true; 3021 } 3022 3023 /// IsQualificationConversion - Determines whether the conversion from 3024 /// an rvalue of type FromType to ToType is a qualification conversion 3025 /// (C++ 4.4). 3026 /// 3027 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3028 /// when the qualification conversion involves a change in the Objective-C 3029 /// object lifetime. 3030 bool 3031 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3032 bool CStyle, bool &ObjCLifetimeConversion) { 3033 FromType = Context.getCanonicalType(FromType); 3034 ToType = Context.getCanonicalType(ToType); 3035 ObjCLifetimeConversion = false; 3036 3037 // If FromType and ToType are the same type, this is not a 3038 // qualification conversion. 3039 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3040 return false; 3041 3042 // (C++ 4.4p4): 3043 // A conversion can add cv-qualifiers at levels other than the first 3044 // in multi-level pointers, subject to the following rules: [...] 3045 bool PreviousToQualsIncludeConst = true; 3046 bool UnwrappedAnyPointer = false; 3047 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 3048 // Within each iteration of the loop, we check the qualifiers to 3049 // determine if this still looks like a qualification 3050 // conversion. Then, if all is well, we unwrap one more level of 3051 // pointers or pointers-to-members and do it all again 3052 // until there are no more pointers or pointers-to-members left to 3053 // unwrap. 3054 UnwrappedAnyPointer = true; 3055 3056 Qualifiers FromQuals = FromType.getQualifiers(); 3057 Qualifiers ToQuals = ToType.getQualifiers(); 3058 3059 // Ignore __unaligned qualifier if this type is void. 3060 if (ToType.getUnqualifiedType()->isVoidType()) 3061 FromQuals.removeUnaligned(); 3062 3063 // Objective-C ARC: 3064 // Check Objective-C lifetime conversions. 3065 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3066 UnwrappedAnyPointer) { 3067 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3068 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3069 ObjCLifetimeConversion = true; 3070 FromQuals.removeObjCLifetime(); 3071 ToQuals.removeObjCLifetime(); 3072 } else { 3073 // Qualification conversions cannot cast between different 3074 // Objective-C lifetime qualifiers. 3075 return false; 3076 } 3077 } 3078 3079 // Allow addition/removal of GC attributes but not changing GC attributes. 3080 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3081 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3082 FromQuals.removeObjCGCAttr(); 3083 ToQuals.removeObjCGCAttr(); 3084 } 3085 3086 // -- for every j > 0, if const is in cv 1,j then const is in cv 3087 // 2,j, and similarly for volatile. 3088 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3089 return false; 3090 3091 // -- if the cv 1,j and cv 2,j are different, then const is in 3092 // every cv for 0 < k < j. 3093 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3094 && !PreviousToQualsIncludeConst) 3095 return false; 3096 3097 // Keep track of whether all prior cv-qualifiers in the "to" type 3098 // include const. 3099 PreviousToQualsIncludeConst 3100 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3101 } 3102 3103 // We are left with FromType and ToType being the pointee types 3104 // after unwrapping the original FromType and ToType the same number 3105 // of types. If we unwrapped any pointers, and if FromType and 3106 // ToType have the same unqualified type (since we checked 3107 // qualifiers above), then this is a qualification conversion. 3108 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3109 } 3110 3111 /// \brief - Determine whether this is a conversion from a scalar type to an 3112 /// atomic type. 3113 /// 3114 /// If successful, updates \c SCS's second and third steps in the conversion 3115 /// sequence to finish the conversion. 3116 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3117 bool InOverloadResolution, 3118 StandardConversionSequence &SCS, 3119 bool CStyle) { 3120 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3121 if (!ToAtomic) 3122 return false; 3123 3124 StandardConversionSequence InnerSCS; 3125 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3126 InOverloadResolution, InnerSCS, 3127 CStyle, /*AllowObjCWritebackConversion=*/false)) 3128 return false; 3129 3130 SCS.Second = InnerSCS.Second; 3131 SCS.setToType(1, InnerSCS.getToType(1)); 3132 SCS.Third = InnerSCS.Third; 3133 SCS.QualificationIncludesObjCLifetime 3134 = InnerSCS.QualificationIncludesObjCLifetime; 3135 SCS.setToType(2, InnerSCS.getToType(2)); 3136 return true; 3137 } 3138 3139 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3140 CXXConstructorDecl *Constructor, 3141 QualType Type) { 3142 const FunctionProtoType *CtorType = 3143 Constructor->getType()->getAs<FunctionProtoType>(); 3144 if (CtorType->getNumParams() > 0) { 3145 QualType FirstArg = CtorType->getParamType(0); 3146 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3147 return true; 3148 } 3149 return false; 3150 } 3151 3152 static OverloadingResult 3153 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3154 CXXRecordDecl *To, 3155 UserDefinedConversionSequence &User, 3156 OverloadCandidateSet &CandidateSet, 3157 bool AllowExplicit) { 3158 for (auto *D : S.LookupConstructors(To)) { 3159 auto Info = getConstructorInfo(D); 3160 if (!Info) 3161 continue; 3162 3163 bool Usable = !Info.Constructor->isInvalidDecl() && 3164 S.isInitListConstructor(Info.Constructor) && 3165 (AllowExplicit || !Info.Constructor->isExplicit()); 3166 if (Usable) { 3167 // If the first argument is (a reference to) the target type, 3168 // suppress conversions. 3169 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3170 S.Context, Info.Constructor, ToType); 3171 if (Info.ConstructorTmpl) 3172 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3173 /*ExplicitArgs*/ nullptr, From, 3174 CandidateSet, SuppressUserConversions); 3175 else 3176 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3177 CandidateSet, SuppressUserConversions); 3178 } 3179 } 3180 3181 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3182 3183 OverloadCandidateSet::iterator Best; 3184 switch (auto Result = 3185 CandidateSet.BestViableFunction(S, From->getLocStart(), 3186 Best, true)) { 3187 case OR_Deleted: 3188 case OR_Success: { 3189 // Record the standard conversion we used and the conversion function. 3190 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3191 QualType ThisType = Constructor->getThisType(S.Context); 3192 // Initializer lists don't have conversions as such. 3193 User.Before.setAsIdentityConversion(); 3194 User.HadMultipleCandidates = HadMultipleCandidates; 3195 User.ConversionFunction = Constructor; 3196 User.FoundConversionFunction = Best->FoundDecl; 3197 User.After.setAsIdentityConversion(); 3198 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3199 User.After.setAllToTypes(ToType); 3200 return Result; 3201 } 3202 3203 case OR_No_Viable_Function: 3204 return OR_No_Viable_Function; 3205 case OR_Ambiguous: 3206 return OR_Ambiguous; 3207 } 3208 3209 llvm_unreachable("Invalid OverloadResult!"); 3210 } 3211 3212 /// Determines whether there is a user-defined conversion sequence 3213 /// (C++ [over.ics.user]) that converts expression From to the type 3214 /// ToType. If such a conversion exists, User will contain the 3215 /// user-defined conversion sequence that performs such a conversion 3216 /// and this routine will return true. Otherwise, this routine returns 3217 /// false and User is unspecified. 3218 /// 3219 /// \param AllowExplicit true if the conversion should consider C++0x 3220 /// "explicit" conversion functions as well as non-explicit conversion 3221 /// functions (C++0x [class.conv.fct]p2). 3222 /// 3223 /// \param AllowObjCConversionOnExplicit true if the conversion should 3224 /// allow an extra Objective-C pointer conversion on uses of explicit 3225 /// constructors. Requires \c AllowExplicit to also be set. 3226 static OverloadingResult 3227 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3228 UserDefinedConversionSequence &User, 3229 OverloadCandidateSet &CandidateSet, 3230 bool AllowExplicit, 3231 bool AllowObjCConversionOnExplicit) { 3232 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3233 3234 // Whether we will only visit constructors. 3235 bool ConstructorsOnly = false; 3236 3237 // If the type we are conversion to is a class type, enumerate its 3238 // constructors. 3239 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3240 // C++ [over.match.ctor]p1: 3241 // When objects of class type are direct-initialized (8.5), or 3242 // copy-initialized from an expression of the same or a 3243 // derived class type (8.5), overload resolution selects the 3244 // constructor. [...] For copy-initialization, the candidate 3245 // functions are all the converting constructors (12.3.1) of 3246 // that class. The argument list is the expression-list within 3247 // the parentheses of the initializer. 3248 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3249 (From->getType()->getAs<RecordType>() && 3250 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3251 ConstructorsOnly = true; 3252 3253 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3254 // We're not going to find any constructors. 3255 } else if (CXXRecordDecl *ToRecordDecl 3256 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3257 3258 Expr **Args = &From; 3259 unsigned NumArgs = 1; 3260 bool ListInitializing = false; 3261 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3262 // But first, see if there is an init-list-constructor that will work. 3263 OverloadingResult Result = IsInitializerListConstructorConversion( 3264 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3265 if (Result != OR_No_Viable_Function) 3266 return Result; 3267 // Never mind. 3268 CandidateSet.clear(); 3269 3270 // If we're list-initializing, we pass the individual elements as 3271 // arguments, not the entire list. 3272 Args = InitList->getInits(); 3273 NumArgs = InitList->getNumInits(); 3274 ListInitializing = true; 3275 } 3276 3277 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3278 auto Info = getConstructorInfo(D); 3279 if (!Info) 3280 continue; 3281 3282 bool Usable = !Info.Constructor->isInvalidDecl(); 3283 if (ListInitializing) 3284 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3285 else 3286 Usable = Usable && 3287 Info.Constructor->isConvertingConstructor(AllowExplicit); 3288 if (Usable) { 3289 bool SuppressUserConversions = !ConstructorsOnly; 3290 if (SuppressUserConversions && ListInitializing) { 3291 SuppressUserConversions = false; 3292 if (NumArgs == 1) { 3293 // If the first argument is (a reference to) the target type, 3294 // suppress conversions. 3295 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3296 S.Context, Info.Constructor, ToType); 3297 } 3298 } 3299 if (Info.ConstructorTmpl) 3300 S.AddTemplateOverloadCandidate( 3301 Info.ConstructorTmpl, Info.FoundDecl, 3302 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3303 CandidateSet, SuppressUserConversions); 3304 else 3305 // Allow one user-defined conversion when user specifies a 3306 // From->ToType conversion via an static cast (c-style, etc). 3307 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3308 llvm::makeArrayRef(Args, NumArgs), 3309 CandidateSet, SuppressUserConversions); 3310 } 3311 } 3312 } 3313 } 3314 3315 // Enumerate conversion functions, if we're allowed to. 3316 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3317 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3318 // No conversion functions from incomplete types. 3319 } else if (const RecordType *FromRecordType 3320 = From->getType()->getAs<RecordType>()) { 3321 if (CXXRecordDecl *FromRecordDecl 3322 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3323 // Add all of the conversion functions as candidates. 3324 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3325 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3326 DeclAccessPair FoundDecl = I.getPair(); 3327 NamedDecl *D = FoundDecl.getDecl(); 3328 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3329 if (isa<UsingShadowDecl>(D)) 3330 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3331 3332 CXXConversionDecl *Conv; 3333 FunctionTemplateDecl *ConvTemplate; 3334 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3335 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3336 else 3337 Conv = cast<CXXConversionDecl>(D); 3338 3339 if (AllowExplicit || !Conv->isExplicit()) { 3340 if (ConvTemplate) 3341 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3342 ActingContext, From, ToType, 3343 CandidateSet, 3344 AllowObjCConversionOnExplicit); 3345 else 3346 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3347 From, ToType, CandidateSet, 3348 AllowObjCConversionOnExplicit); 3349 } 3350 } 3351 } 3352 } 3353 3354 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3355 3356 OverloadCandidateSet::iterator Best; 3357 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3358 Best, true)) { 3359 case OR_Success: 3360 case OR_Deleted: 3361 // Record the standard conversion we used and the conversion function. 3362 if (CXXConstructorDecl *Constructor 3363 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3364 // C++ [over.ics.user]p1: 3365 // If the user-defined conversion is specified by a 3366 // constructor (12.3.1), the initial standard conversion 3367 // sequence converts the source type to the type required by 3368 // the argument of the constructor. 3369 // 3370 QualType ThisType = Constructor->getThisType(S.Context); 3371 if (isa<InitListExpr>(From)) { 3372 // Initializer lists don't have conversions as such. 3373 User.Before.setAsIdentityConversion(); 3374 } else { 3375 if (Best->Conversions[0].isEllipsis()) 3376 User.EllipsisConversion = true; 3377 else { 3378 User.Before = Best->Conversions[0].Standard; 3379 User.EllipsisConversion = false; 3380 } 3381 } 3382 User.HadMultipleCandidates = HadMultipleCandidates; 3383 User.ConversionFunction = Constructor; 3384 User.FoundConversionFunction = Best->FoundDecl; 3385 User.After.setAsIdentityConversion(); 3386 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3387 User.After.setAllToTypes(ToType); 3388 return Result; 3389 } 3390 if (CXXConversionDecl *Conversion 3391 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3392 // C++ [over.ics.user]p1: 3393 // 3394 // [...] If the user-defined conversion is specified by a 3395 // conversion function (12.3.2), the initial standard 3396 // conversion sequence converts the source type to the 3397 // implicit object parameter of the conversion function. 3398 User.Before = Best->Conversions[0].Standard; 3399 User.HadMultipleCandidates = HadMultipleCandidates; 3400 User.ConversionFunction = Conversion; 3401 User.FoundConversionFunction = Best->FoundDecl; 3402 User.EllipsisConversion = false; 3403 3404 // C++ [over.ics.user]p2: 3405 // The second standard conversion sequence converts the 3406 // result of the user-defined conversion to the target type 3407 // for the sequence. Since an implicit conversion sequence 3408 // is an initialization, the special rules for 3409 // initialization by user-defined conversion apply when 3410 // selecting the best user-defined conversion for a 3411 // user-defined conversion sequence (see 13.3.3 and 3412 // 13.3.3.1). 3413 User.After = Best->FinalConversion; 3414 return Result; 3415 } 3416 llvm_unreachable("Not a constructor or conversion function?"); 3417 3418 case OR_No_Viable_Function: 3419 return OR_No_Viable_Function; 3420 3421 case OR_Ambiguous: 3422 return OR_Ambiguous; 3423 } 3424 3425 llvm_unreachable("Invalid OverloadResult!"); 3426 } 3427 3428 bool 3429 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3430 ImplicitConversionSequence ICS; 3431 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3432 OverloadCandidateSet::CSK_Normal); 3433 OverloadingResult OvResult = 3434 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3435 CandidateSet, false, false); 3436 if (OvResult == OR_Ambiguous) 3437 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3438 << From->getType() << ToType << From->getSourceRange(); 3439 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3440 if (!RequireCompleteType(From->getLocStart(), ToType, 3441 diag::err_typecheck_nonviable_condition_incomplete, 3442 From->getType(), From->getSourceRange())) 3443 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3444 << false << From->getType() << From->getSourceRange() << ToType; 3445 } else 3446 return false; 3447 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3448 return true; 3449 } 3450 3451 /// \brief Compare the user-defined conversion functions or constructors 3452 /// of two user-defined conversion sequences to determine whether any ordering 3453 /// is possible. 3454 static ImplicitConversionSequence::CompareKind 3455 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3456 FunctionDecl *Function2) { 3457 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3458 return ImplicitConversionSequence::Indistinguishable; 3459 3460 // Objective-C++: 3461 // If both conversion functions are implicitly-declared conversions from 3462 // a lambda closure type to a function pointer and a block pointer, 3463 // respectively, always prefer the conversion to a function pointer, 3464 // because the function pointer is more lightweight and is more likely 3465 // to keep code working. 3466 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3467 if (!Conv1) 3468 return ImplicitConversionSequence::Indistinguishable; 3469 3470 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3471 if (!Conv2) 3472 return ImplicitConversionSequence::Indistinguishable; 3473 3474 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3475 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3476 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3477 if (Block1 != Block2) 3478 return Block1 ? ImplicitConversionSequence::Worse 3479 : ImplicitConversionSequence::Better; 3480 } 3481 3482 return ImplicitConversionSequence::Indistinguishable; 3483 } 3484 3485 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3486 const ImplicitConversionSequence &ICS) { 3487 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3488 (ICS.isUserDefined() && 3489 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3490 } 3491 3492 /// CompareImplicitConversionSequences - Compare two implicit 3493 /// conversion sequences to determine whether one is better than the 3494 /// other or if they are indistinguishable (C++ 13.3.3.2). 3495 static ImplicitConversionSequence::CompareKind 3496 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3497 const ImplicitConversionSequence& ICS1, 3498 const ImplicitConversionSequence& ICS2) 3499 { 3500 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3501 // conversion sequences (as defined in 13.3.3.1) 3502 // -- a standard conversion sequence (13.3.3.1.1) is a better 3503 // conversion sequence than a user-defined conversion sequence or 3504 // an ellipsis conversion sequence, and 3505 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3506 // conversion sequence than an ellipsis conversion sequence 3507 // (13.3.3.1.3). 3508 // 3509 // C++0x [over.best.ics]p10: 3510 // For the purpose of ranking implicit conversion sequences as 3511 // described in 13.3.3.2, the ambiguous conversion sequence is 3512 // treated as a user-defined sequence that is indistinguishable 3513 // from any other user-defined conversion sequence. 3514 3515 // String literal to 'char *' conversion has been deprecated in C++03. It has 3516 // been removed from C++11. We still accept this conversion, if it happens at 3517 // the best viable function. Otherwise, this conversion is considered worse 3518 // than ellipsis conversion. Consider this as an extension; this is not in the 3519 // standard. For example: 3520 // 3521 // int &f(...); // #1 3522 // void f(char*); // #2 3523 // void g() { int &r = f("foo"); } 3524 // 3525 // In C++03, we pick #2 as the best viable function. 3526 // In C++11, we pick #1 as the best viable function, because ellipsis 3527 // conversion is better than string-literal to char* conversion (since there 3528 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3529 // convert arguments, #2 would be the best viable function in C++11. 3530 // If the best viable function has this conversion, a warning will be issued 3531 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3532 3533 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3534 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3535 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3536 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3537 ? ImplicitConversionSequence::Worse 3538 : ImplicitConversionSequence::Better; 3539 3540 if (ICS1.getKindRank() < ICS2.getKindRank()) 3541 return ImplicitConversionSequence::Better; 3542 if (ICS2.getKindRank() < ICS1.getKindRank()) 3543 return ImplicitConversionSequence::Worse; 3544 3545 // The following checks require both conversion sequences to be of 3546 // the same kind. 3547 if (ICS1.getKind() != ICS2.getKind()) 3548 return ImplicitConversionSequence::Indistinguishable; 3549 3550 ImplicitConversionSequence::CompareKind Result = 3551 ImplicitConversionSequence::Indistinguishable; 3552 3553 // Two implicit conversion sequences of the same form are 3554 // indistinguishable conversion sequences unless one of the 3555 // following rules apply: (C++ 13.3.3.2p3): 3556 3557 // List-initialization sequence L1 is a better conversion sequence than 3558 // list-initialization sequence L2 if: 3559 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3560 // if not that, 3561 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3562 // and N1 is smaller than N2., 3563 // even if one of the other rules in this paragraph would otherwise apply. 3564 if (!ICS1.isBad()) { 3565 if (ICS1.isStdInitializerListElement() && 3566 !ICS2.isStdInitializerListElement()) 3567 return ImplicitConversionSequence::Better; 3568 if (!ICS1.isStdInitializerListElement() && 3569 ICS2.isStdInitializerListElement()) 3570 return ImplicitConversionSequence::Worse; 3571 } 3572 3573 if (ICS1.isStandard()) 3574 // Standard conversion sequence S1 is a better conversion sequence than 3575 // standard conversion sequence S2 if [...] 3576 Result = CompareStandardConversionSequences(S, Loc, 3577 ICS1.Standard, ICS2.Standard); 3578 else if (ICS1.isUserDefined()) { 3579 // User-defined conversion sequence U1 is a better conversion 3580 // sequence than another user-defined conversion sequence U2 if 3581 // they contain the same user-defined conversion function or 3582 // constructor and if the second standard conversion sequence of 3583 // U1 is better than the second standard conversion sequence of 3584 // U2 (C++ 13.3.3.2p3). 3585 if (ICS1.UserDefined.ConversionFunction == 3586 ICS2.UserDefined.ConversionFunction) 3587 Result = CompareStandardConversionSequences(S, Loc, 3588 ICS1.UserDefined.After, 3589 ICS2.UserDefined.After); 3590 else 3591 Result = compareConversionFunctions(S, 3592 ICS1.UserDefined.ConversionFunction, 3593 ICS2.UserDefined.ConversionFunction); 3594 } 3595 3596 return Result; 3597 } 3598 3599 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3600 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3601 Qualifiers Quals; 3602 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3603 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3604 } 3605 3606 return Context.hasSameUnqualifiedType(T1, T2); 3607 } 3608 3609 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3610 // determine if one is a proper subset of the other. 3611 static ImplicitConversionSequence::CompareKind 3612 compareStandardConversionSubsets(ASTContext &Context, 3613 const StandardConversionSequence& SCS1, 3614 const StandardConversionSequence& SCS2) { 3615 ImplicitConversionSequence::CompareKind Result 3616 = ImplicitConversionSequence::Indistinguishable; 3617 3618 // the identity conversion sequence is considered to be a subsequence of 3619 // any non-identity conversion sequence 3620 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3621 return ImplicitConversionSequence::Better; 3622 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3623 return ImplicitConversionSequence::Worse; 3624 3625 if (SCS1.Second != SCS2.Second) { 3626 if (SCS1.Second == ICK_Identity) 3627 Result = ImplicitConversionSequence::Better; 3628 else if (SCS2.Second == ICK_Identity) 3629 Result = ImplicitConversionSequence::Worse; 3630 else 3631 return ImplicitConversionSequence::Indistinguishable; 3632 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3633 return ImplicitConversionSequence::Indistinguishable; 3634 3635 if (SCS1.Third == SCS2.Third) { 3636 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3637 : ImplicitConversionSequence::Indistinguishable; 3638 } 3639 3640 if (SCS1.Third == ICK_Identity) 3641 return Result == ImplicitConversionSequence::Worse 3642 ? ImplicitConversionSequence::Indistinguishable 3643 : ImplicitConversionSequence::Better; 3644 3645 if (SCS2.Third == ICK_Identity) 3646 return Result == ImplicitConversionSequence::Better 3647 ? ImplicitConversionSequence::Indistinguishable 3648 : ImplicitConversionSequence::Worse; 3649 3650 return ImplicitConversionSequence::Indistinguishable; 3651 } 3652 3653 /// \brief Determine whether one of the given reference bindings is better 3654 /// than the other based on what kind of bindings they are. 3655 static bool 3656 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3657 const StandardConversionSequence &SCS2) { 3658 // C++0x [over.ics.rank]p3b4: 3659 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3660 // implicit object parameter of a non-static member function declared 3661 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3662 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3663 // lvalue reference to a function lvalue and S2 binds an rvalue 3664 // reference*. 3665 // 3666 // FIXME: Rvalue references. We're going rogue with the above edits, 3667 // because the semantics in the current C++0x working paper (N3225 at the 3668 // time of this writing) break the standard definition of std::forward 3669 // and std::reference_wrapper when dealing with references to functions. 3670 // Proposed wording changes submitted to CWG for consideration. 3671 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3672 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3673 return false; 3674 3675 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3676 SCS2.IsLvalueReference) || 3677 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3678 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3679 } 3680 3681 /// CompareStandardConversionSequences - Compare two standard 3682 /// conversion sequences to determine whether one is better than the 3683 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3684 static ImplicitConversionSequence::CompareKind 3685 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3686 const StandardConversionSequence& SCS1, 3687 const StandardConversionSequence& SCS2) 3688 { 3689 // Standard conversion sequence S1 is a better conversion sequence 3690 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3691 3692 // -- S1 is a proper subsequence of S2 (comparing the conversion 3693 // sequences in the canonical form defined by 13.3.3.1.1, 3694 // excluding any Lvalue Transformation; the identity conversion 3695 // sequence is considered to be a subsequence of any 3696 // non-identity conversion sequence) or, if not that, 3697 if (ImplicitConversionSequence::CompareKind CK 3698 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3699 return CK; 3700 3701 // -- the rank of S1 is better than the rank of S2 (by the rules 3702 // defined below), or, if not that, 3703 ImplicitConversionRank Rank1 = SCS1.getRank(); 3704 ImplicitConversionRank Rank2 = SCS2.getRank(); 3705 if (Rank1 < Rank2) 3706 return ImplicitConversionSequence::Better; 3707 else if (Rank2 < Rank1) 3708 return ImplicitConversionSequence::Worse; 3709 3710 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3711 // are indistinguishable unless one of the following rules 3712 // applies: 3713 3714 // A conversion that is not a conversion of a pointer, or 3715 // pointer to member, to bool is better than another conversion 3716 // that is such a conversion. 3717 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3718 return SCS2.isPointerConversionToBool() 3719 ? ImplicitConversionSequence::Better 3720 : ImplicitConversionSequence::Worse; 3721 3722 // C++ [over.ics.rank]p4b2: 3723 // 3724 // If class B is derived directly or indirectly from class A, 3725 // conversion of B* to A* is better than conversion of B* to 3726 // void*, and conversion of A* to void* is better than conversion 3727 // of B* to void*. 3728 bool SCS1ConvertsToVoid 3729 = SCS1.isPointerConversionToVoidPointer(S.Context); 3730 bool SCS2ConvertsToVoid 3731 = SCS2.isPointerConversionToVoidPointer(S.Context); 3732 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3733 // Exactly one of the conversion sequences is a conversion to 3734 // a void pointer; it's the worse conversion. 3735 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3736 : ImplicitConversionSequence::Worse; 3737 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3738 // Neither conversion sequence converts to a void pointer; compare 3739 // their derived-to-base conversions. 3740 if (ImplicitConversionSequence::CompareKind DerivedCK 3741 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3742 return DerivedCK; 3743 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3744 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3745 // Both conversion sequences are conversions to void 3746 // pointers. Compare the source types to determine if there's an 3747 // inheritance relationship in their sources. 3748 QualType FromType1 = SCS1.getFromType(); 3749 QualType FromType2 = SCS2.getFromType(); 3750 3751 // Adjust the types we're converting from via the array-to-pointer 3752 // conversion, if we need to. 3753 if (SCS1.First == ICK_Array_To_Pointer) 3754 FromType1 = S.Context.getArrayDecayedType(FromType1); 3755 if (SCS2.First == ICK_Array_To_Pointer) 3756 FromType2 = S.Context.getArrayDecayedType(FromType2); 3757 3758 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3759 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3760 3761 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3762 return ImplicitConversionSequence::Better; 3763 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3764 return ImplicitConversionSequence::Worse; 3765 3766 // Objective-C++: If one interface is more specific than the 3767 // other, it is the better one. 3768 const ObjCObjectPointerType* FromObjCPtr1 3769 = FromType1->getAs<ObjCObjectPointerType>(); 3770 const ObjCObjectPointerType* FromObjCPtr2 3771 = FromType2->getAs<ObjCObjectPointerType>(); 3772 if (FromObjCPtr1 && FromObjCPtr2) { 3773 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3774 FromObjCPtr2); 3775 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3776 FromObjCPtr1); 3777 if (AssignLeft != AssignRight) { 3778 return AssignLeft? ImplicitConversionSequence::Better 3779 : ImplicitConversionSequence::Worse; 3780 } 3781 } 3782 } 3783 3784 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3785 // bullet 3). 3786 if (ImplicitConversionSequence::CompareKind QualCK 3787 = CompareQualificationConversions(S, SCS1, SCS2)) 3788 return QualCK; 3789 3790 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3791 // Check for a better reference binding based on the kind of bindings. 3792 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3793 return ImplicitConversionSequence::Better; 3794 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3795 return ImplicitConversionSequence::Worse; 3796 3797 // C++ [over.ics.rank]p3b4: 3798 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3799 // which the references refer are the same type except for 3800 // top-level cv-qualifiers, and the type to which the reference 3801 // initialized by S2 refers is more cv-qualified than the type 3802 // to which the reference initialized by S1 refers. 3803 QualType T1 = SCS1.getToType(2); 3804 QualType T2 = SCS2.getToType(2); 3805 T1 = S.Context.getCanonicalType(T1); 3806 T2 = S.Context.getCanonicalType(T2); 3807 Qualifiers T1Quals, T2Quals; 3808 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3809 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3810 if (UnqualT1 == UnqualT2) { 3811 // Objective-C++ ARC: If the references refer to objects with different 3812 // lifetimes, prefer bindings that don't change lifetime. 3813 if (SCS1.ObjCLifetimeConversionBinding != 3814 SCS2.ObjCLifetimeConversionBinding) { 3815 return SCS1.ObjCLifetimeConversionBinding 3816 ? ImplicitConversionSequence::Worse 3817 : ImplicitConversionSequence::Better; 3818 } 3819 3820 // If the type is an array type, promote the element qualifiers to the 3821 // type for comparison. 3822 if (isa<ArrayType>(T1) && T1Quals) 3823 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3824 if (isa<ArrayType>(T2) && T2Quals) 3825 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3826 if (T2.isMoreQualifiedThan(T1)) 3827 return ImplicitConversionSequence::Better; 3828 else if (T1.isMoreQualifiedThan(T2)) 3829 return ImplicitConversionSequence::Worse; 3830 } 3831 } 3832 3833 // In Microsoft mode, prefer an integral conversion to a 3834 // floating-to-integral conversion if the integral conversion 3835 // is between types of the same size. 3836 // For example: 3837 // void f(float); 3838 // void f(int); 3839 // int main { 3840 // long a; 3841 // f(a); 3842 // } 3843 // Here, MSVC will call f(int) instead of generating a compile error 3844 // as clang will do in standard mode. 3845 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3846 SCS2.Second == ICK_Floating_Integral && 3847 S.Context.getTypeSize(SCS1.getFromType()) == 3848 S.Context.getTypeSize(SCS1.getToType(2))) 3849 return ImplicitConversionSequence::Better; 3850 3851 return ImplicitConversionSequence::Indistinguishable; 3852 } 3853 3854 /// CompareQualificationConversions - Compares two standard conversion 3855 /// sequences to determine whether they can be ranked based on their 3856 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3857 static ImplicitConversionSequence::CompareKind 3858 CompareQualificationConversions(Sema &S, 3859 const StandardConversionSequence& SCS1, 3860 const StandardConversionSequence& SCS2) { 3861 // C++ 13.3.3.2p3: 3862 // -- S1 and S2 differ only in their qualification conversion and 3863 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3864 // cv-qualification signature of type T1 is a proper subset of 3865 // the cv-qualification signature of type T2, and S1 is not the 3866 // deprecated string literal array-to-pointer conversion (4.2). 3867 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3868 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3869 return ImplicitConversionSequence::Indistinguishable; 3870 3871 // FIXME: the example in the standard doesn't use a qualification 3872 // conversion (!) 3873 QualType T1 = SCS1.getToType(2); 3874 QualType T2 = SCS2.getToType(2); 3875 T1 = S.Context.getCanonicalType(T1); 3876 T2 = S.Context.getCanonicalType(T2); 3877 Qualifiers T1Quals, T2Quals; 3878 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3879 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3880 3881 // If the types are the same, we won't learn anything by unwrapped 3882 // them. 3883 if (UnqualT1 == UnqualT2) 3884 return ImplicitConversionSequence::Indistinguishable; 3885 3886 // If the type is an array type, promote the element qualifiers to the type 3887 // for comparison. 3888 if (isa<ArrayType>(T1) && T1Quals) 3889 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3890 if (isa<ArrayType>(T2) && T2Quals) 3891 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3892 3893 ImplicitConversionSequence::CompareKind Result 3894 = ImplicitConversionSequence::Indistinguishable; 3895 3896 // Objective-C++ ARC: 3897 // Prefer qualification conversions not involving a change in lifetime 3898 // to qualification conversions that do not change lifetime. 3899 if (SCS1.QualificationIncludesObjCLifetime != 3900 SCS2.QualificationIncludesObjCLifetime) { 3901 Result = SCS1.QualificationIncludesObjCLifetime 3902 ? ImplicitConversionSequence::Worse 3903 : ImplicitConversionSequence::Better; 3904 } 3905 3906 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3907 // Within each iteration of the loop, we check the qualifiers to 3908 // determine if this still looks like a qualification 3909 // conversion. Then, if all is well, we unwrap one more level of 3910 // pointers or pointers-to-members and do it all again 3911 // until there are no more pointers or pointers-to-members left 3912 // to unwrap. This essentially mimics what 3913 // IsQualificationConversion does, but here we're checking for a 3914 // strict subset of qualifiers. 3915 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3916 // The qualifiers are the same, so this doesn't tell us anything 3917 // about how the sequences rank. 3918 ; 3919 else if (T2.isMoreQualifiedThan(T1)) { 3920 // T1 has fewer qualifiers, so it could be the better sequence. 3921 if (Result == ImplicitConversionSequence::Worse) 3922 // Neither has qualifiers that are a subset of the other's 3923 // qualifiers. 3924 return ImplicitConversionSequence::Indistinguishable; 3925 3926 Result = ImplicitConversionSequence::Better; 3927 } else if (T1.isMoreQualifiedThan(T2)) { 3928 // T2 has fewer qualifiers, so it could be the better sequence. 3929 if (Result == ImplicitConversionSequence::Better) 3930 // Neither has qualifiers that are a subset of the other's 3931 // qualifiers. 3932 return ImplicitConversionSequence::Indistinguishable; 3933 3934 Result = ImplicitConversionSequence::Worse; 3935 } else { 3936 // Qualifiers are disjoint. 3937 return ImplicitConversionSequence::Indistinguishable; 3938 } 3939 3940 // If the types after this point are equivalent, we're done. 3941 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3942 break; 3943 } 3944 3945 // Check that the winning standard conversion sequence isn't using 3946 // the deprecated string literal array to pointer conversion. 3947 switch (Result) { 3948 case ImplicitConversionSequence::Better: 3949 if (SCS1.DeprecatedStringLiteralToCharPtr) 3950 Result = ImplicitConversionSequence::Indistinguishable; 3951 break; 3952 3953 case ImplicitConversionSequence::Indistinguishable: 3954 break; 3955 3956 case ImplicitConversionSequence::Worse: 3957 if (SCS2.DeprecatedStringLiteralToCharPtr) 3958 Result = ImplicitConversionSequence::Indistinguishable; 3959 break; 3960 } 3961 3962 return Result; 3963 } 3964 3965 /// CompareDerivedToBaseConversions - Compares two standard conversion 3966 /// sequences to determine whether they can be ranked based on their 3967 /// various kinds of derived-to-base conversions (C++ 3968 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3969 /// conversions between Objective-C interface types. 3970 static ImplicitConversionSequence::CompareKind 3971 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3972 const StandardConversionSequence& SCS1, 3973 const StandardConversionSequence& SCS2) { 3974 QualType FromType1 = SCS1.getFromType(); 3975 QualType ToType1 = SCS1.getToType(1); 3976 QualType FromType2 = SCS2.getFromType(); 3977 QualType ToType2 = SCS2.getToType(1); 3978 3979 // Adjust the types we're converting from via the array-to-pointer 3980 // conversion, if we need to. 3981 if (SCS1.First == ICK_Array_To_Pointer) 3982 FromType1 = S.Context.getArrayDecayedType(FromType1); 3983 if (SCS2.First == ICK_Array_To_Pointer) 3984 FromType2 = S.Context.getArrayDecayedType(FromType2); 3985 3986 // Canonicalize all of the types. 3987 FromType1 = S.Context.getCanonicalType(FromType1); 3988 ToType1 = S.Context.getCanonicalType(ToType1); 3989 FromType2 = S.Context.getCanonicalType(FromType2); 3990 ToType2 = S.Context.getCanonicalType(ToType2); 3991 3992 // C++ [over.ics.rank]p4b3: 3993 // 3994 // If class B is derived directly or indirectly from class A and 3995 // class C is derived directly or indirectly from B, 3996 // 3997 // Compare based on pointer conversions. 3998 if (SCS1.Second == ICK_Pointer_Conversion && 3999 SCS2.Second == ICK_Pointer_Conversion && 4000 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4001 FromType1->isPointerType() && FromType2->isPointerType() && 4002 ToType1->isPointerType() && ToType2->isPointerType()) { 4003 QualType FromPointee1 4004 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4005 QualType ToPointee1 4006 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4007 QualType FromPointee2 4008 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4009 QualType ToPointee2 4010 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4011 4012 // -- conversion of C* to B* is better than conversion of C* to A*, 4013 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4014 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4015 return ImplicitConversionSequence::Better; 4016 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4017 return ImplicitConversionSequence::Worse; 4018 } 4019 4020 // -- conversion of B* to A* is better than conversion of C* to A*, 4021 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4022 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4023 return ImplicitConversionSequence::Better; 4024 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4025 return ImplicitConversionSequence::Worse; 4026 } 4027 } else if (SCS1.Second == ICK_Pointer_Conversion && 4028 SCS2.Second == ICK_Pointer_Conversion) { 4029 const ObjCObjectPointerType *FromPtr1 4030 = FromType1->getAs<ObjCObjectPointerType>(); 4031 const ObjCObjectPointerType *FromPtr2 4032 = FromType2->getAs<ObjCObjectPointerType>(); 4033 const ObjCObjectPointerType *ToPtr1 4034 = ToType1->getAs<ObjCObjectPointerType>(); 4035 const ObjCObjectPointerType *ToPtr2 4036 = ToType2->getAs<ObjCObjectPointerType>(); 4037 4038 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4039 // Apply the same conversion ranking rules for Objective-C pointer types 4040 // that we do for C++ pointers to class types. However, we employ the 4041 // Objective-C pseudo-subtyping relationship used for assignment of 4042 // Objective-C pointer types. 4043 bool FromAssignLeft 4044 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4045 bool FromAssignRight 4046 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4047 bool ToAssignLeft 4048 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4049 bool ToAssignRight 4050 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4051 4052 // A conversion to an a non-id object pointer type or qualified 'id' 4053 // type is better than a conversion to 'id'. 4054 if (ToPtr1->isObjCIdType() && 4055 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4056 return ImplicitConversionSequence::Worse; 4057 if (ToPtr2->isObjCIdType() && 4058 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4059 return ImplicitConversionSequence::Better; 4060 4061 // A conversion to a non-id object pointer type is better than a 4062 // conversion to a qualified 'id' type 4063 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4064 return ImplicitConversionSequence::Worse; 4065 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4066 return ImplicitConversionSequence::Better; 4067 4068 // A conversion to an a non-Class object pointer type or qualified 'Class' 4069 // type is better than a conversion to 'Class'. 4070 if (ToPtr1->isObjCClassType() && 4071 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4072 return ImplicitConversionSequence::Worse; 4073 if (ToPtr2->isObjCClassType() && 4074 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4075 return ImplicitConversionSequence::Better; 4076 4077 // A conversion to a non-Class object pointer type is better than a 4078 // conversion to a qualified 'Class' type. 4079 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4080 return ImplicitConversionSequence::Worse; 4081 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4082 return ImplicitConversionSequence::Better; 4083 4084 // -- "conversion of C* to B* is better than conversion of C* to A*," 4085 if (S.Context.hasSameType(FromType1, FromType2) && 4086 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4087 (ToAssignLeft != ToAssignRight)) 4088 return ToAssignLeft? ImplicitConversionSequence::Worse 4089 : ImplicitConversionSequence::Better; 4090 4091 // -- "conversion of B* to A* is better than conversion of C* to A*," 4092 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4093 (FromAssignLeft != FromAssignRight)) 4094 return FromAssignLeft? ImplicitConversionSequence::Better 4095 : ImplicitConversionSequence::Worse; 4096 } 4097 } 4098 4099 // Ranking of member-pointer types. 4100 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4101 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4102 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4103 const MemberPointerType * FromMemPointer1 = 4104 FromType1->getAs<MemberPointerType>(); 4105 const MemberPointerType * ToMemPointer1 = 4106 ToType1->getAs<MemberPointerType>(); 4107 const MemberPointerType * FromMemPointer2 = 4108 FromType2->getAs<MemberPointerType>(); 4109 const MemberPointerType * ToMemPointer2 = 4110 ToType2->getAs<MemberPointerType>(); 4111 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4112 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4113 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4114 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4115 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4116 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4117 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4118 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4119 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4120 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4121 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4122 return ImplicitConversionSequence::Worse; 4123 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4124 return ImplicitConversionSequence::Better; 4125 } 4126 // conversion of B::* to C::* is better than conversion of A::* to C::* 4127 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4128 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4129 return ImplicitConversionSequence::Better; 4130 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4131 return ImplicitConversionSequence::Worse; 4132 } 4133 } 4134 4135 if (SCS1.Second == ICK_Derived_To_Base) { 4136 // -- conversion of C to B is better than conversion of C to A, 4137 // -- binding of an expression of type C to a reference of type 4138 // B& is better than binding an expression of type C to a 4139 // reference of type A&, 4140 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4141 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4142 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4143 return ImplicitConversionSequence::Better; 4144 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4145 return ImplicitConversionSequence::Worse; 4146 } 4147 4148 // -- conversion of B to A is better than conversion of C to A. 4149 // -- binding of an expression of type B to a reference of type 4150 // A& is better than binding an expression of type C to a 4151 // reference of type A&, 4152 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4153 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4154 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4155 return ImplicitConversionSequence::Better; 4156 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4157 return ImplicitConversionSequence::Worse; 4158 } 4159 } 4160 4161 return ImplicitConversionSequence::Indistinguishable; 4162 } 4163 4164 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4165 /// C++ class. 4166 static bool isTypeValid(QualType T) { 4167 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4168 return !Record->isInvalidDecl(); 4169 4170 return true; 4171 } 4172 4173 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4174 /// determine whether they are reference-related, 4175 /// reference-compatible, reference-compatible with added 4176 /// qualification, or incompatible, for use in C++ initialization by 4177 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4178 /// type, and the first type (T1) is the pointee type of the reference 4179 /// type being initialized. 4180 Sema::ReferenceCompareResult 4181 Sema::CompareReferenceRelationship(SourceLocation Loc, 4182 QualType OrigT1, QualType OrigT2, 4183 bool &DerivedToBase, 4184 bool &ObjCConversion, 4185 bool &ObjCLifetimeConversion) { 4186 assert(!OrigT1->isReferenceType() && 4187 "T1 must be the pointee type of the reference type"); 4188 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4189 4190 QualType T1 = Context.getCanonicalType(OrigT1); 4191 QualType T2 = Context.getCanonicalType(OrigT2); 4192 Qualifiers T1Quals, T2Quals; 4193 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4194 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4195 4196 // C++ [dcl.init.ref]p4: 4197 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4198 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4199 // T1 is a base class of T2. 4200 DerivedToBase = false; 4201 ObjCConversion = false; 4202 ObjCLifetimeConversion = false; 4203 QualType ConvertedT2; 4204 if (UnqualT1 == UnqualT2) { 4205 // Nothing to do. 4206 } else if (isCompleteType(Loc, OrigT2) && 4207 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4208 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4209 DerivedToBase = true; 4210 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4211 UnqualT2->isObjCObjectOrInterfaceType() && 4212 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4213 ObjCConversion = true; 4214 else if (UnqualT2->isFunctionType() && 4215 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4216 // C++1z [dcl.init.ref]p4: 4217 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4218 // function" and T1 is "function" 4219 // 4220 // We extend this to also apply to 'noreturn', so allow any function 4221 // conversion between function types. 4222 return Ref_Compatible; 4223 else 4224 return Ref_Incompatible; 4225 4226 // At this point, we know that T1 and T2 are reference-related (at 4227 // least). 4228 4229 // If the type is an array type, promote the element qualifiers to the type 4230 // for comparison. 4231 if (isa<ArrayType>(T1) && T1Quals) 4232 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4233 if (isa<ArrayType>(T2) && T2Quals) 4234 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4235 4236 // C++ [dcl.init.ref]p4: 4237 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4238 // reference-related to T2 and cv1 is the same cv-qualification 4239 // as, or greater cv-qualification than, cv2. For purposes of 4240 // overload resolution, cases for which cv1 is greater 4241 // cv-qualification than cv2 are identified as 4242 // reference-compatible with added qualification (see 13.3.3.2). 4243 // 4244 // Note that we also require equivalence of Objective-C GC and address-space 4245 // qualifiers when performing these computations, so that e.g., an int in 4246 // address space 1 is not reference-compatible with an int in address 4247 // space 2. 4248 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4249 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4250 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4251 ObjCLifetimeConversion = true; 4252 4253 T1Quals.removeObjCLifetime(); 4254 T2Quals.removeObjCLifetime(); 4255 } 4256 4257 // MS compiler ignores __unaligned qualifier for references; do the same. 4258 T1Quals.removeUnaligned(); 4259 T2Quals.removeUnaligned(); 4260 4261 if (T1Quals.compatiblyIncludes(T2Quals)) 4262 return Ref_Compatible; 4263 else 4264 return Ref_Related; 4265 } 4266 4267 /// \brief Look for a user-defined conversion to a value reference-compatible 4268 /// with DeclType. Return true if something definite is found. 4269 static bool 4270 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4271 QualType DeclType, SourceLocation DeclLoc, 4272 Expr *Init, QualType T2, bool AllowRvalues, 4273 bool AllowExplicit) { 4274 assert(T2->isRecordType() && "Can only find conversions of record types."); 4275 CXXRecordDecl *T2RecordDecl 4276 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4277 4278 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4279 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4280 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4281 NamedDecl *D = *I; 4282 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4283 if (isa<UsingShadowDecl>(D)) 4284 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4285 4286 FunctionTemplateDecl *ConvTemplate 4287 = dyn_cast<FunctionTemplateDecl>(D); 4288 CXXConversionDecl *Conv; 4289 if (ConvTemplate) 4290 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4291 else 4292 Conv = cast<CXXConversionDecl>(D); 4293 4294 // If this is an explicit conversion, and we're not allowed to consider 4295 // explicit conversions, skip it. 4296 if (!AllowExplicit && Conv->isExplicit()) 4297 continue; 4298 4299 if (AllowRvalues) { 4300 bool DerivedToBase = false; 4301 bool ObjCConversion = false; 4302 bool ObjCLifetimeConversion = false; 4303 4304 // If we are initializing an rvalue reference, don't permit conversion 4305 // functions that return lvalues. 4306 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4307 const ReferenceType *RefType 4308 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4309 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4310 continue; 4311 } 4312 4313 if (!ConvTemplate && 4314 S.CompareReferenceRelationship( 4315 DeclLoc, 4316 Conv->getConversionType().getNonReferenceType() 4317 .getUnqualifiedType(), 4318 DeclType.getNonReferenceType().getUnqualifiedType(), 4319 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4320 Sema::Ref_Incompatible) 4321 continue; 4322 } else { 4323 // If the conversion function doesn't return a reference type, 4324 // it can't be considered for this conversion. An rvalue reference 4325 // is only acceptable if its referencee is a function type. 4326 4327 const ReferenceType *RefType = 4328 Conv->getConversionType()->getAs<ReferenceType>(); 4329 if (!RefType || 4330 (!RefType->isLValueReferenceType() && 4331 !RefType->getPointeeType()->isFunctionType())) 4332 continue; 4333 } 4334 4335 if (ConvTemplate) 4336 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4337 Init, DeclType, CandidateSet, 4338 /*AllowObjCConversionOnExplicit=*/false); 4339 else 4340 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4341 DeclType, CandidateSet, 4342 /*AllowObjCConversionOnExplicit=*/false); 4343 } 4344 4345 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4346 4347 OverloadCandidateSet::iterator Best; 4348 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4349 case OR_Success: 4350 // C++ [over.ics.ref]p1: 4351 // 4352 // [...] If the parameter binds directly to the result of 4353 // applying a conversion function to the argument 4354 // expression, the implicit conversion sequence is a 4355 // user-defined conversion sequence (13.3.3.1.2), with the 4356 // second standard conversion sequence either an identity 4357 // conversion or, if the conversion function returns an 4358 // entity of a type that is a derived class of the parameter 4359 // type, a derived-to-base Conversion. 4360 if (!Best->FinalConversion.DirectBinding) 4361 return false; 4362 4363 ICS.setUserDefined(); 4364 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4365 ICS.UserDefined.After = Best->FinalConversion; 4366 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4367 ICS.UserDefined.ConversionFunction = Best->Function; 4368 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4369 ICS.UserDefined.EllipsisConversion = false; 4370 assert(ICS.UserDefined.After.ReferenceBinding && 4371 ICS.UserDefined.After.DirectBinding && 4372 "Expected a direct reference binding!"); 4373 return true; 4374 4375 case OR_Ambiguous: 4376 ICS.setAmbiguous(); 4377 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4378 Cand != CandidateSet.end(); ++Cand) 4379 if (Cand->Viable) 4380 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4381 return true; 4382 4383 case OR_No_Viable_Function: 4384 case OR_Deleted: 4385 // There was no suitable conversion, or we found a deleted 4386 // conversion; continue with other checks. 4387 return false; 4388 } 4389 4390 llvm_unreachable("Invalid OverloadResult!"); 4391 } 4392 4393 /// \brief Compute an implicit conversion sequence for reference 4394 /// initialization. 4395 static ImplicitConversionSequence 4396 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4397 SourceLocation DeclLoc, 4398 bool SuppressUserConversions, 4399 bool AllowExplicit) { 4400 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4401 4402 // Most paths end in a failed conversion. 4403 ImplicitConversionSequence ICS; 4404 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4405 4406 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4407 QualType T2 = Init->getType(); 4408 4409 // If the initializer is the address of an overloaded function, try 4410 // to resolve the overloaded function. If all goes well, T2 is the 4411 // type of the resulting function. 4412 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4413 DeclAccessPair Found; 4414 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4415 false, Found)) 4416 T2 = Fn->getType(); 4417 } 4418 4419 // Compute some basic properties of the types and the initializer. 4420 bool isRValRef = DeclType->isRValueReferenceType(); 4421 bool DerivedToBase = false; 4422 bool ObjCConversion = false; 4423 bool ObjCLifetimeConversion = false; 4424 Expr::Classification InitCategory = Init->Classify(S.Context); 4425 Sema::ReferenceCompareResult RefRelationship 4426 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4427 ObjCConversion, ObjCLifetimeConversion); 4428 4429 4430 // C++0x [dcl.init.ref]p5: 4431 // A reference to type "cv1 T1" is initialized by an expression 4432 // of type "cv2 T2" as follows: 4433 4434 // -- If reference is an lvalue reference and the initializer expression 4435 if (!isRValRef) { 4436 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4437 // reference-compatible with "cv2 T2," or 4438 // 4439 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4440 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4441 // C++ [over.ics.ref]p1: 4442 // When a parameter of reference type binds directly (8.5.3) 4443 // to an argument expression, the implicit conversion sequence 4444 // is the identity conversion, unless the argument expression 4445 // has a type that is a derived class of the parameter type, 4446 // in which case the implicit conversion sequence is a 4447 // derived-to-base Conversion (13.3.3.1). 4448 ICS.setStandard(); 4449 ICS.Standard.First = ICK_Identity; 4450 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4451 : ObjCConversion? ICK_Compatible_Conversion 4452 : ICK_Identity; 4453 ICS.Standard.Third = ICK_Identity; 4454 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4455 ICS.Standard.setToType(0, T2); 4456 ICS.Standard.setToType(1, T1); 4457 ICS.Standard.setToType(2, T1); 4458 ICS.Standard.ReferenceBinding = true; 4459 ICS.Standard.DirectBinding = true; 4460 ICS.Standard.IsLvalueReference = !isRValRef; 4461 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4462 ICS.Standard.BindsToRvalue = false; 4463 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4464 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4465 ICS.Standard.CopyConstructor = nullptr; 4466 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4467 4468 // Nothing more to do: the inaccessibility/ambiguity check for 4469 // derived-to-base conversions is suppressed when we're 4470 // computing the implicit conversion sequence (C++ 4471 // [over.best.ics]p2). 4472 return ICS; 4473 } 4474 4475 // -- has a class type (i.e., T2 is a class type), where T1 is 4476 // not reference-related to T2, and can be implicitly 4477 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4478 // is reference-compatible with "cv3 T3" 92) (this 4479 // conversion is selected by enumerating the applicable 4480 // conversion functions (13.3.1.6) and choosing the best 4481 // one through overload resolution (13.3)), 4482 if (!SuppressUserConversions && T2->isRecordType() && 4483 S.isCompleteType(DeclLoc, T2) && 4484 RefRelationship == Sema::Ref_Incompatible) { 4485 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4486 Init, T2, /*AllowRvalues=*/false, 4487 AllowExplicit)) 4488 return ICS; 4489 } 4490 } 4491 4492 // -- Otherwise, the reference shall be an lvalue reference to a 4493 // non-volatile const type (i.e., cv1 shall be const), or the reference 4494 // shall be an rvalue reference. 4495 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4496 return ICS; 4497 4498 // -- If the initializer expression 4499 // 4500 // -- is an xvalue, class prvalue, array prvalue or function 4501 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4502 if (RefRelationship == Sema::Ref_Compatible && 4503 (InitCategory.isXValue() || 4504 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4505 (InitCategory.isLValue() && T2->isFunctionType()))) { 4506 ICS.setStandard(); 4507 ICS.Standard.First = ICK_Identity; 4508 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4509 : ObjCConversion? ICK_Compatible_Conversion 4510 : ICK_Identity; 4511 ICS.Standard.Third = ICK_Identity; 4512 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4513 ICS.Standard.setToType(0, T2); 4514 ICS.Standard.setToType(1, T1); 4515 ICS.Standard.setToType(2, T1); 4516 ICS.Standard.ReferenceBinding = true; 4517 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4518 // binding unless we're binding to a class prvalue. 4519 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4520 // allow the use of rvalue references in C++98/03 for the benefit of 4521 // standard library implementors; therefore, we need the xvalue check here. 4522 ICS.Standard.DirectBinding = 4523 S.getLangOpts().CPlusPlus11 || 4524 !(InitCategory.isPRValue() || T2->isRecordType()); 4525 ICS.Standard.IsLvalueReference = !isRValRef; 4526 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4527 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4528 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4529 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4530 ICS.Standard.CopyConstructor = nullptr; 4531 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4532 return ICS; 4533 } 4534 4535 // -- has a class type (i.e., T2 is a class type), where T1 is not 4536 // reference-related to T2, and can be implicitly converted to 4537 // an xvalue, class prvalue, or function lvalue of type 4538 // "cv3 T3", where "cv1 T1" is reference-compatible with 4539 // "cv3 T3", 4540 // 4541 // then the reference is bound to the value of the initializer 4542 // expression in the first case and to the result of the conversion 4543 // in the second case (or, in either case, to an appropriate base 4544 // class subobject). 4545 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4546 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4547 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4548 Init, T2, /*AllowRvalues=*/true, 4549 AllowExplicit)) { 4550 // In the second case, if the reference is an rvalue reference 4551 // and the second standard conversion sequence of the 4552 // user-defined conversion sequence includes an lvalue-to-rvalue 4553 // conversion, the program is ill-formed. 4554 if (ICS.isUserDefined() && isRValRef && 4555 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4556 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4557 4558 return ICS; 4559 } 4560 4561 // A temporary of function type cannot be created; don't even try. 4562 if (T1->isFunctionType()) 4563 return ICS; 4564 4565 // -- Otherwise, a temporary of type "cv1 T1" is created and 4566 // initialized from the initializer expression using the 4567 // rules for a non-reference copy initialization (8.5). The 4568 // reference is then bound to the temporary. If T1 is 4569 // reference-related to T2, cv1 must be the same 4570 // cv-qualification as, or greater cv-qualification than, 4571 // cv2; otherwise, the program is ill-formed. 4572 if (RefRelationship == Sema::Ref_Related) { 4573 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4574 // we would be reference-compatible or reference-compatible with 4575 // added qualification. But that wasn't the case, so the reference 4576 // initialization fails. 4577 // 4578 // Note that we only want to check address spaces and cvr-qualifiers here. 4579 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4580 Qualifiers T1Quals = T1.getQualifiers(); 4581 Qualifiers T2Quals = T2.getQualifiers(); 4582 T1Quals.removeObjCGCAttr(); 4583 T1Quals.removeObjCLifetime(); 4584 T2Quals.removeObjCGCAttr(); 4585 T2Quals.removeObjCLifetime(); 4586 // MS compiler ignores __unaligned qualifier for references; do the same. 4587 T1Quals.removeUnaligned(); 4588 T2Quals.removeUnaligned(); 4589 if (!T1Quals.compatiblyIncludes(T2Quals)) 4590 return ICS; 4591 } 4592 4593 // If at least one of the types is a class type, the types are not 4594 // related, and we aren't allowed any user conversions, the 4595 // reference binding fails. This case is important for breaking 4596 // recursion, since TryImplicitConversion below will attempt to 4597 // create a temporary through the use of a copy constructor. 4598 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4599 (T1->isRecordType() || T2->isRecordType())) 4600 return ICS; 4601 4602 // If T1 is reference-related to T2 and the reference is an rvalue 4603 // reference, the initializer expression shall not be an lvalue. 4604 if (RefRelationship >= Sema::Ref_Related && 4605 isRValRef && Init->Classify(S.Context).isLValue()) 4606 return ICS; 4607 4608 // C++ [over.ics.ref]p2: 4609 // When a parameter of reference type is not bound directly to 4610 // an argument expression, the conversion sequence is the one 4611 // required to convert the argument expression to the 4612 // underlying type of the reference according to 4613 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4614 // to copy-initializing a temporary of the underlying type with 4615 // the argument expression. Any difference in top-level 4616 // cv-qualification is subsumed by the initialization itself 4617 // and does not constitute a conversion. 4618 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4619 /*AllowExplicit=*/false, 4620 /*InOverloadResolution=*/false, 4621 /*CStyle=*/false, 4622 /*AllowObjCWritebackConversion=*/false, 4623 /*AllowObjCConversionOnExplicit=*/false); 4624 4625 // Of course, that's still a reference binding. 4626 if (ICS.isStandard()) { 4627 ICS.Standard.ReferenceBinding = true; 4628 ICS.Standard.IsLvalueReference = !isRValRef; 4629 ICS.Standard.BindsToFunctionLvalue = false; 4630 ICS.Standard.BindsToRvalue = true; 4631 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4632 ICS.Standard.ObjCLifetimeConversionBinding = false; 4633 } else if (ICS.isUserDefined()) { 4634 const ReferenceType *LValRefType = 4635 ICS.UserDefined.ConversionFunction->getReturnType() 4636 ->getAs<LValueReferenceType>(); 4637 4638 // C++ [over.ics.ref]p3: 4639 // Except for an implicit object parameter, for which see 13.3.1, a 4640 // standard conversion sequence cannot be formed if it requires [...] 4641 // binding an rvalue reference to an lvalue other than a function 4642 // lvalue. 4643 // Note that the function case is not possible here. 4644 if (DeclType->isRValueReferenceType() && LValRefType) { 4645 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4646 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4647 // reference to an rvalue! 4648 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4649 return ICS; 4650 } 4651 4652 ICS.UserDefined.After.ReferenceBinding = true; 4653 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4654 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4655 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4656 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4657 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4658 } 4659 4660 return ICS; 4661 } 4662 4663 static ImplicitConversionSequence 4664 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4665 bool SuppressUserConversions, 4666 bool InOverloadResolution, 4667 bool AllowObjCWritebackConversion, 4668 bool AllowExplicit = false); 4669 4670 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4671 /// initializer list From. 4672 static ImplicitConversionSequence 4673 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4674 bool SuppressUserConversions, 4675 bool InOverloadResolution, 4676 bool AllowObjCWritebackConversion) { 4677 // C++11 [over.ics.list]p1: 4678 // When an argument is an initializer list, it is not an expression and 4679 // special rules apply for converting it to a parameter type. 4680 4681 ImplicitConversionSequence Result; 4682 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4683 4684 // We need a complete type for what follows. Incomplete types can never be 4685 // initialized from init lists. 4686 if (!S.isCompleteType(From->getLocStart(), ToType)) 4687 return Result; 4688 4689 // Per DR1467: 4690 // If the parameter type is a class X and the initializer list has a single 4691 // element of type cv U, where U is X or a class derived from X, the 4692 // implicit conversion sequence is the one required to convert the element 4693 // to the parameter type. 4694 // 4695 // Otherwise, if the parameter type is a character array [... ] 4696 // and the initializer list has a single element that is an 4697 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4698 // implicit conversion sequence is the identity conversion. 4699 if (From->getNumInits() == 1) { 4700 if (ToType->isRecordType()) { 4701 QualType InitType = From->getInit(0)->getType(); 4702 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4703 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4704 return TryCopyInitialization(S, From->getInit(0), ToType, 4705 SuppressUserConversions, 4706 InOverloadResolution, 4707 AllowObjCWritebackConversion); 4708 } 4709 // FIXME: Check the other conditions here: array of character type, 4710 // initializer is a string literal. 4711 if (ToType->isArrayType()) { 4712 InitializedEntity Entity = 4713 InitializedEntity::InitializeParameter(S.Context, ToType, 4714 /*Consumed=*/false); 4715 if (S.CanPerformCopyInitialization(Entity, From)) { 4716 Result.setStandard(); 4717 Result.Standard.setAsIdentityConversion(); 4718 Result.Standard.setFromType(ToType); 4719 Result.Standard.setAllToTypes(ToType); 4720 return Result; 4721 } 4722 } 4723 } 4724 4725 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4726 // C++11 [over.ics.list]p2: 4727 // If the parameter type is std::initializer_list<X> or "array of X" and 4728 // all the elements can be implicitly converted to X, the implicit 4729 // conversion sequence is the worst conversion necessary to convert an 4730 // element of the list to X. 4731 // 4732 // C++14 [over.ics.list]p3: 4733 // Otherwise, if the parameter type is "array of N X", if the initializer 4734 // list has exactly N elements or if it has fewer than N elements and X is 4735 // default-constructible, and if all the elements of the initializer list 4736 // can be implicitly converted to X, the implicit conversion sequence is 4737 // the worst conversion necessary to convert an element of the list to X. 4738 // 4739 // FIXME: We're missing a lot of these checks. 4740 bool toStdInitializerList = false; 4741 QualType X; 4742 if (ToType->isArrayType()) 4743 X = S.Context.getAsArrayType(ToType)->getElementType(); 4744 else 4745 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4746 if (!X.isNull()) { 4747 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4748 Expr *Init = From->getInit(i); 4749 ImplicitConversionSequence ICS = 4750 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4751 InOverloadResolution, 4752 AllowObjCWritebackConversion); 4753 // If a single element isn't convertible, fail. 4754 if (ICS.isBad()) { 4755 Result = ICS; 4756 break; 4757 } 4758 // Otherwise, look for the worst conversion. 4759 if (Result.isBad() || 4760 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4761 Result) == 4762 ImplicitConversionSequence::Worse) 4763 Result = ICS; 4764 } 4765 4766 // For an empty list, we won't have computed any conversion sequence. 4767 // Introduce the identity conversion sequence. 4768 if (From->getNumInits() == 0) { 4769 Result.setStandard(); 4770 Result.Standard.setAsIdentityConversion(); 4771 Result.Standard.setFromType(ToType); 4772 Result.Standard.setAllToTypes(ToType); 4773 } 4774 4775 Result.setStdInitializerListElement(toStdInitializerList); 4776 return Result; 4777 } 4778 4779 // C++14 [over.ics.list]p4: 4780 // C++11 [over.ics.list]p3: 4781 // Otherwise, if the parameter is a non-aggregate class X and overload 4782 // resolution chooses a single best constructor [...] the implicit 4783 // conversion sequence is a user-defined conversion sequence. If multiple 4784 // constructors are viable but none is better than the others, the 4785 // implicit conversion sequence is a user-defined conversion sequence. 4786 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4787 // This function can deal with initializer lists. 4788 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4789 /*AllowExplicit=*/false, 4790 InOverloadResolution, /*CStyle=*/false, 4791 AllowObjCWritebackConversion, 4792 /*AllowObjCConversionOnExplicit=*/false); 4793 } 4794 4795 // C++14 [over.ics.list]p5: 4796 // C++11 [over.ics.list]p4: 4797 // Otherwise, if the parameter has an aggregate type which can be 4798 // initialized from the initializer list [...] the implicit conversion 4799 // sequence is a user-defined conversion sequence. 4800 if (ToType->isAggregateType()) { 4801 // Type is an aggregate, argument is an init list. At this point it comes 4802 // down to checking whether the initialization works. 4803 // FIXME: Find out whether this parameter is consumed or not. 4804 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4805 // need to call into the initialization code here; overload resolution 4806 // should not be doing that. 4807 InitializedEntity Entity = 4808 InitializedEntity::InitializeParameter(S.Context, ToType, 4809 /*Consumed=*/false); 4810 if (S.CanPerformCopyInitialization(Entity, From)) { 4811 Result.setUserDefined(); 4812 Result.UserDefined.Before.setAsIdentityConversion(); 4813 // Initializer lists don't have a type. 4814 Result.UserDefined.Before.setFromType(QualType()); 4815 Result.UserDefined.Before.setAllToTypes(QualType()); 4816 4817 Result.UserDefined.After.setAsIdentityConversion(); 4818 Result.UserDefined.After.setFromType(ToType); 4819 Result.UserDefined.After.setAllToTypes(ToType); 4820 Result.UserDefined.ConversionFunction = nullptr; 4821 } 4822 return Result; 4823 } 4824 4825 // C++14 [over.ics.list]p6: 4826 // C++11 [over.ics.list]p5: 4827 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4828 if (ToType->isReferenceType()) { 4829 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4830 // mention initializer lists in any way. So we go by what list- 4831 // initialization would do and try to extrapolate from that. 4832 4833 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4834 4835 // If the initializer list has a single element that is reference-related 4836 // to the parameter type, we initialize the reference from that. 4837 if (From->getNumInits() == 1) { 4838 Expr *Init = From->getInit(0); 4839 4840 QualType T2 = Init->getType(); 4841 4842 // If the initializer is the address of an overloaded function, try 4843 // to resolve the overloaded function. If all goes well, T2 is the 4844 // type of the resulting function. 4845 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4846 DeclAccessPair Found; 4847 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4848 Init, ToType, false, Found)) 4849 T2 = Fn->getType(); 4850 } 4851 4852 // Compute some basic properties of the types and the initializer. 4853 bool dummy1 = false; 4854 bool dummy2 = false; 4855 bool dummy3 = false; 4856 Sema::ReferenceCompareResult RefRelationship 4857 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4858 dummy2, dummy3); 4859 4860 if (RefRelationship >= Sema::Ref_Related) { 4861 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4862 SuppressUserConversions, 4863 /*AllowExplicit=*/false); 4864 } 4865 } 4866 4867 // Otherwise, we bind the reference to a temporary created from the 4868 // initializer list. 4869 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4870 InOverloadResolution, 4871 AllowObjCWritebackConversion); 4872 if (Result.isFailure()) 4873 return Result; 4874 assert(!Result.isEllipsis() && 4875 "Sub-initialization cannot result in ellipsis conversion."); 4876 4877 // Can we even bind to a temporary? 4878 if (ToType->isRValueReferenceType() || 4879 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4880 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4881 Result.UserDefined.After; 4882 SCS.ReferenceBinding = true; 4883 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4884 SCS.BindsToRvalue = true; 4885 SCS.BindsToFunctionLvalue = false; 4886 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4887 SCS.ObjCLifetimeConversionBinding = false; 4888 } else 4889 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4890 From, ToType); 4891 return Result; 4892 } 4893 4894 // C++14 [over.ics.list]p7: 4895 // C++11 [over.ics.list]p6: 4896 // Otherwise, if the parameter type is not a class: 4897 if (!ToType->isRecordType()) { 4898 // - if the initializer list has one element that is not itself an 4899 // initializer list, the implicit conversion sequence is the one 4900 // required to convert the element to the parameter type. 4901 unsigned NumInits = From->getNumInits(); 4902 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4903 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4904 SuppressUserConversions, 4905 InOverloadResolution, 4906 AllowObjCWritebackConversion); 4907 // - if the initializer list has no elements, the implicit conversion 4908 // sequence is the identity conversion. 4909 else if (NumInits == 0) { 4910 Result.setStandard(); 4911 Result.Standard.setAsIdentityConversion(); 4912 Result.Standard.setFromType(ToType); 4913 Result.Standard.setAllToTypes(ToType); 4914 } 4915 return Result; 4916 } 4917 4918 // C++14 [over.ics.list]p8: 4919 // C++11 [over.ics.list]p7: 4920 // In all cases other than those enumerated above, no conversion is possible 4921 return Result; 4922 } 4923 4924 /// TryCopyInitialization - Try to copy-initialize a value of type 4925 /// ToType from the expression From. Return the implicit conversion 4926 /// sequence required to pass this argument, which may be a bad 4927 /// conversion sequence (meaning that the argument cannot be passed to 4928 /// a parameter of this type). If @p SuppressUserConversions, then we 4929 /// do not permit any user-defined conversion sequences. 4930 static ImplicitConversionSequence 4931 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4932 bool SuppressUserConversions, 4933 bool InOverloadResolution, 4934 bool AllowObjCWritebackConversion, 4935 bool AllowExplicit) { 4936 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4937 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4938 InOverloadResolution,AllowObjCWritebackConversion); 4939 4940 if (ToType->isReferenceType()) 4941 return TryReferenceInit(S, From, ToType, 4942 /*FIXME:*/From->getLocStart(), 4943 SuppressUserConversions, 4944 AllowExplicit); 4945 4946 return TryImplicitConversion(S, From, ToType, 4947 SuppressUserConversions, 4948 /*AllowExplicit=*/false, 4949 InOverloadResolution, 4950 /*CStyle=*/false, 4951 AllowObjCWritebackConversion, 4952 /*AllowObjCConversionOnExplicit=*/false); 4953 } 4954 4955 static bool TryCopyInitialization(const CanQualType FromQTy, 4956 const CanQualType ToQTy, 4957 Sema &S, 4958 SourceLocation Loc, 4959 ExprValueKind FromVK) { 4960 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4961 ImplicitConversionSequence ICS = 4962 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4963 4964 return !ICS.isBad(); 4965 } 4966 4967 /// TryObjectArgumentInitialization - Try to initialize the object 4968 /// parameter of the given member function (@c Method) from the 4969 /// expression @p From. 4970 static ImplicitConversionSequence 4971 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4972 Expr::Classification FromClassification, 4973 CXXMethodDecl *Method, 4974 CXXRecordDecl *ActingContext) { 4975 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4976 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4977 // const volatile object. 4978 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4979 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4980 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4981 4982 // Set up the conversion sequence as a "bad" conversion, to allow us 4983 // to exit early. 4984 ImplicitConversionSequence ICS; 4985 4986 // We need to have an object of class type. 4987 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4988 FromType = PT->getPointeeType(); 4989 4990 // When we had a pointer, it's implicitly dereferenced, so we 4991 // better have an lvalue. 4992 assert(FromClassification.isLValue()); 4993 } 4994 4995 assert(FromType->isRecordType()); 4996 4997 // C++0x [over.match.funcs]p4: 4998 // For non-static member functions, the type of the implicit object 4999 // parameter is 5000 // 5001 // - "lvalue reference to cv X" for functions declared without a 5002 // ref-qualifier or with the & ref-qualifier 5003 // - "rvalue reference to cv X" for functions declared with the && 5004 // ref-qualifier 5005 // 5006 // where X is the class of which the function is a member and cv is the 5007 // cv-qualification on the member function declaration. 5008 // 5009 // However, when finding an implicit conversion sequence for the argument, we 5010 // are not allowed to perform user-defined conversions 5011 // (C++ [over.match.funcs]p5). We perform a simplified version of 5012 // reference binding here, that allows class rvalues to bind to 5013 // non-constant references. 5014 5015 // First check the qualifiers. 5016 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5017 if (ImplicitParamType.getCVRQualifiers() 5018 != FromTypeCanon.getLocalCVRQualifiers() && 5019 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5020 ICS.setBad(BadConversionSequence::bad_qualifiers, 5021 FromType, ImplicitParamType); 5022 return ICS; 5023 } 5024 5025 // Check that we have either the same type or a derived type. It 5026 // affects the conversion rank. 5027 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5028 ImplicitConversionKind SecondKind; 5029 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5030 SecondKind = ICK_Identity; 5031 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5032 SecondKind = ICK_Derived_To_Base; 5033 else { 5034 ICS.setBad(BadConversionSequence::unrelated_class, 5035 FromType, ImplicitParamType); 5036 return ICS; 5037 } 5038 5039 // Check the ref-qualifier. 5040 switch (Method->getRefQualifier()) { 5041 case RQ_None: 5042 // Do nothing; we don't care about lvalueness or rvalueness. 5043 break; 5044 5045 case RQ_LValue: 5046 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 5047 // non-const lvalue reference cannot bind to an rvalue 5048 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5049 ImplicitParamType); 5050 return ICS; 5051 } 5052 break; 5053 5054 case RQ_RValue: 5055 if (!FromClassification.isRValue()) { 5056 // rvalue reference cannot bind to an lvalue 5057 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5058 ImplicitParamType); 5059 return ICS; 5060 } 5061 break; 5062 } 5063 5064 // Success. Mark this as a reference binding. 5065 ICS.setStandard(); 5066 ICS.Standard.setAsIdentityConversion(); 5067 ICS.Standard.Second = SecondKind; 5068 ICS.Standard.setFromType(FromType); 5069 ICS.Standard.setAllToTypes(ImplicitParamType); 5070 ICS.Standard.ReferenceBinding = true; 5071 ICS.Standard.DirectBinding = true; 5072 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5073 ICS.Standard.BindsToFunctionLvalue = false; 5074 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5075 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5076 = (Method->getRefQualifier() == RQ_None); 5077 return ICS; 5078 } 5079 5080 /// PerformObjectArgumentInitialization - Perform initialization of 5081 /// the implicit object parameter for the given Method with the given 5082 /// expression. 5083 ExprResult 5084 Sema::PerformObjectArgumentInitialization(Expr *From, 5085 NestedNameSpecifier *Qualifier, 5086 NamedDecl *FoundDecl, 5087 CXXMethodDecl *Method) { 5088 QualType FromRecordType, DestType; 5089 QualType ImplicitParamRecordType = 5090 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5091 5092 Expr::Classification FromClassification; 5093 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5094 FromRecordType = PT->getPointeeType(); 5095 DestType = Method->getThisType(Context); 5096 FromClassification = Expr::Classification::makeSimpleLValue(); 5097 } else { 5098 FromRecordType = From->getType(); 5099 DestType = ImplicitParamRecordType; 5100 FromClassification = From->Classify(Context); 5101 } 5102 5103 // Note that we always use the true parent context when performing 5104 // the actual argument initialization. 5105 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5106 *this, From->getLocStart(), From->getType(), FromClassification, Method, 5107 Method->getParent()); 5108 if (ICS.isBad()) { 5109 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 5110 Qualifiers FromQs = FromRecordType.getQualifiers(); 5111 Qualifiers ToQs = DestType.getQualifiers(); 5112 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5113 if (CVR) { 5114 Diag(From->getLocStart(), 5115 diag::err_member_function_call_bad_cvr) 5116 << Method->getDeclName() << FromRecordType << (CVR - 1) 5117 << From->getSourceRange(); 5118 Diag(Method->getLocation(), diag::note_previous_decl) 5119 << Method->getDeclName(); 5120 return ExprError(); 5121 } 5122 } 5123 5124 return Diag(From->getLocStart(), 5125 diag::err_implicit_object_parameter_init) 5126 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5127 } 5128 5129 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5130 ExprResult FromRes = 5131 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5132 if (FromRes.isInvalid()) 5133 return ExprError(); 5134 From = FromRes.get(); 5135 } 5136 5137 if (!Context.hasSameType(From->getType(), DestType)) 5138 From = ImpCastExprToType(From, DestType, CK_NoOp, 5139 From->getValueKind()).get(); 5140 return From; 5141 } 5142 5143 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5144 /// expression From to bool (C++0x [conv]p3). 5145 static ImplicitConversionSequence 5146 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5147 return TryImplicitConversion(S, From, S.Context.BoolTy, 5148 /*SuppressUserConversions=*/false, 5149 /*AllowExplicit=*/true, 5150 /*InOverloadResolution=*/false, 5151 /*CStyle=*/false, 5152 /*AllowObjCWritebackConversion=*/false, 5153 /*AllowObjCConversionOnExplicit=*/false); 5154 } 5155 5156 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5157 /// of the expression From to bool (C++0x [conv]p3). 5158 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5159 if (checkPlaceholderForOverload(*this, From)) 5160 return ExprError(); 5161 5162 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5163 if (!ICS.isBad()) 5164 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5165 5166 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5167 return Diag(From->getLocStart(), 5168 diag::err_typecheck_bool_condition) 5169 << From->getType() << From->getSourceRange(); 5170 return ExprError(); 5171 } 5172 5173 /// Check that the specified conversion is permitted in a converted constant 5174 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5175 /// is acceptable. 5176 static bool CheckConvertedConstantConversions(Sema &S, 5177 StandardConversionSequence &SCS) { 5178 // Since we know that the target type is an integral or unscoped enumeration 5179 // type, most conversion kinds are impossible. All possible First and Third 5180 // conversions are fine. 5181 switch (SCS.Second) { 5182 case ICK_Identity: 5183 case ICK_Function_Conversion: 5184 case ICK_Integral_Promotion: 5185 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5186 case ICK_Zero_Queue_Conversion: 5187 return true; 5188 5189 case ICK_Boolean_Conversion: 5190 // Conversion from an integral or unscoped enumeration type to bool is 5191 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5192 // conversion, so we allow it in a converted constant expression. 5193 // 5194 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5195 // a lot of popular code. We should at least add a warning for this 5196 // (non-conforming) extension. 5197 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5198 SCS.getToType(2)->isBooleanType(); 5199 5200 case ICK_Pointer_Conversion: 5201 case ICK_Pointer_Member: 5202 // C++1z: null pointer conversions and null member pointer conversions are 5203 // only permitted if the source type is std::nullptr_t. 5204 return SCS.getFromType()->isNullPtrType(); 5205 5206 case ICK_Floating_Promotion: 5207 case ICK_Complex_Promotion: 5208 case ICK_Floating_Conversion: 5209 case ICK_Complex_Conversion: 5210 case ICK_Floating_Integral: 5211 case ICK_Compatible_Conversion: 5212 case ICK_Derived_To_Base: 5213 case ICK_Vector_Conversion: 5214 case ICK_Vector_Splat: 5215 case ICK_Complex_Real: 5216 case ICK_Block_Pointer_Conversion: 5217 case ICK_TransparentUnionConversion: 5218 case ICK_Writeback_Conversion: 5219 case ICK_Zero_Event_Conversion: 5220 case ICK_C_Only_Conversion: 5221 case ICK_Incompatible_Pointer_Conversion: 5222 return false; 5223 5224 case ICK_Lvalue_To_Rvalue: 5225 case ICK_Array_To_Pointer: 5226 case ICK_Function_To_Pointer: 5227 llvm_unreachable("found a first conversion kind in Second"); 5228 5229 case ICK_Qualification: 5230 llvm_unreachable("found a third conversion kind in Second"); 5231 5232 case ICK_Num_Conversion_Kinds: 5233 break; 5234 } 5235 5236 llvm_unreachable("unknown conversion kind"); 5237 } 5238 5239 /// CheckConvertedConstantExpression - Check that the expression From is a 5240 /// converted constant expression of type T, perform the conversion and produce 5241 /// the converted expression, per C++11 [expr.const]p3. 5242 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5243 QualType T, APValue &Value, 5244 Sema::CCEKind CCE, 5245 bool RequireInt) { 5246 assert(S.getLangOpts().CPlusPlus11 && 5247 "converted constant expression outside C++11"); 5248 5249 if (checkPlaceholderForOverload(S, From)) 5250 return ExprError(); 5251 5252 // C++1z [expr.const]p3: 5253 // A converted constant expression of type T is an expression, 5254 // implicitly converted to type T, where the converted 5255 // expression is a constant expression and the implicit conversion 5256 // sequence contains only [... list of conversions ...]. 5257 // C++1z [stmt.if]p2: 5258 // If the if statement is of the form if constexpr, the value of the 5259 // condition shall be a contextually converted constant expression of type 5260 // bool. 5261 ImplicitConversionSequence ICS = 5262 CCE == Sema::CCEK_ConstexprIf 5263 ? TryContextuallyConvertToBool(S, From) 5264 : TryCopyInitialization(S, From, T, 5265 /*SuppressUserConversions=*/false, 5266 /*InOverloadResolution=*/false, 5267 /*AllowObjcWritebackConversion=*/false, 5268 /*AllowExplicit=*/false); 5269 StandardConversionSequence *SCS = nullptr; 5270 switch (ICS.getKind()) { 5271 case ImplicitConversionSequence::StandardConversion: 5272 SCS = &ICS.Standard; 5273 break; 5274 case ImplicitConversionSequence::UserDefinedConversion: 5275 // We are converting to a non-class type, so the Before sequence 5276 // must be trivial. 5277 SCS = &ICS.UserDefined.After; 5278 break; 5279 case ImplicitConversionSequence::AmbiguousConversion: 5280 case ImplicitConversionSequence::BadConversion: 5281 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5282 return S.Diag(From->getLocStart(), 5283 diag::err_typecheck_converted_constant_expression) 5284 << From->getType() << From->getSourceRange() << T; 5285 return ExprError(); 5286 5287 case ImplicitConversionSequence::EllipsisConversion: 5288 llvm_unreachable("ellipsis conversion in converted constant expression"); 5289 } 5290 5291 // Check that we would only use permitted conversions. 5292 if (!CheckConvertedConstantConversions(S, *SCS)) { 5293 return S.Diag(From->getLocStart(), 5294 diag::err_typecheck_converted_constant_expression_disallowed) 5295 << From->getType() << From->getSourceRange() << T; 5296 } 5297 // [...] and where the reference binding (if any) binds directly. 5298 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5299 return S.Diag(From->getLocStart(), 5300 diag::err_typecheck_converted_constant_expression_indirect) 5301 << From->getType() << From->getSourceRange() << T; 5302 } 5303 5304 ExprResult Result = 5305 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5306 if (Result.isInvalid()) 5307 return Result; 5308 5309 // Check for a narrowing implicit conversion. 5310 APValue PreNarrowingValue; 5311 QualType PreNarrowingType; 5312 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5313 PreNarrowingType)) { 5314 case NK_Dependent_Narrowing: 5315 // Implicit conversion to a narrower type, but the expression is 5316 // value-dependent so we can't tell whether it's actually narrowing. 5317 case NK_Variable_Narrowing: 5318 // Implicit conversion to a narrower type, and the value is not a constant 5319 // expression. We'll diagnose this in a moment. 5320 case NK_Not_Narrowing: 5321 break; 5322 5323 case NK_Constant_Narrowing: 5324 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5325 << CCE << /*Constant*/1 5326 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5327 break; 5328 5329 case NK_Type_Narrowing: 5330 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5331 << CCE << /*Constant*/0 << From->getType() << T; 5332 break; 5333 } 5334 5335 if (Result.get()->isValueDependent()) { 5336 Value = APValue(); 5337 return Result; 5338 } 5339 5340 // Check the expression is a constant expression. 5341 SmallVector<PartialDiagnosticAt, 8> Notes; 5342 Expr::EvalResult Eval; 5343 Eval.Diag = &Notes; 5344 5345 if ((T->isReferenceType() 5346 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5347 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5348 (RequireInt && !Eval.Val.isInt())) { 5349 // The expression can't be folded, so we can't keep it at this position in 5350 // the AST. 5351 Result = ExprError(); 5352 } else { 5353 Value = Eval.Val; 5354 5355 if (Notes.empty()) { 5356 // It's a constant expression. 5357 return Result; 5358 } 5359 } 5360 5361 // It's not a constant expression. Produce an appropriate diagnostic. 5362 if (Notes.size() == 1 && 5363 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5364 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5365 else { 5366 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5367 << CCE << From->getSourceRange(); 5368 for (unsigned I = 0; I < Notes.size(); ++I) 5369 S.Diag(Notes[I].first, Notes[I].second); 5370 } 5371 return ExprError(); 5372 } 5373 5374 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5375 APValue &Value, CCEKind CCE) { 5376 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5377 } 5378 5379 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5380 llvm::APSInt &Value, 5381 CCEKind CCE) { 5382 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5383 5384 APValue V; 5385 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5386 if (!R.isInvalid() && !R.get()->isValueDependent()) 5387 Value = V.getInt(); 5388 return R; 5389 } 5390 5391 5392 /// dropPointerConversions - If the given standard conversion sequence 5393 /// involves any pointer conversions, remove them. This may change 5394 /// the result type of the conversion sequence. 5395 static void dropPointerConversion(StandardConversionSequence &SCS) { 5396 if (SCS.Second == ICK_Pointer_Conversion) { 5397 SCS.Second = ICK_Identity; 5398 SCS.Third = ICK_Identity; 5399 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5400 } 5401 } 5402 5403 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5404 /// convert the expression From to an Objective-C pointer type. 5405 static ImplicitConversionSequence 5406 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5407 // Do an implicit conversion to 'id'. 5408 QualType Ty = S.Context.getObjCIdType(); 5409 ImplicitConversionSequence ICS 5410 = TryImplicitConversion(S, From, Ty, 5411 // FIXME: Are these flags correct? 5412 /*SuppressUserConversions=*/false, 5413 /*AllowExplicit=*/true, 5414 /*InOverloadResolution=*/false, 5415 /*CStyle=*/false, 5416 /*AllowObjCWritebackConversion=*/false, 5417 /*AllowObjCConversionOnExplicit=*/true); 5418 5419 // Strip off any final conversions to 'id'. 5420 switch (ICS.getKind()) { 5421 case ImplicitConversionSequence::BadConversion: 5422 case ImplicitConversionSequence::AmbiguousConversion: 5423 case ImplicitConversionSequence::EllipsisConversion: 5424 break; 5425 5426 case ImplicitConversionSequence::UserDefinedConversion: 5427 dropPointerConversion(ICS.UserDefined.After); 5428 break; 5429 5430 case ImplicitConversionSequence::StandardConversion: 5431 dropPointerConversion(ICS.Standard); 5432 break; 5433 } 5434 5435 return ICS; 5436 } 5437 5438 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5439 /// conversion of the expression From to an Objective-C pointer type. 5440 /// Returns a valid but null ExprResult if no conversion sequence exists. 5441 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5442 if (checkPlaceholderForOverload(*this, From)) 5443 return ExprError(); 5444 5445 QualType Ty = Context.getObjCIdType(); 5446 ImplicitConversionSequence ICS = 5447 TryContextuallyConvertToObjCPointer(*this, From); 5448 if (!ICS.isBad()) 5449 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5450 return ExprResult(); 5451 } 5452 5453 /// Determine whether the provided type is an integral type, or an enumeration 5454 /// type of a permitted flavor. 5455 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5456 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5457 : T->isIntegralOrUnscopedEnumerationType(); 5458 } 5459 5460 static ExprResult 5461 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5462 Sema::ContextualImplicitConverter &Converter, 5463 QualType T, UnresolvedSetImpl &ViableConversions) { 5464 5465 if (Converter.Suppress) 5466 return ExprError(); 5467 5468 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5469 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5470 CXXConversionDecl *Conv = 5471 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5472 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5473 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5474 } 5475 return From; 5476 } 5477 5478 static bool 5479 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5480 Sema::ContextualImplicitConverter &Converter, 5481 QualType T, bool HadMultipleCandidates, 5482 UnresolvedSetImpl &ExplicitConversions) { 5483 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5484 DeclAccessPair Found = ExplicitConversions[0]; 5485 CXXConversionDecl *Conversion = 5486 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5487 5488 // The user probably meant to invoke the given explicit 5489 // conversion; use it. 5490 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5491 std::string TypeStr; 5492 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5493 5494 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5495 << FixItHint::CreateInsertion(From->getLocStart(), 5496 "static_cast<" + TypeStr + ">(") 5497 << FixItHint::CreateInsertion( 5498 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5499 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5500 5501 // If we aren't in a SFINAE context, build a call to the 5502 // explicit conversion function. 5503 if (SemaRef.isSFINAEContext()) 5504 return true; 5505 5506 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5507 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5508 HadMultipleCandidates); 5509 if (Result.isInvalid()) 5510 return true; 5511 // Record usage of conversion in an implicit cast. 5512 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5513 CK_UserDefinedConversion, Result.get(), 5514 nullptr, Result.get()->getValueKind()); 5515 } 5516 return false; 5517 } 5518 5519 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5520 Sema::ContextualImplicitConverter &Converter, 5521 QualType T, bool HadMultipleCandidates, 5522 DeclAccessPair &Found) { 5523 CXXConversionDecl *Conversion = 5524 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5525 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5526 5527 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5528 if (!Converter.SuppressConversion) { 5529 if (SemaRef.isSFINAEContext()) 5530 return true; 5531 5532 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5533 << From->getSourceRange(); 5534 } 5535 5536 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5537 HadMultipleCandidates); 5538 if (Result.isInvalid()) 5539 return true; 5540 // Record usage of conversion in an implicit cast. 5541 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5542 CK_UserDefinedConversion, Result.get(), 5543 nullptr, Result.get()->getValueKind()); 5544 return false; 5545 } 5546 5547 static ExprResult finishContextualImplicitConversion( 5548 Sema &SemaRef, SourceLocation Loc, Expr *From, 5549 Sema::ContextualImplicitConverter &Converter) { 5550 if (!Converter.match(From->getType()) && !Converter.Suppress) 5551 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5552 << From->getSourceRange(); 5553 5554 return SemaRef.DefaultLvalueConversion(From); 5555 } 5556 5557 static void 5558 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5559 UnresolvedSetImpl &ViableConversions, 5560 OverloadCandidateSet &CandidateSet) { 5561 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5562 DeclAccessPair FoundDecl = ViableConversions[I]; 5563 NamedDecl *D = FoundDecl.getDecl(); 5564 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5565 if (isa<UsingShadowDecl>(D)) 5566 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5567 5568 CXXConversionDecl *Conv; 5569 FunctionTemplateDecl *ConvTemplate; 5570 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5571 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5572 else 5573 Conv = cast<CXXConversionDecl>(D); 5574 5575 if (ConvTemplate) 5576 SemaRef.AddTemplateConversionCandidate( 5577 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5578 /*AllowObjCConversionOnExplicit=*/false); 5579 else 5580 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5581 ToType, CandidateSet, 5582 /*AllowObjCConversionOnExplicit=*/false); 5583 } 5584 } 5585 5586 /// \brief Attempt to convert the given expression to a type which is accepted 5587 /// by the given converter. 5588 /// 5589 /// This routine will attempt to convert an expression of class type to a 5590 /// type accepted by the specified converter. In C++11 and before, the class 5591 /// must have a single non-explicit conversion function converting to a matching 5592 /// type. In C++1y, there can be multiple such conversion functions, but only 5593 /// one target type. 5594 /// 5595 /// \param Loc The source location of the construct that requires the 5596 /// conversion. 5597 /// 5598 /// \param From The expression we're converting from. 5599 /// 5600 /// \param Converter Used to control and diagnose the conversion process. 5601 /// 5602 /// \returns The expression, converted to an integral or enumeration type if 5603 /// successful. 5604 ExprResult Sema::PerformContextualImplicitConversion( 5605 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5606 // We can't perform any more checking for type-dependent expressions. 5607 if (From->isTypeDependent()) 5608 return From; 5609 5610 // Process placeholders immediately. 5611 if (From->hasPlaceholderType()) { 5612 ExprResult result = CheckPlaceholderExpr(From); 5613 if (result.isInvalid()) 5614 return result; 5615 From = result.get(); 5616 } 5617 5618 // If the expression already has a matching type, we're golden. 5619 QualType T = From->getType(); 5620 if (Converter.match(T)) 5621 return DefaultLvalueConversion(From); 5622 5623 // FIXME: Check for missing '()' if T is a function type? 5624 5625 // We can only perform contextual implicit conversions on objects of class 5626 // type. 5627 const RecordType *RecordTy = T->getAs<RecordType>(); 5628 if (!RecordTy || !getLangOpts().CPlusPlus) { 5629 if (!Converter.Suppress) 5630 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5631 return From; 5632 } 5633 5634 // We must have a complete class type. 5635 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5636 ContextualImplicitConverter &Converter; 5637 Expr *From; 5638 5639 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5640 : Converter(Converter), From(From) {} 5641 5642 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5643 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5644 } 5645 } IncompleteDiagnoser(Converter, From); 5646 5647 if (Converter.Suppress ? !isCompleteType(Loc, T) 5648 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5649 return From; 5650 5651 // Look for a conversion to an integral or enumeration type. 5652 UnresolvedSet<4> 5653 ViableConversions; // These are *potentially* viable in C++1y. 5654 UnresolvedSet<4> ExplicitConversions; 5655 const auto &Conversions = 5656 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5657 5658 bool HadMultipleCandidates = 5659 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5660 5661 // To check that there is only one target type, in C++1y: 5662 QualType ToType; 5663 bool HasUniqueTargetType = true; 5664 5665 // Collect explicit or viable (potentially in C++1y) conversions. 5666 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5667 NamedDecl *D = (*I)->getUnderlyingDecl(); 5668 CXXConversionDecl *Conversion; 5669 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5670 if (ConvTemplate) { 5671 if (getLangOpts().CPlusPlus14) 5672 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5673 else 5674 continue; // C++11 does not consider conversion operator templates(?). 5675 } else 5676 Conversion = cast<CXXConversionDecl>(D); 5677 5678 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5679 "Conversion operator templates are considered potentially " 5680 "viable in C++1y"); 5681 5682 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5683 if (Converter.match(CurToType) || ConvTemplate) { 5684 5685 if (Conversion->isExplicit()) { 5686 // FIXME: For C++1y, do we need this restriction? 5687 // cf. diagnoseNoViableConversion() 5688 if (!ConvTemplate) 5689 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5690 } else { 5691 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5692 if (ToType.isNull()) 5693 ToType = CurToType.getUnqualifiedType(); 5694 else if (HasUniqueTargetType && 5695 (CurToType.getUnqualifiedType() != ToType)) 5696 HasUniqueTargetType = false; 5697 } 5698 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5699 } 5700 } 5701 } 5702 5703 if (getLangOpts().CPlusPlus14) { 5704 // C++1y [conv]p6: 5705 // ... An expression e of class type E appearing in such a context 5706 // is said to be contextually implicitly converted to a specified 5707 // type T and is well-formed if and only if e can be implicitly 5708 // converted to a type T that is determined as follows: E is searched 5709 // for conversion functions whose return type is cv T or reference to 5710 // cv T such that T is allowed by the context. There shall be 5711 // exactly one such T. 5712 5713 // If no unique T is found: 5714 if (ToType.isNull()) { 5715 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5716 HadMultipleCandidates, 5717 ExplicitConversions)) 5718 return ExprError(); 5719 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5720 } 5721 5722 // If more than one unique Ts are found: 5723 if (!HasUniqueTargetType) 5724 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5725 ViableConversions); 5726 5727 // If one unique T is found: 5728 // First, build a candidate set from the previously recorded 5729 // potentially viable conversions. 5730 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5731 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5732 CandidateSet); 5733 5734 // Then, perform overload resolution over the candidate set. 5735 OverloadCandidateSet::iterator Best; 5736 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5737 case OR_Success: { 5738 // Apply this conversion. 5739 DeclAccessPair Found = 5740 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5741 if (recordConversion(*this, Loc, From, Converter, T, 5742 HadMultipleCandidates, Found)) 5743 return ExprError(); 5744 break; 5745 } 5746 case OR_Ambiguous: 5747 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5748 ViableConversions); 5749 case OR_No_Viable_Function: 5750 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5751 HadMultipleCandidates, 5752 ExplicitConversions)) 5753 return ExprError(); 5754 // fall through 'OR_Deleted' case. 5755 case OR_Deleted: 5756 // We'll complain below about a non-integral condition type. 5757 break; 5758 } 5759 } else { 5760 switch (ViableConversions.size()) { 5761 case 0: { 5762 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5763 HadMultipleCandidates, 5764 ExplicitConversions)) 5765 return ExprError(); 5766 5767 // We'll complain below about a non-integral condition type. 5768 break; 5769 } 5770 case 1: { 5771 // Apply this conversion. 5772 DeclAccessPair Found = ViableConversions[0]; 5773 if (recordConversion(*this, Loc, From, Converter, T, 5774 HadMultipleCandidates, Found)) 5775 return ExprError(); 5776 break; 5777 } 5778 default: 5779 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5780 ViableConversions); 5781 } 5782 } 5783 5784 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5785 } 5786 5787 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5788 /// an acceptable non-member overloaded operator for a call whose 5789 /// arguments have types T1 (and, if non-empty, T2). This routine 5790 /// implements the check in C++ [over.match.oper]p3b2 concerning 5791 /// enumeration types. 5792 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5793 FunctionDecl *Fn, 5794 ArrayRef<Expr *> Args) { 5795 QualType T1 = Args[0]->getType(); 5796 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5797 5798 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5799 return true; 5800 5801 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5802 return true; 5803 5804 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5805 if (Proto->getNumParams() < 1) 5806 return false; 5807 5808 if (T1->isEnumeralType()) { 5809 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5810 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5811 return true; 5812 } 5813 5814 if (Proto->getNumParams() < 2) 5815 return false; 5816 5817 if (!T2.isNull() && T2->isEnumeralType()) { 5818 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5819 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5820 return true; 5821 } 5822 5823 return false; 5824 } 5825 5826 /// AddOverloadCandidate - Adds the given function to the set of 5827 /// candidate functions, using the given function call arguments. If 5828 /// @p SuppressUserConversions, then don't allow user-defined 5829 /// conversions via constructors or conversion operators. 5830 /// 5831 /// \param PartialOverloading true if we are performing "partial" overloading 5832 /// based on an incomplete set of function arguments. This feature is used by 5833 /// code completion. 5834 void 5835 Sema::AddOverloadCandidate(FunctionDecl *Function, 5836 DeclAccessPair FoundDecl, 5837 ArrayRef<Expr *> Args, 5838 OverloadCandidateSet &CandidateSet, 5839 bool SuppressUserConversions, 5840 bool PartialOverloading, 5841 bool AllowExplicit, 5842 ConversionSequenceList EarlyConversions) { 5843 const FunctionProtoType *Proto 5844 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5845 assert(Proto && "Functions without a prototype cannot be overloaded"); 5846 assert(!Function->getDescribedFunctionTemplate() && 5847 "Use AddTemplateOverloadCandidate for function templates"); 5848 5849 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5850 if (!isa<CXXConstructorDecl>(Method)) { 5851 // If we get here, it's because we're calling a member function 5852 // that is named without a member access expression (e.g., 5853 // "this->f") that was either written explicitly or created 5854 // implicitly. This can happen with a qualified call to a member 5855 // function, e.g., X::f(). We use an empty type for the implied 5856 // object argument (C++ [over.call.func]p3), and the acting context 5857 // is irrelevant. 5858 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 5859 Expr::Classification::makeSimpleLValue(), Args, 5860 CandidateSet, SuppressUserConversions, 5861 PartialOverloading, EarlyConversions); 5862 return; 5863 } 5864 // We treat a constructor like a non-member function, since its object 5865 // argument doesn't participate in overload resolution. 5866 } 5867 5868 if (!CandidateSet.isNewCandidate(Function)) 5869 return; 5870 5871 // C++ [over.match.oper]p3: 5872 // if no operand has a class type, only those non-member functions in the 5873 // lookup set that have a first parameter of type T1 or "reference to 5874 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5875 // is a right operand) a second parameter of type T2 or "reference to 5876 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5877 // candidate functions. 5878 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5879 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5880 return; 5881 5882 // C++11 [class.copy]p11: [DR1402] 5883 // A defaulted move constructor that is defined as deleted is ignored by 5884 // overload resolution. 5885 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5886 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5887 Constructor->isMoveConstructor()) 5888 return; 5889 5890 // Overload resolution is always an unevaluated context. 5891 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5892 5893 // Add this candidate 5894 OverloadCandidate &Candidate = 5895 CandidateSet.addCandidate(Args.size(), EarlyConversions); 5896 Candidate.FoundDecl = FoundDecl; 5897 Candidate.Function = Function; 5898 Candidate.Viable = true; 5899 Candidate.IsSurrogate = false; 5900 Candidate.IgnoreObjectArgument = false; 5901 Candidate.ExplicitCallArguments = Args.size(); 5902 5903 if (Constructor) { 5904 // C++ [class.copy]p3: 5905 // A member function template is never instantiated to perform the copy 5906 // of a class object to an object of its class type. 5907 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5908 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5909 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5910 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5911 ClassType))) { 5912 Candidate.Viable = false; 5913 Candidate.FailureKind = ovl_fail_illegal_constructor; 5914 return; 5915 } 5916 5917 // C++ [over.match.funcs]p8: (proposed DR resolution) 5918 // A constructor inherited from class type C that has a first parameter 5919 // of type "reference to P" (including such a constructor instantiated 5920 // from a template) is excluded from the set of candidate functions when 5921 // constructing an object of type cv D if the argument list has exactly 5922 // one argument and D is reference-related to P and P is reference-related 5923 // to C. 5924 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 5925 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 5926 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 5927 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 5928 QualType C = Context.getRecordType(Constructor->getParent()); 5929 QualType D = Context.getRecordType(Shadow->getParent()); 5930 SourceLocation Loc = Args.front()->getExprLoc(); 5931 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 5932 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 5933 Candidate.Viable = false; 5934 Candidate.FailureKind = ovl_fail_inhctor_slice; 5935 return; 5936 } 5937 } 5938 } 5939 5940 unsigned NumParams = Proto->getNumParams(); 5941 5942 // (C++ 13.3.2p2): A candidate function having fewer than m 5943 // parameters is viable only if it has an ellipsis in its parameter 5944 // list (8.3.5). 5945 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5946 !Proto->isVariadic()) { 5947 Candidate.Viable = false; 5948 Candidate.FailureKind = ovl_fail_too_many_arguments; 5949 return; 5950 } 5951 5952 // (C++ 13.3.2p2): A candidate function having more than m parameters 5953 // is viable only if the (m+1)st parameter has a default argument 5954 // (8.3.6). For the purposes of overload resolution, the 5955 // parameter list is truncated on the right, so that there are 5956 // exactly m parameters. 5957 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5958 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5959 // Not enough arguments. 5960 Candidate.Viable = false; 5961 Candidate.FailureKind = ovl_fail_too_few_arguments; 5962 return; 5963 } 5964 5965 // (CUDA B.1): Check for invalid calls between targets. 5966 if (getLangOpts().CUDA) 5967 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5968 // Skip the check for callers that are implicit members, because in this 5969 // case we may not yet know what the member's target is; the target is 5970 // inferred for the member automatically, based on the bases and fields of 5971 // the class. 5972 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 5973 Candidate.Viable = false; 5974 Candidate.FailureKind = ovl_fail_bad_target; 5975 return; 5976 } 5977 5978 // Determine the implicit conversion sequences for each of the 5979 // arguments. 5980 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5981 if (Candidate.Conversions[ArgIdx].isInitialized()) { 5982 // We already formed a conversion sequence for this parameter during 5983 // template argument deduction. 5984 } else if (ArgIdx < NumParams) { 5985 // (C++ 13.3.2p3): for F to be a viable function, there shall 5986 // exist for each argument an implicit conversion sequence 5987 // (13.3.3.1) that converts that argument to the corresponding 5988 // parameter of F. 5989 QualType ParamType = Proto->getParamType(ArgIdx); 5990 Candidate.Conversions[ArgIdx] 5991 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5992 SuppressUserConversions, 5993 /*InOverloadResolution=*/true, 5994 /*AllowObjCWritebackConversion=*/ 5995 getLangOpts().ObjCAutoRefCount, 5996 AllowExplicit); 5997 if (Candidate.Conversions[ArgIdx].isBad()) { 5998 Candidate.Viable = false; 5999 Candidate.FailureKind = ovl_fail_bad_conversion; 6000 return; 6001 } 6002 } else { 6003 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6004 // argument for which there is no corresponding parameter is 6005 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6006 Candidate.Conversions[ArgIdx].setEllipsis(); 6007 } 6008 } 6009 6010 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6011 Candidate.Viable = false; 6012 Candidate.FailureKind = ovl_fail_enable_if; 6013 Candidate.DeductionFailure.Data = FailedAttr; 6014 return; 6015 } 6016 6017 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6018 Candidate.Viable = false; 6019 Candidate.FailureKind = ovl_fail_ext_disabled; 6020 return; 6021 } 6022 } 6023 6024 ObjCMethodDecl * 6025 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6026 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6027 if (Methods.size() <= 1) 6028 return nullptr; 6029 6030 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6031 bool Match = true; 6032 ObjCMethodDecl *Method = Methods[b]; 6033 unsigned NumNamedArgs = Sel.getNumArgs(); 6034 // Method might have more arguments than selector indicates. This is due 6035 // to addition of c-style arguments in method. 6036 if (Method->param_size() > NumNamedArgs) 6037 NumNamedArgs = Method->param_size(); 6038 if (Args.size() < NumNamedArgs) 6039 continue; 6040 6041 for (unsigned i = 0; i < NumNamedArgs; i++) { 6042 // We can't do any type-checking on a type-dependent argument. 6043 if (Args[i]->isTypeDependent()) { 6044 Match = false; 6045 break; 6046 } 6047 6048 ParmVarDecl *param = Method->parameters()[i]; 6049 Expr *argExpr = Args[i]; 6050 assert(argExpr && "SelectBestMethod(): missing expression"); 6051 6052 // Strip the unbridged-cast placeholder expression off unless it's 6053 // a consumed argument. 6054 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6055 !param->hasAttr<CFConsumedAttr>()) 6056 argExpr = stripARCUnbridgedCast(argExpr); 6057 6058 // If the parameter is __unknown_anytype, move on to the next method. 6059 if (param->getType() == Context.UnknownAnyTy) { 6060 Match = false; 6061 break; 6062 } 6063 6064 ImplicitConversionSequence ConversionState 6065 = TryCopyInitialization(*this, argExpr, param->getType(), 6066 /*SuppressUserConversions*/false, 6067 /*InOverloadResolution=*/true, 6068 /*AllowObjCWritebackConversion=*/ 6069 getLangOpts().ObjCAutoRefCount, 6070 /*AllowExplicit*/false); 6071 // This function looks for a reasonably-exact match, so we consider 6072 // incompatible pointer conversions to be a failure here. 6073 if (ConversionState.isBad() || 6074 (ConversionState.isStandard() && 6075 ConversionState.Standard.Second == 6076 ICK_Incompatible_Pointer_Conversion)) { 6077 Match = false; 6078 break; 6079 } 6080 } 6081 // Promote additional arguments to variadic methods. 6082 if (Match && Method->isVariadic()) { 6083 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6084 if (Args[i]->isTypeDependent()) { 6085 Match = false; 6086 break; 6087 } 6088 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6089 nullptr); 6090 if (Arg.isInvalid()) { 6091 Match = false; 6092 break; 6093 } 6094 } 6095 } else { 6096 // Check for extra arguments to non-variadic methods. 6097 if (Args.size() != NumNamedArgs) 6098 Match = false; 6099 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6100 // Special case when selectors have no argument. In this case, select 6101 // one with the most general result type of 'id'. 6102 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6103 QualType ReturnT = Methods[b]->getReturnType(); 6104 if (ReturnT->isObjCIdType()) 6105 return Methods[b]; 6106 } 6107 } 6108 } 6109 6110 if (Match) 6111 return Method; 6112 } 6113 return nullptr; 6114 } 6115 6116 // specific_attr_iterator iterates over enable_if attributes in reverse, and 6117 // enable_if is order-sensitive. As a result, we need to reverse things 6118 // sometimes. Size of 4 elements is arbitrary. 6119 static SmallVector<EnableIfAttr *, 4> 6120 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 6121 SmallVector<EnableIfAttr *, 4> Result; 6122 if (!Function->hasAttrs()) 6123 return Result; 6124 6125 const auto &FuncAttrs = Function->getAttrs(); 6126 for (Attr *Attr : FuncAttrs) 6127 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 6128 Result.push_back(EnableIf); 6129 6130 std::reverse(Result.begin(), Result.end()); 6131 return Result; 6132 } 6133 6134 static bool 6135 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6136 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6137 bool MissingImplicitThis, Expr *&ConvertedThis, 6138 SmallVectorImpl<Expr *> &ConvertedArgs) { 6139 if (ThisArg) { 6140 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6141 assert(!isa<CXXConstructorDecl>(Method) && 6142 "Shouldn't have `this` for ctors!"); 6143 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6144 ExprResult R = S.PerformObjectArgumentInitialization( 6145 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6146 if (R.isInvalid()) 6147 return false; 6148 ConvertedThis = R.get(); 6149 } else { 6150 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6151 (void)MD; 6152 assert((MissingImplicitThis || MD->isStatic() || 6153 isa<CXXConstructorDecl>(MD)) && 6154 "Expected `this` for non-ctor instance methods"); 6155 } 6156 ConvertedThis = nullptr; 6157 } 6158 6159 // Ignore any variadic arguments. Converting them is pointless, since the 6160 // user can't refer to them in the function condition. 6161 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6162 6163 // Convert the arguments. 6164 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6165 ExprResult R; 6166 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6167 S.Context, Function->getParamDecl(I)), 6168 SourceLocation(), Args[I]); 6169 6170 if (R.isInvalid()) 6171 return false; 6172 6173 ConvertedArgs.push_back(R.get()); 6174 } 6175 6176 if (Trap.hasErrorOccurred()) 6177 return false; 6178 6179 // Push default arguments if needed. 6180 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6181 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6182 ParmVarDecl *P = Function->getParamDecl(i); 6183 ExprResult R = S.PerformCopyInitialization( 6184 InitializedEntity::InitializeParameter(S.Context, 6185 Function->getParamDecl(i)), 6186 SourceLocation(), 6187 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6188 : P->getDefaultArg()); 6189 if (R.isInvalid()) 6190 return false; 6191 ConvertedArgs.push_back(R.get()); 6192 } 6193 6194 if (Trap.hasErrorOccurred()) 6195 return false; 6196 } 6197 return true; 6198 } 6199 6200 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6201 bool MissingImplicitThis) { 6202 SmallVector<EnableIfAttr *, 4> EnableIfAttrs = 6203 getOrderedEnableIfAttrs(Function); 6204 if (EnableIfAttrs.empty()) 6205 return nullptr; 6206 6207 SFINAETrap Trap(*this); 6208 SmallVector<Expr *, 16> ConvertedArgs; 6209 // FIXME: We should look into making enable_if late-parsed. 6210 Expr *DiscardedThis; 6211 if (!convertArgsForAvailabilityChecks( 6212 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6213 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6214 return EnableIfAttrs[0]; 6215 6216 for (auto *EIA : EnableIfAttrs) { 6217 APValue Result; 6218 // FIXME: This doesn't consider value-dependent cases, because doing so is 6219 // very difficult. Ideally, we should handle them more gracefully. 6220 if (!EIA->getCond()->EvaluateWithSubstitution( 6221 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6222 return EIA; 6223 6224 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6225 return EIA; 6226 } 6227 return nullptr; 6228 } 6229 6230 template <typename CheckFn> 6231 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const FunctionDecl *FD, 6232 bool ArgDependent, SourceLocation Loc, 6233 CheckFn &&IsSuccessful) { 6234 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6235 for (const auto *DIA : FD->specific_attrs<DiagnoseIfAttr>()) { 6236 if (ArgDependent == DIA->getArgDependent()) 6237 Attrs.push_back(DIA); 6238 } 6239 6240 // Common case: No diagnose_if attributes, so we can quit early. 6241 if (Attrs.empty()) 6242 return false; 6243 6244 auto WarningBegin = std::stable_partition( 6245 Attrs.begin(), Attrs.end(), 6246 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6247 6248 // Note that diagnose_if attributes are late-parsed, so they appear in the 6249 // correct order (unlike enable_if attributes). 6250 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6251 IsSuccessful); 6252 if (ErrAttr != WarningBegin) { 6253 const DiagnoseIfAttr *DIA = *ErrAttr; 6254 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6255 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6256 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6257 return true; 6258 } 6259 6260 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6261 if (IsSuccessful(DIA)) { 6262 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6263 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6264 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6265 } 6266 6267 return false; 6268 } 6269 6270 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6271 const Expr *ThisArg, 6272 ArrayRef<const Expr *> Args, 6273 SourceLocation Loc) { 6274 return diagnoseDiagnoseIfAttrsWith( 6275 *this, Function, /*ArgDependent=*/true, Loc, 6276 [&](const DiagnoseIfAttr *DIA) { 6277 APValue Result; 6278 // It's sane to use the same Args for any redecl of this function, since 6279 // EvaluateWithSubstitution only cares about the position of each 6280 // argument in the arg list, not the ParmVarDecl* it maps to. 6281 if (!DIA->getCond()->EvaluateWithSubstitution( 6282 Result, Context, DIA->getParent(), Args, ThisArg)) 6283 return false; 6284 return Result.isInt() && Result.getInt().getBoolValue(); 6285 }); 6286 } 6287 6288 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function, 6289 SourceLocation Loc) { 6290 return diagnoseDiagnoseIfAttrsWith( 6291 *this, Function, /*ArgDependent=*/false, Loc, 6292 [&](const DiagnoseIfAttr *DIA) { 6293 bool Result; 6294 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6295 Result; 6296 }); 6297 } 6298 6299 /// \brief Add all of the function declarations in the given function set to 6300 /// the overload candidate set. 6301 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6302 ArrayRef<Expr *> Args, 6303 OverloadCandidateSet& CandidateSet, 6304 TemplateArgumentListInfo *ExplicitTemplateArgs, 6305 bool SuppressUserConversions, 6306 bool PartialOverloading) { 6307 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6308 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6309 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6310 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6311 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6312 cast<CXXMethodDecl>(FD)->getParent(), 6313 Args[0]->getType(), Args[0]->Classify(Context), 6314 Args.slice(1), CandidateSet, SuppressUserConversions, 6315 PartialOverloading); 6316 else 6317 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6318 SuppressUserConversions, PartialOverloading); 6319 } else { 6320 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6321 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6322 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6323 AddMethodTemplateCandidate( 6324 FunTmpl, F.getPair(), 6325 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6326 ExplicitTemplateArgs, Args[0]->getType(), 6327 Args[0]->Classify(Context), Args.slice(1), CandidateSet, 6328 SuppressUserConversions, PartialOverloading); 6329 else 6330 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6331 ExplicitTemplateArgs, Args, 6332 CandidateSet, SuppressUserConversions, 6333 PartialOverloading); 6334 } 6335 } 6336 } 6337 6338 /// AddMethodCandidate - Adds a named decl (which is some kind of 6339 /// method) as a method candidate to the given overload set. 6340 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6341 QualType ObjectType, 6342 Expr::Classification ObjectClassification, 6343 ArrayRef<Expr *> Args, 6344 OverloadCandidateSet& CandidateSet, 6345 bool SuppressUserConversions) { 6346 NamedDecl *Decl = FoundDecl.getDecl(); 6347 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6348 6349 if (isa<UsingShadowDecl>(Decl)) 6350 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6351 6352 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6353 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6354 "Expected a member function template"); 6355 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6356 /*ExplicitArgs*/ nullptr, ObjectType, 6357 ObjectClassification, Args, CandidateSet, 6358 SuppressUserConversions); 6359 } else { 6360 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6361 ObjectType, ObjectClassification, Args, CandidateSet, 6362 SuppressUserConversions); 6363 } 6364 } 6365 6366 /// AddMethodCandidate - Adds the given C++ member function to the set 6367 /// of candidate functions, using the given function call arguments 6368 /// and the object argument (@c Object). For example, in a call 6369 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6370 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6371 /// allow user-defined conversions via constructors or conversion 6372 /// operators. 6373 void 6374 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6375 CXXRecordDecl *ActingContext, QualType ObjectType, 6376 Expr::Classification ObjectClassification, 6377 ArrayRef<Expr *> Args, 6378 OverloadCandidateSet &CandidateSet, 6379 bool SuppressUserConversions, 6380 bool PartialOverloading, 6381 ConversionSequenceList EarlyConversions) { 6382 const FunctionProtoType *Proto 6383 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6384 assert(Proto && "Methods without a prototype cannot be overloaded"); 6385 assert(!isa<CXXConstructorDecl>(Method) && 6386 "Use AddOverloadCandidate for constructors"); 6387 6388 if (!CandidateSet.isNewCandidate(Method)) 6389 return; 6390 6391 // C++11 [class.copy]p23: [DR1402] 6392 // A defaulted move assignment operator that is defined as deleted is 6393 // ignored by overload resolution. 6394 if (Method->isDefaulted() && Method->isDeleted() && 6395 Method->isMoveAssignmentOperator()) 6396 return; 6397 6398 // Overload resolution is always an unevaluated context. 6399 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6400 6401 // Add this candidate 6402 OverloadCandidate &Candidate = 6403 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6404 Candidate.FoundDecl = FoundDecl; 6405 Candidate.Function = Method; 6406 Candidate.IsSurrogate = false; 6407 Candidate.IgnoreObjectArgument = false; 6408 Candidate.ExplicitCallArguments = Args.size(); 6409 6410 unsigned NumParams = Proto->getNumParams(); 6411 6412 // (C++ 13.3.2p2): A candidate function having fewer than m 6413 // parameters is viable only if it has an ellipsis in its parameter 6414 // list (8.3.5). 6415 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6416 !Proto->isVariadic()) { 6417 Candidate.Viable = false; 6418 Candidate.FailureKind = ovl_fail_too_many_arguments; 6419 return; 6420 } 6421 6422 // (C++ 13.3.2p2): A candidate function having more than m parameters 6423 // is viable only if the (m+1)st parameter has a default argument 6424 // (8.3.6). For the purposes of overload resolution, the 6425 // parameter list is truncated on the right, so that there are 6426 // exactly m parameters. 6427 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6428 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6429 // Not enough arguments. 6430 Candidate.Viable = false; 6431 Candidate.FailureKind = ovl_fail_too_few_arguments; 6432 return; 6433 } 6434 6435 Candidate.Viable = true; 6436 6437 if (Method->isStatic() || ObjectType.isNull()) 6438 // The implicit object argument is ignored. 6439 Candidate.IgnoreObjectArgument = true; 6440 else { 6441 // Determine the implicit conversion sequence for the object 6442 // parameter. 6443 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6444 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6445 Method, ActingContext); 6446 if (Candidate.Conversions[0].isBad()) { 6447 Candidate.Viable = false; 6448 Candidate.FailureKind = ovl_fail_bad_conversion; 6449 return; 6450 } 6451 } 6452 6453 // (CUDA B.1): Check for invalid calls between targets. 6454 if (getLangOpts().CUDA) 6455 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6456 if (!IsAllowedCUDACall(Caller, Method)) { 6457 Candidate.Viable = false; 6458 Candidate.FailureKind = ovl_fail_bad_target; 6459 return; 6460 } 6461 6462 // Determine the implicit conversion sequences for each of the 6463 // arguments. 6464 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6465 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6466 // We already formed a conversion sequence for this parameter during 6467 // template argument deduction. 6468 } else if (ArgIdx < NumParams) { 6469 // (C++ 13.3.2p3): for F to be a viable function, there shall 6470 // exist for each argument an implicit conversion sequence 6471 // (13.3.3.1) that converts that argument to the corresponding 6472 // parameter of F. 6473 QualType ParamType = Proto->getParamType(ArgIdx); 6474 Candidate.Conversions[ArgIdx + 1] 6475 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6476 SuppressUserConversions, 6477 /*InOverloadResolution=*/true, 6478 /*AllowObjCWritebackConversion=*/ 6479 getLangOpts().ObjCAutoRefCount); 6480 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6481 Candidate.Viable = false; 6482 Candidate.FailureKind = ovl_fail_bad_conversion; 6483 return; 6484 } 6485 } else { 6486 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6487 // argument for which there is no corresponding parameter is 6488 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6489 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6490 } 6491 } 6492 6493 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6494 Candidate.Viable = false; 6495 Candidate.FailureKind = ovl_fail_enable_if; 6496 Candidate.DeductionFailure.Data = FailedAttr; 6497 return; 6498 } 6499 } 6500 6501 /// \brief Add a C++ member function template as a candidate to the candidate 6502 /// set, using template argument deduction to produce an appropriate member 6503 /// function template specialization. 6504 void 6505 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6506 DeclAccessPair FoundDecl, 6507 CXXRecordDecl *ActingContext, 6508 TemplateArgumentListInfo *ExplicitTemplateArgs, 6509 QualType ObjectType, 6510 Expr::Classification ObjectClassification, 6511 ArrayRef<Expr *> Args, 6512 OverloadCandidateSet& CandidateSet, 6513 bool SuppressUserConversions, 6514 bool PartialOverloading) { 6515 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6516 return; 6517 6518 // C++ [over.match.funcs]p7: 6519 // In each case where a candidate is a function template, candidate 6520 // function template specializations are generated using template argument 6521 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6522 // candidate functions in the usual way.113) A given name can refer to one 6523 // or more function templates and also to a set of overloaded non-template 6524 // functions. In such a case, the candidate functions generated from each 6525 // function template are combined with the set of non-template candidate 6526 // functions. 6527 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6528 FunctionDecl *Specialization = nullptr; 6529 ConversionSequenceList Conversions; 6530 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6531 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6532 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6533 return CheckNonDependentConversions( 6534 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6535 SuppressUserConversions, ActingContext, ObjectType, 6536 ObjectClassification); 6537 })) { 6538 OverloadCandidate &Candidate = 6539 CandidateSet.addCandidate(Conversions.size(), Conversions); 6540 Candidate.FoundDecl = FoundDecl; 6541 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6542 Candidate.Viable = false; 6543 Candidate.IsSurrogate = false; 6544 Candidate.IgnoreObjectArgument = 6545 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6546 ObjectType.isNull(); 6547 Candidate.ExplicitCallArguments = Args.size(); 6548 if (Result == TDK_NonDependentConversionFailure) 6549 Candidate.FailureKind = ovl_fail_bad_conversion; 6550 else { 6551 Candidate.FailureKind = ovl_fail_bad_deduction; 6552 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6553 Info); 6554 } 6555 return; 6556 } 6557 6558 // Add the function template specialization produced by template argument 6559 // deduction as a candidate. 6560 assert(Specialization && "Missing member function template specialization?"); 6561 assert(isa<CXXMethodDecl>(Specialization) && 6562 "Specialization is not a member function?"); 6563 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6564 ActingContext, ObjectType, ObjectClassification, Args, 6565 CandidateSet, SuppressUserConversions, PartialOverloading, 6566 Conversions); 6567 } 6568 6569 /// \brief Add a C++ function template specialization as a candidate 6570 /// in the candidate set, using template argument deduction to produce 6571 /// an appropriate function template specialization. 6572 void 6573 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6574 DeclAccessPair FoundDecl, 6575 TemplateArgumentListInfo *ExplicitTemplateArgs, 6576 ArrayRef<Expr *> Args, 6577 OverloadCandidateSet& CandidateSet, 6578 bool SuppressUserConversions, 6579 bool PartialOverloading) { 6580 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6581 return; 6582 6583 // C++ [over.match.funcs]p7: 6584 // In each case where a candidate is a function template, candidate 6585 // function template specializations are generated using template argument 6586 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6587 // candidate functions in the usual way.113) A given name can refer to one 6588 // or more function templates and also to a set of overloaded non-template 6589 // functions. In such a case, the candidate functions generated from each 6590 // function template are combined with the set of non-template candidate 6591 // functions. 6592 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6593 FunctionDecl *Specialization = nullptr; 6594 ConversionSequenceList Conversions; 6595 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6596 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6597 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6598 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6599 Args, CandidateSet, Conversions, 6600 SuppressUserConversions); 6601 })) { 6602 OverloadCandidate &Candidate = 6603 CandidateSet.addCandidate(Conversions.size(), Conversions); 6604 Candidate.FoundDecl = FoundDecl; 6605 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6606 Candidate.Viable = false; 6607 Candidate.IsSurrogate = false; 6608 // Ignore the object argument if there is one, since we don't have an object 6609 // type. 6610 Candidate.IgnoreObjectArgument = 6611 isa<CXXMethodDecl>(Candidate.Function) && 6612 !isa<CXXConstructorDecl>(Candidate.Function); 6613 Candidate.ExplicitCallArguments = Args.size(); 6614 if (Result == TDK_NonDependentConversionFailure) 6615 Candidate.FailureKind = ovl_fail_bad_conversion; 6616 else { 6617 Candidate.FailureKind = ovl_fail_bad_deduction; 6618 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6619 Info); 6620 } 6621 return; 6622 } 6623 6624 // Add the function template specialization produced by template argument 6625 // deduction as a candidate. 6626 assert(Specialization && "Missing function template specialization?"); 6627 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6628 SuppressUserConversions, PartialOverloading, 6629 /*AllowExplicit*/false, Conversions); 6630 } 6631 6632 /// Check that implicit conversion sequences can be formed for each argument 6633 /// whose corresponding parameter has a non-dependent type, per DR1391's 6634 /// [temp.deduct.call]p10. 6635 bool Sema::CheckNonDependentConversions( 6636 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6637 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6638 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6639 CXXRecordDecl *ActingContext, QualType ObjectType, 6640 Expr::Classification ObjectClassification) { 6641 // FIXME: The cases in which we allow explicit conversions for constructor 6642 // arguments never consider calling a constructor template. It's not clear 6643 // that is correct. 6644 const bool AllowExplicit = false; 6645 6646 auto *FD = FunctionTemplate->getTemplatedDecl(); 6647 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6648 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6649 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6650 6651 Conversions = 6652 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6653 6654 // Overload resolution is always an unevaluated context. 6655 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6656 6657 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6658 // require that, but this check should never result in a hard error, and 6659 // overload resolution is permitted to sidestep instantiations. 6660 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6661 !ObjectType.isNull()) { 6662 Conversions[0] = TryObjectArgumentInitialization( 6663 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6664 Method, ActingContext); 6665 if (Conversions[0].isBad()) 6666 return true; 6667 } 6668 6669 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6670 ++I) { 6671 QualType ParamType = ParamTypes[I]; 6672 if (!ParamType->isDependentType()) { 6673 Conversions[ThisConversions + I] 6674 = TryCopyInitialization(*this, Args[I], ParamType, 6675 SuppressUserConversions, 6676 /*InOverloadResolution=*/true, 6677 /*AllowObjCWritebackConversion=*/ 6678 getLangOpts().ObjCAutoRefCount, 6679 AllowExplicit); 6680 if (Conversions[ThisConversions + I].isBad()) 6681 return true; 6682 } 6683 } 6684 6685 return false; 6686 } 6687 6688 /// Determine whether this is an allowable conversion from the result 6689 /// of an explicit conversion operator to the expected type, per C++ 6690 /// [over.match.conv]p1 and [over.match.ref]p1. 6691 /// 6692 /// \param ConvType The return type of the conversion function. 6693 /// 6694 /// \param ToType The type we are converting to. 6695 /// 6696 /// \param AllowObjCPointerConversion Allow a conversion from one 6697 /// Objective-C pointer to another. 6698 /// 6699 /// \returns true if the conversion is allowable, false otherwise. 6700 static bool isAllowableExplicitConversion(Sema &S, 6701 QualType ConvType, QualType ToType, 6702 bool AllowObjCPointerConversion) { 6703 QualType ToNonRefType = ToType.getNonReferenceType(); 6704 6705 // Easy case: the types are the same. 6706 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6707 return true; 6708 6709 // Allow qualification conversions. 6710 bool ObjCLifetimeConversion; 6711 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6712 ObjCLifetimeConversion)) 6713 return true; 6714 6715 // If we're not allowed to consider Objective-C pointer conversions, 6716 // we're done. 6717 if (!AllowObjCPointerConversion) 6718 return false; 6719 6720 // Is this an Objective-C pointer conversion? 6721 bool IncompatibleObjC = false; 6722 QualType ConvertedType; 6723 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6724 IncompatibleObjC); 6725 } 6726 6727 /// AddConversionCandidate - Add a C++ conversion function as a 6728 /// candidate in the candidate set (C++ [over.match.conv], 6729 /// C++ [over.match.copy]). From is the expression we're converting from, 6730 /// and ToType is the type that we're eventually trying to convert to 6731 /// (which may or may not be the same type as the type that the 6732 /// conversion function produces). 6733 void 6734 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6735 DeclAccessPair FoundDecl, 6736 CXXRecordDecl *ActingContext, 6737 Expr *From, QualType ToType, 6738 OverloadCandidateSet& CandidateSet, 6739 bool AllowObjCConversionOnExplicit) { 6740 assert(!Conversion->getDescribedFunctionTemplate() && 6741 "Conversion function templates use AddTemplateConversionCandidate"); 6742 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6743 if (!CandidateSet.isNewCandidate(Conversion)) 6744 return; 6745 6746 // If the conversion function has an undeduced return type, trigger its 6747 // deduction now. 6748 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6749 if (DeduceReturnType(Conversion, From->getExprLoc())) 6750 return; 6751 ConvType = Conversion->getConversionType().getNonReferenceType(); 6752 } 6753 6754 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6755 // operator is only a candidate if its return type is the target type or 6756 // can be converted to the target type with a qualification conversion. 6757 if (Conversion->isExplicit() && 6758 !isAllowableExplicitConversion(*this, ConvType, ToType, 6759 AllowObjCConversionOnExplicit)) 6760 return; 6761 6762 // Overload resolution is always an unevaluated context. 6763 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6764 6765 // Add this candidate 6766 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6767 Candidate.FoundDecl = FoundDecl; 6768 Candidate.Function = Conversion; 6769 Candidate.IsSurrogate = false; 6770 Candidate.IgnoreObjectArgument = false; 6771 Candidate.FinalConversion.setAsIdentityConversion(); 6772 Candidate.FinalConversion.setFromType(ConvType); 6773 Candidate.FinalConversion.setAllToTypes(ToType); 6774 Candidate.Viable = true; 6775 Candidate.ExplicitCallArguments = 1; 6776 6777 // C++ [over.match.funcs]p4: 6778 // For conversion functions, the function is considered to be a member of 6779 // the class of the implicit implied object argument for the purpose of 6780 // defining the type of the implicit object parameter. 6781 // 6782 // Determine the implicit conversion sequence for the implicit 6783 // object parameter. 6784 QualType ImplicitParamType = From->getType(); 6785 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6786 ImplicitParamType = FromPtrType->getPointeeType(); 6787 CXXRecordDecl *ConversionContext 6788 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6789 6790 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6791 *this, CandidateSet.getLocation(), From->getType(), 6792 From->Classify(Context), Conversion, ConversionContext); 6793 6794 if (Candidate.Conversions[0].isBad()) { 6795 Candidate.Viable = false; 6796 Candidate.FailureKind = ovl_fail_bad_conversion; 6797 return; 6798 } 6799 6800 // We won't go through a user-defined type conversion function to convert a 6801 // derived to base as such conversions are given Conversion Rank. They only 6802 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6803 QualType FromCanon 6804 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6805 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6806 if (FromCanon == ToCanon || 6807 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6808 Candidate.Viable = false; 6809 Candidate.FailureKind = ovl_fail_trivial_conversion; 6810 return; 6811 } 6812 6813 // To determine what the conversion from the result of calling the 6814 // conversion function to the type we're eventually trying to 6815 // convert to (ToType), we need to synthesize a call to the 6816 // conversion function and attempt copy initialization from it. This 6817 // makes sure that we get the right semantics with respect to 6818 // lvalues/rvalues and the type. Fortunately, we can allocate this 6819 // call on the stack and we don't need its arguments to be 6820 // well-formed. 6821 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6822 VK_LValue, From->getLocStart()); 6823 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6824 Context.getPointerType(Conversion->getType()), 6825 CK_FunctionToPointerDecay, 6826 &ConversionRef, VK_RValue); 6827 6828 QualType ConversionType = Conversion->getConversionType(); 6829 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6830 Candidate.Viable = false; 6831 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6832 return; 6833 } 6834 6835 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6836 6837 // Note that it is safe to allocate CallExpr on the stack here because 6838 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6839 // allocator). 6840 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6841 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6842 From->getLocStart()); 6843 ImplicitConversionSequence ICS = 6844 TryCopyInitialization(*this, &Call, ToType, 6845 /*SuppressUserConversions=*/true, 6846 /*InOverloadResolution=*/false, 6847 /*AllowObjCWritebackConversion=*/false); 6848 6849 switch (ICS.getKind()) { 6850 case ImplicitConversionSequence::StandardConversion: 6851 Candidate.FinalConversion = ICS.Standard; 6852 6853 // C++ [over.ics.user]p3: 6854 // If the user-defined conversion is specified by a specialization of a 6855 // conversion function template, the second standard conversion sequence 6856 // shall have exact match rank. 6857 if (Conversion->getPrimaryTemplate() && 6858 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6859 Candidate.Viable = false; 6860 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6861 return; 6862 } 6863 6864 // C++0x [dcl.init.ref]p5: 6865 // In the second case, if the reference is an rvalue reference and 6866 // the second standard conversion sequence of the user-defined 6867 // conversion sequence includes an lvalue-to-rvalue conversion, the 6868 // program is ill-formed. 6869 if (ToType->isRValueReferenceType() && 6870 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6871 Candidate.Viable = false; 6872 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6873 return; 6874 } 6875 break; 6876 6877 case ImplicitConversionSequence::BadConversion: 6878 Candidate.Viable = false; 6879 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6880 return; 6881 6882 default: 6883 llvm_unreachable( 6884 "Can only end up with a standard conversion sequence or failure"); 6885 } 6886 6887 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6888 Candidate.Viable = false; 6889 Candidate.FailureKind = ovl_fail_enable_if; 6890 Candidate.DeductionFailure.Data = FailedAttr; 6891 return; 6892 } 6893 } 6894 6895 /// \brief Adds a conversion function template specialization 6896 /// candidate to the overload set, using template argument deduction 6897 /// to deduce the template arguments of the conversion function 6898 /// template from the type that we are converting to (C++ 6899 /// [temp.deduct.conv]). 6900 void 6901 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6902 DeclAccessPair FoundDecl, 6903 CXXRecordDecl *ActingDC, 6904 Expr *From, QualType ToType, 6905 OverloadCandidateSet &CandidateSet, 6906 bool AllowObjCConversionOnExplicit) { 6907 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6908 "Only conversion function templates permitted here"); 6909 6910 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6911 return; 6912 6913 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6914 CXXConversionDecl *Specialization = nullptr; 6915 if (TemplateDeductionResult Result 6916 = DeduceTemplateArguments(FunctionTemplate, ToType, 6917 Specialization, Info)) { 6918 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6919 Candidate.FoundDecl = FoundDecl; 6920 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6921 Candidate.Viable = false; 6922 Candidate.FailureKind = ovl_fail_bad_deduction; 6923 Candidate.IsSurrogate = false; 6924 Candidate.IgnoreObjectArgument = false; 6925 Candidate.ExplicitCallArguments = 1; 6926 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6927 Info); 6928 return; 6929 } 6930 6931 // Add the conversion function template specialization produced by 6932 // template argument deduction as a candidate. 6933 assert(Specialization && "Missing function template specialization?"); 6934 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6935 CandidateSet, AllowObjCConversionOnExplicit); 6936 } 6937 6938 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6939 /// converts the given @c Object to a function pointer via the 6940 /// conversion function @c Conversion, and then attempts to call it 6941 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6942 /// the type of function that we'll eventually be calling. 6943 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6944 DeclAccessPair FoundDecl, 6945 CXXRecordDecl *ActingContext, 6946 const FunctionProtoType *Proto, 6947 Expr *Object, 6948 ArrayRef<Expr *> Args, 6949 OverloadCandidateSet& CandidateSet) { 6950 if (!CandidateSet.isNewCandidate(Conversion)) 6951 return; 6952 6953 // Overload resolution is always an unevaluated context. 6954 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6955 6956 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6957 Candidate.FoundDecl = FoundDecl; 6958 Candidate.Function = nullptr; 6959 Candidate.Surrogate = Conversion; 6960 Candidate.Viable = true; 6961 Candidate.IsSurrogate = true; 6962 Candidate.IgnoreObjectArgument = false; 6963 Candidate.ExplicitCallArguments = Args.size(); 6964 6965 // Determine the implicit conversion sequence for the implicit 6966 // object parameter. 6967 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6968 *this, CandidateSet.getLocation(), Object->getType(), 6969 Object->Classify(Context), Conversion, ActingContext); 6970 if (ObjectInit.isBad()) { 6971 Candidate.Viable = false; 6972 Candidate.FailureKind = ovl_fail_bad_conversion; 6973 Candidate.Conversions[0] = ObjectInit; 6974 return; 6975 } 6976 6977 // The first conversion is actually a user-defined conversion whose 6978 // first conversion is ObjectInit's standard conversion (which is 6979 // effectively a reference binding). Record it as such. 6980 Candidate.Conversions[0].setUserDefined(); 6981 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6982 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6983 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6984 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6985 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6986 Candidate.Conversions[0].UserDefined.After 6987 = Candidate.Conversions[0].UserDefined.Before; 6988 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6989 6990 // Find the 6991 unsigned NumParams = Proto->getNumParams(); 6992 6993 // (C++ 13.3.2p2): A candidate function having fewer than m 6994 // parameters is viable only if it has an ellipsis in its parameter 6995 // list (8.3.5). 6996 if (Args.size() > NumParams && !Proto->isVariadic()) { 6997 Candidate.Viable = false; 6998 Candidate.FailureKind = ovl_fail_too_many_arguments; 6999 return; 7000 } 7001 7002 // Function types don't have any default arguments, so just check if 7003 // we have enough arguments. 7004 if (Args.size() < NumParams) { 7005 // Not enough arguments. 7006 Candidate.Viable = false; 7007 Candidate.FailureKind = ovl_fail_too_few_arguments; 7008 return; 7009 } 7010 7011 // Determine the implicit conversion sequences for each of the 7012 // arguments. 7013 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7014 if (ArgIdx < NumParams) { 7015 // (C++ 13.3.2p3): for F to be a viable function, there shall 7016 // exist for each argument an implicit conversion sequence 7017 // (13.3.3.1) that converts that argument to the corresponding 7018 // parameter of F. 7019 QualType ParamType = Proto->getParamType(ArgIdx); 7020 Candidate.Conversions[ArgIdx + 1] 7021 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7022 /*SuppressUserConversions=*/false, 7023 /*InOverloadResolution=*/false, 7024 /*AllowObjCWritebackConversion=*/ 7025 getLangOpts().ObjCAutoRefCount); 7026 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7027 Candidate.Viable = false; 7028 Candidate.FailureKind = ovl_fail_bad_conversion; 7029 return; 7030 } 7031 } else { 7032 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7033 // argument for which there is no corresponding parameter is 7034 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7035 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7036 } 7037 } 7038 7039 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7040 Candidate.Viable = false; 7041 Candidate.FailureKind = ovl_fail_enable_if; 7042 Candidate.DeductionFailure.Data = FailedAttr; 7043 return; 7044 } 7045 } 7046 7047 /// \brief Add overload candidates for overloaded operators that are 7048 /// member functions. 7049 /// 7050 /// Add the overloaded operator candidates that are member functions 7051 /// for the operator Op that was used in an operator expression such 7052 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7053 /// CandidateSet will store the added overload candidates. (C++ 7054 /// [over.match.oper]). 7055 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7056 SourceLocation OpLoc, 7057 ArrayRef<Expr *> Args, 7058 OverloadCandidateSet& CandidateSet, 7059 SourceRange OpRange) { 7060 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7061 7062 // C++ [over.match.oper]p3: 7063 // For a unary operator @ with an operand of a type whose 7064 // cv-unqualified version is T1, and for a binary operator @ with 7065 // a left operand of a type whose cv-unqualified version is T1 and 7066 // a right operand of a type whose cv-unqualified version is T2, 7067 // three sets of candidate functions, designated member 7068 // candidates, non-member candidates and built-in candidates, are 7069 // constructed as follows: 7070 QualType T1 = Args[0]->getType(); 7071 7072 // -- If T1 is a complete class type or a class currently being 7073 // defined, the set of member candidates is the result of the 7074 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7075 // the set of member candidates is empty. 7076 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7077 // Complete the type if it can be completed. 7078 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7079 return; 7080 // If the type is neither complete nor being defined, bail out now. 7081 if (!T1Rec->getDecl()->getDefinition()) 7082 return; 7083 7084 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7085 LookupQualifiedName(Operators, T1Rec->getDecl()); 7086 Operators.suppressDiagnostics(); 7087 7088 for (LookupResult::iterator Oper = Operators.begin(), 7089 OperEnd = Operators.end(); 7090 Oper != OperEnd; 7091 ++Oper) 7092 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7093 Args[0]->Classify(Context), Args.slice(1), 7094 CandidateSet, /*SuppressUserConversions=*/false); 7095 } 7096 } 7097 7098 /// AddBuiltinCandidate - Add a candidate for a built-in 7099 /// operator. ResultTy and ParamTys are the result and parameter types 7100 /// of the built-in candidate, respectively. Args and NumArgs are the 7101 /// arguments being passed to the candidate. IsAssignmentOperator 7102 /// should be true when this built-in candidate is an assignment 7103 /// operator. NumContextualBoolArguments is the number of arguments 7104 /// (at the beginning of the argument list) that will be contextually 7105 /// converted to bool. 7106 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 7107 ArrayRef<Expr *> Args, 7108 OverloadCandidateSet& CandidateSet, 7109 bool IsAssignmentOperator, 7110 unsigned NumContextualBoolArguments) { 7111 // Overload resolution is always an unevaluated context. 7112 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 7113 7114 // Add this candidate 7115 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7116 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7117 Candidate.Function = nullptr; 7118 Candidate.IsSurrogate = false; 7119 Candidate.IgnoreObjectArgument = false; 7120 Candidate.BuiltinTypes.ResultTy = ResultTy; 7121 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7122 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 7123 7124 // Determine the implicit conversion sequences for each of the 7125 // arguments. 7126 Candidate.Viable = true; 7127 Candidate.ExplicitCallArguments = Args.size(); 7128 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7129 // C++ [over.match.oper]p4: 7130 // For the built-in assignment operators, conversions of the 7131 // left operand are restricted as follows: 7132 // -- no temporaries are introduced to hold the left operand, and 7133 // -- no user-defined conversions are applied to the left 7134 // operand to achieve a type match with the left-most 7135 // parameter of a built-in candidate. 7136 // 7137 // We block these conversions by turning off user-defined 7138 // conversions, since that is the only way that initialization of 7139 // a reference to a non-class type can occur from something that 7140 // is not of the same type. 7141 if (ArgIdx < NumContextualBoolArguments) { 7142 assert(ParamTys[ArgIdx] == Context.BoolTy && 7143 "Contextual conversion to bool requires bool type"); 7144 Candidate.Conversions[ArgIdx] 7145 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7146 } else { 7147 Candidate.Conversions[ArgIdx] 7148 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7149 ArgIdx == 0 && IsAssignmentOperator, 7150 /*InOverloadResolution=*/false, 7151 /*AllowObjCWritebackConversion=*/ 7152 getLangOpts().ObjCAutoRefCount); 7153 } 7154 if (Candidate.Conversions[ArgIdx].isBad()) { 7155 Candidate.Viable = false; 7156 Candidate.FailureKind = ovl_fail_bad_conversion; 7157 break; 7158 } 7159 } 7160 } 7161 7162 namespace { 7163 7164 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7165 /// candidate operator functions for built-in operators (C++ 7166 /// [over.built]). The types are separated into pointer types and 7167 /// enumeration types. 7168 class BuiltinCandidateTypeSet { 7169 /// TypeSet - A set of types. 7170 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7171 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7172 7173 /// PointerTypes - The set of pointer types that will be used in the 7174 /// built-in candidates. 7175 TypeSet PointerTypes; 7176 7177 /// MemberPointerTypes - The set of member pointer types that will be 7178 /// used in the built-in candidates. 7179 TypeSet MemberPointerTypes; 7180 7181 /// EnumerationTypes - The set of enumeration types that will be 7182 /// used in the built-in candidates. 7183 TypeSet EnumerationTypes; 7184 7185 /// \brief The set of vector types that will be used in the built-in 7186 /// candidates. 7187 TypeSet VectorTypes; 7188 7189 /// \brief A flag indicating non-record types are viable candidates 7190 bool HasNonRecordTypes; 7191 7192 /// \brief A flag indicating whether either arithmetic or enumeration types 7193 /// were present in the candidate set. 7194 bool HasArithmeticOrEnumeralTypes; 7195 7196 /// \brief A flag indicating whether the nullptr type was present in the 7197 /// candidate set. 7198 bool HasNullPtrType; 7199 7200 /// Sema - The semantic analysis instance where we are building the 7201 /// candidate type set. 7202 Sema &SemaRef; 7203 7204 /// Context - The AST context in which we will build the type sets. 7205 ASTContext &Context; 7206 7207 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7208 const Qualifiers &VisibleQuals); 7209 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7210 7211 public: 7212 /// iterator - Iterates through the types that are part of the set. 7213 typedef TypeSet::iterator iterator; 7214 7215 BuiltinCandidateTypeSet(Sema &SemaRef) 7216 : HasNonRecordTypes(false), 7217 HasArithmeticOrEnumeralTypes(false), 7218 HasNullPtrType(false), 7219 SemaRef(SemaRef), 7220 Context(SemaRef.Context) { } 7221 7222 void AddTypesConvertedFrom(QualType Ty, 7223 SourceLocation Loc, 7224 bool AllowUserConversions, 7225 bool AllowExplicitConversions, 7226 const Qualifiers &VisibleTypeConversionsQuals); 7227 7228 /// pointer_begin - First pointer type found; 7229 iterator pointer_begin() { return PointerTypes.begin(); } 7230 7231 /// pointer_end - Past the last pointer type found; 7232 iterator pointer_end() { return PointerTypes.end(); } 7233 7234 /// member_pointer_begin - First member pointer type found; 7235 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7236 7237 /// member_pointer_end - Past the last member pointer type found; 7238 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7239 7240 /// enumeration_begin - First enumeration type found; 7241 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7242 7243 /// enumeration_end - Past the last enumeration type found; 7244 iterator enumeration_end() { return EnumerationTypes.end(); } 7245 7246 iterator vector_begin() { return VectorTypes.begin(); } 7247 iterator vector_end() { return VectorTypes.end(); } 7248 7249 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7250 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7251 bool hasNullPtrType() const { return HasNullPtrType; } 7252 }; 7253 7254 } // end anonymous namespace 7255 7256 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7257 /// the set of pointer types along with any more-qualified variants of 7258 /// that type. For example, if @p Ty is "int const *", this routine 7259 /// will add "int const *", "int const volatile *", "int const 7260 /// restrict *", and "int const volatile restrict *" to the set of 7261 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7262 /// false otherwise. 7263 /// 7264 /// FIXME: what to do about extended qualifiers? 7265 bool 7266 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7267 const Qualifiers &VisibleQuals) { 7268 7269 // Insert this type. 7270 if (!PointerTypes.insert(Ty)) 7271 return false; 7272 7273 QualType PointeeTy; 7274 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7275 bool buildObjCPtr = false; 7276 if (!PointerTy) { 7277 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7278 PointeeTy = PTy->getPointeeType(); 7279 buildObjCPtr = true; 7280 } else { 7281 PointeeTy = PointerTy->getPointeeType(); 7282 } 7283 7284 // Don't add qualified variants of arrays. For one, they're not allowed 7285 // (the qualifier would sink to the element type), and for another, the 7286 // only overload situation where it matters is subscript or pointer +- int, 7287 // and those shouldn't have qualifier variants anyway. 7288 if (PointeeTy->isArrayType()) 7289 return true; 7290 7291 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7292 bool hasVolatile = VisibleQuals.hasVolatile(); 7293 bool hasRestrict = VisibleQuals.hasRestrict(); 7294 7295 // Iterate through all strict supersets of BaseCVR. 7296 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7297 if ((CVR | BaseCVR) != CVR) continue; 7298 // Skip over volatile if no volatile found anywhere in the types. 7299 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7300 7301 // Skip over restrict if no restrict found anywhere in the types, or if 7302 // the type cannot be restrict-qualified. 7303 if ((CVR & Qualifiers::Restrict) && 7304 (!hasRestrict || 7305 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7306 continue; 7307 7308 // Build qualified pointee type. 7309 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7310 7311 // Build qualified pointer type. 7312 QualType QPointerTy; 7313 if (!buildObjCPtr) 7314 QPointerTy = Context.getPointerType(QPointeeTy); 7315 else 7316 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7317 7318 // Insert qualified pointer type. 7319 PointerTypes.insert(QPointerTy); 7320 } 7321 7322 return true; 7323 } 7324 7325 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7326 /// to the set of pointer types along with any more-qualified variants of 7327 /// that type. For example, if @p Ty is "int const *", this routine 7328 /// will add "int const *", "int const volatile *", "int const 7329 /// restrict *", and "int const volatile restrict *" to the set of 7330 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7331 /// false otherwise. 7332 /// 7333 /// FIXME: what to do about extended qualifiers? 7334 bool 7335 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7336 QualType Ty) { 7337 // Insert this type. 7338 if (!MemberPointerTypes.insert(Ty)) 7339 return false; 7340 7341 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7342 assert(PointerTy && "type was not a member pointer type!"); 7343 7344 QualType PointeeTy = PointerTy->getPointeeType(); 7345 // Don't add qualified variants of arrays. For one, they're not allowed 7346 // (the qualifier would sink to the element type), and for another, the 7347 // only overload situation where it matters is subscript or pointer +- int, 7348 // and those shouldn't have qualifier variants anyway. 7349 if (PointeeTy->isArrayType()) 7350 return true; 7351 const Type *ClassTy = PointerTy->getClass(); 7352 7353 // Iterate through all strict supersets of the pointee type's CVR 7354 // qualifiers. 7355 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7356 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7357 if ((CVR | BaseCVR) != CVR) continue; 7358 7359 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7360 MemberPointerTypes.insert( 7361 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7362 } 7363 7364 return true; 7365 } 7366 7367 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7368 /// Ty can be implicit converted to the given set of @p Types. We're 7369 /// primarily interested in pointer types and enumeration types. We also 7370 /// take member pointer types, for the conditional operator. 7371 /// AllowUserConversions is true if we should look at the conversion 7372 /// functions of a class type, and AllowExplicitConversions if we 7373 /// should also include the explicit conversion functions of a class 7374 /// type. 7375 void 7376 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7377 SourceLocation Loc, 7378 bool AllowUserConversions, 7379 bool AllowExplicitConversions, 7380 const Qualifiers &VisibleQuals) { 7381 // Only deal with canonical types. 7382 Ty = Context.getCanonicalType(Ty); 7383 7384 // Look through reference types; they aren't part of the type of an 7385 // expression for the purposes of conversions. 7386 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7387 Ty = RefTy->getPointeeType(); 7388 7389 // If we're dealing with an array type, decay to the pointer. 7390 if (Ty->isArrayType()) 7391 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7392 7393 // Otherwise, we don't care about qualifiers on the type. 7394 Ty = Ty.getLocalUnqualifiedType(); 7395 7396 // Flag if we ever add a non-record type. 7397 const RecordType *TyRec = Ty->getAs<RecordType>(); 7398 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7399 7400 // Flag if we encounter an arithmetic type. 7401 HasArithmeticOrEnumeralTypes = 7402 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7403 7404 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7405 PointerTypes.insert(Ty); 7406 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7407 // Insert our type, and its more-qualified variants, into the set 7408 // of types. 7409 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7410 return; 7411 } else if (Ty->isMemberPointerType()) { 7412 // Member pointers are far easier, since the pointee can't be converted. 7413 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7414 return; 7415 } else if (Ty->isEnumeralType()) { 7416 HasArithmeticOrEnumeralTypes = true; 7417 EnumerationTypes.insert(Ty); 7418 } else if (Ty->isVectorType()) { 7419 // We treat vector types as arithmetic types in many contexts as an 7420 // extension. 7421 HasArithmeticOrEnumeralTypes = true; 7422 VectorTypes.insert(Ty); 7423 } else if (Ty->isNullPtrType()) { 7424 HasNullPtrType = true; 7425 } else if (AllowUserConversions && TyRec) { 7426 // No conversion functions in incomplete types. 7427 if (!SemaRef.isCompleteType(Loc, Ty)) 7428 return; 7429 7430 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7431 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7432 if (isa<UsingShadowDecl>(D)) 7433 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7434 7435 // Skip conversion function templates; they don't tell us anything 7436 // about which builtin types we can convert to. 7437 if (isa<FunctionTemplateDecl>(D)) 7438 continue; 7439 7440 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7441 if (AllowExplicitConversions || !Conv->isExplicit()) { 7442 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7443 VisibleQuals); 7444 } 7445 } 7446 } 7447 } 7448 7449 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7450 /// the volatile- and non-volatile-qualified assignment operators for the 7451 /// given type to the candidate set. 7452 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7453 QualType T, 7454 ArrayRef<Expr *> Args, 7455 OverloadCandidateSet &CandidateSet) { 7456 QualType ParamTypes[2]; 7457 7458 // T& operator=(T&, T) 7459 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7460 ParamTypes[1] = T; 7461 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7462 /*IsAssignmentOperator=*/true); 7463 7464 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7465 // volatile T& operator=(volatile T&, T) 7466 ParamTypes[0] 7467 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7468 ParamTypes[1] = T; 7469 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7470 /*IsAssignmentOperator=*/true); 7471 } 7472 } 7473 7474 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7475 /// if any, found in visible type conversion functions found in ArgExpr's type. 7476 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7477 Qualifiers VRQuals; 7478 const RecordType *TyRec; 7479 if (const MemberPointerType *RHSMPType = 7480 ArgExpr->getType()->getAs<MemberPointerType>()) 7481 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7482 else 7483 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7484 if (!TyRec) { 7485 // Just to be safe, assume the worst case. 7486 VRQuals.addVolatile(); 7487 VRQuals.addRestrict(); 7488 return VRQuals; 7489 } 7490 7491 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7492 if (!ClassDecl->hasDefinition()) 7493 return VRQuals; 7494 7495 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7496 if (isa<UsingShadowDecl>(D)) 7497 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7498 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7499 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7500 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7501 CanTy = ResTypeRef->getPointeeType(); 7502 // Need to go down the pointer/mempointer chain and add qualifiers 7503 // as see them. 7504 bool done = false; 7505 while (!done) { 7506 if (CanTy.isRestrictQualified()) 7507 VRQuals.addRestrict(); 7508 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7509 CanTy = ResTypePtr->getPointeeType(); 7510 else if (const MemberPointerType *ResTypeMPtr = 7511 CanTy->getAs<MemberPointerType>()) 7512 CanTy = ResTypeMPtr->getPointeeType(); 7513 else 7514 done = true; 7515 if (CanTy.isVolatileQualified()) 7516 VRQuals.addVolatile(); 7517 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7518 return VRQuals; 7519 } 7520 } 7521 } 7522 return VRQuals; 7523 } 7524 7525 namespace { 7526 7527 /// \brief Helper class to manage the addition of builtin operator overload 7528 /// candidates. It provides shared state and utility methods used throughout 7529 /// the process, as well as a helper method to add each group of builtin 7530 /// operator overloads from the standard to a candidate set. 7531 class BuiltinOperatorOverloadBuilder { 7532 // Common instance state available to all overload candidate addition methods. 7533 Sema &S; 7534 ArrayRef<Expr *> Args; 7535 Qualifiers VisibleTypeConversionsQuals; 7536 bool HasArithmeticOrEnumeralCandidateType; 7537 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7538 OverloadCandidateSet &CandidateSet; 7539 7540 // Define some constants used to index and iterate over the arithemetic types 7541 // provided via the getArithmeticType() method below. 7542 // The "promoted arithmetic types" are the arithmetic 7543 // types are that preserved by promotion (C++ [over.built]p2). 7544 static const unsigned FirstIntegralType = 4; 7545 static const unsigned LastIntegralType = 21; 7546 static const unsigned FirstPromotedIntegralType = 4, 7547 LastPromotedIntegralType = 12; 7548 static const unsigned FirstPromotedArithmeticType = 0, 7549 LastPromotedArithmeticType = 12; 7550 static const unsigned NumArithmeticTypes = 21; 7551 7552 /// \brief Get the canonical type for a given arithmetic type index. 7553 CanQualType getArithmeticType(unsigned index) { 7554 assert(index < NumArithmeticTypes); 7555 static CanQualType ASTContext::* const 7556 ArithmeticTypes[NumArithmeticTypes] = { 7557 // Start of promoted types. 7558 &ASTContext::FloatTy, 7559 &ASTContext::DoubleTy, 7560 &ASTContext::LongDoubleTy, 7561 &ASTContext::Float128Ty, 7562 7563 // Start of integral types. 7564 &ASTContext::IntTy, 7565 &ASTContext::LongTy, 7566 &ASTContext::LongLongTy, 7567 &ASTContext::Int128Ty, 7568 &ASTContext::UnsignedIntTy, 7569 &ASTContext::UnsignedLongTy, 7570 &ASTContext::UnsignedLongLongTy, 7571 &ASTContext::UnsignedInt128Ty, 7572 // End of promoted types. 7573 7574 &ASTContext::BoolTy, 7575 &ASTContext::CharTy, 7576 &ASTContext::WCharTy, 7577 &ASTContext::Char16Ty, 7578 &ASTContext::Char32Ty, 7579 &ASTContext::SignedCharTy, 7580 &ASTContext::ShortTy, 7581 &ASTContext::UnsignedCharTy, 7582 &ASTContext::UnsignedShortTy, 7583 // End of integral types. 7584 // FIXME: What about complex? What about half? 7585 }; 7586 return S.Context.*ArithmeticTypes[index]; 7587 } 7588 7589 /// \brief Gets the canonical type resulting from the usual arithemetic 7590 /// converions for the given arithmetic types. 7591 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7592 // Accelerator table for performing the usual arithmetic conversions. 7593 // The rules are basically: 7594 // - if either is floating-point, use the wider floating-point 7595 // - if same signedness, use the higher rank 7596 // - if same size, use unsigned of the higher rank 7597 // - use the larger type 7598 // These rules, together with the axiom that higher ranks are 7599 // never smaller, are sufficient to precompute all of these results 7600 // *except* when dealing with signed types of higher rank. 7601 // (we could precompute SLL x UI for all known platforms, but it's 7602 // better not to make any assumptions). 7603 // We assume that int128 has a higher rank than long long on all platforms. 7604 enum PromotedType : int8_t { 7605 Dep=-1, 7606 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7607 }; 7608 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7609 [LastPromotedArithmeticType] = { 7610 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7611 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7612 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7613 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7614 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7615 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7616 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7617 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7618 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7619 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7620 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7621 }; 7622 7623 assert(L < LastPromotedArithmeticType); 7624 assert(R < LastPromotedArithmeticType); 7625 int Idx = ConversionsTable[L][R]; 7626 7627 // Fast path: the table gives us a concrete answer. 7628 if (Idx != Dep) return getArithmeticType(Idx); 7629 7630 // Slow path: we need to compare widths. 7631 // An invariant is that the signed type has higher rank. 7632 CanQualType LT = getArithmeticType(L), 7633 RT = getArithmeticType(R); 7634 unsigned LW = S.Context.getIntWidth(LT), 7635 RW = S.Context.getIntWidth(RT); 7636 7637 // If they're different widths, use the signed type. 7638 if (LW > RW) return LT; 7639 else if (LW < RW) return RT; 7640 7641 // Otherwise, use the unsigned type of the signed type's rank. 7642 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7643 assert(L == SLL || R == SLL); 7644 return S.Context.UnsignedLongLongTy; 7645 } 7646 7647 /// \brief Helper method to factor out the common pattern of adding overloads 7648 /// for '++' and '--' builtin operators. 7649 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7650 bool HasVolatile, 7651 bool HasRestrict) { 7652 QualType ParamTypes[2] = { 7653 S.Context.getLValueReferenceType(CandidateTy), 7654 S.Context.IntTy 7655 }; 7656 7657 // Non-volatile version. 7658 if (Args.size() == 1) 7659 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7660 else 7661 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7662 7663 // Use a heuristic to reduce number of builtin candidates in the set: 7664 // add volatile version only if there are conversions to a volatile type. 7665 if (HasVolatile) { 7666 ParamTypes[0] = 7667 S.Context.getLValueReferenceType( 7668 S.Context.getVolatileType(CandidateTy)); 7669 if (Args.size() == 1) 7670 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7671 else 7672 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7673 } 7674 7675 // Add restrict version only if there are conversions to a restrict type 7676 // and our candidate type is a non-restrict-qualified pointer. 7677 if (HasRestrict && CandidateTy->isAnyPointerType() && 7678 !CandidateTy.isRestrictQualified()) { 7679 ParamTypes[0] 7680 = S.Context.getLValueReferenceType( 7681 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7682 if (Args.size() == 1) 7683 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7684 else 7685 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7686 7687 if (HasVolatile) { 7688 ParamTypes[0] 7689 = S.Context.getLValueReferenceType( 7690 S.Context.getCVRQualifiedType(CandidateTy, 7691 (Qualifiers::Volatile | 7692 Qualifiers::Restrict))); 7693 if (Args.size() == 1) 7694 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7695 else 7696 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7697 } 7698 } 7699 7700 } 7701 7702 public: 7703 BuiltinOperatorOverloadBuilder( 7704 Sema &S, ArrayRef<Expr *> Args, 7705 Qualifiers VisibleTypeConversionsQuals, 7706 bool HasArithmeticOrEnumeralCandidateType, 7707 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7708 OverloadCandidateSet &CandidateSet) 7709 : S(S), Args(Args), 7710 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7711 HasArithmeticOrEnumeralCandidateType( 7712 HasArithmeticOrEnumeralCandidateType), 7713 CandidateTypes(CandidateTypes), 7714 CandidateSet(CandidateSet) { 7715 // Validate some of our static helper constants in debug builds. 7716 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7717 "Invalid first promoted integral type"); 7718 assert(getArithmeticType(LastPromotedIntegralType - 1) 7719 == S.Context.UnsignedInt128Ty && 7720 "Invalid last promoted integral type"); 7721 assert(getArithmeticType(FirstPromotedArithmeticType) 7722 == S.Context.FloatTy && 7723 "Invalid first promoted arithmetic type"); 7724 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7725 == S.Context.UnsignedInt128Ty && 7726 "Invalid last promoted arithmetic type"); 7727 } 7728 7729 // C++ [over.built]p3: 7730 // 7731 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7732 // is either volatile or empty, there exist candidate operator 7733 // functions of the form 7734 // 7735 // VQ T& operator++(VQ T&); 7736 // T operator++(VQ T&, int); 7737 // 7738 // C++ [over.built]p4: 7739 // 7740 // For every pair (T, VQ), where T is an arithmetic type other 7741 // than bool, and VQ is either volatile or empty, there exist 7742 // candidate operator functions of the form 7743 // 7744 // VQ T& operator--(VQ T&); 7745 // T operator--(VQ T&, int); 7746 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7747 if (!HasArithmeticOrEnumeralCandidateType) 7748 return; 7749 7750 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7751 Arith < NumArithmeticTypes; ++Arith) { 7752 addPlusPlusMinusMinusStyleOverloads( 7753 getArithmeticType(Arith), 7754 VisibleTypeConversionsQuals.hasVolatile(), 7755 VisibleTypeConversionsQuals.hasRestrict()); 7756 } 7757 } 7758 7759 // C++ [over.built]p5: 7760 // 7761 // For every pair (T, VQ), where T is a cv-qualified or 7762 // cv-unqualified object type, and VQ is either volatile or 7763 // empty, there exist candidate operator functions of the form 7764 // 7765 // T*VQ& operator++(T*VQ&); 7766 // T*VQ& operator--(T*VQ&); 7767 // T* operator++(T*VQ&, int); 7768 // T* operator--(T*VQ&, int); 7769 void addPlusPlusMinusMinusPointerOverloads() { 7770 for (BuiltinCandidateTypeSet::iterator 7771 Ptr = CandidateTypes[0].pointer_begin(), 7772 PtrEnd = CandidateTypes[0].pointer_end(); 7773 Ptr != PtrEnd; ++Ptr) { 7774 // Skip pointer types that aren't pointers to object types. 7775 if (!(*Ptr)->getPointeeType()->isObjectType()) 7776 continue; 7777 7778 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7779 (!(*Ptr).isVolatileQualified() && 7780 VisibleTypeConversionsQuals.hasVolatile()), 7781 (!(*Ptr).isRestrictQualified() && 7782 VisibleTypeConversionsQuals.hasRestrict())); 7783 } 7784 } 7785 7786 // C++ [over.built]p6: 7787 // For every cv-qualified or cv-unqualified object type T, there 7788 // exist candidate operator functions of the form 7789 // 7790 // T& operator*(T*); 7791 // 7792 // C++ [over.built]p7: 7793 // For every function type T that does not have cv-qualifiers or a 7794 // ref-qualifier, there exist candidate operator functions of the form 7795 // T& operator*(T*); 7796 void addUnaryStarPointerOverloads() { 7797 for (BuiltinCandidateTypeSet::iterator 7798 Ptr = CandidateTypes[0].pointer_begin(), 7799 PtrEnd = CandidateTypes[0].pointer_end(); 7800 Ptr != PtrEnd; ++Ptr) { 7801 QualType ParamTy = *Ptr; 7802 QualType PointeeTy = ParamTy->getPointeeType(); 7803 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7804 continue; 7805 7806 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7807 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7808 continue; 7809 7810 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7811 &ParamTy, Args, CandidateSet); 7812 } 7813 } 7814 7815 // C++ [over.built]p9: 7816 // For every promoted arithmetic type T, there exist candidate 7817 // operator functions of the form 7818 // 7819 // T operator+(T); 7820 // T operator-(T); 7821 void addUnaryPlusOrMinusArithmeticOverloads() { 7822 if (!HasArithmeticOrEnumeralCandidateType) 7823 return; 7824 7825 for (unsigned Arith = FirstPromotedArithmeticType; 7826 Arith < LastPromotedArithmeticType; ++Arith) { 7827 QualType ArithTy = getArithmeticType(Arith); 7828 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7829 } 7830 7831 // Extension: We also add these operators for vector types. 7832 for (BuiltinCandidateTypeSet::iterator 7833 Vec = CandidateTypes[0].vector_begin(), 7834 VecEnd = CandidateTypes[0].vector_end(); 7835 Vec != VecEnd; ++Vec) { 7836 QualType VecTy = *Vec; 7837 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7838 } 7839 } 7840 7841 // C++ [over.built]p8: 7842 // For every type T, there exist candidate operator functions of 7843 // the form 7844 // 7845 // T* operator+(T*); 7846 void addUnaryPlusPointerOverloads() { 7847 for (BuiltinCandidateTypeSet::iterator 7848 Ptr = CandidateTypes[0].pointer_begin(), 7849 PtrEnd = CandidateTypes[0].pointer_end(); 7850 Ptr != PtrEnd; ++Ptr) { 7851 QualType ParamTy = *Ptr; 7852 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7853 } 7854 } 7855 7856 // C++ [over.built]p10: 7857 // For every promoted integral type T, there exist candidate 7858 // operator functions of the form 7859 // 7860 // T operator~(T); 7861 void addUnaryTildePromotedIntegralOverloads() { 7862 if (!HasArithmeticOrEnumeralCandidateType) 7863 return; 7864 7865 for (unsigned Int = FirstPromotedIntegralType; 7866 Int < LastPromotedIntegralType; ++Int) { 7867 QualType IntTy = getArithmeticType(Int); 7868 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7869 } 7870 7871 // Extension: We also add this operator for vector types. 7872 for (BuiltinCandidateTypeSet::iterator 7873 Vec = CandidateTypes[0].vector_begin(), 7874 VecEnd = CandidateTypes[0].vector_end(); 7875 Vec != VecEnd; ++Vec) { 7876 QualType VecTy = *Vec; 7877 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7878 } 7879 } 7880 7881 // C++ [over.match.oper]p16: 7882 // For every pointer to member type T or type std::nullptr_t, there 7883 // exist candidate operator functions of the form 7884 // 7885 // bool operator==(T,T); 7886 // bool operator!=(T,T); 7887 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 7888 /// Set of (canonical) types that we've already handled. 7889 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7890 7891 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7892 for (BuiltinCandidateTypeSet::iterator 7893 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7894 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7895 MemPtr != MemPtrEnd; 7896 ++MemPtr) { 7897 // Don't add the same builtin candidate twice. 7898 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7899 continue; 7900 7901 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7902 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7903 } 7904 7905 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7906 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7907 if (AddedTypes.insert(NullPtrTy).second) { 7908 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7909 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7910 CandidateSet); 7911 } 7912 } 7913 } 7914 } 7915 7916 // C++ [over.built]p15: 7917 // 7918 // For every T, where T is an enumeration type or a pointer type, 7919 // there exist candidate operator functions of the form 7920 // 7921 // bool operator<(T, T); 7922 // bool operator>(T, T); 7923 // bool operator<=(T, T); 7924 // bool operator>=(T, T); 7925 // bool operator==(T, T); 7926 // bool operator!=(T, T); 7927 void addRelationalPointerOrEnumeralOverloads() { 7928 // C++ [over.match.oper]p3: 7929 // [...]the built-in candidates include all of the candidate operator 7930 // functions defined in 13.6 that, compared to the given operator, [...] 7931 // do not have the same parameter-type-list as any non-template non-member 7932 // candidate. 7933 // 7934 // Note that in practice, this only affects enumeration types because there 7935 // aren't any built-in candidates of record type, and a user-defined operator 7936 // must have an operand of record or enumeration type. Also, the only other 7937 // overloaded operator with enumeration arguments, operator=, 7938 // cannot be overloaded for enumeration types, so this is the only place 7939 // where we must suppress candidates like this. 7940 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7941 UserDefinedBinaryOperators; 7942 7943 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7944 if (CandidateTypes[ArgIdx].enumeration_begin() != 7945 CandidateTypes[ArgIdx].enumeration_end()) { 7946 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7947 CEnd = CandidateSet.end(); 7948 C != CEnd; ++C) { 7949 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7950 continue; 7951 7952 if (C->Function->isFunctionTemplateSpecialization()) 7953 continue; 7954 7955 QualType FirstParamType = 7956 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7957 QualType SecondParamType = 7958 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7959 7960 // Skip if either parameter isn't of enumeral type. 7961 if (!FirstParamType->isEnumeralType() || 7962 !SecondParamType->isEnumeralType()) 7963 continue; 7964 7965 // Add this operator to the set of known user-defined operators. 7966 UserDefinedBinaryOperators.insert( 7967 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7968 S.Context.getCanonicalType(SecondParamType))); 7969 } 7970 } 7971 } 7972 7973 /// Set of (canonical) types that we've already handled. 7974 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7975 7976 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7977 for (BuiltinCandidateTypeSet::iterator 7978 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7979 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7980 Ptr != PtrEnd; ++Ptr) { 7981 // Don't add the same builtin candidate twice. 7982 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7983 continue; 7984 7985 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7986 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7987 } 7988 for (BuiltinCandidateTypeSet::iterator 7989 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7990 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7991 Enum != EnumEnd; ++Enum) { 7992 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7993 7994 // Don't add the same builtin candidate twice, or if a user defined 7995 // candidate exists. 7996 if (!AddedTypes.insert(CanonType).second || 7997 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7998 CanonType))) 7999 continue; 8000 8001 QualType ParamTypes[2] = { *Enum, *Enum }; 8002 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 8003 } 8004 } 8005 } 8006 8007 // C++ [over.built]p13: 8008 // 8009 // For every cv-qualified or cv-unqualified object type T 8010 // there exist candidate operator functions of the form 8011 // 8012 // T* operator+(T*, ptrdiff_t); 8013 // T& operator[](T*, ptrdiff_t); [BELOW] 8014 // T* operator-(T*, ptrdiff_t); 8015 // T* operator+(ptrdiff_t, T*); 8016 // T& operator[](ptrdiff_t, T*); [BELOW] 8017 // 8018 // C++ [over.built]p14: 8019 // 8020 // For every T, where T is a pointer to object type, there 8021 // exist candidate operator functions of the form 8022 // 8023 // ptrdiff_t operator-(T, T); 8024 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8025 /// Set of (canonical) types that we've already handled. 8026 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8027 8028 for (int Arg = 0; Arg < 2; ++Arg) { 8029 QualType AsymmetricParamTypes[2] = { 8030 S.Context.getPointerDiffType(), 8031 S.Context.getPointerDiffType(), 8032 }; 8033 for (BuiltinCandidateTypeSet::iterator 8034 Ptr = CandidateTypes[Arg].pointer_begin(), 8035 PtrEnd = CandidateTypes[Arg].pointer_end(); 8036 Ptr != PtrEnd; ++Ptr) { 8037 QualType PointeeTy = (*Ptr)->getPointeeType(); 8038 if (!PointeeTy->isObjectType()) 8039 continue; 8040 8041 AsymmetricParamTypes[Arg] = *Ptr; 8042 if (Arg == 0 || Op == OO_Plus) { 8043 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8044 // T* operator+(ptrdiff_t, T*); 8045 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 8046 } 8047 if (Op == OO_Minus) { 8048 // ptrdiff_t operator-(T, T); 8049 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8050 continue; 8051 8052 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8053 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 8054 Args, CandidateSet); 8055 } 8056 } 8057 } 8058 } 8059 8060 // C++ [over.built]p12: 8061 // 8062 // For every pair of promoted arithmetic types L and R, there 8063 // exist candidate operator functions of the form 8064 // 8065 // LR operator*(L, R); 8066 // LR operator/(L, R); 8067 // LR operator+(L, R); 8068 // LR operator-(L, R); 8069 // bool operator<(L, R); 8070 // bool operator>(L, R); 8071 // bool operator<=(L, R); 8072 // bool operator>=(L, R); 8073 // bool operator==(L, R); 8074 // bool operator!=(L, R); 8075 // 8076 // where LR is the result of the usual arithmetic conversions 8077 // between types L and R. 8078 // 8079 // C++ [over.built]p24: 8080 // 8081 // For every pair of promoted arithmetic types L and R, there exist 8082 // candidate operator functions of the form 8083 // 8084 // LR operator?(bool, L, R); 8085 // 8086 // where LR is the result of the usual arithmetic conversions 8087 // between types L and R. 8088 // Our candidates ignore the first parameter. 8089 void addGenericBinaryArithmeticOverloads(bool isComparison) { 8090 if (!HasArithmeticOrEnumeralCandidateType) 8091 return; 8092 8093 for (unsigned Left = FirstPromotedArithmeticType; 8094 Left < LastPromotedArithmeticType; ++Left) { 8095 for (unsigned Right = FirstPromotedArithmeticType; 8096 Right < LastPromotedArithmeticType; ++Right) { 8097 QualType LandR[2] = { getArithmeticType(Left), 8098 getArithmeticType(Right) }; 8099 QualType Result = 8100 isComparison ? S.Context.BoolTy 8101 : getUsualArithmeticConversions(Left, Right); 8102 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 8103 } 8104 } 8105 8106 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8107 // conditional operator for vector types. 8108 for (BuiltinCandidateTypeSet::iterator 8109 Vec1 = CandidateTypes[0].vector_begin(), 8110 Vec1End = CandidateTypes[0].vector_end(); 8111 Vec1 != Vec1End; ++Vec1) { 8112 for (BuiltinCandidateTypeSet::iterator 8113 Vec2 = CandidateTypes[1].vector_begin(), 8114 Vec2End = CandidateTypes[1].vector_end(); 8115 Vec2 != Vec2End; ++Vec2) { 8116 QualType LandR[2] = { *Vec1, *Vec2 }; 8117 QualType Result = S.Context.BoolTy; 8118 if (!isComparison) { 8119 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 8120 Result = *Vec1; 8121 else 8122 Result = *Vec2; 8123 } 8124 8125 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 8126 } 8127 } 8128 } 8129 8130 // C++ [over.built]p17: 8131 // 8132 // For every pair of promoted integral types L and R, there 8133 // exist candidate operator functions of the form 8134 // 8135 // LR operator%(L, R); 8136 // LR operator&(L, R); 8137 // LR operator^(L, R); 8138 // LR operator|(L, R); 8139 // L operator<<(L, R); 8140 // L operator>>(L, R); 8141 // 8142 // where LR is the result of the usual arithmetic conversions 8143 // between types L and R. 8144 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8145 if (!HasArithmeticOrEnumeralCandidateType) 8146 return; 8147 8148 for (unsigned Left = FirstPromotedIntegralType; 8149 Left < LastPromotedIntegralType; ++Left) { 8150 for (unsigned Right = FirstPromotedIntegralType; 8151 Right < LastPromotedIntegralType; ++Right) { 8152 QualType LandR[2] = { getArithmeticType(Left), 8153 getArithmeticType(Right) }; 8154 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 8155 ? LandR[0] 8156 : getUsualArithmeticConversions(Left, Right); 8157 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 8158 } 8159 } 8160 } 8161 8162 // C++ [over.built]p20: 8163 // 8164 // For every pair (T, VQ), where T is an enumeration or 8165 // pointer to member type and VQ is either volatile or 8166 // empty, there exist candidate operator functions of the form 8167 // 8168 // VQ T& operator=(VQ T&, T); 8169 void addAssignmentMemberPointerOrEnumeralOverloads() { 8170 /// Set of (canonical) types that we've already handled. 8171 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8172 8173 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8174 for (BuiltinCandidateTypeSet::iterator 8175 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8176 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8177 Enum != EnumEnd; ++Enum) { 8178 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8179 continue; 8180 8181 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8182 } 8183 8184 for (BuiltinCandidateTypeSet::iterator 8185 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8186 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8187 MemPtr != MemPtrEnd; ++MemPtr) { 8188 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8189 continue; 8190 8191 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8192 } 8193 } 8194 } 8195 8196 // C++ [over.built]p19: 8197 // 8198 // For every pair (T, VQ), where T is any type and VQ is either 8199 // volatile or empty, there exist candidate operator functions 8200 // of the form 8201 // 8202 // T*VQ& operator=(T*VQ&, T*); 8203 // 8204 // C++ [over.built]p21: 8205 // 8206 // For every pair (T, VQ), where T is a cv-qualified or 8207 // cv-unqualified object type and VQ is either volatile or 8208 // empty, there exist candidate operator functions of the form 8209 // 8210 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8211 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8212 void addAssignmentPointerOverloads(bool isEqualOp) { 8213 /// Set of (canonical) types that we've already handled. 8214 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8215 8216 for (BuiltinCandidateTypeSet::iterator 8217 Ptr = CandidateTypes[0].pointer_begin(), 8218 PtrEnd = CandidateTypes[0].pointer_end(); 8219 Ptr != PtrEnd; ++Ptr) { 8220 // If this is operator=, keep track of the builtin candidates we added. 8221 if (isEqualOp) 8222 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8223 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8224 continue; 8225 8226 // non-volatile version 8227 QualType ParamTypes[2] = { 8228 S.Context.getLValueReferenceType(*Ptr), 8229 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8230 }; 8231 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8232 /*IsAssigmentOperator=*/ isEqualOp); 8233 8234 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8235 VisibleTypeConversionsQuals.hasVolatile(); 8236 if (NeedVolatile) { 8237 // volatile version 8238 ParamTypes[0] = 8239 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8240 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8241 /*IsAssigmentOperator=*/isEqualOp); 8242 } 8243 8244 if (!(*Ptr).isRestrictQualified() && 8245 VisibleTypeConversionsQuals.hasRestrict()) { 8246 // restrict version 8247 ParamTypes[0] 8248 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8249 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8250 /*IsAssigmentOperator=*/isEqualOp); 8251 8252 if (NeedVolatile) { 8253 // volatile restrict version 8254 ParamTypes[0] 8255 = S.Context.getLValueReferenceType( 8256 S.Context.getCVRQualifiedType(*Ptr, 8257 (Qualifiers::Volatile | 8258 Qualifiers::Restrict))); 8259 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8260 /*IsAssigmentOperator=*/isEqualOp); 8261 } 8262 } 8263 } 8264 8265 if (isEqualOp) { 8266 for (BuiltinCandidateTypeSet::iterator 8267 Ptr = CandidateTypes[1].pointer_begin(), 8268 PtrEnd = CandidateTypes[1].pointer_end(); 8269 Ptr != PtrEnd; ++Ptr) { 8270 // Make sure we don't add the same candidate twice. 8271 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8272 continue; 8273 8274 QualType ParamTypes[2] = { 8275 S.Context.getLValueReferenceType(*Ptr), 8276 *Ptr, 8277 }; 8278 8279 // non-volatile version 8280 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8281 /*IsAssigmentOperator=*/true); 8282 8283 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8284 VisibleTypeConversionsQuals.hasVolatile(); 8285 if (NeedVolatile) { 8286 // volatile version 8287 ParamTypes[0] = 8288 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8289 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8290 /*IsAssigmentOperator=*/true); 8291 } 8292 8293 if (!(*Ptr).isRestrictQualified() && 8294 VisibleTypeConversionsQuals.hasRestrict()) { 8295 // restrict version 8296 ParamTypes[0] 8297 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8298 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8299 /*IsAssigmentOperator=*/true); 8300 8301 if (NeedVolatile) { 8302 // volatile restrict version 8303 ParamTypes[0] 8304 = S.Context.getLValueReferenceType( 8305 S.Context.getCVRQualifiedType(*Ptr, 8306 (Qualifiers::Volatile | 8307 Qualifiers::Restrict))); 8308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8309 /*IsAssigmentOperator=*/true); 8310 } 8311 } 8312 } 8313 } 8314 } 8315 8316 // C++ [over.built]p18: 8317 // 8318 // For every triple (L, VQ, R), where L is an arithmetic type, 8319 // VQ is either volatile or empty, and R is a promoted 8320 // arithmetic type, there exist candidate operator functions of 8321 // the form 8322 // 8323 // VQ L& operator=(VQ L&, R); 8324 // VQ L& operator*=(VQ L&, R); 8325 // VQ L& operator/=(VQ L&, R); 8326 // VQ L& operator+=(VQ L&, R); 8327 // VQ L& operator-=(VQ L&, R); 8328 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8329 if (!HasArithmeticOrEnumeralCandidateType) 8330 return; 8331 8332 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8333 for (unsigned Right = FirstPromotedArithmeticType; 8334 Right < LastPromotedArithmeticType; ++Right) { 8335 QualType ParamTypes[2]; 8336 ParamTypes[1] = getArithmeticType(Right); 8337 8338 // Add this built-in operator as a candidate (VQ is empty). 8339 ParamTypes[0] = 8340 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8341 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8342 /*IsAssigmentOperator=*/isEqualOp); 8343 8344 // Add this built-in operator as a candidate (VQ is 'volatile'). 8345 if (VisibleTypeConversionsQuals.hasVolatile()) { 8346 ParamTypes[0] = 8347 S.Context.getVolatileType(getArithmeticType(Left)); 8348 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8349 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8350 /*IsAssigmentOperator=*/isEqualOp); 8351 } 8352 } 8353 } 8354 8355 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8356 for (BuiltinCandidateTypeSet::iterator 8357 Vec1 = CandidateTypes[0].vector_begin(), 8358 Vec1End = CandidateTypes[0].vector_end(); 8359 Vec1 != Vec1End; ++Vec1) { 8360 for (BuiltinCandidateTypeSet::iterator 8361 Vec2 = CandidateTypes[1].vector_begin(), 8362 Vec2End = CandidateTypes[1].vector_end(); 8363 Vec2 != Vec2End; ++Vec2) { 8364 QualType ParamTypes[2]; 8365 ParamTypes[1] = *Vec2; 8366 // Add this built-in operator as a candidate (VQ is empty). 8367 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8368 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8369 /*IsAssigmentOperator=*/isEqualOp); 8370 8371 // Add this built-in operator as a candidate (VQ is 'volatile'). 8372 if (VisibleTypeConversionsQuals.hasVolatile()) { 8373 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8374 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8375 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8376 /*IsAssigmentOperator=*/isEqualOp); 8377 } 8378 } 8379 } 8380 } 8381 8382 // C++ [over.built]p22: 8383 // 8384 // For every triple (L, VQ, R), where L is an integral type, VQ 8385 // is either volatile or empty, and R is a promoted integral 8386 // type, there exist candidate operator functions of the form 8387 // 8388 // VQ L& operator%=(VQ L&, R); 8389 // VQ L& operator<<=(VQ L&, R); 8390 // VQ L& operator>>=(VQ L&, R); 8391 // VQ L& operator&=(VQ L&, R); 8392 // VQ L& operator^=(VQ L&, R); 8393 // VQ L& operator|=(VQ L&, R); 8394 void addAssignmentIntegralOverloads() { 8395 if (!HasArithmeticOrEnumeralCandidateType) 8396 return; 8397 8398 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8399 for (unsigned Right = FirstPromotedIntegralType; 8400 Right < LastPromotedIntegralType; ++Right) { 8401 QualType ParamTypes[2]; 8402 ParamTypes[1] = getArithmeticType(Right); 8403 8404 // Add this built-in operator as a candidate (VQ is empty). 8405 ParamTypes[0] = 8406 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8407 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8408 if (VisibleTypeConversionsQuals.hasVolatile()) { 8409 // Add this built-in operator as a candidate (VQ is 'volatile'). 8410 ParamTypes[0] = getArithmeticType(Left); 8411 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8412 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8413 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8414 } 8415 } 8416 } 8417 } 8418 8419 // C++ [over.operator]p23: 8420 // 8421 // There also exist candidate operator functions of the form 8422 // 8423 // bool operator!(bool); 8424 // bool operator&&(bool, bool); 8425 // bool operator||(bool, bool); 8426 void addExclaimOverload() { 8427 QualType ParamTy = S.Context.BoolTy; 8428 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8429 /*IsAssignmentOperator=*/false, 8430 /*NumContextualBoolArguments=*/1); 8431 } 8432 void addAmpAmpOrPipePipeOverload() { 8433 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8434 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8435 /*IsAssignmentOperator=*/false, 8436 /*NumContextualBoolArguments=*/2); 8437 } 8438 8439 // C++ [over.built]p13: 8440 // 8441 // For every cv-qualified or cv-unqualified object type T there 8442 // exist candidate operator functions of the form 8443 // 8444 // T* operator+(T*, ptrdiff_t); [ABOVE] 8445 // T& operator[](T*, ptrdiff_t); 8446 // T* operator-(T*, ptrdiff_t); [ABOVE] 8447 // T* operator+(ptrdiff_t, T*); [ABOVE] 8448 // T& operator[](ptrdiff_t, T*); 8449 void addSubscriptOverloads() { 8450 for (BuiltinCandidateTypeSet::iterator 8451 Ptr = CandidateTypes[0].pointer_begin(), 8452 PtrEnd = CandidateTypes[0].pointer_end(); 8453 Ptr != PtrEnd; ++Ptr) { 8454 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8455 QualType PointeeType = (*Ptr)->getPointeeType(); 8456 if (!PointeeType->isObjectType()) 8457 continue; 8458 8459 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8460 8461 // T& operator[](T*, ptrdiff_t) 8462 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8463 } 8464 8465 for (BuiltinCandidateTypeSet::iterator 8466 Ptr = CandidateTypes[1].pointer_begin(), 8467 PtrEnd = CandidateTypes[1].pointer_end(); 8468 Ptr != PtrEnd; ++Ptr) { 8469 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8470 QualType PointeeType = (*Ptr)->getPointeeType(); 8471 if (!PointeeType->isObjectType()) 8472 continue; 8473 8474 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8475 8476 // T& operator[](ptrdiff_t, T*) 8477 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8478 } 8479 } 8480 8481 // C++ [over.built]p11: 8482 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8483 // C1 is the same type as C2 or is a derived class of C2, T is an object 8484 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8485 // there exist candidate operator functions of the form 8486 // 8487 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8488 // 8489 // where CV12 is the union of CV1 and CV2. 8490 void addArrowStarOverloads() { 8491 for (BuiltinCandidateTypeSet::iterator 8492 Ptr = CandidateTypes[0].pointer_begin(), 8493 PtrEnd = CandidateTypes[0].pointer_end(); 8494 Ptr != PtrEnd; ++Ptr) { 8495 QualType C1Ty = (*Ptr); 8496 QualType C1; 8497 QualifierCollector Q1; 8498 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8499 if (!isa<RecordType>(C1)) 8500 continue; 8501 // heuristic to reduce number of builtin candidates in the set. 8502 // Add volatile/restrict version only if there are conversions to a 8503 // volatile/restrict type. 8504 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8505 continue; 8506 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8507 continue; 8508 for (BuiltinCandidateTypeSet::iterator 8509 MemPtr = CandidateTypes[1].member_pointer_begin(), 8510 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8511 MemPtr != MemPtrEnd; ++MemPtr) { 8512 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8513 QualType C2 = QualType(mptr->getClass(), 0); 8514 C2 = C2.getUnqualifiedType(); 8515 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8516 break; 8517 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8518 // build CV12 T& 8519 QualType T = mptr->getPointeeType(); 8520 if (!VisibleTypeConversionsQuals.hasVolatile() && 8521 T.isVolatileQualified()) 8522 continue; 8523 if (!VisibleTypeConversionsQuals.hasRestrict() && 8524 T.isRestrictQualified()) 8525 continue; 8526 T = Q1.apply(S.Context, T); 8527 QualType ResultTy = S.Context.getLValueReferenceType(T); 8528 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8529 } 8530 } 8531 } 8532 8533 // Note that we don't consider the first argument, since it has been 8534 // contextually converted to bool long ago. The candidates below are 8535 // therefore added as binary. 8536 // 8537 // C++ [over.built]p25: 8538 // For every type T, where T is a pointer, pointer-to-member, or scoped 8539 // enumeration type, there exist candidate operator functions of the form 8540 // 8541 // T operator?(bool, T, T); 8542 // 8543 void addConditionalOperatorOverloads() { 8544 /// Set of (canonical) types that we've already handled. 8545 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8546 8547 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8548 for (BuiltinCandidateTypeSet::iterator 8549 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8550 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8551 Ptr != PtrEnd; ++Ptr) { 8552 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8553 continue; 8554 8555 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8556 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8557 } 8558 8559 for (BuiltinCandidateTypeSet::iterator 8560 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8561 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8562 MemPtr != MemPtrEnd; ++MemPtr) { 8563 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8564 continue; 8565 8566 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8567 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8568 } 8569 8570 if (S.getLangOpts().CPlusPlus11) { 8571 for (BuiltinCandidateTypeSet::iterator 8572 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8573 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8574 Enum != EnumEnd; ++Enum) { 8575 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8576 continue; 8577 8578 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8579 continue; 8580 8581 QualType ParamTypes[2] = { *Enum, *Enum }; 8582 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8583 } 8584 } 8585 } 8586 } 8587 }; 8588 8589 } // end anonymous namespace 8590 8591 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8592 /// operator overloads to the candidate set (C++ [over.built]), based 8593 /// on the operator @p Op and the arguments given. For example, if the 8594 /// operator is a binary '+', this routine might add "int 8595 /// operator+(int, int)" to cover integer addition. 8596 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8597 SourceLocation OpLoc, 8598 ArrayRef<Expr *> Args, 8599 OverloadCandidateSet &CandidateSet) { 8600 // Find all of the types that the arguments can convert to, but only 8601 // if the operator we're looking at has built-in operator candidates 8602 // that make use of these types. Also record whether we encounter non-record 8603 // candidate types or either arithmetic or enumeral candidate types. 8604 Qualifiers VisibleTypeConversionsQuals; 8605 VisibleTypeConversionsQuals.addConst(); 8606 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8607 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8608 8609 bool HasNonRecordCandidateType = false; 8610 bool HasArithmeticOrEnumeralCandidateType = false; 8611 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8612 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8613 CandidateTypes.emplace_back(*this); 8614 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8615 OpLoc, 8616 true, 8617 (Op == OO_Exclaim || 8618 Op == OO_AmpAmp || 8619 Op == OO_PipePipe), 8620 VisibleTypeConversionsQuals); 8621 HasNonRecordCandidateType = HasNonRecordCandidateType || 8622 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8623 HasArithmeticOrEnumeralCandidateType = 8624 HasArithmeticOrEnumeralCandidateType || 8625 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8626 } 8627 8628 // Exit early when no non-record types have been added to the candidate set 8629 // for any of the arguments to the operator. 8630 // 8631 // We can't exit early for !, ||, or &&, since there we have always have 8632 // 'bool' overloads. 8633 if (!HasNonRecordCandidateType && 8634 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8635 return; 8636 8637 // Setup an object to manage the common state for building overloads. 8638 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8639 VisibleTypeConversionsQuals, 8640 HasArithmeticOrEnumeralCandidateType, 8641 CandidateTypes, CandidateSet); 8642 8643 // Dispatch over the operation to add in only those overloads which apply. 8644 switch (Op) { 8645 case OO_None: 8646 case NUM_OVERLOADED_OPERATORS: 8647 llvm_unreachable("Expected an overloaded operator"); 8648 8649 case OO_New: 8650 case OO_Delete: 8651 case OO_Array_New: 8652 case OO_Array_Delete: 8653 case OO_Call: 8654 llvm_unreachable( 8655 "Special operators don't use AddBuiltinOperatorCandidates"); 8656 8657 case OO_Comma: 8658 case OO_Arrow: 8659 case OO_Coawait: 8660 // C++ [over.match.oper]p3: 8661 // -- For the operator ',', the unary operator '&', the 8662 // operator '->', or the operator 'co_await', the 8663 // built-in candidates set is empty. 8664 break; 8665 8666 case OO_Plus: // '+' is either unary or binary 8667 if (Args.size() == 1) 8668 OpBuilder.addUnaryPlusPointerOverloads(); 8669 // Fall through. 8670 8671 case OO_Minus: // '-' is either unary or binary 8672 if (Args.size() == 1) { 8673 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8674 } else { 8675 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8676 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8677 } 8678 break; 8679 8680 case OO_Star: // '*' is either unary or binary 8681 if (Args.size() == 1) 8682 OpBuilder.addUnaryStarPointerOverloads(); 8683 else 8684 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8685 break; 8686 8687 case OO_Slash: 8688 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8689 break; 8690 8691 case OO_PlusPlus: 8692 case OO_MinusMinus: 8693 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8694 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8695 break; 8696 8697 case OO_EqualEqual: 8698 case OO_ExclaimEqual: 8699 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8700 // Fall through. 8701 8702 case OO_Less: 8703 case OO_Greater: 8704 case OO_LessEqual: 8705 case OO_GreaterEqual: 8706 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8707 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8708 break; 8709 8710 case OO_Percent: 8711 case OO_Caret: 8712 case OO_Pipe: 8713 case OO_LessLess: 8714 case OO_GreaterGreater: 8715 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8716 break; 8717 8718 case OO_Amp: // '&' is either unary or binary 8719 if (Args.size() == 1) 8720 // C++ [over.match.oper]p3: 8721 // -- For the operator ',', the unary operator '&', or the 8722 // operator '->', the built-in candidates set is empty. 8723 break; 8724 8725 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8726 break; 8727 8728 case OO_Tilde: 8729 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8730 break; 8731 8732 case OO_Equal: 8733 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8734 // Fall through. 8735 8736 case OO_PlusEqual: 8737 case OO_MinusEqual: 8738 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8739 // Fall through. 8740 8741 case OO_StarEqual: 8742 case OO_SlashEqual: 8743 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8744 break; 8745 8746 case OO_PercentEqual: 8747 case OO_LessLessEqual: 8748 case OO_GreaterGreaterEqual: 8749 case OO_AmpEqual: 8750 case OO_CaretEqual: 8751 case OO_PipeEqual: 8752 OpBuilder.addAssignmentIntegralOverloads(); 8753 break; 8754 8755 case OO_Exclaim: 8756 OpBuilder.addExclaimOverload(); 8757 break; 8758 8759 case OO_AmpAmp: 8760 case OO_PipePipe: 8761 OpBuilder.addAmpAmpOrPipePipeOverload(); 8762 break; 8763 8764 case OO_Subscript: 8765 OpBuilder.addSubscriptOverloads(); 8766 break; 8767 8768 case OO_ArrowStar: 8769 OpBuilder.addArrowStarOverloads(); 8770 break; 8771 8772 case OO_Conditional: 8773 OpBuilder.addConditionalOperatorOverloads(); 8774 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8775 break; 8776 } 8777 } 8778 8779 /// \brief Add function candidates found via argument-dependent lookup 8780 /// to the set of overloading candidates. 8781 /// 8782 /// This routine performs argument-dependent name lookup based on the 8783 /// given function name (which may also be an operator name) and adds 8784 /// all of the overload candidates found by ADL to the overload 8785 /// candidate set (C++ [basic.lookup.argdep]). 8786 void 8787 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8788 SourceLocation Loc, 8789 ArrayRef<Expr *> Args, 8790 TemplateArgumentListInfo *ExplicitTemplateArgs, 8791 OverloadCandidateSet& CandidateSet, 8792 bool PartialOverloading) { 8793 ADLResult Fns; 8794 8795 // FIXME: This approach for uniquing ADL results (and removing 8796 // redundant candidates from the set) relies on pointer-equality, 8797 // which means we need to key off the canonical decl. However, 8798 // always going back to the canonical decl might not get us the 8799 // right set of default arguments. What default arguments are 8800 // we supposed to consider on ADL candidates, anyway? 8801 8802 // FIXME: Pass in the explicit template arguments? 8803 ArgumentDependentLookup(Name, Loc, Args, Fns); 8804 8805 // Erase all of the candidates we already knew about. 8806 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8807 CandEnd = CandidateSet.end(); 8808 Cand != CandEnd; ++Cand) 8809 if (Cand->Function) { 8810 Fns.erase(Cand->Function); 8811 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8812 Fns.erase(FunTmpl); 8813 } 8814 8815 // For each of the ADL candidates we found, add it to the overload 8816 // set. 8817 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8818 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8819 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8820 if (ExplicitTemplateArgs) 8821 continue; 8822 8823 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8824 PartialOverloading); 8825 } else 8826 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8827 FoundDecl, ExplicitTemplateArgs, 8828 Args, CandidateSet, PartialOverloading); 8829 } 8830 } 8831 8832 namespace { 8833 enum class Comparison { Equal, Better, Worse }; 8834 } 8835 8836 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8837 /// overload resolution. 8838 /// 8839 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8840 /// Cand1's first N enable_if attributes have precisely the same conditions as 8841 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8842 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8843 /// 8844 /// Note that you can have a pair of candidates such that Cand1's enable_if 8845 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8846 /// worse than Cand1's. 8847 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8848 const FunctionDecl *Cand2) { 8849 // Common case: One (or both) decls don't have enable_if attrs. 8850 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8851 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8852 if (!Cand1Attr || !Cand2Attr) { 8853 if (Cand1Attr == Cand2Attr) 8854 return Comparison::Equal; 8855 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8856 } 8857 8858 // FIXME: The next several lines are just 8859 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8860 // instead of reverse order which is how they're stored in the AST. 8861 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8862 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8863 8864 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8865 // has fewer enable_if attributes than Cand2. 8866 if (Cand1Attrs.size() < Cand2Attrs.size()) 8867 return Comparison::Worse; 8868 8869 auto Cand1I = Cand1Attrs.begin(); 8870 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8871 for (auto &Cand2A : Cand2Attrs) { 8872 Cand1ID.clear(); 8873 Cand2ID.clear(); 8874 8875 auto &Cand1A = *Cand1I++; 8876 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8877 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8878 if (Cand1ID != Cand2ID) 8879 return Comparison::Worse; 8880 } 8881 8882 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8883 } 8884 8885 /// isBetterOverloadCandidate - Determines whether the first overload 8886 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8887 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8888 const OverloadCandidate &Cand2, 8889 SourceLocation Loc, 8890 bool UserDefinedConversion) { 8891 // Define viable functions to be better candidates than non-viable 8892 // functions. 8893 if (!Cand2.Viable) 8894 return Cand1.Viable; 8895 else if (!Cand1.Viable) 8896 return false; 8897 8898 // C++ [over.match.best]p1: 8899 // 8900 // -- if F is a static member function, ICS1(F) is defined such 8901 // that ICS1(F) is neither better nor worse than ICS1(G) for 8902 // any function G, and, symmetrically, ICS1(G) is neither 8903 // better nor worse than ICS1(F). 8904 unsigned StartArg = 0; 8905 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8906 StartArg = 1; 8907 8908 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 8909 // We don't allow incompatible pointer conversions in C++. 8910 if (!S.getLangOpts().CPlusPlus) 8911 return ICS.isStandard() && 8912 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 8913 8914 // The only ill-formed conversion we allow in C++ is the string literal to 8915 // char* conversion, which is only considered ill-formed after C++11. 8916 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 8917 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 8918 }; 8919 8920 // Define functions that don't require ill-formed conversions for a given 8921 // argument to be better candidates than functions that do. 8922 unsigned NumArgs = Cand1.Conversions.size(); 8923 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 8924 bool HasBetterConversion = false; 8925 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8926 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 8927 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 8928 if (Cand1Bad != Cand2Bad) { 8929 if (Cand1Bad) 8930 return false; 8931 HasBetterConversion = true; 8932 } 8933 } 8934 8935 if (HasBetterConversion) 8936 return true; 8937 8938 // C++ [over.match.best]p1: 8939 // A viable function F1 is defined to be a better function than another 8940 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8941 // conversion sequence than ICSi(F2), and then... 8942 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8943 switch (CompareImplicitConversionSequences(S, Loc, 8944 Cand1.Conversions[ArgIdx], 8945 Cand2.Conversions[ArgIdx])) { 8946 case ImplicitConversionSequence::Better: 8947 // Cand1 has a better conversion sequence. 8948 HasBetterConversion = true; 8949 break; 8950 8951 case ImplicitConversionSequence::Worse: 8952 // Cand1 can't be better than Cand2. 8953 return false; 8954 8955 case ImplicitConversionSequence::Indistinguishable: 8956 // Do nothing. 8957 break; 8958 } 8959 } 8960 8961 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8962 // ICSj(F2), or, if not that, 8963 if (HasBetterConversion) 8964 return true; 8965 8966 // -- the context is an initialization by user-defined conversion 8967 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8968 // from the return type of F1 to the destination type (i.e., 8969 // the type of the entity being initialized) is a better 8970 // conversion sequence than the standard conversion sequence 8971 // from the return type of F2 to the destination type. 8972 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8973 isa<CXXConversionDecl>(Cand1.Function) && 8974 isa<CXXConversionDecl>(Cand2.Function)) { 8975 // First check whether we prefer one of the conversion functions over the 8976 // other. This only distinguishes the results in non-standard, extension 8977 // cases such as the conversion from a lambda closure type to a function 8978 // pointer or block. 8979 ImplicitConversionSequence::CompareKind Result = 8980 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8981 if (Result == ImplicitConversionSequence::Indistinguishable) 8982 Result = CompareStandardConversionSequences(S, Loc, 8983 Cand1.FinalConversion, 8984 Cand2.FinalConversion); 8985 8986 if (Result != ImplicitConversionSequence::Indistinguishable) 8987 return Result == ImplicitConversionSequence::Better; 8988 8989 // FIXME: Compare kind of reference binding if conversion functions 8990 // convert to a reference type used in direct reference binding, per 8991 // C++14 [over.match.best]p1 section 2 bullet 3. 8992 } 8993 8994 // -- F1 is a non-template function and F2 is a function template 8995 // specialization, or, if not that, 8996 bool Cand1IsSpecialization = Cand1.Function && 8997 Cand1.Function->getPrimaryTemplate(); 8998 bool Cand2IsSpecialization = Cand2.Function && 8999 Cand2.Function->getPrimaryTemplate(); 9000 if (Cand1IsSpecialization != Cand2IsSpecialization) 9001 return Cand2IsSpecialization; 9002 9003 // -- F1 and F2 are function template specializations, and the function 9004 // template for F1 is more specialized than the template for F2 9005 // according to the partial ordering rules described in 14.5.5.2, or, 9006 // if not that, 9007 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9008 if (FunctionTemplateDecl *BetterTemplate 9009 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9010 Cand2.Function->getPrimaryTemplate(), 9011 Loc, 9012 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9013 : TPOC_Call, 9014 Cand1.ExplicitCallArguments, 9015 Cand2.ExplicitCallArguments)) 9016 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9017 } 9018 9019 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9020 // A derived-class constructor beats an (inherited) base class constructor. 9021 bool Cand1IsInherited = 9022 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9023 bool Cand2IsInherited = 9024 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9025 if (Cand1IsInherited != Cand2IsInherited) 9026 return Cand2IsInherited; 9027 else if (Cand1IsInherited) { 9028 assert(Cand2IsInherited); 9029 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9030 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9031 if (Cand1Class->isDerivedFrom(Cand2Class)) 9032 return true; 9033 if (Cand2Class->isDerivedFrom(Cand1Class)) 9034 return false; 9035 // Inherited from sibling base classes: still ambiguous. 9036 } 9037 9038 // Check for enable_if value-based overload resolution. 9039 if (Cand1.Function && Cand2.Function) { 9040 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9041 if (Cmp != Comparison::Equal) 9042 return Cmp == Comparison::Better; 9043 } 9044 9045 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9046 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9047 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9048 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9049 } 9050 9051 bool HasPS1 = Cand1.Function != nullptr && 9052 functionHasPassObjectSizeParams(Cand1.Function); 9053 bool HasPS2 = Cand2.Function != nullptr && 9054 functionHasPassObjectSizeParams(Cand2.Function); 9055 return HasPS1 != HasPS2 && HasPS1; 9056 } 9057 9058 /// Determine whether two declarations are "equivalent" for the purposes of 9059 /// name lookup and overload resolution. This applies when the same internal/no 9060 /// linkage entity is defined by two modules (probably by textually including 9061 /// the same header). In such a case, we don't consider the declarations to 9062 /// declare the same entity, but we also don't want lookups with both 9063 /// declarations visible to be ambiguous in some cases (this happens when using 9064 /// a modularized libstdc++). 9065 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9066 const NamedDecl *B) { 9067 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9068 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9069 if (!VA || !VB) 9070 return false; 9071 9072 // The declarations must be declaring the same name as an internal linkage 9073 // entity in different modules. 9074 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9075 VB->getDeclContext()->getRedeclContext()) || 9076 getOwningModule(const_cast<ValueDecl *>(VA)) == 9077 getOwningModule(const_cast<ValueDecl *>(VB)) || 9078 VA->isExternallyVisible() || VB->isExternallyVisible()) 9079 return false; 9080 9081 // Check that the declarations appear to be equivalent. 9082 // 9083 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9084 // For constants and functions, we should check the initializer or body is 9085 // the same. For non-constant variables, we shouldn't allow it at all. 9086 if (Context.hasSameType(VA->getType(), VB->getType())) 9087 return true; 9088 9089 // Enum constants within unnamed enumerations will have different types, but 9090 // may still be similar enough to be interchangeable for our purposes. 9091 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9092 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9093 // Only handle anonymous enums. If the enumerations were named and 9094 // equivalent, they would have been merged to the same type. 9095 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9096 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9097 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9098 !Context.hasSameType(EnumA->getIntegerType(), 9099 EnumB->getIntegerType())) 9100 return false; 9101 // Allow this only if the value is the same for both enumerators. 9102 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9103 } 9104 } 9105 9106 // Nothing else is sufficiently similar. 9107 return false; 9108 } 9109 9110 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9111 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9112 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9113 9114 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9115 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9116 << !M << (M ? M->getFullModuleName() : ""); 9117 9118 for (auto *E : Equiv) { 9119 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9120 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9121 << !M << (M ? M->getFullModuleName() : ""); 9122 } 9123 } 9124 9125 /// \brief Computes the best viable function (C++ 13.3.3) 9126 /// within an overload candidate set. 9127 /// 9128 /// \param Loc The location of the function name (or operator symbol) for 9129 /// which overload resolution occurs. 9130 /// 9131 /// \param Best If overload resolution was successful or found a deleted 9132 /// function, \p Best points to the candidate function found. 9133 /// 9134 /// \returns The result of overload resolution. 9135 OverloadingResult 9136 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9137 iterator &Best, 9138 bool UserDefinedConversion) { 9139 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9140 std::transform(begin(), end(), std::back_inserter(Candidates), 9141 [](OverloadCandidate &Cand) { return &Cand; }); 9142 9143 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9144 // are accepted by both clang and NVCC. However, during a particular 9145 // compilation mode only one call variant is viable. We need to 9146 // exclude non-viable overload candidates from consideration based 9147 // only on their host/device attributes. Specifically, if one 9148 // candidate call is WrongSide and the other is SameSide, we ignore 9149 // the WrongSide candidate. 9150 if (S.getLangOpts().CUDA) { 9151 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9152 bool ContainsSameSideCandidate = 9153 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9154 return Cand->Function && 9155 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9156 Sema::CFP_SameSide; 9157 }); 9158 if (ContainsSameSideCandidate) { 9159 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9160 return Cand->Function && 9161 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9162 Sema::CFP_WrongSide; 9163 }; 9164 llvm::erase_if(Candidates, IsWrongSideCandidate); 9165 } 9166 } 9167 9168 // Find the best viable function. 9169 Best = end(); 9170 for (auto *Cand : Candidates) 9171 if (Cand->Viable) 9172 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 9173 UserDefinedConversion)) 9174 Best = Cand; 9175 9176 // If we didn't find any viable functions, abort. 9177 if (Best == end()) 9178 return OR_No_Viable_Function; 9179 9180 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9181 9182 // Make sure that this function is better than every other viable 9183 // function. If not, we have an ambiguity. 9184 for (auto *Cand : Candidates) { 9185 if (Cand->Viable && 9186 Cand != Best && 9187 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 9188 UserDefinedConversion)) { 9189 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9190 Cand->Function)) { 9191 EquivalentCands.push_back(Cand->Function); 9192 continue; 9193 } 9194 9195 Best = end(); 9196 return OR_Ambiguous; 9197 } 9198 } 9199 9200 // Best is the best viable function. 9201 if (Best->Function && 9202 (Best->Function->isDeleted() || 9203 S.isFunctionConsideredUnavailable(Best->Function))) 9204 return OR_Deleted; 9205 9206 if (!EquivalentCands.empty()) 9207 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9208 EquivalentCands); 9209 9210 return OR_Success; 9211 } 9212 9213 namespace { 9214 9215 enum OverloadCandidateKind { 9216 oc_function, 9217 oc_method, 9218 oc_constructor, 9219 oc_function_template, 9220 oc_method_template, 9221 oc_constructor_template, 9222 oc_implicit_default_constructor, 9223 oc_implicit_copy_constructor, 9224 oc_implicit_move_constructor, 9225 oc_implicit_copy_assignment, 9226 oc_implicit_move_assignment, 9227 oc_inherited_constructor, 9228 oc_inherited_constructor_template 9229 }; 9230 9231 static OverloadCandidateKind 9232 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9233 std::string &Description) { 9234 bool isTemplate = false; 9235 9236 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9237 isTemplate = true; 9238 Description = S.getTemplateArgumentBindingsText( 9239 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9240 } 9241 9242 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9243 if (!Ctor->isImplicit()) { 9244 if (isa<ConstructorUsingShadowDecl>(Found)) 9245 return isTemplate ? oc_inherited_constructor_template 9246 : oc_inherited_constructor; 9247 else 9248 return isTemplate ? oc_constructor_template : oc_constructor; 9249 } 9250 9251 if (Ctor->isDefaultConstructor()) 9252 return oc_implicit_default_constructor; 9253 9254 if (Ctor->isMoveConstructor()) 9255 return oc_implicit_move_constructor; 9256 9257 assert(Ctor->isCopyConstructor() && 9258 "unexpected sort of implicit constructor"); 9259 return oc_implicit_copy_constructor; 9260 } 9261 9262 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9263 // This actually gets spelled 'candidate function' for now, but 9264 // it doesn't hurt to split it out. 9265 if (!Meth->isImplicit()) 9266 return isTemplate ? oc_method_template : oc_method; 9267 9268 if (Meth->isMoveAssignmentOperator()) 9269 return oc_implicit_move_assignment; 9270 9271 if (Meth->isCopyAssignmentOperator()) 9272 return oc_implicit_copy_assignment; 9273 9274 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9275 return oc_method; 9276 } 9277 9278 return isTemplate ? oc_function_template : oc_function; 9279 } 9280 9281 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9282 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9283 // set. 9284 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9285 S.Diag(FoundDecl->getLocation(), 9286 diag::note_ovl_candidate_inherited_constructor) 9287 << Shadow->getNominatedBaseClass(); 9288 } 9289 9290 } // end anonymous namespace 9291 9292 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9293 const FunctionDecl *FD) { 9294 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9295 bool AlwaysTrue; 9296 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9297 return false; 9298 if (!AlwaysTrue) 9299 return false; 9300 } 9301 return true; 9302 } 9303 9304 /// \brief Returns true if we can take the address of the function. 9305 /// 9306 /// \param Complain - If true, we'll emit a diagnostic 9307 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9308 /// we in overload resolution? 9309 /// \param Loc - The location of the statement we're complaining about. Ignored 9310 /// if we're not complaining, or if we're in overload resolution. 9311 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9312 bool Complain, 9313 bool InOverloadResolution, 9314 SourceLocation Loc) { 9315 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9316 if (Complain) { 9317 if (InOverloadResolution) 9318 S.Diag(FD->getLocStart(), 9319 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9320 else 9321 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9322 } 9323 return false; 9324 } 9325 9326 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9327 return P->hasAttr<PassObjectSizeAttr>(); 9328 }); 9329 if (I == FD->param_end()) 9330 return true; 9331 9332 if (Complain) { 9333 // Add one to ParamNo because it's user-facing 9334 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9335 if (InOverloadResolution) 9336 S.Diag(FD->getLocation(), 9337 diag::note_ovl_candidate_has_pass_object_size_params) 9338 << ParamNo; 9339 else 9340 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9341 << FD << ParamNo; 9342 } 9343 return false; 9344 } 9345 9346 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9347 const FunctionDecl *FD) { 9348 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9349 /*InOverloadResolution=*/true, 9350 /*Loc=*/SourceLocation()); 9351 } 9352 9353 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9354 bool Complain, 9355 SourceLocation Loc) { 9356 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9357 /*InOverloadResolution=*/false, 9358 Loc); 9359 } 9360 9361 // Notes the location of an overload candidate. 9362 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9363 QualType DestType, bool TakingAddress) { 9364 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9365 return; 9366 9367 std::string FnDesc; 9368 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9369 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9370 << (unsigned) K << Fn << FnDesc; 9371 9372 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9373 Diag(Fn->getLocation(), PD); 9374 MaybeEmitInheritedConstructorNote(*this, Found); 9375 } 9376 9377 // Notes the location of all overload candidates designated through 9378 // OverloadedExpr 9379 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9380 bool TakingAddress) { 9381 assert(OverloadedExpr->getType() == Context.OverloadTy); 9382 9383 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9384 OverloadExpr *OvlExpr = Ovl.Expression; 9385 9386 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9387 IEnd = OvlExpr->decls_end(); 9388 I != IEnd; ++I) { 9389 if (FunctionTemplateDecl *FunTmpl = 9390 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9391 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9392 TakingAddress); 9393 } else if (FunctionDecl *Fun 9394 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9395 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9396 } 9397 } 9398 } 9399 9400 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9401 /// "lead" diagnostic; it will be given two arguments, the source and 9402 /// target types of the conversion. 9403 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9404 Sema &S, 9405 SourceLocation CaretLoc, 9406 const PartialDiagnostic &PDiag) const { 9407 S.Diag(CaretLoc, PDiag) 9408 << Ambiguous.getFromType() << Ambiguous.getToType(); 9409 // FIXME: The note limiting machinery is borrowed from 9410 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9411 // refactoring here. 9412 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9413 unsigned CandsShown = 0; 9414 AmbiguousConversionSequence::const_iterator I, E; 9415 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9416 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9417 break; 9418 ++CandsShown; 9419 S.NoteOverloadCandidate(I->first, I->second); 9420 } 9421 if (I != E) 9422 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9423 } 9424 9425 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9426 unsigned I, bool TakingCandidateAddress) { 9427 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9428 assert(Conv.isBad()); 9429 assert(Cand->Function && "for now, candidate must be a function"); 9430 FunctionDecl *Fn = Cand->Function; 9431 9432 // There's a conversion slot for the object argument if this is a 9433 // non-constructor method. Note that 'I' corresponds the 9434 // conversion-slot index. 9435 bool isObjectArgument = false; 9436 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9437 if (I == 0) 9438 isObjectArgument = true; 9439 else 9440 I--; 9441 } 9442 9443 std::string FnDesc; 9444 OverloadCandidateKind FnKind = 9445 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9446 9447 Expr *FromExpr = Conv.Bad.FromExpr; 9448 QualType FromTy = Conv.Bad.getFromType(); 9449 QualType ToTy = Conv.Bad.getToType(); 9450 9451 if (FromTy == S.Context.OverloadTy) { 9452 assert(FromExpr && "overload set argument came from implicit argument?"); 9453 Expr *E = FromExpr->IgnoreParens(); 9454 if (isa<UnaryOperator>(E)) 9455 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9456 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9457 9458 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9459 << (unsigned) FnKind << FnDesc 9460 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9461 << ToTy << Name << I+1; 9462 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9463 return; 9464 } 9465 9466 // Do some hand-waving analysis to see if the non-viability is due 9467 // to a qualifier mismatch. 9468 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9469 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9470 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9471 CToTy = RT->getPointeeType(); 9472 else { 9473 // TODO: detect and diagnose the full richness of const mismatches. 9474 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9475 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9476 CFromTy = FromPT->getPointeeType(); 9477 CToTy = ToPT->getPointeeType(); 9478 } 9479 } 9480 9481 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9482 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9483 Qualifiers FromQs = CFromTy.getQualifiers(); 9484 Qualifiers ToQs = CToTy.getQualifiers(); 9485 9486 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9487 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9488 << (unsigned) FnKind << FnDesc 9489 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9490 << FromTy 9491 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9492 << (unsigned) isObjectArgument << I+1; 9493 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9494 return; 9495 } 9496 9497 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9498 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9499 << (unsigned) FnKind << FnDesc 9500 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9501 << FromTy 9502 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9503 << (unsigned) isObjectArgument << I+1; 9504 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9505 return; 9506 } 9507 9508 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9509 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9510 << (unsigned) FnKind << FnDesc 9511 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9512 << FromTy 9513 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9514 << (unsigned) isObjectArgument << I+1; 9515 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9516 return; 9517 } 9518 9519 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9520 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9521 << (unsigned) FnKind << FnDesc 9522 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9523 << FromTy << FromQs.hasUnaligned() << I+1; 9524 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9525 return; 9526 } 9527 9528 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9529 assert(CVR && "unexpected qualifiers mismatch"); 9530 9531 if (isObjectArgument) { 9532 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9533 << (unsigned) FnKind << FnDesc 9534 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9535 << FromTy << (CVR - 1); 9536 } else { 9537 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9538 << (unsigned) FnKind << FnDesc 9539 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9540 << FromTy << (CVR - 1) << I+1; 9541 } 9542 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9543 return; 9544 } 9545 9546 // Special diagnostic for failure to convert an initializer list, since 9547 // telling the user that it has type void is not useful. 9548 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9549 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9550 << (unsigned) FnKind << FnDesc 9551 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9552 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9553 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9554 return; 9555 } 9556 9557 // Diagnose references or pointers to incomplete types differently, 9558 // since it's far from impossible that the incompleteness triggered 9559 // the failure. 9560 QualType TempFromTy = FromTy.getNonReferenceType(); 9561 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9562 TempFromTy = PTy->getPointeeType(); 9563 if (TempFromTy->isIncompleteType()) { 9564 // Emit the generic diagnostic and, optionally, add the hints to it. 9565 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9566 << (unsigned) FnKind << FnDesc 9567 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9568 << FromTy << ToTy << (unsigned) isObjectArgument << I+1 9569 << (unsigned) (Cand->Fix.Kind); 9570 9571 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9572 return; 9573 } 9574 9575 // Diagnose base -> derived pointer conversions. 9576 unsigned BaseToDerivedConversion = 0; 9577 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9578 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9579 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9580 FromPtrTy->getPointeeType()) && 9581 !FromPtrTy->getPointeeType()->isIncompleteType() && 9582 !ToPtrTy->getPointeeType()->isIncompleteType() && 9583 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9584 FromPtrTy->getPointeeType())) 9585 BaseToDerivedConversion = 1; 9586 } 9587 } else if (const ObjCObjectPointerType *FromPtrTy 9588 = FromTy->getAs<ObjCObjectPointerType>()) { 9589 if (const ObjCObjectPointerType *ToPtrTy 9590 = ToTy->getAs<ObjCObjectPointerType>()) 9591 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9592 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9593 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9594 FromPtrTy->getPointeeType()) && 9595 FromIface->isSuperClassOf(ToIface)) 9596 BaseToDerivedConversion = 2; 9597 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9598 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9599 !FromTy->isIncompleteType() && 9600 !ToRefTy->getPointeeType()->isIncompleteType() && 9601 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9602 BaseToDerivedConversion = 3; 9603 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9604 ToTy.getNonReferenceType().getCanonicalType() == 9605 FromTy.getNonReferenceType().getCanonicalType()) { 9606 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9607 << (unsigned) FnKind << FnDesc 9608 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9609 << (unsigned) isObjectArgument << I + 1; 9610 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9611 return; 9612 } 9613 } 9614 9615 if (BaseToDerivedConversion) { 9616 S.Diag(Fn->getLocation(), 9617 diag::note_ovl_candidate_bad_base_to_derived_conv) 9618 << (unsigned) FnKind << FnDesc 9619 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9620 << (BaseToDerivedConversion - 1) 9621 << FromTy << ToTy << I+1; 9622 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9623 return; 9624 } 9625 9626 if (isa<ObjCObjectPointerType>(CFromTy) && 9627 isa<PointerType>(CToTy)) { 9628 Qualifiers FromQs = CFromTy.getQualifiers(); 9629 Qualifiers ToQs = CToTy.getQualifiers(); 9630 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9631 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9632 << (unsigned) FnKind << FnDesc 9633 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9634 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9635 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9636 return; 9637 } 9638 } 9639 9640 if (TakingCandidateAddress && 9641 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9642 return; 9643 9644 // Emit the generic diagnostic and, optionally, add the hints to it. 9645 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9646 FDiag << (unsigned) FnKind << FnDesc 9647 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9648 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9649 << (unsigned) (Cand->Fix.Kind); 9650 9651 // If we can fix the conversion, suggest the FixIts. 9652 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9653 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9654 FDiag << *HI; 9655 S.Diag(Fn->getLocation(), FDiag); 9656 9657 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9658 } 9659 9660 /// Additional arity mismatch diagnosis specific to a function overload 9661 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9662 /// over a candidate in any candidate set. 9663 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9664 unsigned NumArgs) { 9665 FunctionDecl *Fn = Cand->Function; 9666 unsigned MinParams = Fn->getMinRequiredArguments(); 9667 9668 // With invalid overloaded operators, it's possible that we think we 9669 // have an arity mismatch when in fact it looks like we have the 9670 // right number of arguments, because only overloaded operators have 9671 // the weird behavior of overloading member and non-member functions. 9672 // Just don't report anything. 9673 if (Fn->isInvalidDecl() && 9674 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9675 return true; 9676 9677 if (NumArgs < MinParams) { 9678 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9679 (Cand->FailureKind == ovl_fail_bad_deduction && 9680 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9681 } else { 9682 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9683 (Cand->FailureKind == ovl_fail_bad_deduction && 9684 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9685 } 9686 9687 return false; 9688 } 9689 9690 /// General arity mismatch diagnosis over a candidate in a candidate set. 9691 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9692 unsigned NumFormalArgs) { 9693 assert(isa<FunctionDecl>(D) && 9694 "The templated declaration should at least be a function" 9695 " when diagnosing bad template argument deduction due to too many" 9696 " or too few arguments"); 9697 9698 FunctionDecl *Fn = cast<FunctionDecl>(D); 9699 9700 // TODO: treat calls to a missing default constructor as a special case 9701 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9702 unsigned MinParams = Fn->getMinRequiredArguments(); 9703 9704 // at least / at most / exactly 9705 unsigned mode, modeCount; 9706 if (NumFormalArgs < MinParams) { 9707 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9708 FnTy->isTemplateVariadic()) 9709 mode = 0; // "at least" 9710 else 9711 mode = 2; // "exactly" 9712 modeCount = MinParams; 9713 } else { 9714 if (MinParams != FnTy->getNumParams()) 9715 mode = 1; // "at most" 9716 else 9717 mode = 2; // "exactly" 9718 modeCount = FnTy->getNumParams(); 9719 } 9720 9721 std::string Description; 9722 OverloadCandidateKind FnKind = 9723 ClassifyOverloadCandidate(S, Found, Fn, Description); 9724 9725 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9726 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9727 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9728 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9729 else 9730 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9731 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9732 << mode << modeCount << NumFormalArgs; 9733 MaybeEmitInheritedConstructorNote(S, Found); 9734 } 9735 9736 /// Arity mismatch diagnosis specific to a function overload candidate. 9737 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9738 unsigned NumFormalArgs) { 9739 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9740 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9741 } 9742 9743 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9744 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9745 return TD; 9746 llvm_unreachable("Unsupported: Getting the described template declaration" 9747 " for bad deduction diagnosis"); 9748 } 9749 9750 /// Diagnose a failed template-argument deduction. 9751 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9752 DeductionFailureInfo &DeductionFailure, 9753 unsigned NumArgs, 9754 bool TakingCandidateAddress) { 9755 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9756 NamedDecl *ParamD; 9757 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9758 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9759 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9760 switch (DeductionFailure.Result) { 9761 case Sema::TDK_Success: 9762 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9763 9764 case Sema::TDK_Incomplete: { 9765 assert(ParamD && "no parameter found for incomplete deduction result"); 9766 S.Diag(Templated->getLocation(), 9767 diag::note_ovl_candidate_incomplete_deduction) 9768 << ParamD->getDeclName(); 9769 MaybeEmitInheritedConstructorNote(S, Found); 9770 return; 9771 } 9772 9773 case Sema::TDK_Underqualified: { 9774 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9775 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9776 9777 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9778 9779 // Param will have been canonicalized, but it should just be a 9780 // qualified version of ParamD, so move the qualifiers to that. 9781 QualifierCollector Qs; 9782 Qs.strip(Param); 9783 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9784 assert(S.Context.hasSameType(Param, NonCanonParam)); 9785 9786 // Arg has also been canonicalized, but there's nothing we can do 9787 // about that. It also doesn't matter as much, because it won't 9788 // have any template parameters in it (because deduction isn't 9789 // done on dependent types). 9790 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9791 9792 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9793 << ParamD->getDeclName() << Arg << NonCanonParam; 9794 MaybeEmitInheritedConstructorNote(S, Found); 9795 return; 9796 } 9797 9798 case Sema::TDK_Inconsistent: { 9799 assert(ParamD && "no parameter found for inconsistent deduction result"); 9800 int which = 0; 9801 if (isa<TemplateTypeParmDecl>(ParamD)) 9802 which = 0; 9803 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 9804 // Deduction might have failed because we deduced arguments of two 9805 // different types for a non-type template parameter. 9806 // FIXME: Use a different TDK value for this. 9807 QualType T1 = 9808 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 9809 QualType T2 = 9810 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 9811 if (!S.Context.hasSameType(T1, T2)) { 9812 S.Diag(Templated->getLocation(), 9813 diag::note_ovl_candidate_inconsistent_deduction_types) 9814 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 9815 << *DeductionFailure.getSecondArg() << T2; 9816 MaybeEmitInheritedConstructorNote(S, Found); 9817 return; 9818 } 9819 9820 which = 1; 9821 } else { 9822 which = 2; 9823 } 9824 9825 S.Diag(Templated->getLocation(), 9826 diag::note_ovl_candidate_inconsistent_deduction) 9827 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9828 << *DeductionFailure.getSecondArg(); 9829 MaybeEmitInheritedConstructorNote(S, Found); 9830 return; 9831 } 9832 9833 case Sema::TDK_InvalidExplicitArguments: 9834 assert(ParamD && "no parameter found for invalid explicit arguments"); 9835 if (ParamD->getDeclName()) 9836 S.Diag(Templated->getLocation(), 9837 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9838 << ParamD->getDeclName(); 9839 else { 9840 int index = 0; 9841 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9842 index = TTP->getIndex(); 9843 else if (NonTypeTemplateParmDecl *NTTP 9844 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9845 index = NTTP->getIndex(); 9846 else 9847 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9848 S.Diag(Templated->getLocation(), 9849 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9850 << (index + 1); 9851 } 9852 MaybeEmitInheritedConstructorNote(S, Found); 9853 return; 9854 9855 case Sema::TDK_TooManyArguments: 9856 case Sema::TDK_TooFewArguments: 9857 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 9858 return; 9859 9860 case Sema::TDK_InstantiationDepth: 9861 S.Diag(Templated->getLocation(), 9862 diag::note_ovl_candidate_instantiation_depth); 9863 MaybeEmitInheritedConstructorNote(S, Found); 9864 return; 9865 9866 case Sema::TDK_SubstitutionFailure: { 9867 // Format the template argument list into the argument string. 9868 SmallString<128> TemplateArgString; 9869 if (TemplateArgumentList *Args = 9870 DeductionFailure.getTemplateArgumentList()) { 9871 TemplateArgString = " "; 9872 TemplateArgString += S.getTemplateArgumentBindingsText( 9873 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9874 } 9875 9876 // If this candidate was disabled by enable_if, say so. 9877 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9878 if (PDiag && PDiag->second.getDiagID() == 9879 diag::err_typename_nested_not_found_enable_if) { 9880 // FIXME: Use the source range of the condition, and the fully-qualified 9881 // name of the enable_if template. These are both present in PDiag. 9882 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9883 << "'enable_if'" << TemplateArgString; 9884 return; 9885 } 9886 9887 // Format the SFINAE diagnostic into the argument string. 9888 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9889 // formatted message in another diagnostic. 9890 SmallString<128> SFINAEArgString; 9891 SourceRange R; 9892 if (PDiag) { 9893 SFINAEArgString = ": "; 9894 R = SourceRange(PDiag->first, PDiag->first); 9895 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9896 } 9897 9898 S.Diag(Templated->getLocation(), 9899 diag::note_ovl_candidate_substitution_failure) 9900 << TemplateArgString << SFINAEArgString << R; 9901 MaybeEmitInheritedConstructorNote(S, Found); 9902 return; 9903 } 9904 9905 case Sema::TDK_DeducedMismatch: 9906 case Sema::TDK_DeducedMismatchNested: { 9907 // Format the template argument list into the argument string. 9908 SmallString<128> TemplateArgString; 9909 if (TemplateArgumentList *Args = 9910 DeductionFailure.getTemplateArgumentList()) { 9911 TemplateArgString = " "; 9912 TemplateArgString += S.getTemplateArgumentBindingsText( 9913 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9914 } 9915 9916 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9917 << (*DeductionFailure.getCallArgIndex() + 1) 9918 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9919 << TemplateArgString 9920 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 9921 break; 9922 } 9923 9924 case Sema::TDK_NonDeducedMismatch: { 9925 // FIXME: Provide a source location to indicate what we couldn't match. 9926 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9927 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9928 if (FirstTA.getKind() == TemplateArgument::Template && 9929 SecondTA.getKind() == TemplateArgument::Template) { 9930 TemplateName FirstTN = FirstTA.getAsTemplate(); 9931 TemplateName SecondTN = SecondTA.getAsTemplate(); 9932 if (FirstTN.getKind() == TemplateName::Template && 9933 SecondTN.getKind() == TemplateName::Template) { 9934 if (FirstTN.getAsTemplateDecl()->getName() == 9935 SecondTN.getAsTemplateDecl()->getName()) { 9936 // FIXME: This fixes a bad diagnostic where both templates are named 9937 // the same. This particular case is a bit difficult since: 9938 // 1) It is passed as a string to the diagnostic printer. 9939 // 2) The diagnostic printer only attempts to find a better 9940 // name for types, not decls. 9941 // Ideally, this should folded into the diagnostic printer. 9942 S.Diag(Templated->getLocation(), 9943 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9944 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9945 return; 9946 } 9947 } 9948 } 9949 9950 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9951 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9952 return; 9953 9954 // FIXME: For generic lambda parameters, check if the function is a lambda 9955 // call operator, and if so, emit a prettier and more informative 9956 // diagnostic that mentions 'auto' and lambda in addition to 9957 // (or instead of?) the canonical template type parameters. 9958 S.Diag(Templated->getLocation(), 9959 diag::note_ovl_candidate_non_deduced_mismatch) 9960 << FirstTA << SecondTA; 9961 return; 9962 } 9963 // TODO: diagnose these individually, then kill off 9964 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9965 case Sema::TDK_MiscellaneousDeductionFailure: 9966 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9967 MaybeEmitInheritedConstructorNote(S, Found); 9968 return; 9969 case Sema::TDK_CUDATargetMismatch: 9970 S.Diag(Templated->getLocation(), 9971 diag::note_cuda_ovl_candidate_target_mismatch); 9972 return; 9973 } 9974 } 9975 9976 /// Diagnose a failed template-argument deduction, for function calls. 9977 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9978 unsigned NumArgs, 9979 bool TakingCandidateAddress) { 9980 unsigned TDK = Cand->DeductionFailure.Result; 9981 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9982 if (CheckArityMismatch(S, Cand, NumArgs)) 9983 return; 9984 } 9985 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 9986 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9987 } 9988 9989 /// CUDA: diagnose an invalid call across targets. 9990 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9991 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9992 FunctionDecl *Callee = Cand->Function; 9993 9994 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9995 CalleeTarget = S.IdentifyCUDATarget(Callee); 9996 9997 std::string FnDesc; 9998 OverloadCandidateKind FnKind = 9999 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10000 10001 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10002 << (unsigned)FnKind << CalleeTarget << CallerTarget; 10003 10004 // This could be an implicit constructor for which we could not infer the 10005 // target due to a collsion. Diagnose that case. 10006 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10007 if (Meth != nullptr && Meth->isImplicit()) { 10008 CXXRecordDecl *ParentClass = Meth->getParent(); 10009 Sema::CXXSpecialMember CSM; 10010 10011 switch (FnKind) { 10012 default: 10013 return; 10014 case oc_implicit_default_constructor: 10015 CSM = Sema::CXXDefaultConstructor; 10016 break; 10017 case oc_implicit_copy_constructor: 10018 CSM = Sema::CXXCopyConstructor; 10019 break; 10020 case oc_implicit_move_constructor: 10021 CSM = Sema::CXXMoveConstructor; 10022 break; 10023 case oc_implicit_copy_assignment: 10024 CSM = Sema::CXXCopyAssignment; 10025 break; 10026 case oc_implicit_move_assignment: 10027 CSM = Sema::CXXMoveAssignment; 10028 break; 10029 }; 10030 10031 bool ConstRHS = false; 10032 if (Meth->getNumParams()) { 10033 if (const ReferenceType *RT = 10034 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10035 ConstRHS = RT->getPointeeType().isConstQualified(); 10036 } 10037 } 10038 10039 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10040 /* ConstRHS */ ConstRHS, 10041 /* Diagnose */ true); 10042 } 10043 } 10044 10045 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10046 FunctionDecl *Callee = Cand->Function; 10047 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10048 10049 S.Diag(Callee->getLocation(), 10050 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10051 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10052 } 10053 10054 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10055 FunctionDecl *Callee = Cand->Function; 10056 10057 S.Diag(Callee->getLocation(), 10058 diag::note_ovl_candidate_disabled_by_extension); 10059 } 10060 10061 /// Generates a 'note' diagnostic for an overload candidate. We've 10062 /// already generated a primary error at the call site. 10063 /// 10064 /// It really does need to be a single diagnostic with its caret 10065 /// pointed at the candidate declaration. Yes, this creates some 10066 /// major challenges of technical writing. Yes, this makes pointing 10067 /// out problems with specific arguments quite awkward. It's still 10068 /// better than generating twenty screens of text for every failed 10069 /// overload. 10070 /// 10071 /// It would be great to be able to express per-candidate problems 10072 /// more richly for those diagnostic clients that cared, but we'd 10073 /// still have to be just as careful with the default diagnostics. 10074 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10075 unsigned NumArgs, 10076 bool TakingCandidateAddress) { 10077 FunctionDecl *Fn = Cand->Function; 10078 10079 // Note deleted candidates, but only if they're viable. 10080 if (Cand->Viable) { 10081 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) { 10082 std::string FnDesc; 10083 OverloadCandidateKind FnKind = 10084 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10085 10086 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10087 << FnKind << FnDesc 10088 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10089 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10090 return; 10091 } 10092 10093 // We don't really have anything else to say about viable candidates. 10094 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10095 return; 10096 } 10097 10098 switch (Cand->FailureKind) { 10099 case ovl_fail_too_many_arguments: 10100 case ovl_fail_too_few_arguments: 10101 return DiagnoseArityMismatch(S, Cand, NumArgs); 10102 10103 case ovl_fail_bad_deduction: 10104 return DiagnoseBadDeduction(S, Cand, NumArgs, 10105 TakingCandidateAddress); 10106 10107 case ovl_fail_illegal_constructor: { 10108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10109 << (Fn->getPrimaryTemplate() ? 1 : 0); 10110 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10111 return; 10112 } 10113 10114 case ovl_fail_trivial_conversion: 10115 case ovl_fail_bad_final_conversion: 10116 case ovl_fail_final_conversion_not_exact: 10117 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10118 10119 case ovl_fail_bad_conversion: { 10120 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10121 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10122 if (Cand->Conversions[I].isBad()) 10123 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10124 10125 // FIXME: this currently happens when we're called from SemaInit 10126 // when user-conversion overload fails. Figure out how to handle 10127 // those conditions and diagnose them well. 10128 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10129 } 10130 10131 case ovl_fail_bad_target: 10132 return DiagnoseBadTarget(S, Cand); 10133 10134 case ovl_fail_enable_if: 10135 return DiagnoseFailedEnableIfAttr(S, Cand); 10136 10137 case ovl_fail_ext_disabled: 10138 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10139 10140 case ovl_fail_inhctor_slice: 10141 // It's generally not interesting to note copy/move constructors here. 10142 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10143 return; 10144 S.Diag(Fn->getLocation(), 10145 diag::note_ovl_candidate_inherited_constructor_slice) 10146 << (Fn->getPrimaryTemplate() ? 1 : 0) 10147 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10148 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10149 return; 10150 10151 case ovl_fail_addr_not_available: { 10152 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10153 (void)Available; 10154 assert(!Available); 10155 break; 10156 } 10157 } 10158 } 10159 10160 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10161 // Desugar the type of the surrogate down to a function type, 10162 // retaining as many typedefs as possible while still showing 10163 // the function type (and, therefore, its parameter types). 10164 QualType FnType = Cand->Surrogate->getConversionType(); 10165 bool isLValueReference = false; 10166 bool isRValueReference = false; 10167 bool isPointer = false; 10168 if (const LValueReferenceType *FnTypeRef = 10169 FnType->getAs<LValueReferenceType>()) { 10170 FnType = FnTypeRef->getPointeeType(); 10171 isLValueReference = true; 10172 } else if (const RValueReferenceType *FnTypeRef = 10173 FnType->getAs<RValueReferenceType>()) { 10174 FnType = FnTypeRef->getPointeeType(); 10175 isRValueReference = true; 10176 } 10177 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10178 FnType = FnTypePtr->getPointeeType(); 10179 isPointer = true; 10180 } 10181 // Desugar down to a function type. 10182 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10183 // Reconstruct the pointer/reference as appropriate. 10184 if (isPointer) FnType = S.Context.getPointerType(FnType); 10185 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10186 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10187 10188 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10189 << FnType; 10190 } 10191 10192 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10193 SourceLocation OpLoc, 10194 OverloadCandidate *Cand) { 10195 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10196 std::string TypeStr("operator"); 10197 TypeStr += Opc; 10198 TypeStr += "("; 10199 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 10200 if (Cand->Conversions.size() == 1) { 10201 TypeStr += ")"; 10202 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10203 } else { 10204 TypeStr += ", "; 10205 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 10206 TypeStr += ")"; 10207 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10208 } 10209 } 10210 10211 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10212 OverloadCandidate *Cand) { 10213 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10214 if (ICS.isBad()) break; // all meaningless after first invalid 10215 if (!ICS.isAmbiguous()) continue; 10216 10217 ICS.DiagnoseAmbiguousConversion( 10218 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10219 } 10220 } 10221 10222 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10223 if (Cand->Function) 10224 return Cand->Function->getLocation(); 10225 if (Cand->IsSurrogate) 10226 return Cand->Surrogate->getLocation(); 10227 return SourceLocation(); 10228 } 10229 10230 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10231 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10232 case Sema::TDK_Success: 10233 case Sema::TDK_NonDependentConversionFailure: 10234 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10235 10236 case Sema::TDK_Invalid: 10237 case Sema::TDK_Incomplete: 10238 return 1; 10239 10240 case Sema::TDK_Underqualified: 10241 case Sema::TDK_Inconsistent: 10242 return 2; 10243 10244 case Sema::TDK_SubstitutionFailure: 10245 case Sema::TDK_DeducedMismatch: 10246 case Sema::TDK_DeducedMismatchNested: 10247 case Sema::TDK_NonDeducedMismatch: 10248 case Sema::TDK_MiscellaneousDeductionFailure: 10249 case Sema::TDK_CUDATargetMismatch: 10250 return 3; 10251 10252 case Sema::TDK_InstantiationDepth: 10253 return 4; 10254 10255 case Sema::TDK_InvalidExplicitArguments: 10256 return 5; 10257 10258 case Sema::TDK_TooManyArguments: 10259 case Sema::TDK_TooFewArguments: 10260 return 6; 10261 } 10262 llvm_unreachable("Unhandled deduction result"); 10263 } 10264 10265 namespace { 10266 struct CompareOverloadCandidatesForDisplay { 10267 Sema &S; 10268 SourceLocation Loc; 10269 size_t NumArgs; 10270 10271 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 10272 : S(S), NumArgs(nArgs) {} 10273 10274 bool operator()(const OverloadCandidate *L, 10275 const OverloadCandidate *R) { 10276 // Fast-path this check. 10277 if (L == R) return false; 10278 10279 // Order first by viability. 10280 if (L->Viable) { 10281 if (!R->Viable) return true; 10282 10283 // TODO: introduce a tri-valued comparison for overload 10284 // candidates. Would be more worthwhile if we had a sort 10285 // that could exploit it. 10286 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 10287 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 10288 } else if (R->Viable) 10289 return false; 10290 10291 assert(L->Viable == R->Viable); 10292 10293 // Criteria by which we can sort non-viable candidates: 10294 if (!L->Viable) { 10295 // 1. Arity mismatches come after other candidates. 10296 if (L->FailureKind == ovl_fail_too_many_arguments || 10297 L->FailureKind == ovl_fail_too_few_arguments) { 10298 if (R->FailureKind == ovl_fail_too_many_arguments || 10299 R->FailureKind == ovl_fail_too_few_arguments) { 10300 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10301 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10302 if (LDist == RDist) { 10303 if (L->FailureKind == R->FailureKind) 10304 // Sort non-surrogates before surrogates. 10305 return !L->IsSurrogate && R->IsSurrogate; 10306 // Sort candidates requiring fewer parameters than there were 10307 // arguments given after candidates requiring more parameters 10308 // than there were arguments given. 10309 return L->FailureKind == ovl_fail_too_many_arguments; 10310 } 10311 return LDist < RDist; 10312 } 10313 return false; 10314 } 10315 if (R->FailureKind == ovl_fail_too_many_arguments || 10316 R->FailureKind == ovl_fail_too_few_arguments) 10317 return true; 10318 10319 // 2. Bad conversions come first and are ordered by the number 10320 // of bad conversions and quality of good conversions. 10321 if (L->FailureKind == ovl_fail_bad_conversion) { 10322 if (R->FailureKind != ovl_fail_bad_conversion) 10323 return true; 10324 10325 // The conversion that can be fixed with a smaller number of changes, 10326 // comes first. 10327 unsigned numLFixes = L->Fix.NumConversionsFixed; 10328 unsigned numRFixes = R->Fix.NumConversionsFixed; 10329 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10330 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10331 if (numLFixes != numRFixes) { 10332 return numLFixes < numRFixes; 10333 } 10334 10335 // If there's any ordering between the defined conversions... 10336 // FIXME: this might not be transitive. 10337 assert(L->Conversions.size() == R->Conversions.size()); 10338 10339 int leftBetter = 0; 10340 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10341 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10342 switch (CompareImplicitConversionSequences(S, Loc, 10343 L->Conversions[I], 10344 R->Conversions[I])) { 10345 case ImplicitConversionSequence::Better: 10346 leftBetter++; 10347 break; 10348 10349 case ImplicitConversionSequence::Worse: 10350 leftBetter--; 10351 break; 10352 10353 case ImplicitConversionSequence::Indistinguishable: 10354 break; 10355 } 10356 } 10357 if (leftBetter > 0) return true; 10358 if (leftBetter < 0) return false; 10359 10360 } else if (R->FailureKind == ovl_fail_bad_conversion) 10361 return false; 10362 10363 if (L->FailureKind == ovl_fail_bad_deduction) { 10364 if (R->FailureKind != ovl_fail_bad_deduction) 10365 return true; 10366 10367 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10368 return RankDeductionFailure(L->DeductionFailure) 10369 < RankDeductionFailure(R->DeductionFailure); 10370 } else if (R->FailureKind == ovl_fail_bad_deduction) 10371 return false; 10372 10373 // TODO: others? 10374 } 10375 10376 // Sort everything else by location. 10377 SourceLocation LLoc = GetLocationForCandidate(L); 10378 SourceLocation RLoc = GetLocationForCandidate(R); 10379 10380 // Put candidates without locations (e.g. builtins) at the end. 10381 if (LLoc.isInvalid()) return false; 10382 if (RLoc.isInvalid()) return true; 10383 10384 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10385 } 10386 }; 10387 } 10388 10389 /// CompleteNonViableCandidate - Normally, overload resolution only 10390 /// computes up to the first bad conversion. Produces the FixIt set if 10391 /// possible. 10392 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10393 ArrayRef<Expr *> Args) { 10394 assert(!Cand->Viable); 10395 10396 // Don't do anything on failures other than bad conversion. 10397 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10398 10399 // We only want the FixIts if all the arguments can be corrected. 10400 bool Unfixable = false; 10401 // Use a implicit copy initialization to check conversion fixes. 10402 Cand->Fix.setConversionChecker(TryCopyInitialization); 10403 10404 // Attempt to fix the bad conversion. 10405 unsigned ConvCount = Cand->Conversions.size(); 10406 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10407 ++ConvIdx) { 10408 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10409 if (Cand->Conversions[ConvIdx].isInitialized() && 10410 Cand->Conversions[ConvIdx].isBad()) { 10411 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10412 break; 10413 } 10414 } 10415 10416 // FIXME: this should probably be preserved from the overload 10417 // operation somehow. 10418 bool SuppressUserConversions = false; 10419 10420 unsigned ConvIdx = 0; 10421 ArrayRef<QualType> ParamTypes; 10422 10423 if (Cand->IsSurrogate) { 10424 QualType ConvType 10425 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10426 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10427 ConvType = ConvPtrType->getPointeeType(); 10428 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10429 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10430 ConvIdx = 1; 10431 } else if (Cand->Function) { 10432 ParamTypes = 10433 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10434 if (isa<CXXMethodDecl>(Cand->Function) && 10435 !isa<CXXConstructorDecl>(Cand->Function)) { 10436 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10437 ConvIdx = 1; 10438 } 10439 } else { 10440 // Builtin operator. 10441 assert(ConvCount <= 3); 10442 ParamTypes = Cand->BuiltinTypes.ParamTypes; 10443 } 10444 10445 // Fill in the rest of the conversions. 10446 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10447 if (Cand->Conversions[ConvIdx].isInitialized()) { 10448 // We've already checked this conversion. 10449 } else if (ArgIdx < ParamTypes.size()) { 10450 if (ParamTypes[ArgIdx]->isDependentType()) 10451 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10452 Args[ArgIdx]->getType()); 10453 else { 10454 Cand->Conversions[ConvIdx] = 10455 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10456 SuppressUserConversions, 10457 /*InOverloadResolution=*/true, 10458 /*AllowObjCWritebackConversion=*/ 10459 S.getLangOpts().ObjCAutoRefCount); 10460 // Store the FixIt in the candidate if it exists. 10461 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10462 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10463 } 10464 } else 10465 Cand->Conversions[ConvIdx].setEllipsis(); 10466 } 10467 } 10468 10469 /// PrintOverloadCandidates - When overload resolution fails, prints 10470 /// diagnostic messages containing the candidates in the candidate 10471 /// set. 10472 void OverloadCandidateSet::NoteCandidates( 10473 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10474 StringRef Opc, SourceLocation OpLoc, 10475 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10476 // Sort the candidates by viability and position. Sorting directly would 10477 // be prohibitive, so we make a set of pointers and sort those. 10478 SmallVector<OverloadCandidate*, 32> Cands; 10479 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10480 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10481 if (!Filter(*Cand)) 10482 continue; 10483 if (Cand->Viable) 10484 Cands.push_back(Cand); 10485 else if (OCD == OCD_AllCandidates) { 10486 CompleteNonViableCandidate(S, Cand, Args); 10487 if (Cand->Function || Cand->IsSurrogate) 10488 Cands.push_back(Cand); 10489 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10490 // want to list every possible builtin candidate. 10491 } 10492 } 10493 10494 std::sort(Cands.begin(), Cands.end(), 10495 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10496 10497 bool ReportedAmbiguousConversions = false; 10498 10499 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10500 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10501 unsigned CandsShown = 0; 10502 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10503 OverloadCandidate *Cand = *I; 10504 10505 // Set an arbitrary limit on the number of candidate functions we'll spam 10506 // the user with. FIXME: This limit should depend on details of the 10507 // candidate list. 10508 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10509 break; 10510 } 10511 ++CandsShown; 10512 10513 if (Cand->Function) 10514 NoteFunctionCandidate(S, Cand, Args.size(), 10515 /*TakingCandidateAddress=*/false); 10516 else if (Cand->IsSurrogate) 10517 NoteSurrogateCandidate(S, Cand); 10518 else { 10519 assert(Cand->Viable && 10520 "Non-viable built-in candidates are not added to Cands."); 10521 // Generally we only see ambiguities including viable builtin 10522 // operators if overload resolution got screwed up by an 10523 // ambiguous user-defined conversion. 10524 // 10525 // FIXME: It's quite possible for different conversions to see 10526 // different ambiguities, though. 10527 if (!ReportedAmbiguousConversions) { 10528 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10529 ReportedAmbiguousConversions = true; 10530 } 10531 10532 // If this is a viable builtin, print it. 10533 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10534 } 10535 } 10536 10537 if (I != E) 10538 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10539 } 10540 10541 static SourceLocation 10542 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10543 return Cand->Specialization ? Cand->Specialization->getLocation() 10544 : SourceLocation(); 10545 } 10546 10547 namespace { 10548 struct CompareTemplateSpecCandidatesForDisplay { 10549 Sema &S; 10550 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10551 10552 bool operator()(const TemplateSpecCandidate *L, 10553 const TemplateSpecCandidate *R) { 10554 // Fast-path this check. 10555 if (L == R) 10556 return false; 10557 10558 // Assuming that both candidates are not matches... 10559 10560 // Sort by the ranking of deduction failures. 10561 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10562 return RankDeductionFailure(L->DeductionFailure) < 10563 RankDeductionFailure(R->DeductionFailure); 10564 10565 // Sort everything else by location. 10566 SourceLocation LLoc = GetLocationForCandidate(L); 10567 SourceLocation RLoc = GetLocationForCandidate(R); 10568 10569 // Put candidates without locations (e.g. builtins) at the end. 10570 if (LLoc.isInvalid()) 10571 return false; 10572 if (RLoc.isInvalid()) 10573 return true; 10574 10575 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10576 } 10577 }; 10578 } 10579 10580 /// Diagnose a template argument deduction failure. 10581 /// We are treating these failures as overload failures due to bad 10582 /// deductions. 10583 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10584 bool ForTakingAddress) { 10585 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10586 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10587 } 10588 10589 void TemplateSpecCandidateSet::destroyCandidates() { 10590 for (iterator i = begin(), e = end(); i != e; ++i) { 10591 i->DeductionFailure.Destroy(); 10592 } 10593 } 10594 10595 void TemplateSpecCandidateSet::clear() { 10596 destroyCandidates(); 10597 Candidates.clear(); 10598 } 10599 10600 /// NoteCandidates - When no template specialization match is found, prints 10601 /// diagnostic messages containing the non-matching specializations that form 10602 /// the candidate set. 10603 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10604 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10605 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10606 // Sort the candidates by position (assuming no candidate is a match). 10607 // Sorting directly would be prohibitive, so we make a set of pointers 10608 // and sort those. 10609 SmallVector<TemplateSpecCandidate *, 32> Cands; 10610 Cands.reserve(size()); 10611 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10612 if (Cand->Specialization) 10613 Cands.push_back(Cand); 10614 // Otherwise, this is a non-matching builtin candidate. We do not, 10615 // in general, want to list every possible builtin candidate. 10616 } 10617 10618 std::sort(Cands.begin(), Cands.end(), 10619 CompareTemplateSpecCandidatesForDisplay(S)); 10620 10621 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10622 // for generalization purposes (?). 10623 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10624 10625 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10626 unsigned CandsShown = 0; 10627 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10628 TemplateSpecCandidate *Cand = *I; 10629 10630 // Set an arbitrary limit on the number of candidates we'll spam 10631 // the user with. FIXME: This limit should depend on details of the 10632 // candidate list. 10633 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10634 break; 10635 ++CandsShown; 10636 10637 assert(Cand->Specialization && 10638 "Non-matching built-in candidates are not added to Cands."); 10639 Cand->NoteDeductionFailure(S, ForTakingAddress); 10640 } 10641 10642 if (I != E) 10643 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10644 } 10645 10646 // [PossiblyAFunctionType] --> [Return] 10647 // NonFunctionType --> NonFunctionType 10648 // R (A) --> R(A) 10649 // R (*)(A) --> R (A) 10650 // R (&)(A) --> R (A) 10651 // R (S::*)(A) --> R (A) 10652 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10653 QualType Ret = PossiblyAFunctionType; 10654 if (const PointerType *ToTypePtr = 10655 PossiblyAFunctionType->getAs<PointerType>()) 10656 Ret = ToTypePtr->getPointeeType(); 10657 else if (const ReferenceType *ToTypeRef = 10658 PossiblyAFunctionType->getAs<ReferenceType>()) 10659 Ret = ToTypeRef->getPointeeType(); 10660 else if (const MemberPointerType *MemTypePtr = 10661 PossiblyAFunctionType->getAs<MemberPointerType>()) 10662 Ret = MemTypePtr->getPointeeType(); 10663 Ret = 10664 Context.getCanonicalType(Ret).getUnqualifiedType(); 10665 return Ret; 10666 } 10667 10668 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10669 bool Complain = true) { 10670 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10671 S.DeduceReturnType(FD, Loc, Complain)) 10672 return true; 10673 10674 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10675 if (S.getLangOpts().CPlusPlus1z && 10676 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10677 !S.ResolveExceptionSpec(Loc, FPT)) 10678 return true; 10679 10680 return false; 10681 } 10682 10683 namespace { 10684 // A helper class to help with address of function resolution 10685 // - allows us to avoid passing around all those ugly parameters 10686 class AddressOfFunctionResolver { 10687 Sema& S; 10688 Expr* SourceExpr; 10689 const QualType& TargetType; 10690 QualType TargetFunctionType; // Extracted function type from target type 10691 10692 bool Complain; 10693 //DeclAccessPair& ResultFunctionAccessPair; 10694 ASTContext& Context; 10695 10696 bool TargetTypeIsNonStaticMemberFunction; 10697 bool FoundNonTemplateFunction; 10698 bool StaticMemberFunctionFromBoundPointer; 10699 bool HasComplained; 10700 10701 OverloadExpr::FindResult OvlExprInfo; 10702 OverloadExpr *OvlExpr; 10703 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10704 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10705 TemplateSpecCandidateSet FailedCandidates; 10706 10707 public: 10708 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10709 const QualType &TargetType, bool Complain) 10710 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10711 Complain(Complain), Context(S.getASTContext()), 10712 TargetTypeIsNonStaticMemberFunction( 10713 !!TargetType->getAs<MemberPointerType>()), 10714 FoundNonTemplateFunction(false), 10715 StaticMemberFunctionFromBoundPointer(false), 10716 HasComplained(false), 10717 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10718 OvlExpr(OvlExprInfo.Expression), 10719 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10720 ExtractUnqualifiedFunctionTypeFromTargetType(); 10721 10722 if (TargetFunctionType->isFunctionType()) { 10723 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10724 if (!UME->isImplicitAccess() && 10725 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10726 StaticMemberFunctionFromBoundPointer = true; 10727 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10728 DeclAccessPair dap; 10729 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10730 OvlExpr, false, &dap)) { 10731 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10732 if (!Method->isStatic()) { 10733 // If the target type is a non-function type and the function found 10734 // is a non-static member function, pretend as if that was the 10735 // target, it's the only possible type to end up with. 10736 TargetTypeIsNonStaticMemberFunction = true; 10737 10738 // And skip adding the function if its not in the proper form. 10739 // We'll diagnose this due to an empty set of functions. 10740 if (!OvlExprInfo.HasFormOfMemberPointer) 10741 return; 10742 } 10743 10744 Matches.push_back(std::make_pair(dap, Fn)); 10745 } 10746 return; 10747 } 10748 10749 if (OvlExpr->hasExplicitTemplateArgs()) 10750 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10751 10752 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10753 // C++ [over.over]p4: 10754 // If more than one function is selected, [...] 10755 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10756 if (FoundNonTemplateFunction) 10757 EliminateAllTemplateMatches(); 10758 else 10759 EliminateAllExceptMostSpecializedTemplate(); 10760 } 10761 } 10762 10763 if (S.getLangOpts().CUDA && Matches.size() > 1) 10764 EliminateSuboptimalCudaMatches(); 10765 } 10766 10767 bool hasComplained() const { return HasComplained; } 10768 10769 private: 10770 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10771 QualType Discard; 10772 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10773 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 10774 } 10775 10776 /// \return true if A is considered a better overload candidate for the 10777 /// desired type than B. 10778 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10779 // If A doesn't have exactly the correct type, we don't want to classify it 10780 // as "better" than anything else. This way, the user is required to 10781 // disambiguate for us if there are multiple candidates and no exact match. 10782 return candidateHasExactlyCorrectType(A) && 10783 (!candidateHasExactlyCorrectType(B) || 10784 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10785 } 10786 10787 /// \return true if we were able to eliminate all but one overload candidate, 10788 /// false otherwise. 10789 bool eliminiateSuboptimalOverloadCandidates() { 10790 // Same algorithm as overload resolution -- one pass to pick the "best", 10791 // another pass to be sure that nothing is better than the best. 10792 auto Best = Matches.begin(); 10793 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10794 if (isBetterCandidate(I->second, Best->second)) 10795 Best = I; 10796 10797 const FunctionDecl *BestFn = Best->second; 10798 auto IsBestOrInferiorToBest = [this, BestFn]( 10799 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10800 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10801 }; 10802 10803 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10804 // option, so we can potentially give the user a better error 10805 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10806 return false; 10807 Matches[0] = *Best; 10808 Matches.resize(1); 10809 return true; 10810 } 10811 10812 bool isTargetTypeAFunction() const { 10813 return TargetFunctionType->isFunctionType(); 10814 } 10815 10816 // [ToType] [Return] 10817 10818 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10819 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10820 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10821 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10822 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10823 } 10824 10825 // return true if any matching specializations were found 10826 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10827 const DeclAccessPair& CurAccessFunPair) { 10828 if (CXXMethodDecl *Method 10829 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10830 // Skip non-static function templates when converting to pointer, and 10831 // static when converting to member pointer. 10832 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10833 return false; 10834 } 10835 else if (TargetTypeIsNonStaticMemberFunction) 10836 return false; 10837 10838 // C++ [over.over]p2: 10839 // If the name is a function template, template argument deduction is 10840 // done (14.8.2.2), and if the argument deduction succeeds, the 10841 // resulting template argument list is used to generate a single 10842 // function template specialization, which is added to the set of 10843 // overloaded functions considered. 10844 FunctionDecl *Specialization = nullptr; 10845 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10846 if (Sema::TemplateDeductionResult Result 10847 = S.DeduceTemplateArguments(FunctionTemplate, 10848 &OvlExplicitTemplateArgs, 10849 TargetFunctionType, Specialization, 10850 Info, /*IsAddressOfFunction*/true)) { 10851 // Make a note of the failed deduction for diagnostics. 10852 FailedCandidates.addCandidate() 10853 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 10854 MakeDeductionFailureInfo(Context, Result, Info)); 10855 return false; 10856 } 10857 10858 // Template argument deduction ensures that we have an exact match or 10859 // compatible pointer-to-function arguments that would be adjusted by ICS. 10860 // This function template specicalization works. 10861 assert(S.isSameOrCompatibleFunctionType( 10862 Context.getCanonicalType(Specialization->getType()), 10863 Context.getCanonicalType(TargetFunctionType))); 10864 10865 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10866 return false; 10867 10868 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10869 return true; 10870 } 10871 10872 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10873 const DeclAccessPair& CurAccessFunPair) { 10874 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10875 // Skip non-static functions when converting to pointer, and static 10876 // when converting to member pointer. 10877 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10878 return false; 10879 } 10880 else if (TargetTypeIsNonStaticMemberFunction) 10881 return false; 10882 10883 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10884 if (S.getLangOpts().CUDA) 10885 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10886 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 10887 return false; 10888 10889 // If any candidate has a placeholder return type, trigger its deduction 10890 // now. 10891 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(), 10892 Complain)) { 10893 HasComplained |= Complain; 10894 return false; 10895 } 10896 10897 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10898 return false; 10899 10900 // If we're in C, we need to support types that aren't exactly identical. 10901 if (!S.getLangOpts().CPlusPlus || 10902 candidateHasExactlyCorrectType(FunDecl)) { 10903 Matches.push_back(std::make_pair( 10904 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10905 FoundNonTemplateFunction = true; 10906 return true; 10907 } 10908 } 10909 10910 return false; 10911 } 10912 10913 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10914 bool Ret = false; 10915 10916 // If the overload expression doesn't have the form of a pointer to 10917 // member, don't try to convert it to a pointer-to-member type. 10918 if (IsInvalidFormOfPointerToMemberFunction()) 10919 return false; 10920 10921 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10922 E = OvlExpr->decls_end(); 10923 I != E; ++I) { 10924 // Look through any using declarations to find the underlying function. 10925 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10926 10927 // C++ [over.over]p3: 10928 // Non-member functions and static member functions match 10929 // targets of type "pointer-to-function" or "reference-to-function." 10930 // Nonstatic member functions match targets of 10931 // type "pointer-to-member-function." 10932 // Note that according to DR 247, the containing class does not matter. 10933 if (FunctionTemplateDecl *FunctionTemplate 10934 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10935 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10936 Ret = true; 10937 } 10938 // If we have explicit template arguments supplied, skip non-templates. 10939 else if (!OvlExpr->hasExplicitTemplateArgs() && 10940 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10941 Ret = true; 10942 } 10943 assert(Ret || Matches.empty()); 10944 return Ret; 10945 } 10946 10947 void EliminateAllExceptMostSpecializedTemplate() { 10948 // [...] and any given function template specialization F1 is 10949 // eliminated if the set contains a second function template 10950 // specialization whose function template is more specialized 10951 // than the function template of F1 according to the partial 10952 // ordering rules of 14.5.5.2. 10953 10954 // The algorithm specified above is quadratic. We instead use a 10955 // two-pass algorithm (similar to the one used to identify the 10956 // best viable function in an overload set) that identifies the 10957 // best function template (if it exists). 10958 10959 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10960 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10961 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10962 10963 // TODO: It looks like FailedCandidates does not serve much purpose 10964 // here, since the no_viable diagnostic has index 0. 10965 UnresolvedSetIterator Result = S.getMostSpecialized( 10966 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10967 SourceExpr->getLocStart(), S.PDiag(), 10968 S.PDiag(diag::err_addr_ovl_ambiguous) 10969 << Matches[0].second->getDeclName(), 10970 S.PDiag(diag::note_ovl_candidate) 10971 << (unsigned)oc_function_template, 10972 Complain, TargetFunctionType); 10973 10974 if (Result != MatchesCopy.end()) { 10975 // Make it the first and only element 10976 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10977 Matches[0].second = cast<FunctionDecl>(*Result); 10978 Matches.resize(1); 10979 } else 10980 HasComplained |= Complain; 10981 } 10982 10983 void EliminateAllTemplateMatches() { 10984 // [...] any function template specializations in the set are 10985 // eliminated if the set also contains a non-template function, [...] 10986 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10987 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10988 ++I; 10989 else { 10990 Matches[I] = Matches[--N]; 10991 Matches.resize(N); 10992 } 10993 } 10994 } 10995 10996 void EliminateSuboptimalCudaMatches() { 10997 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10998 } 10999 11000 public: 11001 void ComplainNoMatchesFound() const { 11002 assert(Matches.empty()); 11003 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 11004 << OvlExpr->getName() << TargetFunctionType 11005 << OvlExpr->getSourceRange(); 11006 if (FailedCandidates.empty()) 11007 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11008 /*TakingAddress=*/true); 11009 else { 11010 // We have some deduction failure messages. Use them to diagnose 11011 // the function templates, and diagnose the non-template candidates 11012 // normally. 11013 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11014 IEnd = OvlExpr->decls_end(); 11015 I != IEnd; ++I) 11016 if (FunctionDecl *Fun = 11017 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11018 if (!functionHasPassObjectSizeParams(Fun)) 11019 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11020 /*TakingAddress=*/true); 11021 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 11022 } 11023 } 11024 11025 bool IsInvalidFormOfPointerToMemberFunction() const { 11026 return TargetTypeIsNonStaticMemberFunction && 11027 !OvlExprInfo.HasFormOfMemberPointer; 11028 } 11029 11030 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11031 // TODO: Should we condition this on whether any functions might 11032 // have matched, or is it more appropriate to do that in callers? 11033 // TODO: a fixit wouldn't hurt. 11034 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11035 << TargetType << OvlExpr->getSourceRange(); 11036 } 11037 11038 bool IsStaticMemberFunctionFromBoundPointer() const { 11039 return StaticMemberFunctionFromBoundPointer; 11040 } 11041 11042 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11043 S.Diag(OvlExpr->getLocStart(), 11044 diag::err_invalid_form_pointer_member_function) 11045 << OvlExpr->getSourceRange(); 11046 } 11047 11048 void ComplainOfInvalidConversion() const { 11049 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 11050 << OvlExpr->getName() << TargetType; 11051 } 11052 11053 void ComplainMultipleMatchesFound() const { 11054 assert(Matches.size() > 1); 11055 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 11056 << OvlExpr->getName() 11057 << OvlExpr->getSourceRange(); 11058 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11059 /*TakingAddress=*/true); 11060 } 11061 11062 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11063 11064 int getNumMatches() const { return Matches.size(); } 11065 11066 FunctionDecl* getMatchingFunctionDecl() const { 11067 if (Matches.size() != 1) return nullptr; 11068 return Matches[0].second; 11069 } 11070 11071 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11072 if (Matches.size() != 1) return nullptr; 11073 return &Matches[0].first; 11074 } 11075 }; 11076 } 11077 11078 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11079 /// an overloaded function (C++ [over.over]), where @p From is an 11080 /// expression with overloaded function type and @p ToType is the type 11081 /// we're trying to resolve to. For example: 11082 /// 11083 /// @code 11084 /// int f(double); 11085 /// int f(int); 11086 /// 11087 /// int (*pfd)(double) = f; // selects f(double) 11088 /// @endcode 11089 /// 11090 /// This routine returns the resulting FunctionDecl if it could be 11091 /// resolved, and NULL otherwise. When @p Complain is true, this 11092 /// routine will emit diagnostics if there is an error. 11093 FunctionDecl * 11094 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11095 QualType TargetType, 11096 bool Complain, 11097 DeclAccessPair &FoundResult, 11098 bool *pHadMultipleCandidates) { 11099 assert(AddressOfExpr->getType() == Context.OverloadTy); 11100 11101 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11102 Complain); 11103 int NumMatches = Resolver.getNumMatches(); 11104 FunctionDecl *Fn = nullptr; 11105 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11106 if (NumMatches == 0 && ShouldComplain) { 11107 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11108 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11109 else 11110 Resolver.ComplainNoMatchesFound(); 11111 } 11112 else if (NumMatches > 1 && ShouldComplain) 11113 Resolver.ComplainMultipleMatchesFound(); 11114 else if (NumMatches == 1) { 11115 Fn = Resolver.getMatchingFunctionDecl(); 11116 assert(Fn); 11117 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11118 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11119 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11120 if (Complain) { 11121 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11122 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11123 else 11124 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11125 } 11126 } 11127 11128 if (pHadMultipleCandidates) 11129 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11130 return Fn; 11131 } 11132 11133 /// \brief Given an expression that refers to an overloaded function, try to 11134 /// resolve that function to a single function that can have its address taken. 11135 /// This will modify `Pair` iff it returns non-null. 11136 /// 11137 /// This routine can only realistically succeed if all but one candidates in the 11138 /// overload set for SrcExpr cannot have their addresses taken. 11139 FunctionDecl * 11140 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11141 DeclAccessPair &Pair) { 11142 OverloadExpr::FindResult R = OverloadExpr::find(E); 11143 OverloadExpr *Ovl = R.Expression; 11144 FunctionDecl *Result = nullptr; 11145 DeclAccessPair DAP; 11146 // Don't use the AddressOfResolver because we're specifically looking for 11147 // cases where we have one overload candidate that lacks 11148 // enable_if/pass_object_size/... 11149 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11150 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11151 if (!FD) 11152 return nullptr; 11153 11154 if (!checkAddressOfFunctionIsAvailable(FD)) 11155 continue; 11156 11157 // We have more than one result; quit. 11158 if (Result) 11159 return nullptr; 11160 DAP = I.getPair(); 11161 Result = FD; 11162 } 11163 11164 if (Result) 11165 Pair = DAP; 11166 return Result; 11167 } 11168 11169 /// \brief Given an overloaded function, tries to turn it into a non-overloaded 11170 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11171 /// will perform access checks, diagnose the use of the resultant decl, and, if 11172 /// necessary, perform a function-to-pointer decay. 11173 /// 11174 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11175 /// Otherwise, returns true. This may emit diagnostics and return true. 11176 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11177 ExprResult &SrcExpr) { 11178 Expr *E = SrcExpr.get(); 11179 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11180 11181 DeclAccessPair DAP; 11182 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11183 if (!Found) 11184 return false; 11185 11186 // Emitting multiple diagnostics for a function that is both inaccessible and 11187 // unavailable is consistent with our behavior elsewhere. So, always check 11188 // for both. 11189 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11190 CheckAddressOfMemberAccess(E, DAP); 11191 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11192 if (Fixed->getType()->isFunctionType()) 11193 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11194 else 11195 SrcExpr = Fixed; 11196 return true; 11197 } 11198 11199 /// \brief Given an expression that refers to an overloaded function, try to 11200 /// resolve that overloaded function expression down to a single function. 11201 /// 11202 /// This routine can only resolve template-ids that refer to a single function 11203 /// template, where that template-id refers to a single template whose template 11204 /// arguments are either provided by the template-id or have defaults, 11205 /// as described in C++0x [temp.arg.explicit]p3. 11206 /// 11207 /// If no template-ids are found, no diagnostics are emitted and NULL is 11208 /// returned. 11209 FunctionDecl * 11210 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11211 bool Complain, 11212 DeclAccessPair *FoundResult) { 11213 // C++ [over.over]p1: 11214 // [...] [Note: any redundant set of parentheses surrounding the 11215 // overloaded function name is ignored (5.1). ] 11216 // C++ [over.over]p1: 11217 // [...] The overloaded function name can be preceded by the & 11218 // operator. 11219 11220 // If we didn't actually find any template-ids, we're done. 11221 if (!ovl->hasExplicitTemplateArgs()) 11222 return nullptr; 11223 11224 TemplateArgumentListInfo ExplicitTemplateArgs; 11225 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11226 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11227 11228 // Look through all of the overloaded functions, searching for one 11229 // whose type matches exactly. 11230 FunctionDecl *Matched = nullptr; 11231 for (UnresolvedSetIterator I = ovl->decls_begin(), 11232 E = ovl->decls_end(); I != E; ++I) { 11233 // C++0x [temp.arg.explicit]p3: 11234 // [...] In contexts where deduction is done and fails, or in contexts 11235 // where deduction is not done, if a template argument list is 11236 // specified and it, along with any default template arguments, 11237 // identifies a single function template specialization, then the 11238 // template-id is an lvalue for the function template specialization. 11239 FunctionTemplateDecl *FunctionTemplate 11240 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11241 11242 // C++ [over.over]p2: 11243 // If the name is a function template, template argument deduction is 11244 // done (14.8.2.2), and if the argument deduction succeeds, the 11245 // resulting template argument list is used to generate a single 11246 // function template specialization, which is added to the set of 11247 // overloaded functions considered. 11248 FunctionDecl *Specialization = nullptr; 11249 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11250 if (TemplateDeductionResult Result 11251 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11252 Specialization, Info, 11253 /*IsAddressOfFunction*/true)) { 11254 // Make a note of the failed deduction for diagnostics. 11255 // TODO: Actually use the failed-deduction info? 11256 FailedCandidates.addCandidate() 11257 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11258 MakeDeductionFailureInfo(Context, Result, Info)); 11259 continue; 11260 } 11261 11262 assert(Specialization && "no specialization and no error?"); 11263 11264 // Multiple matches; we can't resolve to a single declaration. 11265 if (Matched) { 11266 if (Complain) { 11267 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11268 << ovl->getName(); 11269 NoteAllOverloadCandidates(ovl); 11270 } 11271 return nullptr; 11272 } 11273 11274 Matched = Specialization; 11275 if (FoundResult) *FoundResult = I.getPair(); 11276 } 11277 11278 if (Matched && 11279 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11280 return nullptr; 11281 11282 return Matched; 11283 } 11284 11285 11286 11287 11288 // Resolve and fix an overloaded expression that can be resolved 11289 // because it identifies a single function template specialization. 11290 // 11291 // Last three arguments should only be supplied if Complain = true 11292 // 11293 // Return true if it was logically possible to so resolve the 11294 // expression, regardless of whether or not it succeeded. Always 11295 // returns true if 'complain' is set. 11296 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11297 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11298 bool complain, SourceRange OpRangeForComplaining, 11299 QualType DestTypeForComplaining, 11300 unsigned DiagIDForComplaining) { 11301 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11302 11303 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11304 11305 DeclAccessPair found; 11306 ExprResult SingleFunctionExpression; 11307 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11308 ovl.Expression, /*complain*/ false, &found)) { 11309 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 11310 SrcExpr = ExprError(); 11311 return true; 11312 } 11313 11314 // It is only correct to resolve to an instance method if we're 11315 // resolving a form that's permitted to be a pointer to member. 11316 // Otherwise we'll end up making a bound member expression, which 11317 // is illegal in all the contexts we resolve like this. 11318 if (!ovl.HasFormOfMemberPointer && 11319 isa<CXXMethodDecl>(fn) && 11320 cast<CXXMethodDecl>(fn)->isInstance()) { 11321 if (!complain) return false; 11322 11323 Diag(ovl.Expression->getExprLoc(), 11324 diag::err_bound_member_function) 11325 << 0 << ovl.Expression->getSourceRange(); 11326 11327 // TODO: I believe we only end up here if there's a mix of 11328 // static and non-static candidates (otherwise the expression 11329 // would have 'bound member' type, not 'overload' type). 11330 // Ideally we would note which candidate was chosen and why 11331 // the static candidates were rejected. 11332 SrcExpr = ExprError(); 11333 return true; 11334 } 11335 11336 // Fix the expression to refer to 'fn'. 11337 SingleFunctionExpression = 11338 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11339 11340 // If desired, do function-to-pointer decay. 11341 if (doFunctionPointerConverion) { 11342 SingleFunctionExpression = 11343 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11344 if (SingleFunctionExpression.isInvalid()) { 11345 SrcExpr = ExprError(); 11346 return true; 11347 } 11348 } 11349 } 11350 11351 if (!SingleFunctionExpression.isUsable()) { 11352 if (complain) { 11353 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11354 << ovl.Expression->getName() 11355 << DestTypeForComplaining 11356 << OpRangeForComplaining 11357 << ovl.Expression->getQualifierLoc().getSourceRange(); 11358 NoteAllOverloadCandidates(SrcExpr.get()); 11359 11360 SrcExpr = ExprError(); 11361 return true; 11362 } 11363 11364 return false; 11365 } 11366 11367 SrcExpr = SingleFunctionExpression; 11368 return true; 11369 } 11370 11371 /// \brief Add a single candidate to the overload set. 11372 static void AddOverloadedCallCandidate(Sema &S, 11373 DeclAccessPair FoundDecl, 11374 TemplateArgumentListInfo *ExplicitTemplateArgs, 11375 ArrayRef<Expr *> Args, 11376 OverloadCandidateSet &CandidateSet, 11377 bool PartialOverloading, 11378 bool KnownValid) { 11379 NamedDecl *Callee = FoundDecl.getDecl(); 11380 if (isa<UsingShadowDecl>(Callee)) 11381 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11382 11383 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11384 if (ExplicitTemplateArgs) { 11385 assert(!KnownValid && "Explicit template arguments?"); 11386 return; 11387 } 11388 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11389 /*SuppressUsedConversions=*/false, 11390 PartialOverloading); 11391 return; 11392 } 11393 11394 if (FunctionTemplateDecl *FuncTemplate 11395 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11396 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11397 ExplicitTemplateArgs, Args, CandidateSet, 11398 /*SuppressUsedConversions=*/false, 11399 PartialOverloading); 11400 return; 11401 } 11402 11403 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11404 } 11405 11406 /// \brief Add the overload candidates named by callee and/or found by argument 11407 /// dependent lookup to the given overload set. 11408 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11409 ArrayRef<Expr *> Args, 11410 OverloadCandidateSet &CandidateSet, 11411 bool PartialOverloading) { 11412 11413 #ifndef NDEBUG 11414 // Verify that ArgumentDependentLookup is consistent with the rules 11415 // in C++0x [basic.lookup.argdep]p3: 11416 // 11417 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11418 // and let Y be the lookup set produced by argument dependent 11419 // lookup (defined as follows). If X contains 11420 // 11421 // -- a declaration of a class member, or 11422 // 11423 // -- a block-scope function declaration that is not a 11424 // using-declaration, or 11425 // 11426 // -- a declaration that is neither a function or a function 11427 // template 11428 // 11429 // then Y is empty. 11430 11431 if (ULE->requiresADL()) { 11432 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11433 E = ULE->decls_end(); I != E; ++I) { 11434 assert(!(*I)->getDeclContext()->isRecord()); 11435 assert(isa<UsingShadowDecl>(*I) || 11436 !(*I)->getDeclContext()->isFunctionOrMethod()); 11437 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11438 } 11439 } 11440 #endif 11441 11442 // It would be nice to avoid this copy. 11443 TemplateArgumentListInfo TABuffer; 11444 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11445 if (ULE->hasExplicitTemplateArgs()) { 11446 ULE->copyTemplateArgumentsInto(TABuffer); 11447 ExplicitTemplateArgs = &TABuffer; 11448 } 11449 11450 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11451 E = ULE->decls_end(); I != E; ++I) 11452 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11453 CandidateSet, PartialOverloading, 11454 /*KnownValid*/ true); 11455 11456 if (ULE->requiresADL()) 11457 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11458 Args, ExplicitTemplateArgs, 11459 CandidateSet, PartialOverloading); 11460 } 11461 11462 /// Determine whether a declaration with the specified name could be moved into 11463 /// a different namespace. 11464 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11465 switch (Name.getCXXOverloadedOperator()) { 11466 case OO_New: case OO_Array_New: 11467 case OO_Delete: case OO_Array_Delete: 11468 return false; 11469 11470 default: 11471 return true; 11472 } 11473 } 11474 11475 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11476 /// template, where the non-dependent name was declared after the template 11477 /// was defined. This is common in code written for a compilers which do not 11478 /// correctly implement two-stage name lookup. 11479 /// 11480 /// Returns true if a viable candidate was found and a diagnostic was issued. 11481 static bool 11482 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11483 const CXXScopeSpec &SS, LookupResult &R, 11484 OverloadCandidateSet::CandidateSetKind CSK, 11485 TemplateArgumentListInfo *ExplicitTemplateArgs, 11486 ArrayRef<Expr *> Args, 11487 bool *DoDiagnoseEmptyLookup = nullptr) { 11488 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 11489 return false; 11490 11491 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11492 if (DC->isTransparentContext()) 11493 continue; 11494 11495 SemaRef.LookupQualifiedName(R, DC); 11496 11497 if (!R.empty()) { 11498 R.suppressDiagnostics(); 11499 11500 if (isa<CXXRecordDecl>(DC)) { 11501 // Don't diagnose names we find in classes; we get much better 11502 // diagnostics for these from DiagnoseEmptyLookup. 11503 R.clear(); 11504 if (DoDiagnoseEmptyLookup) 11505 *DoDiagnoseEmptyLookup = true; 11506 return false; 11507 } 11508 11509 OverloadCandidateSet Candidates(FnLoc, CSK); 11510 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11511 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11512 ExplicitTemplateArgs, Args, 11513 Candidates, false, /*KnownValid*/ false); 11514 11515 OverloadCandidateSet::iterator Best; 11516 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11517 // No viable functions. Don't bother the user with notes for functions 11518 // which don't work and shouldn't be found anyway. 11519 R.clear(); 11520 return false; 11521 } 11522 11523 // Find the namespaces where ADL would have looked, and suggest 11524 // declaring the function there instead. 11525 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11526 Sema::AssociatedClassSet AssociatedClasses; 11527 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11528 AssociatedNamespaces, 11529 AssociatedClasses); 11530 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11531 if (canBeDeclaredInNamespace(R.getLookupName())) { 11532 DeclContext *Std = SemaRef.getStdNamespace(); 11533 for (Sema::AssociatedNamespaceSet::iterator 11534 it = AssociatedNamespaces.begin(), 11535 end = AssociatedNamespaces.end(); it != end; ++it) { 11536 // Never suggest declaring a function within namespace 'std'. 11537 if (Std && Std->Encloses(*it)) 11538 continue; 11539 11540 // Never suggest declaring a function within a namespace with a 11541 // reserved name, like __gnu_cxx. 11542 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11543 if (NS && 11544 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11545 continue; 11546 11547 SuggestedNamespaces.insert(*it); 11548 } 11549 } 11550 11551 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11552 << R.getLookupName(); 11553 if (SuggestedNamespaces.empty()) { 11554 SemaRef.Diag(Best->Function->getLocation(), 11555 diag::note_not_found_by_two_phase_lookup) 11556 << R.getLookupName() << 0; 11557 } else if (SuggestedNamespaces.size() == 1) { 11558 SemaRef.Diag(Best->Function->getLocation(), 11559 diag::note_not_found_by_two_phase_lookup) 11560 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11561 } else { 11562 // FIXME: It would be useful to list the associated namespaces here, 11563 // but the diagnostics infrastructure doesn't provide a way to produce 11564 // a localized representation of a list of items. 11565 SemaRef.Diag(Best->Function->getLocation(), 11566 diag::note_not_found_by_two_phase_lookup) 11567 << R.getLookupName() << 2; 11568 } 11569 11570 // Try to recover by calling this function. 11571 return true; 11572 } 11573 11574 R.clear(); 11575 } 11576 11577 return false; 11578 } 11579 11580 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11581 /// template, where the non-dependent operator was declared after the template 11582 /// was defined. 11583 /// 11584 /// Returns true if a viable candidate was found and a diagnostic was issued. 11585 static bool 11586 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11587 SourceLocation OpLoc, 11588 ArrayRef<Expr *> Args) { 11589 DeclarationName OpName = 11590 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11591 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11592 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11593 OverloadCandidateSet::CSK_Operator, 11594 /*ExplicitTemplateArgs=*/nullptr, Args); 11595 } 11596 11597 namespace { 11598 class BuildRecoveryCallExprRAII { 11599 Sema &SemaRef; 11600 public: 11601 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11602 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11603 SemaRef.IsBuildingRecoveryCallExpr = true; 11604 } 11605 11606 ~BuildRecoveryCallExprRAII() { 11607 SemaRef.IsBuildingRecoveryCallExpr = false; 11608 } 11609 }; 11610 11611 } 11612 11613 static std::unique_ptr<CorrectionCandidateCallback> 11614 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11615 bool HasTemplateArgs, bool AllowTypoCorrection) { 11616 if (!AllowTypoCorrection) 11617 return llvm::make_unique<NoTypoCorrectionCCC>(); 11618 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11619 HasTemplateArgs, ME); 11620 } 11621 11622 /// Attempts to recover from a call where no functions were found. 11623 /// 11624 /// Returns true if new candidates were found. 11625 static ExprResult 11626 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11627 UnresolvedLookupExpr *ULE, 11628 SourceLocation LParenLoc, 11629 MutableArrayRef<Expr *> Args, 11630 SourceLocation RParenLoc, 11631 bool EmptyLookup, bool AllowTypoCorrection) { 11632 // Do not try to recover if it is already building a recovery call. 11633 // This stops infinite loops for template instantiations like 11634 // 11635 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11636 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11637 // 11638 if (SemaRef.IsBuildingRecoveryCallExpr) 11639 return ExprError(); 11640 BuildRecoveryCallExprRAII RCE(SemaRef); 11641 11642 CXXScopeSpec SS; 11643 SS.Adopt(ULE->getQualifierLoc()); 11644 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11645 11646 TemplateArgumentListInfo TABuffer; 11647 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11648 if (ULE->hasExplicitTemplateArgs()) { 11649 ULE->copyTemplateArgumentsInto(TABuffer); 11650 ExplicitTemplateArgs = &TABuffer; 11651 } 11652 11653 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11654 Sema::LookupOrdinaryName); 11655 bool DoDiagnoseEmptyLookup = EmptyLookup; 11656 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11657 OverloadCandidateSet::CSK_Normal, 11658 ExplicitTemplateArgs, Args, 11659 &DoDiagnoseEmptyLookup) && 11660 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11661 S, SS, R, 11662 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11663 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11664 ExplicitTemplateArgs, Args))) 11665 return ExprError(); 11666 11667 assert(!R.empty() && "lookup results empty despite recovery"); 11668 11669 // If recovery created an ambiguity, just bail out. 11670 if (R.isAmbiguous()) { 11671 R.suppressDiagnostics(); 11672 return ExprError(); 11673 } 11674 11675 // Build an implicit member call if appropriate. Just drop the 11676 // casts and such from the call, we don't really care. 11677 ExprResult NewFn = ExprError(); 11678 if ((*R.begin())->isCXXClassMember()) 11679 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11680 ExplicitTemplateArgs, S); 11681 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11682 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11683 ExplicitTemplateArgs); 11684 else 11685 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11686 11687 if (NewFn.isInvalid()) 11688 return ExprError(); 11689 11690 // This shouldn't cause an infinite loop because we're giving it 11691 // an expression with viable lookup results, which should never 11692 // end up here. 11693 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11694 MultiExprArg(Args.data(), Args.size()), 11695 RParenLoc); 11696 } 11697 11698 /// \brief Constructs and populates an OverloadedCandidateSet from 11699 /// the given function. 11700 /// \returns true when an the ExprResult output parameter has been set. 11701 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11702 UnresolvedLookupExpr *ULE, 11703 MultiExprArg Args, 11704 SourceLocation RParenLoc, 11705 OverloadCandidateSet *CandidateSet, 11706 ExprResult *Result) { 11707 #ifndef NDEBUG 11708 if (ULE->requiresADL()) { 11709 // To do ADL, we must have found an unqualified name. 11710 assert(!ULE->getQualifier() && "qualified name with ADL"); 11711 11712 // We don't perform ADL for implicit declarations of builtins. 11713 // Verify that this was correctly set up. 11714 FunctionDecl *F; 11715 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11716 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11717 F->getBuiltinID() && F->isImplicit()) 11718 llvm_unreachable("performing ADL for builtin"); 11719 11720 // We don't perform ADL in C. 11721 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11722 } 11723 #endif 11724 11725 UnbridgedCastsSet UnbridgedCasts; 11726 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11727 *Result = ExprError(); 11728 return true; 11729 } 11730 11731 // Add the functions denoted by the callee to the set of candidate 11732 // functions, including those from argument-dependent lookup. 11733 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11734 11735 if (getLangOpts().MSVCCompat && 11736 CurContext->isDependentContext() && !isSFINAEContext() && 11737 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11738 11739 OverloadCandidateSet::iterator Best; 11740 if (CandidateSet->empty() || 11741 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11742 OR_No_Viable_Function) { 11743 // In Microsoft mode, if we are inside a template class member function then 11744 // create a type dependent CallExpr. The goal is to postpone name lookup 11745 // to instantiation time to be able to search into type dependent base 11746 // classes. 11747 CallExpr *CE = new (Context) CallExpr( 11748 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11749 CE->setTypeDependent(true); 11750 CE->setValueDependent(true); 11751 CE->setInstantiationDependent(true); 11752 *Result = CE; 11753 return true; 11754 } 11755 } 11756 11757 if (CandidateSet->empty()) 11758 return false; 11759 11760 UnbridgedCasts.restore(); 11761 return false; 11762 } 11763 11764 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11765 /// the completed call expression. If overload resolution fails, emits 11766 /// diagnostics and returns ExprError() 11767 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11768 UnresolvedLookupExpr *ULE, 11769 SourceLocation LParenLoc, 11770 MultiExprArg Args, 11771 SourceLocation RParenLoc, 11772 Expr *ExecConfig, 11773 OverloadCandidateSet *CandidateSet, 11774 OverloadCandidateSet::iterator *Best, 11775 OverloadingResult OverloadResult, 11776 bool AllowTypoCorrection) { 11777 if (CandidateSet->empty()) 11778 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11779 RParenLoc, /*EmptyLookup=*/true, 11780 AllowTypoCorrection); 11781 11782 switch (OverloadResult) { 11783 case OR_Success: { 11784 FunctionDecl *FDecl = (*Best)->Function; 11785 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11786 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11787 return ExprError(); 11788 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11789 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11790 ExecConfig); 11791 } 11792 11793 case OR_No_Viable_Function: { 11794 // Try to recover by looking for viable functions which the user might 11795 // have meant to call. 11796 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11797 Args, RParenLoc, 11798 /*EmptyLookup=*/false, 11799 AllowTypoCorrection); 11800 if (!Recovery.isInvalid()) 11801 return Recovery; 11802 11803 // If the user passes in a function that we can't take the address of, we 11804 // generally end up emitting really bad error messages. Here, we attempt to 11805 // emit better ones. 11806 for (const Expr *Arg : Args) { 11807 if (!Arg->getType()->isFunctionType()) 11808 continue; 11809 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11810 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11811 if (FD && 11812 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11813 Arg->getExprLoc())) 11814 return ExprError(); 11815 } 11816 } 11817 11818 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11819 << ULE->getName() << Fn->getSourceRange(); 11820 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11821 break; 11822 } 11823 11824 case OR_Ambiguous: 11825 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11826 << ULE->getName() << Fn->getSourceRange(); 11827 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11828 break; 11829 11830 case OR_Deleted: { 11831 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11832 << (*Best)->Function->isDeleted() 11833 << ULE->getName() 11834 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11835 << Fn->getSourceRange(); 11836 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11837 11838 // We emitted an error for the unvailable/deleted function call but keep 11839 // the call in the AST. 11840 FunctionDecl *FDecl = (*Best)->Function; 11841 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11842 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11843 ExecConfig); 11844 } 11845 } 11846 11847 // Overload resolution failed. 11848 return ExprError(); 11849 } 11850 11851 static void markUnaddressableCandidatesUnviable(Sema &S, 11852 OverloadCandidateSet &CS) { 11853 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11854 if (I->Viable && 11855 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11856 I->Viable = false; 11857 I->FailureKind = ovl_fail_addr_not_available; 11858 } 11859 } 11860 } 11861 11862 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11863 /// (which eventually refers to the declaration Func) and the call 11864 /// arguments Args/NumArgs, attempt to resolve the function call down 11865 /// to a specific function. If overload resolution succeeds, returns 11866 /// the call expression produced by overload resolution. 11867 /// Otherwise, emits diagnostics and returns ExprError. 11868 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11869 UnresolvedLookupExpr *ULE, 11870 SourceLocation LParenLoc, 11871 MultiExprArg Args, 11872 SourceLocation RParenLoc, 11873 Expr *ExecConfig, 11874 bool AllowTypoCorrection, 11875 bool CalleesAddressIsTaken) { 11876 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11877 OverloadCandidateSet::CSK_Normal); 11878 ExprResult result; 11879 11880 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11881 &result)) 11882 return result; 11883 11884 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11885 // functions that aren't addressible are considered unviable. 11886 if (CalleesAddressIsTaken) 11887 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11888 11889 OverloadCandidateSet::iterator Best; 11890 OverloadingResult OverloadResult = 11891 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11892 11893 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11894 RParenLoc, ExecConfig, &CandidateSet, 11895 &Best, OverloadResult, 11896 AllowTypoCorrection); 11897 } 11898 11899 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11900 return Functions.size() > 1 || 11901 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11902 } 11903 11904 /// \brief Create a unary operation that may resolve to an overloaded 11905 /// operator. 11906 /// 11907 /// \param OpLoc The location of the operator itself (e.g., '*'). 11908 /// 11909 /// \param Opc The UnaryOperatorKind that describes this operator. 11910 /// 11911 /// \param Fns The set of non-member functions that will be 11912 /// considered by overload resolution. The caller needs to build this 11913 /// set based on the context using, e.g., 11914 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11915 /// set should not contain any member functions; those will be added 11916 /// by CreateOverloadedUnaryOp(). 11917 /// 11918 /// \param Input The input argument. 11919 ExprResult 11920 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11921 const UnresolvedSetImpl &Fns, 11922 Expr *Input) { 11923 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11924 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11925 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11926 // TODO: provide better source location info. 11927 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11928 11929 if (checkPlaceholderForOverload(*this, Input)) 11930 return ExprError(); 11931 11932 Expr *Args[2] = { Input, nullptr }; 11933 unsigned NumArgs = 1; 11934 11935 // For post-increment and post-decrement, add the implicit '0' as 11936 // the second argument, so that we know this is a post-increment or 11937 // post-decrement. 11938 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11939 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11940 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11941 SourceLocation()); 11942 NumArgs = 2; 11943 } 11944 11945 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11946 11947 if (Input->isTypeDependent()) { 11948 if (Fns.empty()) 11949 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11950 VK_RValue, OK_Ordinary, OpLoc); 11951 11952 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11953 UnresolvedLookupExpr *Fn 11954 = UnresolvedLookupExpr::Create(Context, NamingClass, 11955 NestedNameSpecifierLoc(), OpNameInfo, 11956 /*ADL*/ true, IsOverloaded(Fns), 11957 Fns.begin(), Fns.end()); 11958 return new (Context) 11959 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11960 VK_RValue, OpLoc, false); 11961 } 11962 11963 // Build an empty overload set. 11964 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11965 11966 // Add the candidates from the given function set. 11967 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11968 11969 // Add operator candidates that are member functions. 11970 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11971 11972 // Add candidates from ADL. 11973 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11974 /*ExplicitTemplateArgs*/nullptr, 11975 CandidateSet); 11976 11977 // Add builtin operator candidates. 11978 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11979 11980 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11981 11982 // Perform overload resolution. 11983 OverloadCandidateSet::iterator Best; 11984 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11985 case OR_Success: { 11986 // We found a built-in operator or an overloaded operator. 11987 FunctionDecl *FnDecl = Best->Function; 11988 11989 if (FnDecl) { 11990 // We matched an overloaded operator. Build a call to that 11991 // operator. 11992 11993 // Convert the arguments. 11994 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11995 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11996 11997 ExprResult InputRes = 11998 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11999 Best->FoundDecl, Method); 12000 if (InputRes.isInvalid()) 12001 return ExprError(); 12002 Input = InputRes.get(); 12003 } else { 12004 // Convert the arguments. 12005 ExprResult InputInit 12006 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12007 Context, 12008 FnDecl->getParamDecl(0)), 12009 SourceLocation(), 12010 Input); 12011 if (InputInit.isInvalid()) 12012 return ExprError(); 12013 Input = InputInit.get(); 12014 } 12015 12016 // Build the actual expression node. 12017 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12018 HadMultipleCandidates, OpLoc); 12019 if (FnExpr.isInvalid()) 12020 return ExprError(); 12021 12022 // Determine the result type. 12023 QualType ResultTy = FnDecl->getReturnType(); 12024 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12025 ResultTy = ResultTy.getNonLValueExprType(Context); 12026 12027 Args[0] = Input; 12028 CallExpr *TheCall = 12029 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 12030 ResultTy, VK, OpLoc, false); 12031 12032 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12033 return ExprError(); 12034 12035 if (CheckFunctionCall(FnDecl, TheCall, 12036 FnDecl->getType()->castAs<FunctionProtoType>())) 12037 return ExprError(); 12038 12039 return MaybeBindToTemporary(TheCall); 12040 } else { 12041 // We matched a built-in operator. Convert the arguments, then 12042 // break out so that we will build the appropriate built-in 12043 // operator node. 12044 ExprResult InputRes = 12045 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 12046 Best->Conversions[0], AA_Passing); 12047 if (InputRes.isInvalid()) 12048 return ExprError(); 12049 Input = InputRes.get(); 12050 break; 12051 } 12052 } 12053 12054 case OR_No_Viable_Function: 12055 // This is an erroneous use of an operator which can be overloaded by 12056 // a non-member function. Check for non-member operators which were 12057 // defined too late to be candidates. 12058 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12059 // FIXME: Recover by calling the found function. 12060 return ExprError(); 12061 12062 // No viable function; fall through to handling this as a 12063 // built-in operator, which will produce an error message for us. 12064 break; 12065 12066 case OR_Ambiguous: 12067 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12068 << UnaryOperator::getOpcodeStr(Opc) 12069 << Input->getType() 12070 << Input->getSourceRange(); 12071 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 12072 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12073 return ExprError(); 12074 12075 case OR_Deleted: 12076 Diag(OpLoc, diag::err_ovl_deleted_oper) 12077 << Best->Function->isDeleted() 12078 << UnaryOperator::getOpcodeStr(Opc) 12079 << getDeletedOrUnavailableSuffix(Best->Function) 12080 << Input->getSourceRange(); 12081 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 12082 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12083 return ExprError(); 12084 } 12085 12086 // Either we found no viable overloaded operator or we matched a 12087 // built-in operator. In either case, fall through to trying to 12088 // build a built-in operation. 12089 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12090 } 12091 12092 /// \brief Create a binary operation that may resolve to an overloaded 12093 /// operator. 12094 /// 12095 /// \param OpLoc The location of the operator itself (e.g., '+'). 12096 /// 12097 /// \param Opc The BinaryOperatorKind that describes this operator. 12098 /// 12099 /// \param Fns The set of non-member functions that will be 12100 /// considered by overload resolution. The caller needs to build this 12101 /// set based on the context using, e.g., 12102 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12103 /// set should not contain any member functions; those will be added 12104 /// by CreateOverloadedBinOp(). 12105 /// 12106 /// \param LHS Left-hand argument. 12107 /// \param RHS Right-hand argument. 12108 ExprResult 12109 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12110 BinaryOperatorKind Opc, 12111 const UnresolvedSetImpl &Fns, 12112 Expr *LHS, Expr *RHS) { 12113 Expr *Args[2] = { LHS, RHS }; 12114 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12115 12116 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12117 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12118 12119 // If either side is type-dependent, create an appropriate dependent 12120 // expression. 12121 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12122 if (Fns.empty()) { 12123 // If there are no functions to store, just build a dependent 12124 // BinaryOperator or CompoundAssignment. 12125 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12126 return new (Context) BinaryOperator( 12127 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12128 OpLoc, FPFeatures.fp_contract); 12129 12130 return new (Context) CompoundAssignOperator( 12131 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12132 Context.DependentTy, Context.DependentTy, OpLoc, 12133 FPFeatures.fp_contract); 12134 } 12135 12136 // FIXME: save results of ADL from here? 12137 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12138 // TODO: provide better source location info in DNLoc component. 12139 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12140 UnresolvedLookupExpr *Fn 12141 = UnresolvedLookupExpr::Create(Context, NamingClass, 12142 NestedNameSpecifierLoc(), OpNameInfo, 12143 /*ADL*/ true, IsOverloaded(Fns), 12144 Fns.begin(), Fns.end()); 12145 return new (Context) 12146 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 12147 VK_RValue, OpLoc, FPFeatures.fp_contract); 12148 } 12149 12150 // Always do placeholder-like conversions on the RHS. 12151 if (checkPlaceholderForOverload(*this, Args[1])) 12152 return ExprError(); 12153 12154 // Do placeholder-like conversion on the LHS; note that we should 12155 // not get here with a PseudoObject LHS. 12156 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12157 if (checkPlaceholderForOverload(*this, Args[0])) 12158 return ExprError(); 12159 12160 // If this is the assignment operator, we only perform overload resolution 12161 // if the left-hand side is a class or enumeration type. This is actually 12162 // a hack. The standard requires that we do overload resolution between the 12163 // various built-in candidates, but as DR507 points out, this can lead to 12164 // problems. So we do it this way, which pretty much follows what GCC does. 12165 // Note that we go the traditional code path for compound assignment forms. 12166 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12167 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12168 12169 // If this is the .* operator, which is not overloadable, just 12170 // create a built-in binary operator. 12171 if (Opc == BO_PtrMemD) 12172 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12173 12174 // Build an empty overload set. 12175 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12176 12177 // Add the candidates from the given function set. 12178 AddFunctionCandidates(Fns, Args, CandidateSet); 12179 12180 // Add operator candidates that are member functions. 12181 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12182 12183 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12184 // performed for an assignment operator (nor for operator[] nor operator->, 12185 // which don't get here). 12186 if (Opc != BO_Assign) 12187 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12188 /*ExplicitTemplateArgs*/ nullptr, 12189 CandidateSet); 12190 12191 // Add builtin operator candidates. 12192 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12193 12194 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12195 12196 // Perform overload resolution. 12197 OverloadCandidateSet::iterator Best; 12198 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12199 case OR_Success: { 12200 // We found a built-in operator or an overloaded operator. 12201 FunctionDecl *FnDecl = Best->Function; 12202 12203 if (FnDecl) { 12204 // We matched an overloaded operator. Build a call to that 12205 // operator. 12206 12207 // Convert the arguments. 12208 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12209 // Best->Access is only meaningful for class members. 12210 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12211 12212 ExprResult Arg1 = 12213 PerformCopyInitialization( 12214 InitializedEntity::InitializeParameter(Context, 12215 FnDecl->getParamDecl(0)), 12216 SourceLocation(), Args[1]); 12217 if (Arg1.isInvalid()) 12218 return ExprError(); 12219 12220 ExprResult Arg0 = 12221 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12222 Best->FoundDecl, Method); 12223 if (Arg0.isInvalid()) 12224 return ExprError(); 12225 Args[0] = Arg0.getAs<Expr>(); 12226 Args[1] = RHS = Arg1.getAs<Expr>(); 12227 } else { 12228 // Convert the arguments. 12229 ExprResult Arg0 = PerformCopyInitialization( 12230 InitializedEntity::InitializeParameter(Context, 12231 FnDecl->getParamDecl(0)), 12232 SourceLocation(), Args[0]); 12233 if (Arg0.isInvalid()) 12234 return ExprError(); 12235 12236 ExprResult Arg1 = 12237 PerformCopyInitialization( 12238 InitializedEntity::InitializeParameter(Context, 12239 FnDecl->getParamDecl(1)), 12240 SourceLocation(), Args[1]); 12241 if (Arg1.isInvalid()) 12242 return ExprError(); 12243 Args[0] = LHS = Arg0.getAs<Expr>(); 12244 Args[1] = RHS = Arg1.getAs<Expr>(); 12245 } 12246 12247 // Build the actual expression node. 12248 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12249 Best->FoundDecl, 12250 HadMultipleCandidates, OpLoc); 12251 if (FnExpr.isInvalid()) 12252 return ExprError(); 12253 12254 // Determine the result type. 12255 QualType ResultTy = FnDecl->getReturnType(); 12256 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12257 ResultTy = ResultTy.getNonLValueExprType(Context); 12258 12259 CXXOperatorCallExpr *TheCall = 12260 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 12261 Args, ResultTy, VK, OpLoc, 12262 FPFeatures.fp_contract); 12263 12264 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12265 FnDecl)) 12266 return ExprError(); 12267 12268 ArrayRef<const Expr *> ArgsArray(Args, 2); 12269 const Expr *ImplicitThis = nullptr; 12270 // Cut off the implicit 'this'. 12271 if (isa<CXXMethodDecl>(FnDecl)) { 12272 ImplicitThis = ArgsArray[0]; 12273 ArgsArray = ArgsArray.slice(1); 12274 } 12275 12276 // Check for a self move. 12277 if (Op == OO_Equal) 12278 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12279 12280 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12281 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12282 VariadicDoesNotApply); 12283 12284 return MaybeBindToTemporary(TheCall); 12285 } else { 12286 // We matched a built-in operator. Convert the arguments, then 12287 // break out so that we will build the appropriate built-in 12288 // operator node. 12289 ExprResult ArgsRes0 = 12290 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12291 Best->Conversions[0], AA_Passing); 12292 if (ArgsRes0.isInvalid()) 12293 return ExprError(); 12294 Args[0] = ArgsRes0.get(); 12295 12296 ExprResult ArgsRes1 = 12297 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12298 Best->Conversions[1], AA_Passing); 12299 if (ArgsRes1.isInvalid()) 12300 return ExprError(); 12301 Args[1] = ArgsRes1.get(); 12302 break; 12303 } 12304 } 12305 12306 case OR_No_Viable_Function: { 12307 // C++ [over.match.oper]p9: 12308 // If the operator is the operator , [...] and there are no 12309 // viable functions, then the operator is assumed to be the 12310 // built-in operator and interpreted according to clause 5. 12311 if (Opc == BO_Comma) 12312 break; 12313 12314 // For class as left operand for assignment or compound assigment 12315 // operator do not fall through to handling in built-in, but report that 12316 // no overloaded assignment operator found 12317 ExprResult Result = ExprError(); 12318 if (Args[0]->getType()->isRecordType() && 12319 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12320 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12321 << BinaryOperator::getOpcodeStr(Opc) 12322 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12323 if (Args[0]->getType()->isIncompleteType()) { 12324 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12325 << Args[0]->getType() 12326 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12327 } 12328 } else { 12329 // This is an erroneous use of an operator which can be overloaded by 12330 // a non-member function. Check for non-member operators which were 12331 // defined too late to be candidates. 12332 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12333 // FIXME: Recover by calling the found function. 12334 return ExprError(); 12335 12336 // No viable function; try to create a built-in operation, which will 12337 // produce an error. Then, show the non-viable candidates. 12338 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12339 } 12340 assert(Result.isInvalid() && 12341 "C++ binary operator overloading is missing candidates!"); 12342 if (Result.isInvalid()) 12343 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12344 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12345 return Result; 12346 } 12347 12348 case OR_Ambiguous: 12349 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12350 << BinaryOperator::getOpcodeStr(Opc) 12351 << Args[0]->getType() << Args[1]->getType() 12352 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12353 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12354 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12355 return ExprError(); 12356 12357 case OR_Deleted: 12358 if (isImplicitlyDeleted(Best->Function)) { 12359 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12360 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12361 << Context.getRecordType(Method->getParent()) 12362 << getSpecialMember(Method); 12363 12364 // The user probably meant to call this special member. Just 12365 // explain why it's deleted. 12366 NoteDeletedFunction(Method); 12367 return ExprError(); 12368 } else { 12369 Diag(OpLoc, diag::err_ovl_deleted_oper) 12370 << Best->Function->isDeleted() 12371 << BinaryOperator::getOpcodeStr(Opc) 12372 << getDeletedOrUnavailableSuffix(Best->Function) 12373 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12374 } 12375 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12376 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12377 return ExprError(); 12378 } 12379 12380 // We matched a built-in operator; build it. 12381 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12382 } 12383 12384 ExprResult 12385 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12386 SourceLocation RLoc, 12387 Expr *Base, Expr *Idx) { 12388 Expr *Args[2] = { Base, Idx }; 12389 DeclarationName OpName = 12390 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12391 12392 // If either side is type-dependent, create an appropriate dependent 12393 // expression. 12394 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12395 12396 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12397 // CHECKME: no 'operator' keyword? 12398 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12399 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12400 UnresolvedLookupExpr *Fn 12401 = UnresolvedLookupExpr::Create(Context, NamingClass, 12402 NestedNameSpecifierLoc(), OpNameInfo, 12403 /*ADL*/ true, /*Overloaded*/ false, 12404 UnresolvedSetIterator(), 12405 UnresolvedSetIterator()); 12406 // Can't add any actual overloads yet 12407 12408 return new (Context) 12409 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12410 Context.DependentTy, VK_RValue, RLoc, false); 12411 } 12412 12413 // Handle placeholders on both operands. 12414 if (checkPlaceholderForOverload(*this, Args[0])) 12415 return ExprError(); 12416 if (checkPlaceholderForOverload(*this, Args[1])) 12417 return ExprError(); 12418 12419 // Build an empty overload set. 12420 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12421 12422 // Subscript can only be overloaded as a member function. 12423 12424 // Add operator candidates that are member functions. 12425 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12426 12427 // Add builtin operator candidates. 12428 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12429 12430 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12431 12432 // Perform overload resolution. 12433 OverloadCandidateSet::iterator Best; 12434 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12435 case OR_Success: { 12436 // We found a built-in operator or an overloaded operator. 12437 FunctionDecl *FnDecl = Best->Function; 12438 12439 if (FnDecl) { 12440 // We matched an overloaded operator. Build a call to that 12441 // operator. 12442 12443 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12444 12445 // Convert the arguments. 12446 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12447 ExprResult Arg0 = 12448 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12449 Best->FoundDecl, Method); 12450 if (Arg0.isInvalid()) 12451 return ExprError(); 12452 Args[0] = Arg0.get(); 12453 12454 // Convert the arguments. 12455 ExprResult InputInit 12456 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12457 Context, 12458 FnDecl->getParamDecl(0)), 12459 SourceLocation(), 12460 Args[1]); 12461 if (InputInit.isInvalid()) 12462 return ExprError(); 12463 12464 Args[1] = InputInit.getAs<Expr>(); 12465 12466 // Build the actual expression node. 12467 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12468 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12469 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12470 Best->FoundDecl, 12471 HadMultipleCandidates, 12472 OpLocInfo.getLoc(), 12473 OpLocInfo.getInfo()); 12474 if (FnExpr.isInvalid()) 12475 return ExprError(); 12476 12477 // Determine the result type 12478 QualType ResultTy = FnDecl->getReturnType(); 12479 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12480 ResultTy = ResultTy.getNonLValueExprType(Context); 12481 12482 CXXOperatorCallExpr *TheCall = 12483 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12484 FnExpr.get(), Args, 12485 ResultTy, VK, RLoc, 12486 false); 12487 12488 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12489 return ExprError(); 12490 12491 if (CheckFunctionCall(Method, TheCall, 12492 Method->getType()->castAs<FunctionProtoType>())) 12493 return ExprError(); 12494 12495 return MaybeBindToTemporary(TheCall); 12496 } else { 12497 // We matched a built-in operator. Convert the arguments, then 12498 // break out so that we will build the appropriate built-in 12499 // operator node. 12500 ExprResult ArgsRes0 = 12501 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12502 Best->Conversions[0], AA_Passing); 12503 if (ArgsRes0.isInvalid()) 12504 return ExprError(); 12505 Args[0] = ArgsRes0.get(); 12506 12507 ExprResult ArgsRes1 = 12508 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12509 Best->Conversions[1], AA_Passing); 12510 if (ArgsRes1.isInvalid()) 12511 return ExprError(); 12512 Args[1] = ArgsRes1.get(); 12513 12514 break; 12515 } 12516 } 12517 12518 case OR_No_Viable_Function: { 12519 if (CandidateSet.empty()) 12520 Diag(LLoc, diag::err_ovl_no_oper) 12521 << Args[0]->getType() << /*subscript*/ 0 12522 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12523 else 12524 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12525 << Args[0]->getType() 12526 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12527 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12528 "[]", LLoc); 12529 return ExprError(); 12530 } 12531 12532 case OR_Ambiguous: 12533 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12534 << "[]" 12535 << Args[0]->getType() << Args[1]->getType() 12536 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12537 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12538 "[]", LLoc); 12539 return ExprError(); 12540 12541 case OR_Deleted: 12542 Diag(LLoc, diag::err_ovl_deleted_oper) 12543 << Best->Function->isDeleted() << "[]" 12544 << getDeletedOrUnavailableSuffix(Best->Function) 12545 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12546 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12547 "[]", LLoc); 12548 return ExprError(); 12549 } 12550 12551 // We matched a built-in operator; build it. 12552 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12553 } 12554 12555 /// BuildCallToMemberFunction - Build a call to a member 12556 /// function. MemExpr is the expression that refers to the member 12557 /// function (and includes the object parameter), Args/NumArgs are the 12558 /// arguments to the function call (not including the object 12559 /// parameter). The caller needs to validate that the member 12560 /// expression refers to a non-static member function or an overloaded 12561 /// member function. 12562 ExprResult 12563 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12564 SourceLocation LParenLoc, 12565 MultiExprArg Args, 12566 SourceLocation RParenLoc) { 12567 assert(MemExprE->getType() == Context.BoundMemberTy || 12568 MemExprE->getType() == Context.OverloadTy); 12569 12570 // Dig out the member expression. This holds both the object 12571 // argument and the member function we're referring to. 12572 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12573 12574 // Determine whether this is a call to a pointer-to-member function. 12575 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12576 assert(op->getType() == Context.BoundMemberTy); 12577 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12578 12579 QualType fnType = 12580 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12581 12582 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12583 QualType resultType = proto->getCallResultType(Context); 12584 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12585 12586 // Check that the object type isn't more qualified than the 12587 // member function we're calling. 12588 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12589 12590 QualType objectType = op->getLHS()->getType(); 12591 if (op->getOpcode() == BO_PtrMemI) 12592 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12593 Qualifiers objectQuals = objectType.getQualifiers(); 12594 12595 Qualifiers difference = objectQuals - funcQuals; 12596 difference.removeObjCGCAttr(); 12597 difference.removeAddressSpace(); 12598 if (difference) { 12599 std::string qualsString = difference.getAsString(); 12600 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12601 << fnType.getUnqualifiedType() 12602 << qualsString 12603 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12604 } 12605 12606 CXXMemberCallExpr *call 12607 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12608 resultType, valueKind, RParenLoc); 12609 12610 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12611 call, nullptr)) 12612 return ExprError(); 12613 12614 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12615 return ExprError(); 12616 12617 if (CheckOtherCall(call, proto)) 12618 return ExprError(); 12619 12620 return MaybeBindToTemporary(call); 12621 } 12622 12623 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12624 return new (Context) 12625 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12626 12627 UnbridgedCastsSet UnbridgedCasts; 12628 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12629 return ExprError(); 12630 12631 MemberExpr *MemExpr; 12632 CXXMethodDecl *Method = nullptr; 12633 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12634 NestedNameSpecifier *Qualifier = nullptr; 12635 if (isa<MemberExpr>(NakedMemExpr)) { 12636 MemExpr = cast<MemberExpr>(NakedMemExpr); 12637 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12638 FoundDecl = MemExpr->getFoundDecl(); 12639 Qualifier = MemExpr->getQualifier(); 12640 UnbridgedCasts.restore(); 12641 } else { 12642 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12643 Qualifier = UnresExpr->getQualifier(); 12644 12645 QualType ObjectType = UnresExpr->getBaseType(); 12646 Expr::Classification ObjectClassification 12647 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12648 : UnresExpr->getBase()->Classify(Context); 12649 12650 // Add overload candidates 12651 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12652 OverloadCandidateSet::CSK_Normal); 12653 12654 // FIXME: avoid copy. 12655 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12656 if (UnresExpr->hasExplicitTemplateArgs()) { 12657 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12658 TemplateArgs = &TemplateArgsBuffer; 12659 } 12660 12661 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12662 E = UnresExpr->decls_end(); I != E; ++I) { 12663 12664 NamedDecl *Func = *I; 12665 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12666 if (isa<UsingShadowDecl>(Func)) 12667 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12668 12669 12670 // Microsoft supports direct constructor calls. 12671 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12672 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12673 Args, CandidateSet); 12674 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12675 // If explicit template arguments were provided, we can't call a 12676 // non-template member function. 12677 if (TemplateArgs) 12678 continue; 12679 12680 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12681 ObjectClassification, Args, CandidateSet, 12682 /*SuppressUserConversions=*/false); 12683 } else { 12684 AddMethodTemplateCandidate( 12685 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 12686 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 12687 /*SuppressUsedConversions=*/false); 12688 } 12689 } 12690 12691 DeclarationName DeclName = UnresExpr->getMemberName(); 12692 12693 UnbridgedCasts.restore(); 12694 12695 OverloadCandidateSet::iterator Best; 12696 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12697 Best)) { 12698 case OR_Success: 12699 Method = cast<CXXMethodDecl>(Best->Function); 12700 FoundDecl = Best->FoundDecl; 12701 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12702 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12703 return ExprError(); 12704 // If FoundDecl is different from Method (such as if one is a template 12705 // and the other a specialization), make sure DiagnoseUseOfDecl is 12706 // called on both. 12707 // FIXME: This would be more comprehensively addressed by modifying 12708 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12709 // being used. 12710 if (Method != FoundDecl.getDecl() && 12711 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12712 return ExprError(); 12713 break; 12714 12715 case OR_No_Viable_Function: 12716 Diag(UnresExpr->getMemberLoc(), 12717 diag::err_ovl_no_viable_member_function_in_call) 12718 << DeclName << MemExprE->getSourceRange(); 12719 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12720 // FIXME: Leaking incoming expressions! 12721 return ExprError(); 12722 12723 case OR_Ambiguous: 12724 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12725 << DeclName << MemExprE->getSourceRange(); 12726 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12727 // FIXME: Leaking incoming expressions! 12728 return ExprError(); 12729 12730 case OR_Deleted: 12731 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12732 << Best->Function->isDeleted() 12733 << DeclName 12734 << getDeletedOrUnavailableSuffix(Best->Function) 12735 << MemExprE->getSourceRange(); 12736 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12737 // FIXME: Leaking incoming expressions! 12738 return ExprError(); 12739 } 12740 12741 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12742 12743 // If overload resolution picked a static member, build a 12744 // non-member call based on that function. 12745 if (Method->isStatic()) { 12746 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12747 RParenLoc); 12748 } 12749 12750 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12751 } 12752 12753 QualType ResultType = Method->getReturnType(); 12754 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12755 ResultType = ResultType.getNonLValueExprType(Context); 12756 12757 assert(Method && "Member call to something that isn't a method?"); 12758 CXXMemberCallExpr *TheCall = 12759 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12760 ResultType, VK, RParenLoc); 12761 12762 // Check for a valid return type. 12763 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12764 TheCall, Method)) 12765 return ExprError(); 12766 12767 // Convert the object argument (for a non-static member function call). 12768 // We only need to do this if there was actually an overload; otherwise 12769 // it was done at lookup. 12770 if (!Method->isStatic()) { 12771 ExprResult ObjectArg = 12772 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12773 FoundDecl, Method); 12774 if (ObjectArg.isInvalid()) 12775 return ExprError(); 12776 MemExpr->setBase(ObjectArg.get()); 12777 } 12778 12779 // Convert the rest of the arguments 12780 const FunctionProtoType *Proto = 12781 Method->getType()->getAs<FunctionProtoType>(); 12782 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12783 RParenLoc)) 12784 return ExprError(); 12785 12786 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12787 12788 if (CheckFunctionCall(Method, TheCall, Proto)) 12789 return ExprError(); 12790 12791 // In the case the method to call was not selected by the overloading 12792 // resolution process, we still need to handle the enable_if attribute. Do 12793 // that here, so it will not hide previous -- and more relevant -- errors. 12794 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 12795 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12796 Diag(MemE->getMemberLoc(), 12797 diag::err_ovl_no_viable_member_function_in_call) 12798 << Method << Method->getSourceRange(); 12799 Diag(Method->getLocation(), 12800 diag::note_ovl_candidate_disabled_by_function_cond_attr) 12801 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12802 return ExprError(); 12803 } 12804 } 12805 12806 if ((isa<CXXConstructorDecl>(CurContext) || 12807 isa<CXXDestructorDecl>(CurContext)) && 12808 TheCall->getMethodDecl()->isPure()) { 12809 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12810 12811 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12812 MemExpr->performsVirtualDispatch(getLangOpts())) { 12813 Diag(MemExpr->getLocStart(), 12814 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12815 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12816 << MD->getParent()->getDeclName(); 12817 12818 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12819 if (getLangOpts().AppleKext) 12820 Diag(MemExpr->getLocStart(), 12821 diag::note_pure_qualified_call_kext) 12822 << MD->getParent()->getDeclName() 12823 << MD->getDeclName(); 12824 } 12825 } 12826 12827 if (CXXDestructorDecl *DD = 12828 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12829 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12830 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 12831 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12832 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12833 MemExpr->getMemberLoc()); 12834 } 12835 12836 return MaybeBindToTemporary(TheCall); 12837 } 12838 12839 /// BuildCallToObjectOfClassType - Build a call to an object of class 12840 /// type (C++ [over.call.object]), which can end up invoking an 12841 /// overloaded function call operator (@c operator()) or performing a 12842 /// user-defined conversion on the object argument. 12843 ExprResult 12844 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12845 SourceLocation LParenLoc, 12846 MultiExprArg Args, 12847 SourceLocation RParenLoc) { 12848 if (checkPlaceholderForOverload(*this, Obj)) 12849 return ExprError(); 12850 ExprResult Object = Obj; 12851 12852 UnbridgedCastsSet UnbridgedCasts; 12853 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12854 return ExprError(); 12855 12856 assert(Object.get()->getType()->isRecordType() && 12857 "Requires object type argument"); 12858 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12859 12860 // C++ [over.call.object]p1: 12861 // If the primary-expression E in the function call syntax 12862 // evaluates to a class object of type "cv T", then the set of 12863 // candidate functions includes at least the function call 12864 // operators of T. The function call operators of T are obtained by 12865 // ordinary lookup of the name operator() in the context of 12866 // (E).operator(). 12867 OverloadCandidateSet CandidateSet(LParenLoc, 12868 OverloadCandidateSet::CSK_Operator); 12869 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12870 12871 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12872 diag::err_incomplete_object_call, Object.get())) 12873 return true; 12874 12875 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12876 LookupQualifiedName(R, Record->getDecl()); 12877 R.suppressDiagnostics(); 12878 12879 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12880 Oper != OperEnd; ++Oper) { 12881 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12882 Object.get()->Classify(Context), Args, CandidateSet, 12883 /*SuppressUserConversions=*/false); 12884 } 12885 12886 // C++ [over.call.object]p2: 12887 // In addition, for each (non-explicit in C++0x) conversion function 12888 // declared in T of the form 12889 // 12890 // operator conversion-type-id () cv-qualifier; 12891 // 12892 // where cv-qualifier is the same cv-qualification as, or a 12893 // greater cv-qualification than, cv, and where conversion-type-id 12894 // denotes the type "pointer to function of (P1,...,Pn) returning 12895 // R", or the type "reference to pointer to function of 12896 // (P1,...,Pn) returning R", or the type "reference to function 12897 // of (P1,...,Pn) returning R", a surrogate call function [...] 12898 // is also considered as a candidate function. Similarly, 12899 // surrogate call functions are added to the set of candidate 12900 // functions for each conversion function declared in an 12901 // accessible base class provided the function is not hidden 12902 // within T by another intervening declaration. 12903 const auto &Conversions = 12904 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12905 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12906 NamedDecl *D = *I; 12907 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12908 if (isa<UsingShadowDecl>(D)) 12909 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12910 12911 // Skip over templated conversion functions; they aren't 12912 // surrogates. 12913 if (isa<FunctionTemplateDecl>(D)) 12914 continue; 12915 12916 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12917 if (!Conv->isExplicit()) { 12918 // Strip the reference type (if any) and then the pointer type (if 12919 // any) to get down to what might be a function type. 12920 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12921 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12922 ConvType = ConvPtrType->getPointeeType(); 12923 12924 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12925 { 12926 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12927 Object.get(), Args, CandidateSet); 12928 } 12929 } 12930 } 12931 12932 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12933 12934 // Perform overload resolution. 12935 OverloadCandidateSet::iterator Best; 12936 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12937 Best)) { 12938 case OR_Success: 12939 // Overload resolution succeeded; we'll build the appropriate call 12940 // below. 12941 break; 12942 12943 case OR_No_Viable_Function: 12944 if (CandidateSet.empty()) 12945 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12946 << Object.get()->getType() << /*call*/ 1 12947 << Object.get()->getSourceRange(); 12948 else 12949 Diag(Object.get()->getLocStart(), 12950 diag::err_ovl_no_viable_object_call) 12951 << Object.get()->getType() << Object.get()->getSourceRange(); 12952 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12953 break; 12954 12955 case OR_Ambiguous: 12956 Diag(Object.get()->getLocStart(), 12957 diag::err_ovl_ambiguous_object_call) 12958 << Object.get()->getType() << Object.get()->getSourceRange(); 12959 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12960 break; 12961 12962 case OR_Deleted: 12963 Diag(Object.get()->getLocStart(), 12964 diag::err_ovl_deleted_object_call) 12965 << Best->Function->isDeleted() 12966 << Object.get()->getType() 12967 << getDeletedOrUnavailableSuffix(Best->Function) 12968 << Object.get()->getSourceRange(); 12969 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12970 break; 12971 } 12972 12973 if (Best == CandidateSet.end()) 12974 return true; 12975 12976 UnbridgedCasts.restore(); 12977 12978 if (Best->Function == nullptr) { 12979 // Since there is no function declaration, this is one of the 12980 // surrogate candidates. Dig out the conversion function. 12981 CXXConversionDecl *Conv 12982 = cast<CXXConversionDecl>( 12983 Best->Conversions[0].UserDefined.ConversionFunction); 12984 12985 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12986 Best->FoundDecl); 12987 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12988 return ExprError(); 12989 assert(Conv == Best->FoundDecl.getDecl() && 12990 "Found Decl & conversion-to-functionptr should be same, right?!"); 12991 // We selected one of the surrogate functions that converts the 12992 // object parameter to a function pointer. Perform the conversion 12993 // on the object argument, then let ActOnCallExpr finish the job. 12994 12995 // Create an implicit member expr to refer to the conversion operator. 12996 // and then call it. 12997 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12998 Conv, HadMultipleCandidates); 12999 if (Call.isInvalid()) 13000 return ExprError(); 13001 // Record usage of conversion in an implicit cast. 13002 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13003 CK_UserDefinedConversion, Call.get(), 13004 nullptr, VK_RValue); 13005 13006 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13007 } 13008 13009 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13010 13011 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13012 // that calls this method, using Object for the implicit object 13013 // parameter and passing along the remaining arguments. 13014 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13015 13016 // An error diagnostic has already been printed when parsing the declaration. 13017 if (Method->isInvalidDecl()) 13018 return ExprError(); 13019 13020 const FunctionProtoType *Proto = 13021 Method->getType()->getAs<FunctionProtoType>(); 13022 13023 unsigned NumParams = Proto->getNumParams(); 13024 13025 DeclarationNameInfo OpLocInfo( 13026 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13027 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13028 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13029 HadMultipleCandidates, 13030 OpLocInfo.getLoc(), 13031 OpLocInfo.getInfo()); 13032 if (NewFn.isInvalid()) 13033 return true; 13034 13035 // Build the full argument list for the method call (the implicit object 13036 // parameter is placed at the beginning of the list). 13037 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1); 13038 MethodArgs[0] = Object.get(); 13039 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1); 13040 13041 // Once we've built TheCall, all of the expressions are properly 13042 // owned. 13043 QualType ResultTy = Method->getReturnType(); 13044 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13045 ResultTy = ResultTy.getNonLValueExprType(Context); 13046 13047 CXXOperatorCallExpr *TheCall = new (Context) 13048 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, 13049 VK, RParenLoc, false); 13050 13051 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13052 return true; 13053 13054 // We may have default arguments. If so, we need to allocate more 13055 // slots in the call for them. 13056 if (Args.size() < NumParams) 13057 TheCall->setNumArgs(Context, NumParams + 1); 13058 13059 bool IsError = false; 13060 13061 // Initialize the implicit object parameter. 13062 ExprResult ObjRes = 13063 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13064 Best->FoundDecl, Method); 13065 if (ObjRes.isInvalid()) 13066 IsError = true; 13067 else 13068 Object = ObjRes; 13069 TheCall->setArg(0, Object.get()); 13070 13071 // Check the argument types. 13072 for (unsigned i = 0; i != NumParams; i++) { 13073 Expr *Arg; 13074 if (i < Args.size()) { 13075 Arg = Args[i]; 13076 13077 // Pass the argument. 13078 13079 ExprResult InputInit 13080 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13081 Context, 13082 Method->getParamDecl(i)), 13083 SourceLocation(), Arg); 13084 13085 IsError |= InputInit.isInvalid(); 13086 Arg = InputInit.getAs<Expr>(); 13087 } else { 13088 ExprResult DefArg 13089 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13090 if (DefArg.isInvalid()) { 13091 IsError = true; 13092 break; 13093 } 13094 13095 Arg = DefArg.getAs<Expr>(); 13096 } 13097 13098 TheCall->setArg(i + 1, Arg); 13099 } 13100 13101 // If this is a variadic call, handle args passed through "...". 13102 if (Proto->isVariadic()) { 13103 // Promote the arguments (C99 6.5.2.2p7). 13104 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13105 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13106 nullptr); 13107 IsError |= Arg.isInvalid(); 13108 TheCall->setArg(i + 1, Arg.get()); 13109 } 13110 } 13111 13112 if (IsError) return true; 13113 13114 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13115 13116 if (CheckFunctionCall(Method, TheCall, Proto)) 13117 return true; 13118 13119 return MaybeBindToTemporary(TheCall); 13120 } 13121 13122 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13123 /// (if one exists), where @c Base is an expression of class type and 13124 /// @c Member is the name of the member we're trying to find. 13125 ExprResult 13126 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13127 bool *NoArrowOperatorFound) { 13128 assert(Base->getType()->isRecordType() && 13129 "left-hand side must have class type"); 13130 13131 if (checkPlaceholderForOverload(*this, Base)) 13132 return ExprError(); 13133 13134 SourceLocation Loc = Base->getExprLoc(); 13135 13136 // C++ [over.ref]p1: 13137 // 13138 // [...] An expression x->m is interpreted as (x.operator->())->m 13139 // for a class object x of type T if T::operator->() exists and if 13140 // the operator is selected as the best match function by the 13141 // overload resolution mechanism (13.3). 13142 DeclarationName OpName = 13143 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13144 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13145 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13146 13147 if (RequireCompleteType(Loc, Base->getType(), 13148 diag::err_typecheck_incomplete_tag, Base)) 13149 return ExprError(); 13150 13151 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13152 LookupQualifiedName(R, BaseRecord->getDecl()); 13153 R.suppressDiagnostics(); 13154 13155 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13156 Oper != OperEnd; ++Oper) { 13157 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13158 None, CandidateSet, /*SuppressUserConversions=*/false); 13159 } 13160 13161 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13162 13163 // Perform overload resolution. 13164 OverloadCandidateSet::iterator Best; 13165 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13166 case OR_Success: 13167 // Overload resolution succeeded; we'll build the call below. 13168 break; 13169 13170 case OR_No_Viable_Function: 13171 if (CandidateSet.empty()) { 13172 QualType BaseType = Base->getType(); 13173 if (NoArrowOperatorFound) { 13174 // Report this specific error to the caller instead of emitting a 13175 // diagnostic, as requested. 13176 *NoArrowOperatorFound = true; 13177 return ExprError(); 13178 } 13179 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13180 << BaseType << Base->getSourceRange(); 13181 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13182 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13183 << FixItHint::CreateReplacement(OpLoc, "."); 13184 } 13185 } else 13186 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13187 << "operator->" << Base->getSourceRange(); 13188 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13189 return ExprError(); 13190 13191 case OR_Ambiguous: 13192 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 13193 << "->" << Base->getType() << Base->getSourceRange(); 13194 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 13195 return ExprError(); 13196 13197 case OR_Deleted: 13198 Diag(OpLoc, diag::err_ovl_deleted_oper) 13199 << Best->Function->isDeleted() 13200 << "->" 13201 << getDeletedOrUnavailableSuffix(Best->Function) 13202 << Base->getSourceRange(); 13203 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13204 return ExprError(); 13205 } 13206 13207 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13208 13209 // Convert the object parameter. 13210 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13211 ExprResult BaseResult = 13212 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13213 Best->FoundDecl, Method); 13214 if (BaseResult.isInvalid()) 13215 return ExprError(); 13216 Base = BaseResult.get(); 13217 13218 // Build the operator call. 13219 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13220 HadMultipleCandidates, OpLoc); 13221 if (FnExpr.isInvalid()) 13222 return ExprError(); 13223 13224 QualType ResultTy = Method->getReturnType(); 13225 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13226 ResultTy = ResultTy.getNonLValueExprType(Context); 13227 CXXOperatorCallExpr *TheCall = 13228 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 13229 Base, ResultTy, VK, OpLoc, false); 13230 13231 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13232 return ExprError(); 13233 13234 if (CheckFunctionCall(Method, TheCall, 13235 Method->getType()->castAs<FunctionProtoType>())) 13236 return ExprError(); 13237 13238 return MaybeBindToTemporary(TheCall); 13239 } 13240 13241 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13242 /// a literal operator described by the provided lookup results. 13243 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13244 DeclarationNameInfo &SuffixInfo, 13245 ArrayRef<Expr*> Args, 13246 SourceLocation LitEndLoc, 13247 TemplateArgumentListInfo *TemplateArgs) { 13248 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13249 13250 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13251 OverloadCandidateSet::CSK_Normal); 13252 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13253 /*SuppressUserConversions=*/true); 13254 13255 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13256 13257 // Perform overload resolution. This will usually be trivial, but might need 13258 // to perform substitutions for a literal operator template. 13259 OverloadCandidateSet::iterator Best; 13260 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13261 case OR_Success: 13262 case OR_Deleted: 13263 break; 13264 13265 case OR_No_Viable_Function: 13266 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13267 << R.getLookupName(); 13268 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13269 return ExprError(); 13270 13271 case OR_Ambiguous: 13272 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13273 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13274 return ExprError(); 13275 } 13276 13277 FunctionDecl *FD = Best->Function; 13278 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13279 HadMultipleCandidates, 13280 SuffixInfo.getLoc(), 13281 SuffixInfo.getInfo()); 13282 if (Fn.isInvalid()) 13283 return true; 13284 13285 // Check the argument types. This should almost always be a no-op, except 13286 // that array-to-pointer decay is applied to string literals. 13287 Expr *ConvArgs[2]; 13288 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13289 ExprResult InputInit = PerformCopyInitialization( 13290 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13291 SourceLocation(), Args[ArgIdx]); 13292 if (InputInit.isInvalid()) 13293 return true; 13294 ConvArgs[ArgIdx] = InputInit.get(); 13295 } 13296 13297 QualType ResultTy = FD->getReturnType(); 13298 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13299 ResultTy = ResultTy.getNonLValueExprType(Context); 13300 13301 UserDefinedLiteral *UDL = 13302 new (Context) UserDefinedLiteral(Context, Fn.get(), 13303 llvm::makeArrayRef(ConvArgs, Args.size()), 13304 ResultTy, VK, LitEndLoc, UDSuffixLoc); 13305 13306 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13307 return ExprError(); 13308 13309 if (CheckFunctionCall(FD, UDL, nullptr)) 13310 return ExprError(); 13311 13312 return MaybeBindToTemporary(UDL); 13313 } 13314 13315 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13316 /// given LookupResult is non-empty, it is assumed to describe a member which 13317 /// will be invoked. Otherwise, the function will be found via argument 13318 /// dependent lookup. 13319 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13320 /// otherwise CallExpr is set to ExprError() and some non-success value 13321 /// is returned. 13322 Sema::ForRangeStatus 13323 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13324 SourceLocation RangeLoc, 13325 const DeclarationNameInfo &NameInfo, 13326 LookupResult &MemberLookup, 13327 OverloadCandidateSet *CandidateSet, 13328 Expr *Range, ExprResult *CallExpr) { 13329 Scope *S = nullptr; 13330 13331 CandidateSet->clear(); 13332 if (!MemberLookup.empty()) { 13333 ExprResult MemberRef = 13334 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13335 /*IsPtr=*/false, CXXScopeSpec(), 13336 /*TemplateKWLoc=*/SourceLocation(), 13337 /*FirstQualifierInScope=*/nullptr, 13338 MemberLookup, 13339 /*TemplateArgs=*/nullptr, S); 13340 if (MemberRef.isInvalid()) { 13341 *CallExpr = ExprError(); 13342 return FRS_DiagnosticIssued; 13343 } 13344 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13345 if (CallExpr->isInvalid()) { 13346 *CallExpr = ExprError(); 13347 return FRS_DiagnosticIssued; 13348 } 13349 } else { 13350 UnresolvedSet<0> FoundNames; 13351 UnresolvedLookupExpr *Fn = 13352 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13353 NestedNameSpecifierLoc(), NameInfo, 13354 /*NeedsADL=*/true, /*Overloaded=*/false, 13355 FoundNames.begin(), FoundNames.end()); 13356 13357 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13358 CandidateSet, CallExpr); 13359 if (CandidateSet->empty() || CandidateSetError) { 13360 *CallExpr = ExprError(); 13361 return FRS_NoViableFunction; 13362 } 13363 OverloadCandidateSet::iterator Best; 13364 OverloadingResult OverloadResult = 13365 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 13366 13367 if (OverloadResult == OR_No_Viable_Function) { 13368 *CallExpr = ExprError(); 13369 return FRS_NoViableFunction; 13370 } 13371 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13372 Loc, nullptr, CandidateSet, &Best, 13373 OverloadResult, 13374 /*AllowTypoCorrection=*/false); 13375 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13376 *CallExpr = ExprError(); 13377 return FRS_DiagnosticIssued; 13378 } 13379 } 13380 return FRS_Success; 13381 } 13382 13383 13384 /// FixOverloadedFunctionReference - E is an expression that refers to 13385 /// a C++ overloaded function (possibly with some parentheses and 13386 /// perhaps a '&' around it). We have resolved the overloaded function 13387 /// to the function declaration Fn, so patch up the expression E to 13388 /// refer (possibly indirectly) to Fn. Returns the new expr. 13389 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13390 FunctionDecl *Fn) { 13391 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13392 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13393 Found, Fn); 13394 if (SubExpr == PE->getSubExpr()) 13395 return PE; 13396 13397 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13398 } 13399 13400 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13401 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13402 Found, Fn); 13403 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13404 SubExpr->getType()) && 13405 "Implicit cast type cannot be determined from overload"); 13406 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13407 if (SubExpr == ICE->getSubExpr()) 13408 return ICE; 13409 13410 return ImplicitCastExpr::Create(Context, ICE->getType(), 13411 ICE->getCastKind(), 13412 SubExpr, nullptr, 13413 ICE->getValueKind()); 13414 } 13415 13416 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13417 if (!GSE->isResultDependent()) { 13418 Expr *SubExpr = 13419 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13420 if (SubExpr == GSE->getResultExpr()) 13421 return GSE; 13422 13423 // Replace the resulting type information before rebuilding the generic 13424 // selection expression. 13425 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13426 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13427 unsigned ResultIdx = GSE->getResultIndex(); 13428 AssocExprs[ResultIdx] = SubExpr; 13429 13430 return new (Context) GenericSelectionExpr( 13431 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13432 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13433 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13434 ResultIdx); 13435 } 13436 // Rather than fall through to the unreachable, return the original generic 13437 // selection expression. 13438 return GSE; 13439 } 13440 13441 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13442 assert(UnOp->getOpcode() == UO_AddrOf && 13443 "Can only take the address of an overloaded function"); 13444 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13445 if (Method->isStatic()) { 13446 // Do nothing: static member functions aren't any different 13447 // from non-member functions. 13448 } else { 13449 // Fix the subexpression, which really has to be an 13450 // UnresolvedLookupExpr holding an overloaded member function 13451 // or template. 13452 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13453 Found, Fn); 13454 if (SubExpr == UnOp->getSubExpr()) 13455 return UnOp; 13456 13457 assert(isa<DeclRefExpr>(SubExpr) 13458 && "fixed to something other than a decl ref"); 13459 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13460 && "fixed to a member ref with no nested name qualifier"); 13461 13462 // We have taken the address of a pointer to member 13463 // function. Perform the computation here so that we get the 13464 // appropriate pointer to member type. 13465 QualType ClassType 13466 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13467 QualType MemPtrType 13468 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13469 // Under the MS ABI, lock down the inheritance model now. 13470 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13471 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13472 13473 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13474 VK_RValue, OK_Ordinary, 13475 UnOp->getOperatorLoc()); 13476 } 13477 } 13478 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13479 Found, Fn); 13480 if (SubExpr == UnOp->getSubExpr()) 13481 return UnOp; 13482 13483 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13484 Context.getPointerType(SubExpr->getType()), 13485 VK_RValue, OK_Ordinary, 13486 UnOp->getOperatorLoc()); 13487 } 13488 13489 // C++ [except.spec]p17: 13490 // An exception-specification is considered to be needed when: 13491 // - in an expression the function is the unique lookup result or the 13492 // selected member of a set of overloaded functions 13493 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13494 ResolveExceptionSpec(E->getExprLoc(), FPT); 13495 13496 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13497 // FIXME: avoid copy. 13498 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13499 if (ULE->hasExplicitTemplateArgs()) { 13500 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13501 TemplateArgs = &TemplateArgsBuffer; 13502 } 13503 13504 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13505 ULE->getQualifierLoc(), 13506 ULE->getTemplateKeywordLoc(), 13507 Fn, 13508 /*enclosing*/ false, // FIXME? 13509 ULE->getNameLoc(), 13510 Fn->getType(), 13511 VK_LValue, 13512 Found.getDecl(), 13513 TemplateArgs); 13514 MarkDeclRefReferenced(DRE); 13515 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13516 return DRE; 13517 } 13518 13519 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13520 // FIXME: avoid copy. 13521 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13522 if (MemExpr->hasExplicitTemplateArgs()) { 13523 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13524 TemplateArgs = &TemplateArgsBuffer; 13525 } 13526 13527 Expr *Base; 13528 13529 // If we're filling in a static method where we used to have an 13530 // implicit member access, rewrite to a simple decl ref. 13531 if (MemExpr->isImplicitAccess()) { 13532 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13533 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13534 MemExpr->getQualifierLoc(), 13535 MemExpr->getTemplateKeywordLoc(), 13536 Fn, 13537 /*enclosing*/ false, 13538 MemExpr->getMemberLoc(), 13539 Fn->getType(), 13540 VK_LValue, 13541 Found.getDecl(), 13542 TemplateArgs); 13543 MarkDeclRefReferenced(DRE); 13544 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13545 return DRE; 13546 } else { 13547 SourceLocation Loc = MemExpr->getMemberLoc(); 13548 if (MemExpr->getQualifier()) 13549 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13550 CheckCXXThisCapture(Loc); 13551 Base = new (Context) CXXThisExpr(Loc, 13552 MemExpr->getBaseType(), 13553 /*isImplicit=*/true); 13554 } 13555 } else 13556 Base = MemExpr->getBase(); 13557 13558 ExprValueKind valueKind; 13559 QualType type; 13560 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13561 valueKind = VK_LValue; 13562 type = Fn->getType(); 13563 } else { 13564 valueKind = VK_RValue; 13565 type = Context.BoundMemberTy; 13566 } 13567 13568 MemberExpr *ME = MemberExpr::Create( 13569 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13570 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13571 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13572 OK_Ordinary); 13573 ME->setHadMultipleCandidates(true); 13574 MarkMemberReferenced(ME); 13575 return ME; 13576 } 13577 13578 llvm_unreachable("Invalid reference to overloaded function"); 13579 } 13580 13581 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13582 DeclAccessPair Found, 13583 FunctionDecl *Fn) { 13584 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13585 } 13586