1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides Sema routines for C++ overloading. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Sema/Overload.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/DeclObjC.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/TypeOrdering.h" 21 #include "clang/Basic/Diagnostic.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Basic/TargetInfo.h" 25 #include "clang/Sema/Initialization.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/SemaInternal.h" 28 #include "clang/Sema/Template.h" 29 #include "clang/Sema/TemplateDeduction.h" 30 #include "llvm/ADT/DenseSet.h" 31 #include "llvm/ADT/Optional.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 42 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 43 return P->hasAttr<PassObjectSizeAttr>(); 44 }); 45 } 46 47 /// A convenience routine for creating a decayed reference to a function. 48 static ExprResult 49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 50 const Expr *Base, bool HadMultipleCandidates, 51 SourceLocation Loc = SourceLocation(), 52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 54 return ExprError(); 55 // If FoundDecl is different from Fn (such as if one is a template 56 // and the other a specialization), make sure DiagnoseUseOfDecl is 57 // called on both. 58 // FIXME: This would be more comprehensively addressed by modifying 59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 60 // being used. 61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 62 return ExprError(); 63 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 64 S.ResolveExceptionSpec(Loc, FPT); 65 DeclRefExpr *DRE = new (S.Context) 66 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 67 if (HadMultipleCandidates) 68 DRE->setHadMultipleCandidates(true); 69 70 S.MarkDeclRefReferenced(DRE, Base); 71 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 72 CK_FunctionToPointerDecay); 73 } 74 75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 76 bool InOverloadResolution, 77 StandardConversionSequence &SCS, 78 bool CStyle, 79 bool AllowObjCWritebackConversion); 80 81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 82 QualType &ToType, 83 bool InOverloadResolution, 84 StandardConversionSequence &SCS, 85 bool CStyle); 86 static OverloadingResult 87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 88 UserDefinedConversionSequence& User, 89 OverloadCandidateSet& Conversions, 90 bool AllowExplicit, 91 bool AllowObjCConversionOnExplicit); 92 93 94 static ImplicitConversionSequence::CompareKind 95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 96 const StandardConversionSequence& SCS1, 97 const StandardConversionSequence& SCS2); 98 99 static ImplicitConversionSequence::CompareKind 100 CompareQualificationConversions(Sema &S, 101 const StandardConversionSequence& SCS1, 102 const StandardConversionSequence& SCS2); 103 104 static ImplicitConversionSequence::CompareKind 105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 106 const StandardConversionSequence& SCS1, 107 const StandardConversionSequence& SCS2); 108 109 /// GetConversionRank - Retrieve the implicit conversion rank 110 /// corresponding to the given implicit conversion kind. 111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 112 static const ImplicitConversionRank 113 Rank[(int)ICK_Num_Conversion_Kinds] = { 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Promotion, 121 ICR_Promotion, 122 ICR_Promotion, 123 ICR_Conversion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_OCL_Scalar_Widening, 134 ICR_Complex_Real_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Writeback_Conversion, 138 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 139 // it was omitted by the patch that added 140 // ICK_Zero_Event_Conversion 141 ICR_C_Conversion, 142 ICR_C_Conversion_Extension 143 }; 144 return Rank[(int)Kind]; 145 } 146 147 /// GetImplicitConversionName - Return the name of this kind of 148 /// implicit conversion. 149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 150 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 151 "No conversion", 152 "Lvalue-to-rvalue", 153 "Array-to-pointer", 154 "Function-to-pointer", 155 "Function pointer conversion", 156 "Qualification", 157 "Integral promotion", 158 "Floating point promotion", 159 "Complex promotion", 160 "Integral conversion", 161 "Floating conversion", 162 "Complex conversion", 163 "Floating-integral conversion", 164 "Pointer conversion", 165 "Pointer-to-member conversion", 166 "Boolean conversion", 167 "Compatible-types conversion", 168 "Derived-to-base conversion", 169 "Vector conversion", 170 "Vector splat", 171 "Complex-real conversion", 172 "Block Pointer conversion", 173 "Transparent Union Conversion", 174 "Writeback conversion", 175 "OpenCL Zero Event Conversion", 176 "C specific type conversion", 177 "Incompatible pointer conversion" 178 }; 179 return Name[Kind]; 180 } 181 182 /// StandardConversionSequence - Set the standard conversion 183 /// sequence to the identity conversion. 184 void StandardConversionSequence::setAsIdentityConversion() { 185 First = ICK_Identity; 186 Second = ICK_Identity; 187 Third = ICK_Identity; 188 DeprecatedStringLiteralToCharPtr = false; 189 QualificationIncludesObjCLifetime = false; 190 ReferenceBinding = false; 191 DirectBinding = false; 192 IsLvalueReference = true; 193 BindsToFunctionLvalue = false; 194 BindsToRvalue = false; 195 BindsImplicitObjectArgumentWithoutRefQualifier = false; 196 ObjCLifetimeConversionBinding = false; 197 CopyConstructor = nullptr; 198 } 199 200 /// getRank - Retrieve the rank of this standard conversion sequence 201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 202 /// implicit conversions. 203 ImplicitConversionRank StandardConversionSequence::getRank() const { 204 ImplicitConversionRank Rank = ICR_Exact_Match; 205 if (GetConversionRank(First) > Rank) 206 Rank = GetConversionRank(First); 207 if (GetConversionRank(Second) > Rank) 208 Rank = GetConversionRank(Second); 209 if (GetConversionRank(Third) > Rank) 210 Rank = GetConversionRank(Third); 211 return Rank; 212 } 213 214 /// isPointerConversionToBool - Determines whether this conversion is 215 /// a conversion of a pointer or pointer-to-member to bool. This is 216 /// used as part of the ranking of standard conversion sequences 217 /// (C++ 13.3.3.2p4). 218 bool StandardConversionSequence::isPointerConversionToBool() const { 219 // Note that FromType has not necessarily been transformed by the 220 // array-to-pointer or function-to-pointer implicit conversions, so 221 // check for their presence as well as checking whether FromType is 222 // a pointer. 223 if (getToType(1)->isBooleanType() && 224 (getFromType()->isPointerType() || 225 getFromType()->isMemberPointerType() || 226 getFromType()->isObjCObjectPointerType() || 227 getFromType()->isBlockPointerType() || 228 getFromType()->isNullPtrType() || 229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 230 return true; 231 232 return false; 233 } 234 235 /// isPointerConversionToVoidPointer - Determines whether this 236 /// conversion is a conversion of a pointer to a void pointer. This is 237 /// used as part of the ranking of standard conversion sequences (C++ 238 /// 13.3.3.2p4). 239 bool 240 StandardConversionSequence:: 241 isPointerConversionToVoidPointer(ASTContext& Context) const { 242 QualType FromType = getFromType(); 243 QualType ToType = getToType(1); 244 245 // Note that FromType has not necessarily been transformed by the 246 // array-to-pointer implicit conversion, so check for its presence 247 // and redo the conversion to get a pointer. 248 if (First == ICK_Array_To_Pointer) 249 FromType = Context.getArrayDecayedType(FromType); 250 251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 253 return ToPtrType->getPointeeType()->isVoidType(); 254 255 return false; 256 } 257 258 /// Skip any implicit casts which could be either part of a narrowing conversion 259 /// or after one in an implicit conversion. 260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 261 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 262 switch (ICE->getCastKind()) { 263 case CK_NoOp: 264 case CK_IntegralCast: 265 case CK_IntegralToBoolean: 266 case CK_IntegralToFloating: 267 case CK_BooleanToSignedIntegral: 268 case CK_FloatingToIntegral: 269 case CK_FloatingToBoolean: 270 case CK_FloatingCast: 271 Converted = ICE->getSubExpr(); 272 continue; 273 274 default: 275 return Converted; 276 } 277 } 278 279 return Converted; 280 } 281 282 /// Check if this standard conversion sequence represents a narrowing 283 /// conversion, according to C++11 [dcl.init.list]p7. 284 /// 285 /// \param Ctx The AST context. 286 /// \param Converted The result of applying this standard conversion sequence. 287 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 288 /// value of the expression prior to the narrowing conversion. 289 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 290 /// type of the expression prior to the narrowing conversion. 291 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 292 /// from floating point types to integral types should be ignored. 293 NarrowingKind StandardConversionSequence::getNarrowingKind( 294 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 295 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 296 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 297 298 // C++11 [dcl.init.list]p7: 299 // A narrowing conversion is an implicit conversion ... 300 QualType FromType = getToType(0); 301 QualType ToType = getToType(1); 302 303 // A conversion to an enumeration type is narrowing if the conversion to 304 // the underlying type is narrowing. This only arises for expressions of 305 // the form 'Enum{init}'. 306 if (auto *ET = ToType->getAs<EnumType>()) 307 ToType = ET->getDecl()->getIntegerType(); 308 309 switch (Second) { 310 // 'bool' is an integral type; dispatch to the right place to handle it. 311 case ICK_Boolean_Conversion: 312 if (FromType->isRealFloatingType()) 313 goto FloatingIntegralConversion; 314 if (FromType->isIntegralOrUnscopedEnumerationType()) 315 goto IntegralConversion; 316 // Boolean conversions can be from pointers and pointers to members 317 // [conv.bool], and those aren't considered narrowing conversions. 318 return NK_Not_Narrowing; 319 320 // -- from a floating-point type to an integer type, or 321 // 322 // -- from an integer type or unscoped enumeration type to a floating-point 323 // type, except where the source is a constant expression and the actual 324 // value after conversion will fit into the target type and will produce 325 // the original value when converted back to the original type, or 326 case ICK_Floating_Integral: 327 FloatingIntegralConversion: 328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 329 return NK_Type_Narrowing; 330 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 331 ToType->isRealFloatingType()) { 332 if (IgnoreFloatToIntegralConversion) 333 return NK_Not_Narrowing; 334 llvm::APSInt IntConstantValue; 335 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 336 assert(Initializer && "Unknown conversion expression"); 337 338 // If it's value-dependent, we can't tell whether it's narrowing. 339 if (Initializer->isValueDependent()) 340 return NK_Dependent_Narrowing; 341 342 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 343 // Convert the integer to the floating type. 344 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 345 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 346 llvm::APFloat::rmNearestTiesToEven); 347 // And back. 348 llvm::APSInt ConvertedValue = IntConstantValue; 349 bool ignored; 350 Result.convertToInteger(ConvertedValue, 351 llvm::APFloat::rmTowardZero, &ignored); 352 // If the resulting value is different, this was a narrowing conversion. 353 if (IntConstantValue != ConvertedValue) { 354 ConstantValue = APValue(IntConstantValue); 355 ConstantType = Initializer->getType(); 356 return NK_Constant_Narrowing; 357 } 358 } else { 359 // Variables are always narrowings. 360 return NK_Variable_Narrowing; 361 } 362 } 363 return NK_Not_Narrowing; 364 365 // -- from long double to double or float, or from double to float, except 366 // where the source is a constant expression and the actual value after 367 // conversion is within the range of values that can be represented (even 368 // if it cannot be represented exactly), or 369 case ICK_Floating_Conversion: 370 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 371 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 372 // FromType is larger than ToType. 373 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 374 375 // If it's value-dependent, we can't tell whether it's narrowing. 376 if (Initializer->isValueDependent()) 377 return NK_Dependent_Narrowing; 378 379 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 380 // Constant! 381 assert(ConstantValue.isFloat()); 382 llvm::APFloat FloatVal = ConstantValue.getFloat(); 383 // Convert the source value into the target type. 384 bool ignored; 385 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 386 Ctx.getFloatTypeSemantics(ToType), 387 llvm::APFloat::rmNearestTiesToEven, &ignored); 388 // If there was no overflow, the source value is within the range of 389 // values that can be represented. 390 if (ConvertStatus & llvm::APFloat::opOverflow) { 391 ConstantType = Initializer->getType(); 392 return NK_Constant_Narrowing; 393 } 394 } else { 395 return NK_Variable_Narrowing; 396 } 397 } 398 return NK_Not_Narrowing; 399 400 // -- from an integer type or unscoped enumeration type to an integer type 401 // that cannot represent all the values of the original type, except where 402 // the source is a constant expression and the actual value after 403 // conversion will fit into the target type and will produce the original 404 // value when converted back to the original type. 405 case ICK_Integral_Conversion: 406 IntegralConversion: { 407 assert(FromType->isIntegralOrUnscopedEnumerationType()); 408 assert(ToType->isIntegralOrUnscopedEnumerationType()); 409 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 410 const unsigned FromWidth = Ctx.getIntWidth(FromType); 411 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 412 const unsigned ToWidth = Ctx.getIntWidth(ToType); 413 414 if (FromWidth > ToWidth || 415 (FromWidth == ToWidth && FromSigned != ToSigned) || 416 (FromSigned && !ToSigned)) { 417 // Not all values of FromType can be represented in ToType. 418 llvm::APSInt InitializerValue; 419 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 420 421 // If it's value-dependent, we can't tell whether it's narrowing. 422 if (Initializer->isValueDependent()) 423 return NK_Dependent_Narrowing; 424 425 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 426 // Such conversions on variables are always narrowing. 427 return NK_Variable_Narrowing; 428 } 429 bool Narrowing = false; 430 if (FromWidth < ToWidth) { 431 // Negative -> unsigned is narrowing. Otherwise, more bits is never 432 // narrowing. 433 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 434 Narrowing = true; 435 } else { 436 // Add a bit to the InitializerValue so we don't have to worry about 437 // signed vs. unsigned comparisons. 438 InitializerValue = InitializerValue.extend( 439 InitializerValue.getBitWidth() + 1); 440 // Convert the initializer to and from the target width and signed-ness. 441 llvm::APSInt ConvertedValue = InitializerValue; 442 ConvertedValue = ConvertedValue.trunc(ToWidth); 443 ConvertedValue.setIsSigned(ToSigned); 444 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 445 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 446 // If the result is different, this was a narrowing conversion. 447 if (ConvertedValue != InitializerValue) 448 Narrowing = true; 449 } 450 if (Narrowing) { 451 ConstantType = Initializer->getType(); 452 ConstantValue = APValue(InitializerValue); 453 return NK_Constant_Narrowing; 454 } 455 } 456 return NK_Not_Narrowing; 457 } 458 459 default: 460 // Other kinds of conversions are not narrowings. 461 return NK_Not_Narrowing; 462 } 463 } 464 465 /// dump - Print this standard conversion sequence to standard 466 /// error. Useful for debugging overloading issues. 467 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 468 raw_ostream &OS = llvm::errs(); 469 bool PrintedSomething = false; 470 if (First != ICK_Identity) { 471 OS << GetImplicitConversionName(First); 472 PrintedSomething = true; 473 } 474 475 if (Second != ICK_Identity) { 476 if (PrintedSomething) { 477 OS << " -> "; 478 } 479 OS << GetImplicitConversionName(Second); 480 481 if (CopyConstructor) { 482 OS << " (by copy constructor)"; 483 } else if (DirectBinding) { 484 OS << " (direct reference binding)"; 485 } else if (ReferenceBinding) { 486 OS << " (reference binding)"; 487 } 488 PrintedSomething = true; 489 } 490 491 if (Third != ICK_Identity) { 492 if (PrintedSomething) { 493 OS << " -> "; 494 } 495 OS << GetImplicitConversionName(Third); 496 PrintedSomething = true; 497 } 498 499 if (!PrintedSomething) { 500 OS << "No conversions required"; 501 } 502 } 503 504 /// dump - Print this user-defined conversion sequence to standard 505 /// error. Useful for debugging overloading issues. 506 void UserDefinedConversionSequence::dump() const { 507 raw_ostream &OS = llvm::errs(); 508 if (Before.First || Before.Second || Before.Third) { 509 Before.dump(); 510 OS << " -> "; 511 } 512 if (ConversionFunction) 513 OS << '\'' << *ConversionFunction << '\''; 514 else 515 OS << "aggregate initialization"; 516 if (After.First || After.Second || After.Third) { 517 OS << " -> "; 518 After.dump(); 519 } 520 } 521 522 /// dump - Print this implicit conversion sequence to standard 523 /// error. Useful for debugging overloading issues. 524 void ImplicitConversionSequence::dump() const { 525 raw_ostream &OS = llvm::errs(); 526 if (isStdInitializerListElement()) 527 OS << "Worst std::initializer_list element conversion: "; 528 switch (ConversionKind) { 529 case StandardConversion: 530 OS << "Standard conversion: "; 531 Standard.dump(); 532 break; 533 case UserDefinedConversion: 534 OS << "User-defined conversion: "; 535 UserDefined.dump(); 536 break; 537 case EllipsisConversion: 538 OS << "Ellipsis conversion"; 539 break; 540 case AmbiguousConversion: 541 OS << "Ambiguous conversion"; 542 break; 543 case BadConversion: 544 OS << "Bad conversion"; 545 break; 546 } 547 548 OS << "\n"; 549 } 550 551 void AmbiguousConversionSequence::construct() { 552 new (&conversions()) ConversionSet(); 553 } 554 555 void AmbiguousConversionSequence::destruct() { 556 conversions().~ConversionSet(); 557 } 558 559 void 560 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 561 FromTypePtr = O.FromTypePtr; 562 ToTypePtr = O.ToTypePtr; 563 new (&conversions()) ConversionSet(O.conversions()); 564 } 565 566 namespace { 567 // Structure used by DeductionFailureInfo to store 568 // template argument information. 569 struct DFIArguments { 570 TemplateArgument FirstArg; 571 TemplateArgument SecondArg; 572 }; 573 // Structure used by DeductionFailureInfo to store 574 // template parameter and template argument information. 575 struct DFIParamWithArguments : DFIArguments { 576 TemplateParameter Param; 577 }; 578 // Structure used by DeductionFailureInfo to store template argument 579 // information and the index of the problematic call argument. 580 struct DFIDeducedMismatchArgs : DFIArguments { 581 TemplateArgumentList *TemplateArgs; 582 unsigned CallArgIndex; 583 }; 584 } 585 586 /// Convert from Sema's representation of template deduction information 587 /// to the form used in overload-candidate information. 588 DeductionFailureInfo 589 clang::MakeDeductionFailureInfo(ASTContext &Context, 590 Sema::TemplateDeductionResult TDK, 591 TemplateDeductionInfo &Info) { 592 DeductionFailureInfo Result; 593 Result.Result = static_cast<unsigned>(TDK); 594 Result.HasDiagnostic = false; 595 switch (TDK) { 596 case Sema::TDK_Invalid: 597 case Sema::TDK_InstantiationDepth: 598 case Sema::TDK_TooManyArguments: 599 case Sema::TDK_TooFewArguments: 600 case Sema::TDK_MiscellaneousDeductionFailure: 601 case Sema::TDK_CUDATargetMismatch: 602 Result.Data = nullptr; 603 break; 604 605 case Sema::TDK_Incomplete: 606 case Sema::TDK_InvalidExplicitArguments: 607 Result.Data = Info.Param.getOpaqueValue(); 608 break; 609 610 case Sema::TDK_DeducedMismatch: 611 case Sema::TDK_DeducedMismatchNested: { 612 // FIXME: Should allocate from normal heap so that we can free this later. 613 auto *Saved = new (Context) DFIDeducedMismatchArgs; 614 Saved->FirstArg = Info.FirstArg; 615 Saved->SecondArg = Info.SecondArg; 616 Saved->TemplateArgs = Info.take(); 617 Saved->CallArgIndex = Info.CallArgIndex; 618 Result.Data = Saved; 619 break; 620 } 621 622 case Sema::TDK_NonDeducedMismatch: { 623 // FIXME: Should allocate from normal heap so that we can free this later. 624 DFIArguments *Saved = new (Context) DFIArguments; 625 Saved->FirstArg = Info.FirstArg; 626 Saved->SecondArg = Info.SecondArg; 627 Result.Data = Saved; 628 break; 629 } 630 631 case Sema::TDK_IncompletePack: 632 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 633 case Sema::TDK_Inconsistent: 634 case Sema::TDK_Underqualified: { 635 // FIXME: Should allocate from normal heap so that we can free this later. 636 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 637 Saved->Param = Info.Param; 638 Saved->FirstArg = Info.FirstArg; 639 Saved->SecondArg = Info.SecondArg; 640 Result.Data = Saved; 641 break; 642 } 643 644 case Sema::TDK_SubstitutionFailure: 645 Result.Data = Info.take(); 646 if (Info.hasSFINAEDiagnostic()) { 647 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 648 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 649 Info.takeSFINAEDiagnostic(*Diag); 650 Result.HasDiagnostic = true; 651 } 652 break; 653 654 case Sema::TDK_Success: 655 case Sema::TDK_NonDependentConversionFailure: 656 llvm_unreachable("not a deduction failure"); 657 } 658 659 return Result; 660 } 661 662 void DeductionFailureInfo::Destroy() { 663 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 664 case Sema::TDK_Success: 665 case Sema::TDK_Invalid: 666 case Sema::TDK_InstantiationDepth: 667 case Sema::TDK_Incomplete: 668 case Sema::TDK_TooManyArguments: 669 case Sema::TDK_TooFewArguments: 670 case Sema::TDK_InvalidExplicitArguments: 671 case Sema::TDK_CUDATargetMismatch: 672 case Sema::TDK_NonDependentConversionFailure: 673 break; 674 675 case Sema::TDK_IncompletePack: 676 case Sema::TDK_Inconsistent: 677 case Sema::TDK_Underqualified: 678 case Sema::TDK_DeducedMismatch: 679 case Sema::TDK_DeducedMismatchNested: 680 case Sema::TDK_NonDeducedMismatch: 681 // FIXME: Destroy the data? 682 Data = nullptr; 683 break; 684 685 case Sema::TDK_SubstitutionFailure: 686 // FIXME: Destroy the template argument list? 687 Data = nullptr; 688 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 689 Diag->~PartialDiagnosticAt(); 690 HasDiagnostic = false; 691 } 692 break; 693 694 // Unhandled 695 case Sema::TDK_MiscellaneousDeductionFailure: 696 break; 697 } 698 } 699 700 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 701 if (HasDiagnostic) 702 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 703 return nullptr; 704 } 705 706 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 707 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 708 case Sema::TDK_Success: 709 case Sema::TDK_Invalid: 710 case Sema::TDK_InstantiationDepth: 711 case Sema::TDK_TooManyArguments: 712 case Sema::TDK_TooFewArguments: 713 case Sema::TDK_SubstitutionFailure: 714 case Sema::TDK_DeducedMismatch: 715 case Sema::TDK_DeducedMismatchNested: 716 case Sema::TDK_NonDeducedMismatch: 717 case Sema::TDK_CUDATargetMismatch: 718 case Sema::TDK_NonDependentConversionFailure: 719 return TemplateParameter(); 720 721 case Sema::TDK_Incomplete: 722 case Sema::TDK_InvalidExplicitArguments: 723 return TemplateParameter::getFromOpaqueValue(Data); 724 725 case Sema::TDK_IncompletePack: 726 case Sema::TDK_Inconsistent: 727 case Sema::TDK_Underqualified: 728 return static_cast<DFIParamWithArguments*>(Data)->Param; 729 730 // Unhandled 731 case Sema::TDK_MiscellaneousDeductionFailure: 732 break; 733 } 734 735 return TemplateParameter(); 736 } 737 738 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 739 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 740 case Sema::TDK_Success: 741 case Sema::TDK_Invalid: 742 case Sema::TDK_InstantiationDepth: 743 case Sema::TDK_TooManyArguments: 744 case Sema::TDK_TooFewArguments: 745 case Sema::TDK_Incomplete: 746 case Sema::TDK_IncompletePack: 747 case Sema::TDK_InvalidExplicitArguments: 748 case Sema::TDK_Inconsistent: 749 case Sema::TDK_Underqualified: 750 case Sema::TDK_NonDeducedMismatch: 751 case Sema::TDK_CUDATargetMismatch: 752 case Sema::TDK_NonDependentConversionFailure: 753 return nullptr; 754 755 case Sema::TDK_DeducedMismatch: 756 case Sema::TDK_DeducedMismatchNested: 757 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 758 759 case Sema::TDK_SubstitutionFailure: 760 return static_cast<TemplateArgumentList*>(Data); 761 762 // Unhandled 763 case Sema::TDK_MiscellaneousDeductionFailure: 764 break; 765 } 766 767 return nullptr; 768 } 769 770 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 771 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 772 case Sema::TDK_Success: 773 case Sema::TDK_Invalid: 774 case Sema::TDK_InstantiationDepth: 775 case Sema::TDK_Incomplete: 776 case Sema::TDK_TooManyArguments: 777 case Sema::TDK_TooFewArguments: 778 case Sema::TDK_InvalidExplicitArguments: 779 case Sema::TDK_SubstitutionFailure: 780 case Sema::TDK_CUDATargetMismatch: 781 case Sema::TDK_NonDependentConversionFailure: 782 return nullptr; 783 784 case Sema::TDK_IncompletePack: 785 case Sema::TDK_Inconsistent: 786 case Sema::TDK_Underqualified: 787 case Sema::TDK_DeducedMismatch: 788 case Sema::TDK_DeducedMismatchNested: 789 case Sema::TDK_NonDeducedMismatch: 790 return &static_cast<DFIArguments*>(Data)->FirstArg; 791 792 // Unhandled 793 case Sema::TDK_MiscellaneousDeductionFailure: 794 break; 795 } 796 797 return nullptr; 798 } 799 800 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 801 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 802 case Sema::TDK_Success: 803 case Sema::TDK_Invalid: 804 case Sema::TDK_InstantiationDepth: 805 case Sema::TDK_Incomplete: 806 case Sema::TDK_IncompletePack: 807 case Sema::TDK_TooManyArguments: 808 case Sema::TDK_TooFewArguments: 809 case Sema::TDK_InvalidExplicitArguments: 810 case Sema::TDK_SubstitutionFailure: 811 case Sema::TDK_CUDATargetMismatch: 812 case Sema::TDK_NonDependentConversionFailure: 813 return nullptr; 814 815 case Sema::TDK_Inconsistent: 816 case Sema::TDK_Underqualified: 817 case Sema::TDK_DeducedMismatch: 818 case Sema::TDK_DeducedMismatchNested: 819 case Sema::TDK_NonDeducedMismatch: 820 return &static_cast<DFIArguments*>(Data)->SecondArg; 821 822 // Unhandled 823 case Sema::TDK_MiscellaneousDeductionFailure: 824 break; 825 } 826 827 return nullptr; 828 } 829 830 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 831 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 832 case Sema::TDK_DeducedMismatch: 833 case Sema::TDK_DeducedMismatchNested: 834 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 835 836 default: 837 return llvm::None; 838 } 839 } 840 841 void OverloadCandidateSet::destroyCandidates() { 842 for (iterator i = begin(), e = end(); i != e; ++i) { 843 for (auto &C : i->Conversions) 844 C.~ImplicitConversionSequence(); 845 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 846 i->DeductionFailure.Destroy(); 847 } 848 } 849 850 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 851 destroyCandidates(); 852 SlabAllocator.Reset(); 853 NumInlineBytesUsed = 0; 854 Candidates.clear(); 855 Functions.clear(); 856 Kind = CSK; 857 } 858 859 namespace { 860 class UnbridgedCastsSet { 861 struct Entry { 862 Expr **Addr; 863 Expr *Saved; 864 }; 865 SmallVector<Entry, 2> Entries; 866 867 public: 868 void save(Sema &S, Expr *&E) { 869 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 870 Entry entry = { &E, E }; 871 Entries.push_back(entry); 872 E = S.stripARCUnbridgedCast(E); 873 } 874 875 void restore() { 876 for (SmallVectorImpl<Entry>::iterator 877 i = Entries.begin(), e = Entries.end(); i != e; ++i) 878 *i->Addr = i->Saved; 879 } 880 }; 881 } 882 883 /// checkPlaceholderForOverload - Do any interesting placeholder-like 884 /// preprocessing on the given expression. 885 /// 886 /// \param unbridgedCasts a collection to which to add unbridged casts; 887 /// without this, they will be immediately diagnosed as errors 888 /// 889 /// Return true on unrecoverable error. 890 static bool 891 checkPlaceholderForOverload(Sema &S, Expr *&E, 892 UnbridgedCastsSet *unbridgedCasts = nullptr) { 893 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 894 // We can't handle overloaded expressions here because overload 895 // resolution might reasonably tweak them. 896 if (placeholder->getKind() == BuiltinType::Overload) return false; 897 898 // If the context potentially accepts unbridged ARC casts, strip 899 // the unbridged cast and add it to the collection for later restoration. 900 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 901 unbridgedCasts) { 902 unbridgedCasts->save(S, E); 903 return false; 904 } 905 906 // Go ahead and check everything else. 907 ExprResult result = S.CheckPlaceholderExpr(E); 908 if (result.isInvalid()) 909 return true; 910 911 E = result.get(); 912 return false; 913 } 914 915 // Nothing to do. 916 return false; 917 } 918 919 /// checkArgPlaceholdersForOverload - Check a set of call operands for 920 /// placeholders. 921 static bool checkArgPlaceholdersForOverload(Sema &S, 922 MultiExprArg Args, 923 UnbridgedCastsSet &unbridged) { 924 for (unsigned i = 0, e = Args.size(); i != e; ++i) 925 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 926 return true; 927 928 return false; 929 } 930 931 /// Determine whether the given New declaration is an overload of the 932 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 933 /// New and Old cannot be overloaded, e.g., if New has the same signature as 934 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 935 /// functions (or function templates) at all. When it does return Ovl_Match or 936 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 937 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 938 /// declaration. 939 /// 940 /// Example: Given the following input: 941 /// 942 /// void f(int, float); // #1 943 /// void f(int, int); // #2 944 /// int f(int, int); // #3 945 /// 946 /// When we process #1, there is no previous declaration of "f", so IsOverload 947 /// will not be used. 948 /// 949 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 950 /// the parameter types, we see that #1 and #2 are overloaded (since they have 951 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 952 /// unchanged. 953 /// 954 /// When we process #3, Old is an overload set containing #1 and #2. We compare 955 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 956 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 957 /// functions are not part of the signature), IsOverload returns Ovl_Match and 958 /// MatchedDecl will be set to point to the FunctionDecl for #2. 959 /// 960 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 961 /// by a using declaration. The rules for whether to hide shadow declarations 962 /// ignore some properties which otherwise figure into a function template's 963 /// signature. 964 Sema::OverloadKind 965 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 966 NamedDecl *&Match, bool NewIsUsingDecl) { 967 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 968 I != E; ++I) { 969 NamedDecl *OldD = *I; 970 971 bool OldIsUsingDecl = false; 972 if (isa<UsingShadowDecl>(OldD)) { 973 OldIsUsingDecl = true; 974 975 // We can always introduce two using declarations into the same 976 // context, even if they have identical signatures. 977 if (NewIsUsingDecl) continue; 978 979 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 980 } 981 982 // A using-declaration does not conflict with another declaration 983 // if one of them is hidden. 984 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 985 continue; 986 987 // If either declaration was introduced by a using declaration, 988 // we'll need to use slightly different rules for matching. 989 // Essentially, these rules are the normal rules, except that 990 // function templates hide function templates with different 991 // return types or template parameter lists. 992 bool UseMemberUsingDeclRules = 993 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 994 !New->getFriendObjectKind(); 995 996 if (FunctionDecl *OldF = OldD->getAsFunction()) { 997 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 998 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 999 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1000 continue; 1001 } 1002 1003 if (!isa<FunctionTemplateDecl>(OldD) && 1004 !shouldLinkPossiblyHiddenDecl(*I, New)) 1005 continue; 1006 1007 Match = *I; 1008 return Ovl_Match; 1009 } 1010 1011 // Builtins that have custom typechecking or have a reference should 1012 // not be overloadable or redeclarable. 1013 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1014 Match = *I; 1015 return Ovl_NonFunction; 1016 } 1017 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1018 // We can overload with these, which can show up when doing 1019 // redeclaration checks for UsingDecls. 1020 assert(Old.getLookupKind() == LookupUsingDeclName); 1021 } else if (isa<TagDecl>(OldD)) { 1022 // We can always overload with tags by hiding them. 1023 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1024 // Optimistically assume that an unresolved using decl will 1025 // overload; if it doesn't, we'll have to diagnose during 1026 // template instantiation. 1027 // 1028 // Exception: if the scope is dependent and this is not a class 1029 // member, the using declaration can only introduce an enumerator. 1030 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1031 Match = *I; 1032 return Ovl_NonFunction; 1033 } 1034 } else { 1035 // (C++ 13p1): 1036 // Only function declarations can be overloaded; object and type 1037 // declarations cannot be overloaded. 1038 Match = *I; 1039 return Ovl_NonFunction; 1040 } 1041 } 1042 1043 // C++ [temp.friend]p1: 1044 // For a friend function declaration that is not a template declaration: 1045 // -- if the name of the friend is a qualified or unqualified template-id, 1046 // [...], otherwise 1047 // -- if the name of the friend is a qualified-id and a matching 1048 // non-template function is found in the specified class or namespace, 1049 // the friend declaration refers to that function, otherwise, 1050 // -- if the name of the friend is a qualified-id and a matching function 1051 // template is found in the specified class or namespace, the friend 1052 // declaration refers to the deduced specialization of that function 1053 // template, otherwise 1054 // -- the name shall be an unqualified-id [...] 1055 // If we get here for a qualified friend declaration, we've just reached the 1056 // third bullet. If the type of the friend is dependent, skip this lookup 1057 // until instantiation. 1058 if (New->getFriendObjectKind() && New->getQualifier() && 1059 !New->getDependentSpecializationInfo() && 1060 !New->getType()->isDependentType()) { 1061 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1062 TemplateSpecResult.addAllDecls(Old); 1063 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1064 /*QualifiedFriend*/true)) { 1065 New->setInvalidDecl(); 1066 return Ovl_Overload; 1067 } 1068 1069 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1070 return Ovl_Match; 1071 } 1072 1073 return Ovl_Overload; 1074 } 1075 1076 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1077 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1078 // C++ [basic.start.main]p2: This function shall not be overloaded. 1079 if (New->isMain()) 1080 return false; 1081 1082 // MSVCRT user defined entry points cannot be overloaded. 1083 if (New->isMSVCRTEntryPoint()) 1084 return false; 1085 1086 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1087 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1088 1089 // C++ [temp.fct]p2: 1090 // A function template can be overloaded with other function templates 1091 // and with normal (non-template) functions. 1092 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1093 return true; 1094 1095 // Is the function New an overload of the function Old? 1096 QualType OldQType = Context.getCanonicalType(Old->getType()); 1097 QualType NewQType = Context.getCanonicalType(New->getType()); 1098 1099 // Compare the signatures (C++ 1.3.10) of the two functions to 1100 // determine whether they are overloads. If we find any mismatch 1101 // in the signature, they are overloads. 1102 1103 // If either of these functions is a K&R-style function (no 1104 // prototype), then we consider them to have matching signatures. 1105 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1106 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1107 return false; 1108 1109 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1110 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1111 1112 // The signature of a function includes the types of its 1113 // parameters (C++ 1.3.10), which includes the presence or absence 1114 // of the ellipsis; see C++ DR 357). 1115 if (OldQType != NewQType && 1116 (OldType->getNumParams() != NewType->getNumParams() || 1117 OldType->isVariadic() != NewType->isVariadic() || 1118 !FunctionParamTypesAreEqual(OldType, NewType))) 1119 return true; 1120 1121 // C++ [temp.over.link]p4: 1122 // The signature of a function template consists of its function 1123 // signature, its return type and its template parameter list. The names 1124 // of the template parameters are significant only for establishing the 1125 // relationship between the template parameters and the rest of the 1126 // signature. 1127 // 1128 // We check the return type and template parameter lists for function 1129 // templates first; the remaining checks follow. 1130 // 1131 // However, we don't consider either of these when deciding whether 1132 // a member introduced by a shadow declaration is hidden. 1133 if (!UseMemberUsingDeclRules && NewTemplate && 1134 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1135 OldTemplate->getTemplateParameters(), 1136 false, TPL_TemplateMatch) || 1137 !Context.hasSameType(Old->getDeclaredReturnType(), 1138 New->getDeclaredReturnType()))) 1139 return true; 1140 1141 // If the function is a class member, its signature includes the 1142 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1143 // 1144 // As part of this, also check whether one of the member functions 1145 // is static, in which case they are not overloads (C++ 1146 // 13.1p2). While not part of the definition of the signature, 1147 // this check is important to determine whether these functions 1148 // can be overloaded. 1149 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1150 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1151 if (OldMethod && NewMethod && 1152 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1153 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1154 if (!UseMemberUsingDeclRules && 1155 (OldMethod->getRefQualifier() == RQ_None || 1156 NewMethod->getRefQualifier() == RQ_None)) { 1157 // C++0x [over.load]p2: 1158 // - Member function declarations with the same name and the same 1159 // parameter-type-list as well as member function template 1160 // declarations with the same name, the same parameter-type-list, and 1161 // the same template parameter lists cannot be overloaded if any of 1162 // them, but not all, have a ref-qualifier (8.3.5). 1163 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1164 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1165 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1166 } 1167 return true; 1168 } 1169 1170 // We may not have applied the implicit const for a constexpr member 1171 // function yet (because we haven't yet resolved whether this is a static 1172 // or non-static member function). Add it now, on the assumption that this 1173 // is a redeclaration of OldMethod. 1174 auto OldQuals = OldMethod->getMethodQualifiers(); 1175 auto NewQuals = NewMethod->getMethodQualifiers(); 1176 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1177 !isa<CXXConstructorDecl>(NewMethod)) 1178 NewQuals.addConst(); 1179 // We do not allow overloading based off of '__restrict'. 1180 OldQuals.removeRestrict(); 1181 NewQuals.removeRestrict(); 1182 if (OldQuals != NewQuals) 1183 return true; 1184 } 1185 1186 // Though pass_object_size is placed on parameters and takes an argument, we 1187 // consider it to be a function-level modifier for the sake of function 1188 // identity. Either the function has one or more parameters with 1189 // pass_object_size or it doesn't. 1190 if (functionHasPassObjectSizeParams(New) != 1191 functionHasPassObjectSizeParams(Old)) 1192 return true; 1193 1194 // enable_if attributes are an order-sensitive part of the signature. 1195 for (specific_attr_iterator<EnableIfAttr> 1196 NewI = New->specific_attr_begin<EnableIfAttr>(), 1197 NewE = New->specific_attr_end<EnableIfAttr>(), 1198 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1199 OldE = Old->specific_attr_end<EnableIfAttr>(); 1200 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1201 if (NewI == NewE || OldI == OldE) 1202 return true; 1203 llvm::FoldingSetNodeID NewID, OldID; 1204 NewI->getCond()->Profile(NewID, Context, true); 1205 OldI->getCond()->Profile(OldID, Context, true); 1206 if (NewID != OldID) 1207 return true; 1208 } 1209 1210 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1211 // Don't allow overloading of destructors. (In theory we could, but it 1212 // would be a giant change to clang.) 1213 if (isa<CXXDestructorDecl>(New)) 1214 return false; 1215 1216 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1217 OldTarget = IdentifyCUDATarget(Old); 1218 if (NewTarget == CFT_InvalidTarget) 1219 return false; 1220 1221 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1222 1223 // Allow overloading of functions with same signature and different CUDA 1224 // target attributes. 1225 return NewTarget != OldTarget; 1226 } 1227 1228 // The signatures match; this is not an overload. 1229 return false; 1230 } 1231 1232 /// Checks availability of the function depending on the current 1233 /// function context. Inside an unavailable function, unavailability is ignored. 1234 /// 1235 /// \returns true if \arg FD is unavailable and current context is inside 1236 /// an available function, false otherwise. 1237 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1238 if (!FD->isUnavailable()) 1239 return false; 1240 1241 // Walk up the context of the caller. 1242 Decl *C = cast<Decl>(CurContext); 1243 do { 1244 if (C->isUnavailable()) 1245 return false; 1246 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1247 return true; 1248 } 1249 1250 /// Tries a user-defined conversion from From to ToType. 1251 /// 1252 /// Produces an implicit conversion sequence for when a standard conversion 1253 /// is not an option. See TryImplicitConversion for more information. 1254 static ImplicitConversionSequence 1255 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1256 bool SuppressUserConversions, 1257 bool AllowExplicit, 1258 bool InOverloadResolution, 1259 bool CStyle, 1260 bool AllowObjCWritebackConversion, 1261 bool AllowObjCConversionOnExplicit) { 1262 ImplicitConversionSequence ICS; 1263 1264 if (SuppressUserConversions) { 1265 // We're not in the case above, so there is no conversion that 1266 // we can perform. 1267 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1268 return ICS; 1269 } 1270 1271 // Attempt user-defined conversion. 1272 OverloadCandidateSet Conversions(From->getExprLoc(), 1273 OverloadCandidateSet::CSK_Normal); 1274 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1275 Conversions, AllowExplicit, 1276 AllowObjCConversionOnExplicit)) { 1277 case OR_Success: 1278 case OR_Deleted: 1279 ICS.setUserDefined(); 1280 // C++ [over.ics.user]p4: 1281 // A conversion of an expression of class type to the same class 1282 // type is given Exact Match rank, and a conversion of an 1283 // expression of class type to a base class of that type is 1284 // given Conversion rank, in spite of the fact that a copy 1285 // constructor (i.e., a user-defined conversion function) is 1286 // called for those cases. 1287 if (CXXConstructorDecl *Constructor 1288 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1289 QualType FromCanon 1290 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1291 QualType ToCanon 1292 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1293 if (Constructor->isCopyConstructor() && 1294 (FromCanon == ToCanon || 1295 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1296 // Turn this into a "standard" conversion sequence, so that it 1297 // gets ranked with standard conversion sequences. 1298 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1299 ICS.setStandard(); 1300 ICS.Standard.setAsIdentityConversion(); 1301 ICS.Standard.setFromType(From->getType()); 1302 ICS.Standard.setAllToTypes(ToType); 1303 ICS.Standard.CopyConstructor = Constructor; 1304 ICS.Standard.FoundCopyConstructor = Found; 1305 if (ToCanon != FromCanon) 1306 ICS.Standard.Second = ICK_Derived_To_Base; 1307 } 1308 } 1309 break; 1310 1311 case OR_Ambiguous: 1312 ICS.setAmbiguous(); 1313 ICS.Ambiguous.setFromType(From->getType()); 1314 ICS.Ambiguous.setToType(ToType); 1315 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1316 Cand != Conversions.end(); ++Cand) 1317 if (Cand->Viable) 1318 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1319 break; 1320 1321 // Fall through. 1322 case OR_No_Viable_Function: 1323 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1324 break; 1325 } 1326 1327 return ICS; 1328 } 1329 1330 /// TryImplicitConversion - Attempt to perform an implicit conversion 1331 /// from the given expression (Expr) to the given type (ToType). This 1332 /// function returns an implicit conversion sequence that can be used 1333 /// to perform the initialization. Given 1334 /// 1335 /// void f(float f); 1336 /// void g(int i) { f(i); } 1337 /// 1338 /// this routine would produce an implicit conversion sequence to 1339 /// describe the initialization of f from i, which will be a standard 1340 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1341 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1342 // 1343 /// Note that this routine only determines how the conversion can be 1344 /// performed; it does not actually perform the conversion. As such, 1345 /// it will not produce any diagnostics if no conversion is available, 1346 /// but will instead return an implicit conversion sequence of kind 1347 /// "BadConversion". 1348 /// 1349 /// If @p SuppressUserConversions, then user-defined conversions are 1350 /// not permitted. 1351 /// If @p AllowExplicit, then explicit user-defined conversions are 1352 /// permitted. 1353 /// 1354 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1355 /// writeback conversion, which allows __autoreleasing id* parameters to 1356 /// be initialized with __strong id* or __weak id* arguments. 1357 static ImplicitConversionSequence 1358 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1359 bool SuppressUserConversions, 1360 bool AllowExplicit, 1361 bool InOverloadResolution, 1362 bool CStyle, 1363 bool AllowObjCWritebackConversion, 1364 bool AllowObjCConversionOnExplicit) { 1365 ImplicitConversionSequence ICS; 1366 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1367 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1368 ICS.setStandard(); 1369 return ICS; 1370 } 1371 1372 if (!S.getLangOpts().CPlusPlus) { 1373 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1374 return ICS; 1375 } 1376 1377 // C++ [over.ics.user]p4: 1378 // A conversion of an expression of class type to the same class 1379 // type is given Exact Match rank, and a conversion of an 1380 // expression of class type to a base class of that type is 1381 // given Conversion rank, in spite of the fact that a copy/move 1382 // constructor (i.e., a user-defined conversion function) is 1383 // called for those cases. 1384 QualType FromType = From->getType(); 1385 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1386 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1387 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1388 ICS.setStandard(); 1389 ICS.Standard.setAsIdentityConversion(); 1390 ICS.Standard.setFromType(FromType); 1391 ICS.Standard.setAllToTypes(ToType); 1392 1393 // We don't actually check at this point whether there is a valid 1394 // copy/move constructor, since overloading just assumes that it 1395 // exists. When we actually perform initialization, we'll find the 1396 // appropriate constructor to copy the returned object, if needed. 1397 ICS.Standard.CopyConstructor = nullptr; 1398 1399 // Determine whether this is considered a derived-to-base conversion. 1400 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1401 ICS.Standard.Second = ICK_Derived_To_Base; 1402 1403 return ICS; 1404 } 1405 1406 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1407 AllowExplicit, InOverloadResolution, CStyle, 1408 AllowObjCWritebackConversion, 1409 AllowObjCConversionOnExplicit); 1410 } 1411 1412 ImplicitConversionSequence 1413 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1414 bool SuppressUserConversions, 1415 bool AllowExplicit, 1416 bool InOverloadResolution, 1417 bool CStyle, 1418 bool AllowObjCWritebackConversion) { 1419 return ::TryImplicitConversion(*this, From, ToType, 1420 SuppressUserConversions, AllowExplicit, 1421 InOverloadResolution, CStyle, 1422 AllowObjCWritebackConversion, 1423 /*AllowObjCConversionOnExplicit=*/false); 1424 } 1425 1426 /// PerformImplicitConversion - Perform an implicit conversion of the 1427 /// expression From to the type ToType. Returns the 1428 /// converted expression. Flavor is the kind of conversion we're 1429 /// performing, used in the error message. If @p AllowExplicit, 1430 /// explicit user-defined conversions are permitted. 1431 ExprResult 1432 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1433 AssignmentAction Action, bool AllowExplicit) { 1434 ImplicitConversionSequence ICS; 1435 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1436 } 1437 1438 ExprResult 1439 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1440 AssignmentAction Action, bool AllowExplicit, 1441 ImplicitConversionSequence& ICS) { 1442 if (checkPlaceholderForOverload(*this, From)) 1443 return ExprError(); 1444 1445 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1446 bool AllowObjCWritebackConversion 1447 = getLangOpts().ObjCAutoRefCount && 1448 (Action == AA_Passing || Action == AA_Sending); 1449 if (getLangOpts().ObjC) 1450 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1451 From->getType(), From); 1452 ICS = ::TryImplicitConversion(*this, From, ToType, 1453 /*SuppressUserConversions=*/false, 1454 AllowExplicit, 1455 /*InOverloadResolution=*/false, 1456 /*CStyle=*/false, 1457 AllowObjCWritebackConversion, 1458 /*AllowObjCConversionOnExplicit=*/false); 1459 return PerformImplicitConversion(From, ToType, ICS, Action); 1460 } 1461 1462 /// Determine whether the conversion from FromType to ToType is a valid 1463 /// conversion that strips "noexcept" or "noreturn" off the nested function 1464 /// type. 1465 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1466 QualType &ResultTy) { 1467 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1468 return false; 1469 1470 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1471 // or F(t noexcept) -> F(t) 1472 // where F adds one of the following at most once: 1473 // - a pointer 1474 // - a member pointer 1475 // - a block pointer 1476 // Changes here need matching changes in FindCompositePointerType. 1477 CanQualType CanTo = Context.getCanonicalType(ToType); 1478 CanQualType CanFrom = Context.getCanonicalType(FromType); 1479 Type::TypeClass TyClass = CanTo->getTypeClass(); 1480 if (TyClass != CanFrom->getTypeClass()) return false; 1481 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1482 if (TyClass == Type::Pointer) { 1483 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1484 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1485 } else if (TyClass == Type::BlockPointer) { 1486 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1487 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1488 } else if (TyClass == Type::MemberPointer) { 1489 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1490 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1491 // A function pointer conversion cannot change the class of the function. 1492 if (ToMPT->getClass() != FromMPT->getClass()) 1493 return false; 1494 CanTo = ToMPT->getPointeeType(); 1495 CanFrom = FromMPT->getPointeeType(); 1496 } else { 1497 return false; 1498 } 1499 1500 TyClass = CanTo->getTypeClass(); 1501 if (TyClass != CanFrom->getTypeClass()) return false; 1502 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1503 return false; 1504 } 1505 1506 const auto *FromFn = cast<FunctionType>(CanFrom); 1507 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1508 1509 const auto *ToFn = cast<FunctionType>(CanTo); 1510 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1511 1512 bool Changed = false; 1513 1514 // Drop 'noreturn' if not present in target type. 1515 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1516 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1517 Changed = true; 1518 } 1519 1520 // Drop 'noexcept' if not present in target type. 1521 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1522 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1523 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1524 FromFn = cast<FunctionType>( 1525 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1526 EST_None) 1527 .getTypePtr()); 1528 Changed = true; 1529 } 1530 1531 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1532 // only if the ExtParameterInfo lists of the two function prototypes can be 1533 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1534 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1535 bool CanUseToFPT, CanUseFromFPT; 1536 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1537 CanUseFromFPT, NewParamInfos) && 1538 CanUseToFPT && !CanUseFromFPT) { 1539 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1540 ExtInfo.ExtParameterInfos = 1541 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1542 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1543 FromFPT->getParamTypes(), ExtInfo); 1544 FromFn = QT->getAs<FunctionType>(); 1545 Changed = true; 1546 } 1547 } 1548 1549 if (!Changed) 1550 return false; 1551 1552 assert(QualType(FromFn, 0).isCanonical()); 1553 if (QualType(FromFn, 0) != CanTo) return false; 1554 1555 ResultTy = ToType; 1556 return true; 1557 } 1558 1559 /// Determine whether the conversion from FromType to ToType is a valid 1560 /// vector conversion. 1561 /// 1562 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1563 /// conversion. 1564 static bool IsVectorConversion(Sema &S, QualType FromType, 1565 QualType ToType, ImplicitConversionKind &ICK) { 1566 // We need at least one of these types to be a vector type to have a vector 1567 // conversion. 1568 if (!ToType->isVectorType() && !FromType->isVectorType()) 1569 return false; 1570 1571 // Identical types require no conversions. 1572 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1573 return false; 1574 1575 // There are no conversions between extended vector types, only identity. 1576 if (ToType->isExtVectorType()) { 1577 // There are no conversions between extended vector types other than the 1578 // identity conversion. 1579 if (FromType->isExtVectorType()) 1580 return false; 1581 1582 // Vector splat from any arithmetic type to a vector. 1583 if (FromType->isArithmeticType()) { 1584 ICK = ICK_Vector_Splat; 1585 return true; 1586 } 1587 } 1588 1589 // We can perform the conversion between vector types in the following cases: 1590 // 1)vector types are equivalent AltiVec and GCC vector types 1591 // 2)lax vector conversions are permitted and the vector types are of the 1592 // same size 1593 if (ToType->isVectorType() && FromType->isVectorType()) { 1594 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1595 S.isLaxVectorConversion(FromType, ToType)) { 1596 ICK = ICK_Vector_Conversion; 1597 return true; 1598 } 1599 } 1600 1601 return false; 1602 } 1603 1604 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1605 bool InOverloadResolution, 1606 StandardConversionSequence &SCS, 1607 bool CStyle); 1608 1609 /// IsStandardConversion - Determines whether there is a standard 1610 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1611 /// expression From to the type ToType. Standard conversion sequences 1612 /// only consider non-class types; for conversions that involve class 1613 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1614 /// contain the standard conversion sequence required to perform this 1615 /// conversion and this routine will return true. Otherwise, this 1616 /// routine will return false and the value of SCS is unspecified. 1617 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1618 bool InOverloadResolution, 1619 StandardConversionSequence &SCS, 1620 bool CStyle, 1621 bool AllowObjCWritebackConversion) { 1622 QualType FromType = From->getType(); 1623 1624 // Standard conversions (C++ [conv]) 1625 SCS.setAsIdentityConversion(); 1626 SCS.IncompatibleObjC = false; 1627 SCS.setFromType(FromType); 1628 SCS.CopyConstructor = nullptr; 1629 1630 // There are no standard conversions for class types in C++, so 1631 // abort early. When overloading in C, however, we do permit them. 1632 if (S.getLangOpts().CPlusPlus && 1633 (FromType->isRecordType() || ToType->isRecordType())) 1634 return false; 1635 1636 // The first conversion can be an lvalue-to-rvalue conversion, 1637 // array-to-pointer conversion, or function-to-pointer conversion 1638 // (C++ 4p1). 1639 1640 if (FromType == S.Context.OverloadTy) { 1641 DeclAccessPair AccessPair; 1642 if (FunctionDecl *Fn 1643 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1644 AccessPair)) { 1645 // We were able to resolve the address of the overloaded function, 1646 // so we can convert to the type of that function. 1647 FromType = Fn->getType(); 1648 SCS.setFromType(FromType); 1649 1650 // we can sometimes resolve &foo<int> regardless of ToType, so check 1651 // if the type matches (identity) or we are converting to bool 1652 if (!S.Context.hasSameUnqualifiedType( 1653 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1654 QualType resultTy; 1655 // if the function type matches except for [[noreturn]], it's ok 1656 if (!S.IsFunctionConversion(FromType, 1657 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1658 // otherwise, only a boolean conversion is standard 1659 if (!ToType->isBooleanType()) 1660 return false; 1661 } 1662 1663 // Check if the "from" expression is taking the address of an overloaded 1664 // function and recompute the FromType accordingly. Take advantage of the 1665 // fact that non-static member functions *must* have such an address-of 1666 // expression. 1667 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1668 if (Method && !Method->isStatic()) { 1669 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1670 "Non-unary operator on non-static member address"); 1671 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1672 == UO_AddrOf && 1673 "Non-address-of operator on non-static member address"); 1674 const Type *ClassType 1675 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1676 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1677 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1678 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1679 UO_AddrOf && 1680 "Non-address-of operator for overloaded function expression"); 1681 FromType = S.Context.getPointerType(FromType); 1682 } 1683 1684 // Check that we've computed the proper type after overload resolution. 1685 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1686 // be calling it from within an NDEBUG block. 1687 assert(S.Context.hasSameType( 1688 FromType, 1689 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1690 } else { 1691 return false; 1692 } 1693 } 1694 // Lvalue-to-rvalue conversion (C++11 4.1): 1695 // A glvalue (3.10) of a non-function, non-array type T can 1696 // be converted to a prvalue. 1697 bool argIsLValue = From->isGLValue(); 1698 if (argIsLValue && 1699 !FromType->isFunctionType() && !FromType->isArrayType() && 1700 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1701 SCS.First = ICK_Lvalue_To_Rvalue; 1702 1703 // C11 6.3.2.1p2: 1704 // ... if the lvalue has atomic type, the value has the non-atomic version 1705 // of the type of the lvalue ... 1706 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1707 FromType = Atomic->getValueType(); 1708 1709 // If T is a non-class type, the type of the rvalue is the 1710 // cv-unqualified version of T. Otherwise, the type of the rvalue 1711 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1712 // just strip the qualifiers because they don't matter. 1713 FromType = FromType.getUnqualifiedType(); 1714 } else if (FromType->isArrayType()) { 1715 // Array-to-pointer conversion (C++ 4.2) 1716 SCS.First = ICK_Array_To_Pointer; 1717 1718 // An lvalue or rvalue of type "array of N T" or "array of unknown 1719 // bound of T" can be converted to an rvalue of type "pointer to 1720 // T" (C++ 4.2p1). 1721 FromType = S.Context.getArrayDecayedType(FromType); 1722 1723 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1724 // This conversion is deprecated in C++03 (D.4) 1725 SCS.DeprecatedStringLiteralToCharPtr = true; 1726 1727 // For the purpose of ranking in overload resolution 1728 // (13.3.3.1.1), this conversion is considered an 1729 // array-to-pointer conversion followed by a qualification 1730 // conversion (4.4). (C++ 4.2p2) 1731 SCS.Second = ICK_Identity; 1732 SCS.Third = ICK_Qualification; 1733 SCS.QualificationIncludesObjCLifetime = false; 1734 SCS.setAllToTypes(FromType); 1735 return true; 1736 } 1737 } else if (FromType->isFunctionType() && argIsLValue) { 1738 // Function-to-pointer conversion (C++ 4.3). 1739 SCS.First = ICK_Function_To_Pointer; 1740 1741 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1742 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1743 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1744 return false; 1745 1746 // An lvalue of function type T can be converted to an rvalue of 1747 // type "pointer to T." The result is a pointer to the 1748 // function. (C++ 4.3p1). 1749 FromType = S.Context.getPointerType(FromType); 1750 } else { 1751 // We don't require any conversions for the first step. 1752 SCS.First = ICK_Identity; 1753 } 1754 SCS.setToType(0, FromType); 1755 1756 // The second conversion can be an integral promotion, floating 1757 // point promotion, integral conversion, floating point conversion, 1758 // floating-integral conversion, pointer conversion, 1759 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1760 // For overloading in C, this can also be a "compatible-type" 1761 // conversion. 1762 bool IncompatibleObjC = false; 1763 ImplicitConversionKind SecondICK = ICK_Identity; 1764 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1765 // The unqualified versions of the types are the same: there's no 1766 // conversion to do. 1767 SCS.Second = ICK_Identity; 1768 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1769 // Integral promotion (C++ 4.5). 1770 SCS.Second = ICK_Integral_Promotion; 1771 FromType = ToType.getUnqualifiedType(); 1772 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1773 // Floating point promotion (C++ 4.6). 1774 SCS.Second = ICK_Floating_Promotion; 1775 FromType = ToType.getUnqualifiedType(); 1776 } else if (S.IsComplexPromotion(FromType, ToType)) { 1777 // Complex promotion (Clang extension) 1778 SCS.Second = ICK_Complex_Promotion; 1779 FromType = ToType.getUnqualifiedType(); 1780 } else if (ToType->isBooleanType() && 1781 (FromType->isArithmeticType() || 1782 FromType->isAnyPointerType() || 1783 FromType->isBlockPointerType() || 1784 FromType->isMemberPointerType() || 1785 FromType->isNullPtrType())) { 1786 // Boolean conversions (C++ 4.12). 1787 SCS.Second = ICK_Boolean_Conversion; 1788 FromType = S.Context.BoolTy; 1789 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1790 ToType->isIntegralType(S.Context)) { 1791 // Integral conversions (C++ 4.7). 1792 SCS.Second = ICK_Integral_Conversion; 1793 FromType = ToType.getUnqualifiedType(); 1794 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1795 // Complex conversions (C99 6.3.1.6) 1796 SCS.Second = ICK_Complex_Conversion; 1797 FromType = ToType.getUnqualifiedType(); 1798 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1799 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1800 // Complex-real conversions (C99 6.3.1.7) 1801 SCS.Second = ICK_Complex_Real; 1802 FromType = ToType.getUnqualifiedType(); 1803 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1804 // FIXME: disable conversions between long double and __float128 if 1805 // their representation is different until there is back end support 1806 // We of course allow this conversion if long double is really double. 1807 if (&S.Context.getFloatTypeSemantics(FromType) != 1808 &S.Context.getFloatTypeSemantics(ToType)) { 1809 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1810 ToType == S.Context.LongDoubleTy) || 1811 (FromType == S.Context.LongDoubleTy && 1812 ToType == S.Context.Float128Ty)); 1813 if (Float128AndLongDouble && 1814 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1815 &llvm::APFloat::PPCDoubleDouble())) 1816 return false; 1817 } 1818 // Floating point conversions (C++ 4.8). 1819 SCS.Second = ICK_Floating_Conversion; 1820 FromType = ToType.getUnqualifiedType(); 1821 } else if ((FromType->isRealFloatingType() && 1822 ToType->isIntegralType(S.Context)) || 1823 (FromType->isIntegralOrUnscopedEnumerationType() && 1824 ToType->isRealFloatingType())) { 1825 // Floating-integral conversions (C++ 4.9). 1826 SCS.Second = ICK_Floating_Integral; 1827 FromType = ToType.getUnqualifiedType(); 1828 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1829 SCS.Second = ICK_Block_Pointer_Conversion; 1830 } else if (AllowObjCWritebackConversion && 1831 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1832 SCS.Second = ICK_Writeback_Conversion; 1833 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1834 FromType, IncompatibleObjC)) { 1835 // Pointer conversions (C++ 4.10). 1836 SCS.Second = ICK_Pointer_Conversion; 1837 SCS.IncompatibleObjC = IncompatibleObjC; 1838 FromType = FromType.getUnqualifiedType(); 1839 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1840 InOverloadResolution, FromType)) { 1841 // Pointer to member conversions (4.11). 1842 SCS.Second = ICK_Pointer_Member; 1843 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1844 SCS.Second = SecondICK; 1845 FromType = ToType.getUnqualifiedType(); 1846 } else if (!S.getLangOpts().CPlusPlus && 1847 S.Context.typesAreCompatible(ToType, FromType)) { 1848 // Compatible conversions (Clang extension for C function overloading) 1849 SCS.Second = ICK_Compatible_Conversion; 1850 FromType = ToType.getUnqualifiedType(); 1851 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1852 InOverloadResolution, 1853 SCS, CStyle)) { 1854 SCS.Second = ICK_TransparentUnionConversion; 1855 FromType = ToType; 1856 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1857 CStyle)) { 1858 // tryAtomicConversion has updated the standard conversion sequence 1859 // appropriately. 1860 return true; 1861 } else if (ToType->isEventT() && 1862 From->isIntegerConstantExpr(S.getASTContext()) && 1863 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1864 SCS.Second = ICK_Zero_Event_Conversion; 1865 FromType = ToType; 1866 } else if (ToType->isQueueT() && 1867 From->isIntegerConstantExpr(S.getASTContext()) && 1868 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1869 SCS.Second = ICK_Zero_Queue_Conversion; 1870 FromType = ToType; 1871 } else { 1872 // No second conversion required. 1873 SCS.Second = ICK_Identity; 1874 } 1875 SCS.setToType(1, FromType); 1876 1877 // The third conversion can be a function pointer conversion or a 1878 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1879 bool ObjCLifetimeConversion; 1880 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1881 // Function pointer conversions (removing 'noexcept') including removal of 1882 // 'noreturn' (Clang extension). 1883 SCS.Third = ICK_Function_Conversion; 1884 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1885 ObjCLifetimeConversion)) { 1886 SCS.Third = ICK_Qualification; 1887 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1888 FromType = ToType; 1889 } else { 1890 // No conversion required 1891 SCS.Third = ICK_Identity; 1892 } 1893 1894 // C++ [over.best.ics]p6: 1895 // [...] Any difference in top-level cv-qualification is 1896 // subsumed by the initialization itself and does not constitute 1897 // a conversion. [...] 1898 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1899 QualType CanonTo = S.Context.getCanonicalType(ToType); 1900 if (CanonFrom.getLocalUnqualifiedType() 1901 == CanonTo.getLocalUnqualifiedType() && 1902 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1903 FromType = ToType; 1904 CanonFrom = CanonTo; 1905 } 1906 1907 SCS.setToType(2, FromType); 1908 1909 if (CanonFrom == CanonTo) 1910 return true; 1911 1912 // If we have not converted the argument type to the parameter type, 1913 // this is a bad conversion sequence, unless we're resolving an overload in C. 1914 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1915 return false; 1916 1917 ExprResult ER = ExprResult{From}; 1918 Sema::AssignConvertType Conv = 1919 S.CheckSingleAssignmentConstraints(ToType, ER, 1920 /*Diagnose=*/false, 1921 /*DiagnoseCFAudited=*/false, 1922 /*ConvertRHS=*/false); 1923 ImplicitConversionKind SecondConv; 1924 switch (Conv) { 1925 case Sema::Compatible: 1926 SecondConv = ICK_C_Only_Conversion; 1927 break; 1928 // For our purposes, discarding qualifiers is just as bad as using an 1929 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1930 // qualifiers, as well. 1931 case Sema::CompatiblePointerDiscardsQualifiers: 1932 case Sema::IncompatiblePointer: 1933 case Sema::IncompatiblePointerSign: 1934 SecondConv = ICK_Incompatible_Pointer_Conversion; 1935 break; 1936 default: 1937 return false; 1938 } 1939 1940 // First can only be an lvalue conversion, so we pretend that this was the 1941 // second conversion. First should already be valid from earlier in the 1942 // function. 1943 SCS.Second = SecondConv; 1944 SCS.setToType(1, ToType); 1945 1946 // Third is Identity, because Second should rank us worse than any other 1947 // conversion. This could also be ICK_Qualification, but it's simpler to just 1948 // lump everything in with the second conversion, and we don't gain anything 1949 // from making this ICK_Qualification. 1950 SCS.Third = ICK_Identity; 1951 SCS.setToType(2, ToType); 1952 return true; 1953 } 1954 1955 static bool 1956 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1957 QualType &ToType, 1958 bool InOverloadResolution, 1959 StandardConversionSequence &SCS, 1960 bool CStyle) { 1961 1962 const RecordType *UT = ToType->getAsUnionType(); 1963 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1964 return false; 1965 // The field to initialize within the transparent union. 1966 RecordDecl *UD = UT->getDecl(); 1967 // It's compatible if the expression matches any of the fields. 1968 for (const auto *it : UD->fields()) { 1969 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1970 CStyle, /*ObjCWritebackConversion=*/false)) { 1971 ToType = it->getType(); 1972 return true; 1973 } 1974 } 1975 return false; 1976 } 1977 1978 /// IsIntegralPromotion - Determines whether the conversion from the 1979 /// expression From (whose potentially-adjusted type is FromType) to 1980 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1981 /// sets PromotedType to the promoted type. 1982 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1983 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1984 // All integers are built-in. 1985 if (!To) { 1986 return false; 1987 } 1988 1989 // An rvalue of type char, signed char, unsigned char, short int, or 1990 // unsigned short int can be converted to an rvalue of type int if 1991 // int can represent all the values of the source type; otherwise, 1992 // the source rvalue can be converted to an rvalue of type unsigned 1993 // int (C++ 4.5p1). 1994 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1995 !FromType->isEnumeralType()) { 1996 if (// We can promote any signed, promotable integer type to an int 1997 (FromType->isSignedIntegerType() || 1998 // We can promote any unsigned integer type whose size is 1999 // less than int to an int. 2000 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2001 return To->getKind() == BuiltinType::Int; 2002 } 2003 2004 return To->getKind() == BuiltinType::UInt; 2005 } 2006 2007 // C++11 [conv.prom]p3: 2008 // A prvalue of an unscoped enumeration type whose underlying type is not 2009 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2010 // following types that can represent all the values of the enumeration 2011 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2012 // unsigned int, long int, unsigned long int, long long int, or unsigned 2013 // long long int. If none of the types in that list can represent all the 2014 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2015 // type can be converted to an rvalue a prvalue of the extended integer type 2016 // with lowest integer conversion rank (4.13) greater than the rank of long 2017 // long in which all the values of the enumeration can be represented. If 2018 // there are two such extended types, the signed one is chosen. 2019 // C++11 [conv.prom]p4: 2020 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2021 // can be converted to a prvalue of its underlying type. Moreover, if 2022 // integral promotion can be applied to its underlying type, a prvalue of an 2023 // unscoped enumeration type whose underlying type is fixed can also be 2024 // converted to a prvalue of the promoted underlying type. 2025 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2026 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2027 // provided for a scoped enumeration. 2028 if (FromEnumType->getDecl()->isScoped()) 2029 return false; 2030 2031 // We can perform an integral promotion to the underlying type of the enum, 2032 // even if that's not the promoted type. Note that the check for promoting 2033 // the underlying type is based on the type alone, and does not consider 2034 // the bitfield-ness of the actual source expression. 2035 if (FromEnumType->getDecl()->isFixed()) { 2036 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2037 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2038 IsIntegralPromotion(nullptr, Underlying, ToType); 2039 } 2040 2041 // We have already pre-calculated the promotion type, so this is trivial. 2042 if (ToType->isIntegerType() && 2043 isCompleteType(From->getBeginLoc(), FromType)) 2044 return Context.hasSameUnqualifiedType( 2045 ToType, FromEnumType->getDecl()->getPromotionType()); 2046 2047 // C++ [conv.prom]p5: 2048 // If the bit-field has an enumerated type, it is treated as any other 2049 // value of that type for promotion purposes. 2050 // 2051 // ... so do not fall through into the bit-field checks below in C++. 2052 if (getLangOpts().CPlusPlus) 2053 return false; 2054 } 2055 2056 // C++0x [conv.prom]p2: 2057 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2058 // to an rvalue a prvalue of the first of the following types that can 2059 // represent all the values of its underlying type: int, unsigned int, 2060 // long int, unsigned long int, long long int, or unsigned long long int. 2061 // If none of the types in that list can represent all the values of its 2062 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2063 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2064 // type. 2065 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2066 ToType->isIntegerType()) { 2067 // Determine whether the type we're converting from is signed or 2068 // unsigned. 2069 bool FromIsSigned = FromType->isSignedIntegerType(); 2070 uint64_t FromSize = Context.getTypeSize(FromType); 2071 2072 // The types we'll try to promote to, in the appropriate 2073 // order. Try each of these types. 2074 QualType PromoteTypes[6] = { 2075 Context.IntTy, Context.UnsignedIntTy, 2076 Context.LongTy, Context.UnsignedLongTy , 2077 Context.LongLongTy, Context.UnsignedLongLongTy 2078 }; 2079 for (int Idx = 0; Idx < 6; ++Idx) { 2080 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2081 if (FromSize < ToSize || 2082 (FromSize == ToSize && 2083 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2084 // We found the type that we can promote to. If this is the 2085 // type we wanted, we have a promotion. Otherwise, no 2086 // promotion. 2087 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2088 } 2089 } 2090 } 2091 2092 // An rvalue for an integral bit-field (9.6) can be converted to an 2093 // rvalue of type int if int can represent all the values of the 2094 // bit-field; otherwise, it can be converted to unsigned int if 2095 // unsigned int can represent all the values of the bit-field. If 2096 // the bit-field is larger yet, no integral promotion applies to 2097 // it. If the bit-field has an enumerated type, it is treated as any 2098 // other value of that type for promotion purposes (C++ 4.5p3). 2099 // FIXME: We should delay checking of bit-fields until we actually perform the 2100 // conversion. 2101 // 2102 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2103 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2104 // bit-fields and those whose underlying type is larger than int) for GCC 2105 // compatibility. 2106 if (From) { 2107 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2108 llvm::APSInt BitWidth; 2109 if (FromType->isIntegralType(Context) && 2110 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2111 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2112 ToSize = Context.getTypeSize(ToType); 2113 2114 // Are we promoting to an int from a bitfield that fits in an int? 2115 if (BitWidth < ToSize || 2116 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2117 return To->getKind() == BuiltinType::Int; 2118 } 2119 2120 // Are we promoting to an unsigned int from an unsigned bitfield 2121 // that fits into an unsigned int? 2122 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2123 return To->getKind() == BuiltinType::UInt; 2124 } 2125 2126 return false; 2127 } 2128 } 2129 } 2130 2131 // An rvalue of type bool can be converted to an rvalue of type int, 2132 // with false becoming zero and true becoming one (C++ 4.5p4). 2133 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2134 return true; 2135 } 2136 2137 return false; 2138 } 2139 2140 /// IsFloatingPointPromotion - Determines whether the conversion from 2141 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2142 /// returns true and sets PromotedType to the promoted type. 2143 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2144 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2145 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2146 /// An rvalue of type float can be converted to an rvalue of type 2147 /// double. (C++ 4.6p1). 2148 if (FromBuiltin->getKind() == BuiltinType::Float && 2149 ToBuiltin->getKind() == BuiltinType::Double) 2150 return true; 2151 2152 // C99 6.3.1.5p1: 2153 // When a float is promoted to double or long double, or a 2154 // double is promoted to long double [...]. 2155 if (!getLangOpts().CPlusPlus && 2156 (FromBuiltin->getKind() == BuiltinType::Float || 2157 FromBuiltin->getKind() == BuiltinType::Double) && 2158 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2159 ToBuiltin->getKind() == BuiltinType::Float128)) 2160 return true; 2161 2162 // Half can be promoted to float. 2163 if (!getLangOpts().NativeHalfType && 2164 FromBuiltin->getKind() == BuiltinType::Half && 2165 ToBuiltin->getKind() == BuiltinType::Float) 2166 return true; 2167 } 2168 2169 return false; 2170 } 2171 2172 /// Determine if a conversion is a complex promotion. 2173 /// 2174 /// A complex promotion is defined as a complex -> complex conversion 2175 /// where the conversion between the underlying real types is a 2176 /// floating-point or integral promotion. 2177 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2178 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2179 if (!FromComplex) 2180 return false; 2181 2182 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2183 if (!ToComplex) 2184 return false; 2185 2186 return IsFloatingPointPromotion(FromComplex->getElementType(), 2187 ToComplex->getElementType()) || 2188 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2189 ToComplex->getElementType()); 2190 } 2191 2192 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2193 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2194 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2195 /// if non-empty, will be a pointer to ToType that may or may not have 2196 /// the right set of qualifiers on its pointee. 2197 /// 2198 static QualType 2199 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2200 QualType ToPointee, QualType ToType, 2201 ASTContext &Context, 2202 bool StripObjCLifetime = false) { 2203 assert((FromPtr->getTypeClass() == Type::Pointer || 2204 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2205 "Invalid similarly-qualified pointer type"); 2206 2207 /// Conversions to 'id' subsume cv-qualifier conversions. 2208 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2209 return ToType.getUnqualifiedType(); 2210 2211 QualType CanonFromPointee 2212 = Context.getCanonicalType(FromPtr->getPointeeType()); 2213 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2214 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2215 2216 if (StripObjCLifetime) 2217 Quals.removeObjCLifetime(); 2218 2219 // Exact qualifier match -> return the pointer type we're converting to. 2220 if (CanonToPointee.getLocalQualifiers() == Quals) { 2221 // ToType is exactly what we need. Return it. 2222 if (!ToType.isNull()) 2223 return ToType.getUnqualifiedType(); 2224 2225 // Build a pointer to ToPointee. It has the right qualifiers 2226 // already. 2227 if (isa<ObjCObjectPointerType>(ToType)) 2228 return Context.getObjCObjectPointerType(ToPointee); 2229 return Context.getPointerType(ToPointee); 2230 } 2231 2232 // Just build a canonical type that has the right qualifiers. 2233 QualType QualifiedCanonToPointee 2234 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2235 2236 if (isa<ObjCObjectPointerType>(ToType)) 2237 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2238 return Context.getPointerType(QualifiedCanonToPointee); 2239 } 2240 2241 static bool isNullPointerConstantForConversion(Expr *Expr, 2242 bool InOverloadResolution, 2243 ASTContext &Context) { 2244 // Handle value-dependent integral null pointer constants correctly. 2245 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2246 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2247 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2248 return !InOverloadResolution; 2249 2250 return Expr->isNullPointerConstant(Context, 2251 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2252 : Expr::NPC_ValueDependentIsNull); 2253 } 2254 2255 /// IsPointerConversion - Determines whether the conversion of the 2256 /// expression From, which has the (possibly adjusted) type FromType, 2257 /// can be converted to the type ToType via a pointer conversion (C++ 2258 /// 4.10). If so, returns true and places the converted type (that 2259 /// might differ from ToType in its cv-qualifiers at some level) into 2260 /// ConvertedType. 2261 /// 2262 /// This routine also supports conversions to and from block pointers 2263 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2264 /// pointers to interfaces. FIXME: Once we've determined the 2265 /// appropriate overloading rules for Objective-C, we may want to 2266 /// split the Objective-C checks into a different routine; however, 2267 /// GCC seems to consider all of these conversions to be pointer 2268 /// conversions, so for now they live here. IncompatibleObjC will be 2269 /// set if the conversion is an allowed Objective-C conversion that 2270 /// should result in a warning. 2271 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2272 bool InOverloadResolution, 2273 QualType& ConvertedType, 2274 bool &IncompatibleObjC) { 2275 IncompatibleObjC = false; 2276 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2277 IncompatibleObjC)) 2278 return true; 2279 2280 // Conversion from a null pointer constant to any Objective-C pointer type. 2281 if (ToType->isObjCObjectPointerType() && 2282 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2283 ConvertedType = ToType; 2284 return true; 2285 } 2286 2287 // Blocks: Block pointers can be converted to void*. 2288 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2289 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2290 ConvertedType = ToType; 2291 return true; 2292 } 2293 // Blocks: A null pointer constant can be converted to a block 2294 // pointer type. 2295 if (ToType->isBlockPointerType() && 2296 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2297 ConvertedType = ToType; 2298 return true; 2299 } 2300 2301 // If the left-hand-side is nullptr_t, the right side can be a null 2302 // pointer constant. 2303 if (ToType->isNullPtrType() && 2304 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2305 ConvertedType = ToType; 2306 return true; 2307 } 2308 2309 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2310 if (!ToTypePtr) 2311 return false; 2312 2313 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2314 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2315 ConvertedType = ToType; 2316 return true; 2317 } 2318 2319 // Beyond this point, both types need to be pointers 2320 // , including objective-c pointers. 2321 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2322 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2323 !getLangOpts().ObjCAutoRefCount) { 2324 ConvertedType = BuildSimilarlyQualifiedPointerType( 2325 FromType->getAs<ObjCObjectPointerType>(), 2326 ToPointeeType, 2327 ToType, Context); 2328 return true; 2329 } 2330 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2331 if (!FromTypePtr) 2332 return false; 2333 2334 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2335 2336 // If the unqualified pointee types are the same, this can't be a 2337 // pointer conversion, so don't do all of the work below. 2338 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2339 return false; 2340 2341 // An rvalue of type "pointer to cv T," where T is an object type, 2342 // can be converted to an rvalue of type "pointer to cv void" (C++ 2343 // 4.10p2). 2344 if (FromPointeeType->isIncompleteOrObjectType() && 2345 ToPointeeType->isVoidType()) { 2346 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2347 ToPointeeType, 2348 ToType, Context, 2349 /*StripObjCLifetime=*/true); 2350 return true; 2351 } 2352 2353 // MSVC allows implicit function to void* type conversion. 2354 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2355 ToPointeeType->isVoidType()) { 2356 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2357 ToPointeeType, 2358 ToType, Context); 2359 return true; 2360 } 2361 2362 // When we're overloading in C, we allow a special kind of pointer 2363 // conversion for compatible-but-not-identical pointee types. 2364 if (!getLangOpts().CPlusPlus && 2365 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2366 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2367 ToPointeeType, 2368 ToType, Context); 2369 return true; 2370 } 2371 2372 // C++ [conv.ptr]p3: 2373 // 2374 // An rvalue of type "pointer to cv D," where D is a class type, 2375 // can be converted to an rvalue of type "pointer to cv B," where 2376 // B is a base class (clause 10) of D. If B is an inaccessible 2377 // (clause 11) or ambiguous (10.2) base class of D, a program that 2378 // necessitates this conversion is ill-formed. The result of the 2379 // conversion is a pointer to the base class sub-object of the 2380 // derived class object. The null pointer value is converted to 2381 // the null pointer value of the destination type. 2382 // 2383 // Note that we do not check for ambiguity or inaccessibility 2384 // here. That is handled by CheckPointerConversion. 2385 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2386 ToPointeeType->isRecordType() && 2387 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2388 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2389 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2390 ToPointeeType, 2391 ToType, Context); 2392 return true; 2393 } 2394 2395 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2396 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2397 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2398 ToPointeeType, 2399 ToType, Context); 2400 return true; 2401 } 2402 2403 return false; 2404 } 2405 2406 /// Adopt the given qualifiers for the given type. 2407 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2408 Qualifiers TQs = T.getQualifiers(); 2409 2410 // Check whether qualifiers already match. 2411 if (TQs == Qs) 2412 return T; 2413 2414 if (Qs.compatiblyIncludes(TQs)) 2415 return Context.getQualifiedType(T, Qs); 2416 2417 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2418 } 2419 2420 /// isObjCPointerConversion - Determines whether this is an 2421 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2422 /// with the same arguments and return values. 2423 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2424 QualType& ConvertedType, 2425 bool &IncompatibleObjC) { 2426 if (!getLangOpts().ObjC) 2427 return false; 2428 2429 // The set of qualifiers on the type we're converting from. 2430 Qualifiers FromQualifiers = FromType.getQualifiers(); 2431 2432 // First, we handle all conversions on ObjC object pointer types. 2433 const ObjCObjectPointerType* ToObjCPtr = 2434 ToType->getAs<ObjCObjectPointerType>(); 2435 const ObjCObjectPointerType *FromObjCPtr = 2436 FromType->getAs<ObjCObjectPointerType>(); 2437 2438 if (ToObjCPtr && FromObjCPtr) { 2439 // If the pointee types are the same (ignoring qualifications), 2440 // then this is not a pointer conversion. 2441 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2442 FromObjCPtr->getPointeeType())) 2443 return false; 2444 2445 // Conversion between Objective-C pointers. 2446 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2447 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2448 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2449 if (getLangOpts().CPlusPlus && LHS && RHS && 2450 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2451 FromObjCPtr->getPointeeType())) 2452 return false; 2453 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2454 ToObjCPtr->getPointeeType(), 2455 ToType, Context); 2456 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2457 return true; 2458 } 2459 2460 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2461 // Okay: this is some kind of implicit downcast of Objective-C 2462 // interfaces, which is permitted. However, we're going to 2463 // complain about it. 2464 IncompatibleObjC = true; 2465 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2466 ToObjCPtr->getPointeeType(), 2467 ToType, Context); 2468 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2469 return true; 2470 } 2471 } 2472 // Beyond this point, both types need to be C pointers or block pointers. 2473 QualType ToPointeeType; 2474 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2475 ToPointeeType = ToCPtr->getPointeeType(); 2476 else if (const BlockPointerType *ToBlockPtr = 2477 ToType->getAs<BlockPointerType>()) { 2478 // Objective C++: We're able to convert from a pointer to any object 2479 // to a block pointer type. 2480 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2481 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2482 return true; 2483 } 2484 ToPointeeType = ToBlockPtr->getPointeeType(); 2485 } 2486 else if (FromType->getAs<BlockPointerType>() && 2487 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2488 // Objective C++: We're able to convert from a block pointer type to a 2489 // pointer to any object. 2490 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2491 return true; 2492 } 2493 else 2494 return false; 2495 2496 QualType FromPointeeType; 2497 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2498 FromPointeeType = FromCPtr->getPointeeType(); 2499 else if (const BlockPointerType *FromBlockPtr = 2500 FromType->getAs<BlockPointerType>()) 2501 FromPointeeType = FromBlockPtr->getPointeeType(); 2502 else 2503 return false; 2504 2505 // If we have pointers to pointers, recursively check whether this 2506 // is an Objective-C conversion. 2507 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2508 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2509 IncompatibleObjC)) { 2510 // We always complain about this conversion. 2511 IncompatibleObjC = true; 2512 ConvertedType = Context.getPointerType(ConvertedType); 2513 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2514 return true; 2515 } 2516 // Allow conversion of pointee being objective-c pointer to another one; 2517 // as in I* to id. 2518 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2519 ToPointeeType->getAs<ObjCObjectPointerType>() && 2520 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2521 IncompatibleObjC)) { 2522 2523 ConvertedType = Context.getPointerType(ConvertedType); 2524 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2525 return true; 2526 } 2527 2528 // If we have pointers to functions or blocks, check whether the only 2529 // differences in the argument and result types are in Objective-C 2530 // pointer conversions. If so, we permit the conversion (but 2531 // complain about it). 2532 const FunctionProtoType *FromFunctionType 2533 = FromPointeeType->getAs<FunctionProtoType>(); 2534 const FunctionProtoType *ToFunctionType 2535 = ToPointeeType->getAs<FunctionProtoType>(); 2536 if (FromFunctionType && ToFunctionType) { 2537 // If the function types are exactly the same, this isn't an 2538 // Objective-C pointer conversion. 2539 if (Context.getCanonicalType(FromPointeeType) 2540 == Context.getCanonicalType(ToPointeeType)) 2541 return false; 2542 2543 // Perform the quick checks that will tell us whether these 2544 // function types are obviously different. 2545 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2546 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2547 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2548 return false; 2549 2550 bool HasObjCConversion = false; 2551 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2552 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2553 // Okay, the types match exactly. Nothing to do. 2554 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2555 ToFunctionType->getReturnType(), 2556 ConvertedType, IncompatibleObjC)) { 2557 // Okay, we have an Objective-C pointer conversion. 2558 HasObjCConversion = true; 2559 } else { 2560 // Function types are too different. Abort. 2561 return false; 2562 } 2563 2564 // Check argument types. 2565 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2566 ArgIdx != NumArgs; ++ArgIdx) { 2567 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2568 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2569 if (Context.getCanonicalType(FromArgType) 2570 == Context.getCanonicalType(ToArgType)) { 2571 // Okay, the types match exactly. Nothing to do. 2572 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2573 ConvertedType, IncompatibleObjC)) { 2574 // Okay, we have an Objective-C pointer conversion. 2575 HasObjCConversion = true; 2576 } else { 2577 // Argument types are too different. Abort. 2578 return false; 2579 } 2580 } 2581 2582 if (HasObjCConversion) { 2583 // We had an Objective-C conversion. Allow this pointer 2584 // conversion, but complain about it. 2585 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2586 IncompatibleObjC = true; 2587 return true; 2588 } 2589 } 2590 2591 return false; 2592 } 2593 2594 /// Determine whether this is an Objective-C writeback conversion, 2595 /// used for parameter passing when performing automatic reference counting. 2596 /// 2597 /// \param FromType The type we're converting form. 2598 /// 2599 /// \param ToType The type we're converting to. 2600 /// 2601 /// \param ConvertedType The type that will be produced after applying 2602 /// this conversion. 2603 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2604 QualType &ConvertedType) { 2605 if (!getLangOpts().ObjCAutoRefCount || 2606 Context.hasSameUnqualifiedType(FromType, ToType)) 2607 return false; 2608 2609 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2610 QualType ToPointee; 2611 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2612 ToPointee = ToPointer->getPointeeType(); 2613 else 2614 return false; 2615 2616 Qualifiers ToQuals = ToPointee.getQualifiers(); 2617 if (!ToPointee->isObjCLifetimeType() || 2618 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2619 !ToQuals.withoutObjCLifetime().empty()) 2620 return false; 2621 2622 // Argument must be a pointer to __strong to __weak. 2623 QualType FromPointee; 2624 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2625 FromPointee = FromPointer->getPointeeType(); 2626 else 2627 return false; 2628 2629 Qualifiers FromQuals = FromPointee.getQualifiers(); 2630 if (!FromPointee->isObjCLifetimeType() || 2631 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2632 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2633 return false; 2634 2635 // Make sure that we have compatible qualifiers. 2636 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2637 if (!ToQuals.compatiblyIncludes(FromQuals)) 2638 return false; 2639 2640 // Remove qualifiers from the pointee type we're converting from; they 2641 // aren't used in the compatibility check belong, and we'll be adding back 2642 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2643 FromPointee = FromPointee.getUnqualifiedType(); 2644 2645 // The unqualified form of the pointee types must be compatible. 2646 ToPointee = ToPointee.getUnqualifiedType(); 2647 bool IncompatibleObjC; 2648 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2649 FromPointee = ToPointee; 2650 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2651 IncompatibleObjC)) 2652 return false; 2653 2654 /// Construct the type we're converting to, which is a pointer to 2655 /// __autoreleasing pointee. 2656 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2657 ConvertedType = Context.getPointerType(FromPointee); 2658 return true; 2659 } 2660 2661 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2662 QualType& ConvertedType) { 2663 QualType ToPointeeType; 2664 if (const BlockPointerType *ToBlockPtr = 2665 ToType->getAs<BlockPointerType>()) 2666 ToPointeeType = ToBlockPtr->getPointeeType(); 2667 else 2668 return false; 2669 2670 QualType FromPointeeType; 2671 if (const BlockPointerType *FromBlockPtr = 2672 FromType->getAs<BlockPointerType>()) 2673 FromPointeeType = FromBlockPtr->getPointeeType(); 2674 else 2675 return false; 2676 // We have pointer to blocks, check whether the only 2677 // differences in the argument and result types are in Objective-C 2678 // pointer conversions. If so, we permit the conversion. 2679 2680 const FunctionProtoType *FromFunctionType 2681 = FromPointeeType->getAs<FunctionProtoType>(); 2682 const FunctionProtoType *ToFunctionType 2683 = ToPointeeType->getAs<FunctionProtoType>(); 2684 2685 if (!FromFunctionType || !ToFunctionType) 2686 return false; 2687 2688 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2689 return true; 2690 2691 // Perform the quick checks that will tell us whether these 2692 // function types are obviously different. 2693 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2694 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2695 return false; 2696 2697 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2698 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2699 if (FromEInfo != ToEInfo) 2700 return false; 2701 2702 bool IncompatibleObjC = false; 2703 if (Context.hasSameType(FromFunctionType->getReturnType(), 2704 ToFunctionType->getReturnType())) { 2705 // Okay, the types match exactly. Nothing to do. 2706 } else { 2707 QualType RHS = FromFunctionType->getReturnType(); 2708 QualType LHS = ToFunctionType->getReturnType(); 2709 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2710 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2711 LHS = LHS.getUnqualifiedType(); 2712 2713 if (Context.hasSameType(RHS,LHS)) { 2714 // OK exact match. 2715 } else if (isObjCPointerConversion(RHS, LHS, 2716 ConvertedType, IncompatibleObjC)) { 2717 if (IncompatibleObjC) 2718 return false; 2719 // Okay, we have an Objective-C pointer conversion. 2720 } 2721 else 2722 return false; 2723 } 2724 2725 // Check argument types. 2726 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2727 ArgIdx != NumArgs; ++ArgIdx) { 2728 IncompatibleObjC = false; 2729 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2730 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2731 if (Context.hasSameType(FromArgType, ToArgType)) { 2732 // Okay, the types match exactly. Nothing to do. 2733 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2734 ConvertedType, IncompatibleObjC)) { 2735 if (IncompatibleObjC) 2736 return false; 2737 // Okay, we have an Objective-C pointer conversion. 2738 } else 2739 // Argument types are too different. Abort. 2740 return false; 2741 } 2742 2743 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2744 bool CanUseToFPT, CanUseFromFPT; 2745 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2746 CanUseToFPT, CanUseFromFPT, 2747 NewParamInfos)) 2748 return false; 2749 2750 ConvertedType = ToType; 2751 return true; 2752 } 2753 2754 enum { 2755 ft_default, 2756 ft_different_class, 2757 ft_parameter_arity, 2758 ft_parameter_mismatch, 2759 ft_return_type, 2760 ft_qualifer_mismatch, 2761 ft_noexcept 2762 }; 2763 2764 /// Attempts to get the FunctionProtoType from a Type. Handles 2765 /// MemberFunctionPointers properly. 2766 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2767 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2768 return FPT; 2769 2770 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2771 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2772 2773 return nullptr; 2774 } 2775 2776 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2777 /// function types. Catches different number of parameter, mismatch in 2778 /// parameter types, and different return types. 2779 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2780 QualType FromType, QualType ToType) { 2781 // If either type is not valid, include no extra info. 2782 if (FromType.isNull() || ToType.isNull()) { 2783 PDiag << ft_default; 2784 return; 2785 } 2786 2787 // Get the function type from the pointers. 2788 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2789 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2790 *ToMember = ToType->getAs<MemberPointerType>(); 2791 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2792 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2793 << QualType(FromMember->getClass(), 0); 2794 return; 2795 } 2796 FromType = FromMember->getPointeeType(); 2797 ToType = ToMember->getPointeeType(); 2798 } 2799 2800 if (FromType->isPointerType()) 2801 FromType = FromType->getPointeeType(); 2802 if (ToType->isPointerType()) 2803 ToType = ToType->getPointeeType(); 2804 2805 // Remove references. 2806 FromType = FromType.getNonReferenceType(); 2807 ToType = ToType.getNonReferenceType(); 2808 2809 // Don't print extra info for non-specialized template functions. 2810 if (FromType->isInstantiationDependentType() && 2811 !FromType->getAs<TemplateSpecializationType>()) { 2812 PDiag << ft_default; 2813 return; 2814 } 2815 2816 // No extra info for same types. 2817 if (Context.hasSameType(FromType, ToType)) { 2818 PDiag << ft_default; 2819 return; 2820 } 2821 2822 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2823 *ToFunction = tryGetFunctionProtoType(ToType); 2824 2825 // Both types need to be function types. 2826 if (!FromFunction || !ToFunction) { 2827 PDiag << ft_default; 2828 return; 2829 } 2830 2831 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2832 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2833 << FromFunction->getNumParams(); 2834 return; 2835 } 2836 2837 // Handle different parameter types. 2838 unsigned ArgPos; 2839 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2840 PDiag << ft_parameter_mismatch << ArgPos + 1 2841 << ToFunction->getParamType(ArgPos) 2842 << FromFunction->getParamType(ArgPos); 2843 return; 2844 } 2845 2846 // Handle different return type. 2847 if (!Context.hasSameType(FromFunction->getReturnType(), 2848 ToFunction->getReturnType())) { 2849 PDiag << ft_return_type << ToFunction->getReturnType() 2850 << FromFunction->getReturnType(); 2851 return; 2852 } 2853 2854 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2855 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2856 << FromFunction->getMethodQuals(); 2857 return; 2858 } 2859 2860 // Handle exception specification differences on canonical type (in C++17 2861 // onwards). 2862 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2863 ->isNothrow() != 2864 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2865 ->isNothrow()) { 2866 PDiag << ft_noexcept; 2867 return; 2868 } 2869 2870 // Unable to find a difference, so add no extra info. 2871 PDiag << ft_default; 2872 } 2873 2874 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2875 /// for equality of their argument types. Caller has already checked that 2876 /// they have same number of arguments. If the parameters are different, 2877 /// ArgPos will have the parameter index of the first different parameter. 2878 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2879 const FunctionProtoType *NewType, 2880 unsigned *ArgPos) { 2881 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2882 N = NewType->param_type_begin(), 2883 E = OldType->param_type_end(); 2884 O && (O != E); ++O, ++N) { 2885 if (!Context.hasSameType(O->getUnqualifiedType(), 2886 N->getUnqualifiedType())) { 2887 if (ArgPos) 2888 *ArgPos = O - OldType->param_type_begin(); 2889 return false; 2890 } 2891 } 2892 return true; 2893 } 2894 2895 /// CheckPointerConversion - Check the pointer conversion from the 2896 /// expression From to the type ToType. This routine checks for 2897 /// ambiguous or inaccessible derived-to-base pointer 2898 /// conversions for which IsPointerConversion has already returned 2899 /// true. It returns true and produces a diagnostic if there was an 2900 /// error, or returns false otherwise. 2901 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2902 CastKind &Kind, 2903 CXXCastPath& BasePath, 2904 bool IgnoreBaseAccess, 2905 bool Diagnose) { 2906 QualType FromType = From->getType(); 2907 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2908 2909 Kind = CK_BitCast; 2910 2911 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2912 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2913 Expr::NPCK_ZeroExpression) { 2914 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2915 DiagRuntimeBehavior(From->getExprLoc(), From, 2916 PDiag(diag::warn_impcast_bool_to_null_pointer) 2917 << ToType << From->getSourceRange()); 2918 else if (!isUnevaluatedContext()) 2919 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2920 << ToType << From->getSourceRange(); 2921 } 2922 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2923 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2924 QualType FromPointeeType = FromPtrType->getPointeeType(), 2925 ToPointeeType = ToPtrType->getPointeeType(); 2926 2927 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2928 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2929 // We must have a derived-to-base conversion. Check an 2930 // ambiguous or inaccessible conversion. 2931 unsigned InaccessibleID = 0; 2932 unsigned AmbigiousID = 0; 2933 if (Diagnose) { 2934 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2935 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2936 } 2937 if (CheckDerivedToBaseConversion( 2938 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2939 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2940 &BasePath, IgnoreBaseAccess)) 2941 return true; 2942 2943 // The conversion was successful. 2944 Kind = CK_DerivedToBase; 2945 } 2946 2947 if (Diagnose && !IsCStyleOrFunctionalCast && 2948 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2949 assert(getLangOpts().MSVCCompat && 2950 "this should only be possible with MSVCCompat!"); 2951 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2952 << From->getSourceRange(); 2953 } 2954 } 2955 } else if (const ObjCObjectPointerType *ToPtrType = 2956 ToType->getAs<ObjCObjectPointerType>()) { 2957 if (const ObjCObjectPointerType *FromPtrType = 2958 FromType->getAs<ObjCObjectPointerType>()) { 2959 // Objective-C++ conversions are always okay. 2960 // FIXME: We should have a different class of conversions for the 2961 // Objective-C++ implicit conversions. 2962 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2963 return false; 2964 } else if (FromType->isBlockPointerType()) { 2965 Kind = CK_BlockPointerToObjCPointerCast; 2966 } else { 2967 Kind = CK_CPointerToObjCPointerCast; 2968 } 2969 } else if (ToType->isBlockPointerType()) { 2970 if (!FromType->isBlockPointerType()) 2971 Kind = CK_AnyPointerToBlockPointerCast; 2972 } 2973 2974 // We shouldn't fall into this case unless it's valid for other 2975 // reasons. 2976 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2977 Kind = CK_NullToPointer; 2978 2979 return false; 2980 } 2981 2982 /// IsMemberPointerConversion - Determines whether the conversion of the 2983 /// expression From, which has the (possibly adjusted) type FromType, can be 2984 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2985 /// If so, returns true and places the converted type (that might differ from 2986 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2987 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2988 QualType ToType, 2989 bool InOverloadResolution, 2990 QualType &ConvertedType) { 2991 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2992 if (!ToTypePtr) 2993 return false; 2994 2995 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2996 if (From->isNullPointerConstant(Context, 2997 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2998 : Expr::NPC_ValueDependentIsNull)) { 2999 ConvertedType = ToType; 3000 return true; 3001 } 3002 3003 // Otherwise, both types have to be member pointers. 3004 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3005 if (!FromTypePtr) 3006 return false; 3007 3008 // A pointer to member of B can be converted to a pointer to member of D, 3009 // where D is derived from B (C++ 4.11p2). 3010 QualType FromClass(FromTypePtr->getClass(), 0); 3011 QualType ToClass(ToTypePtr->getClass(), 0); 3012 3013 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3014 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3015 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3016 ToClass.getTypePtr()); 3017 return true; 3018 } 3019 3020 return false; 3021 } 3022 3023 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3024 /// expression From to the type ToType. This routine checks for ambiguous or 3025 /// virtual or inaccessible base-to-derived member pointer conversions 3026 /// for which IsMemberPointerConversion has already returned true. It returns 3027 /// true and produces a diagnostic if there was an error, or returns false 3028 /// otherwise. 3029 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3030 CastKind &Kind, 3031 CXXCastPath &BasePath, 3032 bool IgnoreBaseAccess) { 3033 QualType FromType = From->getType(); 3034 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3035 if (!FromPtrType) { 3036 // This must be a null pointer to member pointer conversion 3037 assert(From->isNullPointerConstant(Context, 3038 Expr::NPC_ValueDependentIsNull) && 3039 "Expr must be null pointer constant!"); 3040 Kind = CK_NullToMemberPointer; 3041 return false; 3042 } 3043 3044 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3045 assert(ToPtrType && "No member pointer cast has a target type " 3046 "that is not a member pointer."); 3047 3048 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3049 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3050 3051 // FIXME: What about dependent types? 3052 assert(FromClass->isRecordType() && "Pointer into non-class."); 3053 assert(ToClass->isRecordType() && "Pointer into non-class."); 3054 3055 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3056 /*DetectVirtual=*/true); 3057 bool DerivationOkay = 3058 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3059 assert(DerivationOkay && 3060 "Should not have been called if derivation isn't OK."); 3061 (void)DerivationOkay; 3062 3063 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3064 getUnqualifiedType())) { 3065 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3066 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3067 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3068 return true; 3069 } 3070 3071 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3072 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3073 << FromClass << ToClass << QualType(VBase, 0) 3074 << From->getSourceRange(); 3075 return true; 3076 } 3077 3078 if (!IgnoreBaseAccess) 3079 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3080 Paths.front(), 3081 diag::err_downcast_from_inaccessible_base); 3082 3083 // Must be a base to derived member conversion. 3084 BuildBasePathArray(Paths, BasePath); 3085 Kind = CK_BaseToDerivedMemberPointer; 3086 return false; 3087 } 3088 3089 /// Determine whether the lifetime conversion between the two given 3090 /// qualifiers sets is nontrivial. 3091 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3092 Qualifiers ToQuals) { 3093 // Converting anything to const __unsafe_unretained is trivial. 3094 if (ToQuals.hasConst() && 3095 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3096 return false; 3097 3098 return true; 3099 } 3100 3101 /// IsQualificationConversion - Determines whether the conversion from 3102 /// an rvalue of type FromType to ToType is a qualification conversion 3103 /// (C++ 4.4). 3104 /// 3105 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3106 /// when the qualification conversion involves a change in the Objective-C 3107 /// object lifetime. 3108 bool 3109 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3110 bool CStyle, bool &ObjCLifetimeConversion) { 3111 FromType = Context.getCanonicalType(FromType); 3112 ToType = Context.getCanonicalType(ToType); 3113 ObjCLifetimeConversion = false; 3114 3115 // If FromType and ToType are the same type, this is not a 3116 // qualification conversion. 3117 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3118 return false; 3119 3120 // (C++ 4.4p4): 3121 // A conversion can add cv-qualifiers at levels other than the first 3122 // in multi-level pointers, subject to the following rules: [...] 3123 bool PreviousToQualsIncludeConst = true; 3124 bool UnwrappedAnyPointer = false; 3125 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3126 // Within each iteration of the loop, we check the qualifiers to 3127 // determine if this still looks like a qualification 3128 // conversion. Then, if all is well, we unwrap one more level of 3129 // pointers or pointers-to-members and do it all again 3130 // until there are no more pointers or pointers-to-members left to 3131 // unwrap. 3132 UnwrappedAnyPointer = true; 3133 3134 Qualifiers FromQuals = FromType.getQualifiers(); 3135 Qualifiers ToQuals = ToType.getQualifiers(); 3136 3137 // Ignore __unaligned qualifier if this type is void. 3138 if (ToType.getUnqualifiedType()->isVoidType()) 3139 FromQuals.removeUnaligned(); 3140 3141 // Objective-C ARC: 3142 // Check Objective-C lifetime conversions. 3143 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3144 UnwrappedAnyPointer) { 3145 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3146 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3147 ObjCLifetimeConversion = true; 3148 FromQuals.removeObjCLifetime(); 3149 ToQuals.removeObjCLifetime(); 3150 } else { 3151 // Qualification conversions cannot cast between different 3152 // Objective-C lifetime qualifiers. 3153 return false; 3154 } 3155 } 3156 3157 // Allow addition/removal of GC attributes but not changing GC attributes. 3158 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3159 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3160 FromQuals.removeObjCGCAttr(); 3161 ToQuals.removeObjCGCAttr(); 3162 } 3163 3164 // -- for every j > 0, if const is in cv 1,j then const is in cv 3165 // 2,j, and similarly for volatile. 3166 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3167 return false; 3168 3169 // -- if the cv 1,j and cv 2,j are different, then const is in 3170 // every cv for 0 < k < j. 3171 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3172 && !PreviousToQualsIncludeConst) 3173 return false; 3174 3175 // Keep track of whether all prior cv-qualifiers in the "to" type 3176 // include const. 3177 PreviousToQualsIncludeConst 3178 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3179 } 3180 3181 // Allows address space promotion by language rules implemented in 3182 // Type::Qualifiers::isAddressSpaceSupersetOf. 3183 Qualifiers FromQuals = FromType.getQualifiers(); 3184 Qualifiers ToQuals = ToType.getQualifiers(); 3185 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3186 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3187 return false; 3188 } 3189 3190 // We are left with FromType and ToType being the pointee types 3191 // after unwrapping the original FromType and ToType the same number 3192 // of types. If we unwrapped any pointers, and if FromType and 3193 // ToType have the same unqualified type (since we checked 3194 // qualifiers above), then this is a qualification conversion. 3195 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3196 } 3197 3198 /// - Determine whether this is a conversion from a scalar type to an 3199 /// atomic type. 3200 /// 3201 /// If successful, updates \c SCS's second and third steps in the conversion 3202 /// sequence to finish the conversion. 3203 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3204 bool InOverloadResolution, 3205 StandardConversionSequence &SCS, 3206 bool CStyle) { 3207 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3208 if (!ToAtomic) 3209 return false; 3210 3211 StandardConversionSequence InnerSCS; 3212 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3213 InOverloadResolution, InnerSCS, 3214 CStyle, /*AllowObjCWritebackConversion=*/false)) 3215 return false; 3216 3217 SCS.Second = InnerSCS.Second; 3218 SCS.setToType(1, InnerSCS.getToType(1)); 3219 SCS.Third = InnerSCS.Third; 3220 SCS.QualificationIncludesObjCLifetime 3221 = InnerSCS.QualificationIncludesObjCLifetime; 3222 SCS.setToType(2, InnerSCS.getToType(2)); 3223 return true; 3224 } 3225 3226 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3227 CXXConstructorDecl *Constructor, 3228 QualType Type) { 3229 const FunctionProtoType *CtorType = 3230 Constructor->getType()->getAs<FunctionProtoType>(); 3231 if (CtorType->getNumParams() > 0) { 3232 QualType FirstArg = CtorType->getParamType(0); 3233 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3234 return true; 3235 } 3236 return false; 3237 } 3238 3239 static OverloadingResult 3240 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3241 CXXRecordDecl *To, 3242 UserDefinedConversionSequence &User, 3243 OverloadCandidateSet &CandidateSet, 3244 bool AllowExplicit) { 3245 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3246 for (auto *D : S.LookupConstructors(To)) { 3247 auto Info = getConstructorInfo(D); 3248 if (!Info) 3249 continue; 3250 3251 bool Usable = !Info.Constructor->isInvalidDecl() && 3252 S.isInitListConstructor(Info.Constructor) && 3253 (AllowExplicit || !Info.Constructor->isExplicit()); 3254 if (Usable) { 3255 // If the first argument is (a reference to) the target type, 3256 // suppress conversions. 3257 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3258 S.Context, Info.Constructor, ToType); 3259 if (Info.ConstructorTmpl) 3260 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3261 /*ExplicitArgs*/ nullptr, From, 3262 CandidateSet, SuppressUserConversions); 3263 else 3264 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3265 CandidateSet, SuppressUserConversions); 3266 } 3267 } 3268 3269 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3270 3271 OverloadCandidateSet::iterator Best; 3272 switch (auto Result = 3273 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3274 case OR_Deleted: 3275 case OR_Success: { 3276 // Record the standard conversion we used and the conversion function. 3277 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3278 QualType ThisType = Constructor->getThisType(); 3279 // Initializer lists don't have conversions as such. 3280 User.Before.setAsIdentityConversion(); 3281 User.HadMultipleCandidates = HadMultipleCandidates; 3282 User.ConversionFunction = Constructor; 3283 User.FoundConversionFunction = Best->FoundDecl; 3284 User.After.setAsIdentityConversion(); 3285 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3286 User.After.setAllToTypes(ToType); 3287 return Result; 3288 } 3289 3290 case OR_No_Viable_Function: 3291 return OR_No_Viable_Function; 3292 case OR_Ambiguous: 3293 return OR_Ambiguous; 3294 } 3295 3296 llvm_unreachable("Invalid OverloadResult!"); 3297 } 3298 3299 /// Determines whether there is a user-defined conversion sequence 3300 /// (C++ [over.ics.user]) that converts expression From to the type 3301 /// ToType. If such a conversion exists, User will contain the 3302 /// user-defined conversion sequence that performs such a conversion 3303 /// and this routine will return true. Otherwise, this routine returns 3304 /// false and User is unspecified. 3305 /// 3306 /// \param AllowExplicit true if the conversion should consider C++0x 3307 /// "explicit" conversion functions as well as non-explicit conversion 3308 /// functions (C++0x [class.conv.fct]p2). 3309 /// 3310 /// \param AllowObjCConversionOnExplicit true if the conversion should 3311 /// allow an extra Objective-C pointer conversion on uses of explicit 3312 /// constructors. Requires \c AllowExplicit to also be set. 3313 static OverloadingResult 3314 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3315 UserDefinedConversionSequence &User, 3316 OverloadCandidateSet &CandidateSet, 3317 bool AllowExplicit, 3318 bool AllowObjCConversionOnExplicit) { 3319 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3320 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3321 3322 // Whether we will only visit constructors. 3323 bool ConstructorsOnly = false; 3324 3325 // If the type we are conversion to is a class type, enumerate its 3326 // constructors. 3327 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3328 // C++ [over.match.ctor]p1: 3329 // When objects of class type are direct-initialized (8.5), or 3330 // copy-initialized from an expression of the same or a 3331 // derived class type (8.5), overload resolution selects the 3332 // constructor. [...] For copy-initialization, the candidate 3333 // functions are all the converting constructors (12.3.1) of 3334 // that class. The argument list is the expression-list within 3335 // the parentheses of the initializer. 3336 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3337 (From->getType()->getAs<RecordType>() && 3338 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3339 ConstructorsOnly = true; 3340 3341 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3342 // We're not going to find any constructors. 3343 } else if (CXXRecordDecl *ToRecordDecl 3344 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3345 3346 Expr **Args = &From; 3347 unsigned NumArgs = 1; 3348 bool ListInitializing = false; 3349 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3350 // But first, see if there is an init-list-constructor that will work. 3351 OverloadingResult Result = IsInitializerListConstructorConversion( 3352 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3353 if (Result != OR_No_Viable_Function) 3354 return Result; 3355 // Never mind. 3356 CandidateSet.clear( 3357 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3358 3359 // If we're list-initializing, we pass the individual elements as 3360 // arguments, not the entire list. 3361 Args = InitList->getInits(); 3362 NumArgs = InitList->getNumInits(); 3363 ListInitializing = true; 3364 } 3365 3366 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3367 auto Info = getConstructorInfo(D); 3368 if (!Info) 3369 continue; 3370 3371 bool Usable = !Info.Constructor->isInvalidDecl(); 3372 if (ListInitializing) 3373 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3374 else 3375 Usable = Usable && 3376 Info.Constructor->isConvertingConstructor(AllowExplicit); 3377 if (Usable) { 3378 bool SuppressUserConversions = !ConstructorsOnly; 3379 if (SuppressUserConversions && ListInitializing) { 3380 SuppressUserConversions = false; 3381 if (NumArgs == 1) { 3382 // If the first argument is (a reference to) the target type, 3383 // suppress conversions. 3384 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3385 S.Context, Info.Constructor, ToType); 3386 } 3387 } 3388 if (Info.ConstructorTmpl) 3389 S.AddTemplateOverloadCandidate( 3390 Info.ConstructorTmpl, Info.FoundDecl, 3391 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3392 CandidateSet, SuppressUserConversions); 3393 else 3394 // Allow one user-defined conversion when user specifies a 3395 // From->ToType conversion via an static cast (c-style, etc). 3396 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3397 llvm::makeArrayRef(Args, NumArgs), 3398 CandidateSet, SuppressUserConversions); 3399 } 3400 } 3401 } 3402 } 3403 3404 // Enumerate conversion functions, if we're allowed to. 3405 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3406 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3407 // No conversion functions from incomplete types. 3408 } else if (const RecordType *FromRecordType = 3409 From->getType()->getAs<RecordType>()) { 3410 if (CXXRecordDecl *FromRecordDecl 3411 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3412 // Add all of the conversion functions as candidates. 3413 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3414 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3415 DeclAccessPair FoundDecl = I.getPair(); 3416 NamedDecl *D = FoundDecl.getDecl(); 3417 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3418 if (isa<UsingShadowDecl>(D)) 3419 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3420 3421 CXXConversionDecl *Conv; 3422 FunctionTemplateDecl *ConvTemplate; 3423 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3424 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3425 else 3426 Conv = cast<CXXConversionDecl>(D); 3427 3428 if (AllowExplicit || !Conv->isExplicit()) { 3429 if (ConvTemplate) 3430 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3431 ActingContext, From, ToType, 3432 CandidateSet, 3433 AllowObjCConversionOnExplicit); 3434 else 3435 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3436 From, ToType, CandidateSet, 3437 AllowObjCConversionOnExplicit); 3438 } 3439 } 3440 } 3441 } 3442 3443 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3444 3445 OverloadCandidateSet::iterator Best; 3446 switch (auto Result = 3447 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3448 case OR_Success: 3449 case OR_Deleted: 3450 // Record the standard conversion we used and the conversion function. 3451 if (CXXConstructorDecl *Constructor 3452 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3453 // C++ [over.ics.user]p1: 3454 // If the user-defined conversion is specified by a 3455 // constructor (12.3.1), the initial standard conversion 3456 // sequence converts the source type to the type required by 3457 // the argument of the constructor. 3458 // 3459 QualType ThisType = Constructor->getThisType(); 3460 if (isa<InitListExpr>(From)) { 3461 // Initializer lists don't have conversions as such. 3462 User.Before.setAsIdentityConversion(); 3463 } else { 3464 if (Best->Conversions[0].isEllipsis()) 3465 User.EllipsisConversion = true; 3466 else { 3467 User.Before = Best->Conversions[0].Standard; 3468 User.EllipsisConversion = false; 3469 } 3470 } 3471 User.HadMultipleCandidates = HadMultipleCandidates; 3472 User.ConversionFunction = Constructor; 3473 User.FoundConversionFunction = Best->FoundDecl; 3474 User.After.setAsIdentityConversion(); 3475 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3476 User.After.setAllToTypes(ToType); 3477 return Result; 3478 } 3479 if (CXXConversionDecl *Conversion 3480 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3481 // C++ [over.ics.user]p1: 3482 // 3483 // [...] If the user-defined conversion is specified by a 3484 // conversion function (12.3.2), the initial standard 3485 // conversion sequence converts the source type to the 3486 // implicit object parameter of the conversion function. 3487 User.Before = Best->Conversions[0].Standard; 3488 User.HadMultipleCandidates = HadMultipleCandidates; 3489 User.ConversionFunction = Conversion; 3490 User.FoundConversionFunction = Best->FoundDecl; 3491 User.EllipsisConversion = false; 3492 3493 // C++ [over.ics.user]p2: 3494 // The second standard conversion sequence converts the 3495 // result of the user-defined conversion to the target type 3496 // for the sequence. Since an implicit conversion sequence 3497 // is an initialization, the special rules for 3498 // initialization by user-defined conversion apply when 3499 // selecting the best user-defined conversion for a 3500 // user-defined conversion sequence (see 13.3.3 and 3501 // 13.3.3.1). 3502 User.After = Best->FinalConversion; 3503 return Result; 3504 } 3505 llvm_unreachable("Not a constructor or conversion function?"); 3506 3507 case OR_No_Viable_Function: 3508 return OR_No_Viable_Function; 3509 3510 case OR_Ambiguous: 3511 return OR_Ambiguous; 3512 } 3513 3514 llvm_unreachable("Invalid OverloadResult!"); 3515 } 3516 3517 bool 3518 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3519 ImplicitConversionSequence ICS; 3520 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3521 OverloadCandidateSet::CSK_Normal); 3522 OverloadingResult OvResult = 3523 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3524 CandidateSet, false, false); 3525 if (OvResult == OR_Ambiguous) 3526 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3527 << From->getType() << ToType << From->getSourceRange(); 3528 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3529 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3530 diag::err_typecheck_nonviable_condition_incomplete, 3531 From->getType(), From->getSourceRange())) 3532 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3533 << false << From->getType() << From->getSourceRange() << ToType; 3534 } else 3535 return false; 3536 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3537 return true; 3538 } 3539 3540 /// Compare the user-defined conversion functions or constructors 3541 /// of two user-defined conversion sequences to determine whether any ordering 3542 /// is possible. 3543 static ImplicitConversionSequence::CompareKind 3544 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3545 FunctionDecl *Function2) { 3546 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3547 return ImplicitConversionSequence::Indistinguishable; 3548 3549 // Objective-C++: 3550 // If both conversion functions are implicitly-declared conversions from 3551 // a lambda closure type to a function pointer and a block pointer, 3552 // respectively, always prefer the conversion to a function pointer, 3553 // because the function pointer is more lightweight and is more likely 3554 // to keep code working. 3555 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3556 if (!Conv1) 3557 return ImplicitConversionSequence::Indistinguishable; 3558 3559 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3560 if (!Conv2) 3561 return ImplicitConversionSequence::Indistinguishable; 3562 3563 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3564 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3565 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3566 if (Block1 != Block2) 3567 return Block1 ? ImplicitConversionSequence::Worse 3568 : ImplicitConversionSequence::Better; 3569 } 3570 3571 return ImplicitConversionSequence::Indistinguishable; 3572 } 3573 3574 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3575 const ImplicitConversionSequence &ICS) { 3576 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3577 (ICS.isUserDefined() && 3578 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3579 } 3580 3581 /// CompareImplicitConversionSequences - Compare two implicit 3582 /// conversion sequences to determine whether one is better than the 3583 /// other or if they are indistinguishable (C++ 13.3.3.2). 3584 static ImplicitConversionSequence::CompareKind 3585 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3586 const ImplicitConversionSequence& ICS1, 3587 const ImplicitConversionSequence& ICS2) 3588 { 3589 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3590 // conversion sequences (as defined in 13.3.3.1) 3591 // -- a standard conversion sequence (13.3.3.1.1) is a better 3592 // conversion sequence than a user-defined conversion sequence or 3593 // an ellipsis conversion sequence, and 3594 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3595 // conversion sequence than an ellipsis conversion sequence 3596 // (13.3.3.1.3). 3597 // 3598 // C++0x [over.best.ics]p10: 3599 // For the purpose of ranking implicit conversion sequences as 3600 // described in 13.3.3.2, the ambiguous conversion sequence is 3601 // treated as a user-defined sequence that is indistinguishable 3602 // from any other user-defined conversion sequence. 3603 3604 // String literal to 'char *' conversion has been deprecated in C++03. It has 3605 // been removed from C++11. We still accept this conversion, if it happens at 3606 // the best viable function. Otherwise, this conversion is considered worse 3607 // than ellipsis conversion. Consider this as an extension; this is not in the 3608 // standard. For example: 3609 // 3610 // int &f(...); // #1 3611 // void f(char*); // #2 3612 // void g() { int &r = f("foo"); } 3613 // 3614 // In C++03, we pick #2 as the best viable function. 3615 // In C++11, we pick #1 as the best viable function, because ellipsis 3616 // conversion is better than string-literal to char* conversion (since there 3617 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3618 // convert arguments, #2 would be the best viable function in C++11. 3619 // If the best viable function has this conversion, a warning will be issued 3620 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3621 3622 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3623 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3624 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3625 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3626 ? ImplicitConversionSequence::Worse 3627 : ImplicitConversionSequence::Better; 3628 3629 if (ICS1.getKindRank() < ICS2.getKindRank()) 3630 return ImplicitConversionSequence::Better; 3631 if (ICS2.getKindRank() < ICS1.getKindRank()) 3632 return ImplicitConversionSequence::Worse; 3633 3634 // The following checks require both conversion sequences to be of 3635 // the same kind. 3636 if (ICS1.getKind() != ICS2.getKind()) 3637 return ImplicitConversionSequence::Indistinguishable; 3638 3639 ImplicitConversionSequence::CompareKind Result = 3640 ImplicitConversionSequence::Indistinguishable; 3641 3642 // Two implicit conversion sequences of the same form are 3643 // indistinguishable conversion sequences unless one of the 3644 // following rules apply: (C++ 13.3.3.2p3): 3645 3646 // List-initialization sequence L1 is a better conversion sequence than 3647 // list-initialization sequence L2 if: 3648 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3649 // if not that, 3650 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3651 // and N1 is smaller than N2., 3652 // even if one of the other rules in this paragraph would otherwise apply. 3653 if (!ICS1.isBad()) { 3654 if (ICS1.isStdInitializerListElement() && 3655 !ICS2.isStdInitializerListElement()) 3656 return ImplicitConversionSequence::Better; 3657 if (!ICS1.isStdInitializerListElement() && 3658 ICS2.isStdInitializerListElement()) 3659 return ImplicitConversionSequence::Worse; 3660 } 3661 3662 if (ICS1.isStandard()) 3663 // Standard conversion sequence S1 is a better conversion sequence than 3664 // standard conversion sequence S2 if [...] 3665 Result = CompareStandardConversionSequences(S, Loc, 3666 ICS1.Standard, ICS2.Standard); 3667 else if (ICS1.isUserDefined()) { 3668 // User-defined conversion sequence U1 is a better conversion 3669 // sequence than another user-defined conversion sequence U2 if 3670 // they contain the same user-defined conversion function or 3671 // constructor and if the second standard conversion sequence of 3672 // U1 is better than the second standard conversion sequence of 3673 // U2 (C++ 13.3.3.2p3). 3674 if (ICS1.UserDefined.ConversionFunction == 3675 ICS2.UserDefined.ConversionFunction) 3676 Result = CompareStandardConversionSequences(S, Loc, 3677 ICS1.UserDefined.After, 3678 ICS2.UserDefined.After); 3679 else 3680 Result = compareConversionFunctions(S, 3681 ICS1.UserDefined.ConversionFunction, 3682 ICS2.UserDefined.ConversionFunction); 3683 } 3684 3685 return Result; 3686 } 3687 3688 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3689 // determine if one is a proper subset of the other. 3690 static ImplicitConversionSequence::CompareKind 3691 compareStandardConversionSubsets(ASTContext &Context, 3692 const StandardConversionSequence& SCS1, 3693 const StandardConversionSequence& SCS2) { 3694 ImplicitConversionSequence::CompareKind Result 3695 = ImplicitConversionSequence::Indistinguishable; 3696 3697 // the identity conversion sequence is considered to be a subsequence of 3698 // any non-identity conversion sequence 3699 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3700 return ImplicitConversionSequence::Better; 3701 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3702 return ImplicitConversionSequence::Worse; 3703 3704 if (SCS1.Second != SCS2.Second) { 3705 if (SCS1.Second == ICK_Identity) 3706 Result = ImplicitConversionSequence::Better; 3707 else if (SCS2.Second == ICK_Identity) 3708 Result = ImplicitConversionSequence::Worse; 3709 else 3710 return ImplicitConversionSequence::Indistinguishable; 3711 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3712 return ImplicitConversionSequence::Indistinguishable; 3713 3714 if (SCS1.Third == SCS2.Third) { 3715 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3716 : ImplicitConversionSequence::Indistinguishable; 3717 } 3718 3719 if (SCS1.Third == ICK_Identity) 3720 return Result == ImplicitConversionSequence::Worse 3721 ? ImplicitConversionSequence::Indistinguishable 3722 : ImplicitConversionSequence::Better; 3723 3724 if (SCS2.Third == ICK_Identity) 3725 return Result == ImplicitConversionSequence::Better 3726 ? ImplicitConversionSequence::Indistinguishable 3727 : ImplicitConversionSequence::Worse; 3728 3729 return ImplicitConversionSequence::Indistinguishable; 3730 } 3731 3732 /// Determine whether one of the given reference bindings is better 3733 /// than the other based on what kind of bindings they are. 3734 static bool 3735 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3736 const StandardConversionSequence &SCS2) { 3737 // C++0x [over.ics.rank]p3b4: 3738 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3739 // implicit object parameter of a non-static member function declared 3740 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3741 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3742 // lvalue reference to a function lvalue and S2 binds an rvalue 3743 // reference*. 3744 // 3745 // FIXME: Rvalue references. We're going rogue with the above edits, 3746 // because the semantics in the current C++0x working paper (N3225 at the 3747 // time of this writing) break the standard definition of std::forward 3748 // and std::reference_wrapper when dealing with references to functions. 3749 // Proposed wording changes submitted to CWG for consideration. 3750 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3751 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3752 return false; 3753 3754 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3755 SCS2.IsLvalueReference) || 3756 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3757 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3758 } 3759 3760 /// CompareStandardConversionSequences - Compare two standard 3761 /// conversion sequences to determine whether one is better than the 3762 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3763 static ImplicitConversionSequence::CompareKind 3764 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3765 const StandardConversionSequence& SCS1, 3766 const StandardConversionSequence& SCS2) 3767 { 3768 // Standard conversion sequence S1 is a better conversion sequence 3769 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3770 3771 // -- S1 is a proper subsequence of S2 (comparing the conversion 3772 // sequences in the canonical form defined by 13.3.3.1.1, 3773 // excluding any Lvalue Transformation; the identity conversion 3774 // sequence is considered to be a subsequence of any 3775 // non-identity conversion sequence) or, if not that, 3776 if (ImplicitConversionSequence::CompareKind CK 3777 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3778 return CK; 3779 3780 // -- the rank of S1 is better than the rank of S2 (by the rules 3781 // defined below), or, if not that, 3782 ImplicitConversionRank Rank1 = SCS1.getRank(); 3783 ImplicitConversionRank Rank2 = SCS2.getRank(); 3784 if (Rank1 < Rank2) 3785 return ImplicitConversionSequence::Better; 3786 else if (Rank2 < Rank1) 3787 return ImplicitConversionSequence::Worse; 3788 3789 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3790 // are indistinguishable unless one of the following rules 3791 // applies: 3792 3793 // A conversion that is not a conversion of a pointer, or 3794 // pointer to member, to bool is better than another conversion 3795 // that is such a conversion. 3796 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3797 return SCS2.isPointerConversionToBool() 3798 ? ImplicitConversionSequence::Better 3799 : ImplicitConversionSequence::Worse; 3800 3801 // C++ [over.ics.rank]p4b2: 3802 // 3803 // If class B is derived directly or indirectly from class A, 3804 // conversion of B* to A* is better than conversion of B* to 3805 // void*, and conversion of A* to void* is better than conversion 3806 // of B* to void*. 3807 bool SCS1ConvertsToVoid 3808 = SCS1.isPointerConversionToVoidPointer(S.Context); 3809 bool SCS2ConvertsToVoid 3810 = SCS2.isPointerConversionToVoidPointer(S.Context); 3811 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3812 // Exactly one of the conversion sequences is a conversion to 3813 // a void pointer; it's the worse conversion. 3814 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3815 : ImplicitConversionSequence::Worse; 3816 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3817 // Neither conversion sequence converts to a void pointer; compare 3818 // their derived-to-base conversions. 3819 if (ImplicitConversionSequence::CompareKind DerivedCK 3820 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3821 return DerivedCK; 3822 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3823 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3824 // Both conversion sequences are conversions to void 3825 // pointers. Compare the source types to determine if there's an 3826 // inheritance relationship in their sources. 3827 QualType FromType1 = SCS1.getFromType(); 3828 QualType FromType2 = SCS2.getFromType(); 3829 3830 // Adjust the types we're converting from via the array-to-pointer 3831 // conversion, if we need to. 3832 if (SCS1.First == ICK_Array_To_Pointer) 3833 FromType1 = S.Context.getArrayDecayedType(FromType1); 3834 if (SCS2.First == ICK_Array_To_Pointer) 3835 FromType2 = S.Context.getArrayDecayedType(FromType2); 3836 3837 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3838 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3839 3840 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3841 return ImplicitConversionSequence::Better; 3842 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3843 return ImplicitConversionSequence::Worse; 3844 3845 // Objective-C++: If one interface is more specific than the 3846 // other, it is the better one. 3847 const ObjCObjectPointerType* FromObjCPtr1 3848 = FromType1->getAs<ObjCObjectPointerType>(); 3849 const ObjCObjectPointerType* FromObjCPtr2 3850 = FromType2->getAs<ObjCObjectPointerType>(); 3851 if (FromObjCPtr1 && FromObjCPtr2) { 3852 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3853 FromObjCPtr2); 3854 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3855 FromObjCPtr1); 3856 if (AssignLeft != AssignRight) { 3857 return AssignLeft? ImplicitConversionSequence::Better 3858 : ImplicitConversionSequence::Worse; 3859 } 3860 } 3861 } 3862 3863 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3864 // bullet 3). 3865 if (ImplicitConversionSequence::CompareKind QualCK 3866 = CompareQualificationConversions(S, SCS1, SCS2)) 3867 return QualCK; 3868 3869 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3870 // Check for a better reference binding based on the kind of bindings. 3871 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3872 return ImplicitConversionSequence::Better; 3873 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3874 return ImplicitConversionSequence::Worse; 3875 3876 // C++ [over.ics.rank]p3b4: 3877 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3878 // which the references refer are the same type except for 3879 // top-level cv-qualifiers, and the type to which the reference 3880 // initialized by S2 refers is more cv-qualified than the type 3881 // to which the reference initialized by S1 refers. 3882 QualType T1 = SCS1.getToType(2); 3883 QualType T2 = SCS2.getToType(2); 3884 T1 = S.Context.getCanonicalType(T1); 3885 T2 = S.Context.getCanonicalType(T2); 3886 Qualifiers T1Quals, T2Quals; 3887 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3888 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3889 if (UnqualT1 == UnqualT2) { 3890 // Objective-C++ ARC: If the references refer to objects with different 3891 // lifetimes, prefer bindings that don't change lifetime. 3892 if (SCS1.ObjCLifetimeConversionBinding != 3893 SCS2.ObjCLifetimeConversionBinding) { 3894 return SCS1.ObjCLifetimeConversionBinding 3895 ? ImplicitConversionSequence::Worse 3896 : ImplicitConversionSequence::Better; 3897 } 3898 3899 // If the type is an array type, promote the element qualifiers to the 3900 // type for comparison. 3901 if (isa<ArrayType>(T1) && T1Quals) 3902 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3903 if (isa<ArrayType>(T2) && T2Quals) 3904 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3905 if (T2.isMoreQualifiedThan(T1)) 3906 return ImplicitConversionSequence::Better; 3907 else if (T1.isMoreQualifiedThan(T2)) 3908 return ImplicitConversionSequence::Worse; 3909 } 3910 } 3911 3912 // In Microsoft mode, prefer an integral conversion to a 3913 // floating-to-integral conversion if the integral conversion 3914 // is between types of the same size. 3915 // For example: 3916 // void f(float); 3917 // void f(int); 3918 // int main { 3919 // long a; 3920 // f(a); 3921 // } 3922 // Here, MSVC will call f(int) instead of generating a compile error 3923 // as clang will do in standard mode. 3924 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3925 SCS2.Second == ICK_Floating_Integral && 3926 S.Context.getTypeSize(SCS1.getFromType()) == 3927 S.Context.getTypeSize(SCS1.getToType(2))) 3928 return ImplicitConversionSequence::Better; 3929 3930 // Prefer a compatible vector conversion over a lax vector conversion 3931 // For example: 3932 // 3933 // typedef float __v4sf __attribute__((__vector_size__(16))); 3934 // void f(vector float); 3935 // void f(vector signed int); 3936 // int main() { 3937 // __v4sf a; 3938 // f(a); 3939 // } 3940 // Here, we'd like to choose f(vector float) and not 3941 // report an ambiguous call error 3942 if (SCS1.Second == ICK_Vector_Conversion && 3943 SCS2.Second == ICK_Vector_Conversion) { 3944 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3945 SCS1.getFromType(), SCS1.getToType(2)); 3946 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3947 SCS2.getFromType(), SCS2.getToType(2)); 3948 3949 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 3950 return SCS1IsCompatibleVectorConversion 3951 ? ImplicitConversionSequence::Better 3952 : ImplicitConversionSequence::Worse; 3953 } 3954 3955 return ImplicitConversionSequence::Indistinguishable; 3956 } 3957 3958 /// CompareQualificationConversions - Compares two standard conversion 3959 /// sequences to determine whether they can be ranked based on their 3960 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3961 static ImplicitConversionSequence::CompareKind 3962 CompareQualificationConversions(Sema &S, 3963 const StandardConversionSequence& SCS1, 3964 const StandardConversionSequence& SCS2) { 3965 // C++ 13.3.3.2p3: 3966 // -- S1 and S2 differ only in their qualification conversion and 3967 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3968 // cv-qualification signature of type T1 is a proper subset of 3969 // the cv-qualification signature of type T2, and S1 is not the 3970 // deprecated string literal array-to-pointer conversion (4.2). 3971 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3972 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3973 return ImplicitConversionSequence::Indistinguishable; 3974 3975 // FIXME: the example in the standard doesn't use a qualification 3976 // conversion (!) 3977 QualType T1 = SCS1.getToType(2); 3978 QualType T2 = SCS2.getToType(2); 3979 T1 = S.Context.getCanonicalType(T1); 3980 T2 = S.Context.getCanonicalType(T2); 3981 Qualifiers T1Quals, T2Quals; 3982 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3983 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3984 3985 // If the types are the same, we won't learn anything by unwrapped 3986 // them. 3987 if (UnqualT1 == UnqualT2) 3988 return ImplicitConversionSequence::Indistinguishable; 3989 3990 // If the type is an array type, promote the element qualifiers to the type 3991 // for comparison. 3992 if (isa<ArrayType>(T1) && T1Quals) 3993 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3994 if (isa<ArrayType>(T2) && T2Quals) 3995 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3996 3997 ImplicitConversionSequence::CompareKind Result 3998 = ImplicitConversionSequence::Indistinguishable; 3999 4000 // Objective-C++ ARC: 4001 // Prefer qualification conversions not involving a change in lifetime 4002 // to qualification conversions that do not change lifetime. 4003 if (SCS1.QualificationIncludesObjCLifetime != 4004 SCS2.QualificationIncludesObjCLifetime) { 4005 Result = SCS1.QualificationIncludesObjCLifetime 4006 ? ImplicitConversionSequence::Worse 4007 : ImplicitConversionSequence::Better; 4008 } 4009 4010 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4011 // Within each iteration of the loop, we check the qualifiers to 4012 // determine if this still looks like a qualification 4013 // conversion. Then, if all is well, we unwrap one more level of 4014 // pointers or pointers-to-members and do it all again 4015 // until there are no more pointers or pointers-to-members left 4016 // to unwrap. This essentially mimics what 4017 // IsQualificationConversion does, but here we're checking for a 4018 // strict subset of qualifiers. 4019 if (T1.getQualifiers().withoutObjCLifetime() == 4020 T2.getQualifiers().withoutObjCLifetime()) 4021 // The qualifiers are the same, so this doesn't tell us anything 4022 // about how the sequences rank. 4023 // ObjC ownership quals are omitted above as they interfere with 4024 // the ARC overload rule. 4025 ; 4026 else if (T2.isMoreQualifiedThan(T1)) { 4027 // T1 has fewer qualifiers, so it could be the better sequence. 4028 if (Result == ImplicitConversionSequence::Worse) 4029 // Neither has qualifiers that are a subset of the other's 4030 // qualifiers. 4031 return ImplicitConversionSequence::Indistinguishable; 4032 4033 Result = ImplicitConversionSequence::Better; 4034 } else if (T1.isMoreQualifiedThan(T2)) { 4035 // T2 has fewer qualifiers, so it could be the better sequence. 4036 if (Result == ImplicitConversionSequence::Better) 4037 // Neither has qualifiers that are a subset of the other's 4038 // qualifiers. 4039 return ImplicitConversionSequence::Indistinguishable; 4040 4041 Result = ImplicitConversionSequence::Worse; 4042 } else { 4043 // Qualifiers are disjoint. 4044 return ImplicitConversionSequence::Indistinguishable; 4045 } 4046 4047 // If the types after this point are equivalent, we're done. 4048 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4049 break; 4050 } 4051 4052 // Check that the winning standard conversion sequence isn't using 4053 // the deprecated string literal array to pointer conversion. 4054 switch (Result) { 4055 case ImplicitConversionSequence::Better: 4056 if (SCS1.DeprecatedStringLiteralToCharPtr) 4057 Result = ImplicitConversionSequence::Indistinguishable; 4058 break; 4059 4060 case ImplicitConversionSequence::Indistinguishable: 4061 break; 4062 4063 case ImplicitConversionSequence::Worse: 4064 if (SCS2.DeprecatedStringLiteralToCharPtr) 4065 Result = ImplicitConversionSequence::Indistinguishable; 4066 break; 4067 } 4068 4069 return Result; 4070 } 4071 4072 /// CompareDerivedToBaseConversions - Compares two standard conversion 4073 /// sequences to determine whether they can be ranked based on their 4074 /// various kinds of derived-to-base conversions (C++ 4075 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4076 /// conversions between Objective-C interface types. 4077 static ImplicitConversionSequence::CompareKind 4078 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4079 const StandardConversionSequence& SCS1, 4080 const StandardConversionSequence& SCS2) { 4081 QualType FromType1 = SCS1.getFromType(); 4082 QualType ToType1 = SCS1.getToType(1); 4083 QualType FromType2 = SCS2.getFromType(); 4084 QualType ToType2 = SCS2.getToType(1); 4085 4086 // Adjust the types we're converting from via the array-to-pointer 4087 // conversion, if we need to. 4088 if (SCS1.First == ICK_Array_To_Pointer) 4089 FromType1 = S.Context.getArrayDecayedType(FromType1); 4090 if (SCS2.First == ICK_Array_To_Pointer) 4091 FromType2 = S.Context.getArrayDecayedType(FromType2); 4092 4093 // Canonicalize all of the types. 4094 FromType1 = S.Context.getCanonicalType(FromType1); 4095 ToType1 = S.Context.getCanonicalType(ToType1); 4096 FromType2 = S.Context.getCanonicalType(FromType2); 4097 ToType2 = S.Context.getCanonicalType(ToType2); 4098 4099 // C++ [over.ics.rank]p4b3: 4100 // 4101 // If class B is derived directly or indirectly from class A and 4102 // class C is derived directly or indirectly from B, 4103 // 4104 // Compare based on pointer conversions. 4105 if (SCS1.Second == ICK_Pointer_Conversion && 4106 SCS2.Second == ICK_Pointer_Conversion && 4107 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4108 FromType1->isPointerType() && FromType2->isPointerType() && 4109 ToType1->isPointerType() && ToType2->isPointerType()) { 4110 QualType FromPointee1 4111 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4112 QualType ToPointee1 4113 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4114 QualType FromPointee2 4115 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4116 QualType ToPointee2 4117 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4118 4119 // -- conversion of C* to B* is better than conversion of C* to A*, 4120 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4121 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4122 return ImplicitConversionSequence::Better; 4123 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4124 return ImplicitConversionSequence::Worse; 4125 } 4126 4127 // -- conversion of B* to A* is better than conversion of C* to A*, 4128 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4129 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4130 return ImplicitConversionSequence::Better; 4131 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4132 return ImplicitConversionSequence::Worse; 4133 } 4134 } else if (SCS1.Second == ICK_Pointer_Conversion && 4135 SCS2.Second == ICK_Pointer_Conversion) { 4136 const ObjCObjectPointerType *FromPtr1 4137 = FromType1->getAs<ObjCObjectPointerType>(); 4138 const ObjCObjectPointerType *FromPtr2 4139 = FromType2->getAs<ObjCObjectPointerType>(); 4140 const ObjCObjectPointerType *ToPtr1 4141 = ToType1->getAs<ObjCObjectPointerType>(); 4142 const ObjCObjectPointerType *ToPtr2 4143 = ToType2->getAs<ObjCObjectPointerType>(); 4144 4145 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4146 // Apply the same conversion ranking rules for Objective-C pointer types 4147 // that we do for C++ pointers to class types. However, we employ the 4148 // Objective-C pseudo-subtyping relationship used for assignment of 4149 // Objective-C pointer types. 4150 bool FromAssignLeft 4151 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4152 bool FromAssignRight 4153 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4154 bool ToAssignLeft 4155 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4156 bool ToAssignRight 4157 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4158 4159 // A conversion to an a non-id object pointer type or qualified 'id' 4160 // type is better than a conversion to 'id'. 4161 if (ToPtr1->isObjCIdType() && 4162 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4163 return ImplicitConversionSequence::Worse; 4164 if (ToPtr2->isObjCIdType() && 4165 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4166 return ImplicitConversionSequence::Better; 4167 4168 // A conversion to a non-id object pointer type is better than a 4169 // conversion to a qualified 'id' type 4170 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4171 return ImplicitConversionSequence::Worse; 4172 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4173 return ImplicitConversionSequence::Better; 4174 4175 // A conversion to an a non-Class object pointer type or qualified 'Class' 4176 // type is better than a conversion to 'Class'. 4177 if (ToPtr1->isObjCClassType() && 4178 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4179 return ImplicitConversionSequence::Worse; 4180 if (ToPtr2->isObjCClassType() && 4181 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4182 return ImplicitConversionSequence::Better; 4183 4184 // A conversion to a non-Class object pointer type is better than a 4185 // conversion to a qualified 'Class' type. 4186 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4187 return ImplicitConversionSequence::Worse; 4188 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4189 return ImplicitConversionSequence::Better; 4190 4191 // -- "conversion of C* to B* is better than conversion of C* to A*," 4192 if (S.Context.hasSameType(FromType1, FromType2) && 4193 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4194 (ToAssignLeft != ToAssignRight)) { 4195 if (FromPtr1->isSpecialized()) { 4196 // "conversion of B<A> * to B * is better than conversion of B * to 4197 // C *. 4198 bool IsFirstSame = 4199 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4200 bool IsSecondSame = 4201 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4202 if (IsFirstSame) { 4203 if (!IsSecondSame) 4204 return ImplicitConversionSequence::Better; 4205 } else if (IsSecondSame) 4206 return ImplicitConversionSequence::Worse; 4207 } 4208 return ToAssignLeft? ImplicitConversionSequence::Worse 4209 : ImplicitConversionSequence::Better; 4210 } 4211 4212 // -- "conversion of B* to A* is better than conversion of C* to A*," 4213 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4214 (FromAssignLeft != FromAssignRight)) 4215 return FromAssignLeft? ImplicitConversionSequence::Better 4216 : ImplicitConversionSequence::Worse; 4217 } 4218 } 4219 4220 // Ranking of member-pointer types. 4221 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4222 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4223 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4224 const MemberPointerType * FromMemPointer1 = 4225 FromType1->getAs<MemberPointerType>(); 4226 const MemberPointerType * ToMemPointer1 = 4227 ToType1->getAs<MemberPointerType>(); 4228 const MemberPointerType * FromMemPointer2 = 4229 FromType2->getAs<MemberPointerType>(); 4230 const MemberPointerType * ToMemPointer2 = 4231 ToType2->getAs<MemberPointerType>(); 4232 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4233 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4234 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4235 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4236 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4237 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4238 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4239 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4240 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4241 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4242 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4243 return ImplicitConversionSequence::Worse; 4244 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4245 return ImplicitConversionSequence::Better; 4246 } 4247 // conversion of B::* to C::* is better than conversion of A::* to C::* 4248 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4249 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4250 return ImplicitConversionSequence::Better; 4251 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4252 return ImplicitConversionSequence::Worse; 4253 } 4254 } 4255 4256 if (SCS1.Second == ICK_Derived_To_Base) { 4257 // -- conversion of C to B is better than conversion of C to A, 4258 // -- binding of an expression of type C to a reference of type 4259 // B& is better than binding an expression of type C to a 4260 // reference of type A&, 4261 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4262 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4263 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4264 return ImplicitConversionSequence::Better; 4265 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4266 return ImplicitConversionSequence::Worse; 4267 } 4268 4269 // -- conversion of B to A is better than conversion of C to A. 4270 // -- binding of an expression of type B to a reference of type 4271 // A& is better than binding an expression of type C to a 4272 // reference of type A&, 4273 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4274 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4275 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4276 return ImplicitConversionSequence::Better; 4277 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4278 return ImplicitConversionSequence::Worse; 4279 } 4280 } 4281 4282 return ImplicitConversionSequence::Indistinguishable; 4283 } 4284 4285 /// Determine whether the given type is valid, e.g., it is not an invalid 4286 /// C++ class. 4287 static bool isTypeValid(QualType T) { 4288 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4289 return !Record->isInvalidDecl(); 4290 4291 return true; 4292 } 4293 4294 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4295 /// determine whether they are reference-related, 4296 /// reference-compatible, reference-compatible with added 4297 /// qualification, or incompatible, for use in C++ initialization by 4298 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4299 /// type, and the first type (T1) is the pointee type of the reference 4300 /// type being initialized. 4301 Sema::ReferenceCompareResult 4302 Sema::CompareReferenceRelationship(SourceLocation Loc, 4303 QualType OrigT1, QualType OrigT2, 4304 bool &DerivedToBase, 4305 bool &ObjCConversion, 4306 bool &ObjCLifetimeConversion) { 4307 assert(!OrigT1->isReferenceType() && 4308 "T1 must be the pointee type of the reference type"); 4309 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4310 4311 QualType T1 = Context.getCanonicalType(OrigT1); 4312 QualType T2 = Context.getCanonicalType(OrigT2); 4313 Qualifiers T1Quals, T2Quals; 4314 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4315 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4316 4317 // C++ [dcl.init.ref]p4: 4318 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4319 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4320 // T1 is a base class of T2. 4321 DerivedToBase = false; 4322 ObjCConversion = false; 4323 ObjCLifetimeConversion = false; 4324 QualType ConvertedT2; 4325 if (UnqualT1 == UnqualT2) { 4326 // Nothing to do. 4327 } else if (isCompleteType(Loc, OrigT2) && 4328 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4329 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4330 DerivedToBase = true; 4331 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4332 UnqualT2->isObjCObjectOrInterfaceType() && 4333 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4334 ObjCConversion = true; 4335 else if (UnqualT2->isFunctionType() && 4336 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4337 // C++1z [dcl.init.ref]p4: 4338 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4339 // function" and T1 is "function" 4340 // 4341 // We extend this to also apply to 'noreturn', so allow any function 4342 // conversion between function types. 4343 return Ref_Compatible; 4344 else 4345 return Ref_Incompatible; 4346 4347 // At this point, we know that T1 and T2 are reference-related (at 4348 // least). 4349 4350 // If the type is an array type, promote the element qualifiers to the type 4351 // for comparison. 4352 if (isa<ArrayType>(T1) && T1Quals) 4353 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4354 if (isa<ArrayType>(T2) && T2Quals) 4355 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4356 4357 // C++ [dcl.init.ref]p4: 4358 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4359 // reference-related to T2 and cv1 is the same cv-qualification 4360 // as, or greater cv-qualification than, cv2. For purposes of 4361 // overload resolution, cases for which cv1 is greater 4362 // cv-qualification than cv2 are identified as 4363 // reference-compatible with added qualification (see 13.3.3.2). 4364 // 4365 // Note that we also require equivalence of Objective-C GC and address-space 4366 // qualifiers when performing these computations, so that e.g., an int in 4367 // address space 1 is not reference-compatible with an int in address 4368 // space 2. 4369 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4370 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4371 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4372 ObjCLifetimeConversion = true; 4373 4374 T1Quals.removeObjCLifetime(); 4375 T2Quals.removeObjCLifetime(); 4376 } 4377 4378 // MS compiler ignores __unaligned qualifier for references; do the same. 4379 T1Quals.removeUnaligned(); 4380 T2Quals.removeUnaligned(); 4381 4382 if (T1Quals.compatiblyIncludes(T2Quals)) 4383 return Ref_Compatible; 4384 else 4385 return Ref_Related; 4386 } 4387 4388 /// Look for a user-defined conversion to a value reference-compatible 4389 /// with DeclType. Return true if something definite is found. 4390 static bool 4391 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4392 QualType DeclType, SourceLocation DeclLoc, 4393 Expr *Init, QualType T2, bool AllowRvalues, 4394 bool AllowExplicit) { 4395 assert(T2->isRecordType() && "Can only find conversions of record types."); 4396 CXXRecordDecl *T2RecordDecl 4397 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4398 4399 OverloadCandidateSet CandidateSet( 4400 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4401 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4402 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4403 NamedDecl *D = *I; 4404 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4405 if (isa<UsingShadowDecl>(D)) 4406 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4407 4408 FunctionTemplateDecl *ConvTemplate 4409 = dyn_cast<FunctionTemplateDecl>(D); 4410 CXXConversionDecl *Conv; 4411 if (ConvTemplate) 4412 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4413 else 4414 Conv = cast<CXXConversionDecl>(D); 4415 4416 // If this is an explicit conversion, and we're not allowed to consider 4417 // explicit conversions, skip it. 4418 if (!AllowExplicit && Conv->isExplicit()) 4419 continue; 4420 4421 if (AllowRvalues) { 4422 bool DerivedToBase = false; 4423 bool ObjCConversion = false; 4424 bool ObjCLifetimeConversion = false; 4425 4426 // If we are initializing an rvalue reference, don't permit conversion 4427 // functions that return lvalues. 4428 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4429 const ReferenceType *RefType 4430 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4431 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4432 continue; 4433 } 4434 4435 if (!ConvTemplate && 4436 S.CompareReferenceRelationship( 4437 DeclLoc, 4438 Conv->getConversionType().getNonReferenceType() 4439 .getUnqualifiedType(), 4440 DeclType.getNonReferenceType().getUnqualifiedType(), 4441 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4442 Sema::Ref_Incompatible) 4443 continue; 4444 } else { 4445 // If the conversion function doesn't return a reference type, 4446 // it can't be considered for this conversion. An rvalue reference 4447 // is only acceptable if its referencee is a function type. 4448 4449 const ReferenceType *RefType = 4450 Conv->getConversionType()->getAs<ReferenceType>(); 4451 if (!RefType || 4452 (!RefType->isLValueReferenceType() && 4453 !RefType->getPointeeType()->isFunctionType())) 4454 continue; 4455 } 4456 4457 if (ConvTemplate) 4458 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4459 Init, DeclType, CandidateSet, 4460 /*AllowObjCConversionOnExplicit=*/false); 4461 else 4462 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4463 DeclType, CandidateSet, 4464 /*AllowObjCConversionOnExplicit=*/false); 4465 } 4466 4467 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4468 4469 OverloadCandidateSet::iterator Best; 4470 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4471 case OR_Success: 4472 // C++ [over.ics.ref]p1: 4473 // 4474 // [...] If the parameter binds directly to the result of 4475 // applying a conversion function to the argument 4476 // expression, the implicit conversion sequence is a 4477 // user-defined conversion sequence (13.3.3.1.2), with the 4478 // second standard conversion sequence either an identity 4479 // conversion or, if the conversion function returns an 4480 // entity of a type that is a derived class of the parameter 4481 // type, a derived-to-base Conversion. 4482 if (!Best->FinalConversion.DirectBinding) 4483 return false; 4484 4485 ICS.setUserDefined(); 4486 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4487 ICS.UserDefined.After = Best->FinalConversion; 4488 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4489 ICS.UserDefined.ConversionFunction = Best->Function; 4490 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4491 ICS.UserDefined.EllipsisConversion = false; 4492 assert(ICS.UserDefined.After.ReferenceBinding && 4493 ICS.UserDefined.After.DirectBinding && 4494 "Expected a direct reference binding!"); 4495 return true; 4496 4497 case OR_Ambiguous: 4498 ICS.setAmbiguous(); 4499 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4500 Cand != CandidateSet.end(); ++Cand) 4501 if (Cand->Viable) 4502 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4503 return true; 4504 4505 case OR_No_Viable_Function: 4506 case OR_Deleted: 4507 // There was no suitable conversion, or we found a deleted 4508 // conversion; continue with other checks. 4509 return false; 4510 } 4511 4512 llvm_unreachable("Invalid OverloadResult!"); 4513 } 4514 4515 /// Compute an implicit conversion sequence for reference 4516 /// initialization. 4517 static ImplicitConversionSequence 4518 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4519 SourceLocation DeclLoc, 4520 bool SuppressUserConversions, 4521 bool AllowExplicit) { 4522 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4523 4524 // Most paths end in a failed conversion. 4525 ImplicitConversionSequence ICS; 4526 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4527 4528 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4529 QualType T2 = Init->getType(); 4530 4531 // If the initializer is the address of an overloaded function, try 4532 // to resolve the overloaded function. If all goes well, T2 is the 4533 // type of the resulting function. 4534 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4535 DeclAccessPair Found; 4536 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4537 false, Found)) 4538 T2 = Fn->getType(); 4539 } 4540 4541 // Compute some basic properties of the types and the initializer. 4542 bool isRValRef = DeclType->isRValueReferenceType(); 4543 bool DerivedToBase = false; 4544 bool ObjCConversion = false; 4545 bool ObjCLifetimeConversion = false; 4546 Expr::Classification InitCategory = Init->Classify(S.Context); 4547 Sema::ReferenceCompareResult RefRelationship 4548 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4549 ObjCConversion, ObjCLifetimeConversion); 4550 4551 4552 // C++0x [dcl.init.ref]p5: 4553 // A reference to type "cv1 T1" is initialized by an expression 4554 // of type "cv2 T2" as follows: 4555 4556 // -- If reference is an lvalue reference and the initializer expression 4557 if (!isRValRef) { 4558 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4559 // reference-compatible with "cv2 T2," or 4560 // 4561 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4562 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4563 // C++ [over.ics.ref]p1: 4564 // When a parameter of reference type binds directly (8.5.3) 4565 // to an argument expression, the implicit conversion sequence 4566 // is the identity conversion, unless the argument expression 4567 // has a type that is a derived class of the parameter type, 4568 // in which case the implicit conversion sequence is a 4569 // derived-to-base Conversion (13.3.3.1). 4570 ICS.setStandard(); 4571 ICS.Standard.First = ICK_Identity; 4572 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4573 : ObjCConversion? ICK_Compatible_Conversion 4574 : ICK_Identity; 4575 ICS.Standard.Third = ICK_Identity; 4576 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4577 ICS.Standard.setToType(0, T2); 4578 ICS.Standard.setToType(1, T1); 4579 ICS.Standard.setToType(2, T1); 4580 ICS.Standard.ReferenceBinding = true; 4581 ICS.Standard.DirectBinding = true; 4582 ICS.Standard.IsLvalueReference = !isRValRef; 4583 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4584 ICS.Standard.BindsToRvalue = false; 4585 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4586 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4587 ICS.Standard.CopyConstructor = nullptr; 4588 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4589 4590 // Nothing more to do: the inaccessibility/ambiguity check for 4591 // derived-to-base conversions is suppressed when we're 4592 // computing the implicit conversion sequence (C++ 4593 // [over.best.ics]p2). 4594 return ICS; 4595 } 4596 4597 // -- has a class type (i.e., T2 is a class type), where T1 is 4598 // not reference-related to T2, and can be implicitly 4599 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4600 // is reference-compatible with "cv3 T3" 92) (this 4601 // conversion is selected by enumerating the applicable 4602 // conversion functions (13.3.1.6) and choosing the best 4603 // one through overload resolution (13.3)), 4604 if (!SuppressUserConversions && T2->isRecordType() && 4605 S.isCompleteType(DeclLoc, T2) && 4606 RefRelationship == Sema::Ref_Incompatible) { 4607 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4608 Init, T2, /*AllowRvalues=*/false, 4609 AllowExplicit)) 4610 return ICS; 4611 } 4612 } 4613 4614 // -- Otherwise, the reference shall be an lvalue reference to a 4615 // non-volatile const type (i.e., cv1 shall be const), or the reference 4616 // shall be an rvalue reference. 4617 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4618 return ICS; 4619 4620 // -- If the initializer expression 4621 // 4622 // -- is an xvalue, class prvalue, array prvalue or function 4623 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4624 if (RefRelationship == Sema::Ref_Compatible && 4625 (InitCategory.isXValue() || 4626 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4627 (InitCategory.isLValue() && T2->isFunctionType()))) { 4628 ICS.setStandard(); 4629 ICS.Standard.First = ICK_Identity; 4630 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4631 : ObjCConversion? ICK_Compatible_Conversion 4632 : ICK_Identity; 4633 ICS.Standard.Third = ICK_Identity; 4634 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4635 ICS.Standard.setToType(0, T2); 4636 ICS.Standard.setToType(1, T1); 4637 ICS.Standard.setToType(2, T1); 4638 ICS.Standard.ReferenceBinding = true; 4639 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4640 // binding unless we're binding to a class prvalue. 4641 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4642 // allow the use of rvalue references in C++98/03 for the benefit of 4643 // standard library implementors; therefore, we need the xvalue check here. 4644 ICS.Standard.DirectBinding = 4645 S.getLangOpts().CPlusPlus11 || 4646 !(InitCategory.isPRValue() || T2->isRecordType()); 4647 ICS.Standard.IsLvalueReference = !isRValRef; 4648 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4649 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4650 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4651 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4652 ICS.Standard.CopyConstructor = nullptr; 4653 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4654 return ICS; 4655 } 4656 4657 // -- has a class type (i.e., T2 is a class type), where T1 is not 4658 // reference-related to T2, and can be implicitly converted to 4659 // an xvalue, class prvalue, or function lvalue of type 4660 // "cv3 T3", where "cv1 T1" is reference-compatible with 4661 // "cv3 T3", 4662 // 4663 // then the reference is bound to the value of the initializer 4664 // expression in the first case and to the result of the conversion 4665 // in the second case (or, in either case, to an appropriate base 4666 // class subobject). 4667 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4668 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4669 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4670 Init, T2, /*AllowRvalues=*/true, 4671 AllowExplicit)) { 4672 // In the second case, if the reference is an rvalue reference 4673 // and the second standard conversion sequence of the 4674 // user-defined conversion sequence includes an lvalue-to-rvalue 4675 // conversion, the program is ill-formed. 4676 if (ICS.isUserDefined() && isRValRef && 4677 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4678 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4679 4680 return ICS; 4681 } 4682 4683 // A temporary of function type cannot be created; don't even try. 4684 if (T1->isFunctionType()) 4685 return ICS; 4686 4687 // -- Otherwise, a temporary of type "cv1 T1" is created and 4688 // initialized from the initializer expression using the 4689 // rules for a non-reference copy initialization (8.5). The 4690 // reference is then bound to the temporary. If T1 is 4691 // reference-related to T2, cv1 must be the same 4692 // cv-qualification as, or greater cv-qualification than, 4693 // cv2; otherwise, the program is ill-formed. 4694 if (RefRelationship == Sema::Ref_Related) { 4695 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4696 // we would be reference-compatible or reference-compatible with 4697 // added qualification. But that wasn't the case, so the reference 4698 // initialization fails. 4699 // 4700 // Note that we only want to check address spaces and cvr-qualifiers here. 4701 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4702 Qualifiers T1Quals = T1.getQualifiers(); 4703 Qualifiers T2Quals = T2.getQualifiers(); 4704 T1Quals.removeObjCGCAttr(); 4705 T1Quals.removeObjCLifetime(); 4706 T2Quals.removeObjCGCAttr(); 4707 T2Quals.removeObjCLifetime(); 4708 // MS compiler ignores __unaligned qualifier for references; do the same. 4709 T1Quals.removeUnaligned(); 4710 T2Quals.removeUnaligned(); 4711 if (!T1Quals.compatiblyIncludes(T2Quals)) 4712 return ICS; 4713 } 4714 4715 // If at least one of the types is a class type, the types are not 4716 // related, and we aren't allowed any user conversions, the 4717 // reference binding fails. This case is important for breaking 4718 // recursion, since TryImplicitConversion below will attempt to 4719 // create a temporary through the use of a copy constructor. 4720 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4721 (T1->isRecordType() || T2->isRecordType())) 4722 return ICS; 4723 4724 // If T1 is reference-related to T2 and the reference is an rvalue 4725 // reference, the initializer expression shall not be an lvalue. 4726 if (RefRelationship >= Sema::Ref_Related && 4727 isRValRef && Init->Classify(S.Context).isLValue()) 4728 return ICS; 4729 4730 // C++ [over.ics.ref]p2: 4731 // When a parameter of reference type is not bound directly to 4732 // an argument expression, the conversion sequence is the one 4733 // required to convert the argument expression to the 4734 // underlying type of the reference according to 4735 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4736 // to copy-initializing a temporary of the underlying type with 4737 // the argument expression. Any difference in top-level 4738 // cv-qualification is subsumed by the initialization itself 4739 // and does not constitute a conversion. 4740 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4741 /*AllowExplicit=*/false, 4742 /*InOverloadResolution=*/false, 4743 /*CStyle=*/false, 4744 /*AllowObjCWritebackConversion=*/false, 4745 /*AllowObjCConversionOnExplicit=*/false); 4746 4747 // Of course, that's still a reference binding. 4748 if (ICS.isStandard()) { 4749 ICS.Standard.ReferenceBinding = true; 4750 ICS.Standard.IsLvalueReference = !isRValRef; 4751 ICS.Standard.BindsToFunctionLvalue = false; 4752 ICS.Standard.BindsToRvalue = true; 4753 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4754 ICS.Standard.ObjCLifetimeConversionBinding = false; 4755 } else if (ICS.isUserDefined()) { 4756 const ReferenceType *LValRefType = 4757 ICS.UserDefined.ConversionFunction->getReturnType() 4758 ->getAs<LValueReferenceType>(); 4759 4760 // C++ [over.ics.ref]p3: 4761 // Except for an implicit object parameter, for which see 13.3.1, a 4762 // standard conversion sequence cannot be formed if it requires [...] 4763 // binding an rvalue reference to an lvalue other than a function 4764 // lvalue. 4765 // Note that the function case is not possible here. 4766 if (DeclType->isRValueReferenceType() && LValRefType) { 4767 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4768 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4769 // reference to an rvalue! 4770 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4771 return ICS; 4772 } 4773 4774 ICS.UserDefined.After.ReferenceBinding = true; 4775 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4776 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4777 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4778 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4779 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4780 } 4781 4782 return ICS; 4783 } 4784 4785 static ImplicitConversionSequence 4786 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4787 bool SuppressUserConversions, 4788 bool InOverloadResolution, 4789 bool AllowObjCWritebackConversion, 4790 bool AllowExplicit = false); 4791 4792 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4793 /// initializer list From. 4794 static ImplicitConversionSequence 4795 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4796 bool SuppressUserConversions, 4797 bool InOverloadResolution, 4798 bool AllowObjCWritebackConversion) { 4799 // C++11 [over.ics.list]p1: 4800 // When an argument is an initializer list, it is not an expression and 4801 // special rules apply for converting it to a parameter type. 4802 4803 ImplicitConversionSequence Result; 4804 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4805 4806 // We need a complete type for what follows. Incomplete types can never be 4807 // initialized from init lists. 4808 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4809 return Result; 4810 4811 // Per DR1467: 4812 // If the parameter type is a class X and the initializer list has a single 4813 // element of type cv U, where U is X or a class derived from X, the 4814 // implicit conversion sequence is the one required to convert the element 4815 // to the parameter type. 4816 // 4817 // Otherwise, if the parameter type is a character array [... ] 4818 // and the initializer list has a single element that is an 4819 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4820 // implicit conversion sequence is the identity conversion. 4821 if (From->getNumInits() == 1) { 4822 if (ToType->isRecordType()) { 4823 QualType InitType = From->getInit(0)->getType(); 4824 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4825 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4826 return TryCopyInitialization(S, From->getInit(0), ToType, 4827 SuppressUserConversions, 4828 InOverloadResolution, 4829 AllowObjCWritebackConversion); 4830 } 4831 // FIXME: Check the other conditions here: array of character type, 4832 // initializer is a string literal. 4833 if (ToType->isArrayType()) { 4834 InitializedEntity Entity = 4835 InitializedEntity::InitializeParameter(S.Context, ToType, 4836 /*Consumed=*/false); 4837 if (S.CanPerformCopyInitialization(Entity, From)) { 4838 Result.setStandard(); 4839 Result.Standard.setAsIdentityConversion(); 4840 Result.Standard.setFromType(ToType); 4841 Result.Standard.setAllToTypes(ToType); 4842 return Result; 4843 } 4844 } 4845 } 4846 4847 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4848 // C++11 [over.ics.list]p2: 4849 // If the parameter type is std::initializer_list<X> or "array of X" and 4850 // all the elements can be implicitly converted to X, the implicit 4851 // conversion sequence is the worst conversion necessary to convert an 4852 // element of the list to X. 4853 // 4854 // C++14 [over.ics.list]p3: 4855 // Otherwise, if the parameter type is "array of N X", if the initializer 4856 // list has exactly N elements or if it has fewer than N elements and X is 4857 // default-constructible, and if all the elements of the initializer list 4858 // can be implicitly converted to X, the implicit conversion sequence is 4859 // the worst conversion necessary to convert an element of the list to X. 4860 // 4861 // FIXME: We're missing a lot of these checks. 4862 bool toStdInitializerList = false; 4863 QualType X; 4864 if (ToType->isArrayType()) 4865 X = S.Context.getAsArrayType(ToType)->getElementType(); 4866 else 4867 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4868 if (!X.isNull()) { 4869 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4870 Expr *Init = From->getInit(i); 4871 ImplicitConversionSequence ICS = 4872 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4873 InOverloadResolution, 4874 AllowObjCWritebackConversion); 4875 // If a single element isn't convertible, fail. 4876 if (ICS.isBad()) { 4877 Result = ICS; 4878 break; 4879 } 4880 // Otherwise, look for the worst conversion. 4881 if (Result.isBad() || CompareImplicitConversionSequences( 4882 S, From->getBeginLoc(), ICS, Result) == 4883 ImplicitConversionSequence::Worse) 4884 Result = ICS; 4885 } 4886 4887 // For an empty list, we won't have computed any conversion sequence. 4888 // Introduce the identity conversion sequence. 4889 if (From->getNumInits() == 0) { 4890 Result.setStandard(); 4891 Result.Standard.setAsIdentityConversion(); 4892 Result.Standard.setFromType(ToType); 4893 Result.Standard.setAllToTypes(ToType); 4894 } 4895 4896 Result.setStdInitializerListElement(toStdInitializerList); 4897 return Result; 4898 } 4899 4900 // C++14 [over.ics.list]p4: 4901 // C++11 [over.ics.list]p3: 4902 // Otherwise, if the parameter is a non-aggregate class X and overload 4903 // resolution chooses a single best constructor [...] the implicit 4904 // conversion sequence is a user-defined conversion sequence. If multiple 4905 // constructors are viable but none is better than the others, the 4906 // implicit conversion sequence is a user-defined conversion sequence. 4907 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4908 // This function can deal with initializer lists. 4909 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4910 /*AllowExplicit=*/false, 4911 InOverloadResolution, /*CStyle=*/false, 4912 AllowObjCWritebackConversion, 4913 /*AllowObjCConversionOnExplicit=*/false); 4914 } 4915 4916 // C++14 [over.ics.list]p5: 4917 // C++11 [over.ics.list]p4: 4918 // Otherwise, if the parameter has an aggregate type which can be 4919 // initialized from the initializer list [...] the implicit conversion 4920 // sequence is a user-defined conversion sequence. 4921 if (ToType->isAggregateType()) { 4922 // Type is an aggregate, argument is an init list. At this point it comes 4923 // down to checking whether the initialization works. 4924 // FIXME: Find out whether this parameter is consumed or not. 4925 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4926 // need to call into the initialization code here; overload resolution 4927 // should not be doing that. 4928 InitializedEntity Entity = 4929 InitializedEntity::InitializeParameter(S.Context, ToType, 4930 /*Consumed=*/false); 4931 if (S.CanPerformCopyInitialization(Entity, From)) { 4932 Result.setUserDefined(); 4933 Result.UserDefined.Before.setAsIdentityConversion(); 4934 // Initializer lists don't have a type. 4935 Result.UserDefined.Before.setFromType(QualType()); 4936 Result.UserDefined.Before.setAllToTypes(QualType()); 4937 4938 Result.UserDefined.After.setAsIdentityConversion(); 4939 Result.UserDefined.After.setFromType(ToType); 4940 Result.UserDefined.After.setAllToTypes(ToType); 4941 Result.UserDefined.ConversionFunction = nullptr; 4942 } 4943 return Result; 4944 } 4945 4946 // C++14 [over.ics.list]p6: 4947 // C++11 [over.ics.list]p5: 4948 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4949 if (ToType->isReferenceType()) { 4950 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4951 // mention initializer lists in any way. So we go by what list- 4952 // initialization would do and try to extrapolate from that. 4953 4954 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4955 4956 // If the initializer list has a single element that is reference-related 4957 // to the parameter type, we initialize the reference from that. 4958 if (From->getNumInits() == 1) { 4959 Expr *Init = From->getInit(0); 4960 4961 QualType T2 = Init->getType(); 4962 4963 // If the initializer is the address of an overloaded function, try 4964 // to resolve the overloaded function. If all goes well, T2 is the 4965 // type of the resulting function. 4966 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4967 DeclAccessPair Found; 4968 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4969 Init, ToType, false, Found)) 4970 T2 = Fn->getType(); 4971 } 4972 4973 // Compute some basic properties of the types and the initializer. 4974 bool dummy1 = false; 4975 bool dummy2 = false; 4976 bool dummy3 = false; 4977 Sema::ReferenceCompareResult RefRelationship = 4978 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, 4979 dummy2, dummy3); 4980 4981 if (RefRelationship >= Sema::Ref_Related) { 4982 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 4983 SuppressUserConversions, 4984 /*AllowExplicit=*/false); 4985 } 4986 } 4987 4988 // Otherwise, we bind the reference to a temporary created from the 4989 // initializer list. 4990 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4991 InOverloadResolution, 4992 AllowObjCWritebackConversion); 4993 if (Result.isFailure()) 4994 return Result; 4995 assert(!Result.isEllipsis() && 4996 "Sub-initialization cannot result in ellipsis conversion."); 4997 4998 // Can we even bind to a temporary? 4999 if (ToType->isRValueReferenceType() || 5000 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5001 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5002 Result.UserDefined.After; 5003 SCS.ReferenceBinding = true; 5004 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5005 SCS.BindsToRvalue = true; 5006 SCS.BindsToFunctionLvalue = false; 5007 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5008 SCS.ObjCLifetimeConversionBinding = false; 5009 } else 5010 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5011 From, ToType); 5012 return Result; 5013 } 5014 5015 // C++14 [over.ics.list]p7: 5016 // C++11 [over.ics.list]p6: 5017 // Otherwise, if the parameter type is not a class: 5018 if (!ToType->isRecordType()) { 5019 // - if the initializer list has one element that is not itself an 5020 // initializer list, the implicit conversion sequence is the one 5021 // required to convert the element to the parameter type. 5022 unsigned NumInits = From->getNumInits(); 5023 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5024 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5025 SuppressUserConversions, 5026 InOverloadResolution, 5027 AllowObjCWritebackConversion); 5028 // - if the initializer list has no elements, the implicit conversion 5029 // sequence is the identity conversion. 5030 else if (NumInits == 0) { 5031 Result.setStandard(); 5032 Result.Standard.setAsIdentityConversion(); 5033 Result.Standard.setFromType(ToType); 5034 Result.Standard.setAllToTypes(ToType); 5035 } 5036 return Result; 5037 } 5038 5039 // C++14 [over.ics.list]p8: 5040 // C++11 [over.ics.list]p7: 5041 // In all cases other than those enumerated above, no conversion is possible 5042 return Result; 5043 } 5044 5045 /// TryCopyInitialization - Try to copy-initialize a value of type 5046 /// ToType from the expression From. Return the implicit conversion 5047 /// sequence required to pass this argument, which may be a bad 5048 /// conversion sequence (meaning that the argument cannot be passed to 5049 /// a parameter of this type). If @p SuppressUserConversions, then we 5050 /// do not permit any user-defined conversion sequences. 5051 static ImplicitConversionSequence 5052 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5053 bool SuppressUserConversions, 5054 bool InOverloadResolution, 5055 bool AllowObjCWritebackConversion, 5056 bool AllowExplicit) { 5057 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5058 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5059 InOverloadResolution,AllowObjCWritebackConversion); 5060 5061 if (ToType->isReferenceType()) 5062 return TryReferenceInit(S, From, ToType, 5063 /*FIXME:*/ From->getBeginLoc(), 5064 SuppressUserConversions, AllowExplicit); 5065 5066 return TryImplicitConversion(S, From, ToType, 5067 SuppressUserConversions, 5068 /*AllowExplicit=*/false, 5069 InOverloadResolution, 5070 /*CStyle=*/false, 5071 AllowObjCWritebackConversion, 5072 /*AllowObjCConversionOnExplicit=*/false); 5073 } 5074 5075 static bool TryCopyInitialization(const CanQualType FromQTy, 5076 const CanQualType ToQTy, 5077 Sema &S, 5078 SourceLocation Loc, 5079 ExprValueKind FromVK) { 5080 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5081 ImplicitConversionSequence ICS = 5082 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5083 5084 return !ICS.isBad(); 5085 } 5086 5087 /// TryObjectArgumentInitialization - Try to initialize the object 5088 /// parameter of the given member function (@c Method) from the 5089 /// expression @p From. 5090 static ImplicitConversionSequence 5091 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5092 Expr::Classification FromClassification, 5093 CXXMethodDecl *Method, 5094 CXXRecordDecl *ActingContext) { 5095 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5096 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5097 // const volatile object. 5098 Qualifiers Quals; 5099 if (isa<CXXDestructorDecl>(Method)) { 5100 Quals.addConst(); 5101 Quals.addVolatile(); 5102 } else { 5103 Quals = Method->getMethodQualifiers(); 5104 } 5105 5106 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5107 5108 // Set up the conversion sequence as a "bad" conversion, to allow us 5109 // to exit early. 5110 ImplicitConversionSequence ICS; 5111 5112 // We need to have an object of class type. 5113 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5114 FromType = PT->getPointeeType(); 5115 5116 // When we had a pointer, it's implicitly dereferenced, so we 5117 // better have an lvalue. 5118 assert(FromClassification.isLValue()); 5119 } 5120 5121 assert(FromType->isRecordType()); 5122 5123 // C++0x [over.match.funcs]p4: 5124 // For non-static member functions, the type of the implicit object 5125 // parameter is 5126 // 5127 // - "lvalue reference to cv X" for functions declared without a 5128 // ref-qualifier or with the & ref-qualifier 5129 // - "rvalue reference to cv X" for functions declared with the && 5130 // ref-qualifier 5131 // 5132 // where X is the class of which the function is a member and cv is the 5133 // cv-qualification on the member function declaration. 5134 // 5135 // However, when finding an implicit conversion sequence for the argument, we 5136 // are not allowed to perform user-defined conversions 5137 // (C++ [over.match.funcs]p5). We perform a simplified version of 5138 // reference binding here, that allows class rvalues to bind to 5139 // non-constant references. 5140 5141 // First check the qualifiers. 5142 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5143 if (ImplicitParamType.getCVRQualifiers() 5144 != FromTypeCanon.getLocalCVRQualifiers() && 5145 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5146 ICS.setBad(BadConversionSequence::bad_qualifiers, 5147 FromType, ImplicitParamType); 5148 return ICS; 5149 } 5150 5151 if (FromTypeCanon.getQualifiers().hasAddressSpace()) { 5152 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5153 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5154 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5155 ICS.setBad(BadConversionSequence::bad_qualifiers, 5156 FromType, ImplicitParamType); 5157 return ICS; 5158 } 5159 } 5160 5161 // Check that we have either the same type or a derived type. It 5162 // affects the conversion rank. 5163 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5164 ImplicitConversionKind SecondKind; 5165 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5166 SecondKind = ICK_Identity; 5167 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5168 SecondKind = ICK_Derived_To_Base; 5169 else { 5170 ICS.setBad(BadConversionSequence::unrelated_class, 5171 FromType, ImplicitParamType); 5172 return ICS; 5173 } 5174 5175 // Check the ref-qualifier. 5176 switch (Method->getRefQualifier()) { 5177 case RQ_None: 5178 // Do nothing; we don't care about lvalueness or rvalueness. 5179 break; 5180 5181 case RQ_LValue: 5182 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5183 // non-const lvalue reference cannot bind to an rvalue 5184 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5185 ImplicitParamType); 5186 return ICS; 5187 } 5188 break; 5189 5190 case RQ_RValue: 5191 if (!FromClassification.isRValue()) { 5192 // rvalue reference cannot bind to an lvalue 5193 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5194 ImplicitParamType); 5195 return ICS; 5196 } 5197 break; 5198 } 5199 5200 // Success. Mark this as a reference binding. 5201 ICS.setStandard(); 5202 ICS.Standard.setAsIdentityConversion(); 5203 ICS.Standard.Second = SecondKind; 5204 ICS.Standard.setFromType(FromType); 5205 ICS.Standard.setAllToTypes(ImplicitParamType); 5206 ICS.Standard.ReferenceBinding = true; 5207 ICS.Standard.DirectBinding = true; 5208 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5209 ICS.Standard.BindsToFunctionLvalue = false; 5210 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5211 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5212 = (Method->getRefQualifier() == RQ_None); 5213 return ICS; 5214 } 5215 5216 /// PerformObjectArgumentInitialization - Perform initialization of 5217 /// the implicit object parameter for the given Method with the given 5218 /// expression. 5219 ExprResult 5220 Sema::PerformObjectArgumentInitialization(Expr *From, 5221 NestedNameSpecifier *Qualifier, 5222 NamedDecl *FoundDecl, 5223 CXXMethodDecl *Method) { 5224 QualType FromRecordType, DestType; 5225 QualType ImplicitParamRecordType = 5226 Method->getThisType()->getAs<PointerType>()->getPointeeType(); 5227 5228 Expr::Classification FromClassification; 5229 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5230 FromRecordType = PT->getPointeeType(); 5231 DestType = Method->getThisType(); 5232 FromClassification = Expr::Classification::makeSimpleLValue(); 5233 } else { 5234 FromRecordType = From->getType(); 5235 DestType = ImplicitParamRecordType; 5236 FromClassification = From->Classify(Context); 5237 5238 // When performing member access on an rvalue, materialize a temporary. 5239 if (From->isRValue()) { 5240 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5241 Method->getRefQualifier() != 5242 RefQualifierKind::RQ_RValue); 5243 } 5244 } 5245 5246 // Note that we always use the true parent context when performing 5247 // the actual argument initialization. 5248 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5249 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5250 Method->getParent()); 5251 if (ICS.isBad()) { 5252 switch (ICS.Bad.Kind) { 5253 case BadConversionSequence::bad_qualifiers: { 5254 Qualifiers FromQs = FromRecordType.getQualifiers(); 5255 Qualifiers ToQs = DestType.getQualifiers(); 5256 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5257 if (CVR) { 5258 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5259 << Method->getDeclName() << FromRecordType << (CVR - 1) 5260 << From->getSourceRange(); 5261 Diag(Method->getLocation(), diag::note_previous_decl) 5262 << Method->getDeclName(); 5263 return ExprError(); 5264 } 5265 break; 5266 } 5267 5268 case BadConversionSequence::lvalue_ref_to_rvalue: 5269 case BadConversionSequence::rvalue_ref_to_lvalue: { 5270 bool IsRValueQualified = 5271 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5272 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5273 << Method->getDeclName() << FromClassification.isRValue() 5274 << IsRValueQualified; 5275 Diag(Method->getLocation(), diag::note_previous_decl) 5276 << Method->getDeclName(); 5277 return ExprError(); 5278 } 5279 5280 case BadConversionSequence::no_conversion: 5281 case BadConversionSequence::unrelated_class: 5282 break; 5283 } 5284 5285 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5286 << ImplicitParamRecordType << FromRecordType 5287 << From->getSourceRange(); 5288 } 5289 5290 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5291 ExprResult FromRes = 5292 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5293 if (FromRes.isInvalid()) 5294 return ExprError(); 5295 From = FromRes.get(); 5296 } 5297 5298 if (!Context.hasSameType(From->getType(), DestType)) { 5299 if (From->getType().getAddressSpace() != DestType.getAddressSpace()) 5300 From = ImpCastExprToType(From, DestType, CK_AddressSpaceConversion, 5301 From->getValueKind()).get(); 5302 else 5303 From = ImpCastExprToType(From, DestType, CK_NoOp, 5304 From->getValueKind()).get(); 5305 } 5306 return From; 5307 } 5308 5309 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5310 /// expression From to bool (C++0x [conv]p3). 5311 static ImplicitConversionSequence 5312 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5313 return TryImplicitConversion(S, From, S.Context.BoolTy, 5314 /*SuppressUserConversions=*/false, 5315 /*AllowExplicit=*/true, 5316 /*InOverloadResolution=*/false, 5317 /*CStyle=*/false, 5318 /*AllowObjCWritebackConversion=*/false, 5319 /*AllowObjCConversionOnExplicit=*/false); 5320 } 5321 5322 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5323 /// of the expression From to bool (C++0x [conv]p3). 5324 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5325 if (checkPlaceholderForOverload(*this, From)) 5326 return ExprError(); 5327 5328 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5329 if (!ICS.isBad()) 5330 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5331 5332 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5333 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5334 << From->getType() << From->getSourceRange(); 5335 return ExprError(); 5336 } 5337 5338 /// Check that the specified conversion is permitted in a converted constant 5339 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5340 /// is acceptable. 5341 static bool CheckConvertedConstantConversions(Sema &S, 5342 StandardConversionSequence &SCS) { 5343 // Since we know that the target type is an integral or unscoped enumeration 5344 // type, most conversion kinds are impossible. All possible First and Third 5345 // conversions are fine. 5346 switch (SCS.Second) { 5347 case ICK_Identity: 5348 case ICK_Function_Conversion: 5349 case ICK_Integral_Promotion: 5350 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5351 case ICK_Zero_Queue_Conversion: 5352 return true; 5353 5354 case ICK_Boolean_Conversion: 5355 // Conversion from an integral or unscoped enumeration type to bool is 5356 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5357 // conversion, so we allow it in a converted constant expression. 5358 // 5359 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5360 // a lot of popular code. We should at least add a warning for this 5361 // (non-conforming) extension. 5362 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5363 SCS.getToType(2)->isBooleanType(); 5364 5365 case ICK_Pointer_Conversion: 5366 case ICK_Pointer_Member: 5367 // C++1z: null pointer conversions and null member pointer conversions are 5368 // only permitted if the source type is std::nullptr_t. 5369 return SCS.getFromType()->isNullPtrType(); 5370 5371 case ICK_Floating_Promotion: 5372 case ICK_Complex_Promotion: 5373 case ICK_Floating_Conversion: 5374 case ICK_Complex_Conversion: 5375 case ICK_Floating_Integral: 5376 case ICK_Compatible_Conversion: 5377 case ICK_Derived_To_Base: 5378 case ICK_Vector_Conversion: 5379 case ICK_Vector_Splat: 5380 case ICK_Complex_Real: 5381 case ICK_Block_Pointer_Conversion: 5382 case ICK_TransparentUnionConversion: 5383 case ICK_Writeback_Conversion: 5384 case ICK_Zero_Event_Conversion: 5385 case ICK_C_Only_Conversion: 5386 case ICK_Incompatible_Pointer_Conversion: 5387 return false; 5388 5389 case ICK_Lvalue_To_Rvalue: 5390 case ICK_Array_To_Pointer: 5391 case ICK_Function_To_Pointer: 5392 llvm_unreachable("found a first conversion kind in Second"); 5393 5394 case ICK_Qualification: 5395 llvm_unreachable("found a third conversion kind in Second"); 5396 5397 case ICK_Num_Conversion_Kinds: 5398 break; 5399 } 5400 5401 llvm_unreachable("unknown conversion kind"); 5402 } 5403 5404 /// CheckConvertedConstantExpression - Check that the expression From is a 5405 /// converted constant expression of type T, perform the conversion and produce 5406 /// the converted expression, per C++11 [expr.const]p3. 5407 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5408 QualType T, APValue &Value, 5409 Sema::CCEKind CCE, 5410 bool RequireInt) { 5411 assert(S.getLangOpts().CPlusPlus11 && 5412 "converted constant expression outside C++11"); 5413 5414 if (checkPlaceholderForOverload(S, From)) 5415 return ExprError(); 5416 5417 // C++1z [expr.const]p3: 5418 // A converted constant expression of type T is an expression, 5419 // implicitly converted to type T, where the converted 5420 // expression is a constant expression and the implicit conversion 5421 // sequence contains only [... list of conversions ...]. 5422 // C++1z [stmt.if]p2: 5423 // If the if statement is of the form if constexpr, the value of the 5424 // condition shall be a contextually converted constant expression of type 5425 // bool. 5426 ImplicitConversionSequence ICS = 5427 CCE == Sema::CCEK_ConstexprIf 5428 ? TryContextuallyConvertToBool(S, From) 5429 : TryCopyInitialization(S, From, T, 5430 /*SuppressUserConversions=*/false, 5431 /*InOverloadResolution=*/false, 5432 /*AllowObjcWritebackConversion=*/false, 5433 /*AllowExplicit=*/false); 5434 StandardConversionSequence *SCS = nullptr; 5435 switch (ICS.getKind()) { 5436 case ImplicitConversionSequence::StandardConversion: 5437 SCS = &ICS.Standard; 5438 break; 5439 case ImplicitConversionSequence::UserDefinedConversion: 5440 // We are converting to a non-class type, so the Before sequence 5441 // must be trivial. 5442 SCS = &ICS.UserDefined.After; 5443 break; 5444 case ImplicitConversionSequence::AmbiguousConversion: 5445 case ImplicitConversionSequence::BadConversion: 5446 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5447 return S.Diag(From->getBeginLoc(), 5448 diag::err_typecheck_converted_constant_expression) 5449 << From->getType() << From->getSourceRange() << T; 5450 return ExprError(); 5451 5452 case ImplicitConversionSequence::EllipsisConversion: 5453 llvm_unreachable("ellipsis conversion in converted constant expression"); 5454 } 5455 5456 // Check that we would only use permitted conversions. 5457 if (!CheckConvertedConstantConversions(S, *SCS)) { 5458 return S.Diag(From->getBeginLoc(), 5459 diag::err_typecheck_converted_constant_expression_disallowed) 5460 << From->getType() << From->getSourceRange() << T; 5461 } 5462 // [...] and where the reference binding (if any) binds directly. 5463 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5464 return S.Diag(From->getBeginLoc(), 5465 diag::err_typecheck_converted_constant_expression_indirect) 5466 << From->getType() << From->getSourceRange() << T; 5467 } 5468 5469 ExprResult Result = 5470 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5471 if (Result.isInvalid()) 5472 return Result; 5473 5474 // Check for a narrowing implicit conversion. 5475 APValue PreNarrowingValue; 5476 QualType PreNarrowingType; 5477 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5478 PreNarrowingType)) { 5479 case NK_Dependent_Narrowing: 5480 // Implicit conversion to a narrower type, but the expression is 5481 // value-dependent so we can't tell whether it's actually narrowing. 5482 case NK_Variable_Narrowing: 5483 // Implicit conversion to a narrower type, and the value is not a constant 5484 // expression. We'll diagnose this in a moment. 5485 case NK_Not_Narrowing: 5486 break; 5487 5488 case NK_Constant_Narrowing: 5489 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5490 << CCE << /*Constant*/ 1 5491 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5492 break; 5493 5494 case NK_Type_Narrowing: 5495 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5496 << CCE << /*Constant*/ 0 << From->getType() << T; 5497 break; 5498 } 5499 5500 if (Result.get()->isValueDependent()) { 5501 Value = APValue(); 5502 return Result; 5503 } 5504 5505 // Check the expression is a constant expression. 5506 SmallVector<PartialDiagnosticAt, 8> Notes; 5507 Expr::EvalResult Eval; 5508 Eval.Diag = &Notes; 5509 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5510 ? Expr::EvaluateForMangling 5511 : Expr::EvaluateForCodeGen; 5512 5513 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5514 (RequireInt && !Eval.Val.isInt())) { 5515 // The expression can't be folded, so we can't keep it at this position in 5516 // the AST. 5517 Result = ExprError(); 5518 } else { 5519 Value = Eval.Val; 5520 5521 if (Notes.empty()) { 5522 // It's a constant expression. 5523 return ConstantExpr::Create(S.Context, Result.get()); 5524 } 5525 } 5526 5527 // It's not a constant expression. Produce an appropriate diagnostic. 5528 if (Notes.size() == 1 && 5529 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5530 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5531 else { 5532 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5533 << CCE << From->getSourceRange(); 5534 for (unsigned I = 0; I < Notes.size(); ++I) 5535 S.Diag(Notes[I].first, Notes[I].second); 5536 } 5537 return ExprError(); 5538 } 5539 5540 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5541 APValue &Value, CCEKind CCE) { 5542 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5543 } 5544 5545 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5546 llvm::APSInt &Value, 5547 CCEKind CCE) { 5548 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5549 5550 APValue V; 5551 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5552 if (!R.isInvalid() && !R.get()->isValueDependent()) 5553 Value = V.getInt(); 5554 return R; 5555 } 5556 5557 5558 /// dropPointerConversions - If the given standard conversion sequence 5559 /// involves any pointer conversions, remove them. This may change 5560 /// the result type of the conversion sequence. 5561 static void dropPointerConversion(StandardConversionSequence &SCS) { 5562 if (SCS.Second == ICK_Pointer_Conversion) { 5563 SCS.Second = ICK_Identity; 5564 SCS.Third = ICK_Identity; 5565 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5566 } 5567 } 5568 5569 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5570 /// convert the expression From to an Objective-C pointer type. 5571 static ImplicitConversionSequence 5572 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5573 // Do an implicit conversion to 'id'. 5574 QualType Ty = S.Context.getObjCIdType(); 5575 ImplicitConversionSequence ICS 5576 = TryImplicitConversion(S, From, Ty, 5577 // FIXME: Are these flags correct? 5578 /*SuppressUserConversions=*/false, 5579 /*AllowExplicit=*/true, 5580 /*InOverloadResolution=*/false, 5581 /*CStyle=*/false, 5582 /*AllowObjCWritebackConversion=*/false, 5583 /*AllowObjCConversionOnExplicit=*/true); 5584 5585 // Strip off any final conversions to 'id'. 5586 switch (ICS.getKind()) { 5587 case ImplicitConversionSequence::BadConversion: 5588 case ImplicitConversionSequence::AmbiguousConversion: 5589 case ImplicitConversionSequence::EllipsisConversion: 5590 break; 5591 5592 case ImplicitConversionSequence::UserDefinedConversion: 5593 dropPointerConversion(ICS.UserDefined.After); 5594 break; 5595 5596 case ImplicitConversionSequence::StandardConversion: 5597 dropPointerConversion(ICS.Standard); 5598 break; 5599 } 5600 5601 return ICS; 5602 } 5603 5604 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5605 /// conversion of the expression From to an Objective-C pointer type. 5606 /// Returns a valid but null ExprResult if no conversion sequence exists. 5607 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5608 if (checkPlaceholderForOverload(*this, From)) 5609 return ExprError(); 5610 5611 QualType Ty = Context.getObjCIdType(); 5612 ImplicitConversionSequence ICS = 5613 TryContextuallyConvertToObjCPointer(*this, From); 5614 if (!ICS.isBad()) 5615 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5616 return ExprResult(); 5617 } 5618 5619 /// Determine whether the provided type is an integral type, or an enumeration 5620 /// type of a permitted flavor. 5621 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5622 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5623 : T->isIntegralOrUnscopedEnumerationType(); 5624 } 5625 5626 static ExprResult 5627 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5628 Sema::ContextualImplicitConverter &Converter, 5629 QualType T, UnresolvedSetImpl &ViableConversions) { 5630 5631 if (Converter.Suppress) 5632 return ExprError(); 5633 5634 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5635 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5636 CXXConversionDecl *Conv = 5637 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5638 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5639 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5640 } 5641 return From; 5642 } 5643 5644 static bool 5645 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5646 Sema::ContextualImplicitConverter &Converter, 5647 QualType T, bool HadMultipleCandidates, 5648 UnresolvedSetImpl &ExplicitConversions) { 5649 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5650 DeclAccessPair Found = ExplicitConversions[0]; 5651 CXXConversionDecl *Conversion = 5652 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5653 5654 // The user probably meant to invoke the given explicit 5655 // conversion; use it. 5656 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5657 std::string TypeStr; 5658 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5659 5660 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5661 << FixItHint::CreateInsertion(From->getBeginLoc(), 5662 "static_cast<" + TypeStr + ">(") 5663 << FixItHint::CreateInsertion( 5664 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5665 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5666 5667 // If we aren't in a SFINAE context, build a call to the 5668 // explicit conversion function. 5669 if (SemaRef.isSFINAEContext()) 5670 return true; 5671 5672 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5673 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5674 HadMultipleCandidates); 5675 if (Result.isInvalid()) 5676 return true; 5677 // Record usage of conversion in an implicit cast. 5678 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5679 CK_UserDefinedConversion, Result.get(), 5680 nullptr, Result.get()->getValueKind()); 5681 } 5682 return false; 5683 } 5684 5685 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5686 Sema::ContextualImplicitConverter &Converter, 5687 QualType T, bool HadMultipleCandidates, 5688 DeclAccessPair &Found) { 5689 CXXConversionDecl *Conversion = 5690 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5691 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5692 5693 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5694 if (!Converter.SuppressConversion) { 5695 if (SemaRef.isSFINAEContext()) 5696 return true; 5697 5698 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5699 << From->getSourceRange(); 5700 } 5701 5702 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5703 HadMultipleCandidates); 5704 if (Result.isInvalid()) 5705 return true; 5706 // Record usage of conversion in an implicit cast. 5707 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5708 CK_UserDefinedConversion, Result.get(), 5709 nullptr, Result.get()->getValueKind()); 5710 return false; 5711 } 5712 5713 static ExprResult finishContextualImplicitConversion( 5714 Sema &SemaRef, SourceLocation Loc, Expr *From, 5715 Sema::ContextualImplicitConverter &Converter) { 5716 if (!Converter.match(From->getType()) && !Converter.Suppress) 5717 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5718 << From->getSourceRange(); 5719 5720 return SemaRef.DefaultLvalueConversion(From); 5721 } 5722 5723 static void 5724 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5725 UnresolvedSetImpl &ViableConversions, 5726 OverloadCandidateSet &CandidateSet) { 5727 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5728 DeclAccessPair FoundDecl = ViableConversions[I]; 5729 NamedDecl *D = FoundDecl.getDecl(); 5730 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5731 if (isa<UsingShadowDecl>(D)) 5732 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5733 5734 CXXConversionDecl *Conv; 5735 FunctionTemplateDecl *ConvTemplate; 5736 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5737 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5738 else 5739 Conv = cast<CXXConversionDecl>(D); 5740 5741 if (ConvTemplate) 5742 SemaRef.AddTemplateConversionCandidate( 5743 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5744 /*AllowObjCConversionOnExplicit=*/false); 5745 else 5746 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5747 ToType, CandidateSet, 5748 /*AllowObjCConversionOnExplicit=*/false); 5749 } 5750 } 5751 5752 /// Attempt to convert the given expression to a type which is accepted 5753 /// by the given converter. 5754 /// 5755 /// This routine will attempt to convert an expression of class type to a 5756 /// type accepted by the specified converter. In C++11 and before, the class 5757 /// must have a single non-explicit conversion function converting to a matching 5758 /// type. In C++1y, there can be multiple such conversion functions, but only 5759 /// one target type. 5760 /// 5761 /// \param Loc The source location of the construct that requires the 5762 /// conversion. 5763 /// 5764 /// \param From The expression we're converting from. 5765 /// 5766 /// \param Converter Used to control and diagnose the conversion process. 5767 /// 5768 /// \returns The expression, converted to an integral or enumeration type if 5769 /// successful. 5770 ExprResult Sema::PerformContextualImplicitConversion( 5771 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5772 // We can't perform any more checking for type-dependent expressions. 5773 if (From->isTypeDependent()) 5774 return From; 5775 5776 // Process placeholders immediately. 5777 if (From->hasPlaceholderType()) { 5778 ExprResult result = CheckPlaceholderExpr(From); 5779 if (result.isInvalid()) 5780 return result; 5781 From = result.get(); 5782 } 5783 5784 // If the expression already has a matching type, we're golden. 5785 QualType T = From->getType(); 5786 if (Converter.match(T)) 5787 return DefaultLvalueConversion(From); 5788 5789 // FIXME: Check for missing '()' if T is a function type? 5790 5791 // We can only perform contextual implicit conversions on objects of class 5792 // type. 5793 const RecordType *RecordTy = T->getAs<RecordType>(); 5794 if (!RecordTy || !getLangOpts().CPlusPlus) { 5795 if (!Converter.Suppress) 5796 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5797 return From; 5798 } 5799 5800 // We must have a complete class type. 5801 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5802 ContextualImplicitConverter &Converter; 5803 Expr *From; 5804 5805 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5806 : Converter(Converter), From(From) {} 5807 5808 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5809 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5810 } 5811 } IncompleteDiagnoser(Converter, From); 5812 5813 if (Converter.Suppress ? !isCompleteType(Loc, T) 5814 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5815 return From; 5816 5817 // Look for a conversion to an integral or enumeration type. 5818 UnresolvedSet<4> 5819 ViableConversions; // These are *potentially* viable in C++1y. 5820 UnresolvedSet<4> ExplicitConversions; 5821 const auto &Conversions = 5822 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5823 5824 bool HadMultipleCandidates = 5825 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5826 5827 // To check that there is only one target type, in C++1y: 5828 QualType ToType; 5829 bool HasUniqueTargetType = true; 5830 5831 // Collect explicit or viable (potentially in C++1y) conversions. 5832 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5833 NamedDecl *D = (*I)->getUnderlyingDecl(); 5834 CXXConversionDecl *Conversion; 5835 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5836 if (ConvTemplate) { 5837 if (getLangOpts().CPlusPlus14) 5838 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5839 else 5840 continue; // C++11 does not consider conversion operator templates(?). 5841 } else 5842 Conversion = cast<CXXConversionDecl>(D); 5843 5844 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5845 "Conversion operator templates are considered potentially " 5846 "viable in C++1y"); 5847 5848 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5849 if (Converter.match(CurToType) || ConvTemplate) { 5850 5851 if (Conversion->isExplicit()) { 5852 // FIXME: For C++1y, do we need this restriction? 5853 // cf. diagnoseNoViableConversion() 5854 if (!ConvTemplate) 5855 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5856 } else { 5857 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5858 if (ToType.isNull()) 5859 ToType = CurToType.getUnqualifiedType(); 5860 else if (HasUniqueTargetType && 5861 (CurToType.getUnqualifiedType() != ToType)) 5862 HasUniqueTargetType = false; 5863 } 5864 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5865 } 5866 } 5867 } 5868 5869 if (getLangOpts().CPlusPlus14) { 5870 // C++1y [conv]p6: 5871 // ... An expression e of class type E appearing in such a context 5872 // is said to be contextually implicitly converted to a specified 5873 // type T and is well-formed if and only if e can be implicitly 5874 // converted to a type T that is determined as follows: E is searched 5875 // for conversion functions whose return type is cv T or reference to 5876 // cv T such that T is allowed by the context. There shall be 5877 // exactly one such T. 5878 5879 // If no unique T is found: 5880 if (ToType.isNull()) { 5881 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5882 HadMultipleCandidates, 5883 ExplicitConversions)) 5884 return ExprError(); 5885 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5886 } 5887 5888 // If more than one unique Ts are found: 5889 if (!HasUniqueTargetType) 5890 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5891 ViableConversions); 5892 5893 // If one unique T is found: 5894 // First, build a candidate set from the previously recorded 5895 // potentially viable conversions. 5896 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5897 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5898 CandidateSet); 5899 5900 // Then, perform overload resolution over the candidate set. 5901 OverloadCandidateSet::iterator Best; 5902 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5903 case OR_Success: { 5904 // Apply this conversion. 5905 DeclAccessPair Found = 5906 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5907 if (recordConversion(*this, Loc, From, Converter, T, 5908 HadMultipleCandidates, Found)) 5909 return ExprError(); 5910 break; 5911 } 5912 case OR_Ambiguous: 5913 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5914 ViableConversions); 5915 case OR_No_Viable_Function: 5916 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5917 HadMultipleCandidates, 5918 ExplicitConversions)) 5919 return ExprError(); 5920 LLVM_FALLTHROUGH; 5921 case OR_Deleted: 5922 // We'll complain below about a non-integral condition type. 5923 break; 5924 } 5925 } else { 5926 switch (ViableConversions.size()) { 5927 case 0: { 5928 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5929 HadMultipleCandidates, 5930 ExplicitConversions)) 5931 return ExprError(); 5932 5933 // We'll complain below about a non-integral condition type. 5934 break; 5935 } 5936 case 1: { 5937 // Apply this conversion. 5938 DeclAccessPair Found = ViableConversions[0]; 5939 if (recordConversion(*this, Loc, From, Converter, T, 5940 HadMultipleCandidates, Found)) 5941 return ExprError(); 5942 break; 5943 } 5944 default: 5945 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5946 ViableConversions); 5947 } 5948 } 5949 5950 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5951 } 5952 5953 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5954 /// an acceptable non-member overloaded operator for a call whose 5955 /// arguments have types T1 (and, if non-empty, T2). This routine 5956 /// implements the check in C++ [over.match.oper]p3b2 concerning 5957 /// enumeration types. 5958 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5959 FunctionDecl *Fn, 5960 ArrayRef<Expr *> Args) { 5961 QualType T1 = Args[0]->getType(); 5962 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5963 5964 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5965 return true; 5966 5967 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5968 return true; 5969 5970 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5971 if (Proto->getNumParams() < 1) 5972 return false; 5973 5974 if (T1->isEnumeralType()) { 5975 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5976 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5977 return true; 5978 } 5979 5980 if (Proto->getNumParams() < 2) 5981 return false; 5982 5983 if (!T2.isNull() && T2->isEnumeralType()) { 5984 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5985 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5986 return true; 5987 } 5988 5989 return false; 5990 } 5991 5992 /// AddOverloadCandidate - Adds the given function to the set of 5993 /// candidate functions, using the given function call arguments. If 5994 /// @p SuppressUserConversions, then don't allow user-defined 5995 /// conversions via constructors or conversion operators. 5996 /// 5997 /// \param PartialOverloading true if we are performing "partial" overloading 5998 /// based on an incomplete set of function arguments. This feature is used by 5999 /// code completion. 6000 void Sema::AddOverloadCandidate(FunctionDecl *Function, 6001 DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6002 OverloadCandidateSet &CandidateSet, 6003 bool SuppressUserConversions, 6004 bool PartialOverloading, bool AllowExplicit, 6005 ADLCallKind IsADLCandidate, 6006 ConversionSequenceList EarlyConversions) { 6007 const FunctionProtoType *Proto 6008 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6009 assert(Proto && "Functions without a prototype cannot be overloaded"); 6010 assert(!Function->getDescribedFunctionTemplate() && 6011 "Use AddTemplateOverloadCandidate for function templates"); 6012 6013 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6014 if (!isa<CXXConstructorDecl>(Method)) { 6015 // If we get here, it's because we're calling a member function 6016 // that is named without a member access expression (e.g., 6017 // "this->f") that was either written explicitly or created 6018 // implicitly. This can happen with a qualified call to a member 6019 // function, e.g., X::f(). We use an empty type for the implied 6020 // object argument (C++ [over.call.func]p3), and the acting context 6021 // is irrelevant. 6022 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6023 Expr::Classification::makeSimpleLValue(), Args, 6024 CandidateSet, SuppressUserConversions, 6025 PartialOverloading, EarlyConversions); 6026 return; 6027 } 6028 // We treat a constructor like a non-member function, since its object 6029 // argument doesn't participate in overload resolution. 6030 } 6031 6032 if (!CandidateSet.isNewCandidate(Function)) 6033 return; 6034 6035 // C++ [over.match.oper]p3: 6036 // if no operand has a class type, only those non-member functions in the 6037 // lookup set that have a first parameter of type T1 or "reference to 6038 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6039 // is a right operand) a second parameter of type T2 or "reference to 6040 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6041 // candidate functions. 6042 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6043 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6044 return; 6045 6046 // C++11 [class.copy]p11: [DR1402] 6047 // A defaulted move constructor that is defined as deleted is ignored by 6048 // overload resolution. 6049 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6050 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6051 Constructor->isMoveConstructor()) 6052 return; 6053 6054 // Overload resolution is always an unevaluated context. 6055 EnterExpressionEvaluationContext Unevaluated( 6056 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6057 6058 // Add this candidate 6059 OverloadCandidate &Candidate = 6060 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6061 Candidate.FoundDecl = FoundDecl; 6062 Candidate.Function = Function; 6063 Candidate.Viable = true; 6064 Candidate.IsSurrogate = false; 6065 Candidate.IsADLCandidate = IsADLCandidate; 6066 Candidate.IgnoreObjectArgument = false; 6067 Candidate.ExplicitCallArguments = Args.size(); 6068 6069 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6070 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6071 Candidate.Viable = false; 6072 Candidate.FailureKind = ovl_non_default_multiversion_function; 6073 return; 6074 } 6075 6076 if (Constructor) { 6077 // C++ [class.copy]p3: 6078 // A member function template is never instantiated to perform the copy 6079 // of a class object to an object of its class type. 6080 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6081 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6082 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6083 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6084 ClassType))) { 6085 Candidate.Viable = false; 6086 Candidate.FailureKind = ovl_fail_illegal_constructor; 6087 return; 6088 } 6089 6090 // C++ [over.match.funcs]p8: (proposed DR resolution) 6091 // A constructor inherited from class type C that has a first parameter 6092 // of type "reference to P" (including such a constructor instantiated 6093 // from a template) is excluded from the set of candidate functions when 6094 // constructing an object of type cv D if the argument list has exactly 6095 // one argument and D is reference-related to P and P is reference-related 6096 // to C. 6097 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6098 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6099 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6100 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6101 QualType C = Context.getRecordType(Constructor->getParent()); 6102 QualType D = Context.getRecordType(Shadow->getParent()); 6103 SourceLocation Loc = Args.front()->getExprLoc(); 6104 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6105 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6106 Candidate.Viable = false; 6107 Candidate.FailureKind = ovl_fail_inhctor_slice; 6108 return; 6109 } 6110 } 6111 } 6112 6113 unsigned NumParams = Proto->getNumParams(); 6114 6115 // (C++ 13.3.2p2): A candidate function having fewer than m 6116 // parameters is viable only if it has an ellipsis in its parameter 6117 // list (8.3.5). 6118 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6119 !Proto->isVariadic()) { 6120 Candidate.Viable = false; 6121 Candidate.FailureKind = ovl_fail_too_many_arguments; 6122 return; 6123 } 6124 6125 // (C++ 13.3.2p2): A candidate function having more than m parameters 6126 // is viable only if the (m+1)st parameter has a default argument 6127 // (8.3.6). For the purposes of overload resolution, the 6128 // parameter list is truncated on the right, so that there are 6129 // exactly m parameters. 6130 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6131 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6132 // Not enough arguments. 6133 Candidate.Viable = false; 6134 Candidate.FailureKind = ovl_fail_too_few_arguments; 6135 return; 6136 } 6137 6138 // (CUDA B.1): Check for invalid calls between targets. 6139 if (getLangOpts().CUDA) 6140 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6141 // Skip the check for callers that are implicit members, because in this 6142 // case we may not yet know what the member's target is; the target is 6143 // inferred for the member automatically, based on the bases and fields of 6144 // the class. 6145 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6146 Candidate.Viable = false; 6147 Candidate.FailureKind = ovl_fail_bad_target; 6148 return; 6149 } 6150 6151 // Determine the implicit conversion sequences for each of the 6152 // arguments. 6153 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6154 if (Candidate.Conversions[ArgIdx].isInitialized()) { 6155 // We already formed a conversion sequence for this parameter during 6156 // template argument deduction. 6157 } else if (ArgIdx < NumParams) { 6158 // (C++ 13.3.2p3): for F to be a viable function, there shall 6159 // exist for each argument an implicit conversion sequence 6160 // (13.3.3.1) that converts that argument to the corresponding 6161 // parameter of F. 6162 QualType ParamType = Proto->getParamType(ArgIdx); 6163 Candidate.Conversions[ArgIdx] 6164 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6165 SuppressUserConversions, 6166 /*InOverloadResolution=*/true, 6167 /*AllowObjCWritebackConversion=*/ 6168 getLangOpts().ObjCAutoRefCount, 6169 AllowExplicit); 6170 if (Candidate.Conversions[ArgIdx].isBad()) { 6171 Candidate.Viable = false; 6172 Candidate.FailureKind = ovl_fail_bad_conversion; 6173 return; 6174 } 6175 } else { 6176 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6177 // argument for which there is no corresponding parameter is 6178 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6179 Candidate.Conversions[ArgIdx].setEllipsis(); 6180 } 6181 } 6182 6183 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6184 Candidate.Viable = false; 6185 Candidate.FailureKind = ovl_fail_enable_if; 6186 Candidate.DeductionFailure.Data = FailedAttr; 6187 return; 6188 } 6189 6190 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6191 Candidate.Viable = false; 6192 Candidate.FailureKind = ovl_fail_ext_disabled; 6193 return; 6194 } 6195 } 6196 6197 ObjCMethodDecl * 6198 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6199 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6200 if (Methods.size() <= 1) 6201 return nullptr; 6202 6203 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6204 bool Match = true; 6205 ObjCMethodDecl *Method = Methods[b]; 6206 unsigned NumNamedArgs = Sel.getNumArgs(); 6207 // Method might have more arguments than selector indicates. This is due 6208 // to addition of c-style arguments in method. 6209 if (Method->param_size() > NumNamedArgs) 6210 NumNamedArgs = Method->param_size(); 6211 if (Args.size() < NumNamedArgs) 6212 continue; 6213 6214 for (unsigned i = 0; i < NumNamedArgs; i++) { 6215 // We can't do any type-checking on a type-dependent argument. 6216 if (Args[i]->isTypeDependent()) { 6217 Match = false; 6218 break; 6219 } 6220 6221 ParmVarDecl *param = Method->parameters()[i]; 6222 Expr *argExpr = Args[i]; 6223 assert(argExpr && "SelectBestMethod(): missing expression"); 6224 6225 // Strip the unbridged-cast placeholder expression off unless it's 6226 // a consumed argument. 6227 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6228 !param->hasAttr<CFConsumedAttr>()) 6229 argExpr = stripARCUnbridgedCast(argExpr); 6230 6231 // If the parameter is __unknown_anytype, move on to the next method. 6232 if (param->getType() == Context.UnknownAnyTy) { 6233 Match = false; 6234 break; 6235 } 6236 6237 ImplicitConversionSequence ConversionState 6238 = TryCopyInitialization(*this, argExpr, param->getType(), 6239 /*SuppressUserConversions*/false, 6240 /*InOverloadResolution=*/true, 6241 /*AllowObjCWritebackConversion=*/ 6242 getLangOpts().ObjCAutoRefCount, 6243 /*AllowExplicit*/false); 6244 // This function looks for a reasonably-exact match, so we consider 6245 // incompatible pointer conversions to be a failure here. 6246 if (ConversionState.isBad() || 6247 (ConversionState.isStandard() && 6248 ConversionState.Standard.Second == 6249 ICK_Incompatible_Pointer_Conversion)) { 6250 Match = false; 6251 break; 6252 } 6253 } 6254 // Promote additional arguments to variadic methods. 6255 if (Match && Method->isVariadic()) { 6256 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6257 if (Args[i]->isTypeDependent()) { 6258 Match = false; 6259 break; 6260 } 6261 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6262 nullptr); 6263 if (Arg.isInvalid()) { 6264 Match = false; 6265 break; 6266 } 6267 } 6268 } else { 6269 // Check for extra arguments to non-variadic methods. 6270 if (Args.size() != NumNamedArgs) 6271 Match = false; 6272 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6273 // Special case when selectors have no argument. In this case, select 6274 // one with the most general result type of 'id'. 6275 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6276 QualType ReturnT = Methods[b]->getReturnType(); 6277 if (ReturnT->isObjCIdType()) 6278 return Methods[b]; 6279 } 6280 } 6281 } 6282 6283 if (Match) 6284 return Method; 6285 } 6286 return nullptr; 6287 } 6288 6289 static bool 6290 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6291 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6292 bool MissingImplicitThis, Expr *&ConvertedThis, 6293 SmallVectorImpl<Expr *> &ConvertedArgs) { 6294 if (ThisArg) { 6295 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6296 assert(!isa<CXXConstructorDecl>(Method) && 6297 "Shouldn't have `this` for ctors!"); 6298 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6299 ExprResult R = S.PerformObjectArgumentInitialization( 6300 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6301 if (R.isInvalid()) 6302 return false; 6303 ConvertedThis = R.get(); 6304 } else { 6305 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6306 (void)MD; 6307 assert((MissingImplicitThis || MD->isStatic() || 6308 isa<CXXConstructorDecl>(MD)) && 6309 "Expected `this` for non-ctor instance methods"); 6310 } 6311 ConvertedThis = nullptr; 6312 } 6313 6314 // Ignore any variadic arguments. Converting them is pointless, since the 6315 // user can't refer to them in the function condition. 6316 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6317 6318 // Convert the arguments. 6319 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6320 ExprResult R; 6321 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6322 S.Context, Function->getParamDecl(I)), 6323 SourceLocation(), Args[I]); 6324 6325 if (R.isInvalid()) 6326 return false; 6327 6328 ConvertedArgs.push_back(R.get()); 6329 } 6330 6331 if (Trap.hasErrorOccurred()) 6332 return false; 6333 6334 // Push default arguments if needed. 6335 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6336 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6337 ParmVarDecl *P = Function->getParamDecl(i); 6338 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6339 ? P->getUninstantiatedDefaultArg() 6340 : P->getDefaultArg(); 6341 // This can only happen in code completion, i.e. when PartialOverloading 6342 // is true. 6343 if (!DefArg) 6344 return false; 6345 ExprResult R = 6346 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6347 S.Context, Function->getParamDecl(i)), 6348 SourceLocation(), DefArg); 6349 if (R.isInvalid()) 6350 return false; 6351 ConvertedArgs.push_back(R.get()); 6352 } 6353 6354 if (Trap.hasErrorOccurred()) 6355 return false; 6356 } 6357 return true; 6358 } 6359 6360 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6361 bool MissingImplicitThis) { 6362 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6363 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6364 return nullptr; 6365 6366 SFINAETrap Trap(*this); 6367 SmallVector<Expr *, 16> ConvertedArgs; 6368 // FIXME: We should look into making enable_if late-parsed. 6369 Expr *DiscardedThis; 6370 if (!convertArgsForAvailabilityChecks( 6371 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6372 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6373 return *EnableIfAttrs.begin(); 6374 6375 for (auto *EIA : EnableIfAttrs) { 6376 APValue Result; 6377 // FIXME: This doesn't consider value-dependent cases, because doing so is 6378 // very difficult. Ideally, we should handle them more gracefully. 6379 if (!EIA->getCond()->EvaluateWithSubstitution( 6380 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6381 return EIA; 6382 6383 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6384 return EIA; 6385 } 6386 return nullptr; 6387 } 6388 6389 template <typename CheckFn> 6390 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6391 bool ArgDependent, SourceLocation Loc, 6392 CheckFn &&IsSuccessful) { 6393 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6394 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6395 if (ArgDependent == DIA->getArgDependent()) 6396 Attrs.push_back(DIA); 6397 } 6398 6399 // Common case: No diagnose_if attributes, so we can quit early. 6400 if (Attrs.empty()) 6401 return false; 6402 6403 auto WarningBegin = std::stable_partition( 6404 Attrs.begin(), Attrs.end(), 6405 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6406 6407 // Note that diagnose_if attributes are late-parsed, so they appear in the 6408 // correct order (unlike enable_if attributes). 6409 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6410 IsSuccessful); 6411 if (ErrAttr != WarningBegin) { 6412 const DiagnoseIfAttr *DIA = *ErrAttr; 6413 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6414 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6415 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6416 return true; 6417 } 6418 6419 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6420 if (IsSuccessful(DIA)) { 6421 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6422 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6423 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6424 } 6425 6426 return false; 6427 } 6428 6429 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6430 const Expr *ThisArg, 6431 ArrayRef<const Expr *> Args, 6432 SourceLocation Loc) { 6433 return diagnoseDiagnoseIfAttrsWith( 6434 *this, Function, /*ArgDependent=*/true, Loc, 6435 [&](const DiagnoseIfAttr *DIA) { 6436 APValue Result; 6437 // It's sane to use the same Args for any redecl of this function, since 6438 // EvaluateWithSubstitution only cares about the position of each 6439 // argument in the arg list, not the ParmVarDecl* it maps to. 6440 if (!DIA->getCond()->EvaluateWithSubstitution( 6441 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6442 return false; 6443 return Result.isInt() && Result.getInt().getBoolValue(); 6444 }); 6445 } 6446 6447 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6448 SourceLocation Loc) { 6449 return diagnoseDiagnoseIfAttrsWith( 6450 *this, ND, /*ArgDependent=*/false, Loc, 6451 [&](const DiagnoseIfAttr *DIA) { 6452 bool Result; 6453 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6454 Result; 6455 }); 6456 } 6457 6458 /// Add all of the function declarations in the given function set to 6459 /// the overload candidate set. 6460 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6461 ArrayRef<Expr *> Args, 6462 OverloadCandidateSet &CandidateSet, 6463 TemplateArgumentListInfo *ExplicitTemplateArgs, 6464 bool SuppressUserConversions, 6465 bool PartialOverloading, 6466 bool FirstArgumentIsBase) { 6467 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6468 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6469 ArrayRef<Expr *> FunctionArgs = Args; 6470 6471 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6472 FunctionDecl *FD = 6473 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6474 6475 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6476 QualType ObjectType; 6477 Expr::Classification ObjectClassification; 6478 if (Args.size() > 0) { 6479 if (Expr *E = Args[0]) { 6480 // Use the explicit base to restrict the lookup: 6481 ObjectType = E->getType(); 6482 // Pointers in the object arguments are implicitly dereferenced, so we 6483 // always classify them as l-values. 6484 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6485 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6486 else 6487 ObjectClassification = E->Classify(Context); 6488 } // .. else there is an implicit base. 6489 FunctionArgs = Args.slice(1); 6490 } 6491 if (FunTmpl) { 6492 AddMethodTemplateCandidate( 6493 FunTmpl, F.getPair(), 6494 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6495 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6496 FunctionArgs, CandidateSet, SuppressUserConversions, 6497 PartialOverloading); 6498 } else { 6499 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6500 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6501 ObjectClassification, FunctionArgs, CandidateSet, 6502 SuppressUserConversions, PartialOverloading); 6503 } 6504 } else { 6505 // This branch handles both standalone functions and static methods. 6506 6507 // Slice the first argument (which is the base) when we access 6508 // static method as non-static. 6509 if (Args.size() > 0 && 6510 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6511 !isa<CXXConstructorDecl>(FD)))) { 6512 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6513 FunctionArgs = Args.slice(1); 6514 } 6515 if (FunTmpl) { 6516 AddTemplateOverloadCandidate( 6517 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs, 6518 CandidateSet, SuppressUserConversions, PartialOverloading); 6519 } else { 6520 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6521 SuppressUserConversions, PartialOverloading); 6522 } 6523 } 6524 } 6525 } 6526 6527 /// AddMethodCandidate - Adds a named decl (which is some kind of 6528 /// method) as a method candidate to the given overload set. 6529 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6530 QualType ObjectType, 6531 Expr::Classification ObjectClassification, 6532 ArrayRef<Expr *> Args, 6533 OverloadCandidateSet& CandidateSet, 6534 bool SuppressUserConversions) { 6535 NamedDecl *Decl = FoundDecl.getDecl(); 6536 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6537 6538 if (isa<UsingShadowDecl>(Decl)) 6539 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6540 6541 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6542 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6543 "Expected a member function template"); 6544 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6545 /*ExplicitArgs*/ nullptr, ObjectType, 6546 ObjectClassification, Args, CandidateSet, 6547 SuppressUserConversions); 6548 } else { 6549 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6550 ObjectType, ObjectClassification, Args, CandidateSet, 6551 SuppressUserConversions); 6552 } 6553 } 6554 6555 /// AddMethodCandidate - Adds the given C++ member function to the set 6556 /// of candidate functions, using the given function call arguments 6557 /// and the object argument (@c Object). For example, in a call 6558 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6559 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6560 /// allow user-defined conversions via constructors or conversion 6561 /// operators. 6562 void 6563 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6564 CXXRecordDecl *ActingContext, QualType ObjectType, 6565 Expr::Classification ObjectClassification, 6566 ArrayRef<Expr *> Args, 6567 OverloadCandidateSet &CandidateSet, 6568 bool SuppressUserConversions, 6569 bool PartialOverloading, 6570 ConversionSequenceList EarlyConversions) { 6571 const FunctionProtoType *Proto 6572 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6573 assert(Proto && "Methods without a prototype cannot be overloaded"); 6574 assert(!isa<CXXConstructorDecl>(Method) && 6575 "Use AddOverloadCandidate for constructors"); 6576 6577 if (!CandidateSet.isNewCandidate(Method)) 6578 return; 6579 6580 // C++11 [class.copy]p23: [DR1402] 6581 // A defaulted move assignment operator that is defined as deleted is 6582 // ignored by overload resolution. 6583 if (Method->isDefaulted() && Method->isDeleted() && 6584 Method->isMoveAssignmentOperator()) 6585 return; 6586 6587 // Overload resolution is always an unevaluated context. 6588 EnterExpressionEvaluationContext Unevaluated( 6589 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6590 6591 // Add this candidate 6592 OverloadCandidate &Candidate = 6593 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6594 Candidate.FoundDecl = FoundDecl; 6595 Candidate.Function = Method; 6596 Candidate.IsSurrogate = false; 6597 Candidate.IgnoreObjectArgument = false; 6598 Candidate.ExplicitCallArguments = Args.size(); 6599 6600 unsigned NumParams = Proto->getNumParams(); 6601 6602 // (C++ 13.3.2p2): A candidate function having fewer than m 6603 // parameters is viable only if it has an ellipsis in its parameter 6604 // list (8.3.5). 6605 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6606 !Proto->isVariadic()) { 6607 Candidate.Viable = false; 6608 Candidate.FailureKind = ovl_fail_too_many_arguments; 6609 return; 6610 } 6611 6612 // (C++ 13.3.2p2): A candidate function having more than m parameters 6613 // is viable only if the (m+1)st parameter has a default argument 6614 // (8.3.6). For the purposes of overload resolution, the 6615 // parameter list is truncated on the right, so that there are 6616 // exactly m parameters. 6617 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6618 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6619 // Not enough arguments. 6620 Candidate.Viable = false; 6621 Candidate.FailureKind = ovl_fail_too_few_arguments; 6622 return; 6623 } 6624 6625 Candidate.Viable = true; 6626 6627 if (Method->isStatic() || ObjectType.isNull()) 6628 // The implicit object argument is ignored. 6629 Candidate.IgnoreObjectArgument = true; 6630 else { 6631 // Determine the implicit conversion sequence for the object 6632 // parameter. 6633 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6634 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6635 Method, ActingContext); 6636 if (Candidate.Conversions[0].isBad()) { 6637 Candidate.Viable = false; 6638 Candidate.FailureKind = ovl_fail_bad_conversion; 6639 return; 6640 } 6641 } 6642 6643 // (CUDA B.1): Check for invalid calls between targets. 6644 if (getLangOpts().CUDA) 6645 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6646 if (!IsAllowedCUDACall(Caller, Method)) { 6647 Candidate.Viable = false; 6648 Candidate.FailureKind = ovl_fail_bad_target; 6649 return; 6650 } 6651 6652 // Determine the implicit conversion sequences for each of the 6653 // arguments. 6654 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6655 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6656 // We already formed a conversion sequence for this parameter during 6657 // template argument deduction. 6658 } else if (ArgIdx < NumParams) { 6659 // (C++ 13.3.2p3): for F to be a viable function, there shall 6660 // exist for each argument an implicit conversion sequence 6661 // (13.3.3.1) that converts that argument to the corresponding 6662 // parameter of F. 6663 QualType ParamType = Proto->getParamType(ArgIdx); 6664 Candidate.Conversions[ArgIdx + 1] 6665 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6666 SuppressUserConversions, 6667 /*InOverloadResolution=*/true, 6668 /*AllowObjCWritebackConversion=*/ 6669 getLangOpts().ObjCAutoRefCount); 6670 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6671 Candidate.Viable = false; 6672 Candidate.FailureKind = ovl_fail_bad_conversion; 6673 return; 6674 } 6675 } else { 6676 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6677 // argument for which there is no corresponding parameter is 6678 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6679 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6680 } 6681 } 6682 6683 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6684 Candidate.Viable = false; 6685 Candidate.FailureKind = ovl_fail_enable_if; 6686 Candidate.DeductionFailure.Data = FailedAttr; 6687 return; 6688 } 6689 6690 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6691 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6692 Candidate.Viable = false; 6693 Candidate.FailureKind = ovl_non_default_multiversion_function; 6694 } 6695 } 6696 6697 /// Add a C++ member function template as a candidate to the candidate 6698 /// set, using template argument deduction to produce an appropriate member 6699 /// function template specialization. 6700 void 6701 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6702 DeclAccessPair FoundDecl, 6703 CXXRecordDecl *ActingContext, 6704 TemplateArgumentListInfo *ExplicitTemplateArgs, 6705 QualType ObjectType, 6706 Expr::Classification ObjectClassification, 6707 ArrayRef<Expr *> Args, 6708 OverloadCandidateSet& CandidateSet, 6709 bool SuppressUserConversions, 6710 bool PartialOverloading) { 6711 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6712 return; 6713 6714 // C++ [over.match.funcs]p7: 6715 // In each case where a candidate is a function template, candidate 6716 // function template specializations are generated using template argument 6717 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6718 // candidate functions in the usual way.113) A given name can refer to one 6719 // or more function templates and also to a set of overloaded non-template 6720 // functions. In such a case, the candidate functions generated from each 6721 // function template are combined with the set of non-template candidate 6722 // functions. 6723 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6724 FunctionDecl *Specialization = nullptr; 6725 ConversionSequenceList Conversions; 6726 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6727 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6728 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6729 return CheckNonDependentConversions( 6730 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6731 SuppressUserConversions, ActingContext, ObjectType, 6732 ObjectClassification); 6733 })) { 6734 OverloadCandidate &Candidate = 6735 CandidateSet.addCandidate(Conversions.size(), Conversions); 6736 Candidate.FoundDecl = FoundDecl; 6737 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6738 Candidate.Viable = false; 6739 Candidate.IsSurrogate = false; 6740 Candidate.IgnoreObjectArgument = 6741 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6742 ObjectType.isNull(); 6743 Candidate.ExplicitCallArguments = Args.size(); 6744 if (Result == TDK_NonDependentConversionFailure) 6745 Candidate.FailureKind = ovl_fail_bad_conversion; 6746 else { 6747 Candidate.FailureKind = ovl_fail_bad_deduction; 6748 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6749 Info); 6750 } 6751 return; 6752 } 6753 6754 // Add the function template specialization produced by template argument 6755 // deduction as a candidate. 6756 assert(Specialization && "Missing member function template specialization?"); 6757 assert(isa<CXXMethodDecl>(Specialization) && 6758 "Specialization is not a member function?"); 6759 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6760 ActingContext, ObjectType, ObjectClassification, Args, 6761 CandidateSet, SuppressUserConversions, PartialOverloading, 6762 Conversions); 6763 } 6764 6765 /// Add a C++ function template specialization as a candidate 6766 /// in the candidate set, using template argument deduction to produce 6767 /// an appropriate function template specialization. 6768 void Sema::AddTemplateOverloadCandidate( 6769 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6770 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6771 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6772 bool PartialOverloading, ADLCallKind IsADLCandidate) { 6773 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6774 return; 6775 6776 // C++ [over.match.funcs]p7: 6777 // In each case where a candidate is a function template, candidate 6778 // function template specializations are generated using template argument 6779 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6780 // candidate functions in the usual way.113) A given name can refer to one 6781 // or more function templates and also to a set of overloaded non-template 6782 // functions. In such a case, the candidate functions generated from each 6783 // function template are combined with the set of non-template candidate 6784 // functions. 6785 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6786 FunctionDecl *Specialization = nullptr; 6787 ConversionSequenceList Conversions; 6788 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6789 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6790 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6791 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6792 Args, CandidateSet, Conversions, 6793 SuppressUserConversions); 6794 })) { 6795 OverloadCandidate &Candidate = 6796 CandidateSet.addCandidate(Conversions.size(), Conversions); 6797 Candidate.FoundDecl = FoundDecl; 6798 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6799 Candidate.Viable = false; 6800 Candidate.IsSurrogate = false; 6801 Candidate.IsADLCandidate = IsADLCandidate; 6802 // Ignore the object argument if there is one, since we don't have an object 6803 // type. 6804 Candidate.IgnoreObjectArgument = 6805 isa<CXXMethodDecl>(Candidate.Function) && 6806 !isa<CXXConstructorDecl>(Candidate.Function); 6807 Candidate.ExplicitCallArguments = Args.size(); 6808 if (Result == TDK_NonDependentConversionFailure) 6809 Candidate.FailureKind = ovl_fail_bad_conversion; 6810 else { 6811 Candidate.FailureKind = ovl_fail_bad_deduction; 6812 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6813 Info); 6814 } 6815 return; 6816 } 6817 6818 // Add the function template specialization produced by template argument 6819 // deduction as a candidate. 6820 assert(Specialization && "Missing function template specialization?"); 6821 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6822 SuppressUserConversions, PartialOverloading, 6823 /*AllowExplicit*/ false, IsADLCandidate, Conversions); 6824 } 6825 6826 /// Check that implicit conversion sequences can be formed for each argument 6827 /// whose corresponding parameter has a non-dependent type, per DR1391's 6828 /// [temp.deduct.call]p10. 6829 bool Sema::CheckNonDependentConversions( 6830 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6831 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6832 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6833 CXXRecordDecl *ActingContext, QualType ObjectType, 6834 Expr::Classification ObjectClassification) { 6835 // FIXME: The cases in which we allow explicit conversions for constructor 6836 // arguments never consider calling a constructor template. It's not clear 6837 // that is correct. 6838 const bool AllowExplicit = false; 6839 6840 auto *FD = FunctionTemplate->getTemplatedDecl(); 6841 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6842 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6843 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6844 6845 Conversions = 6846 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6847 6848 // Overload resolution is always an unevaluated context. 6849 EnterExpressionEvaluationContext Unevaluated( 6850 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6851 6852 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6853 // require that, but this check should never result in a hard error, and 6854 // overload resolution is permitted to sidestep instantiations. 6855 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6856 !ObjectType.isNull()) { 6857 Conversions[0] = TryObjectArgumentInitialization( 6858 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6859 Method, ActingContext); 6860 if (Conversions[0].isBad()) 6861 return true; 6862 } 6863 6864 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6865 ++I) { 6866 QualType ParamType = ParamTypes[I]; 6867 if (!ParamType->isDependentType()) { 6868 Conversions[ThisConversions + I] 6869 = TryCopyInitialization(*this, Args[I], ParamType, 6870 SuppressUserConversions, 6871 /*InOverloadResolution=*/true, 6872 /*AllowObjCWritebackConversion=*/ 6873 getLangOpts().ObjCAutoRefCount, 6874 AllowExplicit); 6875 if (Conversions[ThisConversions + I].isBad()) 6876 return true; 6877 } 6878 } 6879 6880 return false; 6881 } 6882 6883 /// Determine whether this is an allowable conversion from the result 6884 /// of an explicit conversion operator to the expected type, per C++ 6885 /// [over.match.conv]p1 and [over.match.ref]p1. 6886 /// 6887 /// \param ConvType The return type of the conversion function. 6888 /// 6889 /// \param ToType The type we are converting to. 6890 /// 6891 /// \param AllowObjCPointerConversion Allow a conversion from one 6892 /// Objective-C pointer to another. 6893 /// 6894 /// \returns true if the conversion is allowable, false otherwise. 6895 static bool isAllowableExplicitConversion(Sema &S, 6896 QualType ConvType, QualType ToType, 6897 bool AllowObjCPointerConversion) { 6898 QualType ToNonRefType = ToType.getNonReferenceType(); 6899 6900 // Easy case: the types are the same. 6901 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6902 return true; 6903 6904 // Allow qualification conversions. 6905 bool ObjCLifetimeConversion; 6906 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6907 ObjCLifetimeConversion)) 6908 return true; 6909 6910 // If we're not allowed to consider Objective-C pointer conversions, 6911 // we're done. 6912 if (!AllowObjCPointerConversion) 6913 return false; 6914 6915 // Is this an Objective-C pointer conversion? 6916 bool IncompatibleObjC = false; 6917 QualType ConvertedType; 6918 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6919 IncompatibleObjC); 6920 } 6921 6922 /// AddConversionCandidate - Add a C++ conversion function as a 6923 /// candidate in the candidate set (C++ [over.match.conv], 6924 /// C++ [over.match.copy]). From is the expression we're converting from, 6925 /// and ToType is the type that we're eventually trying to convert to 6926 /// (which may or may not be the same type as the type that the 6927 /// conversion function produces). 6928 void 6929 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6930 DeclAccessPair FoundDecl, 6931 CXXRecordDecl *ActingContext, 6932 Expr *From, QualType ToType, 6933 OverloadCandidateSet& CandidateSet, 6934 bool AllowObjCConversionOnExplicit, 6935 bool AllowResultConversion) { 6936 assert(!Conversion->getDescribedFunctionTemplate() && 6937 "Conversion function templates use AddTemplateConversionCandidate"); 6938 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6939 if (!CandidateSet.isNewCandidate(Conversion)) 6940 return; 6941 6942 // If the conversion function has an undeduced return type, trigger its 6943 // deduction now. 6944 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6945 if (DeduceReturnType(Conversion, From->getExprLoc())) 6946 return; 6947 ConvType = Conversion->getConversionType().getNonReferenceType(); 6948 } 6949 6950 // If we don't allow any conversion of the result type, ignore conversion 6951 // functions that don't convert to exactly (possibly cv-qualified) T. 6952 if (!AllowResultConversion && 6953 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 6954 return; 6955 6956 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6957 // operator is only a candidate if its return type is the target type or 6958 // can be converted to the target type with a qualification conversion. 6959 if (Conversion->isExplicit() && 6960 !isAllowableExplicitConversion(*this, ConvType, ToType, 6961 AllowObjCConversionOnExplicit)) 6962 return; 6963 6964 // Overload resolution is always an unevaluated context. 6965 EnterExpressionEvaluationContext Unevaluated( 6966 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6967 6968 // Add this candidate 6969 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6970 Candidate.FoundDecl = FoundDecl; 6971 Candidate.Function = Conversion; 6972 Candidate.IsSurrogate = false; 6973 Candidate.IgnoreObjectArgument = false; 6974 Candidate.FinalConversion.setAsIdentityConversion(); 6975 Candidate.FinalConversion.setFromType(ConvType); 6976 Candidate.FinalConversion.setAllToTypes(ToType); 6977 Candidate.Viable = true; 6978 Candidate.ExplicitCallArguments = 1; 6979 6980 // C++ [over.match.funcs]p4: 6981 // For conversion functions, the function is considered to be a member of 6982 // the class of the implicit implied object argument for the purpose of 6983 // defining the type of the implicit object parameter. 6984 // 6985 // Determine the implicit conversion sequence for the implicit 6986 // object parameter. 6987 QualType ImplicitParamType = From->getType(); 6988 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6989 ImplicitParamType = FromPtrType->getPointeeType(); 6990 CXXRecordDecl *ConversionContext 6991 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6992 6993 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6994 *this, CandidateSet.getLocation(), From->getType(), 6995 From->Classify(Context), Conversion, ConversionContext); 6996 6997 if (Candidate.Conversions[0].isBad()) { 6998 Candidate.Viable = false; 6999 Candidate.FailureKind = ovl_fail_bad_conversion; 7000 return; 7001 } 7002 7003 // We won't go through a user-defined type conversion function to convert a 7004 // derived to base as such conversions are given Conversion Rank. They only 7005 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7006 QualType FromCanon 7007 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7008 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7009 if (FromCanon == ToCanon || 7010 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7011 Candidate.Viable = false; 7012 Candidate.FailureKind = ovl_fail_trivial_conversion; 7013 return; 7014 } 7015 7016 // To determine what the conversion from the result of calling the 7017 // conversion function to the type we're eventually trying to 7018 // convert to (ToType), we need to synthesize a call to the 7019 // conversion function and attempt copy initialization from it. This 7020 // makes sure that we get the right semantics with respect to 7021 // lvalues/rvalues and the type. Fortunately, we can allocate this 7022 // call on the stack and we don't need its arguments to be 7023 // well-formed. 7024 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7025 VK_LValue, From->getBeginLoc()); 7026 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7027 Context.getPointerType(Conversion->getType()), 7028 CK_FunctionToPointerDecay, 7029 &ConversionRef, VK_RValue); 7030 7031 QualType ConversionType = Conversion->getConversionType(); 7032 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7033 Candidate.Viable = false; 7034 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7035 return; 7036 } 7037 7038 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7039 7040 // Note that it is safe to allocate CallExpr on the stack here because 7041 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7042 // allocator). 7043 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7044 7045 llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)> 7046 Buffer; 7047 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7048 Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7049 7050 ImplicitConversionSequence ICS = 7051 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7052 /*SuppressUserConversions=*/true, 7053 /*InOverloadResolution=*/false, 7054 /*AllowObjCWritebackConversion=*/false); 7055 7056 switch (ICS.getKind()) { 7057 case ImplicitConversionSequence::StandardConversion: 7058 Candidate.FinalConversion = ICS.Standard; 7059 7060 // C++ [over.ics.user]p3: 7061 // If the user-defined conversion is specified by a specialization of a 7062 // conversion function template, the second standard conversion sequence 7063 // shall have exact match rank. 7064 if (Conversion->getPrimaryTemplate() && 7065 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7066 Candidate.Viable = false; 7067 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7068 return; 7069 } 7070 7071 // C++0x [dcl.init.ref]p5: 7072 // In the second case, if the reference is an rvalue reference and 7073 // the second standard conversion sequence of the user-defined 7074 // conversion sequence includes an lvalue-to-rvalue conversion, the 7075 // program is ill-formed. 7076 if (ToType->isRValueReferenceType() && 7077 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7078 Candidate.Viable = false; 7079 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7080 return; 7081 } 7082 break; 7083 7084 case ImplicitConversionSequence::BadConversion: 7085 Candidate.Viable = false; 7086 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7087 return; 7088 7089 default: 7090 llvm_unreachable( 7091 "Can only end up with a standard conversion sequence or failure"); 7092 } 7093 7094 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7095 Candidate.Viable = false; 7096 Candidate.FailureKind = ovl_fail_enable_if; 7097 Candidate.DeductionFailure.Data = FailedAttr; 7098 return; 7099 } 7100 7101 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7102 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7103 Candidate.Viable = false; 7104 Candidate.FailureKind = ovl_non_default_multiversion_function; 7105 } 7106 } 7107 7108 /// Adds a conversion function template specialization 7109 /// candidate to the overload set, using template argument deduction 7110 /// to deduce the template arguments of the conversion function 7111 /// template from the type that we are converting to (C++ 7112 /// [temp.deduct.conv]). 7113 void 7114 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 7115 DeclAccessPair FoundDecl, 7116 CXXRecordDecl *ActingDC, 7117 Expr *From, QualType ToType, 7118 OverloadCandidateSet &CandidateSet, 7119 bool AllowObjCConversionOnExplicit, 7120 bool AllowResultConversion) { 7121 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7122 "Only conversion function templates permitted here"); 7123 7124 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7125 return; 7126 7127 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7128 CXXConversionDecl *Specialization = nullptr; 7129 if (TemplateDeductionResult Result 7130 = DeduceTemplateArguments(FunctionTemplate, ToType, 7131 Specialization, Info)) { 7132 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7133 Candidate.FoundDecl = FoundDecl; 7134 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7135 Candidate.Viable = false; 7136 Candidate.FailureKind = ovl_fail_bad_deduction; 7137 Candidate.IsSurrogate = false; 7138 Candidate.IgnoreObjectArgument = false; 7139 Candidate.ExplicitCallArguments = 1; 7140 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7141 Info); 7142 return; 7143 } 7144 7145 // Add the conversion function template specialization produced by 7146 // template argument deduction as a candidate. 7147 assert(Specialization && "Missing function template specialization?"); 7148 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7149 CandidateSet, AllowObjCConversionOnExplicit, 7150 AllowResultConversion); 7151 } 7152 7153 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7154 /// converts the given @c Object to a function pointer via the 7155 /// conversion function @c Conversion, and then attempts to call it 7156 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7157 /// the type of function that we'll eventually be calling. 7158 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7159 DeclAccessPair FoundDecl, 7160 CXXRecordDecl *ActingContext, 7161 const FunctionProtoType *Proto, 7162 Expr *Object, 7163 ArrayRef<Expr *> Args, 7164 OverloadCandidateSet& CandidateSet) { 7165 if (!CandidateSet.isNewCandidate(Conversion)) 7166 return; 7167 7168 // Overload resolution is always an unevaluated context. 7169 EnterExpressionEvaluationContext Unevaluated( 7170 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7171 7172 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7173 Candidate.FoundDecl = FoundDecl; 7174 Candidate.Function = nullptr; 7175 Candidate.Surrogate = Conversion; 7176 Candidate.Viable = true; 7177 Candidate.IsSurrogate = true; 7178 Candidate.IgnoreObjectArgument = false; 7179 Candidate.ExplicitCallArguments = Args.size(); 7180 7181 // Determine the implicit conversion sequence for the implicit 7182 // object parameter. 7183 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7184 *this, CandidateSet.getLocation(), Object->getType(), 7185 Object->Classify(Context), Conversion, ActingContext); 7186 if (ObjectInit.isBad()) { 7187 Candidate.Viable = false; 7188 Candidate.FailureKind = ovl_fail_bad_conversion; 7189 Candidate.Conversions[0] = ObjectInit; 7190 return; 7191 } 7192 7193 // The first conversion is actually a user-defined conversion whose 7194 // first conversion is ObjectInit's standard conversion (which is 7195 // effectively a reference binding). Record it as such. 7196 Candidate.Conversions[0].setUserDefined(); 7197 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7198 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7199 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7200 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7201 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7202 Candidate.Conversions[0].UserDefined.After 7203 = Candidate.Conversions[0].UserDefined.Before; 7204 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7205 7206 // Find the 7207 unsigned NumParams = Proto->getNumParams(); 7208 7209 // (C++ 13.3.2p2): A candidate function having fewer than m 7210 // parameters is viable only if it has an ellipsis in its parameter 7211 // list (8.3.5). 7212 if (Args.size() > NumParams && !Proto->isVariadic()) { 7213 Candidate.Viable = false; 7214 Candidate.FailureKind = ovl_fail_too_many_arguments; 7215 return; 7216 } 7217 7218 // Function types don't have any default arguments, so just check if 7219 // we have enough arguments. 7220 if (Args.size() < NumParams) { 7221 // Not enough arguments. 7222 Candidate.Viable = false; 7223 Candidate.FailureKind = ovl_fail_too_few_arguments; 7224 return; 7225 } 7226 7227 // Determine the implicit conversion sequences for each of the 7228 // arguments. 7229 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7230 if (ArgIdx < NumParams) { 7231 // (C++ 13.3.2p3): for F to be a viable function, there shall 7232 // exist for each argument an implicit conversion sequence 7233 // (13.3.3.1) that converts that argument to the corresponding 7234 // parameter of F. 7235 QualType ParamType = Proto->getParamType(ArgIdx); 7236 Candidate.Conversions[ArgIdx + 1] 7237 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7238 /*SuppressUserConversions=*/false, 7239 /*InOverloadResolution=*/false, 7240 /*AllowObjCWritebackConversion=*/ 7241 getLangOpts().ObjCAutoRefCount); 7242 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7243 Candidate.Viable = false; 7244 Candidate.FailureKind = ovl_fail_bad_conversion; 7245 return; 7246 } 7247 } else { 7248 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7249 // argument for which there is no corresponding parameter is 7250 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7251 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7252 } 7253 } 7254 7255 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7256 Candidate.Viable = false; 7257 Candidate.FailureKind = ovl_fail_enable_if; 7258 Candidate.DeductionFailure.Data = FailedAttr; 7259 return; 7260 } 7261 } 7262 7263 /// Add overload candidates for overloaded operators that are 7264 /// member functions. 7265 /// 7266 /// Add the overloaded operator candidates that are member functions 7267 /// for the operator Op that was used in an operator expression such 7268 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7269 /// CandidateSet will store the added overload candidates. (C++ 7270 /// [over.match.oper]). 7271 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7272 SourceLocation OpLoc, 7273 ArrayRef<Expr *> Args, 7274 OverloadCandidateSet& CandidateSet, 7275 SourceRange OpRange) { 7276 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7277 7278 // C++ [over.match.oper]p3: 7279 // For a unary operator @ with an operand of a type whose 7280 // cv-unqualified version is T1, and for a binary operator @ with 7281 // a left operand of a type whose cv-unqualified version is T1 and 7282 // a right operand of a type whose cv-unqualified version is T2, 7283 // three sets of candidate functions, designated member 7284 // candidates, non-member candidates and built-in candidates, are 7285 // constructed as follows: 7286 QualType T1 = Args[0]->getType(); 7287 7288 // -- If T1 is a complete class type or a class currently being 7289 // defined, the set of member candidates is the result of the 7290 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7291 // the set of member candidates is empty. 7292 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7293 // Complete the type if it can be completed. 7294 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7295 return; 7296 // If the type is neither complete nor being defined, bail out now. 7297 if (!T1Rec->getDecl()->getDefinition()) 7298 return; 7299 7300 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7301 LookupQualifiedName(Operators, T1Rec->getDecl()); 7302 Operators.suppressDiagnostics(); 7303 7304 for (LookupResult::iterator Oper = Operators.begin(), 7305 OperEnd = Operators.end(); 7306 Oper != OperEnd; 7307 ++Oper) 7308 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7309 Args[0]->Classify(Context), Args.slice(1), 7310 CandidateSet, /*SuppressUserConversions=*/false); 7311 } 7312 } 7313 7314 /// AddBuiltinCandidate - Add a candidate for a built-in 7315 /// operator. ResultTy and ParamTys are the result and parameter types 7316 /// of the built-in candidate, respectively. Args and NumArgs are the 7317 /// arguments being passed to the candidate. IsAssignmentOperator 7318 /// should be true when this built-in candidate is an assignment 7319 /// operator. NumContextualBoolArguments is the number of arguments 7320 /// (at the beginning of the argument list) that will be contextually 7321 /// converted to bool. 7322 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7323 OverloadCandidateSet& CandidateSet, 7324 bool IsAssignmentOperator, 7325 unsigned NumContextualBoolArguments) { 7326 // Overload resolution is always an unevaluated context. 7327 EnterExpressionEvaluationContext Unevaluated( 7328 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7329 7330 // Add this candidate 7331 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7332 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7333 Candidate.Function = nullptr; 7334 Candidate.IsSurrogate = false; 7335 Candidate.IgnoreObjectArgument = false; 7336 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7337 7338 // Determine the implicit conversion sequences for each of the 7339 // arguments. 7340 Candidate.Viable = true; 7341 Candidate.ExplicitCallArguments = Args.size(); 7342 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7343 // C++ [over.match.oper]p4: 7344 // For the built-in assignment operators, conversions of the 7345 // left operand are restricted as follows: 7346 // -- no temporaries are introduced to hold the left operand, and 7347 // -- no user-defined conversions are applied to the left 7348 // operand to achieve a type match with the left-most 7349 // parameter of a built-in candidate. 7350 // 7351 // We block these conversions by turning off user-defined 7352 // conversions, since that is the only way that initialization of 7353 // a reference to a non-class type can occur from something that 7354 // is not of the same type. 7355 if (ArgIdx < NumContextualBoolArguments) { 7356 assert(ParamTys[ArgIdx] == Context.BoolTy && 7357 "Contextual conversion to bool requires bool type"); 7358 Candidate.Conversions[ArgIdx] 7359 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7360 } else { 7361 Candidate.Conversions[ArgIdx] 7362 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7363 ArgIdx == 0 && IsAssignmentOperator, 7364 /*InOverloadResolution=*/false, 7365 /*AllowObjCWritebackConversion=*/ 7366 getLangOpts().ObjCAutoRefCount); 7367 } 7368 if (Candidate.Conversions[ArgIdx].isBad()) { 7369 Candidate.Viable = false; 7370 Candidate.FailureKind = ovl_fail_bad_conversion; 7371 break; 7372 } 7373 } 7374 } 7375 7376 namespace { 7377 7378 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7379 /// candidate operator functions for built-in operators (C++ 7380 /// [over.built]). The types are separated into pointer types and 7381 /// enumeration types. 7382 class BuiltinCandidateTypeSet { 7383 /// TypeSet - A set of types. 7384 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7385 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7386 7387 /// PointerTypes - The set of pointer types that will be used in the 7388 /// built-in candidates. 7389 TypeSet PointerTypes; 7390 7391 /// MemberPointerTypes - The set of member pointer types that will be 7392 /// used in the built-in candidates. 7393 TypeSet MemberPointerTypes; 7394 7395 /// EnumerationTypes - The set of enumeration types that will be 7396 /// used in the built-in candidates. 7397 TypeSet EnumerationTypes; 7398 7399 /// The set of vector types that will be used in the built-in 7400 /// candidates. 7401 TypeSet VectorTypes; 7402 7403 /// A flag indicating non-record types are viable candidates 7404 bool HasNonRecordTypes; 7405 7406 /// A flag indicating whether either arithmetic or enumeration types 7407 /// were present in the candidate set. 7408 bool HasArithmeticOrEnumeralTypes; 7409 7410 /// A flag indicating whether the nullptr type was present in the 7411 /// candidate set. 7412 bool HasNullPtrType; 7413 7414 /// Sema - The semantic analysis instance where we are building the 7415 /// candidate type set. 7416 Sema &SemaRef; 7417 7418 /// Context - The AST context in which we will build the type sets. 7419 ASTContext &Context; 7420 7421 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7422 const Qualifiers &VisibleQuals); 7423 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7424 7425 public: 7426 /// iterator - Iterates through the types that are part of the set. 7427 typedef TypeSet::iterator iterator; 7428 7429 BuiltinCandidateTypeSet(Sema &SemaRef) 7430 : HasNonRecordTypes(false), 7431 HasArithmeticOrEnumeralTypes(false), 7432 HasNullPtrType(false), 7433 SemaRef(SemaRef), 7434 Context(SemaRef.Context) { } 7435 7436 void AddTypesConvertedFrom(QualType Ty, 7437 SourceLocation Loc, 7438 bool AllowUserConversions, 7439 bool AllowExplicitConversions, 7440 const Qualifiers &VisibleTypeConversionsQuals); 7441 7442 /// pointer_begin - First pointer type found; 7443 iterator pointer_begin() { return PointerTypes.begin(); } 7444 7445 /// pointer_end - Past the last pointer type found; 7446 iterator pointer_end() { return PointerTypes.end(); } 7447 7448 /// member_pointer_begin - First member pointer type found; 7449 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7450 7451 /// member_pointer_end - Past the last member pointer type found; 7452 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7453 7454 /// enumeration_begin - First enumeration type found; 7455 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7456 7457 /// enumeration_end - Past the last enumeration type found; 7458 iterator enumeration_end() { return EnumerationTypes.end(); } 7459 7460 iterator vector_begin() { return VectorTypes.begin(); } 7461 iterator vector_end() { return VectorTypes.end(); } 7462 7463 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7464 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7465 bool hasNullPtrType() const { return HasNullPtrType; } 7466 }; 7467 7468 } // end anonymous namespace 7469 7470 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7471 /// the set of pointer types along with any more-qualified variants of 7472 /// that type. For example, if @p Ty is "int const *", this routine 7473 /// will add "int const *", "int const volatile *", "int const 7474 /// restrict *", and "int const volatile restrict *" to the set of 7475 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7476 /// false otherwise. 7477 /// 7478 /// FIXME: what to do about extended qualifiers? 7479 bool 7480 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7481 const Qualifiers &VisibleQuals) { 7482 7483 // Insert this type. 7484 if (!PointerTypes.insert(Ty)) 7485 return false; 7486 7487 QualType PointeeTy; 7488 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7489 bool buildObjCPtr = false; 7490 if (!PointerTy) { 7491 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7492 PointeeTy = PTy->getPointeeType(); 7493 buildObjCPtr = true; 7494 } else { 7495 PointeeTy = PointerTy->getPointeeType(); 7496 } 7497 7498 // Don't add qualified variants of arrays. For one, they're not allowed 7499 // (the qualifier would sink to the element type), and for another, the 7500 // only overload situation where it matters is subscript or pointer +- int, 7501 // and those shouldn't have qualifier variants anyway. 7502 if (PointeeTy->isArrayType()) 7503 return true; 7504 7505 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7506 bool hasVolatile = VisibleQuals.hasVolatile(); 7507 bool hasRestrict = VisibleQuals.hasRestrict(); 7508 7509 // Iterate through all strict supersets of BaseCVR. 7510 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7511 if ((CVR | BaseCVR) != CVR) continue; 7512 // Skip over volatile if no volatile found anywhere in the types. 7513 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7514 7515 // Skip over restrict if no restrict found anywhere in the types, or if 7516 // the type cannot be restrict-qualified. 7517 if ((CVR & Qualifiers::Restrict) && 7518 (!hasRestrict || 7519 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7520 continue; 7521 7522 // Build qualified pointee type. 7523 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7524 7525 // Build qualified pointer type. 7526 QualType QPointerTy; 7527 if (!buildObjCPtr) 7528 QPointerTy = Context.getPointerType(QPointeeTy); 7529 else 7530 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7531 7532 // Insert qualified pointer type. 7533 PointerTypes.insert(QPointerTy); 7534 } 7535 7536 return true; 7537 } 7538 7539 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7540 /// to the set of pointer types along with any more-qualified variants of 7541 /// that type. For example, if @p Ty is "int const *", this routine 7542 /// will add "int const *", "int const volatile *", "int const 7543 /// restrict *", and "int const volatile restrict *" to the set of 7544 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7545 /// false otherwise. 7546 /// 7547 /// FIXME: what to do about extended qualifiers? 7548 bool 7549 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7550 QualType Ty) { 7551 // Insert this type. 7552 if (!MemberPointerTypes.insert(Ty)) 7553 return false; 7554 7555 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7556 assert(PointerTy && "type was not a member pointer type!"); 7557 7558 QualType PointeeTy = PointerTy->getPointeeType(); 7559 // Don't add qualified variants of arrays. For one, they're not allowed 7560 // (the qualifier would sink to the element type), and for another, the 7561 // only overload situation where it matters is subscript or pointer +- int, 7562 // and those shouldn't have qualifier variants anyway. 7563 if (PointeeTy->isArrayType()) 7564 return true; 7565 const Type *ClassTy = PointerTy->getClass(); 7566 7567 // Iterate through all strict supersets of the pointee type's CVR 7568 // qualifiers. 7569 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7570 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7571 if ((CVR | BaseCVR) != CVR) continue; 7572 7573 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7574 MemberPointerTypes.insert( 7575 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7576 } 7577 7578 return true; 7579 } 7580 7581 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7582 /// Ty can be implicit converted to the given set of @p Types. We're 7583 /// primarily interested in pointer types and enumeration types. We also 7584 /// take member pointer types, for the conditional operator. 7585 /// AllowUserConversions is true if we should look at the conversion 7586 /// functions of a class type, and AllowExplicitConversions if we 7587 /// should also include the explicit conversion functions of a class 7588 /// type. 7589 void 7590 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7591 SourceLocation Loc, 7592 bool AllowUserConversions, 7593 bool AllowExplicitConversions, 7594 const Qualifiers &VisibleQuals) { 7595 // Only deal with canonical types. 7596 Ty = Context.getCanonicalType(Ty); 7597 7598 // Look through reference types; they aren't part of the type of an 7599 // expression for the purposes of conversions. 7600 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7601 Ty = RefTy->getPointeeType(); 7602 7603 // If we're dealing with an array type, decay to the pointer. 7604 if (Ty->isArrayType()) 7605 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7606 7607 // Otherwise, we don't care about qualifiers on the type. 7608 Ty = Ty.getLocalUnqualifiedType(); 7609 7610 // Flag if we ever add a non-record type. 7611 const RecordType *TyRec = Ty->getAs<RecordType>(); 7612 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7613 7614 // Flag if we encounter an arithmetic type. 7615 HasArithmeticOrEnumeralTypes = 7616 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7617 7618 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7619 PointerTypes.insert(Ty); 7620 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7621 // Insert our type, and its more-qualified variants, into the set 7622 // of types. 7623 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7624 return; 7625 } else if (Ty->isMemberPointerType()) { 7626 // Member pointers are far easier, since the pointee can't be converted. 7627 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7628 return; 7629 } else if (Ty->isEnumeralType()) { 7630 HasArithmeticOrEnumeralTypes = true; 7631 EnumerationTypes.insert(Ty); 7632 } else if (Ty->isVectorType()) { 7633 // We treat vector types as arithmetic types in many contexts as an 7634 // extension. 7635 HasArithmeticOrEnumeralTypes = true; 7636 VectorTypes.insert(Ty); 7637 } else if (Ty->isNullPtrType()) { 7638 HasNullPtrType = true; 7639 } else if (AllowUserConversions && TyRec) { 7640 // No conversion functions in incomplete types. 7641 if (!SemaRef.isCompleteType(Loc, Ty)) 7642 return; 7643 7644 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7645 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7646 if (isa<UsingShadowDecl>(D)) 7647 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7648 7649 // Skip conversion function templates; they don't tell us anything 7650 // about which builtin types we can convert to. 7651 if (isa<FunctionTemplateDecl>(D)) 7652 continue; 7653 7654 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7655 if (AllowExplicitConversions || !Conv->isExplicit()) { 7656 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7657 VisibleQuals); 7658 } 7659 } 7660 } 7661 } 7662 /// Helper function for adjusting address spaces for the pointer or reference 7663 /// operands of builtin operators depending on the argument. 7664 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7665 Expr *Arg) { 7666 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7667 } 7668 7669 /// Helper function for AddBuiltinOperatorCandidates() that adds 7670 /// the volatile- and non-volatile-qualified assignment operators for the 7671 /// given type to the candidate set. 7672 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7673 QualType T, 7674 ArrayRef<Expr *> Args, 7675 OverloadCandidateSet &CandidateSet) { 7676 QualType ParamTypes[2]; 7677 7678 // T& operator=(T&, T) 7679 ParamTypes[0] = S.Context.getLValueReferenceType( 7680 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7681 ParamTypes[1] = T; 7682 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7683 /*IsAssignmentOperator=*/true); 7684 7685 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7686 // volatile T& operator=(volatile T&, T) 7687 ParamTypes[0] = S.Context.getLValueReferenceType( 7688 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7689 Args[0])); 7690 ParamTypes[1] = T; 7691 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7692 /*IsAssignmentOperator=*/true); 7693 } 7694 } 7695 7696 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7697 /// if any, found in visible type conversion functions found in ArgExpr's type. 7698 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7699 Qualifiers VRQuals; 7700 const RecordType *TyRec; 7701 if (const MemberPointerType *RHSMPType = 7702 ArgExpr->getType()->getAs<MemberPointerType>()) 7703 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7704 else 7705 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7706 if (!TyRec) { 7707 // Just to be safe, assume the worst case. 7708 VRQuals.addVolatile(); 7709 VRQuals.addRestrict(); 7710 return VRQuals; 7711 } 7712 7713 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7714 if (!ClassDecl->hasDefinition()) 7715 return VRQuals; 7716 7717 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7718 if (isa<UsingShadowDecl>(D)) 7719 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7720 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7721 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7722 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7723 CanTy = ResTypeRef->getPointeeType(); 7724 // Need to go down the pointer/mempointer chain and add qualifiers 7725 // as see them. 7726 bool done = false; 7727 while (!done) { 7728 if (CanTy.isRestrictQualified()) 7729 VRQuals.addRestrict(); 7730 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7731 CanTy = ResTypePtr->getPointeeType(); 7732 else if (const MemberPointerType *ResTypeMPtr = 7733 CanTy->getAs<MemberPointerType>()) 7734 CanTy = ResTypeMPtr->getPointeeType(); 7735 else 7736 done = true; 7737 if (CanTy.isVolatileQualified()) 7738 VRQuals.addVolatile(); 7739 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7740 return VRQuals; 7741 } 7742 } 7743 } 7744 return VRQuals; 7745 } 7746 7747 namespace { 7748 7749 /// Helper class to manage the addition of builtin operator overload 7750 /// candidates. It provides shared state and utility methods used throughout 7751 /// the process, as well as a helper method to add each group of builtin 7752 /// operator overloads from the standard to a candidate set. 7753 class BuiltinOperatorOverloadBuilder { 7754 // Common instance state available to all overload candidate addition methods. 7755 Sema &S; 7756 ArrayRef<Expr *> Args; 7757 Qualifiers VisibleTypeConversionsQuals; 7758 bool HasArithmeticOrEnumeralCandidateType; 7759 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7760 OverloadCandidateSet &CandidateSet; 7761 7762 static constexpr int ArithmeticTypesCap = 24; 7763 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7764 7765 // Define some indices used to iterate over the arithemetic types in 7766 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7767 // types are that preserved by promotion (C++ [over.built]p2). 7768 unsigned FirstIntegralType, 7769 LastIntegralType; 7770 unsigned FirstPromotedIntegralType, 7771 LastPromotedIntegralType; 7772 unsigned FirstPromotedArithmeticType, 7773 LastPromotedArithmeticType; 7774 unsigned NumArithmeticTypes; 7775 7776 void InitArithmeticTypes() { 7777 // Start of promoted types. 7778 FirstPromotedArithmeticType = 0; 7779 ArithmeticTypes.push_back(S.Context.FloatTy); 7780 ArithmeticTypes.push_back(S.Context.DoubleTy); 7781 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7782 if (S.Context.getTargetInfo().hasFloat128Type()) 7783 ArithmeticTypes.push_back(S.Context.Float128Ty); 7784 7785 // Start of integral types. 7786 FirstIntegralType = ArithmeticTypes.size(); 7787 FirstPromotedIntegralType = ArithmeticTypes.size(); 7788 ArithmeticTypes.push_back(S.Context.IntTy); 7789 ArithmeticTypes.push_back(S.Context.LongTy); 7790 ArithmeticTypes.push_back(S.Context.LongLongTy); 7791 if (S.Context.getTargetInfo().hasInt128Type()) 7792 ArithmeticTypes.push_back(S.Context.Int128Ty); 7793 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7794 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7795 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7796 if (S.Context.getTargetInfo().hasInt128Type()) 7797 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7798 LastPromotedIntegralType = ArithmeticTypes.size(); 7799 LastPromotedArithmeticType = ArithmeticTypes.size(); 7800 // End of promoted types. 7801 7802 ArithmeticTypes.push_back(S.Context.BoolTy); 7803 ArithmeticTypes.push_back(S.Context.CharTy); 7804 ArithmeticTypes.push_back(S.Context.WCharTy); 7805 if (S.Context.getLangOpts().Char8) 7806 ArithmeticTypes.push_back(S.Context.Char8Ty); 7807 ArithmeticTypes.push_back(S.Context.Char16Ty); 7808 ArithmeticTypes.push_back(S.Context.Char32Ty); 7809 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7810 ArithmeticTypes.push_back(S.Context.ShortTy); 7811 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7812 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7813 LastIntegralType = ArithmeticTypes.size(); 7814 NumArithmeticTypes = ArithmeticTypes.size(); 7815 // End of integral types. 7816 // FIXME: What about complex? What about half? 7817 7818 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7819 "Enough inline storage for all arithmetic types."); 7820 } 7821 7822 /// Helper method to factor out the common pattern of adding overloads 7823 /// for '++' and '--' builtin operators. 7824 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7825 bool HasVolatile, 7826 bool HasRestrict) { 7827 QualType ParamTypes[2] = { 7828 S.Context.getLValueReferenceType(CandidateTy), 7829 S.Context.IntTy 7830 }; 7831 7832 // Non-volatile version. 7833 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7834 7835 // Use a heuristic to reduce number of builtin candidates in the set: 7836 // add volatile version only if there are conversions to a volatile type. 7837 if (HasVolatile) { 7838 ParamTypes[0] = 7839 S.Context.getLValueReferenceType( 7840 S.Context.getVolatileType(CandidateTy)); 7841 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7842 } 7843 7844 // Add restrict version only if there are conversions to a restrict type 7845 // and our candidate type is a non-restrict-qualified pointer. 7846 if (HasRestrict && CandidateTy->isAnyPointerType() && 7847 !CandidateTy.isRestrictQualified()) { 7848 ParamTypes[0] 7849 = S.Context.getLValueReferenceType( 7850 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7851 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7852 7853 if (HasVolatile) { 7854 ParamTypes[0] 7855 = S.Context.getLValueReferenceType( 7856 S.Context.getCVRQualifiedType(CandidateTy, 7857 (Qualifiers::Volatile | 7858 Qualifiers::Restrict))); 7859 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7860 } 7861 } 7862 7863 } 7864 7865 public: 7866 BuiltinOperatorOverloadBuilder( 7867 Sema &S, ArrayRef<Expr *> Args, 7868 Qualifiers VisibleTypeConversionsQuals, 7869 bool HasArithmeticOrEnumeralCandidateType, 7870 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7871 OverloadCandidateSet &CandidateSet) 7872 : S(S), Args(Args), 7873 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7874 HasArithmeticOrEnumeralCandidateType( 7875 HasArithmeticOrEnumeralCandidateType), 7876 CandidateTypes(CandidateTypes), 7877 CandidateSet(CandidateSet) { 7878 7879 InitArithmeticTypes(); 7880 } 7881 7882 // Increment is deprecated for bool since C++17. 7883 // 7884 // C++ [over.built]p3: 7885 // 7886 // For every pair (T, VQ), where T is an arithmetic type other 7887 // than bool, and VQ is either volatile or empty, there exist 7888 // candidate operator functions of the form 7889 // 7890 // VQ T& operator++(VQ T&); 7891 // T operator++(VQ T&, int); 7892 // 7893 // C++ [over.built]p4: 7894 // 7895 // For every pair (T, VQ), where T is an arithmetic type other 7896 // than bool, and VQ is either volatile or empty, there exist 7897 // candidate operator functions of the form 7898 // 7899 // VQ T& operator--(VQ T&); 7900 // T operator--(VQ T&, int); 7901 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7902 if (!HasArithmeticOrEnumeralCandidateType) 7903 return; 7904 7905 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 7906 const auto TypeOfT = ArithmeticTypes[Arith]; 7907 if (TypeOfT == S.Context.BoolTy) { 7908 if (Op == OO_MinusMinus) 7909 continue; 7910 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 7911 continue; 7912 } 7913 addPlusPlusMinusMinusStyleOverloads( 7914 TypeOfT, 7915 VisibleTypeConversionsQuals.hasVolatile(), 7916 VisibleTypeConversionsQuals.hasRestrict()); 7917 } 7918 } 7919 7920 // C++ [over.built]p5: 7921 // 7922 // For every pair (T, VQ), where T is a cv-qualified or 7923 // cv-unqualified object type, and VQ is either volatile or 7924 // empty, there exist candidate operator functions of the form 7925 // 7926 // T*VQ& operator++(T*VQ&); 7927 // T*VQ& operator--(T*VQ&); 7928 // T* operator++(T*VQ&, int); 7929 // T* operator--(T*VQ&, int); 7930 void addPlusPlusMinusMinusPointerOverloads() { 7931 for (BuiltinCandidateTypeSet::iterator 7932 Ptr = CandidateTypes[0].pointer_begin(), 7933 PtrEnd = CandidateTypes[0].pointer_end(); 7934 Ptr != PtrEnd; ++Ptr) { 7935 // Skip pointer types that aren't pointers to object types. 7936 if (!(*Ptr)->getPointeeType()->isObjectType()) 7937 continue; 7938 7939 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7940 (!(*Ptr).isVolatileQualified() && 7941 VisibleTypeConversionsQuals.hasVolatile()), 7942 (!(*Ptr).isRestrictQualified() && 7943 VisibleTypeConversionsQuals.hasRestrict())); 7944 } 7945 } 7946 7947 // C++ [over.built]p6: 7948 // For every cv-qualified or cv-unqualified object type T, there 7949 // exist candidate operator functions of the form 7950 // 7951 // T& operator*(T*); 7952 // 7953 // C++ [over.built]p7: 7954 // For every function type T that does not have cv-qualifiers or a 7955 // ref-qualifier, there exist candidate operator functions of the form 7956 // T& operator*(T*); 7957 void addUnaryStarPointerOverloads() { 7958 for (BuiltinCandidateTypeSet::iterator 7959 Ptr = CandidateTypes[0].pointer_begin(), 7960 PtrEnd = CandidateTypes[0].pointer_end(); 7961 Ptr != PtrEnd; ++Ptr) { 7962 QualType ParamTy = *Ptr; 7963 QualType PointeeTy = ParamTy->getPointeeType(); 7964 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7965 continue; 7966 7967 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7968 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 7969 continue; 7970 7971 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7972 } 7973 } 7974 7975 // C++ [over.built]p9: 7976 // For every promoted arithmetic type T, there exist candidate 7977 // operator functions of the form 7978 // 7979 // T operator+(T); 7980 // T operator-(T); 7981 void addUnaryPlusOrMinusArithmeticOverloads() { 7982 if (!HasArithmeticOrEnumeralCandidateType) 7983 return; 7984 7985 for (unsigned Arith = FirstPromotedArithmeticType; 7986 Arith < LastPromotedArithmeticType; ++Arith) { 7987 QualType ArithTy = ArithmeticTypes[Arith]; 7988 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 7989 } 7990 7991 // Extension: We also add these operators for vector types. 7992 for (BuiltinCandidateTypeSet::iterator 7993 Vec = CandidateTypes[0].vector_begin(), 7994 VecEnd = CandidateTypes[0].vector_end(); 7995 Vec != VecEnd; ++Vec) { 7996 QualType VecTy = *Vec; 7997 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 7998 } 7999 } 8000 8001 // C++ [over.built]p8: 8002 // For every type T, there exist candidate operator functions of 8003 // the form 8004 // 8005 // T* operator+(T*); 8006 void addUnaryPlusPointerOverloads() { 8007 for (BuiltinCandidateTypeSet::iterator 8008 Ptr = CandidateTypes[0].pointer_begin(), 8009 PtrEnd = CandidateTypes[0].pointer_end(); 8010 Ptr != PtrEnd; ++Ptr) { 8011 QualType ParamTy = *Ptr; 8012 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8013 } 8014 } 8015 8016 // C++ [over.built]p10: 8017 // For every promoted integral type T, there exist candidate 8018 // operator functions of the form 8019 // 8020 // T operator~(T); 8021 void addUnaryTildePromotedIntegralOverloads() { 8022 if (!HasArithmeticOrEnumeralCandidateType) 8023 return; 8024 8025 for (unsigned Int = FirstPromotedIntegralType; 8026 Int < LastPromotedIntegralType; ++Int) { 8027 QualType IntTy = ArithmeticTypes[Int]; 8028 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8029 } 8030 8031 // Extension: We also add this operator for vector types. 8032 for (BuiltinCandidateTypeSet::iterator 8033 Vec = CandidateTypes[0].vector_begin(), 8034 VecEnd = CandidateTypes[0].vector_end(); 8035 Vec != VecEnd; ++Vec) { 8036 QualType VecTy = *Vec; 8037 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8038 } 8039 } 8040 8041 // C++ [over.match.oper]p16: 8042 // For every pointer to member type T or type std::nullptr_t, there 8043 // exist candidate operator functions of the form 8044 // 8045 // bool operator==(T,T); 8046 // bool operator!=(T,T); 8047 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8048 /// Set of (canonical) types that we've already handled. 8049 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8050 8051 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8052 for (BuiltinCandidateTypeSet::iterator 8053 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8054 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8055 MemPtr != MemPtrEnd; 8056 ++MemPtr) { 8057 // Don't add the same builtin candidate twice. 8058 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8059 continue; 8060 8061 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8062 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8063 } 8064 8065 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8066 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8067 if (AddedTypes.insert(NullPtrTy).second) { 8068 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8069 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8070 } 8071 } 8072 } 8073 } 8074 8075 // C++ [over.built]p15: 8076 // 8077 // For every T, where T is an enumeration type or a pointer type, 8078 // there exist candidate operator functions of the form 8079 // 8080 // bool operator<(T, T); 8081 // bool operator>(T, T); 8082 // bool operator<=(T, T); 8083 // bool operator>=(T, T); 8084 // bool operator==(T, T); 8085 // bool operator!=(T, T); 8086 // R operator<=>(T, T) 8087 void addGenericBinaryPointerOrEnumeralOverloads() { 8088 // C++ [over.match.oper]p3: 8089 // [...]the built-in candidates include all of the candidate operator 8090 // functions defined in 13.6 that, compared to the given operator, [...] 8091 // do not have the same parameter-type-list as any non-template non-member 8092 // candidate. 8093 // 8094 // Note that in practice, this only affects enumeration types because there 8095 // aren't any built-in candidates of record type, and a user-defined operator 8096 // must have an operand of record or enumeration type. Also, the only other 8097 // overloaded operator with enumeration arguments, operator=, 8098 // cannot be overloaded for enumeration types, so this is the only place 8099 // where we must suppress candidates like this. 8100 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8101 UserDefinedBinaryOperators; 8102 8103 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8104 if (CandidateTypes[ArgIdx].enumeration_begin() != 8105 CandidateTypes[ArgIdx].enumeration_end()) { 8106 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8107 CEnd = CandidateSet.end(); 8108 C != CEnd; ++C) { 8109 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8110 continue; 8111 8112 if (C->Function->isFunctionTemplateSpecialization()) 8113 continue; 8114 8115 QualType FirstParamType = 8116 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 8117 QualType SecondParamType = 8118 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 8119 8120 // Skip if either parameter isn't of enumeral type. 8121 if (!FirstParamType->isEnumeralType() || 8122 !SecondParamType->isEnumeralType()) 8123 continue; 8124 8125 // Add this operator to the set of known user-defined operators. 8126 UserDefinedBinaryOperators.insert( 8127 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8128 S.Context.getCanonicalType(SecondParamType))); 8129 } 8130 } 8131 } 8132 8133 /// Set of (canonical) types that we've already handled. 8134 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8135 8136 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8137 for (BuiltinCandidateTypeSet::iterator 8138 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8139 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8140 Ptr != PtrEnd; ++Ptr) { 8141 // Don't add the same builtin candidate twice. 8142 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8143 continue; 8144 8145 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8146 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8147 } 8148 for (BuiltinCandidateTypeSet::iterator 8149 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8150 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8151 Enum != EnumEnd; ++Enum) { 8152 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8153 8154 // Don't add the same builtin candidate twice, or if a user defined 8155 // candidate exists. 8156 if (!AddedTypes.insert(CanonType).second || 8157 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8158 CanonType))) 8159 continue; 8160 QualType ParamTypes[2] = { *Enum, *Enum }; 8161 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8162 } 8163 } 8164 } 8165 8166 // C++ [over.built]p13: 8167 // 8168 // For every cv-qualified or cv-unqualified object type T 8169 // there exist candidate operator functions of the form 8170 // 8171 // T* operator+(T*, ptrdiff_t); 8172 // T& operator[](T*, ptrdiff_t); [BELOW] 8173 // T* operator-(T*, ptrdiff_t); 8174 // T* operator+(ptrdiff_t, T*); 8175 // T& operator[](ptrdiff_t, T*); [BELOW] 8176 // 8177 // C++ [over.built]p14: 8178 // 8179 // For every T, where T is a pointer to object type, there 8180 // exist candidate operator functions of the form 8181 // 8182 // ptrdiff_t operator-(T, T); 8183 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8184 /// Set of (canonical) types that we've already handled. 8185 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8186 8187 for (int Arg = 0; Arg < 2; ++Arg) { 8188 QualType AsymmetricParamTypes[2] = { 8189 S.Context.getPointerDiffType(), 8190 S.Context.getPointerDiffType(), 8191 }; 8192 for (BuiltinCandidateTypeSet::iterator 8193 Ptr = CandidateTypes[Arg].pointer_begin(), 8194 PtrEnd = CandidateTypes[Arg].pointer_end(); 8195 Ptr != PtrEnd; ++Ptr) { 8196 QualType PointeeTy = (*Ptr)->getPointeeType(); 8197 if (!PointeeTy->isObjectType()) 8198 continue; 8199 8200 AsymmetricParamTypes[Arg] = *Ptr; 8201 if (Arg == 0 || Op == OO_Plus) { 8202 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8203 // T* operator+(ptrdiff_t, T*); 8204 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8205 } 8206 if (Op == OO_Minus) { 8207 // ptrdiff_t operator-(T, T); 8208 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8209 continue; 8210 8211 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8212 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8213 } 8214 } 8215 } 8216 } 8217 8218 // C++ [over.built]p12: 8219 // 8220 // For every pair of promoted arithmetic types L and R, there 8221 // exist candidate operator functions of the form 8222 // 8223 // LR operator*(L, R); 8224 // LR operator/(L, R); 8225 // LR operator+(L, R); 8226 // LR operator-(L, R); 8227 // bool operator<(L, R); 8228 // bool operator>(L, R); 8229 // bool operator<=(L, R); 8230 // bool operator>=(L, R); 8231 // bool operator==(L, R); 8232 // bool operator!=(L, R); 8233 // 8234 // where LR is the result of the usual arithmetic conversions 8235 // between types L and R. 8236 // 8237 // C++ [over.built]p24: 8238 // 8239 // For every pair of promoted arithmetic types L and R, there exist 8240 // candidate operator functions of the form 8241 // 8242 // LR operator?(bool, L, R); 8243 // 8244 // where LR is the result of the usual arithmetic conversions 8245 // between types L and R. 8246 // Our candidates ignore the first parameter. 8247 void addGenericBinaryArithmeticOverloads() { 8248 if (!HasArithmeticOrEnumeralCandidateType) 8249 return; 8250 8251 for (unsigned Left = FirstPromotedArithmeticType; 8252 Left < LastPromotedArithmeticType; ++Left) { 8253 for (unsigned Right = FirstPromotedArithmeticType; 8254 Right < LastPromotedArithmeticType; ++Right) { 8255 QualType LandR[2] = { ArithmeticTypes[Left], 8256 ArithmeticTypes[Right] }; 8257 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8258 } 8259 } 8260 8261 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8262 // conditional operator for vector types. 8263 for (BuiltinCandidateTypeSet::iterator 8264 Vec1 = CandidateTypes[0].vector_begin(), 8265 Vec1End = CandidateTypes[0].vector_end(); 8266 Vec1 != Vec1End; ++Vec1) { 8267 for (BuiltinCandidateTypeSet::iterator 8268 Vec2 = CandidateTypes[1].vector_begin(), 8269 Vec2End = CandidateTypes[1].vector_end(); 8270 Vec2 != Vec2End; ++Vec2) { 8271 QualType LandR[2] = { *Vec1, *Vec2 }; 8272 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8273 } 8274 } 8275 } 8276 8277 // C++2a [over.built]p14: 8278 // 8279 // For every integral type T there exists a candidate operator function 8280 // of the form 8281 // 8282 // std::strong_ordering operator<=>(T, T) 8283 // 8284 // C++2a [over.built]p15: 8285 // 8286 // For every pair of floating-point types L and R, there exists a candidate 8287 // operator function of the form 8288 // 8289 // std::partial_ordering operator<=>(L, R); 8290 // 8291 // FIXME: The current specification for integral types doesn't play nice with 8292 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8293 // comparisons. Under the current spec this can lead to ambiguity during 8294 // overload resolution. For example: 8295 // 8296 // enum A : int {a}; 8297 // auto x = (a <=> (long)42); 8298 // 8299 // error: call is ambiguous for arguments 'A' and 'long'. 8300 // note: candidate operator<=>(int, int) 8301 // note: candidate operator<=>(long, long) 8302 // 8303 // To avoid this error, this function deviates from the specification and adds 8304 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8305 // arithmetic types (the same as the generic relational overloads). 8306 // 8307 // For now this function acts as a placeholder. 8308 void addThreeWayArithmeticOverloads() { 8309 addGenericBinaryArithmeticOverloads(); 8310 } 8311 8312 // C++ [over.built]p17: 8313 // 8314 // For every pair of promoted integral types L and R, there 8315 // exist candidate operator functions of the form 8316 // 8317 // LR operator%(L, R); 8318 // LR operator&(L, R); 8319 // LR operator^(L, R); 8320 // LR operator|(L, R); 8321 // L operator<<(L, R); 8322 // L operator>>(L, R); 8323 // 8324 // where LR is the result of the usual arithmetic conversions 8325 // between types L and R. 8326 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8327 if (!HasArithmeticOrEnumeralCandidateType) 8328 return; 8329 8330 for (unsigned Left = FirstPromotedIntegralType; 8331 Left < LastPromotedIntegralType; ++Left) { 8332 for (unsigned Right = FirstPromotedIntegralType; 8333 Right < LastPromotedIntegralType; ++Right) { 8334 QualType LandR[2] = { ArithmeticTypes[Left], 8335 ArithmeticTypes[Right] }; 8336 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8337 } 8338 } 8339 } 8340 8341 // C++ [over.built]p20: 8342 // 8343 // For every pair (T, VQ), where T is an enumeration or 8344 // pointer to member type and VQ is either volatile or 8345 // empty, there exist candidate operator functions of the form 8346 // 8347 // VQ T& operator=(VQ T&, T); 8348 void addAssignmentMemberPointerOrEnumeralOverloads() { 8349 /// Set of (canonical) types that we've already handled. 8350 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8351 8352 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8353 for (BuiltinCandidateTypeSet::iterator 8354 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8355 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8356 Enum != EnumEnd; ++Enum) { 8357 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8358 continue; 8359 8360 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8361 } 8362 8363 for (BuiltinCandidateTypeSet::iterator 8364 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8365 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8366 MemPtr != MemPtrEnd; ++MemPtr) { 8367 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8368 continue; 8369 8370 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8371 } 8372 } 8373 } 8374 8375 // C++ [over.built]p19: 8376 // 8377 // For every pair (T, VQ), where T is any type and VQ is either 8378 // volatile or empty, there exist candidate operator functions 8379 // of the form 8380 // 8381 // T*VQ& operator=(T*VQ&, T*); 8382 // 8383 // C++ [over.built]p21: 8384 // 8385 // For every pair (T, VQ), where T is a cv-qualified or 8386 // cv-unqualified object type and VQ is either volatile or 8387 // empty, there exist candidate operator functions of the form 8388 // 8389 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8390 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8391 void addAssignmentPointerOverloads(bool isEqualOp) { 8392 /// Set of (canonical) types that we've already handled. 8393 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8394 8395 for (BuiltinCandidateTypeSet::iterator 8396 Ptr = CandidateTypes[0].pointer_begin(), 8397 PtrEnd = CandidateTypes[0].pointer_end(); 8398 Ptr != PtrEnd; ++Ptr) { 8399 // If this is operator=, keep track of the builtin candidates we added. 8400 if (isEqualOp) 8401 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8402 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8403 continue; 8404 8405 // non-volatile version 8406 QualType ParamTypes[2] = { 8407 S.Context.getLValueReferenceType(*Ptr), 8408 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8409 }; 8410 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8411 /*IsAssigmentOperator=*/ isEqualOp); 8412 8413 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8414 VisibleTypeConversionsQuals.hasVolatile(); 8415 if (NeedVolatile) { 8416 // volatile version 8417 ParamTypes[0] = 8418 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8419 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8420 /*IsAssigmentOperator=*/isEqualOp); 8421 } 8422 8423 if (!(*Ptr).isRestrictQualified() && 8424 VisibleTypeConversionsQuals.hasRestrict()) { 8425 // restrict version 8426 ParamTypes[0] 8427 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8428 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8429 /*IsAssigmentOperator=*/isEqualOp); 8430 8431 if (NeedVolatile) { 8432 // volatile restrict version 8433 ParamTypes[0] 8434 = S.Context.getLValueReferenceType( 8435 S.Context.getCVRQualifiedType(*Ptr, 8436 (Qualifiers::Volatile | 8437 Qualifiers::Restrict))); 8438 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8439 /*IsAssigmentOperator=*/isEqualOp); 8440 } 8441 } 8442 } 8443 8444 if (isEqualOp) { 8445 for (BuiltinCandidateTypeSet::iterator 8446 Ptr = CandidateTypes[1].pointer_begin(), 8447 PtrEnd = CandidateTypes[1].pointer_end(); 8448 Ptr != PtrEnd; ++Ptr) { 8449 // Make sure we don't add the same candidate twice. 8450 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8451 continue; 8452 8453 QualType ParamTypes[2] = { 8454 S.Context.getLValueReferenceType(*Ptr), 8455 *Ptr, 8456 }; 8457 8458 // non-volatile version 8459 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8460 /*IsAssigmentOperator=*/true); 8461 8462 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8463 VisibleTypeConversionsQuals.hasVolatile(); 8464 if (NeedVolatile) { 8465 // volatile version 8466 ParamTypes[0] = 8467 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8468 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8469 /*IsAssigmentOperator=*/true); 8470 } 8471 8472 if (!(*Ptr).isRestrictQualified() && 8473 VisibleTypeConversionsQuals.hasRestrict()) { 8474 // restrict version 8475 ParamTypes[0] 8476 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8477 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8478 /*IsAssigmentOperator=*/true); 8479 8480 if (NeedVolatile) { 8481 // volatile restrict version 8482 ParamTypes[0] 8483 = S.Context.getLValueReferenceType( 8484 S.Context.getCVRQualifiedType(*Ptr, 8485 (Qualifiers::Volatile | 8486 Qualifiers::Restrict))); 8487 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8488 /*IsAssigmentOperator=*/true); 8489 } 8490 } 8491 } 8492 } 8493 } 8494 8495 // C++ [over.built]p18: 8496 // 8497 // For every triple (L, VQ, R), where L is an arithmetic type, 8498 // VQ is either volatile or empty, and R is a promoted 8499 // arithmetic type, there exist candidate operator functions of 8500 // the form 8501 // 8502 // VQ L& operator=(VQ L&, R); 8503 // VQ L& operator*=(VQ L&, R); 8504 // VQ L& operator/=(VQ L&, R); 8505 // VQ L& operator+=(VQ L&, R); 8506 // VQ L& operator-=(VQ L&, R); 8507 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8508 if (!HasArithmeticOrEnumeralCandidateType) 8509 return; 8510 8511 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8512 for (unsigned Right = FirstPromotedArithmeticType; 8513 Right < LastPromotedArithmeticType; ++Right) { 8514 QualType ParamTypes[2]; 8515 ParamTypes[1] = ArithmeticTypes[Right]; 8516 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8517 S, ArithmeticTypes[Left], Args[0]); 8518 // Add this built-in operator as a candidate (VQ is empty). 8519 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8520 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8521 /*IsAssigmentOperator=*/isEqualOp); 8522 8523 // Add this built-in operator as a candidate (VQ is 'volatile'). 8524 if (VisibleTypeConversionsQuals.hasVolatile()) { 8525 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8526 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8527 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8528 /*IsAssigmentOperator=*/isEqualOp); 8529 } 8530 } 8531 } 8532 8533 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8534 for (BuiltinCandidateTypeSet::iterator 8535 Vec1 = CandidateTypes[0].vector_begin(), 8536 Vec1End = CandidateTypes[0].vector_end(); 8537 Vec1 != Vec1End; ++Vec1) { 8538 for (BuiltinCandidateTypeSet::iterator 8539 Vec2 = CandidateTypes[1].vector_begin(), 8540 Vec2End = CandidateTypes[1].vector_end(); 8541 Vec2 != Vec2End; ++Vec2) { 8542 QualType ParamTypes[2]; 8543 ParamTypes[1] = *Vec2; 8544 // Add this built-in operator as a candidate (VQ is empty). 8545 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8546 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8547 /*IsAssigmentOperator=*/isEqualOp); 8548 8549 // Add this built-in operator as a candidate (VQ is 'volatile'). 8550 if (VisibleTypeConversionsQuals.hasVolatile()) { 8551 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8552 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8553 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8554 /*IsAssigmentOperator=*/isEqualOp); 8555 } 8556 } 8557 } 8558 } 8559 8560 // C++ [over.built]p22: 8561 // 8562 // For every triple (L, VQ, R), where L is an integral type, VQ 8563 // is either volatile or empty, and R is a promoted integral 8564 // type, there exist candidate operator functions of the form 8565 // 8566 // VQ L& operator%=(VQ L&, R); 8567 // VQ L& operator<<=(VQ L&, R); 8568 // VQ L& operator>>=(VQ L&, R); 8569 // VQ L& operator&=(VQ L&, R); 8570 // VQ L& operator^=(VQ L&, R); 8571 // VQ L& operator|=(VQ L&, R); 8572 void addAssignmentIntegralOverloads() { 8573 if (!HasArithmeticOrEnumeralCandidateType) 8574 return; 8575 8576 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8577 for (unsigned Right = FirstPromotedIntegralType; 8578 Right < LastPromotedIntegralType; ++Right) { 8579 QualType ParamTypes[2]; 8580 ParamTypes[1] = ArithmeticTypes[Right]; 8581 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8582 S, ArithmeticTypes[Left], Args[0]); 8583 // Add this built-in operator as a candidate (VQ is empty). 8584 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8585 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8586 if (VisibleTypeConversionsQuals.hasVolatile()) { 8587 // Add this built-in operator as a candidate (VQ is 'volatile'). 8588 ParamTypes[0] = LeftBaseTy; 8589 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8590 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8591 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8592 } 8593 } 8594 } 8595 } 8596 8597 // C++ [over.operator]p23: 8598 // 8599 // There also exist candidate operator functions of the form 8600 // 8601 // bool operator!(bool); 8602 // bool operator&&(bool, bool); 8603 // bool operator||(bool, bool); 8604 void addExclaimOverload() { 8605 QualType ParamTy = S.Context.BoolTy; 8606 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8607 /*IsAssignmentOperator=*/false, 8608 /*NumContextualBoolArguments=*/1); 8609 } 8610 void addAmpAmpOrPipePipeOverload() { 8611 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8612 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8613 /*IsAssignmentOperator=*/false, 8614 /*NumContextualBoolArguments=*/2); 8615 } 8616 8617 // C++ [over.built]p13: 8618 // 8619 // For every cv-qualified or cv-unqualified object type T there 8620 // exist candidate operator functions of the form 8621 // 8622 // T* operator+(T*, ptrdiff_t); [ABOVE] 8623 // T& operator[](T*, ptrdiff_t); 8624 // T* operator-(T*, ptrdiff_t); [ABOVE] 8625 // T* operator+(ptrdiff_t, T*); [ABOVE] 8626 // T& operator[](ptrdiff_t, T*); 8627 void addSubscriptOverloads() { 8628 for (BuiltinCandidateTypeSet::iterator 8629 Ptr = CandidateTypes[0].pointer_begin(), 8630 PtrEnd = CandidateTypes[0].pointer_end(); 8631 Ptr != PtrEnd; ++Ptr) { 8632 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8633 QualType PointeeType = (*Ptr)->getPointeeType(); 8634 if (!PointeeType->isObjectType()) 8635 continue; 8636 8637 // T& operator[](T*, ptrdiff_t) 8638 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8639 } 8640 8641 for (BuiltinCandidateTypeSet::iterator 8642 Ptr = CandidateTypes[1].pointer_begin(), 8643 PtrEnd = CandidateTypes[1].pointer_end(); 8644 Ptr != PtrEnd; ++Ptr) { 8645 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8646 QualType PointeeType = (*Ptr)->getPointeeType(); 8647 if (!PointeeType->isObjectType()) 8648 continue; 8649 8650 // T& operator[](ptrdiff_t, T*) 8651 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8652 } 8653 } 8654 8655 // C++ [over.built]p11: 8656 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8657 // C1 is the same type as C2 or is a derived class of C2, T is an object 8658 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8659 // there exist candidate operator functions of the form 8660 // 8661 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8662 // 8663 // where CV12 is the union of CV1 and CV2. 8664 void addArrowStarOverloads() { 8665 for (BuiltinCandidateTypeSet::iterator 8666 Ptr = CandidateTypes[0].pointer_begin(), 8667 PtrEnd = CandidateTypes[0].pointer_end(); 8668 Ptr != PtrEnd; ++Ptr) { 8669 QualType C1Ty = (*Ptr); 8670 QualType C1; 8671 QualifierCollector Q1; 8672 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8673 if (!isa<RecordType>(C1)) 8674 continue; 8675 // heuristic to reduce number of builtin candidates in the set. 8676 // Add volatile/restrict version only if there are conversions to a 8677 // volatile/restrict type. 8678 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8679 continue; 8680 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8681 continue; 8682 for (BuiltinCandidateTypeSet::iterator 8683 MemPtr = CandidateTypes[1].member_pointer_begin(), 8684 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8685 MemPtr != MemPtrEnd; ++MemPtr) { 8686 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8687 QualType C2 = QualType(mptr->getClass(), 0); 8688 C2 = C2.getUnqualifiedType(); 8689 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8690 break; 8691 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8692 // build CV12 T& 8693 QualType T = mptr->getPointeeType(); 8694 if (!VisibleTypeConversionsQuals.hasVolatile() && 8695 T.isVolatileQualified()) 8696 continue; 8697 if (!VisibleTypeConversionsQuals.hasRestrict() && 8698 T.isRestrictQualified()) 8699 continue; 8700 T = Q1.apply(S.Context, T); 8701 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8702 } 8703 } 8704 } 8705 8706 // Note that we don't consider the first argument, since it has been 8707 // contextually converted to bool long ago. The candidates below are 8708 // therefore added as binary. 8709 // 8710 // C++ [over.built]p25: 8711 // For every type T, where T is a pointer, pointer-to-member, or scoped 8712 // enumeration type, there exist candidate operator functions of the form 8713 // 8714 // T operator?(bool, T, T); 8715 // 8716 void addConditionalOperatorOverloads() { 8717 /// Set of (canonical) types that we've already handled. 8718 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8719 8720 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8721 for (BuiltinCandidateTypeSet::iterator 8722 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8723 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8724 Ptr != PtrEnd; ++Ptr) { 8725 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8726 continue; 8727 8728 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8729 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8730 } 8731 8732 for (BuiltinCandidateTypeSet::iterator 8733 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8734 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8735 MemPtr != MemPtrEnd; ++MemPtr) { 8736 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8737 continue; 8738 8739 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8740 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8741 } 8742 8743 if (S.getLangOpts().CPlusPlus11) { 8744 for (BuiltinCandidateTypeSet::iterator 8745 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8746 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8747 Enum != EnumEnd; ++Enum) { 8748 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8749 continue; 8750 8751 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8752 continue; 8753 8754 QualType ParamTypes[2] = { *Enum, *Enum }; 8755 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8756 } 8757 } 8758 } 8759 } 8760 }; 8761 8762 } // end anonymous namespace 8763 8764 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8765 /// operator overloads to the candidate set (C++ [over.built]), based 8766 /// on the operator @p Op and the arguments given. For example, if the 8767 /// operator is a binary '+', this routine might add "int 8768 /// operator+(int, int)" to cover integer addition. 8769 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8770 SourceLocation OpLoc, 8771 ArrayRef<Expr *> Args, 8772 OverloadCandidateSet &CandidateSet) { 8773 // Find all of the types that the arguments can convert to, but only 8774 // if the operator we're looking at has built-in operator candidates 8775 // that make use of these types. Also record whether we encounter non-record 8776 // candidate types or either arithmetic or enumeral candidate types. 8777 Qualifiers VisibleTypeConversionsQuals; 8778 VisibleTypeConversionsQuals.addConst(); 8779 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8780 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8781 8782 bool HasNonRecordCandidateType = false; 8783 bool HasArithmeticOrEnumeralCandidateType = false; 8784 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8785 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8786 CandidateTypes.emplace_back(*this); 8787 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8788 OpLoc, 8789 true, 8790 (Op == OO_Exclaim || 8791 Op == OO_AmpAmp || 8792 Op == OO_PipePipe), 8793 VisibleTypeConversionsQuals); 8794 HasNonRecordCandidateType = HasNonRecordCandidateType || 8795 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8796 HasArithmeticOrEnumeralCandidateType = 8797 HasArithmeticOrEnumeralCandidateType || 8798 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8799 } 8800 8801 // Exit early when no non-record types have been added to the candidate set 8802 // for any of the arguments to the operator. 8803 // 8804 // We can't exit early for !, ||, or &&, since there we have always have 8805 // 'bool' overloads. 8806 if (!HasNonRecordCandidateType && 8807 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8808 return; 8809 8810 // Setup an object to manage the common state for building overloads. 8811 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8812 VisibleTypeConversionsQuals, 8813 HasArithmeticOrEnumeralCandidateType, 8814 CandidateTypes, CandidateSet); 8815 8816 // Dispatch over the operation to add in only those overloads which apply. 8817 switch (Op) { 8818 case OO_None: 8819 case NUM_OVERLOADED_OPERATORS: 8820 llvm_unreachable("Expected an overloaded operator"); 8821 8822 case OO_New: 8823 case OO_Delete: 8824 case OO_Array_New: 8825 case OO_Array_Delete: 8826 case OO_Call: 8827 llvm_unreachable( 8828 "Special operators don't use AddBuiltinOperatorCandidates"); 8829 8830 case OO_Comma: 8831 case OO_Arrow: 8832 case OO_Coawait: 8833 // C++ [over.match.oper]p3: 8834 // -- For the operator ',', the unary operator '&', the 8835 // operator '->', or the operator 'co_await', the 8836 // built-in candidates set is empty. 8837 break; 8838 8839 case OO_Plus: // '+' is either unary or binary 8840 if (Args.size() == 1) 8841 OpBuilder.addUnaryPlusPointerOverloads(); 8842 LLVM_FALLTHROUGH; 8843 8844 case OO_Minus: // '-' is either unary or binary 8845 if (Args.size() == 1) { 8846 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8847 } else { 8848 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8849 OpBuilder.addGenericBinaryArithmeticOverloads(); 8850 } 8851 break; 8852 8853 case OO_Star: // '*' is either unary or binary 8854 if (Args.size() == 1) 8855 OpBuilder.addUnaryStarPointerOverloads(); 8856 else 8857 OpBuilder.addGenericBinaryArithmeticOverloads(); 8858 break; 8859 8860 case OO_Slash: 8861 OpBuilder.addGenericBinaryArithmeticOverloads(); 8862 break; 8863 8864 case OO_PlusPlus: 8865 case OO_MinusMinus: 8866 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8867 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8868 break; 8869 8870 case OO_EqualEqual: 8871 case OO_ExclaimEqual: 8872 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8873 LLVM_FALLTHROUGH; 8874 8875 case OO_Less: 8876 case OO_Greater: 8877 case OO_LessEqual: 8878 case OO_GreaterEqual: 8879 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8880 OpBuilder.addGenericBinaryArithmeticOverloads(); 8881 break; 8882 8883 case OO_Spaceship: 8884 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8885 OpBuilder.addThreeWayArithmeticOverloads(); 8886 break; 8887 8888 case OO_Percent: 8889 case OO_Caret: 8890 case OO_Pipe: 8891 case OO_LessLess: 8892 case OO_GreaterGreater: 8893 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8894 break; 8895 8896 case OO_Amp: // '&' is either unary or binary 8897 if (Args.size() == 1) 8898 // C++ [over.match.oper]p3: 8899 // -- For the operator ',', the unary operator '&', or the 8900 // operator '->', the built-in candidates set is empty. 8901 break; 8902 8903 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8904 break; 8905 8906 case OO_Tilde: 8907 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8908 break; 8909 8910 case OO_Equal: 8911 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8912 LLVM_FALLTHROUGH; 8913 8914 case OO_PlusEqual: 8915 case OO_MinusEqual: 8916 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8917 LLVM_FALLTHROUGH; 8918 8919 case OO_StarEqual: 8920 case OO_SlashEqual: 8921 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8922 break; 8923 8924 case OO_PercentEqual: 8925 case OO_LessLessEqual: 8926 case OO_GreaterGreaterEqual: 8927 case OO_AmpEqual: 8928 case OO_CaretEqual: 8929 case OO_PipeEqual: 8930 OpBuilder.addAssignmentIntegralOverloads(); 8931 break; 8932 8933 case OO_Exclaim: 8934 OpBuilder.addExclaimOverload(); 8935 break; 8936 8937 case OO_AmpAmp: 8938 case OO_PipePipe: 8939 OpBuilder.addAmpAmpOrPipePipeOverload(); 8940 break; 8941 8942 case OO_Subscript: 8943 OpBuilder.addSubscriptOverloads(); 8944 break; 8945 8946 case OO_ArrowStar: 8947 OpBuilder.addArrowStarOverloads(); 8948 break; 8949 8950 case OO_Conditional: 8951 OpBuilder.addConditionalOperatorOverloads(); 8952 OpBuilder.addGenericBinaryArithmeticOverloads(); 8953 break; 8954 } 8955 } 8956 8957 /// Add function candidates found via argument-dependent lookup 8958 /// to the set of overloading candidates. 8959 /// 8960 /// This routine performs argument-dependent name lookup based on the 8961 /// given function name (which may also be an operator name) and adds 8962 /// all of the overload candidates found by ADL to the overload 8963 /// candidate set (C++ [basic.lookup.argdep]). 8964 void 8965 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8966 SourceLocation Loc, 8967 ArrayRef<Expr *> Args, 8968 TemplateArgumentListInfo *ExplicitTemplateArgs, 8969 OverloadCandidateSet& CandidateSet, 8970 bool PartialOverloading) { 8971 ADLResult Fns; 8972 8973 // FIXME: This approach for uniquing ADL results (and removing 8974 // redundant candidates from the set) relies on pointer-equality, 8975 // which means we need to key off the canonical decl. However, 8976 // always going back to the canonical decl might not get us the 8977 // right set of default arguments. What default arguments are 8978 // we supposed to consider on ADL candidates, anyway? 8979 8980 // FIXME: Pass in the explicit template arguments? 8981 ArgumentDependentLookup(Name, Loc, Args, Fns); 8982 8983 // Erase all of the candidates we already knew about. 8984 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8985 CandEnd = CandidateSet.end(); 8986 Cand != CandEnd; ++Cand) 8987 if (Cand->Function) { 8988 Fns.erase(Cand->Function); 8989 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8990 Fns.erase(FunTmpl); 8991 } 8992 8993 // For each of the ADL candidates we found, add it to the overload 8994 // set. 8995 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8996 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8997 8998 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8999 if (ExplicitTemplateArgs) 9000 continue; 9001 9002 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, 9003 /*SupressUserConversions=*/false, PartialOverloading, 9004 /*AllowExplicit=*/false, ADLCallKind::UsesADL); 9005 } else { 9006 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), FoundDecl, 9007 ExplicitTemplateArgs, Args, CandidateSet, 9008 /*SupressUserConversions=*/false, 9009 PartialOverloading, ADLCallKind::UsesADL); 9010 } 9011 } 9012 } 9013 9014 namespace { 9015 enum class Comparison { Equal, Better, Worse }; 9016 } 9017 9018 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9019 /// overload resolution. 9020 /// 9021 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9022 /// Cand1's first N enable_if attributes have precisely the same conditions as 9023 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9024 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9025 /// 9026 /// Note that you can have a pair of candidates such that Cand1's enable_if 9027 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9028 /// worse than Cand1's. 9029 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9030 const FunctionDecl *Cand2) { 9031 // Common case: One (or both) decls don't have enable_if attrs. 9032 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9033 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9034 if (!Cand1Attr || !Cand2Attr) { 9035 if (Cand1Attr == Cand2Attr) 9036 return Comparison::Equal; 9037 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9038 } 9039 9040 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9041 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9042 9043 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9044 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9045 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9046 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9047 9048 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9049 // has fewer enable_if attributes than Cand2, and vice versa. 9050 if (!Cand1A) 9051 return Comparison::Worse; 9052 if (!Cand2A) 9053 return Comparison::Better; 9054 9055 Cand1ID.clear(); 9056 Cand2ID.clear(); 9057 9058 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9059 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9060 if (Cand1ID != Cand2ID) 9061 return Comparison::Worse; 9062 } 9063 9064 return Comparison::Equal; 9065 } 9066 9067 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9068 const OverloadCandidate &Cand2) { 9069 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9070 !Cand2.Function->isMultiVersion()) 9071 return false; 9072 9073 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9074 // is obviously better. 9075 if (Cand1.Function->isInvalidDecl()) return false; 9076 if (Cand2.Function->isInvalidDecl()) return true; 9077 9078 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9079 // cpu_dispatch, else arbitrarily based on the identifiers. 9080 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9081 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9082 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9083 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9084 9085 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9086 return false; 9087 9088 if (Cand1CPUDisp && !Cand2CPUDisp) 9089 return true; 9090 if (Cand2CPUDisp && !Cand1CPUDisp) 9091 return false; 9092 9093 if (Cand1CPUSpec && Cand2CPUSpec) { 9094 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9095 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9096 9097 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9098 FirstDiff = std::mismatch( 9099 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9100 Cand2CPUSpec->cpus_begin(), 9101 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9102 return LHS->getName() == RHS->getName(); 9103 }); 9104 9105 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9106 "Two different cpu-specific versions should not have the same " 9107 "identifier list, otherwise they'd be the same decl!"); 9108 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9109 } 9110 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9111 } 9112 9113 /// isBetterOverloadCandidate - Determines whether the first overload 9114 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9115 bool clang::isBetterOverloadCandidate( 9116 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9117 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9118 // Define viable functions to be better candidates than non-viable 9119 // functions. 9120 if (!Cand2.Viable) 9121 return Cand1.Viable; 9122 else if (!Cand1.Viable) 9123 return false; 9124 9125 // C++ [over.match.best]p1: 9126 // 9127 // -- if F is a static member function, ICS1(F) is defined such 9128 // that ICS1(F) is neither better nor worse than ICS1(G) for 9129 // any function G, and, symmetrically, ICS1(G) is neither 9130 // better nor worse than ICS1(F). 9131 unsigned StartArg = 0; 9132 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9133 StartArg = 1; 9134 9135 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9136 // We don't allow incompatible pointer conversions in C++. 9137 if (!S.getLangOpts().CPlusPlus) 9138 return ICS.isStandard() && 9139 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9140 9141 // The only ill-formed conversion we allow in C++ is the string literal to 9142 // char* conversion, which is only considered ill-formed after C++11. 9143 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9144 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9145 }; 9146 9147 // Define functions that don't require ill-formed conversions for a given 9148 // argument to be better candidates than functions that do. 9149 unsigned NumArgs = Cand1.Conversions.size(); 9150 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9151 bool HasBetterConversion = false; 9152 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9153 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9154 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9155 if (Cand1Bad != Cand2Bad) { 9156 if (Cand1Bad) 9157 return false; 9158 HasBetterConversion = true; 9159 } 9160 } 9161 9162 if (HasBetterConversion) 9163 return true; 9164 9165 // C++ [over.match.best]p1: 9166 // A viable function F1 is defined to be a better function than another 9167 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9168 // conversion sequence than ICSi(F2), and then... 9169 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9170 switch (CompareImplicitConversionSequences(S, Loc, 9171 Cand1.Conversions[ArgIdx], 9172 Cand2.Conversions[ArgIdx])) { 9173 case ImplicitConversionSequence::Better: 9174 // Cand1 has a better conversion sequence. 9175 HasBetterConversion = true; 9176 break; 9177 9178 case ImplicitConversionSequence::Worse: 9179 // Cand1 can't be better than Cand2. 9180 return false; 9181 9182 case ImplicitConversionSequence::Indistinguishable: 9183 // Do nothing. 9184 break; 9185 } 9186 } 9187 9188 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9189 // ICSj(F2), or, if not that, 9190 if (HasBetterConversion) 9191 return true; 9192 9193 // -- the context is an initialization by user-defined conversion 9194 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9195 // from the return type of F1 to the destination type (i.e., 9196 // the type of the entity being initialized) is a better 9197 // conversion sequence than the standard conversion sequence 9198 // from the return type of F2 to the destination type. 9199 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9200 Cand1.Function && Cand2.Function && 9201 isa<CXXConversionDecl>(Cand1.Function) && 9202 isa<CXXConversionDecl>(Cand2.Function)) { 9203 // First check whether we prefer one of the conversion functions over the 9204 // other. This only distinguishes the results in non-standard, extension 9205 // cases such as the conversion from a lambda closure type to a function 9206 // pointer or block. 9207 ImplicitConversionSequence::CompareKind Result = 9208 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9209 if (Result == ImplicitConversionSequence::Indistinguishable) 9210 Result = CompareStandardConversionSequences(S, Loc, 9211 Cand1.FinalConversion, 9212 Cand2.FinalConversion); 9213 9214 if (Result != ImplicitConversionSequence::Indistinguishable) 9215 return Result == ImplicitConversionSequence::Better; 9216 9217 // FIXME: Compare kind of reference binding if conversion functions 9218 // convert to a reference type used in direct reference binding, per 9219 // C++14 [over.match.best]p1 section 2 bullet 3. 9220 } 9221 9222 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9223 // as combined with the resolution to CWG issue 243. 9224 // 9225 // When the context is initialization by constructor ([over.match.ctor] or 9226 // either phase of [over.match.list]), a constructor is preferred over 9227 // a conversion function. 9228 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9229 Cand1.Function && Cand2.Function && 9230 isa<CXXConstructorDecl>(Cand1.Function) != 9231 isa<CXXConstructorDecl>(Cand2.Function)) 9232 return isa<CXXConstructorDecl>(Cand1.Function); 9233 9234 // -- F1 is a non-template function and F2 is a function template 9235 // specialization, or, if not that, 9236 bool Cand1IsSpecialization = Cand1.Function && 9237 Cand1.Function->getPrimaryTemplate(); 9238 bool Cand2IsSpecialization = Cand2.Function && 9239 Cand2.Function->getPrimaryTemplate(); 9240 if (Cand1IsSpecialization != Cand2IsSpecialization) 9241 return Cand2IsSpecialization; 9242 9243 // -- F1 and F2 are function template specializations, and the function 9244 // template for F1 is more specialized than the template for F2 9245 // according to the partial ordering rules described in 14.5.5.2, or, 9246 // if not that, 9247 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9248 if (FunctionTemplateDecl *BetterTemplate 9249 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9250 Cand2.Function->getPrimaryTemplate(), 9251 Loc, 9252 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9253 : TPOC_Call, 9254 Cand1.ExplicitCallArguments, 9255 Cand2.ExplicitCallArguments)) 9256 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9257 } 9258 9259 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9260 // A derived-class constructor beats an (inherited) base class constructor. 9261 bool Cand1IsInherited = 9262 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9263 bool Cand2IsInherited = 9264 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9265 if (Cand1IsInherited != Cand2IsInherited) 9266 return Cand2IsInherited; 9267 else if (Cand1IsInherited) { 9268 assert(Cand2IsInherited); 9269 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9270 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9271 if (Cand1Class->isDerivedFrom(Cand2Class)) 9272 return true; 9273 if (Cand2Class->isDerivedFrom(Cand1Class)) 9274 return false; 9275 // Inherited from sibling base classes: still ambiguous. 9276 } 9277 9278 // Check C++17 tie-breakers for deduction guides. 9279 { 9280 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9281 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9282 if (Guide1 && Guide2) { 9283 // -- F1 is generated from a deduction-guide and F2 is not 9284 if (Guide1->isImplicit() != Guide2->isImplicit()) 9285 return Guide2->isImplicit(); 9286 9287 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9288 if (Guide1->isCopyDeductionCandidate()) 9289 return true; 9290 } 9291 } 9292 9293 // Check for enable_if value-based overload resolution. 9294 if (Cand1.Function && Cand2.Function) { 9295 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9296 if (Cmp != Comparison::Equal) 9297 return Cmp == Comparison::Better; 9298 } 9299 9300 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9301 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9302 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9303 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9304 } 9305 9306 bool HasPS1 = Cand1.Function != nullptr && 9307 functionHasPassObjectSizeParams(Cand1.Function); 9308 bool HasPS2 = Cand2.Function != nullptr && 9309 functionHasPassObjectSizeParams(Cand2.Function); 9310 if (HasPS1 != HasPS2 && HasPS1) 9311 return true; 9312 9313 return isBetterMultiversionCandidate(Cand1, Cand2); 9314 } 9315 9316 /// Determine whether two declarations are "equivalent" for the purposes of 9317 /// name lookup and overload resolution. This applies when the same internal/no 9318 /// linkage entity is defined by two modules (probably by textually including 9319 /// the same header). In such a case, we don't consider the declarations to 9320 /// declare the same entity, but we also don't want lookups with both 9321 /// declarations visible to be ambiguous in some cases (this happens when using 9322 /// a modularized libstdc++). 9323 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9324 const NamedDecl *B) { 9325 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9326 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9327 if (!VA || !VB) 9328 return false; 9329 9330 // The declarations must be declaring the same name as an internal linkage 9331 // entity in different modules. 9332 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9333 VB->getDeclContext()->getRedeclContext()) || 9334 getOwningModule(const_cast<ValueDecl *>(VA)) == 9335 getOwningModule(const_cast<ValueDecl *>(VB)) || 9336 VA->isExternallyVisible() || VB->isExternallyVisible()) 9337 return false; 9338 9339 // Check that the declarations appear to be equivalent. 9340 // 9341 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9342 // For constants and functions, we should check the initializer or body is 9343 // the same. For non-constant variables, we shouldn't allow it at all. 9344 if (Context.hasSameType(VA->getType(), VB->getType())) 9345 return true; 9346 9347 // Enum constants within unnamed enumerations will have different types, but 9348 // may still be similar enough to be interchangeable for our purposes. 9349 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9350 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9351 // Only handle anonymous enums. If the enumerations were named and 9352 // equivalent, they would have been merged to the same type. 9353 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9354 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9355 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9356 !Context.hasSameType(EnumA->getIntegerType(), 9357 EnumB->getIntegerType())) 9358 return false; 9359 // Allow this only if the value is the same for both enumerators. 9360 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9361 } 9362 } 9363 9364 // Nothing else is sufficiently similar. 9365 return false; 9366 } 9367 9368 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9369 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9370 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9371 9372 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9373 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9374 << !M << (M ? M->getFullModuleName() : ""); 9375 9376 for (auto *E : Equiv) { 9377 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9378 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9379 << !M << (M ? M->getFullModuleName() : ""); 9380 } 9381 } 9382 9383 /// Computes the best viable function (C++ 13.3.3) 9384 /// within an overload candidate set. 9385 /// 9386 /// \param Loc The location of the function name (or operator symbol) for 9387 /// which overload resolution occurs. 9388 /// 9389 /// \param Best If overload resolution was successful or found a deleted 9390 /// function, \p Best points to the candidate function found. 9391 /// 9392 /// \returns The result of overload resolution. 9393 OverloadingResult 9394 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9395 iterator &Best) { 9396 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9397 std::transform(begin(), end(), std::back_inserter(Candidates), 9398 [](OverloadCandidate &Cand) { return &Cand; }); 9399 9400 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9401 // are accepted by both clang and NVCC. However, during a particular 9402 // compilation mode only one call variant is viable. We need to 9403 // exclude non-viable overload candidates from consideration based 9404 // only on their host/device attributes. Specifically, if one 9405 // candidate call is WrongSide and the other is SameSide, we ignore 9406 // the WrongSide candidate. 9407 if (S.getLangOpts().CUDA) { 9408 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9409 bool ContainsSameSideCandidate = 9410 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9411 return Cand->Function && 9412 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9413 Sema::CFP_SameSide; 9414 }); 9415 if (ContainsSameSideCandidate) { 9416 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9417 return Cand->Function && 9418 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9419 Sema::CFP_WrongSide; 9420 }; 9421 llvm::erase_if(Candidates, IsWrongSideCandidate); 9422 } 9423 } 9424 9425 // Find the best viable function. 9426 Best = end(); 9427 for (auto *Cand : Candidates) 9428 if (Cand->Viable) 9429 if (Best == end() || 9430 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9431 Best = Cand; 9432 9433 // If we didn't find any viable functions, abort. 9434 if (Best == end()) 9435 return OR_No_Viable_Function; 9436 9437 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9438 9439 // Make sure that this function is better than every other viable 9440 // function. If not, we have an ambiguity. 9441 for (auto *Cand : Candidates) { 9442 if (Cand->Viable && Cand != Best && 9443 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { 9444 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9445 Cand->Function)) { 9446 EquivalentCands.push_back(Cand->Function); 9447 continue; 9448 } 9449 9450 Best = end(); 9451 return OR_Ambiguous; 9452 } 9453 } 9454 9455 // Best is the best viable function. 9456 if (Best->Function && 9457 (Best->Function->isDeleted() || 9458 S.isFunctionConsideredUnavailable(Best->Function))) 9459 return OR_Deleted; 9460 9461 if (!EquivalentCands.empty()) 9462 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9463 EquivalentCands); 9464 9465 return OR_Success; 9466 } 9467 9468 namespace { 9469 9470 enum OverloadCandidateKind { 9471 oc_function, 9472 oc_method, 9473 oc_constructor, 9474 oc_implicit_default_constructor, 9475 oc_implicit_copy_constructor, 9476 oc_implicit_move_constructor, 9477 oc_implicit_copy_assignment, 9478 oc_implicit_move_assignment, 9479 oc_inherited_constructor 9480 }; 9481 9482 enum OverloadCandidateSelect { 9483 ocs_non_template, 9484 ocs_template, 9485 ocs_described_template, 9486 }; 9487 9488 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9489 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9490 std::string &Description) { 9491 9492 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9493 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9494 isTemplate = true; 9495 Description = S.getTemplateArgumentBindingsText( 9496 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9497 } 9498 9499 OverloadCandidateSelect Select = [&]() { 9500 if (!Description.empty()) 9501 return ocs_described_template; 9502 return isTemplate ? ocs_template : ocs_non_template; 9503 }(); 9504 9505 OverloadCandidateKind Kind = [&]() { 9506 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9507 if (!Ctor->isImplicit()) { 9508 if (isa<ConstructorUsingShadowDecl>(Found)) 9509 return oc_inherited_constructor; 9510 else 9511 return oc_constructor; 9512 } 9513 9514 if (Ctor->isDefaultConstructor()) 9515 return oc_implicit_default_constructor; 9516 9517 if (Ctor->isMoveConstructor()) 9518 return oc_implicit_move_constructor; 9519 9520 assert(Ctor->isCopyConstructor() && 9521 "unexpected sort of implicit constructor"); 9522 return oc_implicit_copy_constructor; 9523 } 9524 9525 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9526 // This actually gets spelled 'candidate function' for now, but 9527 // it doesn't hurt to split it out. 9528 if (!Meth->isImplicit()) 9529 return oc_method; 9530 9531 if (Meth->isMoveAssignmentOperator()) 9532 return oc_implicit_move_assignment; 9533 9534 if (Meth->isCopyAssignmentOperator()) 9535 return oc_implicit_copy_assignment; 9536 9537 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9538 return oc_method; 9539 } 9540 9541 return oc_function; 9542 }(); 9543 9544 return std::make_pair(Kind, Select); 9545 } 9546 9547 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9548 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9549 // set. 9550 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9551 S.Diag(FoundDecl->getLocation(), 9552 diag::note_ovl_candidate_inherited_constructor) 9553 << Shadow->getNominatedBaseClass(); 9554 } 9555 9556 } // end anonymous namespace 9557 9558 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9559 const FunctionDecl *FD) { 9560 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9561 bool AlwaysTrue; 9562 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9563 return false; 9564 if (!AlwaysTrue) 9565 return false; 9566 } 9567 return true; 9568 } 9569 9570 /// Returns true if we can take the address of the function. 9571 /// 9572 /// \param Complain - If true, we'll emit a diagnostic 9573 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9574 /// we in overload resolution? 9575 /// \param Loc - The location of the statement we're complaining about. Ignored 9576 /// if we're not complaining, or if we're in overload resolution. 9577 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9578 bool Complain, 9579 bool InOverloadResolution, 9580 SourceLocation Loc) { 9581 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9582 if (Complain) { 9583 if (InOverloadResolution) 9584 S.Diag(FD->getBeginLoc(), 9585 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9586 else 9587 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9588 } 9589 return false; 9590 } 9591 9592 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9593 return P->hasAttr<PassObjectSizeAttr>(); 9594 }); 9595 if (I == FD->param_end()) 9596 return true; 9597 9598 if (Complain) { 9599 // Add one to ParamNo because it's user-facing 9600 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9601 if (InOverloadResolution) 9602 S.Diag(FD->getLocation(), 9603 diag::note_ovl_candidate_has_pass_object_size_params) 9604 << ParamNo; 9605 else 9606 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9607 << FD << ParamNo; 9608 } 9609 return false; 9610 } 9611 9612 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9613 const FunctionDecl *FD) { 9614 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9615 /*InOverloadResolution=*/true, 9616 /*Loc=*/SourceLocation()); 9617 } 9618 9619 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9620 bool Complain, 9621 SourceLocation Loc) { 9622 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9623 /*InOverloadResolution=*/false, 9624 Loc); 9625 } 9626 9627 // Notes the location of an overload candidate. 9628 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9629 QualType DestType, bool TakingAddress) { 9630 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9631 return; 9632 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9633 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9634 return; 9635 9636 std::string FnDesc; 9637 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9638 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9639 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9640 << (unsigned)KSPair.first << (unsigned)KSPair.second 9641 << Fn << FnDesc; 9642 9643 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9644 Diag(Fn->getLocation(), PD); 9645 MaybeEmitInheritedConstructorNote(*this, Found); 9646 } 9647 9648 // Notes the location of all overload candidates designated through 9649 // OverloadedExpr 9650 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9651 bool TakingAddress) { 9652 assert(OverloadedExpr->getType() == Context.OverloadTy); 9653 9654 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9655 OverloadExpr *OvlExpr = Ovl.Expression; 9656 9657 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9658 IEnd = OvlExpr->decls_end(); 9659 I != IEnd; ++I) { 9660 if (FunctionTemplateDecl *FunTmpl = 9661 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9662 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9663 TakingAddress); 9664 } else if (FunctionDecl *Fun 9665 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9666 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9667 } 9668 } 9669 } 9670 9671 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9672 /// "lead" diagnostic; it will be given two arguments, the source and 9673 /// target types of the conversion. 9674 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9675 Sema &S, 9676 SourceLocation CaretLoc, 9677 const PartialDiagnostic &PDiag) const { 9678 S.Diag(CaretLoc, PDiag) 9679 << Ambiguous.getFromType() << Ambiguous.getToType(); 9680 // FIXME: The note limiting machinery is borrowed from 9681 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9682 // refactoring here. 9683 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9684 unsigned CandsShown = 0; 9685 AmbiguousConversionSequence::const_iterator I, E; 9686 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9687 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9688 break; 9689 ++CandsShown; 9690 S.NoteOverloadCandidate(I->first, I->second); 9691 } 9692 if (I != E) 9693 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9694 } 9695 9696 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9697 unsigned I, bool TakingCandidateAddress) { 9698 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9699 assert(Conv.isBad()); 9700 assert(Cand->Function && "for now, candidate must be a function"); 9701 FunctionDecl *Fn = Cand->Function; 9702 9703 // There's a conversion slot for the object argument if this is a 9704 // non-constructor method. Note that 'I' corresponds the 9705 // conversion-slot index. 9706 bool isObjectArgument = false; 9707 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9708 if (I == 0) 9709 isObjectArgument = true; 9710 else 9711 I--; 9712 } 9713 9714 std::string FnDesc; 9715 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9716 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9717 9718 Expr *FromExpr = Conv.Bad.FromExpr; 9719 QualType FromTy = Conv.Bad.getFromType(); 9720 QualType ToTy = Conv.Bad.getToType(); 9721 9722 if (FromTy == S.Context.OverloadTy) { 9723 assert(FromExpr && "overload set argument came from implicit argument?"); 9724 Expr *E = FromExpr->IgnoreParens(); 9725 if (isa<UnaryOperator>(E)) 9726 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9727 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9728 9729 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9730 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9731 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9732 << Name << I + 1; 9733 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9734 return; 9735 } 9736 9737 // Do some hand-waving analysis to see if the non-viability is due 9738 // to a qualifier mismatch. 9739 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9740 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9741 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9742 CToTy = RT->getPointeeType(); 9743 else { 9744 // TODO: detect and diagnose the full richness of const mismatches. 9745 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9746 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9747 CFromTy = FromPT->getPointeeType(); 9748 CToTy = ToPT->getPointeeType(); 9749 } 9750 } 9751 9752 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9753 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9754 Qualifiers FromQs = CFromTy.getQualifiers(); 9755 Qualifiers ToQs = CToTy.getQualifiers(); 9756 9757 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9758 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9759 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9760 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9761 << ToTy << (unsigned)isObjectArgument << I + 1; 9762 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9763 return; 9764 } 9765 9766 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9767 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9768 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9769 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9770 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9771 << (unsigned)isObjectArgument << I + 1; 9772 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9773 return; 9774 } 9775 9776 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9777 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9778 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9779 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9780 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9781 << (unsigned)isObjectArgument << I + 1; 9782 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9783 return; 9784 } 9785 9786 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9787 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9788 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9789 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9790 << FromQs.hasUnaligned() << I + 1; 9791 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9792 return; 9793 } 9794 9795 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9796 assert(CVR && "unexpected qualifiers mismatch"); 9797 9798 if (isObjectArgument) { 9799 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9800 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9801 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9802 << (CVR - 1); 9803 } else { 9804 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9805 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9806 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9807 << (CVR - 1) << I + 1; 9808 } 9809 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9810 return; 9811 } 9812 9813 // Special diagnostic for failure to convert an initializer list, since 9814 // telling the user that it has type void is not useful. 9815 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9816 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9817 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9818 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9819 << ToTy << (unsigned)isObjectArgument << I + 1; 9820 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9821 return; 9822 } 9823 9824 // Diagnose references or pointers to incomplete types differently, 9825 // since it's far from impossible that the incompleteness triggered 9826 // the failure. 9827 QualType TempFromTy = FromTy.getNonReferenceType(); 9828 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9829 TempFromTy = PTy->getPointeeType(); 9830 if (TempFromTy->isIncompleteType()) { 9831 // Emit the generic diagnostic and, optionally, add the hints to it. 9832 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9833 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9834 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9835 << ToTy << (unsigned)isObjectArgument << I + 1 9836 << (unsigned)(Cand->Fix.Kind); 9837 9838 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9839 return; 9840 } 9841 9842 // Diagnose base -> derived pointer conversions. 9843 unsigned BaseToDerivedConversion = 0; 9844 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9845 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9846 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9847 FromPtrTy->getPointeeType()) && 9848 !FromPtrTy->getPointeeType()->isIncompleteType() && 9849 !ToPtrTy->getPointeeType()->isIncompleteType() && 9850 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9851 FromPtrTy->getPointeeType())) 9852 BaseToDerivedConversion = 1; 9853 } 9854 } else if (const ObjCObjectPointerType *FromPtrTy 9855 = FromTy->getAs<ObjCObjectPointerType>()) { 9856 if (const ObjCObjectPointerType *ToPtrTy 9857 = ToTy->getAs<ObjCObjectPointerType>()) 9858 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9859 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9860 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9861 FromPtrTy->getPointeeType()) && 9862 FromIface->isSuperClassOf(ToIface)) 9863 BaseToDerivedConversion = 2; 9864 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9865 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9866 !FromTy->isIncompleteType() && 9867 !ToRefTy->getPointeeType()->isIncompleteType() && 9868 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9869 BaseToDerivedConversion = 3; 9870 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9871 ToTy.getNonReferenceType().getCanonicalType() == 9872 FromTy.getNonReferenceType().getCanonicalType()) { 9873 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9874 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9875 << (unsigned)isObjectArgument << I + 1 9876 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 9877 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9878 return; 9879 } 9880 } 9881 9882 if (BaseToDerivedConversion) { 9883 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 9884 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9885 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9886 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 9887 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9888 return; 9889 } 9890 9891 if (isa<ObjCObjectPointerType>(CFromTy) && 9892 isa<PointerType>(CToTy)) { 9893 Qualifiers FromQs = CFromTy.getQualifiers(); 9894 Qualifiers ToQs = CToTy.getQualifiers(); 9895 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9896 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9897 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9898 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9899 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 9900 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9901 return; 9902 } 9903 } 9904 9905 if (TakingCandidateAddress && 9906 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9907 return; 9908 9909 // Emit the generic diagnostic and, optionally, add the hints to it. 9910 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9911 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9912 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9913 << ToTy << (unsigned)isObjectArgument << I + 1 9914 << (unsigned)(Cand->Fix.Kind); 9915 9916 // If we can fix the conversion, suggest the FixIts. 9917 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9918 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9919 FDiag << *HI; 9920 S.Diag(Fn->getLocation(), FDiag); 9921 9922 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9923 } 9924 9925 /// Additional arity mismatch diagnosis specific to a function overload 9926 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9927 /// over a candidate in any candidate set. 9928 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9929 unsigned NumArgs) { 9930 FunctionDecl *Fn = Cand->Function; 9931 unsigned MinParams = Fn->getMinRequiredArguments(); 9932 9933 // With invalid overloaded operators, it's possible that we think we 9934 // have an arity mismatch when in fact it looks like we have the 9935 // right number of arguments, because only overloaded operators have 9936 // the weird behavior of overloading member and non-member functions. 9937 // Just don't report anything. 9938 if (Fn->isInvalidDecl() && 9939 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9940 return true; 9941 9942 if (NumArgs < MinParams) { 9943 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9944 (Cand->FailureKind == ovl_fail_bad_deduction && 9945 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9946 } else { 9947 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9948 (Cand->FailureKind == ovl_fail_bad_deduction && 9949 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9950 } 9951 9952 return false; 9953 } 9954 9955 /// General arity mismatch diagnosis over a candidate in a candidate set. 9956 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9957 unsigned NumFormalArgs) { 9958 assert(isa<FunctionDecl>(D) && 9959 "The templated declaration should at least be a function" 9960 " when diagnosing bad template argument deduction due to too many" 9961 " or too few arguments"); 9962 9963 FunctionDecl *Fn = cast<FunctionDecl>(D); 9964 9965 // TODO: treat calls to a missing default constructor as a special case 9966 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9967 unsigned MinParams = Fn->getMinRequiredArguments(); 9968 9969 // at least / at most / exactly 9970 unsigned mode, modeCount; 9971 if (NumFormalArgs < MinParams) { 9972 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9973 FnTy->isTemplateVariadic()) 9974 mode = 0; // "at least" 9975 else 9976 mode = 2; // "exactly" 9977 modeCount = MinParams; 9978 } else { 9979 if (MinParams != FnTy->getNumParams()) 9980 mode = 1; // "at most" 9981 else 9982 mode = 2; // "exactly" 9983 modeCount = FnTy->getNumParams(); 9984 } 9985 9986 std::string Description; 9987 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9988 ClassifyOverloadCandidate(S, Found, Fn, Description); 9989 9990 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9991 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9992 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9993 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 9994 else 9995 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9996 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9997 << Description << mode << modeCount << NumFormalArgs; 9998 9999 MaybeEmitInheritedConstructorNote(S, Found); 10000 } 10001 10002 /// Arity mismatch diagnosis specific to a function overload candidate. 10003 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10004 unsigned NumFormalArgs) { 10005 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10006 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10007 } 10008 10009 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10010 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10011 return TD; 10012 llvm_unreachable("Unsupported: Getting the described template declaration" 10013 " for bad deduction diagnosis"); 10014 } 10015 10016 /// Diagnose a failed template-argument deduction. 10017 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10018 DeductionFailureInfo &DeductionFailure, 10019 unsigned NumArgs, 10020 bool TakingCandidateAddress) { 10021 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10022 NamedDecl *ParamD; 10023 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10024 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10025 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10026 switch (DeductionFailure.Result) { 10027 case Sema::TDK_Success: 10028 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10029 10030 case Sema::TDK_Incomplete: { 10031 assert(ParamD && "no parameter found for incomplete deduction result"); 10032 S.Diag(Templated->getLocation(), 10033 diag::note_ovl_candidate_incomplete_deduction) 10034 << ParamD->getDeclName(); 10035 MaybeEmitInheritedConstructorNote(S, Found); 10036 return; 10037 } 10038 10039 case Sema::TDK_IncompletePack: { 10040 assert(ParamD && "no parameter found for incomplete deduction result"); 10041 S.Diag(Templated->getLocation(), 10042 diag::note_ovl_candidate_incomplete_deduction_pack) 10043 << ParamD->getDeclName() 10044 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10045 << *DeductionFailure.getFirstArg(); 10046 MaybeEmitInheritedConstructorNote(S, Found); 10047 return; 10048 } 10049 10050 case Sema::TDK_Underqualified: { 10051 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10052 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10053 10054 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10055 10056 // Param will have been canonicalized, but it should just be a 10057 // qualified version of ParamD, so move the qualifiers to that. 10058 QualifierCollector Qs; 10059 Qs.strip(Param); 10060 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10061 assert(S.Context.hasSameType(Param, NonCanonParam)); 10062 10063 // Arg has also been canonicalized, but there's nothing we can do 10064 // about that. It also doesn't matter as much, because it won't 10065 // have any template parameters in it (because deduction isn't 10066 // done on dependent types). 10067 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10068 10069 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10070 << ParamD->getDeclName() << Arg << NonCanonParam; 10071 MaybeEmitInheritedConstructorNote(S, Found); 10072 return; 10073 } 10074 10075 case Sema::TDK_Inconsistent: { 10076 assert(ParamD && "no parameter found for inconsistent deduction result"); 10077 int which = 0; 10078 if (isa<TemplateTypeParmDecl>(ParamD)) 10079 which = 0; 10080 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10081 // Deduction might have failed because we deduced arguments of two 10082 // different types for a non-type template parameter. 10083 // FIXME: Use a different TDK value for this. 10084 QualType T1 = 10085 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10086 QualType T2 = 10087 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10088 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10089 S.Diag(Templated->getLocation(), 10090 diag::note_ovl_candidate_inconsistent_deduction_types) 10091 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10092 << *DeductionFailure.getSecondArg() << T2; 10093 MaybeEmitInheritedConstructorNote(S, Found); 10094 return; 10095 } 10096 10097 which = 1; 10098 } else { 10099 which = 2; 10100 } 10101 10102 S.Diag(Templated->getLocation(), 10103 diag::note_ovl_candidate_inconsistent_deduction) 10104 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10105 << *DeductionFailure.getSecondArg(); 10106 MaybeEmitInheritedConstructorNote(S, Found); 10107 return; 10108 } 10109 10110 case Sema::TDK_InvalidExplicitArguments: 10111 assert(ParamD && "no parameter found for invalid explicit arguments"); 10112 if (ParamD->getDeclName()) 10113 S.Diag(Templated->getLocation(), 10114 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10115 << ParamD->getDeclName(); 10116 else { 10117 int index = 0; 10118 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10119 index = TTP->getIndex(); 10120 else if (NonTypeTemplateParmDecl *NTTP 10121 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10122 index = NTTP->getIndex(); 10123 else 10124 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10125 S.Diag(Templated->getLocation(), 10126 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10127 << (index + 1); 10128 } 10129 MaybeEmitInheritedConstructorNote(S, Found); 10130 return; 10131 10132 case Sema::TDK_TooManyArguments: 10133 case Sema::TDK_TooFewArguments: 10134 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10135 return; 10136 10137 case Sema::TDK_InstantiationDepth: 10138 S.Diag(Templated->getLocation(), 10139 diag::note_ovl_candidate_instantiation_depth); 10140 MaybeEmitInheritedConstructorNote(S, Found); 10141 return; 10142 10143 case Sema::TDK_SubstitutionFailure: { 10144 // Format the template argument list into the argument string. 10145 SmallString<128> TemplateArgString; 10146 if (TemplateArgumentList *Args = 10147 DeductionFailure.getTemplateArgumentList()) { 10148 TemplateArgString = " "; 10149 TemplateArgString += S.getTemplateArgumentBindingsText( 10150 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10151 } 10152 10153 // If this candidate was disabled by enable_if, say so. 10154 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10155 if (PDiag && PDiag->second.getDiagID() == 10156 diag::err_typename_nested_not_found_enable_if) { 10157 // FIXME: Use the source range of the condition, and the fully-qualified 10158 // name of the enable_if template. These are both present in PDiag. 10159 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10160 << "'enable_if'" << TemplateArgString; 10161 return; 10162 } 10163 10164 // We found a specific requirement that disabled the enable_if. 10165 if (PDiag && PDiag->second.getDiagID() == 10166 diag::err_typename_nested_not_found_requirement) { 10167 S.Diag(Templated->getLocation(), 10168 diag::note_ovl_candidate_disabled_by_requirement) 10169 << PDiag->second.getStringArg(0) << TemplateArgString; 10170 return; 10171 } 10172 10173 // Format the SFINAE diagnostic into the argument string. 10174 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10175 // formatted message in another diagnostic. 10176 SmallString<128> SFINAEArgString; 10177 SourceRange R; 10178 if (PDiag) { 10179 SFINAEArgString = ": "; 10180 R = SourceRange(PDiag->first, PDiag->first); 10181 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10182 } 10183 10184 S.Diag(Templated->getLocation(), 10185 diag::note_ovl_candidate_substitution_failure) 10186 << TemplateArgString << SFINAEArgString << R; 10187 MaybeEmitInheritedConstructorNote(S, Found); 10188 return; 10189 } 10190 10191 case Sema::TDK_DeducedMismatch: 10192 case Sema::TDK_DeducedMismatchNested: { 10193 // Format the template argument list into the argument string. 10194 SmallString<128> TemplateArgString; 10195 if (TemplateArgumentList *Args = 10196 DeductionFailure.getTemplateArgumentList()) { 10197 TemplateArgString = " "; 10198 TemplateArgString += S.getTemplateArgumentBindingsText( 10199 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10200 } 10201 10202 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10203 << (*DeductionFailure.getCallArgIndex() + 1) 10204 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10205 << TemplateArgString 10206 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10207 break; 10208 } 10209 10210 case Sema::TDK_NonDeducedMismatch: { 10211 // FIXME: Provide a source location to indicate what we couldn't match. 10212 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10213 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10214 if (FirstTA.getKind() == TemplateArgument::Template && 10215 SecondTA.getKind() == TemplateArgument::Template) { 10216 TemplateName FirstTN = FirstTA.getAsTemplate(); 10217 TemplateName SecondTN = SecondTA.getAsTemplate(); 10218 if (FirstTN.getKind() == TemplateName::Template && 10219 SecondTN.getKind() == TemplateName::Template) { 10220 if (FirstTN.getAsTemplateDecl()->getName() == 10221 SecondTN.getAsTemplateDecl()->getName()) { 10222 // FIXME: This fixes a bad diagnostic where both templates are named 10223 // the same. This particular case is a bit difficult since: 10224 // 1) It is passed as a string to the diagnostic printer. 10225 // 2) The diagnostic printer only attempts to find a better 10226 // name for types, not decls. 10227 // Ideally, this should folded into the diagnostic printer. 10228 S.Diag(Templated->getLocation(), 10229 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10230 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10231 return; 10232 } 10233 } 10234 } 10235 10236 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10237 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10238 return; 10239 10240 // FIXME: For generic lambda parameters, check if the function is a lambda 10241 // call operator, and if so, emit a prettier and more informative 10242 // diagnostic that mentions 'auto' and lambda in addition to 10243 // (or instead of?) the canonical template type parameters. 10244 S.Diag(Templated->getLocation(), 10245 diag::note_ovl_candidate_non_deduced_mismatch) 10246 << FirstTA << SecondTA; 10247 return; 10248 } 10249 // TODO: diagnose these individually, then kill off 10250 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10251 case Sema::TDK_MiscellaneousDeductionFailure: 10252 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10253 MaybeEmitInheritedConstructorNote(S, Found); 10254 return; 10255 case Sema::TDK_CUDATargetMismatch: 10256 S.Diag(Templated->getLocation(), 10257 diag::note_cuda_ovl_candidate_target_mismatch); 10258 return; 10259 } 10260 } 10261 10262 /// Diagnose a failed template-argument deduction, for function calls. 10263 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10264 unsigned NumArgs, 10265 bool TakingCandidateAddress) { 10266 unsigned TDK = Cand->DeductionFailure.Result; 10267 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10268 if (CheckArityMismatch(S, Cand, NumArgs)) 10269 return; 10270 } 10271 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10272 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10273 } 10274 10275 /// CUDA: diagnose an invalid call across targets. 10276 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10277 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10278 FunctionDecl *Callee = Cand->Function; 10279 10280 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10281 CalleeTarget = S.IdentifyCUDATarget(Callee); 10282 10283 std::string FnDesc; 10284 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10285 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10286 10287 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10288 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10289 << FnDesc /* Ignored */ 10290 << CalleeTarget << CallerTarget; 10291 10292 // This could be an implicit constructor for which we could not infer the 10293 // target due to a collsion. Diagnose that case. 10294 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10295 if (Meth != nullptr && Meth->isImplicit()) { 10296 CXXRecordDecl *ParentClass = Meth->getParent(); 10297 Sema::CXXSpecialMember CSM; 10298 10299 switch (FnKindPair.first) { 10300 default: 10301 return; 10302 case oc_implicit_default_constructor: 10303 CSM = Sema::CXXDefaultConstructor; 10304 break; 10305 case oc_implicit_copy_constructor: 10306 CSM = Sema::CXXCopyConstructor; 10307 break; 10308 case oc_implicit_move_constructor: 10309 CSM = Sema::CXXMoveConstructor; 10310 break; 10311 case oc_implicit_copy_assignment: 10312 CSM = Sema::CXXCopyAssignment; 10313 break; 10314 case oc_implicit_move_assignment: 10315 CSM = Sema::CXXMoveAssignment; 10316 break; 10317 }; 10318 10319 bool ConstRHS = false; 10320 if (Meth->getNumParams()) { 10321 if (const ReferenceType *RT = 10322 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10323 ConstRHS = RT->getPointeeType().isConstQualified(); 10324 } 10325 } 10326 10327 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10328 /* ConstRHS */ ConstRHS, 10329 /* Diagnose */ true); 10330 } 10331 } 10332 10333 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10334 FunctionDecl *Callee = Cand->Function; 10335 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10336 10337 S.Diag(Callee->getLocation(), 10338 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10339 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10340 } 10341 10342 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10343 FunctionDecl *Callee = Cand->Function; 10344 10345 S.Diag(Callee->getLocation(), 10346 diag::note_ovl_candidate_disabled_by_extension) 10347 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10348 } 10349 10350 /// Generates a 'note' diagnostic for an overload candidate. We've 10351 /// already generated a primary error at the call site. 10352 /// 10353 /// It really does need to be a single diagnostic with its caret 10354 /// pointed at the candidate declaration. Yes, this creates some 10355 /// major challenges of technical writing. Yes, this makes pointing 10356 /// out problems with specific arguments quite awkward. It's still 10357 /// better than generating twenty screens of text for every failed 10358 /// overload. 10359 /// 10360 /// It would be great to be able to express per-candidate problems 10361 /// more richly for those diagnostic clients that cared, but we'd 10362 /// still have to be just as careful with the default diagnostics. 10363 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10364 unsigned NumArgs, 10365 bool TakingCandidateAddress) { 10366 FunctionDecl *Fn = Cand->Function; 10367 10368 // Note deleted candidates, but only if they're viable. 10369 if (Cand->Viable) { 10370 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) { 10371 std::string FnDesc; 10372 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10373 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10374 10375 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10376 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10377 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10378 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10379 return; 10380 } 10381 10382 // We don't really have anything else to say about viable candidates. 10383 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10384 return; 10385 } 10386 10387 switch (Cand->FailureKind) { 10388 case ovl_fail_too_many_arguments: 10389 case ovl_fail_too_few_arguments: 10390 return DiagnoseArityMismatch(S, Cand, NumArgs); 10391 10392 case ovl_fail_bad_deduction: 10393 return DiagnoseBadDeduction(S, Cand, NumArgs, 10394 TakingCandidateAddress); 10395 10396 case ovl_fail_illegal_constructor: { 10397 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10398 << (Fn->getPrimaryTemplate() ? 1 : 0); 10399 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10400 return; 10401 } 10402 10403 case ovl_fail_trivial_conversion: 10404 case ovl_fail_bad_final_conversion: 10405 case ovl_fail_final_conversion_not_exact: 10406 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10407 10408 case ovl_fail_bad_conversion: { 10409 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10410 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10411 if (Cand->Conversions[I].isBad()) 10412 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10413 10414 // FIXME: this currently happens when we're called from SemaInit 10415 // when user-conversion overload fails. Figure out how to handle 10416 // those conditions and diagnose them well. 10417 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10418 } 10419 10420 case ovl_fail_bad_target: 10421 return DiagnoseBadTarget(S, Cand); 10422 10423 case ovl_fail_enable_if: 10424 return DiagnoseFailedEnableIfAttr(S, Cand); 10425 10426 case ovl_fail_ext_disabled: 10427 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10428 10429 case ovl_fail_inhctor_slice: 10430 // It's generally not interesting to note copy/move constructors here. 10431 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10432 return; 10433 S.Diag(Fn->getLocation(), 10434 diag::note_ovl_candidate_inherited_constructor_slice) 10435 << (Fn->getPrimaryTemplate() ? 1 : 0) 10436 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10437 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10438 return; 10439 10440 case ovl_fail_addr_not_available: { 10441 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10442 (void)Available; 10443 assert(!Available); 10444 break; 10445 } 10446 case ovl_non_default_multiversion_function: 10447 // Do nothing, these should simply be ignored. 10448 break; 10449 } 10450 } 10451 10452 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10453 // Desugar the type of the surrogate down to a function type, 10454 // retaining as many typedefs as possible while still showing 10455 // the function type (and, therefore, its parameter types). 10456 QualType FnType = Cand->Surrogate->getConversionType(); 10457 bool isLValueReference = false; 10458 bool isRValueReference = false; 10459 bool isPointer = false; 10460 if (const LValueReferenceType *FnTypeRef = 10461 FnType->getAs<LValueReferenceType>()) { 10462 FnType = FnTypeRef->getPointeeType(); 10463 isLValueReference = true; 10464 } else if (const RValueReferenceType *FnTypeRef = 10465 FnType->getAs<RValueReferenceType>()) { 10466 FnType = FnTypeRef->getPointeeType(); 10467 isRValueReference = true; 10468 } 10469 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10470 FnType = FnTypePtr->getPointeeType(); 10471 isPointer = true; 10472 } 10473 // Desugar down to a function type. 10474 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10475 // Reconstruct the pointer/reference as appropriate. 10476 if (isPointer) FnType = S.Context.getPointerType(FnType); 10477 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10478 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10479 10480 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10481 << FnType; 10482 } 10483 10484 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10485 SourceLocation OpLoc, 10486 OverloadCandidate *Cand) { 10487 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10488 std::string TypeStr("operator"); 10489 TypeStr += Opc; 10490 TypeStr += "("; 10491 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10492 if (Cand->Conversions.size() == 1) { 10493 TypeStr += ")"; 10494 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10495 } else { 10496 TypeStr += ", "; 10497 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10498 TypeStr += ")"; 10499 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10500 } 10501 } 10502 10503 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10504 OverloadCandidate *Cand) { 10505 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10506 if (ICS.isBad()) break; // all meaningless after first invalid 10507 if (!ICS.isAmbiguous()) continue; 10508 10509 ICS.DiagnoseAmbiguousConversion( 10510 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10511 } 10512 } 10513 10514 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10515 if (Cand->Function) 10516 return Cand->Function->getLocation(); 10517 if (Cand->IsSurrogate) 10518 return Cand->Surrogate->getLocation(); 10519 return SourceLocation(); 10520 } 10521 10522 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10523 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10524 case Sema::TDK_Success: 10525 case Sema::TDK_NonDependentConversionFailure: 10526 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10527 10528 case Sema::TDK_Invalid: 10529 case Sema::TDK_Incomplete: 10530 case Sema::TDK_IncompletePack: 10531 return 1; 10532 10533 case Sema::TDK_Underqualified: 10534 case Sema::TDK_Inconsistent: 10535 return 2; 10536 10537 case Sema::TDK_SubstitutionFailure: 10538 case Sema::TDK_DeducedMismatch: 10539 case Sema::TDK_DeducedMismatchNested: 10540 case Sema::TDK_NonDeducedMismatch: 10541 case Sema::TDK_MiscellaneousDeductionFailure: 10542 case Sema::TDK_CUDATargetMismatch: 10543 return 3; 10544 10545 case Sema::TDK_InstantiationDepth: 10546 return 4; 10547 10548 case Sema::TDK_InvalidExplicitArguments: 10549 return 5; 10550 10551 case Sema::TDK_TooManyArguments: 10552 case Sema::TDK_TooFewArguments: 10553 return 6; 10554 } 10555 llvm_unreachable("Unhandled deduction result"); 10556 } 10557 10558 namespace { 10559 struct CompareOverloadCandidatesForDisplay { 10560 Sema &S; 10561 SourceLocation Loc; 10562 size_t NumArgs; 10563 OverloadCandidateSet::CandidateSetKind CSK; 10564 10565 CompareOverloadCandidatesForDisplay( 10566 Sema &S, SourceLocation Loc, size_t NArgs, 10567 OverloadCandidateSet::CandidateSetKind CSK) 10568 : S(S), NumArgs(NArgs), CSK(CSK) {} 10569 10570 bool operator()(const OverloadCandidate *L, 10571 const OverloadCandidate *R) { 10572 // Fast-path this check. 10573 if (L == R) return false; 10574 10575 // Order first by viability. 10576 if (L->Viable) { 10577 if (!R->Viable) return true; 10578 10579 // TODO: introduce a tri-valued comparison for overload 10580 // candidates. Would be more worthwhile if we had a sort 10581 // that could exploit it. 10582 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10583 return true; 10584 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10585 return false; 10586 } else if (R->Viable) 10587 return false; 10588 10589 assert(L->Viable == R->Viable); 10590 10591 // Criteria by which we can sort non-viable candidates: 10592 if (!L->Viable) { 10593 // 1. Arity mismatches come after other candidates. 10594 if (L->FailureKind == ovl_fail_too_many_arguments || 10595 L->FailureKind == ovl_fail_too_few_arguments) { 10596 if (R->FailureKind == ovl_fail_too_many_arguments || 10597 R->FailureKind == ovl_fail_too_few_arguments) { 10598 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10599 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10600 if (LDist == RDist) { 10601 if (L->FailureKind == R->FailureKind) 10602 // Sort non-surrogates before surrogates. 10603 return !L->IsSurrogate && R->IsSurrogate; 10604 // Sort candidates requiring fewer parameters than there were 10605 // arguments given after candidates requiring more parameters 10606 // than there were arguments given. 10607 return L->FailureKind == ovl_fail_too_many_arguments; 10608 } 10609 return LDist < RDist; 10610 } 10611 return false; 10612 } 10613 if (R->FailureKind == ovl_fail_too_many_arguments || 10614 R->FailureKind == ovl_fail_too_few_arguments) 10615 return true; 10616 10617 // 2. Bad conversions come first and are ordered by the number 10618 // of bad conversions and quality of good conversions. 10619 if (L->FailureKind == ovl_fail_bad_conversion) { 10620 if (R->FailureKind != ovl_fail_bad_conversion) 10621 return true; 10622 10623 // The conversion that can be fixed with a smaller number of changes, 10624 // comes first. 10625 unsigned numLFixes = L->Fix.NumConversionsFixed; 10626 unsigned numRFixes = R->Fix.NumConversionsFixed; 10627 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10628 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10629 if (numLFixes != numRFixes) { 10630 return numLFixes < numRFixes; 10631 } 10632 10633 // If there's any ordering between the defined conversions... 10634 // FIXME: this might not be transitive. 10635 assert(L->Conversions.size() == R->Conversions.size()); 10636 10637 int leftBetter = 0; 10638 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10639 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10640 switch (CompareImplicitConversionSequences(S, Loc, 10641 L->Conversions[I], 10642 R->Conversions[I])) { 10643 case ImplicitConversionSequence::Better: 10644 leftBetter++; 10645 break; 10646 10647 case ImplicitConversionSequence::Worse: 10648 leftBetter--; 10649 break; 10650 10651 case ImplicitConversionSequence::Indistinguishable: 10652 break; 10653 } 10654 } 10655 if (leftBetter > 0) return true; 10656 if (leftBetter < 0) return false; 10657 10658 } else if (R->FailureKind == ovl_fail_bad_conversion) 10659 return false; 10660 10661 if (L->FailureKind == ovl_fail_bad_deduction) { 10662 if (R->FailureKind != ovl_fail_bad_deduction) 10663 return true; 10664 10665 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10666 return RankDeductionFailure(L->DeductionFailure) 10667 < RankDeductionFailure(R->DeductionFailure); 10668 } else if (R->FailureKind == ovl_fail_bad_deduction) 10669 return false; 10670 10671 // TODO: others? 10672 } 10673 10674 // Sort everything else by location. 10675 SourceLocation LLoc = GetLocationForCandidate(L); 10676 SourceLocation RLoc = GetLocationForCandidate(R); 10677 10678 // Put candidates without locations (e.g. builtins) at the end. 10679 if (LLoc.isInvalid()) return false; 10680 if (RLoc.isInvalid()) return true; 10681 10682 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10683 } 10684 }; 10685 } 10686 10687 /// CompleteNonViableCandidate - Normally, overload resolution only 10688 /// computes up to the first bad conversion. Produces the FixIt set if 10689 /// possible. 10690 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10691 ArrayRef<Expr *> Args) { 10692 assert(!Cand->Viable); 10693 10694 // Don't do anything on failures other than bad conversion. 10695 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10696 10697 // We only want the FixIts if all the arguments can be corrected. 10698 bool Unfixable = false; 10699 // Use a implicit copy initialization to check conversion fixes. 10700 Cand->Fix.setConversionChecker(TryCopyInitialization); 10701 10702 // Attempt to fix the bad conversion. 10703 unsigned ConvCount = Cand->Conversions.size(); 10704 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10705 ++ConvIdx) { 10706 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10707 if (Cand->Conversions[ConvIdx].isInitialized() && 10708 Cand->Conversions[ConvIdx].isBad()) { 10709 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10710 break; 10711 } 10712 } 10713 10714 // FIXME: this should probably be preserved from the overload 10715 // operation somehow. 10716 bool SuppressUserConversions = false; 10717 10718 unsigned ConvIdx = 0; 10719 ArrayRef<QualType> ParamTypes; 10720 10721 if (Cand->IsSurrogate) { 10722 QualType ConvType 10723 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10724 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10725 ConvType = ConvPtrType->getPointeeType(); 10726 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10727 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10728 ConvIdx = 1; 10729 } else if (Cand->Function) { 10730 ParamTypes = 10731 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10732 if (isa<CXXMethodDecl>(Cand->Function) && 10733 !isa<CXXConstructorDecl>(Cand->Function)) { 10734 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10735 ConvIdx = 1; 10736 } 10737 } else { 10738 // Builtin operator. 10739 assert(ConvCount <= 3); 10740 ParamTypes = Cand->BuiltinParamTypes; 10741 } 10742 10743 // Fill in the rest of the conversions. 10744 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10745 if (Cand->Conversions[ConvIdx].isInitialized()) { 10746 // We've already checked this conversion. 10747 } else if (ArgIdx < ParamTypes.size()) { 10748 if (ParamTypes[ArgIdx]->isDependentType()) 10749 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10750 Args[ArgIdx]->getType()); 10751 else { 10752 Cand->Conversions[ConvIdx] = 10753 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10754 SuppressUserConversions, 10755 /*InOverloadResolution=*/true, 10756 /*AllowObjCWritebackConversion=*/ 10757 S.getLangOpts().ObjCAutoRefCount); 10758 // Store the FixIt in the candidate if it exists. 10759 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10760 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10761 } 10762 } else 10763 Cand->Conversions[ConvIdx].setEllipsis(); 10764 } 10765 } 10766 10767 /// When overload resolution fails, prints diagnostic messages containing the 10768 /// candidates in the candidate set. 10769 void OverloadCandidateSet::NoteCandidates( 10770 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10771 StringRef Opc, SourceLocation OpLoc, 10772 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10773 // Sort the candidates by viability and position. Sorting directly would 10774 // be prohibitive, so we make a set of pointers and sort those. 10775 SmallVector<OverloadCandidate*, 32> Cands; 10776 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10777 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10778 if (!Filter(*Cand)) 10779 continue; 10780 if (Cand->Viable) 10781 Cands.push_back(Cand); 10782 else if (OCD == OCD_AllCandidates) { 10783 CompleteNonViableCandidate(S, Cand, Args); 10784 if (Cand->Function || Cand->IsSurrogate) 10785 Cands.push_back(Cand); 10786 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10787 // want to list every possible builtin candidate. 10788 } 10789 } 10790 10791 std::stable_sort(Cands.begin(), Cands.end(), 10792 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 10793 10794 bool ReportedAmbiguousConversions = false; 10795 10796 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10797 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10798 unsigned CandsShown = 0; 10799 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10800 OverloadCandidate *Cand = *I; 10801 10802 // Set an arbitrary limit on the number of candidate functions we'll spam 10803 // the user with. FIXME: This limit should depend on details of the 10804 // candidate list. 10805 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10806 break; 10807 } 10808 ++CandsShown; 10809 10810 if (Cand->Function) 10811 NoteFunctionCandidate(S, Cand, Args.size(), 10812 /*TakingCandidateAddress=*/false); 10813 else if (Cand->IsSurrogate) 10814 NoteSurrogateCandidate(S, Cand); 10815 else { 10816 assert(Cand->Viable && 10817 "Non-viable built-in candidates are not added to Cands."); 10818 // Generally we only see ambiguities including viable builtin 10819 // operators if overload resolution got screwed up by an 10820 // ambiguous user-defined conversion. 10821 // 10822 // FIXME: It's quite possible for different conversions to see 10823 // different ambiguities, though. 10824 if (!ReportedAmbiguousConversions) { 10825 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10826 ReportedAmbiguousConversions = true; 10827 } 10828 10829 // If this is a viable builtin, print it. 10830 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10831 } 10832 } 10833 10834 if (I != E) 10835 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10836 } 10837 10838 static SourceLocation 10839 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10840 return Cand->Specialization ? Cand->Specialization->getLocation() 10841 : SourceLocation(); 10842 } 10843 10844 namespace { 10845 struct CompareTemplateSpecCandidatesForDisplay { 10846 Sema &S; 10847 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10848 10849 bool operator()(const TemplateSpecCandidate *L, 10850 const TemplateSpecCandidate *R) { 10851 // Fast-path this check. 10852 if (L == R) 10853 return false; 10854 10855 // Assuming that both candidates are not matches... 10856 10857 // Sort by the ranking of deduction failures. 10858 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10859 return RankDeductionFailure(L->DeductionFailure) < 10860 RankDeductionFailure(R->DeductionFailure); 10861 10862 // Sort everything else by location. 10863 SourceLocation LLoc = GetLocationForCandidate(L); 10864 SourceLocation RLoc = GetLocationForCandidate(R); 10865 10866 // Put candidates without locations (e.g. builtins) at the end. 10867 if (LLoc.isInvalid()) 10868 return false; 10869 if (RLoc.isInvalid()) 10870 return true; 10871 10872 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10873 } 10874 }; 10875 } 10876 10877 /// Diagnose a template argument deduction failure. 10878 /// We are treating these failures as overload failures due to bad 10879 /// deductions. 10880 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10881 bool ForTakingAddress) { 10882 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10883 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10884 } 10885 10886 void TemplateSpecCandidateSet::destroyCandidates() { 10887 for (iterator i = begin(), e = end(); i != e; ++i) { 10888 i->DeductionFailure.Destroy(); 10889 } 10890 } 10891 10892 void TemplateSpecCandidateSet::clear() { 10893 destroyCandidates(); 10894 Candidates.clear(); 10895 } 10896 10897 /// NoteCandidates - When no template specialization match is found, prints 10898 /// diagnostic messages containing the non-matching specializations that form 10899 /// the candidate set. 10900 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10901 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10902 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10903 // Sort the candidates by position (assuming no candidate is a match). 10904 // Sorting directly would be prohibitive, so we make a set of pointers 10905 // and sort those. 10906 SmallVector<TemplateSpecCandidate *, 32> Cands; 10907 Cands.reserve(size()); 10908 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10909 if (Cand->Specialization) 10910 Cands.push_back(Cand); 10911 // Otherwise, this is a non-matching builtin candidate. We do not, 10912 // in general, want to list every possible builtin candidate. 10913 } 10914 10915 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 10916 10917 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10918 // for generalization purposes (?). 10919 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10920 10921 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10922 unsigned CandsShown = 0; 10923 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10924 TemplateSpecCandidate *Cand = *I; 10925 10926 // Set an arbitrary limit on the number of candidates we'll spam 10927 // the user with. FIXME: This limit should depend on details of the 10928 // candidate list. 10929 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10930 break; 10931 ++CandsShown; 10932 10933 assert(Cand->Specialization && 10934 "Non-matching built-in candidates are not added to Cands."); 10935 Cand->NoteDeductionFailure(S, ForTakingAddress); 10936 } 10937 10938 if (I != E) 10939 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10940 } 10941 10942 // [PossiblyAFunctionType] --> [Return] 10943 // NonFunctionType --> NonFunctionType 10944 // R (A) --> R(A) 10945 // R (*)(A) --> R (A) 10946 // R (&)(A) --> R (A) 10947 // R (S::*)(A) --> R (A) 10948 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10949 QualType Ret = PossiblyAFunctionType; 10950 if (const PointerType *ToTypePtr = 10951 PossiblyAFunctionType->getAs<PointerType>()) 10952 Ret = ToTypePtr->getPointeeType(); 10953 else if (const ReferenceType *ToTypeRef = 10954 PossiblyAFunctionType->getAs<ReferenceType>()) 10955 Ret = ToTypeRef->getPointeeType(); 10956 else if (const MemberPointerType *MemTypePtr = 10957 PossiblyAFunctionType->getAs<MemberPointerType>()) 10958 Ret = MemTypePtr->getPointeeType(); 10959 Ret = 10960 Context.getCanonicalType(Ret).getUnqualifiedType(); 10961 return Ret; 10962 } 10963 10964 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10965 bool Complain = true) { 10966 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10967 S.DeduceReturnType(FD, Loc, Complain)) 10968 return true; 10969 10970 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10971 if (S.getLangOpts().CPlusPlus17 && 10972 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10973 !S.ResolveExceptionSpec(Loc, FPT)) 10974 return true; 10975 10976 return false; 10977 } 10978 10979 namespace { 10980 // A helper class to help with address of function resolution 10981 // - allows us to avoid passing around all those ugly parameters 10982 class AddressOfFunctionResolver { 10983 Sema& S; 10984 Expr* SourceExpr; 10985 const QualType& TargetType; 10986 QualType TargetFunctionType; // Extracted function type from target type 10987 10988 bool Complain; 10989 //DeclAccessPair& ResultFunctionAccessPair; 10990 ASTContext& Context; 10991 10992 bool TargetTypeIsNonStaticMemberFunction; 10993 bool FoundNonTemplateFunction; 10994 bool StaticMemberFunctionFromBoundPointer; 10995 bool HasComplained; 10996 10997 OverloadExpr::FindResult OvlExprInfo; 10998 OverloadExpr *OvlExpr; 10999 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11000 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11001 TemplateSpecCandidateSet FailedCandidates; 11002 11003 public: 11004 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11005 const QualType &TargetType, bool Complain) 11006 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11007 Complain(Complain), Context(S.getASTContext()), 11008 TargetTypeIsNonStaticMemberFunction( 11009 !!TargetType->getAs<MemberPointerType>()), 11010 FoundNonTemplateFunction(false), 11011 StaticMemberFunctionFromBoundPointer(false), 11012 HasComplained(false), 11013 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11014 OvlExpr(OvlExprInfo.Expression), 11015 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11016 ExtractUnqualifiedFunctionTypeFromTargetType(); 11017 11018 if (TargetFunctionType->isFunctionType()) { 11019 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11020 if (!UME->isImplicitAccess() && 11021 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11022 StaticMemberFunctionFromBoundPointer = true; 11023 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11024 DeclAccessPair dap; 11025 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11026 OvlExpr, false, &dap)) { 11027 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11028 if (!Method->isStatic()) { 11029 // If the target type is a non-function type and the function found 11030 // is a non-static member function, pretend as if that was the 11031 // target, it's the only possible type to end up with. 11032 TargetTypeIsNonStaticMemberFunction = true; 11033 11034 // And skip adding the function if its not in the proper form. 11035 // We'll diagnose this due to an empty set of functions. 11036 if (!OvlExprInfo.HasFormOfMemberPointer) 11037 return; 11038 } 11039 11040 Matches.push_back(std::make_pair(dap, Fn)); 11041 } 11042 return; 11043 } 11044 11045 if (OvlExpr->hasExplicitTemplateArgs()) 11046 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11047 11048 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11049 // C++ [over.over]p4: 11050 // If more than one function is selected, [...] 11051 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11052 if (FoundNonTemplateFunction) 11053 EliminateAllTemplateMatches(); 11054 else 11055 EliminateAllExceptMostSpecializedTemplate(); 11056 } 11057 } 11058 11059 if (S.getLangOpts().CUDA && Matches.size() > 1) 11060 EliminateSuboptimalCudaMatches(); 11061 } 11062 11063 bool hasComplained() const { return HasComplained; } 11064 11065 private: 11066 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11067 QualType Discard; 11068 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11069 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11070 } 11071 11072 /// \return true if A is considered a better overload candidate for the 11073 /// desired type than B. 11074 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11075 // If A doesn't have exactly the correct type, we don't want to classify it 11076 // as "better" than anything else. This way, the user is required to 11077 // disambiguate for us if there are multiple candidates and no exact match. 11078 return candidateHasExactlyCorrectType(A) && 11079 (!candidateHasExactlyCorrectType(B) || 11080 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11081 } 11082 11083 /// \return true if we were able to eliminate all but one overload candidate, 11084 /// false otherwise. 11085 bool eliminiateSuboptimalOverloadCandidates() { 11086 // Same algorithm as overload resolution -- one pass to pick the "best", 11087 // another pass to be sure that nothing is better than the best. 11088 auto Best = Matches.begin(); 11089 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11090 if (isBetterCandidate(I->second, Best->second)) 11091 Best = I; 11092 11093 const FunctionDecl *BestFn = Best->second; 11094 auto IsBestOrInferiorToBest = [this, BestFn]( 11095 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11096 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11097 }; 11098 11099 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11100 // option, so we can potentially give the user a better error 11101 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11102 return false; 11103 Matches[0] = *Best; 11104 Matches.resize(1); 11105 return true; 11106 } 11107 11108 bool isTargetTypeAFunction() const { 11109 return TargetFunctionType->isFunctionType(); 11110 } 11111 11112 // [ToType] [Return] 11113 11114 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11115 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11116 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11117 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11118 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11119 } 11120 11121 // return true if any matching specializations were found 11122 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11123 const DeclAccessPair& CurAccessFunPair) { 11124 if (CXXMethodDecl *Method 11125 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11126 // Skip non-static function templates when converting to pointer, and 11127 // static when converting to member pointer. 11128 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11129 return false; 11130 } 11131 else if (TargetTypeIsNonStaticMemberFunction) 11132 return false; 11133 11134 // C++ [over.over]p2: 11135 // If the name is a function template, template argument deduction is 11136 // done (14.8.2.2), and if the argument deduction succeeds, the 11137 // resulting template argument list is used to generate a single 11138 // function template specialization, which is added to the set of 11139 // overloaded functions considered. 11140 FunctionDecl *Specialization = nullptr; 11141 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11142 if (Sema::TemplateDeductionResult Result 11143 = S.DeduceTemplateArguments(FunctionTemplate, 11144 &OvlExplicitTemplateArgs, 11145 TargetFunctionType, Specialization, 11146 Info, /*IsAddressOfFunction*/true)) { 11147 // Make a note of the failed deduction for diagnostics. 11148 FailedCandidates.addCandidate() 11149 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11150 MakeDeductionFailureInfo(Context, Result, Info)); 11151 return false; 11152 } 11153 11154 // Template argument deduction ensures that we have an exact match or 11155 // compatible pointer-to-function arguments that would be adjusted by ICS. 11156 // This function template specicalization works. 11157 assert(S.isSameOrCompatibleFunctionType( 11158 Context.getCanonicalType(Specialization->getType()), 11159 Context.getCanonicalType(TargetFunctionType))); 11160 11161 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11162 return false; 11163 11164 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11165 return true; 11166 } 11167 11168 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11169 const DeclAccessPair& CurAccessFunPair) { 11170 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11171 // Skip non-static functions when converting to pointer, and static 11172 // when converting to member pointer. 11173 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11174 return false; 11175 } 11176 else if (TargetTypeIsNonStaticMemberFunction) 11177 return false; 11178 11179 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11180 if (S.getLangOpts().CUDA) 11181 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11182 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11183 return false; 11184 if (FunDecl->isMultiVersion()) { 11185 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11186 if (TA && !TA->isDefaultVersion()) 11187 return false; 11188 } 11189 11190 // If any candidate has a placeholder return type, trigger its deduction 11191 // now. 11192 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11193 Complain)) { 11194 HasComplained |= Complain; 11195 return false; 11196 } 11197 11198 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11199 return false; 11200 11201 // If we're in C, we need to support types that aren't exactly identical. 11202 if (!S.getLangOpts().CPlusPlus || 11203 candidateHasExactlyCorrectType(FunDecl)) { 11204 Matches.push_back(std::make_pair( 11205 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11206 FoundNonTemplateFunction = true; 11207 return true; 11208 } 11209 } 11210 11211 return false; 11212 } 11213 11214 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11215 bool Ret = false; 11216 11217 // If the overload expression doesn't have the form of a pointer to 11218 // member, don't try to convert it to a pointer-to-member type. 11219 if (IsInvalidFormOfPointerToMemberFunction()) 11220 return false; 11221 11222 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11223 E = OvlExpr->decls_end(); 11224 I != E; ++I) { 11225 // Look through any using declarations to find the underlying function. 11226 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11227 11228 // C++ [over.over]p3: 11229 // Non-member functions and static member functions match 11230 // targets of type "pointer-to-function" or "reference-to-function." 11231 // Nonstatic member functions match targets of 11232 // type "pointer-to-member-function." 11233 // Note that according to DR 247, the containing class does not matter. 11234 if (FunctionTemplateDecl *FunctionTemplate 11235 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11236 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11237 Ret = true; 11238 } 11239 // If we have explicit template arguments supplied, skip non-templates. 11240 else if (!OvlExpr->hasExplicitTemplateArgs() && 11241 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11242 Ret = true; 11243 } 11244 assert(Ret || Matches.empty()); 11245 return Ret; 11246 } 11247 11248 void EliminateAllExceptMostSpecializedTemplate() { 11249 // [...] and any given function template specialization F1 is 11250 // eliminated if the set contains a second function template 11251 // specialization whose function template is more specialized 11252 // than the function template of F1 according to the partial 11253 // ordering rules of 14.5.5.2. 11254 11255 // The algorithm specified above is quadratic. We instead use a 11256 // two-pass algorithm (similar to the one used to identify the 11257 // best viable function in an overload set) that identifies the 11258 // best function template (if it exists). 11259 11260 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11261 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11262 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11263 11264 // TODO: It looks like FailedCandidates does not serve much purpose 11265 // here, since the no_viable diagnostic has index 0. 11266 UnresolvedSetIterator Result = S.getMostSpecialized( 11267 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11268 SourceExpr->getBeginLoc(), S.PDiag(), 11269 S.PDiag(diag::err_addr_ovl_ambiguous) 11270 << Matches[0].second->getDeclName(), 11271 S.PDiag(diag::note_ovl_candidate) 11272 << (unsigned)oc_function << (unsigned)ocs_described_template, 11273 Complain, TargetFunctionType); 11274 11275 if (Result != MatchesCopy.end()) { 11276 // Make it the first and only element 11277 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11278 Matches[0].second = cast<FunctionDecl>(*Result); 11279 Matches.resize(1); 11280 } else 11281 HasComplained |= Complain; 11282 } 11283 11284 void EliminateAllTemplateMatches() { 11285 // [...] any function template specializations in the set are 11286 // eliminated if the set also contains a non-template function, [...] 11287 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11288 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11289 ++I; 11290 else { 11291 Matches[I] = Matches[--N]; 11292 Matches.resize(N); 11293 } 11294 } 11295 } 11296 11297 void EliminateSuboptimalCudaMatches() { 11298 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11299 } 11300 11301 public: 11302 void ComplainNoMatchesFound() const { 11303 assert(Matches.empty()); 11304 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11305 << OvlExpr->getName() << TargetFunctionType 11306 << OvlExpr->getSourceRange(); 11307 if (FailedCandidates.empty()) 11308 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11309 /*TakingAddress=*/true); 11310 else { 11311 // We have some deduction failure messages. Use them to diagnose 11312 // the function templates, and diagnose the non-template candidates 11313 // normally. 11314 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11315 IEnd = OvlExpr->decls_end(); 11316 I != IEnd; ++I) 11317 if (FunctionDecl *Fun = 11318 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11319 if (!functionHasPassObjectSizeParams(Fun)) 11320 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11321 /*TakingAddress=*/true); 11322 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11323 } 11324 } 11325 11326 bool IsInvalidFormOfPointerToMemberFunction() const { 11327 return TargetTypeIsNonStaticMemberFunction && 11328 !OvlExprInfo.HasFormOfMemberPointer; 11329 } 11330 11331 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11332 // TODO: Should we condition this on whether any functions might 11333 // have matched, or is it more appropriate to do that in callers? 11334 // TODO: a fixit wouldn't hurt. 11335 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11336 << TargetType << OvlExpr->getSourceRange(); 11337 } 11338 11339 bool IsStaticMemberFunctionFromBoundPointer() const { 11340 return StaticMemberFunctionFromBoundPointer; 11341 } 11342 11343 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11344 S.Diag(OvlExpr->getBeginLoc(), 11345 diag::err_invalid_form_pointer_member_function) 11346 << OvlExpr->getSourceRange(); 11347 } 11348 11349 void ComplainOfInvalidConversion() const { 11350 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11351 << OvlExpr->getName() << TargetType; 11352 } 11353 11354 void ComplainMultipleMatchesFound() const { 11355 assert(Matches.size() > 1); 11356 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11357 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11358 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11359 /*TakingAddress=*/true); 11360 } 11361 11362 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11363 11364 int getNumMatches() const { return Matches.size(); } 11365 11366 FunctionDecl* getMatchingFunctionDecl() const { 11367 if (Matches.size() != 1) return nullptr; 11368 return Matches[0].second; 11369 } 11370 11371 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11372 if (Matches.size() != 1) return nullptr; 11373 return &Matches[0].first; 11374 } 11375 }; 11376 } 11377 11378 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11379 /// an overloaded function (C++ [over.over]), where @p From is an 11380 /// expression with overloaded function type and @p ToType is the type 11381 /// we're trying to resolve to. For example: 11382 /// 11383 /// @code 11384 /// int f(double); 11385 /// int f(int); 11386 /// 11387 /// int (*pfd)(double) = f; // selects f(double) 11388 /// @endcode 11389 /// 11390 /// This routine returns the resulting FunctionDecl if it could be 11391 /// resolved, and NULL otherwise. When @p Complain is true, this 11392 /// routine will emit diagnostics if there is an error. 11393 FunctionDecl * 11394 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11395 QualType TargetType, 11396 bool Complain, 11397 DeclAccessPair &FoundResult, 11398 bool *pHadMultipleCandidates) { 11399 assert(AddressOfExpr->getType() == Context.OverloadTy); 11400 11401 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11402 Complain); 11403 int NumMatches = Resolver.getNumMatches(); 11404 FunctionDecl *Fn = nullptr; 11405 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11406 if (NumMatches == 0 && ShouldComplain) { 11407 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11408 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11409 else 11410 Resolver.ComplainNoMatchesFound(); 11411 } 11412 else if (NumMatches > 1 && ShouldComplain) 11413 Resolver.ComplainMultipleMatchesFound(); 11414 else if (NumMatches == 1) { 11415 Fn = Resolver.getMatchingFunctionDecl(); 11416 assert(Fn); 11417 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11418 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11419 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11420 if (Complain) { 11421 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11422 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11423 else 11424 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11425 } 11426 } 11427 11428 if (pHadMultipleCandidates) 11429 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11430 return Fn; 11431 } 11432 11433 /// Given an expression that refers to an overloaded function, try to 11434 /// resolve that function to a single function that can have its address taken. 11435 /// This will modify `Pair` iff it returns non-null. 11436 /// 11437 /// This routine can only realistically succeed if all but one candidates in the 11438 /// overload set for SrcExpr cannot have their addresses taken. 11439 FunctionDecl * 11440 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11441 DeclAccessPair &Pair) { 11442 OverloadExpr::FindResult R = OverloadExpr::find(E); 11443 OverloadExpr *Ovl = R.Expression; 11444 FunctionDecl *Result = nullptr; 11445 DeclAccessPair DAP; 11446 // Don't use the AddressOfResolver because we're specifically looking for 11447 // cases where we have one overload candidate that lacks 11448 // enable_if/pass_object_size/... 11449 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11450 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11451 if (!FD) 11452 return nullptr; 11453 11454 if (!checkAddressOfFunctionIsAvailable(FD)) 11455 continue; 11456 11457 // We have more than one result; quit. 11458 if (Result) 11459 return nullptr; 11460 DAP = I.getPair(); 11461 Result = FD; 11462 } 11463 11464 if (Result) 11465 Pair = DAP; 11466 return Result; 11467 } 11468 11469 /// Given an overloaded function, tries to turn it into a non-overloaded 11470 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11471 /// will perform access checks, diagnose the use of the resultant decl, and, if 11472 /// requested, potentially perform a function-to-pointer decay. 11473 /// 11474 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11475 /// Otherwise, returns true. This may emit diagnostics and return true. 11476 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11477 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11478 Expr *E = SrcExpr.get(); 11479 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11480 11481 DeclAccessPair DAP; 11482 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11483 if (!Found || Found->isCPUDispatchMultiVersion() || 11484 Found->isCPUSpecificMultiVersion()) 11485 return false; 11486 11487 // Emitting multiple diagnostics for a function that is both inaccessible and 11488 // unavailable is consistent with our behavior elsewhere. So, always check 11489 // for both. 11490 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11491 CheckAddressOfMemberAccess(E, DAP); 11492 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11493 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11494 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11495 else 11496 SrcExpr = Fixed; 11497 return true; 11498 } 11499 11500 /// Given an expression that refers to an overloaded function, try to 11501 /// resolve that overloaded function expression down to a single function. 11502 /// 11503 /// This routine can only resolve template-ids that refer to a single function 11504 /// template, where that template-id refers to a single template whose template 11505 /// arguments are either provided by the template-id or have defaults, 11506 /// as described in C++0x [temp.arg.explicit]p3. 11507 /// 11508 /// If no template-ids are found, no diagnostics are emitted and NULL is 11509 /// returned. 11510 FunctionDecl * 11511 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11512 bool Complain, 11513 DeclAccessPair *FoundResult) { 11514 // C++ [over.over]p1: 11515 // [...] [Note: any redundant set of parentheses surrounding the 11516 // overloaded function name is ignored (5.1). ] 11517 // C++ [over.over]p1: 11518 // [...] The overloaded function name can be preceded by the & 11519 // operator. 11520 11521 // If we didn't actually find any template-ids, we're done. 11522 if (!ovl->hasExplicitTemplateArgs()) 11523 return nullptr; 11524 11525 TemplateArgumentListInfo ExplicitTemplateArgs; 11526 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11527 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11528 11529 // Look through all of the overloaded functions, searching for one 11530 // whose type matches exactly. 11531 FunctionDecl *Matched = nullptr; 11532 for (UnresolvedSetIterator I = ovl->decls_begin(), 11533 E = ovl->decls_end(); I != E; ++I) { 11534 // C++0x [temp.arg.explicit]p3: 11535 // [...] In contexts where deduction is done and fails, or in contexts 11536 // where deduction is not done, if a template argument list is 11537 // specified and it, along with any default template arguments, 11538 // identifies a single function template specialization, then the 11539 // template-id is an lvalue for the function template specialization. 11540 FunctionTemplateDecl *FunctionTemplate 11541 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11542 11543 // C++ [over.over]p2: 11544 // If the name is a function template, template argument deduction is 11545 // done (14.8.2.2), and if the argument deduction succeeds, the 11546 // resulting template argument list is used to generate a single 11547 // function template specialization, which is added to the set of 11548 // overloaded functions considered. 11549 FunctionDecl *Specialization = nullptr; 11550 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11551 if (TemplateDeductionResult Result 11552 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11553 Specialization, Info, 11554 /*IsAddressOfFunction*/true)) { 11555 // Make a note of the failed deduction for diagnostics. 11556 // TODO: Actually use the failed-deduction info? 11557 FailedCandidates.addCandidate() 11558 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11559 MakeDeductionFailureInfo(Context, Result, Info)); 11560 continue; 11561 } 11562 11563 assert(Specialization && "no specialization and no error?"); 11564 11565 // Multiple matches; we can't resolve to a single declaration. 11566 if (Matched) { 11567 if (Complain) { 11568 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11569 << ovl->getName(); 11570 NoteAllOverloadCandidates(ovl); 11571 } 11572 return nullptr; 11573 } 11574 11575 Matched = Specialization; 11576 if (FoundResult) *FoundResult = I.getPair(); 11577 } 11578 11579 if (Matched && 11580 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11581 return nullptr; 11582 11583 return Matched; 11584 } 11585 11586 // Resolve and fix an overloaded expression that can be resolved 11587 // because it identifies a single function template specialization. 11588 // 11589 // Last three arguments should only be supplied if Complain = true 11590 // 11591 // Return true if it was logically possible to so resolve the 11592 // expression, regardless of whether or not it succeeded. Always 11593 // returns true if 'complain' is set. 11594 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11595 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11596 bool complain, SourceRange OpRangeForComplaining, 11597 QualType DestTypeForComplaining, 11598 unsigned DiagIDForComplaining) { 11599 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11600 11601 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11602 11603 DeclAccessPair found; 11604 ExprResult SingleFunctionExpression; 11605 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11606 ovl.Expression, /*complain*/ false, &found)) { 11607 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11608 SrcExpr = ExprError(); 11609 return true; 11610 } 11611 11612 // It is only correct to resolve to an instance method if we're 11613 // resolving a form that's permitted to be a pointer to member. 11614 // Otherwise we'll end up making a bound member expression, which 11615 // is illegal in all the contexts we resolve like this. 11616 if (!ovl.HasFormOfMemberPointer && 11617 isa<CXXMethodDecl>(fn) && 11618 cast<CXXMethodDecl>(fn)->isInstance()) { 11619 if (!complain) return false; 11620 11621 Diag(ovl.Expression->getExprLoc(), 11622 diag::err_bound_member_function) 11623 << 0 << ovl.Expression->getSourceRange(); 11624 11625 // TODO: I believe we only end up here if there's a mix of 11626 // static and non-static candidates (otherwise the expression 11627 // would have 'bound member' type, not 'overload' type). 11628 // Ideally we would note which candidate was chosen and why 11629 // the static candidates were rejected. 11630 SrcExpr = ExprError(); 11631 return true; 11632 } 11633 11634 // Fix the expression to refer to 'fn'. 11635 SingleFunctionExpression = 11636 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11637 11638 // If desired, do function-to-pointer decay. 11639 if (doFunctionPointerConverion) { 11640 SingleFunctionExpression = 11641 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11642 if (SingleFunctionExpression.isInvalid()) { 11643 SrcExpr = ExprError(); 11644 return true; 11645 } 11646 } 11647 } 11648 11649 if (!SingleFunctionExpression.isUsable()) { 11650 if (complain) { 11651 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11652 << ovl.Expression->getName() 11653 << DestTypeForComplaining 11654 << OpRangeForComplaining 11655 << ovl.Expression->getQualifierLoc().getSourceRange(); 11656 NoteAllOverloadCandidates(SrcExpr.get()); 11657 11658 SrcExpr = ExprError(); 11659 return true; 11660 } 11661 11662 return false; 11663 } 11664 11665 SrcExpr = SingleFunctionExpression; 11666 return true; 11667 } 11668 11669 /// Add a single candidate to the overload set. 11670 static void AddOverloadedCallCandidate(Sema &S, 11671 DeclAccessPair FoundDecl, 11672 TemplateArgumentListInfo *ExplicitTemplateArgs, 11673 ArrayRef<Expr *> Args, 11674 OverloadCandidateSet &CandidateSet, 11675 bool PartialOverloading, 11676 bool KnownValid) { 11677 NamedDecl *Callee = FoundDecl.getDecl(); 11678 if (isa<UsingShadowDecl>(Callee)) 11679 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11680 11681 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11682 if (ExplicitTemplateArgs) { 11683 assert(!KnownValid && "Explicit template arguments?"); 11684 return; 11685 } 11686 // Prevent ill-formed function decls to be added as overload candidates. 11687 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11688 return; 11689 11690 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11691 /*SuppressUsedConversions=*/false, 11692 PartialOverloading); 11693 return; 11694 } 11695 11696 if (FunctionTemplateDecl *FuncTemplate 11697 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11698 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11699 ExplicitTemplateArgs, Args, CandidateSet, 11700 /*SuppressUsedConversions=*/false, 11701 PartialOverloading); 11702 return; 11703 } 11704 11705 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11706 } 11707 11708 /// Add the overload candidates named by callee and/or found by argument 11709 /// dependent lookup to the given overload set. 11710 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11711 ArrayRef<Expr *> Args, 11712 OverloadCandidateSet &CandidateSet, 11713 bool PartialOverloading) { 11714 11715 #ifndef NDEBUG 11716 // Verify that ArgumentDependentLookup is consistent with the rules 11717 // in C++0x [basic.lookup.argdep]p3: 11718 // 11719 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11720 // and let Y be the lookup set produced by argument dependent 11721 // lookup (defined as follows). If X contains 11722 // 11723 // -- a declaration of a class member, or 11724 // 11725 // -- a block-scope function declaration that is not a 11726 // using-declaration, or 11727 // 11728 // -- a declaration that is neither a function or a function 11729 // template 11730 // 11731 // then Y is empty. 11732 11733 if (ULE->requiresADL()) { 11734 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11735 E = ULE->decls_end(); I != E; ++I) { 11736 assert(!(*I)->getDeclContext()->isRecord()); 11737 assert(isa<UsingShadowDecl>(*I) || 11738 !(*I)->getDeclContext()->isFunctionOrMethod()); 11739 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11740 } 11741 } 11742 #endif 11743 11744 // It would be nice to avoid this copy. 11745 TemplateArgumentListInfo TABuffer; 11746 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11747 if (ULE->hasExplicitTemplateArgs()) { 11748 ULE->copyTemplateArgumentsInto(TABuffer); 11749 ExplicitTemplateArgs = &TABuffer; 11750 } 11751 11752 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11753 E = ULE->decls_end(); I != E; ++I) 11754 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11755 CandidateSet, PartialOverloading, 11756 /*KnownValid*/ true); 11757 11758 if (ULE->requiresADL()) 11759 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11760 Args, ExplicitTemplateArgs, 11761 CandidateSet, PartialOverloading); 11762 } 11763 11764 /// Determine whether a declaration with the specified name could be moved into 11765 /// a different namespace. 11766 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11767 switch (Name.getCXXOverloadedOperator()) { 11768 case OO_New: case OO_Array_New: 11769 case OO_Delete: case OO_Array_Delete: 11770 return false; 11771 11772 default: 11773 return true; 11774 } 11775 } 11776 11777 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11778 /// template, where the non-dependent name was declared after the template 11779 /// was defined. This is common in code written for a compilers which do not 11780 /// correctly implement two-stage name lookup. 11781 /// 11782 /// Returns true if a viable candidate was found and a diagnostic was issued. 11783 static bool 11784 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11785 const CXXScopeSpec &SS, LookupResult &R, 11786 OverloadCandidateSet::CandidateSetKind CSK, 11787 TemplateArgumentListInfo *ExplicitTemplateArgs, 11788 ArrayRef<Expr *> Args, 11789 bool *DoDiagnoseEmptyLookup = nullptr) { 11790 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 11791 return false; 11792 11793 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11794 if (DC->isTransparentContext()) 11795 continue; 11796 11797 SemaRef.LookupQualifiedName(R, DC); 11798 11799 if (!R.empty()) { 11800 R.suppressDiagnostics(); 11801 11802 if (isa<CXXRecordDecl>(DC)) { 11803 // Don't diagnose names we find in classes; we get much better 11804 // diagnostics for these from DiagnoseEmptyLookup. 11805 R.clear(); 11806 if (DoDiagnoseEmptyLookup) 11807 *DoDiagnoseEmptyLookup = true; 11808 return false; 11809 } 11810 11811 OverloadCandidateSet Candidates(FnLoc, CSK); 11812 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11813 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11814 ExplicitTemplateArgs, Args, 11815 Candidates, false, /*KnownValid*/ false); 11816 11817 OverloadCandidateSet::iterator Best; 11818 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11819 // No viable functions. Don't bother the user with notes for functions 11820 // which don't work and shouldn't be found anyway. 11821 R.clear(); 11822 return false; 11823 } 11824 11825 // Find the namespaces where ADL would have looked, and suggest 11826 // declaring the function there instead. 11827 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11828 Sema::AssociatedClassSet AssociatedClasses; 11829 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11830 AssociatedNamespaces, 11831 AssociatedClasses); 11832 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11833 if (canBeDeclaredInNamespace(R.getLookupName())) { 11834 DeclContext *Std = SemaRef.getStdNamespace(); 11835 for (Sema::AssociatedNamespaceSet::iterator 11836 it = AssociatedNamespaces.begin(), 11837 end = AssociatedNamespaces.end(); it != end; ++it) { 11838 // Never suggest declaring a function within namespace 'std'. 11839 if (Std && Std->Encloses(*it)) 11840 continue; 11841 11842 // Never suggest declaring a function within a namespace with a 11843 // reserved name, like __gnu_cxx. 11844 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11845 if (NS && 11846 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11847 continue; 11848 11849 SuggestedNamespaces.insert(*it); 11850 } 11851 } 11852 11853 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11854 << R.getLookupName(); 11855 if (SuggestedNamespaces.empty()) { 11856 SemaRef.Diag(Best->Function->getLocation(), 11857 diag::note_not_found_by_two_phase_lookup) 11858 << R.getLookupName() << 0; 11859 } else if (SuggestedNamespaces.size() == 1) { 11860 SemaRef.Diag(Best->Function->getLocation(), 11861 diag::note_not_found_by_two_phase_lookup) 11862 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11863 } else { 11864 // FIXME: It would be useful to list the associated namespaces here, 11865 // but the diagnostics infrastructure doesn't provide a way to produce 11866 // a localized representation of a list of items. 11867 SemaRef.Diag(Best->Function->getLocation(), 11868 diag::note_not_found_by_two_phase_lookup) 11869 << R.getLookupName() << 2; 11870 } 11871 11872 // Try to recover by calling this function. 11873 return true; 11874 } 11875 11876 R.clear(); 11877 } 11878 11879 return false; 11880 } 11881 11882 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11883 /// template, where the non-dependent operator was declared after the template 11884 /// was defined. 11885 /// 11886 /// Returns true if a viable candidate was found and a diagnostic was issued. 11887 static bool 11888 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11889 SourceLocation OpLoc, 11890 ArrayRef<Expr *> Args) { 11891 DeclarationName OpName = 11892 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11893 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11894 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11895 OverloadCandidateSet::CSK_Operator, 11896 /*ExplicitTemplateArgs=*/nullptr, Args); 11897 } 11898 11899 namespace { 11900 class BuildRecoveryCallExprRAII { 11901 Sema &SemaRef; 11902 public: 11903 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11904 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11905 SemaRef.IsBuildingRecoveryCallExpr = true; 11906 } 11907 11908 ~BuildRecoveryCallExprRAII() { 11909 SemaRef.IsBuildingRecoveryCallExpr = false; 11910 } 11911 }; 11912 11913 } 11914 11915 static std::unique_ptr<CorrectionCandidateCallback> 11916 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11917 bool HasTemplateArgs, bool AllowTypoCorrection) { 11918 if (!AllowTypoCorrection) 11919 return llvm::make_unique<NoTypoCorrectionCCC>(); 11920 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11921 HasTemplateArgs, ME); 11922 } 11923 11924 /// Attempts to recover from a call where no functions were found. 11925 /// 11926 /// Returns true if new candidates were found. 11927 static ExprResult 11928 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11929 UnresolvedLookupExpr *ULE, 11930 SourceLocation LParenLoc, 11931 MutableArrayRef<Expr *> Args, 11932 SourceLocation RParenLoc, 11933 bool EmptyLookup, bool AllowTypoCorrection) { 11934 // Do not try to recover if it is already building a recovery call. 11935 // This stops infinite loops for template instantiations like 11936 // 11937 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11938 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11939 // 11940 if (SemaRef.IsBuildingRecoveryCallExpr) 11941 return ExprError(); 11942 BuildRecoveryCallExprRAII RCE(SemaRef); 11943 11944 CXXScopeSpec SS; 11945 SS.Adopt(ULE->getQualifierLoc()); 11946 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11947 11948 TemplateArgumentListInfo TABuffer; 11949 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11950 if (ULE->hasExplicitTemplateArgs()) { 11951 ULE->copyTemplateArgumentsInto(TABuffer); 11952 ExplicitTemplateArgs = &TABuffer; 11953 } 11954 11955 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11956 Sema::LookupOrdinaryName); 11957 bool DoDiagnoseEmptyLookup = EmptyLookup; 11958 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11959 OverloadCandidateSet::CSK_Normal, 11960 ExplicitTemplateArgs, Args, 11961 &DoDiagnoseEmptyLookup) && 11962 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11963 S, SS, R, 11964 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11965 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11966 ExplicitTemplateArgs, Args))) 11967 return ExprError(); 11968 11969 assert(!R.empty() && "lookup results empty despite recovery"); 11970 11971 // If recovery created an ambiguity, just bail out. 11972 if (R.isAmbiguous()) { 11973 R.suppressDiagnostics(); 11974 return ExprError(); 11975 } 11976 11977 // Build an implicit member call if appropriate. Just drop the 11978 // casts and such from the call, we don't really care. 11979 ExprResult NewFn = ExprError(); 11980 if ((*R.begin())->isCXXClassMember()) 11981 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11982 ExplicitTemplateArgs, S); 11983 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11984 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11985 ExplicitTemplateArgs); 11986 else 11987 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11988 11989 if (NewFn.isInvalid()) 11990 return ExprError(); 11991 11992 // This shouldn't cause an infinite loop because we're giving it 11993 // an expression with viable lookup results, which should never 11994 // end up here. 11995 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11996 MultiExprArg(Args.data(), Args.size()), 11997 RParenLoc); 11998 } 11999 12000 /// Constructs and populates an OverloadedCandidateSet from 12001 /// the given function. 12002 /// \returns true when an the ExprResult output parameter has been set. 12003 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12004 UnresolvedLookupExpr *ULE, 12005 MultiExprArg Args, 12006 SourceLocation RParenLoc, 12007 OverloadCandidateSet *CandidateSet, 12008 ExprResult *Result) { 12009 #ifndef NDEBUG 12010 if (ULE->requiresADL()) { 12011 // To do ADL, we must have found an unqualified name. 12012 assert(!ULE->getQualifier() && "qualified name with ADL"); 12013 12014 // We don't perform ADL for implicit declarations of builtins. 12015 // Verify that this was correctly set up. 12016 FunctionDecl *F; 12017 if (ULE->decls_begin() + 1 == ULE->decls_end() && 12018 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12019 F->getBuiltinID() && F->isImplicit()) 12020 llvm_unreachable("performing ADL for builtin"); 12021 12022 // We don't perform ADL in C. 12023 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12024 } 12025 #endif 12026 12027 UnbridgedCastsSet UnbridgedCasts; 12028 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12029 *Result = ExprError(); 12030 return true; 12031 } 12032 12033 // Add the functions denoted by the callee to the set of candidate 12034 // functions, including those from argument-dependent lookup. 12035 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12036 12037 if (getLangOpts().MSVCCompat && 12038 CurContext->isDependentContext() && !isSFINAEContext() && 12039 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12040 12041 OverloadCandidateSet::iterator Best; 12042 if (CandidateSet->empty() || 12043 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12044 OR_No_Viable_Function) { 12045 // In Microsoft mode, if we are inside a template class member function 12046 // then create a type dependent CallExpr. The goal is to postpone name 12047 // lookup to instantiation time to be able to search into type dependent 12048 // base classes. 12049 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12050 VK_RValue, RParenLoc); 12051 CE->setTypeDependent(true); 12052 CE->setValueDependent(true); 12053 CE->setInstantiationDependent(true); 12054 *Result = CE; 12055 return true; 12056 } 12057 } 12058 12059 if (CandidateSet->empty()) 12060 return false; 12061 12062 UnbridgedCasts.restore(); 12063 return false; 12064 } 12065 12066 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12067 /// the completed call expression. If overload resolution fails, emits 12068 /// diagnostics and returns ExprError() 12069 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12070 UnresolvedLookupExpr *ULE, 12071 SourceLocation LParenLoc, 12072 MultiExprArg Args, 12073 SourceLocation RParenLoc, 12074 Expr *ExecConfig, 12075 OverloadCandidateSet *CandidateSet, 12076 OverloadCandidateSet::iterator *Best, 12077 OverloadingResult OverloadResult, 12078 bool AllowTypoCorrection) { 12079 if (CandidateSet->empty()) 12080 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12081 RParenLoc, /*EmptyLookup=*/true, 12082 AllowTypoCorrection); 12083 12084 switch (OverloadResult) { 12085 case OR_Success: { 12086 FunctionDecl *FDecl = (*Best)->Function; 12087 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12088 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12089 return ExprError(); 12090 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12091 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12092 ExecConfig, /*IsExecConfig=*/false, 12093 (*Best)->IsADLCandidate); 12094 } 12095 12096 case OR_No_Viable_Function: { 12097 // Try to recover by looking for viable functions which the user might 12098 // have meant to call. 12099 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12100 Args, RParenLoc, 12101 /*EmptyLookup=*/false, 12102 AllowTypoCorrection); 12103 if (!Recovery.isInvalid()) 12104 return Recovery; 12105 12106 // If the user passes in a function that we can't take the address of, we 12107 // generally end up emitting really bad error messages. Here, we attempt to 12108 // emit better ones. 12109 for (const Expr *Arg : Args) { 12110 if (!Arg->getType()->isFunctionType()) 12111 continue; 12112 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12113 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12114 if (FD && 12115 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12116 Arg->getExprLoc())) 12117 return ExprError(); 12118 } 12119 } 12120 12121 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call) 12122 << ULE->getName() << Fn->getSourceRange(); 12123 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12124 break; 12125 } 12126 12127 case OR_Ambiguous: 12128 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call) 12129 << ULE->getName() << Fn->getSourceRange(); 12130 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 12131 break; 12132 12133 case OR_Deleted: { 12134 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call) 12135 << (*Best)->Function->isDeleted() << ULE->getName() 12136 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 12137 << Fn->getSourceRange(); 12138 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12139 12140 // We emitted an error for the unavailable/deleted function call but keep 12141 // the call in the AST. 12142 FunctionDecl *FDecl = (*Best)->Function; 12143 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12144 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12145 ExecConfig, /*IsExecConfig=*/false, 12146 (*Best)->IsADLCandidate); 12147 } 12148 } 12149 12150 // Overload resolution failed. 12151 return ExprError(); 12152 } 12153 12154 static void markUnaddressableCandidatesUnviable(Sema &S, 12155 OverloadCandidateSet &CS) { 12156 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12157 if (I->Viable && 12158 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12159 I->Viable = false; 12160 I->FailureKind = ovl_fail_addr_not_available; 12161 } 12162 } 12163 } 12164 12165 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12166 /// (which eventually refers to the declaration Func) and the call 12167 /// arguments Args/NumArgs, attempt to resolve the function call down 12168 /// to a specific function. If overload resolution succeeds, returns 12169 /// the call expression produced by overload resolution. 12170 /// Otherwise, emits diagnostics and returns ExprError. 12171 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12172 UnresolvedLookupExpr *ULE, 12173 SourceLocation LParenLoc, 12174 MultiExprArg Args, 12175 SourceLocation RParenLoc, 12176 Expr *ExecConfig, 12177 bool AllowTypoCorrection, 12178 bool CalleesAddressIsTaken) { 12179 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12180 OverloadCandidateSet::CSK_Normal); 12181 ExprResult result; 12182 12183 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12184 &result)) 12185 return result; 12186 12187 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12188 // functions that aren't addressible are considered unviable. 12189 if (CalleesAddressIsTaken) 12190 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12191 12192 OverloadCandidateSet::iterator Best; 12193 OverloadingResult OverloadResult = 12194 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12195 12196 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 12197 RParenLoc, ExecConfig, &CandidateSet, 12198 &Best, OverloadResult, 12199 AllowTypoCorrection); 12200 } 12201 12202 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12203 return Functions.size() > 1 || 12204 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12205 } 12206 12207 /// Create a unary operation that may resolve to an overloaded 12208 /// operator. 12209 /// 12210 /// \param OpLoc The location of the operator itself (e.g., '*'). 12211 /// 12212 /// \param Opc The UnaryOperatorKind that describes this operator. 12213 /// 12214 /// \param Fns The set of non-member functions that will be 12215 /// considered by overload resolution. The caller needs to build this 12216 /// set based on the context using, e.g., 12217 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12218 /// set should not contain any member functions; those will be added 12219 /// by CreateOverloadedUnaryOp(). 12220 /// 12221 /// \param Input The input argument. 12222 ExprResult 12223 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12224 const UnresolvedSetImpl &Fns, 12225 Expr *Input, bool PerformADL) { 12226 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12227 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12228 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12229 // TODO: provide better source location info. 12230 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12231 12232 if (checkPlaceholderForOverload(*this, Input)) 12233 return ExprError(); 12234 12235 Expr *Args[2] = { Input, nullptr }; 12236 unsigned NumArgs = 1; 12237 12238 // For post-increment and post-decrement, add the implicit '0' as 12239 // the second argument, so that we know this is a post-increment or 12240 // post-decrement. 12241 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12242 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12243 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12244 SourceLocation()); 12245 NumArgs = 2; 12246 } 12247 12248 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12249 12250 if (Input->isTypeDependent()) { 12251 if (Fns.empty()) 12252 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12253 VK_RValue, OK_Ordinary, OpLoc, false); 12254 12255 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12256 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12257 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12258 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12259 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12260 Context.DependentTy, VK_RValue, OpLoc, 12261 FPOptions()); 12262 } 12263 12264 // Build an empty overload set. 12265 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12266 12267 // Add the candidates from the given function set. 12268 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 12269 12270 // Add operator candidates that are member functions. 12271 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12272 12273 // Add candidates from ADL. 12274 if (PerformADL) { 12275 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12276 /*ExplicitTemplateArgs*/nullptr, 12277 CandidateSet); 12278 } 12279 12280 // Add builtin operator candidates. 12281 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12282 12283 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12284 12285 // Perform overload resolution. 12286 OverloadCandidateSet::iterator Best; 12287 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12288 case OR_Success: { 12289 // We found a built-in operator or an overloaded operator. 12290 FunctionDecl *FnDecl = Best->Function; 12291 12292 if (FnDecl) { 12293 Expr *Base = nullptr; 12294 // We matched an overloaded operator. Build a call to that 12295 // operator. 12296 12297 // Convert the arguments. 12298 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12299 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12300 12301 ExprResult InputRes = 12302 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12303 Best->FoundDecl, Method); 12304 if (InputRes.isInvalid()) 12305 return ExprError(); 12306 Base = Input = InputRes.get(); 12307 } else { 12308 // Convert the arguments. 12309 ExprResult InputInit 12310 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12311 Context, 12312 FnDecl->getParamDecl(0)), 12313 SourceLocation(), 12314 Input); 12315 if (InputInit.isInvalid()) 12316 return ExprError(); 12317 Input = InputInit.get(); 12318 } 12319 12320 // Build the actual expression node. 12321 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12322 Base, HadMultipleCandidates, 12323 OpLoc); 12324 if (FnExpr.isInvalid()) 12325 return ExprError(); 12326 12327 // Determine the result type. 12328 QualType ResultTy = FnDecl->getReturnType(); 12329 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12330 ResultTy = ResultTy.getNonLValueExprType(Context); 12331 12332 Args[0] = Input; 12333 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12334 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 12335 FPOptions(), Best->IsADLCandidate); 12336 12337 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12338 return ExprError(); 12339 12340 if (CheckFunctionCall(FnDecl, TheCall, 12341 FnDecl->getType()->castAs<FunctionProtoType>())) 12342 return ExprError(); 12343 12344 return MaybeBindToTemporary(TheCall); 12345 } else { 12346 // We matched a built-in operator. Convert the arguments, then 12347 // break out so that we will build the appropriate built-in 12348 // operator node. 12349 ExprResult InputRes = PerformImplicitConversion( 12350 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12351 CCK_ForBuiltinOverloadedOp); 12352 if (InputRes.isInvalid()) 12353 return ExprError(); 12354 Input = InputRes.get(); 12355 break; 12356 } 12357 } 12358 12359 case OR_No_Viable_Function: 12360 // This is an erroneous use of an operator which can be overloaded by 12361 // a non-member function. Check for non-member operators which were 12362 // defined too late to be candidates. 12363 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12364 // FIXME: Recover by calling the found function. 12365 return ExprError(); 12366 12367 // No viable function; fall through to handling this as a 12368 // built-in operator, which will produce an error message for us. 12369 break; 12370 12371 case OR_Ambiguous: 12372 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12373 << UnaryOperator::getOpcodeStr(Opc) 12374 << Input->getType() 12375 << Input->getSourceRange(); 12376 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 12377 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12378 return ExprError(); 12379 12380 case OR_Deleted: 12381 Diag(OpLoc, diag::err_ovl_deleted_oper) 12382 << Best->Function->isDeleted() 12383 << UnaryOperator::getOpcodeStr(Opc) 12384 << getDeletedOrUnavailableSuffix(Best->Function) 12385 << Input->getSourceRange(); 12386 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 12387 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12388 return ExprError(); 12389 } 12390 12391 // Either we found no viable overloaded operator or we matched a 12392 // built-in operator. In either case, fall through to trying to 12393 // build a built-in operation. 12394 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12395 } 12396 12397 /// Create a binary operation that may resolve to an overloaded 12398 /// operator. 12399 /// 12400 /// \param OpLoc The location of the operator itself (e.g., '+'). 12401 /// 12402 /// \param Opc The BinaryOperatorKind that describes this operator. 12403 /// 12404 /// \param Fns The set of non-member functions that will be 12405 /// considered by overload resolution. The caller needs to build this 12406 /// set based on the context using, e.g., 12407 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12408 /// set should not contain any member functions; those will be added 12409 /// by CreateOverloadedBinOp(). 12410 /// 12411 /// \param LHS Left-hand argument. 12412 /// \param RHS Right-hand argument. 12413 ExprResult 12414 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12415 BinaryOperatorKind Opc, 12416 const UnresolvedSetImpl &Fns, 12417 Expr *LHS, Expr *RHS, bool PerformADL) { 12418 Expr *Args[2] = { LHS, RHS }; 12419 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12420 12421 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12422 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12423 12424 // If either side is type-dependent, create an appropriate dependent 12425 // expression. 12426 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12427 if (Fns.empty()) { 12428 // If there are no functions to store, just build a dependent 12429 // BinaryOperator or CompoundAssignment. 12430 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12431 return new (Context) BinaryOperator( 12432 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12433 OpLoc, FPFeatures); 12434 12435 return new (Context) CompoundAssignOperator( 12436 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12437 Context.DependentTy, Context.DependentTy, OpLoc, 12438 FPFeatures); 12439 } 12440 12441 // FIXME: save results of ADL from here? 12442 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12443 // TODO: provide better source location info in DNLoc component. 12444 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12445 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12446 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12447 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12448 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 12449 Context.DependentTy, VK_RValue, OpLoc, 12450 FPFeatures); 12451 } 12452 12453 // Always do placeholder-like conversions on the RHS. 12454 if (checkPlaceholderForOverload(*this, Args[1])) 12455 return ExprError(); 12456 12457 // Do placeholder-like conversion on the LHS; note that we should 12458 // not get here with a PseudoObject LHS. 12459 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12460 if (checkPlaceholderForOverload(*this, Args[0])) 12461 return ExprError(); 12462 12463 // If this is the assignment operator, we only perform overload resolution 12464 // if the left-hand side is a class or enumeration type. This is actually 12465 // a hack. The standard requires that we do overload resolution between the 12466 // various built-in candidates, but as DR507 points out, this can lead to 12467 // problems. So we do it this way, which pretty much follows what GCC does. 12468 // Note that we go the traditional code path for compound assignment forms. 12469 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12470 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12471 12472 // If this is the .* operator, which is not overloadable, just 12473 // create a built-in binary operator. 12474 if (Opc == BO_PtrMemD) 12475 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12476 12477 // Build an empty overload set. 12478 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12479 12480 // Add the candidates from the given function set. 12481 AddFunctionCandidates(Fns, Args, CandidateSet); 12482 12483 // Add operator candidates that are member functions. 12484 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12485 12486 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12487 // performed for an assignment operator (nor for operator[] nor operator->, 12488 // which don't get here). 12489 if (Opc != BO_Assign && PerformADL) 12490 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12491 /*ExplicitTemplateArgs*/ nullptr, 12492 CandidateSet); 12493 12494 // Add builtin operator candidates. 12495 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12496 12497 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12498 12499 // Perform overload resolution. 12500 OverloadCandidateSet::iterator Best; 12501 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12502 case OR_Success: { 12503 // We found a built-in operator or an overloaded operator. 12504 FunctionDecl *FnDecl = Best->Function; 12505 12506 if (FnDecl) { 12507 Expr *Base = nullptr; 12508 // We matched an overloaded operator. Build a call to that 12509 // operator. 12510 12511 // Convert the arguments. 12512 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12513 // Best->Access is only meaningful for class members. 12514 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12515 12516 ExprResult Arg1 = 12517 PerformCopyInitialization( 12518 InitializedEntity::InitializeParameter(Context, 12519 FnDecl->getParamDecl(0)), 12520 SourceLocation(), Args[1]); 12521 if (Arg1.isInvalid()) 12522 return ExprError(); 12523 12524 ExprResult Arg0 = 12525 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12526 Best->FoundDecl, Method); 12527 if (Arg0.isInvalid()) 12528 return ExprError(); 12529 Base = Args[0] = Arg0.getAs<Expr>(); 12530 Args[1] = RHS = Arg1.getAs<Expr>(); 12531 } else { 12532 // Convert the arguments. 12533 ExprResult Arg0 = PerformCopyInitialization( 12534 InitializedEntity::InitializeParameter(Context, 12535 FnDecl->getParamDecl(0)), 12536 SourceLocation(), Args[0]); 12537 if (Arg0.isInvalid()) 12538 return ExprError(); 12539 12540 ExprResult Arg1 = 12541 PerformCopyInitialization( 12542 InitializedEntity::InitializeParameter(Context, 12543 FnDecl->getParamDecl(1)), 12544 SourceLocation(), Args[1]); 12545 if (Arg1.isInvalid()) 12546 return ExprError(); 12547 Args[0] = LHS = Arg0.getAs<Expr>(); 12548 Args[1] = RHS = Arg1.getAs<Expr>(); 12549 } 12550 12551 // Build the actual expression node. 12552 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12553 Best->FoundDecl, Base, 12554 HadMultipleCandidates, OpLoc); 12555 if (FnExpr.isInvalid()) 12556 return ExprError(); 12557 12558 // Determine the result type. 12559 QualType ResultTy = FnDecl->getReturnType(); 12560 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12561 ResultTy = ResultTy.getNonLValueExprType(Context); 12562 12563 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 12564 Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures, 12565 Best->IsADLCandidate); 12566 12567 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12568 FnDecl)) 12569 return ExprError(); 12570 12571 ArrayRef<const Expr *> ArgsArray(Args, 2); 12572 const Expr *ImplicitThis = nullptr; 12573 // Cut off the implicit 'this'. 12574 if (isa<CXXMethodDecl>(FnDecl)) { 12575 ImplicitThis = ArgsArray[0]; 12576 ArgsArray = ArgsArray.slice(1); 12577 } 12578 12579 // Check for a self move. 12580 if (Op == OO_Equal) 12581 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12582 12583 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12584 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12585 VariadicDoesNotApply); 12586 12587 return MaybeBindToTemporary(TheCall); 12588 } else { 12589 // We matched a built-in operator. Convert the arguments, then 12590 // break out so that we will build the appropriate built-in 12591 // operator node. 12592 ExprResult ArgsRes0 = PerformImplicitConversion( 12593 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12594 AA_Passing, CCK_ForBuiltinOverloadedOp); 12595 if (ArgsRes0.isInvalid()) 12596 return ExprError(); 12597 Args[0] = ArgsRes0.get(); 12598 12599 ExprResult ArgsRes1 = PerformImplicitConversion( 12600 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12601 AA_Passing, CCK_ForBuiltinOverloadedOp); 12602 if (ArgsRes1.isInvalid()) 12603 return ExprError(); 12604 Args[1] = ArgsRes1.get(); 12605 break; 12606 } 12607 } 12608 12609 case OR_No_Viable_Function: { 12610 // C++ [over.match.oper]p9: 12611 // If the operator is the operator , [...] and there are no 12612 // viable functions, then the operator is assumed to be the 12613 // built-in operator and interpreted according to clause 5. 12614 if (Opc == BO_Comma) 12615 break; 12616 12617 // For class as left operand for assignment or compound assignment 12618 // operator do not fall through to handling in built-in, but report that 12619 // no overloaded assignment operator found 12620 ExprResult Result = ExprError(); 12621 if (Args[0]->getType()->isRecordType() && 12622 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12623 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12624 << BinaryOperator::getOpcodeStr(Opc) 12625 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12626 if (Args[0]->getType()->isIncompleteType()) { 12627 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12628 << Args[0]->getType() 12629 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12630 } 12631 } else { 12632 // This is an erroneous use of an operator which can be overloaded by 12633 // a non-member function. Check for non-member operators which were 12634 // defined too late to be candidates. 12635 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12636 // FIXME: Recover by calling the found function. 12637 return ExprError(); 12638 12639 // No viable function; try to create a built-in operation, which will 12640 // produce an error. Then, show the non-viable candidates. 12641 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12642 } 12643 assert(Result.isInvalid() && 12644 "C++ binary operator overloading is missing candidates!"); 12645 if (Result.isInvalid()) 12646 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12647 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12648 return Result; 12649 } 12650 12651 case OR_Ambiguous: 12652 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12653 << BinaryOperator::getOpcodeStr(Opc) 12654 << Args[0]->getType() << Args[1]->getType() 12655 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12656 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12657 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12658 return ExprError(); 12659 12660 case OR_Deleted: 12661 if (isImplicitlyDeleted(Best->Function)) { 12662 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12663 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12664 << Context.getRecordType(Method->getParent()) 12665 << getSpecialMember(Method); 12666 12667 // The user probably meant to call this special member. Just 12668 // explain why it's deleted. 12669 NoteDeletedFunction(Method); 12670 return ExprError(); 12671 } else { 12672 Diag(OpLoc, diag::err_ovl_deleted_oper) 12673 << Best->Function->isDeleted() 12674 << BinaryOperator::getOpcodeStr(Opc) 12675 << getDeletedOrUnavailableSuffix(Best->Function) 12676 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12677 } 12678 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12679 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12680 return ExprError(); 12681 } 12682 12683 // We matched a built-in operator; build it. 12684 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12685 } 12686 12687 ExprResult 12688 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12689 SourceLocation RLoc, 12690 Expr *Base, Expr *Idx) { 12691 Expr *Args[2] = { Base, Idx }; 12692 DeclarationName OpName = 12693 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12694 12695 // If either side is type-dependent, create an appropriate dependent 12696 // expression. 12697 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12698 12699 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12700 // CHECKME: no 'operator' keyword? 12701 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12702 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12703 UnresolvedLookupExpr *Fn 12704 = UnresolvedLookupExpr::Create(Context, NamingClass, 12705 NestedNameSpecifierLoc(), OpNameInfo, 12706 /*ADL*/ true, /*Overloaded*/ false, 12707 UnresolvedSetIterator(), 12708 UnresolvedSetIterator()); 12709 // Can't add any actual overloads yet 12710 12711 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 12712 Context.DependentTy, VK_RValue, RLoc, 12713 FPOptions()); 12714 } 12715 12716 // Handle placeholders on both operands. 12717 if (checkPlaceholderForOverload(*this, Args[0])) 12718 return ExprError(); 12719 if (checkPlaceholderForOverload(*this, Args[1])) 12720 return ExprError(); 12721 12722 // Build an empty overload set. 12723 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12724 12725 // Subscript can only be overloaded as a member function. 12726 12727 // Add operator candidates that are member functions. 12728 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12729 12730 // Add builtin operator candidates. 12731 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12732 12733 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12734 12735 // Perform overload resolution. 12736 OverloadCandidateSet::iterator Best; 12737 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12738 case OR_Success: { 12739 // We found a built-in operator or an overloaded operator. 12740 FunctionDecl *FnDecl = Best->Function; 12741 12742 if (FnDecl) { 12743 // We matched an overloaded operator. Build a call to that 12744 // operator. 12745 12746 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12747 12748 // Convert the arguments. 12749 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12750 ExprResult Arg0 = 12751 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12752 Best->FoundDecl, Method); 12753 if (Arg0.isInvalid()) 12754 return ExprError(); 12755 Args[0] = Arg0.get(); 12756 12757 // Convert the arguments. 12758 ExprResult InputInit 12759 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12760 Context, 12761 FnDecl->getParamDecl(0)), 12762 SourceLocation(), 12763 Args[1]); 12764 if (InputInit.isInvalid()) 12765 return ExprError(); 12766 12767 Args[1] = InputInit.getAs<Expr>(); 12768 12769 // Build the actual expression node. 12770 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12771 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12772 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12773 Best->FoundDecl, 12774 Base, 12775 HadMultipleCandidates, 12776 OpLocInfo.getLoc(), 12777 OpLocInfo.getInfo()); 12778 if (FnExpr.isInvalid()) 12779 return ExprError(); 12780 12781 // Determine the result type 12782 QualType ResultTy = FnDecl->getReturnType(); 12783 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12784 ResultTy = ResultTy.getNonLValueExprType(Context); 12785 12786 CXXOperatorCallExpr *TheCall = 12787 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 12788 Args, ResultTy, VK, RLoc, FPOptions()); 12789 12790 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12791 return ExprError(); 12792 12793 if (CheckFunctionCall(Method, TheCall, 12794 Method->getType()->castAs<FunctionProtoType>())) 12795 return ExprError(); 12796 12797 return MaybeBindToTemporary(TheCall); 12798 } else { 12799 // We matched a built-in operator. Convert the arguments, then 12800 // break out so that we will build the appropriate built-in 12801 // operator node. 12802 ExprResult ArgsRes0 = PerformImplicitConversion( 12803 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12804 AA_Passing, CCK_ForBuiltinOverloadedOp); 12805 if (ArgsRes0.isInvalid()) 12806 return ExprError(); 12807 Args[0] = ArgsRes0.get(); 12808 12809 ExprResult ArgsRes1 = PerformImplicitConversion( 12810 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12811 AA_Passing, CCK_ForBuiltinOverloadedOp); 12812 if (ArgsRes1.isInvalid()) 12813 return ExprError(); 12814 Args[1] = ArgsRes1.get(); 12815 12816 break; 12817 } 12818 } 12819 12820 case OR_No_Viable_Function: { 12821 if (CandidateSet.empty()) 12822 Diag(LLoc, diag::err_ovl_no_oper) 12823 << Args[0]->getType() << /*subscript*/ 0 12824 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12825 else 12826 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12827 << Args[0]->getType() 12828 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12829 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12830 "[]", LLoc); 12831 return ExprError(); 12832 } 12833 12834 case OR_Ambiguous: 12835 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12836 << "[]" 12837 << Args[0]->getType() << Args[1]->getType() 12838 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12839 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12840 "[]", LLoc); 12841 return ExprError(); 12842 12843 case OR_Deleted: 12844 Diag(LLoc, diag::err_ovl_deleted_oper) 12845 << Best->Function->isDeleted() << "[]" 12846 << getDeletedOrUnavailableSuffix(Best->Function) 12847 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12848 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12849 "[]", LLoc); 12850 return ExprError(); 12851 } 12852 12853 // We matched a built-in operator; build it. 12854 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12855 } 12856 12857 /// BuildCallToMemberFunction - Build a call to a member 12858 /// function. MemExpr is the expression that refers to the member 12859 /// function (and includes the object parameter), Args/NumArgs are the 12860 /// arguments to the function call (not including the object 12861 /// parameter). The caller needs to validate that the member 12862 /// expression refers to a non-static member function or an overloaded 12863 /// member function. 12864 ExprResult 12865 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12866 SourceLocation LParenLoc, 12867 MultiExprArg Args, 12868 SourceLocation RParenLoc) { 12869 assert(MemExprE->getType() == Context.BoundMemberTy || 12870 MemExprE->getType() == Context.OverloadTy); 12871 12872 // Dig out the member expression. This holds both the object 12873 // argument and the member function we're referring to. 12874 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12875 12876 // Determine whether this is a call to a pointer-to-member function. 12877 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12878 assert(op->getType() == Context.BoundMemberTy); 12879 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12880 12881 QualType fnType = 12882 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12883 12884 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12885 QualType resultType = proto->getCallResultType(Context); 12886 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12887 12888 // Check that the object type isn't more qualified than the 12889 // member function we're calling. 12890 Qualifiers funcQuals = proto->getMethodQuals(); 12891 12892 QualType objectType = op->getLHS()->getType(); 12893 if (op->getOpcode() == BO_PtrMemI) 12894 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12895 Qualifiers objectQuals = objectType.getQualifiers(); 12896 12897 Qualifiers difference = objectQuals - funcQuals; 12898 difference.removeObjCGCAttr(); 12899 difference.removeAddressSpace(); 12900 if (difference) { 12901 std::string qualsString = difference.getAsString(); 12902 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12903 << fnType.getUnqualifiedType() 12904 << qualsString 12905 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12906 } 12907 12908 CXXMemberCallExpr *call = 12909 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 12910 valueKind, RParenLoc, proto->getNumParams()); 12911 12912 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 12913 call, nullptr)) 12914 return ExprError(); 12915 12916 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12917 return ExprError(); 12918 12919 if (CheckOtherCall(call, proto)) 12920 return ExprError(); 12921 12922 return MaybeBindToTemporary(call); 12923 } 12924 12925 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12926 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 12927 RParenLoc); 12928 12929 UnbridgedCastsSet UnbridgedCasts; 12930 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12931 return ExprError(); 12932 12933 MemberExpr *MemExpr; 12934 CXXMethodDecl *Method = nullptr; 12935 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12936 NestedNameSpecifier *Qualifier = nullptr; 12937 if (isa<MemberExpr>(NakedMemExpr)) { 12938 MemExpr = cast<MemberExpr>(NakedMemExpr); 12939 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12940 FoundDecl = MemExpr->getFoundDecl(); 12941 Qualifier = MemExpr->getQualifier(); 12942 UnbridgedCasts.restore(); 12943 } else { 12944 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12945 Qualifier = UnresExpr->getQualifier(); 12946 12947 QualType ObjectType = UnresExpr->getBaseType(); 12948 Expr::Classification ObjectClassification 12949 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12950 : UnresExpr->getBase()->Classify(Context); 12951 12952 // Add overload candidates 12953 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12954 OverloadCandidateSet::CSK_Normal); 12955 12956 // FIXME: avoid copy. 12957 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12958 if (UnresExpr->hasExplicitTemplateArgs()) { 12959 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12960 TemplateArgs = &TemplateArgsBuffer; 12961 } 12962 12963 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12964 E = UnresExpr->decls_end(); I != E; ++I) { 12965 12966 NamedDecl *Func = *I; 12967 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12968 if (isa<UsingShadowDecl>(Func)) 12969 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12970 12971 12972 // Microsoft supports direct constructor calls. 12973 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12974 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12975 Args, CandidateSet); 12976 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12977 // If explicit template arguments were provided, we can't call a 12978 // non-template member function. 12979 if (TemplateArgs) 12980 continue; 12981 12982 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12983 ObjectClassification, Args, CandidateSet, 12984 /*SuppressUserConversions=*/false); 12985 } else { 12986 AddMethodTemplateCandidate( 12987 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 12988 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 12989 /*SuppressUsedConversions=*/false); 12990 } 12991 } 12992 12993 DeclarationName DeclName = UnresExpr->getMemberName(); 12994 12995 UnbridgedCasts.restore(); 12996 12997 OverloadCandidateSet::iterator Best; 12998 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 12999 Best)) { 13000 case OR_Success: 13001 Method = cast<CXXMethodDecl>(Best->Function); 13002 FoundDecl = Best->FoundDecl; 13003 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13004 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13005 return ExprError(); 13006 // If FoundDecl is different from Method (such as if one is a template 13007 // and the other a specialization), make sure DiagnoseUseOfDecl is 13008 // called on both. 13009 // FIXME: This would be more comprehensively addressed by modifying 13010 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13011 // being used. 13012 if (Method != FoundDecl.getDecl() && 13013 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13014 return ExprError(); 13015 break; 13016 13017 case OR_No_Viable_Function: 13018 Diag(UnresExpr->getMemberLoc(), 13019 diag::err_ovl_no_viable_member_function_in_call) 13020 << DeclName << MemExprE->getSourceRange(); 13021 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13022 // FIXME: Leaking incoming expressions! 13023 return ExprError(); 13024 13025 case OR_Ambiguous: 13026 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 13027 << DeclName << MemExprE->getSourceRange(); 13028 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13029 // FIXME: Leaking incoming expressions! 13030 return ExprError(); 13031 13032 case OR_Deleted: 13033 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 13034 << Best->Function->isDeleted() 13035 << DeclName 13036 << getDeletedOrUnavailableSuffix(Best->Function) 13037 << MemExprE->getSourceRange(); 13038 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13039 // FIXME: Leaking incoming expressions! 13040 return ExprError(); 13041 } 13042 13043 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13044 13045 // If overload resolution picked a static member, build a 13046 // non-member call based on that function. 13047 if (Method->isStatic()) { 13048 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13049 RParenLoc); 13050 } 13051 13052 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13053 } 13054 13055 QualType ResultType = Method->getReturnType(); 13056 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13057 ResultType = ResultType.getNonLValueExprType(Context); 13058 13059 assert(Method && "Member call to something that isn't a method?"); 13060 const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); 13061 CXXMemberCallExpr *TheCall = 13062 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13063 RParenLoc, Proto->getNumParams()); 13064 13065 // Check for a valid return type. 13066 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13067 TheCall, Method)) 13068 return ExprError(); 13069 13070 // Convert the object argument (for a non-static member function call). 13071 // We only need to do this if there was actually an overload; otherwise 13072 // it was done at lookup. 13073 if (!Method->isStatic()) { 13074 ExprResult ObjectArg = 13075 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13076 FoundDecl, Method); 13077 if (ObjectArg.isInvalid()) 13078 return ExprError(); 13079 MemExpr->setBase(ObjectArg.get()); 13080 } 13081 13082 // Convert the rest of the arguments 13083 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13084 RParenLoc)) 13085 return ExprError(); 13086 13087 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13088 13089 if (CheckFunctionCall(Method, TheCall, Proto)) 13090 return ExprError(); 13091 13092 // In the case the method to call was not selected by the overloading 13093 // resolution process, we still need to handle the enable_if attribute. Do 13094 // that here, so it will not hide previous -- and more relevant -- errors. 13095 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13096 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13097 Diag(MemE->getMemberLoc(), 13098 diag::err_ovl_no_viable_member_function_in_call) 13099 << Method << Method->getSourceRange(); 13100 Diag(Method->getLocation(), 13101 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13102 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13103 return ExprError(); 13104 } 13105 } 13106 13107 if ((isa<CXXConstructorDecl>(CurContext) || 13108 isa<CXXDestructorDecl>(CurContext)) && 13109 TheCall->getMethodDecl()->isPure()) { 13110 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13111 13112 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13113 MemExpr->performsVirtualDispatch(getLangOpts())) { 13114 Diag(MemExpr->getBeginLoc(), 13115 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13116 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13117 << MD->getParent()->getDeclName(); 13118 13119 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13120 if (getLangOpts().AppleKext) 13121 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13122 << MD->getParent()->getDeclName() << MD->getDeclName(); 13123 } 13124 } 13125 13126 if (CXXDestructorDecl *DD = 13127 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13128 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13129 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13130 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13131 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13132 MemExpr->getMemberLoc()); 13133 } 13134 13135 return MaybeBindToTemporary(TheCall); 13136 } 13137 13138 /// BuildCallToObjectOfClassType - Build a call to an object of class 13139 /// type (C++ [over.call.object]), which can end up invoking an 13140 /// overloaded function call operator (@c operator()) or performing a 13141 /// user-defined conversion on the object argument. 13142 ExprResult 13143 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13144 SourceLocation LParenLoc, 13145 MultiExprArg Args, 13146 SourceLocation RParenLoc) { 13147 if (checkPlaceholderForOverload(*this, Obj)) 13148 return ExprError(); 13149 ExprResult Object = Obj; 13150 13151 UnbridgedCastsSet UnbridgedCasts; 13152 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13153 return ExprError(); 13154 13155 assert(Object.get()->getType()->isRecordType() && 13156 "Requires object type argument"); 13157 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13158 13159 // C++ [over.call.object]p1: 13160 // If the primary-expression E in the function call syntax 13161 // evaluates to a class object of type "cv T", then the set of 13162 // candidate functions includes at least the function call 13163 // operators of T. The function call operators of T are obtained by 13164 // ordinary lookup of the name operator() in the context of 13165 // (E).operator(). 13166 OverloadCandidateSet CandidateSet(LParenLoc, 13167 OverloadCandidateSet::CSK_Operator); 13168 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13169 13170 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13171 diag::err_incomplete_object_call, Object.get())) 13172 return true; 13173 13174 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13175 LookupQualifiedName(R, Record->getDecl()); 13176 R.suppressDiagnostics(); 13177 13178 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13179 Oper != OperEnd; ++Oper) { 13180 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13181 Object.get()->Classify(Context), Args, CandidateSet, 13182 /*SuppressUserConversions=*/false); 13183 } 13184 13185 // C++ [over.call.object]p2: 13186 // In addition, for each (non-explicit in C++0x) conversion function 13187 // declared in T of the form 13188 // 13189 // operator conversion-type-id () cv-qualifier; 13190 // 13191 // where cv-qualifier is the same cv-qualification as, or a 13192 // greater cv-qualification than, cv, and where conversion-type-id 13193 // denotes the type "pointer to function of (P1,...,Pn) returning 13194 // R", or the type "reference to pointer to function of 13195 // (P1,...,Pn) returning R", or the type "reference to function 13196 // of (P1,...,Pn) returning R", a surrogate call function [...] 13197 // is also considered as a candidate function. Similarly, 13198 // surrogate call functions are added to the set of candidate 13199 // functions for each conversion function declared in an 13200 // accessible base class provided the function is not hidden 13201 // within T by another intervening declaration. 13202 const auto &Conversions = 13203 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13204 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13205 NamedDecl *D = *I; 13206 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13207 if (isa<UsingShadowDecl>(D)) 13208 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13209 13210 // Skip over templated conversion functions; they aren't 13211 // surrogates. 13212 if (isa<FunctionTemplateDecl>(D)) 13213 continue; 13214 13215 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13216 if (!Conv->isExplicit()) { 13217 // Strip the reference type (if any) and then the pointer type (if 13218 // any) to get down to what might be a function type. 13219 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13220 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13221 ConvType = ConvPtrType->getPointeeType(); 13222 13223 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13224 { 13225 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13226 Object.get(), Args, CandidateSet); 13227 } 13228 } 13229 } 13230 13231 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13232 13233 // Perform overload resolution. 13234 OverloadCandidateSet::iterator Best; 13235 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13236 Best)) { 13237 case OR_Success: 13238 // Overload resolution succeeded; we'll build the appropriate call 13239 // below. 13240 break; 13241 13242 case OR_No_Viable_Function: 13243 if (CandidateSet.empty()) 13244 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper) 13245 << Object.get()->getType() << /*call*/ 1 13246 << Object.get()->getSourceRange(); 13247 else 13248 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call) 13249 << Object.get()->getType() << Object.get()->getSourceRange(); 13250 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13251 break; 13252 13253 case OR_Ambiguous: 13254 Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call) 13255 << Object.get()->getType() << Object.get()->getSourceRange(); 13256 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13257 break; 13258 13259 case OR_Deleted: 13260 Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call) 13261 << Best->Function->isDeleted() << Object.get()->getType() 13262 << getDeletedOrUnavailableSuffix(Best->Function) 13263 << Object.get()->getSourceRange(); 13264 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13265 break; 13266 } 13267 13268 if (Best == CandidateSet.end()) 13269 return true; 13270 13271 UnbridgedCasts.restore(); 13272 13273 if (Best->Function == nullptr) { 13274 // Since there is no function declaration, this is one of the 13275 // surrogate candidates. Dig out the conversion function. 13276 CXXConversionDecl *Conv 13277 = cast<CXXConversionDecl>( 13278 Best->Conversions[0].UserDefined.ConversionFunction); 13279 13280 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13281 Best->FoundDecl); 13282 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13283 return ExprError(); 13284 assert(Conv == Best->FoundDecl.getDecl() && 13285 "Found Decl & conversion-to-functionptr should be same, right?!"); 13286 // We selected one of the surrogate functions that converts the 13287 // object parameter to a function pointer. Perform the conversion 13288 // on the object argument, then let ActOnCallExpr finish the job. 13289 13290 // Create an implicit member expr to refer to the conversion operator. 13291 // and then call it. 13292 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13293 Conv, HadMultipleCandidates); 13294 if (Call.isInvalid()) 13295 return ExprError(); 13296 // Record usage of conversion in an implicit cast. 13297 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13298 CK_UserDefinedConversion, Call.get(), 13299 nullptr, VK_RValue); 13300 13301 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13302 } 13303 13304 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13305 13306 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13307 // that calls this method, using Object for the implicit object 13308 // parameter and passing along the remaining arguments. 13309 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13310 13311 // An error diagnostic has already been printed when parsing the declaration. 13312 if (Method->isInvalidDecl()) 13313 return ExprError(); 13314 13315 const FunctionProtoType *Proto = 13316 Method->getType()->getAs<FunctionProtoType>(); 13317 13318 unsigned NumParams = Proto->getNumParams(); 13319 13320 DeclarationNameInfo OpLocInfo( 13321 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13322 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13323 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13324 Obj, HadMultipleCandidates, 13325 OpLocInfo.getLoc(), 13326 OpLocInfo.getInfo()); 13327 if (NewFn.isInvalid()) 13328 return true; 13329 13330 // The number of argument slots to allocate in the call. If we have default 13331 // arguments we need to allocate space for them as well. We additionally 13332 // need one more slot for the object parameter. 13333 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 13334 13335 // Build the full argument list for the method call (the implicit object 13336 // parameter is placed at the beginning of the list). 13337 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 13338 13339 bool IsError = false; 13340 13341 // Initialize the implicit object parameter. 13342 ExprResult ObjRes = 13343 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13344 Best->FoundDecl, Method); 13345 if (ObjRes.isInvalid()) 13346 IsError = true; 13347 else 13348 Object = ObjRes; 13349 MethodArgs[0] = Object.get(); 13350 13351 // Check the argument types. 13352 for (unsigned i = 0; i != NumParams; i++) { 13353 Expr *Arg; 13354 if (i < Args.size()) { 13355 Arg = Args[i]; 13356 13357 // Pass the argument. 13358 13359 ExprResult InputInit 13360 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13361 Context, 13362 Method->getParamDecl(i)), 13363 SourceLocation(), Arg); 13364 13365 IsError |= InputInit.isInvalid(); 13366 Arg = InputInit.getAs<Expr>(); 13367 } else { 13368 ExprResult DefArg 13369 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13370 if (DefArg.isInvalid()) { 13371 IsError = true; 13372 break; 13373 } 13374 13375 Arg = DefArg.getAs<Expr>(); 13376 } 13377 13378 MethodArgs[i + 1] = Arg; 13379 } 13380 13381 // If this is a variadic call, handle args passed through "...". 13382 if (Proto->isVariadic()) { 13383 // Promote the arguments (C99 6.5.2.2p7). 13384 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13385 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13386 nullptr); 13387 IsError |= Arg.isInvalid(); 13388 MethodArgs[i + 1] = Arg.get(); 13389 } 13390 } 13391 13392 if (IsError) 13393 return true; 13394 13395 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13396 13397 // Once we've built TheCall, all of the expressions are properly owned. 13398 QualType ResultTy = Method->getReturnType(); 13399 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13400 ResultTy = ResultTy.getNonLValueExprType(Context); 13401 13402 CXXOperatorCallExpr *TheCall = 13403 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 13404 ResultTy, VK, RParenLoc, FPOptions()); 13405 13406 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13407 return true; 13408 13409 if (CheckFunctionCall(Method, TheCall, Proto)) 13410 return true; 13411 13412 return MaybeBindToTemporary(TheCall); 13413 } 13414 13415 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13416 /// (if one exists), where @c Base is an expression of class type and 13417 /// @c Member is the name of the member we're trying to find. 13418 ExprResult 13419 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13420 bool *NoArrowOperatorFound) { 13421 assert(Base->getType()->isRecordType() && 13422 "left-hand side must have class type"); 13423 13424 if (checkPlaceholderForOverload(*this, Base)) 13425 return ExprError(); 13426 13427 SourceLocation Loc = Base->getExprLoc(); 13428 13429 // C++ [over.ref]p1: 13430 // 13431 // [...] An expression x->m is interpreted as (x.operator->())->m 13432 // for a class object x of type T if T::operator->() exists and if 13433 // the operator is selected as the best match function by the 13434 // overload resolution mechanism (13.3). 13435 DeclarationName OpName = 13436 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13437 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13438 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13439 13440 if (RequireCompleteType(Loc, Base->getType(), 13441 diag::err_typecheck_incomplete_tag, Base)) 13442 return ExprError(); 13443 13444 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13445 LookupQualifiedName(R, BaseRecord->getDecl()); 13446 R.suppressDiagnostics(); 13447 13448 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13449 Oper != OperEnd; ++Oper) { 13450 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13451 None, CandidateSet, /*SuppressUserConversions=*/false); 13452 } 13453 13454 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13455 13456 // Perform overload resolution. 13457 OverloadCandidateSet::iterator Best; 13458 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13459 case OR_Success: 13460 // Overload resolution succeeded; we'll build the call below. 13461 break; 13462 13463 case OR_No_Viable_Function: 13464 if (CandidateSet.empty()) { 13465 QualType BaseType = Base->getType(); 13466 if (NoArrowOperatorFound) { 13467 // Report this specific error to the caller instead of emitting a 13468 // diagnostic, as requested. 13469 *NoArrowOperatorFound = true; 13470 return ExprError(); 13471 } 13472 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13473 << BaseType << Base->getSourceRange(); 13474 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13475 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13476 << FixItHint::CreateReplacement(OpLoc, "."); 13477 } 13478 } else 13479 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13480 << "operator->" << Base->getSourceRange(); 13481 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13482 return ExprError(); 13483 13484 case OR_Ambiguous: 13485 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 13486 << "->" << Base->getType() << Base->getSourceRange(); 13487 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 13488 return ExprError(); 13489 13490 case OR_Deleted: 13491 Diag(OpLoc, diag::err_ovl_deleted_oper) 13492 << Best->Function->isDeleted() 13493 << "->" 13494 << getDeletedOrUnavailableSuffix(Best->Function) 13495 << Base->getSourceRange(); 13496 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13497 return ExprError(); 13498 } 13499 13500 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13501 13502 // Convert the object parameter. 13503 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13504 ExprResult BaseResult = 13505 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13506 Best->FoundDecl, Method); 13507 if (BaseResult.isInvalid()) 13508 return ExprError(); 13509 Base = BaseResult.get(); 13510 13511 // Build the operator call. 13512 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13513 Base, HadMultipleCandidates, OpLoc); 13514 if (FnExpr.isInvalid()) 13515 return ExprError(); 13516 13517 QualType ResultTy = Method->getReturnType(); 13518 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13519 ResultTy = ResultTy.getNonLValueExprType(Context); 13520 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13521 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 13522 13523 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13524 return ExprError(); 13525 13526 if (CheckFunctionCall(Method, TheCall, 13527 Method->getType()->castAs<FunctionProtoType>())) 13528 return ExprError(); 13529 13530 return MaybeBindToTemporary(TheCall); 13531 } 13532 13533 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13534 /// a literal operator described by the provided lookup results. 13535 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13536 DeclarationNameInfo &SuffixInfo, 13537 ArrayRef<Expr*> Args, 13538 SourceLocation LitEndLoc, 13539 TemplateArgumentListInfo *TemplateArgs) { 13540 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13541 13542 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13543 OverloadCandidateSet::CSK_Normal); 13544 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13545 /*SuppressUserConversions=*/true); 13546 13547 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13548 13549 // Perform overload resolution. This will usually be trivial, but might need 13550 // to perform substitutions for a literal operator template. 13551 OverloadCandidateSet::iterator Best; 13552 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13553 case OR_Success: 13554 case OR_Deleted: 13555 break; 13556 13557 case OR_No_Viable_Function: 13558 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13559 << R.getLookupName(); 13560 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13561 return ExprError(); 13562 13563 case OR_Ambiguous: 13564 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13565 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13566 return ExprError(); 13567 } 13568 13569 FunctionDecl *FD = Best->Function; 13570 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13571 nullptr, HadMultipleCandidates, 13572 SuffixInfo.getLoc(), 13573 SuffixInfo.getInfo()); 13574 if (Fn.isInvalid()) 13575 return true; 13576 13577 // Check the argument types. This should almost always be a no-op, except 13578 // that array-to-pointer decay is applied to string literals. 13579 Expr *ConvArgs[2]; 13580 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13581 ExprResult InputInit = PerformCopyInitialization( 13582 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13583 SourceLocation(), Args[ArgIdx]); 13584 if (InputInit.isInvalid()) 13585 return true; 13586 ConvArgs[ArgIdx] = InputInit.get(); 13587 } 13588 13589 QualType ResultTy = FD->getReturnType(); 13590 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13591 ResultTy = ResultTy.getNonLValueExprType(Context); 13592 13593 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 13594 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 13595 VK, LitEndLoc, UDSuffixLoc); 13596 13597 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13598 return ExprError(); 13599 13600 if (CheckFunctionCall(FD, UDL, nullptr)) 13601 return ExprError(); 13602 13603 return MaybeBindToTemporary(UDL); 13604 } 13605 13606 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13607 /// given LookupResult is non-empty, it is assumed to describe a member which 13608 /// will be invoked. Otherwise, the function will be found via argument 13609 /// dependent lookup. 13610 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13611 /// otherwise CallExpr is set to ExprError() and some non-success value 13612 /// is returned. 13613 Sema::ForRangeStatus 13614 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13615 SourceLocation RangeLoc, 13616 const DeclarationNameInfo &NameInfo, 13617 LookupResult &MemberLookup, 13618 OverloadCandidateSet *CandidateSet, 13619 Expr *Range, ExprResult *CallExpr) { 13620 Scope *S = nullptr; 13621 13622 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 13623 if (!MemberLookup.empty()) { 13624 ExprResult MemberRef = 13625 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13626 /*IsPtr=*/false, CXXScopeSpec(), 13627 /*TemplateKWLoc=*/SourceLocation(), 13628 /*FirstQualifierInScope=*/nullptr, 13629 MemberLookup, 13630 /*TemplateArgs=*/nullptr, S); 13631 if (MemberRef.isInvalid()) { 13632 *CallExpr = ExprError(); 13633 return FRS_DiagnosticIssued; 13634 } 13635 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13636 if (CallExpr->isInvalid()) { 13637 *CallExpr = ExprError(); 13638 return FRS_DiagnosticIssued; 13639 } 13640 } else { 13641 UnresolvedSet<0> FoundNames; 13642 UnresolvedLookupExpr *Fn = 13643 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13644 NestedNameSpecifierLoc(), NameInfo, 13645 /*NeedsADL=*/true, /*Overloaded=*/false, 13646 FoundNames.begin(), FoundNames.end()); 13647 13648 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13649 CandidateSet, CallExpr); 13650 if (CandidateSet->empty() || CandidateSetError) { 13651 *CallExpr = ExprError(); 13652 return FRS_NoViableFunction; 13653 } 13654 OverloadCandidateSet::iterator Best; 13655 OverloadingResult OverloadResult = 13656 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 13657 13658 if (OverloadResult == OR_No_Viable_Function) { 13659 *CallExpr = ExprError(); 13660 return FRS_NoViableFunction; 13661 } 13662 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13663 Loc, nullptr, CandidateSet, &Best, 13664 OverloadResult, 13665 /*AllowTypoCorrection=*/false); 13666 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13667 *CallExpr = ExprError(); 13668 return FRS_DiagnosticIssued; 13669 } 13670 } 13671 return FRS_Success; 13672 } 13673 13674 13675 /// FixOverloadedFunctionReference - E is an expression that refers to 13676 /// a C++ overloaded function (possibly with some parentheses and 13677 /// perhaps a '&' around it). We have resolved the overloaded function 13678 /// to the function declaration Fn, so patch up the expression E to 13679 /// refer (possibly indirectly) to Fn. Returns the new expr. 13680 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13681 FunctionDecl *Fn) { 13682 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13683 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13684 Found, Fn); 13685 if (SubExpr == PE->getSubExpr()) 13686 return PE; 13687 13688 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13689 } 13690 13691 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13692 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13693 Found, Fn); 13694 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13695 SubExpr->getType()) && 13696 "Implicit cast type cannot be determined from overload"); 13697 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13698 if (SubExpr == ICE->getSubExpr()) 13699 return ICE; 13700 13701 return ImplicitCastExpr::Create(Context, ICE->getType(), 13702 ICE->getCastKind(), 13703 SubExpr, nullptr, 13704 ICE->getValueKind()); 13705 } 13706 13707 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13708 if (!GSE->isResultDependent()) { 13709 Expr *SubExpr = 13710 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13711 if (SubExpr == GSE->getResultExpr()) 13712 return GSE; 13713 13714 // Replace the resulting type information before rebuilding the generic 13715 // selection expression. 13716 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13717 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13718 unsigned ResultIdx = GSE->getResultIndex(); 13719 AssocExprs[ResultIdx] = SubExpr; 13720 13721 return GenericSelectionExpr::Create( 13722 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13723 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13724 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13725 ResultIdx); 13726 } 13727 // Rather than fall through to the unreachable, return the original generic 13728 // selection expression. 13729 return GSE; 13730 } 13731 13732 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13733 assert(UnOp->getOpcode() == UO_AddrOf && 13734 "Can only take the address of an overloaded function"); 13735 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13736 if (Method->isStatic()) { 13737 // Do nothing: static member functions aren't any different 13738 // from non-member functions. 13739 } else { 13740 // Fix the subexpression, which really has to be an 13741 // UnresolvedLookupExpr holding an overloaded member function 13742 // or template. 13743 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13744 Found, Fn); 13745 if (SubExpr == UnOp->getSubExpr()) 13746 return UnOp; 13747 13748 assert(isa<DeclRefExpr>(SubExpr) 13749 && "fixed to something other than a decl ref"); 13750 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13751 && "fixed to a member ref with no nested name qualifier"); 13752 13753 // We have taken the address of a pointer to member 13754 // function. Perform the computation here so that we get the 13755 // appropriate pointer to member type. 13756 QualType ClassType 13757 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13758 QualType MemPtrType 13759 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13760 // Under the MS ABI, lock down the inheritance model now. 13761 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13762 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13763 13764 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13765 VK_RValue, OK_Ordinary, 13766 UnOp->getOperatorLoc(), false); 13767 } 13768 } 13769 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13770 Found, Fn); 13771 if (SubExpr == UnOp->getSubExpr()) 13772 return UnOp; 13773 13774 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13775 Context.getPointerType(SubExpr->getType()), 13776 VK_RValue, OK_Ordinary, 13777 UnOp->getOperatorLoc(), false); 13778 } 13779 13780 // C++ [except.spec]p17: 13781 // An exception-specification is considered to be needed when: 13782 // - in an expression the function is the unique lookup result or the 13783 // selected member of a set of overloaded functions 13784 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13785 ResolveExceptionSpec(E->getExprLoc(), FPT); 13786 13787 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13788 // FIXME: avoid copy. 13789 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13790 if (ULE->hasExplicitTemplateArgs()) { 13791 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13792 TemplateArgs = &TemplateArgsBuffer; 13793 } 13794 13795 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13796 ULE->getQualifierLoc(), 13797 ULE->getTemplateKeywordLoc(), 13798 Fn, 13799 /*enclosing*/ false, // FIXME? 13800 ULE->getNameLoc(), 13801 Fn->getType(), 13802 VK_LValue, 13803 Found.getDecl(), 13804 TemplateArgs); 13805 MarkDeclRefReferenced(DRE); 13806 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13807 return DRE; 13808 } 13809 13810 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13811 // FIXME: avoid copy. 13812 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13813 if (MemExpr->hasExplicitTemplateArgs()) { 13814 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13815 TemplateArgs = &TemplateArgsBuffer; 13816 } 13817 13818 Expr *Base; 13819 13820 // If we're filling in a static method where we used to have an 13821 // implicit member access, rewrite to a simple decl ref. 13822 if (MemExpr->isImplicitAccess()) { 13823 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13824 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13825 MemExpr->getQualifierLoc(), 13826 MemExpr->getTemplateKeywordLoc(), 13827 Fn, 13828 /*enclosing*/ false, 13829 MemExpr->getMemberLoc(), 13830 Fn->getType(), 13831 VK_LValue, 13832 Found.getDecl(), 13833 TemplateArgs); 13834 MarkDeclRefReferenced(DRE); 13835 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13836 return DRE; 13837 } else { 13838 SourceLocation Loc = MemExpr->getMemberLoc(); 13839 if (MemExpr->getQualifier()) 13840 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13841 CheckCXXThisCapture(Loc); 13842 Base = new (Context) CXXThisExpr(Loc, 13843 MemExpr->getBaseType(), 13844 /*isImplicit=*/true); 13845 } 13846 } else 13847 Base = MemExpr->getBase(); 13848 13849 ExprValueKind valueKind; 13850 QualType type; 13851 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13852 valueKind = VK_LValue; 13853 type = Fn->getType(); 13854 } else { 13855 valueKind = VK_RValue; 13856 type = Context.BoundMemberTy; 13857 } 13858 13859 MemberExpr *ME = MemberExpr::Create( 13860 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13861 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13862 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13863 OK_Ordinary); 13864 ME->setHadMultipleCandidates(true); 13865 MarkMemberReferenced(ME); 13866 return ME; 13867 } 13868 13869 llvm_unreachable("Invalid reference to overloaded function"); 13870 } 13871 13872 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13873 DeclAccessPair Found, 13874 FunctionDecl *Fn) { 13875 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13876 } 13877