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(ASTContext &Ctx, 261 const Expr *Converted) { 262 // We can have cleanups wrapping the converted expression; these need to be 263 // preserved so that destructors run if necessary. 264 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 265 Expr *Inner = 266 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 267 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 268 EWC->getObjects()); 269 } 270 271 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 272 switch (ICE->getCastKind()) { 273 case CK_NoOp: 274 case CK_IntegralCast: 275 case CK_IntegralToBoolean: 276 case CK_IntegralToFloating: 277 case CK_BooleanToSignedIntegral: 278 case CK_FloatingToIntegral: 279 case CK_FloatingToBoolean: 280 case CK_FloatingCast: 281 Converted = ICE->getSubExpr(); 282 continue; 283 284 default: 285 return Converted; 286 } 287 } 288 289 return Converted; 290 } 291 292 /// Check if this standard conversion sequence represents a narrowing 293 /// conversion, according to C++11 [dcl.init.list]p7. 294 /// 295 /// \param Ctx The AST context. 296 /// \param Converted The result of applying this standard conversion sequence. 297 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 298 /// value of the expression prior to the narrowing conversion. 299 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 300 /// type of the expression prior to the narrowing conversion. 301 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 302 /// from floating point types to integral types should be ignored. 303 NarrowingKind StandardConversionSequence::getNarrowingKind( 304 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 305 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 306 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 307 308 // C++11 [dcl.init.list]p7: 309 // A narrowing conversion is an implicit conversion ... 310 QualType FromType = getToType(0); 311 QualType ToType = getToType(1); 312 313 // A conversion to an enumeration type is narrowing if the conversion to 314 // the underlying type is narrowing. This only arises for expressions of 315 // the form 'Enum{init}'. 316 if (auto *ET = ToType->getAs<EnumType>()) 317 ToType = ET->getDecl()->getIntegerType(); 318 319 switch (Second) { 320 // 'bool' is an integral type; dispatch to the right place to handle it. 321 case ICK_Boolean_Conversion: 322 if (FromType->isRealFloatingType()) 323 goto FloatingIntegralConversion; 324 if (FromType->isIntegralOrUnscopedEnumerationType()) 325 goto IntegralConversion; 326 // Boolean conversions can be from pointers and pointers to members 327 // [conv.bool], and those aren't considered narrowing conversions. 328 return NK_Not_Narrowing; 329 330 // -- from a floating-point type to an integer type, or 331 // 332 // -- from an integer type or unscoped enumeration type to a floating-point 333 // type, except where the source is a constant expression and the actual 334 // value after conversion will fit into the target type and will produce 335 // the original value when converted back to the original type, or 336 case ICK_Floating_Integral: 337 FloatingIntegralConversion: 338 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 339 return NK_Type_Narrowing; 340 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 341 ToType->isRealFloatingType()) { 342 if (IgnoreFloatToIntegralConversion) 343 return NK_Not_Narrowing; 344 llvm::APSInt IntConstantValue; 345 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 346 assert(Initializer && "Unknown conversion expression"); 347 348 // If it's value-dependent, we can't tell whether it's narrowing. 349 if (Initializer->isValueDependent()) 350 return NK_Dependent_Narrowing; 351 352 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 353 // Convert the integer to the floating type. 354 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 355 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 356 llvm::APFloat::rmNearestTiesToEven); 357 // And back. 358 llvm::APSInt ConvertedValue = IntConstantValue; 359 bool ignored; 360 Result.convertToInteger(ConvertedValue, 361 llvm::APFloat::rmTowardZero, &ignored); 362 // If the resulting value is different, this was a narrowing conversion. 363 if (IntConstantValue != ConvertedValue) { 364 ConstantValue = APValue(IntConstantValue); 365 ConstantType = Initializer->getType(); 366 return NK_Constant_Narrowing; 367 } 368 } else { 369 // Variables are always narrowings. 370 return NK_Variable_Narrowing; 371 } 372 } 373 return NK_Not_Narrowing; 374 375 // -- from long double to double or float, or from double to float, except 376 // where the source is a constant expression and the actual value after 377 // conversion is within the range of values that can be represented (even 378 // if it cannot be represented exactly), or 379 case ICK_Floating_Conversion: 380 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 381 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 382 // FromType is larger than ToType. 383 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 384 385 // If it's value-dependent, we can't tell whether it's narrowing. 386 if (Initializer->isValueDependent()) 387 return NK_Dependent_Narrowing; 388 389 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 390 // Constant! 391 assert(ConstantValue.isFloat()); 392 llvm::APFloat FloatVal = ConstantValue.getFloat(); 393 // Convert the source value into the target type. 394 bool ignored; 395 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 396 Ctx.getFloatTypeSemantics(ToType), 397 llvm::APFloat::rmNearestTiesToEven, &ignored); 398 // If there was no overflow, the source value is within the range of 399 // values that can be represented. 400 if (ConvertStatus & llvm::APFloat::opOverflow) { 401 ConstantType = Initializer->getType(); 402 return NK_Constant_Narrowing; 403 } 404 } else { 405 return NK_Variable_Narrowing; 406 } 407 } 408 return NK_Not_Narrowing; 409 410 // -- from an integer type or unscoped enumeration type to an integer type 411 // that cannot represent all the values of the original type, except where 412 // the source is a constant expression and the actual value after 413 // conversion will fit into the target type and will produce the original 414 // value when converted back to the original type. 415 case ICK_Integral_Conversion: 416 IntegralConversion: { 417 assert(FromType->isIntegralOrUnscopedEnumerationType()); 418 assert(ToType->isIntegralOrUnscopedEnumerationType()); 419 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 420 const unsigned FromWidth = Ctx.getIntWidth(FromType); 421 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 422 const unsigned ToWidth = Ctx.getIntWidth(ToType); 423 424 if (FromWidth > ToWidth || 425 (FromWidth == ToWidth && FromSigned != ToSigned) || 426 (FromSigned && !ToSigned)) { 427 // Not all values of FromType can be represented in ToType. 428 llvm::APSInt InitializerValue; 429 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 430 431 // If it's value-dependent, we can't tell whether it's narrowing. 432 if (Initializer->isValueDependent()) 433 return NK_Dependent_Narrowing; 434 435 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 436 // Such conversions on variables are always narrowing. 437 return NK_Variable_Narrowing; 438 } 439 bool Narrowing = false; 440 if (FromWidth < ToWidth) { 441 // Negative -> unsigned is narrowing. Otherwise, more bits is never 442 // narrowing. 443 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 444 Narrowing = true; 445 } else { 446 // Add a bit to the InitializerValue so we don't have to worry about 447 // signed vs. unsigned comparisons. 448 InitializerValue = InitializerValue.extend( 449 InitializerValue.getBitWidth() + 1); 450 // Convert the initializer to and from the target width and signed-ness. 451 llvm::APSInt ConvertedValue = InitializerValue; 452 ConvertedValue = ConvertedValue.trunc(ToWidth); 453 ConvertedValue.setIsSigned(ToSigned); 454 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 455 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 456 // If the result is different, this was a narrowing conversion. 457 if (ConvertedValue != InitializerValue) 458 Narrowing = true; 459 } 460 if (Narrowing) { 461 ConstantType = Initializer->getType(); 462 ConstantValue = APValue(InitializerValue); 463 return NK_Constant_Narrowing; 464 } 465 } 466 return NK_Not_Narrowing; 467 } 468 469 default: 470 // Other kinds of conversions are not narrowings. 471 return NK_Not_Narrowing; 472 } 473 } 474 475 /// dump - Print this standard conversion sequence to standard 476 /// error. Useful for debugging overloading issues. 477 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 478 raw_ostream &OS = llvm::errs(); 479 bool PrintedSomething = false; 480 if (First != ICK_Identity) { 481 OS << GetImplicitConversionName(First); 482 PrintedSomething = true; 483 } 484 485 if (Second != ICK_Identity) { 486 if (PrintedSomething) { 487 OS << " -> "; 488 } 489 OS << GetImplicitConversionName(Second); 490 491 if (CopyConstructor) { 492 OS << " (by copy constructor)"; 493 } else if (DirectBinding) { 494 OS << " (direct reference binding)"; 495 } else if (ReferenceBinding) { 496 OS << " (reference binding)"; 497 } 498 PrintedSomething = true; 499 } 500 501 if (Third != ICK_Identity) { 502 if (PrintedSomething) { 503 OS << " -> "; 504 } 505 OS << GetImplicitConversionName(Third); 506 PrintedSomething = true; 507 } 508 509 if (!PrintedSomething) { 510 OS << "No conversions required"; 511 } 512 } 513 514 /// dump - Print this user-defined conversion sequence to standard 515 /// error. Useful for debugging overloading issues. 516 void UserDefinedConversionSequence::dump() const { 517 raw_ostream &OS = llvm::errs(); 518 if (Before.First || Before.Second || Before.Third) { 519 Before.dump(); 520 OS << " -> "; 521 } 522 if (ConversionFunction) 523 OS << '\'' << *ConversionFunction << '\''; 524 else 525 OS << "aggregate initialization"; 526 if (After.First || After.Second || After.Third) { 527 OS << " -> "; 528 After.dump(); 529 } 530 } 531 532 /// dump - Print this implicit conversion sequence to standard 533 /// error. Useful for debugging overloading issues. 534 void ImplicitConversionSequence::dump() const { 535 raw_ostream &OS = llvm::errs(); 536 if (isStdInitializerListElement()) 537 OS << "Worst std::initializer_list element conversion: "; 538 switch (ConversionKind) { 539 case StandardConversion: 540 OS << "Standard conversion: "; 541 Standard.dump(); 542 break; 543 case UserDefinedConversion: 544 OS << "User-defined conversion: "; 545 UserDefined.dump(); 546 break; 547 case EllipsisConversion: 548 OS << "Ellipsis conversion"; 549 break; 550 case AmbiguousConversion: 551 OS << "Ambiguous conversion"; 552 break; 553 case BadConversion: 554 OS << "Bad conversion"; 555 break; 556 } 557 558 OS << "\n"; 559 } 560 561 void AmbiguousConversionSequence::construct() { 562 new (&conversions()) ConversionSet(); 563 } 564 565 void AmbiguousConversionSequence::destruct() { 566 conversions().~ConversionSet(); 567 } 568 569 void 570 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 571 FromTypePtr = O.FromTypePtr; 572 ToTypePtr = O.ToTypePtr; 573 new (&conversions()) ConversionSet(O.conversions()); 574 } 575 576 namespace { 577 // Structure used by DeductionFailureInfo to store 578 // template argument information. 579 struct DFIArguments { 580 TemplateArgument FirstArg; 581 TemplateArgument SecondArg; 582 }; 583 // Structure used by DeductionFailureInfo to store 584 // template parameter and template argument information. 585 struct DFIParamWithArguments : DFIArguments { 586 TemplateParameter Param; 587 }; 588 // Structure used by DeductionFailureInfo to store template argument 589 // information and the index of the problematic call argument. 590 struct DFIDeducedMismatchArgs : DFIArguments { 591 TemplateArgumentList *TemplateArgs; 592 unsigned CallArgIndex; 593 }; 594 } 595 596 /// Convert from Sema's representation of template deduction information 597 /// to the form used in overload-candidate information. 598 DeductionFailureInfo 599 clang::MakeDeductionFailureInfo(ASTContext &Context, 600 Sema::TemplateDeductionResult TDK, 601 TemplateDeductionInfo &Info) { 602 DeductionFailureInfo Result; 603 Result.Result = static_cast<unsigned>(TDK); 604 Result.HasDiagnostic = false; 605 switch (TDK) { 606 case Sema::TDK_Invalid: 607 case Sema::TDK_InstantiationDepth: 608 case Sema::TDK_TooManyArguments: 609 case Sema::TDK_TooFewArguments: 610 case Sema::TDK_MiscellaneousDeductionFailure: 611 case Sema::TDK_CUDATargetMismatch: 612 Result.Data = nullptr; 613 break; 614 615 case Sema::TDK_Incomplete: 616 case Sema::TDK_InvalidExplicitArguments: 617 Result.Data = Info.Param.getOpaqueValue(); 618 break; 619 620 case Sema::TDK_DeducedMismatch: 621 case Sema::TDK_DeducedMismatchNested: { 622 // FIXME: Should allocate from normal heap so that we can free this later. 623 auto *Saved = new (Context) DFIDeducedMismatchArgs; 624 Saved->FirstArg = Info.FirstArg; 625 Saved->SecondArg = Info.SecondArg; 626 Saved->TemplateArgs = Info.take(); 627 Saved->CallArgIndex = Info.CallArgIndex; 628 Result.Data = Saved; 629 break; 630 } 631 632 case Sema::TDK_NonDeducedMismatch: { 633 // FIXME: Should allocate from normal heap so that we can free this later. 634 DFIArguments *Saved = new (Context) DFIArguments; 635 Saved->FirstArg = Info.FirstArg; 636 Saved->SecondArg = Info.SecondArg; 637 Result.Data = Saved; 638 break; 639 } 640 641 case Sema::TDK_IncompletePack: 642 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 643 case Sema::TDK_Inconsistent: 644 case Sema::TDK_Underqualified: { 645 // FIXME: Should allocate from normal heap so that we can free this later. 646 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 647 Saved->Param = Info.Param; 648 Saved->FirstArg = Info.FirstArg; 649 Saved->SecondArg = Info.SecondArg; 650 Result.Data = Saved; 651 break; 652 } 653 654 case Sema::TDK_SubstitutionFailure: 655 Result.Data = Info.take(); 656 if (Info.hasSFINAEDiagnostic()) { 657 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 658 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 659 Info.takeSFINAEDiagnostic(*Diag); 660 Result.HasDiagnostic = true; 661 } 662 break; 663 664 case Sema::TDK_Success: 665 case Sema::TDK_NonDependentConversionFailure: 666 llvm_unreachable("not a deduction failure"); 667 } 668 669 return Result; 670 } 671 672 void DeductionFailureInfo::Destroy() { 673 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 674 case Sema::TDK_Success: 675 case Sema::TDK_Invalid: 676 case Sema::TDK_InstantiationDepth: 677 case Sema::TDK_Incomplete: 678 case Sema::TDK_TooManyArguments: 679 case Sema::TDK_TooFewArguments: 680 case Sema::TDK_InvalidExplicitArguments: 681 case Sema::TDK_CUDATargetMismatch: 682 case Sema::TDK_NonDependentConversionFailure: 683 break; 684 685 case Sema::TDK_IncompletePack: 686 case Sema::TDK_Inconsistent: 687 case Sema::TDK_Underqualified: 688 case Sema::TDK_DeducedMismatch: 689 case Sema::TDK_DeducedMismatchNested: 690 case Sema::TDK_NonDeducedMismatch: 691 // FIXME: Destroy the data? 692 Data = nullptr; 693 break; 694 695 case Sema::TDK_SubstitutionFailure: 696 // FIXME: Destroy the template argument list? 697 Data = nullptr; 698 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 699 Diag->~PartialDiagnosticAt(); 700 HasDiagnostic = false; 701 } 702 break; 703 704 // Unhandled 705 case Sema::TDK_MiscellaneousDeductionFailure: 706 break; 707 } 708 } 709 710 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 711 if (HasDiagnostic) 712 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 713 return nullptr; 714 } 715 716 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 717 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 718 case Sema::TDK_Success: 719 case Sema::TDK_Invalid: 720 case Sema::TDK_InstantiationDepth: 721 case Sema::TDK_TooManyArguments: 722 case Sema::TDK_TooFewArguments: 723 case Sema::TDK_SubstitutionFailure: 724 case Sema::TDK_DeducedMismatch: 725 case Sema::TDK_DeducedMismatchNested: 726 case Sema::TDK_NonDeducedMismatch: 727 case Sema::TDK_CUDATargetMismatch: 728 case Sema::TDK_NonDependentConversionFailure: 729 return TemplateParameter(); 730 731 case Sema::TDK_Incomplete: 732 case Sema::TDK_InvalidExplicitArguments: 733 return TemplateParameter::getFromOpaqueValue(Data); 734 735 case Sema::TDK_IncompletePack: 736 case Sema::TDK_Inconsistent: 737 case Sema::TDK_Underqualified: 738 return static_cast<DFIParamWithArguments*>(Data)->Param; 739 740 // Unhandled 741 case Sema::TDK_MiscellaneousDeductionFailure: 742 break; 743 } 744 745 return TemplateParameter(); 746 } 747 748 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 749 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 750 case Sema::TDK_Success: 751 case Sema::TDK_Invalid: 752 case Sema::TDK_InstantiationDepth: 753 case Sema::TDK_TooManyArguments: 754 case Sema::TDK_TooFewArguments: 755 case Sema::TDK_Incomplete: 756 case Sema::TDK_IncompletePack: 757 case Sema::TDK_InvalidExplicitArguments: 758 case Sema::TDK_Inconsistent: 759 case Sema::TDK_Underqualified: 760 case Sema::TDK_NonDeducedMismatch: 761 case Sema::TDK_CUDATargetMismatch: 762 case Sema::TDK_NonDependentConversionFailure: 763 return nullptr; 764 765 case Sema::TDK_DeducedMismatch: 766 case Sema::TDK_DeducedMismatchNested: 767 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 768 769 case Sema::TDK_SubstitutionFailure: 770 return static_cast<TemplateArgumentList*>(Data); 771 772 // Unhandled 773 case Sema::TDK_MiscellaneousDeductionFailure: 774 break; 775 } 776 777 return nullptr; 778 } 779 780 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 781 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 782 case Sema::TDK_Success: 783 case Sema::TDK_Invalid: 784 case Sema::TDK_InstantiationDepth: 785 case Sema::TDK_Incomplete: 786 case Sema::TDK_TooManyArguments: 787 case Sema::TDK_TooFewArguments: 788 case Sema::TDK_InvalidExplicitArguments: 789 case Sema::TDK_SubstitutionFailure: 790 case Sema::TDK_CUDATargetMismatch: 791 case Sema::TDK_NonDependentConversionFailure: 792 return nullptr; 793 794 case Sema::TDK_IncompletePack: 795 case Sema::TDK_Inconsistent: 796 case Sema::TDK_Underqualified: 797 case Sema::TDK_DeducedMismatch: 798 case Sema::TDK_DeducedMismatchNested: 799 case Sema::TDK_NonDeducedMismatch: 800 return &static_cast<DFIArguments*>(Data)->FirstArg; 801 802 // Unhandled 803 case Sema::TDK_MiscellaneousDeductionFailure: 804 break; 805 } 806 807 return nullptr; 808 } 809 810 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 811 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 812 case Sema::TDK_Success: 813 case Sema::TDK_Invalid: 814 case Sema::TDK_InstantiationDepth: 815 case Sema::TDK_Incomplete: 816 case Sema::TDK_IncompletePack: 817 case Sema::TDK_TooManyArguments: 818 case Sema::TDK_TooFewArguments: 819 case Sema::TDK_InvalidExplicitArguments: 820 case Sema::TDK_SubstitutionFailure: 821 case Sema::TDK_CUDATargetMismatch: 822 case Sema::TDK_NonDependentConversionFailure: 823 return nullptr; 824 825 case Sema::TDK_Inconsistent: 826 case Sema::TDK_Underqualified: 827 case Sema::TDK_DeducedMismatch: 828 case Sema::TDK_DeducedMismatchNested: 829 case Sema::TDK_NonDeducedMismatch: 830 return &static_cast<DFIArguments*>(Data)->SecondArg; 831 832 // Unhandled 833 case Sema::TDK_MiscellaneousDeductionFailure: 834 break; 835 } 836 837 return nullptr; 838 } 839 840 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 841 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 842 case Sema::TDK_DeducedMismatch: 843 case Sema::TDK_DeducedMismatchNested: 844 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 845 846 default: 847 return llvm::None; 848 } 849 } 850 851 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 852 OverloadedOperatorKind Op) { 853 if (!AllowRewrittenCandidates) 854 return false; 855 return Op == OO_EqualEqual || Op == OO_Spaceship; 856 } 857 858 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 859 ASTContext &Ctx, const FunctionDecl *FD) { 860 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 861 return false; 862 // Don't bother adding a reversed candidate that can never be a better 863 // match than the non-reversed version. 864 return FD->getNumParams() != 2 || 865 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 866 FD->getParamDecl(1)->getType()) || 867 FD->hasAttr<EnableIfAttr>(); 868 } 869 870 void OverloadCandidateSet::destroyCandidates() { 871 for (iterator i = begin(), e = end(); i != e; ++i) { 872 for (auto &C : i->Conversions) 873 C.~ImplicitConversionSequence(); 874 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 875 i->DeductionFailure.Destroy(); 876 } 877 } 878 879 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 880 destroyCandidates(); 881 SlabAllocator.Reset(); 882 NumInlineBytesUsed = 0; 883 Candidates.clear(); 884 Functions.clear(); 885 Kind = CSK; 886 } 887 888 namespace { 889 class UnbridgedCastsSet { 890 struct Entry { 891 Expr **Addr; 892 Expr *Saved; 893 }; 894 SmallVector<Entry, 2> Entries; 895 896 public: 897 void save(Sema &S, Expr *&E) { 898 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 899 Entry entry = { &E, E }; 900 Entries.push_back(entry); 901 E = S.stripARCUnbridgedCast(E); 902 } 903 904 void restore() { 905 for (SmallVectorImpl<Entry>::iterator 906 i = Entries.begin(), e = Entries.end(); i != e; ++i) 907 *i->Addr = i->Saved; 908 } 909 }; 910 } 911 912 /// checkPlaceholderForOverload - Do any interesting placeholder-like 913 /// preprocessing on the given expression. 914 /// 915 /// \param unbridgedCasts a collection to which to add unbridged casts; 916 /// without this, they will be immediately diagnosed as errors 917 /// 918 /// Return true on unrecoverable error. 919 static bool 920 checkPlaceholderForOverload(Sema &S, Expr *&E, 921 UnbridgedCastsSet *unbridgedCasts = nullptr) { 922 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 923 // We can't handle overloaded expressions here because overload 924 // resolution might reasonably tweak them. 925 if (placeholder->getKind() == BuiltinType::Overload) return false; 926 927 // If the context potentially accepts unbridged ARC casts, strip 928 // the unbridged cast and add it to the collection for later restoration. 929 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 930 unbridgedCasts) { 931 unbridgedCasts->save(S, E); 932 return false; 933 } 934 935 // Go ahead and check everything else. 936 ExprResult result = S.CheckPlaceholderExpr(E); 937 if (result.isInvalid()) 938 return true; 939 940 E = result.get(); 941 return false; 942 } 943 944 // Nothing to do. 945 return false; 946 } 947 948 /// checkArgPlaceholdersForOverload - Check a set of call operands for 949 /// placeholders. 950 static bool checkArgPlaceholdersForOverload(Sema &S, 951 MultiExprArg Args, 952 UnbridgedCastsSet &unbridged) { 953 for (unsigned i = 0, e = Args.size(); i != e; ++i) 954 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 955 return true; 956 957 return false; 958 } 959 960 /// Determine whether the given New declaration is an overload of the 961 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 962 /// New and Old cannot be overloaded, e.g., if New has the same signature as 963 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 964 /// functions (or function templates) at all. When it does return Ovl_Match or 965 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 966 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 967 /// declaration. 968 /// 969 /// Example: Given the following input: 970 /// 971 /// void f(int, float); // #1 972 /// void f(int, int); // #2 973 /// int f(int, int); // #3 974 /// 975 /// When we process #1, there is no previous declaration of "f", so IsOverload 976 /// will not be used. 977 /// 978 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 979 /// the parameter types, we see that #1 and #2 are overloaded (since they have 980 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 981 /// unchanged. 982 /// 983 /// When we process #3, Old is an overload set containing #1 and #2. We compare 984 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 985 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 986 /// functions are not part of the signature), IsOverload returns Ovl_Match and 987 /// MatchedDecl will be set to point to the FunctionDecl for #2. 988 /// 989 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 990 /// by a using declaration. The rules for whether to hide shadow declarations 991 /// ignore some properties which otherwise figure into a function template's 992 /// signature. 993 Sema::OverloadKind 994 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 995 NamedDecl *&Match, bool NewIsUsingDecl) { 996 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 997 I != E; ++I) { 998 NamedDecl *OldD = *I; 999 1000 bool OldIsUsingDecl = false; 1001 if (isa<UsingShadowDecl>(OldD)) { 1002 OldIsUsingDecl = true; 1003 1004 // We can always introduce two using declarations into the same 1005 // context, even if they have identical signatures. 1006 if (NewIsUsingDecl) continue; 1007 1008 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1009 } 1010 1011 // A using-declaration does not conflict with another declaration 1012 // if one of them is hidden. 1013 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1014 continue; 1015 1016 // If either declaration was introduced by a using declaration, 1017 // we'll need to use slightly different rules for matching. 1018 // Essentially, these rules are the normal rules, except that 1019 // function templates hide function templates with different 1020 // return types or template parameter lists. 1021 bool UseMemberUsingDeclRules = 1022 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1023 !New->getFriendObjectKind(); 1024 1025 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1026 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1027 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1028 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1029 continue; 1030 } 1031 1032 if (!isa<FunctionTemplateDecl>(OldD) && 1033 !shouldLinkPossiblyHiddenDecl(*I, New)) 1034 continue; 1035 1036 Match = *I; 1037 return Ovl_Match; 1038 } 1039 1040 // Builtins that have custom typechecking or have a reference should 1041 // not be overloadable or redeclarable. 1042 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1043 Match = *I; 1044 return Ovl_NonFunction; 1045 } 1046 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1047 // We can overload with these, which can show up when doing 1048 // redeclaration checks for UsingDecls. 1049 assert(Old.getLookupKind() == LookupUsingDeclName); 1050 } else if (isa<TagDecl>(OldD)) { 1051 // We can always overload with tags by hiding them. 1052 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1053 // Optimistically assume that an unresolved using decl will 1054 // overload; if it doesn't, we'll have to diagnose during 1055 // template instantiation. 1056 // 1057 // Exception: if the scope is dependent and this is not a class 1058 // member, the using declaration can only introduce an enumerator. 1059 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1060 Match = *I; 1061 return Ovl_NonFunction; 1062 } 1063 } else { 1064 // (C++ 13p1): 1065 // Only function declarations can be overloaded; object and type 1066 // declarations cannot be overloaded. 1067 Match = *I; 1068 return Ovl_NonFunction; 1069 } 1070 } 1071 1072 // C++ [temp.friend]p1: 1073 // For a friend function declaration that is not a template declaration: 1074 // -- if the name of the friend is a qualified or unqualified template-id, 1075 // [...], otherwise 1076 // -- if the name of the friend is a qualified-id and a matching 1077 // non-template function is found in the specified class or namespace, 1078 // the friend declaration refers to that function, otherwise, 1079 // -- if the name of the friend is a qualified-id and a matching function 1080 // template is found in the specified class or namespace, the friend 1081 // declaration refers to the deduced specialization of that function 1082 // template, otherwise 1083 // -- the name shall be an unqualified-id [...] 1084 // If we get here for a qualified friend declaration, we've just reached the 1085 // third bullet. If the type of the friend is dependent, skip this lookup 1086 // until instantiation. 1087 if (New->getFriendObjectKind() && New->getQualifier() && 1088 !New->getDescribedFunctionTemplate() && 1089 !New->getDependentSpecializationInfo() && 1090 !New->getType()->isDependentType()) { 1091 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1092 TemplateSpecResult.addAllDecls(Old); 1093 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1094 /*QualifiedFriend*/true)) { 1095 New->setInvalidDecl(); 1096 return Ovl_Overload; 1097 } 1098 1099 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1100 return Ovl_Match; 1101 } 1102 1103 return Ovl_Overload; 1104 } 1105 1106 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1107 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1108 // C++ [basic.start.main]p2: This function shall not be overloaded. 1109 if (New->isMain()) 1110 return false; 1111 1112 // MSVCRT user defined entry points cannot be overloaded. 1113 if (New->isMSVCRTEntryPoint()) 1114 return false; 1115 1116 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1117 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1118 1119 // C++ [temp.fct]p2: 1120 // A function template can be overloaded with other function templates 1121 // and with normal (non-template) functions. 1122 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1123 return true; 1124 1125 // Is the function New an overload of the function Old? 1126 QualType OldQType = Context.getCanonicalType(Old->getType()); 1127 QualType NewQType = Context.getCanonicalType(New->getType()); 1128 1129 // Compare the signatures (C++ 1.3.10) of the two functions to 1130 // determine whether they are overloads. If we find any mismatch 1131 // in the signature, they are overloads. 1132 1133 // If either of these functions is a K&R-style function (no 1134 // prototype), then we consider them to have matching signatures. 1135 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1136 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1137 return false; 1138 1139 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1140 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1141 1142 // The signature of a function includes the types of its 1143 // parameters (C++ 1.3.10), which includes the presence or absence 1144 // of the ellipsis; see C++ DR 357). 1145 if (OldQType != NewQType && 1146 (OldType->getNumParams() != NewType->getNumParams() || 1147 OldType->isVariadic() != NewType->isVariadic() || 1148 !FunctionParamTypesAreEqual(OldType, NewType))) 1149 return true; 1150 1151 // C++ [temp.over.link]p4: 1152 // The signature of a function template consists of its function 1153 // signature, its return type and its template parameter list. The names 1154 // of the template parameters are significant only for establishing the 1155 // relationship between the template parameters and the rest of the 1156 // signature. 1157 // 1158 // We check the return type and template parameter lists for function 1159 // templates first; the remaining checks follow. 1160 // 1161 // However, we don't consider either of these when deciding whether 1162 // a member introduced by a shadow declaration is hidden. 1163 if (!UseMemberUsingDeclRules && NewTemplate && 1164 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1165 OldTemplate->getTemplateParameters(), 1166 false, TPL_TemplateMatch) || 1167 !Context.hasSameType(Old->getDeclaredReturnType(), 1168 New->getDeclaredReturnType()))) 1169 return true; 1170 1171 // If the function is a class member, its signature includes the 1172 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1173 // 1174 // As part of this, also check whether one of the member functions 1175 // is static, in which case they are not overloads (C++ 1176 // 13.1p2). While not part of the definition of the signature, 1177 // this check is important to determine whether these functions 1178 // can be overloaded. 1179 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1180 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1181 if (OldMethod && NewMethod && 1182 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1183 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1184 if (!UseMemberUsingDeclRules && 1185 (OldMethod->getRefQualifier() == RQ_None || 1186 NewMethod->getRefQualifier() == RQ_None)) { 1187 // C++0x [over.load]p2: 1188 // - Member function declarations with the same name and the same 1189 // parameter-type-list as well as member function template 1190 // declarations with the same name, the same parameter-type-list, and 1191 // the same template parameter lists cannot be overloaded if any of 1192 // them, but not all, have a ref-qualifier (8.3.5). 1193 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1194 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1195 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1196 } 1197 return true; 1198 } 1199 1200 // We may not have applied the implicit const for a constexpr member 1201 // function yet (because we haven't yet resolved whether this is a static 1202 // or non-static member function). Add it now, on the assumption that this 1203 // is a redeclaration of OldMethod. 1204 auto OldQuals = OldMethod->getMethodQualifiers(); 1205 auto NewQuals = NewMethod->getMethodQualifiers(); 1206 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1207 !isa<CXXConstructorDecl>(NewMethod)) 1208 NewQuals.addConst(); 1209 // We do not allow overloading based off of '__restrict'. 1210 OldQuals.removeRestrict(); 1211 NewQuals.removeRestrict(); 1212 if (OldQuals != NewQuals) 1213 return true; 1214 } 1215 1216 // Though pass_object_size is placed on parameters and takes an argument, we 1217 // consider it to be a function-level modifier for the sake of function 1218 // identity. Either the function has one or more parameters with 1219 // pass_object_size or it doesn't. 1220 if (functionHasPassObjectSizeParams(New) != 1221 functionHasPassObjectSizeParams(Old)) 1222 return true; 1223 1224 // enable_if attributes are an order-sensitive part of the signature. 1225 for (specific_attr_iterator<EnableIfAttr> 1226 NewI = New->specific_attr_begin<EnableIfAttr>(), 1227 NewE = New->specific_attr_end<EnableIfAttr>(), 1228 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1229 OldE = Old->specific_attr_end<EnableIfAttr>(); 1230 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1231 if (NewI == NewE || OldI == OldE) 1232 return true; 1233 llvm::FoldingSetNodeID NewID, OldID; 1234 NewI->getCond()->Profile(NewID, Context, true); 1235 OldI->getCond()->Profile(OldID, Context, true); 1236 if (NewID != OldID) 1237 return true; 1238 } 1239 1240 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1241 // Don't allow overloading of destructors. (In theory we could, but it 1242 // would be a giant change to clang.) 1243 if (isa<CXXDestructorDecl>(New)) 1244 return false; 1245 1246 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1247 OldTarget = IdentifyCUDATarget(Old); 1248 if (NewTarget == CFT_InvalidTarget) 1249 return false; 1250 1251 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1252 1253 // Allow overloading of functions with same signature and different CUDA 1254 // target attributes. 1255 return NewTarget != OldTarget; 1256 } 1257 1258 // The signatures match; this is not an overload. 1259 return false; 1260 } 1261 1262 /// Tries a user-defined conversion from From to ToType. 1263 /// 1264 /// Produces an implicit conversion sequence for when a standard conversion 1265 /// is not an option. See TryImplicitConversion for more information. 1266 static ImplicitConversionSequence 1267 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1268 bool SuppressUserConversions, 1269 bool AllowExplicit, 1270 bool InOverloadResolution, 1271 bool CStyle, 1272 bool AllowObjCWritebackConversion, 1273 bool AllowObjCConversionOnExplicit) { 1274 ImplicitConversionSequence ICS; 1275 1276 if (SuppressUserConversions) { 1277 // We're not in the case above, so there is no conversion that 1278 // we can perform. 1279 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1280 return ICS; 1281 } 1282 1283 // Attempt user-defined conversion. 1284 OverloadCandidateSet Conversions(From->getExprLoc(), 1285 OverloadCandidateSet::CSK_Normal); 1286 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1287 Conversions, AllowExplicit, 1288 AllowObjCConversionOnExplicit)) { 1289 case OR_Success: 1290 case OR_Deleted: 1291 ICS.setUserDefined(); 1292 // C++ [over.ics.user]p4: 1293 // A conversion of an expression of class type to the same class 1294 // type is given Exact Match rank, and a conversion of an 1295 // expression of class type to a base class of that type is 1296 // given Conversion rank, in spite of the fact that a copy 1297 // constructor (i.e., a user-defined conversion function) is 1298 // called for those cases. 1299 if (CXXConstructorDecl *Constructor 1300 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1301 QualType FromCanon 1302 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1303 QualType ToCanon 1304 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1305 if (Constructor->isCopyConstructor() && 1306 (FromCanon == ToCanon || 1307 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1308 // Turn this into a "standard" conversion sequence, so that it 1309 // gets ranked with standard conversion sequences. 1310 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1311 ICS.setStandard(); 1312 ICS.Standard.setAsIdentityConversion(); 1313 ICS.Standard.setFromType(From->getType()); 1314 ICS.Standard.setAllToTypes(ToType); 1315 ICS.Standard.CopyConstructor = Constructor; 1316 ICS.Standard.FoundCopyConstructor = Found; 1317 if (ToCanon != FromCanon) 1318 ICS.Standard.Second = ICK_Derived_To_Base; 1319 } 1320 } 1321 break; 1322 1323 case OR_Ambiguous: 1324 ICS.setAmbiguous(); 1325 ICS.Ambiguous.setFromType(From->getType()); 1326 ICS.Ambiguous.setToType(ToType); 1327 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1328 Cand != Conversions.end(); ++Cand) 1329 if (Cand->Best) 1330 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1331 break; 1332 1333 // Fall through. 1334 case OR_No_Viable_Function: 1335 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1336 break; 1337 } 1338 1339 return ICS; 1340 } 1341 1342 /// TryImplicitConversion - Attempt to perform an implicit conversion 1343 /// from the given expression (Expr) to the given type (ToType). This 1344 /// function returns an implicit conversion sequence that can be used 1345 /// to perform the initialization. Given 1346 /// 1347 /// void f(float f); 1348 /// void g(int i) { f(i); } 1349 /// 1350 /// this routine would produce an implicit conversion sequence to 1351 /// describe the initialization of f from i, which will be a standard 1352 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1353 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1354 // 1355 /// Note that this routine only determines how the conversion can be 1356 /// performed; it does not actually perform the conversion. As such, 1357 /// it will not produce any diagnostics if no conversion is available, 1358 /// but will instead return an implicit conversion sequence of kind 1359 /// "BadConversion". 1360 /// 1361 /// If @p SuppressUserConversions, then user-defined conversions are 1362 /// not permitted. 1363 /// If @p AllowExplicit, then explicit user-defined conversions are 1364 /// permitted. 1365 /// 1366 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1367 /// writeback conversion, which allows __autoreleasing id* parameters to 1368 /// be initialized with __strong id* or __weak id* arguments. 1369 static ImplicitConversionSequence 1370 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1371 bool SuppressUserConversions, 1372 bool AllowExplicit, 1373 bool InOverloadResolution, 1374 bool CStyle, 1375 bool AllowObjCWritebackConversion, 1376 bool AllowObjCConversionOnExplicit) { 1377 ImplicitConversionSequence ICS; 1378 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1379 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1380 ICS.setStandard(); 1381 return ICS; 1382 } 1383 1384 if (!S.getLangOpts().CPlusPlus) { 1385 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1386 return ICS; 1387 } 1388 1389 // C++ [over.ics.user]p4: 1390 // A conversion of an expression of class type to the same class 1391 // type is given Exact Match rank, and a conversion of an 1392 // expression of class type to a base class of that type is 1393 // given Conversion rank, in spite of the fact that a copy/move 1394 // constructor (i.e., a user-defined conversion function) is 1395 // called for those cases. 1396 QualType FromType = From->getType(); 1397 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1398 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1399 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1400 ICS.setStandard(); 1401 ICS.Standard.setAsIdentityConversion(); 1402 ICS.Standard.setFromType(FromType); 1403 ICS.Standard.setAllToTypes(ToType); 1404 1405 // We don't actually check at this point whether there is a valid 1406 // copy/move constructor, since overloading just assumes that it 1407 // exists. When we actually perform initialization, we'll find the 1408 // appropriate constructor to copy the returned object, if needed. 1409 ICS.Standard.CopyConstructor = nullptr; 1410 1411 // Determine whether this is considered a derived-to-base conversion. 1412 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1413 ICS.Standard.Second = ICK_Derived_To_Base; 1414 1415 return ICS; 1416 } 1417 1418 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1419 AllowExplicit, InOverloadResolution, CStyle, 1420 AllowObjCWritebackConversion, 1421 AllowObjCConversionOnExplicit); 1422 } 1423 1424 ImplicitConversionSequence 1425 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1426 bool SuppressUserConversions, 1427 bool AllowExplicit, 1428 bool InOverloadResolution, 1429 bool CStyle, 1430 bool AllowObjCWritebackConversion) { 1431 return ::TryImplicitConversion(*this, From, ToType, 1432 SuppressUserConversions, AllowExplicit, 1433 InOverloadResolution, CStyle, 1434 AllowObjCWritebackConversion, 1435 /*AllowObjCConversionOnExplicit=*/false); 1436 } 1437 1438 /// PerformImplicitConversion - Perform an implicit conversion of the 1439 /// expression From to the type ToType. Returns the 1440 /// converted expression. Flavor is the kind of conversion we're 1441 /// performing, used in the error message. If @p AllowExplicit, 1442 /// explicit user-defined conversions are permitted. 1443 ExprResult 1444 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1445 AssignmentAction Action, bool AllowExplicit) { 1446 ImplicitConversionSequence ICS; 1447 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1448 } 1449 1450 ExprResult 1451 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1452 AssignmentAction Action, bool AllowExplicit, 1453 ImplicitConversionSequence& ICS) { 1454 if (checkPlaceholderForOverload(*this, From)) 1455 return ExprError(); 1456 1457 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1458 bool AllowObjCWritebackConversion 1459 = getLangOpts().ObjCAutoRefCount && 1460 (Action == AA_Passing || Action == AA_Sending); 1461 if (getLangOpts().ObjC) 1462 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1463 From->getType(), From); 1464 ICS = ::TryImplicitConversion(*this, From, ToType, 1465 /*SuppressUserConversions=*/false, 1466 AllowExplicit, 1467 /*InOverloadResolution=*/false, 1468 /*CStyle=*/false, 1469 AllowObjCWritebackConversion, 1470 /*AllowObjCConversionOnExplicit=*/false); 1471 return PerformImplicitConversion(From, ToType, ICS, Action); 1472 } 1473 1474 /// Determine whether the conversion from FromType to ToType is a valid 1475 /// conversion that strips "noexcept" or "noreturn" off the nested function 1476 /// type. 1477 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1478 QualType &ResultTy) { 1479 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1480 return false; 1481 1482 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1483 // or F(t noexcept) -> F(t) 1484 // where F adds one of the following at most once: 1485 // - a pointer 1486 // - a member pointer 1487 // - a block pointer 1488 // Changes here need matching changes in FindCompositePointerType. 1489 CanQualType CanTo = Context.getCanonicalType(ToType); 1490 CanQualType CanFrom = Context.getCanonicalType(FromType); 1491 Type::TypeClass TyClass = CanTo->getTypeClass(); 1492 if (TyClass != CanFrom->getTypeClass()) return false; 1493 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1494 if (TyClass == Type::Pointer) { 1495 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1496 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1497 } else if (TyClass == Type::BlockPointer) { 1498 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1499 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1500 } else if (TyClass == Type::MemberPointer) { 1501 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1502 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1503 // A function pointer conversion cannot change the class of the function. 1504 if (ToMPT->getClass() != FromMPT->getClass()) 1505 return false; 1506 CanTo = ToMPT->getPointeeType(); 1507 CanFrom = FromMPT->getPointeeType(); 1508 } else { 1509 return false; 1510 } 1511 1512 TyClass = CanTo->getTypeClass(); 1513 if (TyClass != CanFrom->getTypeClass()) return false; 1514 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1515 return false; 1516 } 1517 1518 const auto *FromFn = cast<FunctionType>(CanFrom); 1519 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1520 1521 const auto *ToFn = cast<FunctionType>(CanTo); 1522 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1523 1524 bool Changed = false; 1525 1526 // Drop 'noreturn' if not present in target type. 1527 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1528 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1529 Changed = true; 1530 } 1531 1532 // Drop 'noexcept' if not present in target type. 1533 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1534 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1535 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1536 FromFn = cast<FunctionType>( 1537 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1538 EST_None) 1539 .getTypePtr()); 1540 Changed = true; 1541 } 1542 1543 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1544 // only if the ExtParameterInfo lists of the two function prototypes can be 1545 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1546 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1547 bool CanUseToFPT, CanUseFromFPT; 1548 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1549 CanUseFromFPT, NewParamInfos) && 1550 CanUseToFPT && !CanUseFromFPT) { 1551 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1552 ExtInfo.ExtParameterInfos = 1553 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1554 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1555 FromFPT->getParamTypes(), ExtInfo); 1556 FromFn = QT->getAs<FunctionType>(); 1557 Changed = true; 1558 } 1559 } 1560 1561 if (!Changed) 1562 return false; 1563 1564 assert(QualType(FromFn, 0).isCanonical()); 1565 if (QualType(FromFn, 0) != CanTo) return false; 1566 1567 ResultTy = ToType; 1568 return true; 1569 } 1570 1571 /// Determine whether the conversion from FromType to ToType is a valid 1572 /// vector conversion. 1573 /// 1574 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1575 /// conversion. 1576 static bool IsVectorConversion(Sema &S, QualType FromType, 1577 QualType ToType, ImplicitConversionKind &ICK) { 1578 // We need at least one of these types to be a vector type to have a vector 1579 // conversion. 1580 if (!ToType->isVectorType() && !FromType->isVectorType()) 1581 return false; 1582 1583 // Identical types require no conversions. 1584 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1585 return false; 1586 1587 // There are no conversions between extended vector types, only identity. 1588 if (ToType->isExtVectorType()) { 1589 // There are no conversions between extended vector types other than the 1590 // identity conversion. 1591 if (FromType->isExtVectorType()) 1592 return false; 1593 1594 // Vector splat from any arithmetic type to a vector. 1595 if (FromType->isArithmeticType()) { 1596 ICK = ICK_Vector_Splat; 1597 return true; 1598 } 1599 } 1600 1601 // We can perform the conversion between vector types in the following cases: 1602 // 1)vector types are equivalent AltiVec and GCC vector types 1603 // 2)lax vector conversions are permitted and the vector types are of the 1604 // same size 1605 if (ToType->isVectorType() && FromType->isVectorType()) { 1606 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1607 S.isLaxVectorConversion(FromType, ToType)) { 1608 ICK = ICK_Vector_Conversion; 1609 return true; 1610 } 1611 } 1612 1613 return false; 1614 } 1615 1616 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1617 bool InOverloadResolution, 1618 StandardConversionSequence &SCS, 1619 bool CStyle); 1620 1621 /// IsStandardConversion - Determines whether there is a standard 1622 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1623 /// expression From to the type ToType. Standard conversion sequences 1624 /// only consider non-class types; for conversions that involve class 1625 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1626 /// contain the standard conversion sequence required to perform this 1627 /// conversion and this routine will return true. Otherwise, this 1628 /// routine will return false and the value of SCS is unspecified. 1629 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1630 bool InOverloadResolution, 1631 StandardConversionSequence &SCS, 1632 bool CStyle, 1633 bool AllowObjCWritebackConversion) { 1634 QualType FromType = From->getType(); 1635 1636 // Standard conversions (C++ [conv]) 1637 SCS.setAsIdentityConversion(); 1638 SCS.IncompatibleObjC = false; 1639 SCS.setFromType(FromType); 1640 SCS.CopyConstructor = nullptr; 1641 1642 // There are no standard conversions for class types in C++, so 1643 // abort early. When overloading in C, however, we do permit them. 1644 if (S.getLangOpts().CPlusPlus && 1645 (FromType->isRecordType() || ToType->isRecordType())) 1646 return false; 1647 1648 // The first conversion can be an lvalue-to-rvalue conversion, 1649 // array-to-pointer conversion, or function-to-pointer conversion 1650 // (C++ 4p1). 1651 1652 if (FromType == S.Context.OverloadTy) { 1653 DeclAccessPair AccessPair; 1654 if (FunctionDecl *Fn 1655 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1656 AccessPair)) { 1657 // We were able to resolve the address of the overloaded function, 1658 // so we can convert to the type of that function. 1659 FromType = Fn->getType(); 1660 SCS.setFromType(FromType); 1661 1662 // we can sometimes resolve &foo<int> regardless of ToType, so check 1663 // if the type matches (identity) or we are converting to bool 1664 if (!S.Context.hasSameUnqualifiedType( 1665 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1666 QualType resultTy; 1667 // if the function type matches except for [[noreturn]], it's ok 1668 if (!S.IsFunctionConversion(FromType, 1669 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1670 // otherwise, only a boolean conversion is standard 1671 if (!ToType->isBooleanType()) 1672 return false; 1673 } 1674 1675 // Check if the "from" expression is taking the address of an overloaded 1676 // function and recompute the FromType accordingly. Take advantage of the 1677 // fact that non-static member functions *must* have such an address-of 1678 // expression. 1679 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1680 if (Method && !Method->isStatic()) { 1681 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1682 "Non-unary operator on non-static member address"); 1683 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1684 == UO_AddrOf && 1685 "Non-address-of operator on non-static member address"); 1686 const Type *ClassType 1687 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1688 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1689 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1690 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1691 UO_AddrOf && 1692 "Non-address-of operator for overloaded function expression"); 1693 FromType = S.Context.getPointerType(FromType); 1694 } 1695 1696 // Check that we've computed the proper type after overload resolution. 1697 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1698 // be calling it from within an NDEBUG block. 1699 assert(S.Context.hasSameType( 1700 FromType, 1701 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1702 } else { 1703 return false; 1704 } 1705 } 1706 // Lvalue-to-rvalue conversion (C++11 4.1): 1707 // A glvalue (3.10) of a non-function, non-array type T can 1708 // be converted to a prvalue. 1709 bool argIsLValue = From->isGLValue(); 1710 if (argIsLValue && 1711 !FromType->isFunctionType() && !FromType->isArrayType() && 1712 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1713 SCS.First = ICK_Lvalue_To_Rvalue; 1714 1715 // C11 6.3.2.1p2: 1716 // ... if the lvalue has atomic type, the value has the non-atomic version 1717 // of the type of the lvalue ... 1718 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1719 FromType = Atomic->getValueType(); 1720 1721 // If T is a non-class type, the type of the rvalue is the 1722 // cv-unqualified version of T. Otherwise, the type of the rvalue 1723 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1724 // just strip the qualifiers because they don't matter. 1725 FromType = FromType.getUnqualifiedType(); 1726 } else if (FromType->isArrayType()) { 1727 // Array-to-pointer conversion (C++ 4.2) 1728 SCS.First = ICK_Array_To_Pointer; 1729 1730 // An lvalue or rvalue of type "array of N T" or "array of unknown 1731 // bound of T" can be converted to an rvalue of type "pointer to 1732 // T" (C++ 4.2p1). 1733 FromType = S.Context.getArrayDecayedType(FromType); 1734 1735 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1736 // This conversion is deprecated in C++03 (D.4) 1737 SCS.DeprecatedStringLiteralToCharPtr = true; 1738 1739 // For the purpose of ranking in overload resolution 1740 // (13.3.3.1.1), this conversion is considered an 1741 // array-to-pointer conversion followed by a qualification 1742 // conversion (4.4). (C++ 4.2p2) 1743 SCS.Second = ICK_Identity; 1744 SCS.Third = ICK_Qualification; 1745 SCS.QualificationIncludesObjCLifetime = false; 1746 SCS.setAllToTypes(FromType); 1747 return true; 1748 } 1749 } else if (FromType->isFunctionType() && argIsLValue) { 1750 // Function-to-pointer conversion (C++ 4.3). 1751 SCS.First = ICK_Function_To_Pointer; 1752 1753 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1754 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1755 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1756 return false; 1757 1758 // An lvalue of function type T can be converted to an rvalue of 1759 // type "pointer to T." The result is a pointer to the 1760 // function. (C++ 4.3p1). 1761 FromType = S.Context.getPointerType(FromType); 1762 } else { 1763 // We don't require any conversions for the first step. 1764 SCS.First = ICK_Identity; 1765 } 1766 SCS.setToType(0, FromType); 1767 1768 // The second conversion can be an integral promotion, floating 1769 // point promotion, integral conversion, floating point conversion, 1770 // floating-integral conversion, pointer conversion, 1771 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1772 // For overloading in C, this can also be a "compatible-type" 1773 // conversion. 1774 bool IncompatibleObjC = false; 1775 ImplicitConversionKind SecondICK = ICK_Identity; 1776 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1777 // The unqualified versions of the types are the same: there's no 1778 // conversion to do. 1779 SCS.Second = ICK_Identity; 1780 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1781 // Integral promotion (C++ 4.5). 1782 SCS.Second = ICK_Integral_Promotion; 1783 FromType = ToType.getUnqualifiedType(); 1784 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1785 // Floating point promotion (C++ 4.6). 1786 SCS.Second = ICK_Floating_Promotion; 1787 FromType = ToType.getUnqualifiedType(); 1788 } else if (S.IsComplexPromotion(FromType, ToType)) { 1789 // Complex promotion (Clang extension) 1790 SCS.Second = ICK_Complex_Promotion; 1791 FromType = ToType.getUnqualifiedType(); 1792 } else if (ToType->isBooleanType() && 1793 (FromType->isArithmeticType() || 1794 FromType->isAnyPointerType() || 1795 FromType->isBlockPointerType() || 1796 FromType->isMemberPointerType() || 1797 FromType->isNullPtrType())) { 1798 // Boolean conversions (C++ 4.12). 1799 SCS.Second = ICK_Boolean_Conversion; 1800 FromType = S.Context.BoolTy; 1801 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1802 ToType->isIntegralType(S.Context)) { 1803 // Integral conversions (C++ 4.7). 1804 SCS.Second = ICK_Integral_Conversion; 1805 FromType = ToType.getUnqualifiedType(); 1806 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1807 // Complex conversions (C99 6.3.1.6) 1808 SCS.Second = ICK_Complex_Conversion; 1809 FromType = ToType.getUnqualifiedType(); 1810 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1811 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1812 // Complex-real conversions (C99 6.3.1.7) 1813 SCS.Second = ICK_Complex_Real; 1814 FromType = ToType.getUnqualifiedType(); 1815 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1816 // FIXME: disable conversions between long double and __float128 if 1817 // their representation is different until there is back end support 1818 // We of course allow this conversion if long double is really double. 1819 if (&S.Context.getFloatTypeSemantics(FromType) != 1820 &S.Context.getFloatTypeSemantics(ToType)) { 1821 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1822 ToType == S.Context.LongDoubleTy) || 1823 (FromType == S.Context.LongDoubleTy && 1824 ToType == S.Context.Float128Ty)); 1825 if (Float128AndLongDouble && 1826 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1827 &llvm::APFloat::PPCDoubleDouble())) 1828 return false; 1829 } 1830 // Floating point conversions (C++ 4.8). 1831 SCS.Second = ICK_Floating_Conversion; 1832 FromType = ToType.getUnqualifiedType(); 1833 } else if ((FromType->isRealFloatingType() && 1834 ToType->isIntegralType(S.Context)) || 1835 (FromType->isIntegralOrUnscopedEnumerationType() && 1836 ToType->isRealFloatingType())) { 1837 // Floating-integral conversions (C++ 4.9). 1838 SCS.Second = ICK_Floating_Integral; 1839 FromType = ToType.getUnqualifiedType(); 1840 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1841 SCS.Second = ICK_Block_Pointer_Conversion; 1842 } else if (AllowObjCWritebackConversion && 1843 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1844 SCS.Second = ICK_Writeback_Conversion; 1845 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1846 FromType, IncompatibleObjC)) { 1847 // Pointer conversions (C++ 4.10). 1848 SCS.Second = ICK_Pointer_Conversion; 1849 SCS.IncompatibleObjC = IncompatibleObjC; 1850 FromType = FromType.getUnqualifiedType(); 1851 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1852 InOverloadResolution, FromType)) { 1853 // Pointer to member conversions (4.11). 1854 SCS.Second = ICK_Pointer_Member; 1855 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1856 SCS.Second = SecondICK; 1857 FromType = ToType.getUnqualifiedType(); 1858 } else if (!S.getLangOpts().CPlusPlus && 1859 S.Context.typesAreCompatible(ToType, FromType)) { 1860 // Compatible conversions (Clang extension for C function overloading) 1861 SCS.Second = ICK_Compatible_Conversion; 1862 FromType = ToType.getUnqualifiedType(); 1863 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1864 InOverloadResolution, 1865 SCS, CStyle)) { 1866 SCS.Second = ICK_TransparentUnionConversion; 1867 FromType = ToType; 1868 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1869 CStyle)) { 1870 // tryAtomicConversion has updated the standard conversion sequence 1871 // appropriately. 1872 return true; 1873 } else if (ToType->isEventT() && 1874 From->isIntegerConstantExpr(S.getASTContext()) && 1875 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1876 SCS.Second = ICK_Zero_Event_Conversion; 1877 FromType = ToType; 1878 } else if (ToType->isQueueT() && 1879 From->isIntegerConstantExpr(S.getASTContext()) && 1880 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1881 SCS.Second = ICK_Zero_Queue_Conversion; 1882 FromType = ToType; 1883 } else if (ToType->isSamplerT() && 1884 From->isIntegerConstantExpr(S.getASTContext())) { 1885 SCS.Second = ICK_Compatible_Conversion; 1886 FromType = ToType; 1887 } else { 1888 // No second conversion required. 1889 SCS.Second = ICK_Identity; 1890 } 1891 SCS.setToType(1, FromType); 1892 1893 // The third conversion can be a function pointer conversion or a 1894 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1895 bool ObjCLifetimeConversion; 1896 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1897 // Function pointer conversions (removing 'noexcept') including removal of 1898 // 'noreturn' (Clang extension). 1899 SCS.Third = ICK_Function_Conversion; 1900 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1901 ObjCLifetimeConversion)) { 1902 SCS.Third = ICK_Qualification; 1903 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1904 FromType = ToType; 1905 } else { 1906 // No conversion required 1907 SCS.Third = ICK_Identity; 1908 } 1909 1910 // C++ [over.best.ics]p6: 1911 // [...] Any difference in top-level cv-qualification is 1912 // subsumed by the initialization itself and does not constitute 1913 // a conversion. [...] 1914 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1915 QualType CanonTo = S.Context.getCanonicalType(ToType); 1916 if (CanonFrom.getLocalUnqualifiedType() 1917 == CanonTo.getLocalUnqualifiedType() && 1918 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1919 FromType = ToType; 1920 CanonFrom = CanonTo; 1921 } 1922 1923 SCS.setToType(2, FromType); 1924 1925 if (CanonFrom == CanonTo) 1926 return true; 1927 1928 // If we have not converted the argument type to the parameter type, 1929 // this is a bad conversion sequence, unless we're resolving an overload in C. 1930 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1931 return false; 1932 1933 ExprResult ER = ExprResult{From}; 1934 Sema::AssignConvertType Conv = 1935 S.CheckSingleAssignmentConstraints(ToType, ER, 1936 /*Diagnose=*/false, 1937 /*DiagnoseCFAudited=*/false, 1938 /*ConvertRHS=*/false); 1939 ImplicitConversionKind SecondConv; 1940 switch (Conv) { 1941 case Sema::Compatible: 1942 SecondConv = ICK_C_Only_Conversion; 1943 break; 1944 // For our purposes, discarding qualifiers is just as bad as using an 1945 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1946 // qualifiers, as well. 1947 case Sema::CompatiblePointerDiscardsQualifiers: 1948 case Sema::IncompatiblePointer: 1949 case Sema::IncompatiblePointerSign: 1950 SecondConv = ICK_Incompatible_Pointer_Conversion; 1951 break; 1952 default: 1953 return false; 1954 } 1955 1956 // First can only be an lvalue conversion, so we pretend that this was the 1957 // second conversion. First should already be valid from earlier in the 1958 // function. 1959 SCS.Second = SecondConv; 1960 SCS.setToType(1, ToType); 1961 1962 // Third is Identity, because Second should rank us worse than any other 1963 // conversion. This could also be ICK_Qualification, but it's simpler to just 1964 // lump everything in with the second conversion, and we don't gain anything 1965 // from making this ICK_Qualification. 1966 SCS.Third = ICK_Identity; 1967 SCS.setToType(2, ToType); 1968 return true; 1969 } 1970 1971 static bool 1972 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1973 QualType &ToType, 1974 bool InOverloadResolution, 1975 StandardConversionSequence &SCS, 1976 bool CStyle) { 1977 1978 const RecordType *UT = ToType->getAsUnionType(); 1979 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1980 return false; 1981 // The field to initialize within the transparent union. 1982 RecordDecl *UD = UT->getDecl(); 1983 // It's compatible if the expression matches any of the fields. 1984 for (const auto *it : UD->fields()) { 1985 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1986 CStyle, /*AllowObjCWritebackConversion=*/false)) { 1987 ToType = it->getType(); 1988 return true; 1989 } 1990 } 1991 return false; 1992 } 1993 1994 /// IsIntegralPromotion - Determines whether the conversion from the 1995 /// expression From (whose potentially-adjusted type is FromType) to 1996 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1997 /// sets PromotedType to the promoted type. 1998 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1999 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2000 // All integers are built-in. 2001 if (!To) { 2002 return false; 2003 } 2004 2005 // An rvalue of type char, signed char, unsigned char, short int, or 2006 // unsigned short int can be converted to an rvalue of type int if 2007 // int can represent all the values of the source type; otherwise, 2008 // the source rvalue can be converted to an rvalue of type unsigned 2009 // int (C++ 4.5p1). 2010 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2011 !FromType->isEnumeralType()) { 2012 if (// We can promote any signed, promotable integer type to an int 2013 (FromType->isSignedIntegerType() || 2014 // We can promote any unsigned integer type whose size is 2015 // less than int to an int. 2016 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2017 return To->getKind() == BuiltinType::Int; 2018 } 2019 2020 return To->getKind() == BuiltinType::UInt; 2021 } 2022 2023 // C++11 [conv.prom]p3: 2024 // A prvalue of an unscoped enumeration type whose underlying type is not 2025 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2026 // following types that can represent all the values of the enumeration 2027 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2028 // unsigned int, long int, unsigned long int, long long int, or unsigned 2029 // long long int. If none of the types in that list can represent all the 2030 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2031 // type can be converted to an rvalue a prvalue of the extended integer type 2032 // with lowest integer conversion rank (4.13) greater than the rank of long 2033 // long in which all the values of the enumeration can be represented. If 2034 // there are two such extended types, the signed one is chosen. 2035 // C++11 [conv.prom]p4: 2036 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2037 // can be converted to a prvalue of its underlying type. Moreover, if 2038 // integral promotion can be applied to its underlying type, a prvalue of an 2039 // unscoped enumeration type whose underlying type is fixed can also be 2040 // converted to a prvalue of the promoted underlying type. 2041 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2042 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2043 // provided for a scoped enumeration. 2044 if (FromEnumType->getDecl()->isScoped()) 2045 return false; 2046 2047 // We can perform an integral promotion to the underlying type of the enum, 2048 // even if that's not the promoted type. Note that the check for promoting 2049 // the underlying type is based on the type alone, and does not consider 2050 // the bitfield-ness of the actual source expression. 2051 if (FromEnumType->getDecl()->isFixed()) { 2052 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2053 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2054 IsIntegralPromotion(nullptr, Underlying, ToType); 2055 } 2056 2057 // We have already pre-calculated the promotion type, so this is trivial. 2058 if (ToType->isIntegerType() && 2059 isCompleteType(From->getBeginLoc(), FromType)) 2060 return Context.hasSameUnqualifiedType( 2061 ToType, FromEnumType->getDecl()->getPromotionType()); 2062 2063 // C++ [conv.prom]p5: 2064 // If the bit-field has an enumerated type, it is treated as any other 2065 // value of that type for promotion purposes. 2066 // 2067 // ... so do not fall through into the bit-field checks below in C++. 2068 if (getLangOpts().CPlusPlus) 2069 return false; 2070 } 2071 2072 // C++0x [conv.prom]p2: 2073 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2074 // to an rvalue a prvalue of the first of the following types that can 2075 // represent all the values of its underlying type: int, unsigned int, 2076 // long int, unsigned long int, long long int, or unsigned long long int. 2077 // If none of the types in that list can represent all the values of its 2078 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2079 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2080 // type. 2081 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2082 ToType->isIntegerType()) { 2083 // Determine whether the type we're converting from is signed or 2084 // unsigned. 2085 bool FromIsSigned = FromType->isSignedIntegerType(); 2086 uint64_t FromSize = Context.getTypeSize(FromType); 2087 2088 // The types we'll try to promote to, in the appropriate 2089 // order. Try each of these types. 2090 QualType PromoteTypes[6] = { 2091 Context.IntTy, Context.UnsignedIntTy, 2092 Context.LongTy, Context.UnsignedLongTy , 2093 Context.LongLongTy, Context.UnsignedLongLongTy 2094 }; 2095 for (int Idx = 0; Idx < 6; ++Idx) { 2096 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2097 if (FromSize < ToSize || 2098 (FromSize == ToSize && 2099 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2100 // We found the type that we can promote to. If this is the 2101 // type we wanted, we have a promotion. Otherwise, no 2102 // promotion. 2103 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2104 } 2105 } 2106 } 2107 2108 // An rvalue for an integral bit-field (9.6) can be converted to an 2109 // rvalue of type int if int can represent all the values of the 2110 // bit-field; otherwise, it can be converted to unsigned int if 2111 // unsigned int can represent all the values of the bit-field. If 2112 // the bit-field is larger yet, no integral promotion applies to 2113 // it. If the bit-field has an enumerated type, it is treated as any 2114 // other value of that type for promotion purposes (C++ 4.5p3). 2115 // FIXME: We should delay checking of bit-fields until we actually perform the 2116 // conversion. 2117 // 2118 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2119 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2120 // bit-fields and those whose underlying type is larger than int) for GCC 2121 // compatibility. 2122 if (From) { 2123 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2124 llvm::APSInt BitWidth; 2125 if (FromType->isIntegralType(Context) && 2126 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2127 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2128 ToSize = Context.getTypeSize(ToType); 2129 2130 // Are we promoting to an int from a bitfield that fits in an int? 2131 if (BitWidth < ToSize || 2132 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2133 return To->getKind() == BuiltinType::Int; 2134 } 2135 2136 // Are we promoting to an unsigned int from an unsigned bitfield 2137 // that fits into an unsigned int? 2138 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2139 return To->getKind() == BuiltinType::UInt; 2140 } 2141 2142 return false; 2143 } 2144 } 2145 } 2146 2147 // An rvalue of type bool can be converted to an rvalue of type int, 2148 // with false becoming zero and true becoming one (C++ 4.5p4). 2149 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2150 return true; 2151 } 2152 2153 return false; 2154 } 2155 2156 /// IsFloatingPointPromotion - Determines whether the conversion from 2157 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2158 /// returns true and sets PromotedType to the promoted type. 2159 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2160 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2161 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2162 /// An rvalue of type float can be converted to an rvalue of type 2163 /// double. (C++ 4.6p1). 2164 if (FromBuiltin->getKind() == BuiltinType::Float && 2165 ToBuiltin->getKind() == BuiltinType::Double) 2166 return true; 2167 2168 // C99 6.3.1.5p1: 2169 // When a float is promoted to double or long double, or a 2170 // double is promoted to long double [...]. 2171 if (!getLangOpts().CPlusPlus && 2172 (FromBuiltin->getKind() == BuiltinType::Float || 2173 FromBuiltin->getKind() == BuiltinType::Double) && 2174 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2175 ToBuiltin->getKind() == BuiltinType::Float128)) 2176 return true; 2177 2178 // Half can be promoted to float. 2179 if (!getLangOpts().NativeHalfType && 2180 FromBuiltin->getKind() == BuiltinType::Half && 2181 ToBuiltin->getKind() == BuiltinType::Float) 2182 return true; 2183 } 2184 2185 return false; 2186 } 2187 2188 /// Determine if a conversion is a complex promotion. 2189 /// 2190 /// A complex promotion is defined as a complex -> complex conversion 2191 /// where the conversion between the underlying real types is a 2192 /// floating-point or integral promotion. 2193 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2194 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2195 if (!FromComplex) 2196 return false; 2197 2198 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2199 if (!ToComplex) 2200 return false; 2201 2202 return IsFloatingPointPromotion(FromComplex->getElementType(), 2203 ToComplex->getElementType()) || 2204 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2205 ToComplex->getElementType()); 2206 } 2207 2208 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2209 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2210 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2211 /// if non-empty, will be a pointer to ToType that may or may not have 2212 /// the right set of qualifiers on its pointee. 2213 /// 2214 static QualType 2215 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2216 QualType ToPointee, QualType ToType, 2217 ASTContext &Context, 2218 bool StripObjCLifetime = false) { 2219 assert((FromPtr->getTypeClass() == Type::Pointer || 2220 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2221 "Invalid similarly-qualified pointer type"); 2222 2223 /// Conversions to 'id' subsume cv-qualifier conversions. 2224 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2225 return ToType.getUnqualifiedType(); 2226 2227 QualType CanonFromPointee 2228 = Context.getCanonicalType(FromPtr->getPointeeType()); 2229 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2230 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2231 2232 if (StripObjCLifetime) 2233 Quals.removeObjCLifetime(); 2234 2235 // Exact qualifier match -> return the pointer type we're converting to. 2236 if (CanonToPointee.getLocalQualifiers() == Quals) { 2237 // ToType is exactly what we need. Return it. 2238 if (!ToType.isNull()) 2239 return ToType.getUnqualifiedType(); 2240 2241 // Build a pointer to ToPointee. It has the right qualifiers 2242 // already. 2243 if (isa<ObjCObjectPointerType>(ToType)) 2244 return Context.getObjCObjectPointerType(ToPointee); 2245 return Context.getPointerType(ToPointee); 2246 } 2247 2248 // Just build a canonical type that has the right qualifiers. 2249 QualType QualifiedCanonToPointee 2250 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2251 2252 if (isa<ObjCObjectPointerType>(ToType)) 2253 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2254 return Context.getPointerType(QualifiedCanonToPointee); 2255 } 2256 2257 static bool isNullPointerConstantForConversion(Expr *Expr, 2258 bool InOverloadResolution, 2259 ASTContext &Context) { 2260 // Handle value-dependent integral null pointer constants correctly. 2261 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2262 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2263 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2264 return !InOverloadResolution; 2265 2266 return Expr->isNullPointerConstant(Context, 2267 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2268 : Expr::NPC_ValueDependentIsNull); 2269 } 2270 2271 /// IsPointerConversion - Determines whether the conversion of the 2272 /// expression From, which has the (possibly adjusted) type FromType, 2273 /// can be converted to the type ToType via a pointer conversion (C++ 2274 /// 4.10). If so, returns true and places the converted type (that 2275 /// might differ from ToType in its cv-qualifiers at some level) into 2276 /// ConvertedType. 2277 /// 2278 /// This routine also supports conversions to and from block pointers 2279 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2280 /// pointers to interfaces. FIXME: Once we've determined the 2281 /// appropriate overloading rules for Objective-C, we may want to 2282 /// split the Objective-C checks into a different routine; however, 2283 /// GCC seems to consider all of these conversions to be pointer 2284 /// conversions, so for now they live here. IncompatibleObjC will be 2285 /// set if the conversion is an allowed Objective-C conversion that 2286 /// should result in a warning. 2287 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2288 bool InOverloadResolution, 2289 QualType& ConvertedType, 2290 bool &IncompatibleObjC) { 2291 IncompatibleObjC = false; 2292 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2293 IncompatibleObjC)) 2294 return true; 2295 2296 // Conversion from a null pointer constant to any Objective-C pointer type. 2297 if (ToType->isObjCObjectPointerType() && 2298 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2299 ConvertedType = ToType; 2300 return true; 2301 } 2302 2303 // Blocks: Block pointers can be converted to void*. 2304 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2305 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2306 ConvertedType = ToType; 2307 return true; 2308 } 2309 // Blocks: A null pointer constant can be converted to a block 2310 // pointer type. 2311 if (ToType->isBlockPointerType() && 2312 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2313 ConvertedType = ToType; 2314 return true; 2315 } 2316 2317 // If the left-hand-side is nullptr_t, the right side can be a null 2318 // pointer constant. 2319 if (ToType->isNullPtrType() && 2320 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2321 ConvertedType = ToType; 2322 return true; 2323 } 2324 2325 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2326 if (!ToTypePtr) 2327 return false; 2328 2329 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2330 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2331 ConvertedType = ToType; 2332 return true; 2333 } 2334 2335 // Beyond this point, both types need to be pointers 2336 // , including objective-c pointers. 2337 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2338 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2339 !getLangOpts().ObjCAutoRefCount) { 2340 ConvertedType = BuildSimilarlyQualifiedPointerType( 2341 FromType->getAs<ObjCObjectPointerType>(), 2342 ToPointeeType, 2343 ToType, Context); 2344 return true; 2345 } 2346 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2347 if (!FromTypePtr) 2348 return false; 2349 2350 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2351 2352 // If the unqualified pointee types are the same, this can't be a 2353 // pointer conversion, so don't do all of the work below. 2354 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2355 return false; 2356 2357 // An rvalue of type "pointer to cv T," where T is an object type, 2358 // can be converted to an rvalue of type "pointer to cv void" (C++ 2359 // 4.10p2). 2360 if (FromPointeeType->isIncompleteOrObjectType() && 2361 ToPointeeType->isVoidType()) { 2362 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2363 ToPointeeType, 2364 ToType, Context, 2365 /*StripObjCLifetime=*/true); 2366 return true; 2367 } 2368 2369 // MSVC allows implicit function to void* type conversion. 2370 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2371 ToPointeeType->isVoidType()) { 2372 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2373 ToPointeeType, 2374 ToType, Context); 2375 return true; 2376 } 2377 2378 // When we're overloading in C, we allow a special kind of pointer 2379 // conversion for compatible-but-not-identical pointee types. 2380 if (!getLangOpts().CPlusPlus && 2381 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2382 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2383 ToPointeeType, 2384 ToType, Context); 2385 return true; 2386 } 2387 2388 // C++ [conv.ptr]p3: 2389 // 2390 // An rvalue of type "pointer to cv D," where D is a class type, 2391 // can be converted to an rvalue of type "pointer to cv B," where 2392 // B is a base class (clause 10) of D. If B is an inaccessible 2393 // (clause 11) or ambiguous (10.2) base class of D, a program that 2394 // necessitates this conversion is ill-formed. The result of the 2395 // conversion is a pointer to the base class sub-object of the 2396 // derived class object. The null pointer value is converted to 2397 // the null pointer value of the destination type. 2398 // 2399 // Note that we do not check for ambiguity or inaccessibility 2400 // here. That is handled by CheckPointerConversion. 2401 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2402 ToPointeeType->isRecordType() && 2403 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2404 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2405 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2406 ToPointeeType, 2407 ToType, Context); 2408 return true; 2409 } 2410 2411 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2412 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2413 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2414 ToPointeeType, 2415 ToType, Context); 2416 return true; 2417 } 2418 2419 return false; 2420 } 2421 2422 /// Adopt the given qualifiers for the given type. 2423 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2424 Qualifiers TQs = T.getQualifiers(); 2425 2426 // Check whether qualifiers already match. 2427 if (TQs == Qs) 2428 return T; 2429 2430 if (Qs.compatiblyIncludes(TQs)) 2431 return Context.getQualifiedType(T, Qs); 2432 2433 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2434 } 2435 2436 /// isObjCPointerConversion - Determines whether this is an 2437 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2438 /// with the same arguments and return values. 2439 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2440 QualType& ConvertedType, 2441 bool &IncompatibleObjC) { 2442 if (!getLangOpts().ObjC) 2443 return false; 2444 2445 // The set of qualifiers on the type we're converting from. 2446 Qualifiers FromQualifiers = FromType.getQualifiers(); 2447 2448 // First, we handle all conversions on ObjC object pointer types. 2449 const ObjCObjectPointerType* ToObjCPtr = 2450 ToType->getAs<ObjCObjectPointerType>(); 2451 const ObjCObjectPointerType *FromObjCPtr = 2452 FromType->getAs<ObjCObjectPointerType>(); 2453 2454 if (ToObjCPtr && FromObjCPtr) { 2455 // If the pointee types are the same (ignoring qualifications), 2456 // then this is not a pointer conversion. 2457 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2458 FromObjCPtr->getPointeeType())) 2459 return false; 2460 2461 // Conversion between Objective-C pointers. 2462 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2463 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2464 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2465 if (getLangOpts().CPlusPlus && LHS && RHS && 2466 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2467 FromObjCPtr->getPointeeType())) 2468 return false; 2469 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2470 ToObjCPtr->getPointeeType(), 2471 ToType, Context); 2472 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2473 return true; 2474 } 2475 2476 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2477 // Okay: this is some kind of implicit downcast of Objective-C 2478 // interfaces, which is permitted. However, we're going to 2479 // complain about it. 2480 IncompatibleObjC = true; 2481 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2482 ToObjCPtr->getPointeeType(), 2483 ToType, Context); 2484 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2485 return true; 2486 } 2487 } 2488 // Beyond this point, both types need to be C pointers or block pointers. 2489 QualType ToPointeeType; 2490 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2491 ToPointeeType = ToCPtr->getPointeeType(); 2492 else if (const BlockPointerType *ToBlockPtr = 2493 ToType->getAs<BlockPointerType>()) { 2494 // Objective C++: We're able to convert from a pointer to any object 2495 // to a block pointer type. 2496 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2497 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2498 return true; 2499 } 2500 ToPointeeType = ToBlockPtr->getPointeeType(); 2501 } 2502 else if (FromType->getAs<BlockPointerType>() && 2503 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2504 // Objective C++: We're able to convert from a block pointer type to a 2505 // pointer to any object. 2506 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2507 return true; 2508 } 2509 else 2510 return false; 2511 2512 QualType FromPointeeType; 2513 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2514 FromPointeeType = FromCPtr->getPointeeType(); 2515 else if (const BlockPointerType *FromBlockPtr = 2516 FromType->getAs<BlockPointerType>()) 2517 FromPointeeType = FromBlockPtr->getPointeeType(); 2518 else 2519 return false; 2520 2521 // If we have pointers to pointers, recursively check whether this 2522 // is an Objective-C conversion. 2523 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2524 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2525 IncompatibleObjC)) { 2526 // We always complain about this conversion. 2527 IncompatibleObjC = true; 2528 ConvertedType = Context.getPointerType(ConvertedType); 2529 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2530 return true; 2531 } 2532 // Allow conversion of pointee being objective-c pointer to another one; 2533 // as in I* to id. 2534 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2535 ToPointeeType->getAs<ObjCObjectPointerType>() && 2536 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2537 IncompatibleObjC)) { 2538 2539 ConvertedType = Context.getPointerType(ConvertedType); 2540 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2541 return true; 2542 } 2543 2544 // If we have pointers to functions or blocks, check whether the only 2545 // differences in the argument and result types are in Objective-C 2546 // pointer conversions. If so, we permit the conversion (but 2547 // complain about it). 2548 const FunctionProtoType *FromFunctionType 2549 = FromPointeeType->getAs<FunctionProtoType>(); 2550 const FunctionProtoType *ToFunctionType 2551 = ToPointeeType->getAs<FunctionProtoType>(); 2552 if (FromFunctionType && ToFunctionType) { 2553 // If the function types are exactly the same, this isn't an 2554 // Objective-C pointer conversion. 2555 if (Context.getCanonicalType(FromPointeeType) 2556 == Context.getCanonicalType(ToPointeeType)) 2557 return false; 2558 2559 // Perform the quick checks that will tell us whether these 2560 // function types are obviously different. 2561 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2562 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2563 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2564 return false; 2565 2566 bool HasObjCConversion = false; 2567 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2568 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2569 // Okay, the types match exactly. Nothing to do. 2570 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2571 ToFunctionType->getReturnType(), 2572 ConvertedType, IncompatibleObjC)) { 2573 // Okay, we have an Objective-C pointer conversion. 2574 HasObjCConversion = true; 2575 } else { 2576 // Function types are too different. Abort. 2577 return false; 2578 } 2579 2580 // Check argument types. 2581 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2582 ArgIdx != NumArgs; ++ArgIdx) { 2583 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2584 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2585 if (Context.getCanonicalType(FromArgType) 2586 == Context.getCanonicalType(ToArgType)) { 2587 // Okay, the types match exactly. Nothing to do. 2588 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2589 ConvertedType, IncompatibleObjC)) { 2590 // Okay, we have an Objective-C pointer conversion. 2591 HasObjCConversion = true; 2592 } else { 2593 // Argument types are too different. Abort. 2594 return false; 2595 } 2596 } 2597 2598 if (HasObjCConversion) { 2599 // We had an Objective-C conversion. Allow this pointer 2600 // conversion, but complain about it. 2601 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2602 IncompatibleObjC = true; 2603 return true; 2604 } 2605 } 2606 2607 return false; 2608 } 2609 2610 /// Determine whether this is an Objective-C writeback conversion, 2611 /// used for parameter passing when performing automatic reference counting. 2612 /// 2613 /// \param FromType The type we're converting form. 2614 /// 2615 /// \param ToType The type we're converting to. 2616 /// 2617 /// \param ConvertedType The type that will be produced after applying 2618 /// this conversion. 2619 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2620 QualType &ConvertedType) { 2621 if (!getLangOpts().ObjCAutoRefCount || 2622 Context.hasSameUnqualifiedType(FromType, ToType)) 2623 return false; 2624 2625 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2626 QualType ToPointee; 2627 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2628 ToPointee = ToPointer->getPointeeType(); 2629 else 2630 return false; 2631 2632 Qualifiers ToQuals = ToPointee.getQualifiers(); 2633 if (!ToPointee->isObjCLifetimeType() || 2634 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2635 !ToQuals.withoutObjCLifetime().empty()) 2636 return false; 2637 2638 // Argument must be a pointer to __strong to __weak. 2639 QualType FromPointee; 2640 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2641 FromPointee = FromPointer->getPointeeType(); 2642 else 2643 return false; 2644 2645 Qualifiers FromQuals = FromPointee.getQualifiers(); 2646 if (!FromPointee->isObjCLifetimeType() || 2647 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2648 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2649 return false; 2650 2651 // Make sure that we have compatible qualifiers. 2652 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2653 if (!ToQuals.compatiblyIncludes(FromQuals)) 2654 return false; 2655 2656 // Remove qualifiers from the pointee type we're converting from; they 2657 // aren't used in the compatibility check belong, and we'll be adding back 2658 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2659 FromPointee = FromPointee.getUnqualifiedType(); 2660 2661 // The unqualified form of the pointee types must be compatible. 2662 ToPointee = ToPointee.getUnqualifiedType(); 2663 bool IncompatibleObjC; 2664 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2665 FromPointee = ToPointee; 2666 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2667 IncompatibleObjC)) 2668 return false; 2669 2670 /// Construct the type we're converting to, which is a pointer to 2671 /// __autoreleasing pointee. 2672 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2673 ConvertedType = Context.getPointerType(FromPointee); 2674 return true; 2675 } 2676 2677 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2678 QualType& ConvertedType) { 2679 QualType ToPointeeType; 2680 if (const BlockPointerType *ToBlockPtr = 2681 ToType->getAs<BlockPointerType>()) 2682 ToPointeeType = ToBlockPtr->getPointeeType(); 2683 else 2684 return false; 2685 2686 QualType FromPointeeType; 2687 if (const BlockPointerType *FromBlockPtr = 2688 FromType->getAs<BlockPointerType>()) 2689 FromPointeeType = FromBlockPtr->getPointeeType(); 2690 else 2691 return false; 2692 // We have pointer to blocks, check whether the only 2693 // differences in the argument and result types are in Objective-C 2694 // pointer conversions. If so, we permit the conversion. 2695 2696 const FunctionProtoType *FromFunctionType 2697 = FromPointeeType->getAs<FunctionProtoType>(); 2698 const FunctionProtoType *ToFunctionType 2699 = ToPointeeType->getAs<FunctionProtoType>(); 2700 2701 if (!FromFunctionType || !ToFunctionType) 2702 return false; 2703 2704 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2705 return true; 2706 2707 // Perform the quick checks that will tell us whether these 2708 // function types are obviously different. 2709 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2710 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2711 return false; 2712 2713 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2714 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2715 if (FromEInfo != ToEInfo) 2716 return false; 2717 2718 bool IncompatibleObjC = false; 2719 if (Context.hasSameType(FromFunctionType->getReturnType(), 2720 ToFunctionType->getReturnType())) { 2721 // Okay, the types match exactly. Nothing to do. 2722 } else { 2723 QualType RHS = FromFunctionType->getReturnType(); 2724 QualType LHS = ToFunctionType->getReturnType(); 2725 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2726 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2727 LHS = LHS.getUnqualifiedType(); 2728 2729 if (Context.hasSameType(RHS,LHS)) { 2730 // OK exact match. 2731 } else if (isObjCPointerConversion(RHS, LHS, 2732 ConvertedType, IncompatibleObjC)) { 2733 if (IncompatibleObjC) 2734 return false; 2735 // Okay, we have an Objective-C pointer conversion. 2736 } 2737 else 2738 return false; 2739 } 2740 2741 // Check argument types. 2742 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2743 ArgIdx != NumArgs; ++ArgIdx) { 2744 IncompatibleObjC = false; 2745 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2746 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2747 if (Context.hasSameType(FromArgType, ToArgType)) { 2748 // Okay, the types match exactly. Nothing to do. 2749 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2750 ConvertedType, IncompatibleObjC)) { 2751 if (IncompatibleObjC) 2752 return false; 2753 // Okay, we have an Objective-C pointer conversion. 2754 } else 2755 // Argument types are too different. Abort. 2756 return false; 2757 } 2758 2759 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2760 bool CanUseToFPT, CanUseFromFPT; 2761 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2762 CanUseToFPT, CanUseFromFPT, 2763 NewParamInfos)) 2764 return false; 2765 2766 ConvertedType = ToType; 2767 return true; 2768 } 2769 2770 enum { 2771 ft_default, 2772 ft_different_class, 2773 ft_parameter_arity, 2774 ft_parameter_mismatch, 2775 ft_return_type, 2776 ft_qualifer_mismatch, 2777 ft_noexcept 2778 }; 2779 2780 /// Attempts to get the FunctionProtoType from a Type. Handles 2781 /// MemberFunctionPointers properly. 2782 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2783 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2784 return FPT; 2785 2786 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2787 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2788 2789 return nullptr; 2790 } 2791 2792 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2793 /// function types. Catches different number of parameter, mismatch in 2794 /// parameter types, and different return types. 2795 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2796 QualType FromType, QualType ToType) { 2797 // If either type is not valid, include no extra info. 2798 if (FromType.isNull() || ToType.isNull()) { 2799 PDiag << ft_default; 2800 return; 2801 } 2802 2803 // Get the function type from the pointers. 2804 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2805 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2806 *ToMember = ToType->getAs<MemberPointerType>(); 2807 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2808 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2809 << QualType(FromMember->getClass(), 0); 2810 return; 2811 } 2812 FromType = FromMember->getPointeeType(); 2813 ToType = ToMember->getPointeeType(); 2814 } 2815 2816 if (FromType->isPointerType()) 2817 FromType = FromType->getPointeeType(); 2818 if (ToType->isPointerType()) 2819 ToType = ToType->getPointeeType(); 2820 2821 // Remove references. 2822 FromType = FromType.getNonReferenceType(); 2823 ToType = ToType.getNonReferenceType(); 2824 2825 // Don't print extra info for non-specialized template functions. 2826 if (FromType->isInstantiationDependentType() && 2827 !FromType->getAs<TemplateSpecializationType>()) { 2828 PDiag << ft_default; 2829 return; 2830 } 2831 2832 // No extra info for same types. 2833 if (Context.hasSameType(FromType, ToType)) { 2834 PDiag << ft_default; 2835 return; 2836 } 2837 2838 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2839 *ToFunction = tryGetFunctionProtoType(ToType); 2840 2841 // Both types need to be function types. 2842 if (!FromFunction || !ToFunction) { 2843 PDiag << ft_default; 2844 return; 2845 } 2846 2847 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2848 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2849 << FromFunction->getNumParams(); 2850 return; 2851 } 2852 2853 // Handle different parameter types. 2854 unsigned ArgPos; 2855 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2856 PDiag << ft_parameter_mismatch << ArgPos + 1 2857 << ToFunction->getParamType(ArgPos) 2858 << FromFunction->getParamType(ArgPos); 2859 return; 2860 } 2861 2862 // Handle different return type. 2863 if (!Context.hasSameType(FromFunction->getReturnType(), 2864 ToFunction->getReturnType())) { 2865 PDiag << ft_return_type << ToFunction->getReturnType() 2866 << FromFunction->getReturnType(); 2867 return; 2868 } 2869 2870 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2871 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2872 << FromFunction->getMethodQuals(); 2873 return; 2874 } 2875 2876 // Handle exception specification differences on canonical type (in C++17 2877 // onwards). 2878 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2879 ->isNothrow() != 2880 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2881 ->isNothrow()) { 2882 PDiag << ft_noexcept; 2883 return; 2884 } 2885 2886 // Unable to find a difference, so add no extra info. 2887 PDiag << ft_default; 2888 } 2889 2890 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2891 /// for equality of their argument types. Caller has already checked that 2892 /// they have same number of arguments. If the parameters are different, 2893 /// ArgPos will have the parameter index of the first different parameter. 2894 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2895 const FunctionProtoType *NewType, 2896 unsigned *ArgPos) { 2897 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2898 N = NewType->param_type_begin(), 2899 E = OldType->param_type_end(); 2900 O && (O != E); ++O, ++N) { 2901 if (!Context.hasSameType(O->getUnqualifiedType(), 2902 N->getUnqualifiedType())) { 2903 if (ArgPos) 2904 *ArgPos = O - OldType->param_type_begin(); 2905 return false; 2906 } 2907 } 2908 return true; 2909 } 2910 2911 /// CheckPointerConversion - Check the pointer conversion from the 2912 /// expression From to the type ToType. This routine checks for 2913 /// ambiguous or inaccessible derived-to-base pointer 2914 /// conversions for which IsPointerConversion has already returned 2915 /// true. It returns true and produces a diagnostic if there was an 2916 /// error, or returns false otherwise. 2917 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2918 CastKind &Kind, 2919 CXXCastPath& BasePath, 2920 bool IgnoreBaseAccess, 2921 bool Diagnose) { 2922 QualType FromType = From->getType(); 2923 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2924 2925 Kind = CK_BitCast; 2926 2927 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2928 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2929 Expr::NPCK_ZeroExpression) { 2930 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2931 DiagRuntimeBehavior(From->getExprLoc(), From, 2932 PDiag(diag::warn_impcast_bool_to_null_pointer) 2933 << ToType << From->getSourceRange()); 2934 else if (!isUnevaluatedContext()) 2935 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2936 << ToType << From->getSourceRange(); 2937 } 2938 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2939 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2940 QualType FromPointeeType = FromPtrType->getPointeeType(), 2941 ToPointeeType = ToPtrType->getPointeeType(); 2942 2943 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2944 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2945 // We must have a derived-to-base conversion. Check an 2946 // ambiguous or inaccessible conversion. 2947 unsigned InaccessibleID = 0; 2948 unsigned AmbigiousID = 0; 2949 if (Diagnose) { 2950 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2951 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2952 } 2953 if (CheckDerivedToBaseConversion( 2954 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2955 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2956 &BasePath, IgnoreBaseAccess)) 2957 return true; 2958 2959 // The conversion was successful. 2960 Kind = CK_DerivedToBase; 2961 } 2962 2963 if (Diagnose && !IsCStyleOrFunctionalCast && 2964 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2965 assert(getLangOpts().MSVCCompat && 2966 "this should only be possible with MSVCCompat!"); 2967 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2968 << From->getSourceRange(); 2969 } 2970 } 2971 } else if (const ObjCObjectPointerType *ToPtrType = 2972 ToType->getAs<ObjCObjectPointerType>()) { 2973 if (const ObjCObjectPointerType *FromPtrType = 2974 FromType->getAs<ObjCObjectPointerType>()) { 2975 // Objective-C++ conversions are always okay. 2976 // FIXME: We should have a different class of conversions for the 2977 // Objective-C++ implicit conversions. 2978 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2979 return false; 2980 } else if (FromType->isBlockPointerType()) { 2981 Kind = CK_BlockPointerToObjCPointerCast; 2982 } else { 2983 Kind = CK_CPointerToObjCPointerCast; 2984 } 2985 } else if (ToType->isBlockPointerType()) { 2986 if (!FromType->isBlockPointerType()) 2987 Kind = CK_AnyPointerToBlockPointerCast; 2988 } 2989 2990 // We shouldn't fall into this case unless it's valid for other 2991 // reasons. 2992 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2993 Kind = CK_NullToPointer; 2994 2995 return false; 2996 } 2997 2998 /// IsMemberPointerConversion - Determines whether the conversion of the 2999 /// expression From, which has the (possibly adjusted) type FromType, can be 3000 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3001 /// If so, returns true and places the converted type (that might differ from 3002 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3003 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3004 QualType ToType, 3005 bool InOverloadResolution, 3006 QualType &ConvertedType) { 3007 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3008 if (!ToTypePtr) 3009 return false; 3010 3011 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3012 if (From->isNullPointerConstant(Context, 3013 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3014 : Expr::NPC_ValueDependentIsNull)) { 3015 ConvertedType = ToType; 3016 return true; 3017 } 3018 3019 // Otherwise, both types have to be member pointers. 3020 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3021 if (!FromTypePtr) 3022 return false; 3023 3024 // A pointer to member of B can be converted to a pointer to member of D, 3025 // where D is derived from B (C++ 4.11p2). 3026 QualType FromClass(FromTypePtr->getClass(), 0); 3027 QualType ToClass(ToTypePtr->getClass(), 0); 3028 3029 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3030 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3031 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3032 ToClass.getTypePtr()); 3033 return true; 3034 } 3035 3036 return false; 3037 } 3038 3039 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3040 /// expression From to the type ToType. This routine checks for ambiguous or 3041 /// virtual or inaccessible base-to-derived member pointer conversions 3042 /// for which IsMemberPointerConversion has already returned true. It returns 3043 /// true and produces a diagnostic if there was an error, or returns false 3044 /// otherwise. 3045 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3046 CastKind &Kind, 3047 CXXCastPath &BasePath, 3048 bool IgnoreBaseAccess) { 3049 QualType FromType = From->getType(); 3050 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3051 if (!FromPtrType) { 3052 // This must be a null pointer to member pointer conversion 3053 assert(From->isNullPointerConstant(Context, 3054 Expr::NPC_ValueDependentIsNull) && 3055 "Expr must be null pointer constant!"); 3056 Kind = CK_NullToMemberPointer; 3057 return false; 3058 } 3059 3060 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3061 assert(ToPtrType && "No member pointer cast has a target type " 3062 "that is not a member pointer."); 3063 3064 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3065 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3066 3067 // FIXME: What about dependent types? 3068 assert(FromClass->isRecordType() && "Pointer into non-class."); 3069 assert(ToClass->isRecordType() && "Pointer into non-class."); 3070 3071 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3072 /*DetectVirtual=*/true); 3073 bool DerivationOkay = 3074 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3075 assert(DerivationOkay && 3076 "Should not have been called if derivation isn't OK."); 3077 (void)DerivationOkay; 3078 3079 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3080 getUnqualifiedType())) { 3081 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3082 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3083 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3084 return true; 3085 } 3086 3087 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3088 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3089 << FromClass << ToClass << QualType(VBase, 0) 3090 << From->getSourceRange(); 3091 return true; 3092 } 3093 3094 if (!IgnoreBaseAccess) 3095 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3096 Paths.front(), 3097 diag::err_downcast_from_inaccessible_base); 3098 3099 // Must be a base to derived member conversion. 3100 BuildBasePathArray(Paths, BasePath); 3101 Kind = CK_BaseToDerivedMemberPointer; 3102 return false; 3103 } 3104 3105 /// Determine whether the lifetime conversion between the two given 3106 /// qualifiers sets is nontrivial. 3107 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3108 Qualifiers ToQuals) { 3109 // Converting anything to const __unsafe_unretained is trivial. 3110 if (ToQuals.hasConst() && 3111 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3112 return false; 3113 3114 return true; 3115 } 3116 3117 /// IsQualificationConversion - Determines whether the conversion from 3118 /// an rvalue of type FromType to ToType is a qualification conversion 3119 /// (C++ 4.4). 3120 /// 3121 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3122 /// when the qualification conversion involves a change in the Objective-C 3123 /// object lifetime. 3124 bool 3125 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3126 bool CStyle, bool &ObjCLifetimeConversion) { 3127 FromType = Context.getCanonicalType(FromType); 3128 ToType = Context.getCanonicalType(ToType); 3129 ObjCLifetimeConversion = false; 3130 3131 // If FromType and ToType are the same type, this is not a 3132 // qualification conversion. 3133 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3134 return false; 3135 3136 // (C++ 4.4p4): 3137 // A conversion can add cv-qualifiers at levels other than the first 3138 // in multi-level pointers, subject to the following rules: [...] 3139 bool PreviousToQualsIncludeConst = true; 3140 bool UnwrappedAnyPointer = false; 3141 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3142 // Within each iteration of the loop, we check the qualifiers to 3143 // determine if this still looks like a qualification 3144 // conversion. Then, if all is well, we unwrap one more level of 3145 // pointers or pointers-to-members and do it all again 3146 // until there are no more pointers or pointers-to-members left to 3147 // unwrap. 3148 UnwrappedAnyPointer = true; 3149 3150 Qualifiers FromQuals = FromType.getQualifiers(); 3151 Qualifiers ToQuals = ToType.getQualifiers(); 3152 3153 // Ignore __unaligned qualifier if this type is void. 3154 if (ToType.getUnqualifiedType()->isVoidType()) 3155 FromQuals.removeUnaligned(); 3156 3157 // Objective-C ARC: 3158 // Check Objective-C lifetime conversions. 3159 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3160 UnwrappedAnyPointer) { 3161 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3162 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3163 ObjCLifetimeConversion = true; 3164 FromQuals.removeObjCLifetime(); 3165 ToQuals.removeObjCLifetime(); 3166 } else { 3167 // Qualification conversions cannot cast between different 3168 // Objective-C lifetime qualifiers. 3169 return false; 3170 } 3171 } 3172 3173 // Allow addition/removal of GC attributes but not changing GC attributes. 3174 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3175 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3176 FromQuals.removeObjCGCAttr(); 3177 ToQuals.removeObjCGCAttr(); 3178 } 3179 3180 // -- for every j > 0, if const is in cv 1,j then const is in cv 3181 // 2,j, and similarly for volatile. 3182 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3183 return false; 3184 3185 // -- if the cv 1,j and cv 2,j are different, then const is in 3186 // every cv for 0 < k < j. 3187 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3188 && !PreviousToQualsIncludeConst) 3189 return false; 3190 3191 // Keep track of whether all prior cv-qualifiers in the "to" type 3192 // include const. 3193 PreviousToQualsIncludeConst 3194 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3195 } 3196 3197 // Allows address space promotion by language rules implemented in 3198 // Type::Qualifiers::isAddressSpaceSupersetOf. 3199 Qualifiers FromQuals = FromType.getQualifiers(); 3200 Qualifiers ToQuals = ToType.getQualifiers(); 3201 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3202 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3203 return false; 3204 } 3205 3206 // We are left with FromType and ToType being the pointee types 3207 // after unwrapping the original FromType and ToType the same number 3208 // of types. If we unwrapped any pointers, and if FromType and 3209 // ToType have the same unqualified type (since we checked 3210 // qualifiers above), then this is a qualification conversion. 3211 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3212 } 3213 3214 /// - Determine whether this is a conversion from a scalar type to an 3215 /// atomic type. 3216 /// 3217 /// If successful, updates \c SCS's second and third steps in the conversion 3218 /// sequence to finish the conversion. 3219 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3220 bool InOverloadResolution, 3221 StandardConversionSequence &SCS, 3222 bool CStyle) { 3223 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3224 if (!ToAtomic) 3225 return false; 3226 3227 StandardConversionSequence InnerSCS; 3228 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3229 InOverloadResolution, InnerSCS, 3230 CStyle, /*AllowObjCWritebackConversion=*/false)) 3231 return false; 3232 3233 SCS.Second = InnerSCS.Second; 3234 SCS.setToType(1, InnerSCS.getToType(1)); 3235 SCS.Third = InnerSCS.Third; 3236 SCS.QualificationIncludesObjCLifetime 3237 = InnerSCS.QualificationIncludesObjCLifetime; 3238 SCS.setToType(2, InnerSCS.getToType(2)); 3239 return true; 3240 } 3241 3242 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3243 CXXConstructorDecl *Constructor, 3244 QualType Type) { 3245 const FunctionProtoType *CtorType = 3246 Constructor->getType()->getAs<FunctionProtoType>(); 3247 if (CtorType->getNumParams() > 0) { 3248 QualType FirstArg = CtorType->getParamType(0); 3249 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3250 return true; 3251 } 3252 return false; 3253 } 3254 3255 static OverloadingResult 3256 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3257 CXXRecordDecl *To, 3258 UserDefinedConversionSequence &User, 3259 OverloadCandidateSet &CandidateSet, 3260 bool AllowExplicit) { 3261 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3262 for (auto *D : S.LookupConstructors(To)) { 3263 auto Info = getConstructorInfo(D); 3264 if (!Info) 3265 continue; 3266 3267 bool Usable = !Info.Constructor->isInvalidDecl() && 3268 S.isInitListConstructor(Info.Constructor) && 3269 (AllowExplicit || !Info.Constructor->isExplicit()); 3270 if (Usable) { 3271 // If the first argument is (a reference to) the target type, 3272 // suppress conversions. 3273 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3274 S.Context, Info.Constructor, ToType); 3275 if (Info.ConstructorTmpl) 3276 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3277 /*ExplicitArgs*/ nullptr, From, 3278 CandidateSet, SuppressUserConversions, 3279 /*PartialOverloading*/ false, 3280 AllowExplicit); 3281 else 3282 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3283 CandidateSet, SuppressUserConversions, 3284 /*PartialOverloading*/ false, AllowExplicit); 3285 } 3286 } 3287 3288 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3289 3290 OverloadCandidateSet::iterator Best; 3291 switch (auto Result = 3292 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3293 case OR_Deleted: 3294 case OR_Success: { 3295 // Record the standard conversion we used and the conversion function. 3296 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3297 QualType ThisType = Constructor->getThisType(); 3298 // Initializer lists don't have conversions as such. 3299 User.Before.setAsIdentityConversion(); 3300 User.HadMultipleCandidates = HadMultipleCandidates; 3301 User.ConversionFunction = Constructor; 3302 User.FoundConversionFunction = Best->FoundDecl; 3303 User.After.setAsIdentityConversion(); 3304 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3305 User.After.setAllToTypes(ToType); 3306 return Result; 3307 } 3308 3309 case OR_No_Viable_Function: 3310 return OR_No_Viable_Function; 3311 case OR_Ambiguous: 3312 return OR_Ambiguous; 3313 } 3314 3315 llvm_unreachable("Invalid OverloadResult!"); 3316 } 3317 3318 /// Determines whether there is a user-defined conversion sequence 3319 /// (C++ [over.ics.user]) that converts expression From to the type 3320 /// ToType. If such a conversion exists, User will contain the 3321 /// user-defined conversion sequence that performs such a conversion 3322 /// and this routine will return true. Otherwise, this routine returns 3323 /// false and User is unspecified. 3324 /// 3325 /// \param AllowExplicit true if the conversion should consider C++0x 3326 /// "explicit" conversion functions as well as non-explicit conversion 3327 /// functions (C++0x [class.conv.fct]p2). 3328 /// 3329 /// \param AllowObjCConversionOnExplicit true if the conversion should 3330 /// allow an extra Objective-C pointer conversion on uses of explicit 3331 /// constructors. Requires \c AllowExplicit to also be set. 3332 static OverloadingResult 3333 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3334 UserDefinedConversionSequence &User, 3335 OverloadCandidateSet &CandidateSet, 3336 bool AllowExplicit, 3337 bool AllowObjCConversionOnExplicit) { 3338 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3339 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3340 3341 // Whether we will only visit constructors. 3342 bool ConstructorsOnly = false; 3343 3344 // If the type we are conversion to is a class type, enumerate its 3345 // constructors. 3346 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3347 // C++ [over.match.ctor]p1: 3348 // When objects of class type are direct-initialized (8.5), or 3349 // copy-initialized from an expression of the same or a 3350 // derived class type (8.5), overload resolution selects the 3351 // constructor. [...] For copy-initialization, the candidate 3352 // functions are all the converting constructors (12.3.1) of 3353 // that class. The argument list is the expression-list within 3354 // the parentheses of the initializer. 3355 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3356 (From->getType()->getAs<RecordType>() && 3357 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3358 ConstructorsOnly = true; 3359 3360 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3361 // We're not going to find any constructors. 3362 } else if (CXXRecordDecl *ToRecordDecl 3363 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3364 3365 Expr **Args = &From; 3366 unsigned NumArgs = 1; 3367 bool ListInitializing = false; 3368 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3369 // But first, see if there is an init-list-constructor that will work. 3370 OverloadingResult Result = IsInitializerListConstructorConversion( 3371 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3372 if (Result != OR_No_Viable_Function) 3373 return Result; 3374 // Never mind. 3375 CandidateSet.clear( 3376 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3377 3378 // If we're list-initializing, we pass the individual elements as 3379 // arguments, not the entire list. 3380 Args = InitList->getInits(); 3381 NumArgs = InitList->getNumInits(); 3382 ListInitializing = true; 3383 } 3384 3385 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3386 auto Info = getConstructorInfo(D); 3387 if (!Info) 3388 continue; 3389 3390 bool Usable = !Info.Constructor->isInvalidDecl(); 3391 if (ListInitializing) 3392 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3393 else 3394 Usable = Usable && 3395 Info.Constructor->isConvertingConstructor(AllowExplicit); 3396 if (Usable) { 3397 bool SuppressUserConversions = !ConstructorsOnly; 3398 if (SuppressUserConversions && ListInitializing) { 3399 SuppressUserConversions = false; 3400 if (NumArgs == 1) { 3401 // If the first argument is (a reference to) the target type, 3402 // suppress conversions. 3403 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3404 S.Context, Info.Constructor, ToType); 3405 } 3406 } 3407 if (Info.ConstructorTmpl) 3408 S.AddTemplateOverloadCandidate( 3409 Info.ConstructorTmpl, Info.FoundDecl, 3410 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3411 CandidateSet, SuppressUserConversions, 3412 /*PartialOverloading*/ false, AllowExplicit); 3413 else 3414 // Allow one user-defined conversion when user specifies a 3415 // From->ToType conversion via an static cast (c-style, etc). 3416 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3417 llvm::makeArrayRef(Args, NumArgs), 3418 CandidateSet, SuppressUserConversions, 3419 /*PartialOverloading*/ false, AllowExplicit); 3420 } 3421 } 3422 } 3423 } 3424 3425 // Enumerate conversion functions, if we're allowed to. 3426 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3427 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3428 // No conversion functions from incomplete types. 3429 } else if (const RecordType *FromRecordType = 3430 From->getType()->getAs<RecordType>()) { 3431 if (CXXRecordDecl *FromRecordDecl 3432 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3433 // Add all of the conversion functions as candidates. 3434 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3435 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3436 DeclAccessPair FoundDecl = I.getPair(); 3437 NamedDecl *D = FoundDecl.getDecl(); 3438 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3439 if (isa<UsingShadowDecl>(D)) 3440 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3441 3442 CXXConversionDecl *Conv; 3443 FunctionTemplateDecl *ConvTemplate; 3444 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3445 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3446 else 3447 Conv = cast<CXXConversionDecl>(D); 3448 3449 if (AllowExplicit || !Conv->isExplicit()) { 3450 if (ConvTemplate) 3451 S.AddTemplateConversionCandidate( 3452 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3453 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit); 3454 else 3455 S.AddConversionCandidate( 3456 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet, 3457 AllowObjCConversionOnExplicit, AllowExplicit); 3458 } 3459 } 3460 } 3461 } 3462 3463 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3464 3465 OverloadCandidateSet::iterator Best; 3466 switch (auto Result = 3467 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3468 case OR_Success: 3469 case OR_Deleted: 3470 // Record the standard conversion we used and the conversion function. 3471 if (CXXConstructorDecl *Constructor 3472 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3473 // C++ [over.ics.user]p1: 3474 // If the user-defined conversion is specified by a 3475 // constructor (12.3.1), the initial standard conversion 3476 // sequence converts the source type to the type required by 3477 // the argument of the constructor. 3478 // 3479 QualType ThisType = Constructor->getThisType(); 3480 if (isa<InitListExpr>(From)) { 3481 // Initializer lists don't have conversions as such. 3482 User.Before.setAsIdentityConversion(); 3483 } else { 3484 if (Best->Conversions[0].isEllipsis()) 3485 User.EllipsisConversion = true; 3486 else { 3487 User.Before = Best->Conversions[0].Standard; 3488 User.EllipsisConversion = false; 3489 } 3490 } 3491 User.HadMultipleCandidates = HadMultipleCandidates; 3492 User.ConversionFunction = Constructor; 3493 User.FoundConversionFunction = Best->FoundDecl; 3494 User.After.setAsIdentityConversion(); 3495 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3496 User.After.setAllToTypes(ToType); 3497 return Result; 3498 } 3499 if (CXXConversionDecl *Conversion 3500 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3501 // C++ [over.ics.user]p1: 3502 // 3503 // [...] If the user-defined conversion is specified by a 3504 // conversion function (12.3.2), the initial standard 3505 // conversion sequence converts the source type to the 3506 // implicit object parameter of the conversion function. 3507 User.Before = Best->Conversions[0].Standard; 3508 User.HadMultipleCandidates = HadMultipleCandidates; 3509 User.ConversionFunction = Conversion; 3510 User.FoundConversionFunction = Best->FoundDecl; 3511 User.EllipsisConversion = false; 3512 3513 // C++ [over.ics.user]p2: 3514 // The second standard conversion sequence converts the 3515 // result of the user-defined conversion to the target type 3516 // for the sequence. Since an implicit conversion sequence 3517 // is an initialization, the special rules for 3518 // initialization by user-defined conversion apply when 3519 // selecting the best user-defined conversion for a 3520 // user-defined conversion sequence (see 13.3.3 and 3521 // 13.3.3.1). 3522 User.After = Best->FinalConversion; 3523 return Result; 3524 } 3525 llvm_unreachable("Not a constructor or conversion function?"); 3526 3527 case OR_No_Viable_Function: 3528 return OR_No_Viable_Function; 3529 3530 case OR_Ambiguous: 3531 return OR_Ambiguous; 3532 } 3533 3534 llvm_unreachable("Invalid OverloadResult!"); 3535 } 3536 3537 bool 3538 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3539 ImplicitConversionSequence ICS; 3540 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3541 OverloadCandidateSet::CSK_Normal); 3542 OverloadingResult OvResult = 3543 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3544 CandidateSet, false, false); 3545 3546 if (!(OvResult == OR_Ambiguous || 3547 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3548 return false; 3549 3550 auto Cands = CandidateSet.CompleteCandidates( 3551 *this, 3552 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3553 From); 3554 if (OvResult == OR_Ambiguous) 3555 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3556 << From->getType() << ToType << From->getSourceRange(); 3557 else { // OR_No_Viable_Function && !CandidateSet.empty() 3558 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3559 diag::err_typecheck_nonviable_condition_incomplete, 3560 From->getType(), From->getSourceRange())) 3561 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3562 << false << From->getType() << From->getSourceRange() << ToType; 3563 } 3564 3565 CandidateSet.NoteCandidates( 3566 *this, From, Cands); 3567 return true; 3568 } 3569 3570 /// Compare the user-defined conversion functions or constructors 3571 /// of two user-defined conversion sequences to determine whether any ordering 3572 /// is possible. 3573 static ImplicitConversionSequence::CompareKind 3574 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3575 FunctionDecl *Function2) { 3576 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3577 return ImplicitConversionSequence::Indistinguishable; 3578 3579 // Objective-C++: 3580 // If both conversion functions are implicitly-declared conversions from 3581 // a lambda closure type to a function pointer and a block pointer, 3582 // respectively, always prefer the conversion to a function pointer, 3583 // because the function pointer is more lightweight and is more likely 3584 // to keep code working. 3585 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3586 if (!Conv1) 3587 return ImplicitConversionSequence::Indistinguishable; 3588 3589 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3590 if (!Conv2) 3591 return ImplicitConversionSequence::Indistinguishable; 3592 3593 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3594 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3595 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3596 if (Block1 != Block2) 3597 return Block1 ? ImplicitConversionSequence::Worse 3598 : ImplicitConversionSequence::Better; 3599 } 3600 3601 return ImplicitConversionSequence::Indistinguishable; 3602 } 3603 3604 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3605 const ImplicitConversionSequence &ICS) { 3606 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3607 (ICS.isUserDefined() && 3608 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3609 } 3610 3611 /// CompareImplicitConversionSequences - Compare two implicit 3612 /// conversion sequences to determine whether one is better than the 3613 /// other or if they are indistinguishable (C++ 13.3.3.2). 3614 static ImplicitConversionSequence::CompareKind 3615 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3616 const ImplicitConversionSequence& ICS1, 3617 const ImplicitConversionSequence& ICS2) 3618 { 3619 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3620 // conversion sequences (as defined in 13.3.3.1) 3621 // -- a standard conversion sequence (13.3.3.1.1) is a better 3622 // conversion sequence than a user-defined conversion sequence or 3623 // an ellipsis conversion sequence, and 3624 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3625 // conversion sequence than an ellipsis conversion sequence 3626 // (13.3.3.1.3). 3627 // 3628 // C++0x [over.best.ics]p10: 3629 // For the purpose of ranking implicit conversion sequences as 3630 // described in 13.3.3.2, the ambiguous conversion sequence is 3631 // treated as a user-defined sequence that is indistinguishable 3632 // from any other user-defined conversion sequence. 3633 3634 // String literal to 'char *' conversion has been deprecated in C++03. It has 3635 // been removed from C++11. We still accept this conversion, if it happens at 3636 // the best viable function. Otherwise, this conversion is considered worse 3637 // than ellipsis conversion. Consider this as an extension; this is not in the 3638 // standard. For example: 3639 // 3640 // int &f(...); // #1 3641 // void f(char*); // #2 3642 // void g() { int &r = f("foo"); } 3643 // 3644 // In C++03, we pick #2 as the best viable function. 3645 // In C++11, we pick #1 as the best viable function, because ellipsis 3646 // conversion is better than string-literal to char* conversion (since there 3647 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3648 // convert arguments, #2 would be the best viable function in C++11. 3649 // If the best viable function has this conversion, a warning will be issued 3650 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3651 3652 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3653 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3654 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3655 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3656 ? ImplicitConversionSequence::Worse 3657 : ImplicitConversionSequence::Better; 3658 3659 if (ICS1.getKindRank() < ICS2.getKindRank()) 3660 return ImplicitConversionSequence::Better; 3661 if (ICS2.getKindRank() < ICS1.getKindRank()) 3662 return ImplicitConversionSequence::Worse; 3663 3664 // The following checks require both conversion sequences to be of 3665 // the same kind. 3666 if (ICS1.getKind() != ICS2.getKind()) 3667 return ImplicitConversionSequence::Indistinguishable; 3668 3669 ImplicitConversionSequence::CompareKind Result = 3670 ImplicitConversionSequence::Indistinguishable; 3671 3672 // Two implicit conversion sequences of the same form are 3673 // indistinguishable conversion sequences unless one of the 3674 // following rules apply: (C++ 13.3.3.2p3): 3675 3676 // List-initialization sequence L1 is a better conversion sequence than 3677 // list-initialization sequence L2 if: 3678 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3679 // if not that, 3680 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3681 // and N1 is smaller than N2., 3682 // even if one of the other rules in this paragraph would otherwise apply. 3683 if (!ICS1.isBad()) { 3684 if (ICS1.isStdInitializerListElement() && 3685 !ICS2.isStdInitializerListElement()) 3686 return ImplicitConversionSequence::Better; 3687 if (!ICS1.isStdInitializerListElement() && 3688 ICS2.isStdInitializerListElement()) 3689 return ImplicitConversionSequence::Worse; 3690 } 3691 3692 if (ICS1.isStandard()) 3693 // Standard conversion sequence S1 is a better conversion sequence than 3694 // standard conversion sequence S2 if [...] 3695 Result = CompareStandardConversionSequences(S, Loc, 3696 ICS1.Standard, ICS2.Standard); 3697 else if (ICS1.isUserDefined()) { 3698 // User-defined conversion sequence U1 is a better conversion 3699 // sequence than another user-defined conversion sequence U2 if 3700 // they contain the same user-defined conversion function or 3701 // constructor and if the second standard conversion sequence of 3702 // U1 is better than the second standard conversion sequence of 3703 // U2 (C++ 13.3.3.2p3). 3704 if (ICS1.UserDefined.ConversionFunction == 3705 ICS2.UserDefined.ConversionFunction) 3706 Result = CompareStandardConversionSequences(S, Loc, 3707 ICS1.UserDefined.After, 3708 ICS2.UserDefined.After); 3709 else 3710 Result = compareConversionFunctions(S, 3711 ICS1.UserDefined.ConversionFunction, 3712 ICS2.UserDefined.ConversionFunction); 3713 } 3714 3715 return Result; 3716 } 3717 3718 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3719 // determine if one is a proper subset of the other. 3720 static ImplicitConversionSequence::CompareKind 3721 compareStandardConversionSubsets(ASTContext &Context, 3722 const StandardConversionSequence& SCS1, 3723 const StandardConversionSequence& SCS2) { 3724 ImplicitConversionSequence::CompareKind Result 3725 = ImplicitConversionSequence::Indistinguishable; 3726 3727 // the identity conversion sequence is considered to be a subsequence of 3728 // any non-identity conversion sequence 3729 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3730 return ImplicitConversionSequence::Better; 3731 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3732 return ImplicitConversionSequence::Worse; 3733 3734 if (SCS1.Second != SCS2.Second) { 3735 if (SCS1.Second == ICK_Identity) 3736 Result = ImplicitConversionSequence::Better; 3737 else if (SCS2.Second == ICK_Identity) 3738 Result = ImplicitConversionSequence::Worse; 3739 else 3740 return ImplicitConversionSequence::Indistinguishable; 3741 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3742 return ImplicitConversionSequence::Indistinguishable; 3743 3744 if (SCS1.Third == SCS2.Third) { 3745 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3746 : ImplicitConversionSequence::Indistinguishable; 3747 } 3748 3749 if (SCS1.Third == ICK_Identity) 3750 return Result == ImplicitConversionSequence::Worse 3751 ? ImplicitConversionSequence::Indistinguishable 3752 : ImplicitConversionSequence::Better; 3753 3754 if (SCS2.Third == ICK_Identity) 3755 return Result == ImplicitConversionSequence::Better 3756 ? ImplicitConversionSequence::Indistinguishable 3757 : ImplicitConversionSequence::Worse; 3758 3759 return ImplicitConversionSequence::Indistinguishable; 3760 } 3761 3762 /// Determine whether one of the given reference bindings is better 3763 /// than the other based on what kind of bindings they are. 3764 static bool 3765 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3766 const StandardConversionSequence &SCS2) { 3767 // C++0x [over.ics.rank]p3b4: 3768 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3769 // implicit object parameter of a non-static member function declared 3770 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3771 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3772 // lvalue reference to a function lvalue and S2 binds an rvalue 3773 // reference*. 3774 // 3775 // FIXME: Rvalue references. We're going rogue with the above edits, 3776 // because the semantics in the current C++0x working paper (N3225 at the 3777 // time of this writing) break the standard definition of std::forward 3778 // and std::reference_wrapper when dealing with references to functions. 3779 // Proposed wording changes submitted to CWG for consideration. 3780 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3781 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3782 return false; 3783 3784 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3785 SCS2.IsLvalueReference) || 3786 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3787 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3788 } 3789 3790 enum class FixedEnumPromotion { 3791 None, 3792 ToUnderlyingType, 3793 ToPromotedUnderlyingType 3794 }; 3795 3796 /// Returns kind of fixed enum promotion the \a SCS uses. 3797 static FixedEnumPromotion 3798 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3799 3800 if (SCS.Second != ICK_Integral_Promotion) 3801 return FixedEnumPromotion::None; 3802 3803 QualType FromType = SCS.getFromType(); 3804 if (!FromType->isEnumeralType()) 3805 return FixedEnumPromotion::None; 3806 3807 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3808 if (!Enum->isFixed()) 3809 return FixedEnumPromotion::None; 3810 3811 QualType UnderlyingType = Enum->getIntegerType(); 3812 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3813 return FixedEnumPromotion::ToUnderlyingType; 3814 3815 return FixedEnumPromotion::ToPromotedUnderlyingType; 3816 } 3817 3818 /// CompareStandardConversionSequences - Compare two standard 3819 /// conversion sequences to determine whether one is better than the 3820 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3821 static ImplicitConversionSequence::CompareKind 3822 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3823 const StandardConversionSequence& SCS1, 3824 const StandardConversionSequence& SCS2) 3825 { 3826 // Standard conversion sequence S1 is a better conversion sequence 3827 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3828 3829 // -- S1 is a proper subsequence of S2 (comparing the conversion 3830 // sequences in the canonical form defined by 13.3.3.1.1, 3831 // excluding any Lvalue Transformation; the identity conversion 3832 // sequence is considered to be a subsequence of any 3833 // non-identity conversion sequence) or, if not that, 3834 if (ImplicitConversionSequence::CompareKind CK 3835 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3836 return CK; 3837 3838 // -- the rank of S1 is better than the rank of S2 (by the rules 3839 // defined below), or, if not that, 3840 ImplicitConversionRank Rank1 = SCS1.getRank(); 3841 ImplicitConversionRank Rank2 = SCS2.getRank(); 3842 if (Rank1 < Rank2) 3843 return ImplicitConversionSequence::Better; 3844 else if (Rank2 < Rank1) 3845 return ImplicitConversionSequence::Worse; 3846 3847 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3848 // are indistinguishable unless one of the following rules 3849 // applies: 3850 3851 // A conversion that is not a conversion of a pointer, or 3852 // pointer to member, to bool is better than another conversion 3853 // that is such a conversion. 3854 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3855 return SCS2.isPointerConversionToBool() 3856 ? ImplicitConversionSequence::Better 3857 : ImplicitConversionSequence::Worse; 3858 3859 // C++14 [over.ics.rank]p4b2: 3860 // This is retroactively applied to C++11 by CWG 1601. 3861 // 3862 // A conversion that promotes an enumeration whose underlying type is fixed 3863 // to its underlying type is better than one that promotes to the promoted 3864 // underlying type, if the two are different. 3865 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3866 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3867 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3868 FEP1 != FEP2) 3869 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3870 ? ImplicitConversionSequence::Better 3871 : ImplicitConversionSequence::Worse; 3872 3873 // C++ [over.ics.rank]p4b2: 3874 // 3875 // If class B is derived directly or indirectly from class A, 3876 // conversion of B* to A* is better than conversion of B* to 3877 // void*, and conversion of A* to void* is better than conversion 3878 // of B* to void*. 3879 bool SCS1ConvertsToVoid 3880 = SCS1.isPointerConversionToVoidPointer(S.Context); 3881 bool SCS2ConvertsToVoid 3882 = SCS2.isPointerConversionToVoidPointer(S.Context); 3883 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3884 // Exactly one of the conversion sequences is a conversion to 3885 // a void pointer; it's the worse conversion. 3886 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3887 : ImplicitConversionSequence::Worse; 3888 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3889 // Neither conversion sequence converts to a void pointer; compare 3890 // their derived-to-base conversions. 3891 if (ImplicitConversionSequence::CompareKind DerivedCK 3892 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3893 return DerivedCK; 3894 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3895 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3896 // Both conversion sequences are conversions to void 3897 // pointers. Compare the source types to determine if there's an 3898 // inheritance relationship in their sources. 3899 QualType FromType1 = SCS1.getFromType(); 3900 QualType FromType2 = SCS2.getFromType(); 3901 3902 // Adjust the types we're converting from via the array-to-pointer 3903 // conversion, if we need to. 3904 if (SCS1.First == ICK_Array_To_Pointer) 3905 FromType1 = S.Context.getArrayDecayedType(FromType1); 3906 if (SCS2.First == ICK_Array_To_Pointer) 3907 FromType2 = S.Context.getArrayDecayedType(FromType2); 3908 3909 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3910 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3911 3912 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3913 return ImplicitConversionSequence::Better; 3914 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3915 return ImplicitConversionSequence::Worse; 3916 3917 // Objective-C++: If one interface is more specific than the 3918 // other, it is the better one. 3919 const ObjCObjectPointerType* FromObjCPtr1 3920 = FromType1->getAs<ObjCObjectPointerType>(); 3921 const ObjCObjectPointerType* FromObjCPtr2 3922 = FromType2->getAs<ObjCObjectPointerType>(); 3923 if (FromObjCPtr1 && FromObjCPtr2) { 3924 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3925 FromObjCPtr2); 3926 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3927 FromObjCPtr1); 3928 if (AssignLeft != AssignRight) { 3929 return AssignLeft? ImplicitConversionSequence::Better 3930 : ImplicitConversionSequence::Worse; 3931 } 3932 } 3933 } 3934 3935 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3936 // bullet 3). 3937 if (ImplicitConversionSequence::CompareKind QualCK 3938 = CompareQualificationConversions(S, SCS1, SCS2)) 3939 return QualCK; 3940 3941 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3942 // Check for a better reference binding based on the kind of bindings. 3943 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3944 return ImplicitConversionSequence::Better; 3945 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3946 return ImplicitConversionSequence::Worse; 3947 3948 // C++ [over.ics.rank]p3b4: 3949 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3950 // which the references refer are the same type except for 3951 // top-level cv-qualifiers, and the type to which the reference 3952 // initialized by S2 refers is more cv-qualified than the type 3953 // to which the reference initialized by S1 refers. 3954 QualType T1 = SCS1.getToType(2); 3955 QualType T2 = SCS2.getToType(2); 3956 T1 = S.Context.getCanonicalType(T1); 3957 T2 = S.Context.getCanonicalType(T2); 3958 Qualifiers T1Quals, T2Quals; 3959 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3960 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3961 if (UnqualT1 == UnqualT2) { 3962 // Objective-C++ ARC: If the references refer to objects with different 3963 // lifetimes, prefer bindings that don't change lifetime. 3964 if (SCS1.ObjCLifetimeConversionBinding != 3965 SCS2.ObjCLifetimeConversionBinding) { 3966 return SCS1.ObjCLifetimeConversionBinding 3967 ? ImplicitConversionSequence::Worse 3968 : ImplicitConversionSequence::Better; 3969 } 3970 3971 // If the type is an array type, promote the element qualifiers to the 3972 // type for comparison. 3973 if (isa<ArrayType>(T1) && T1Quals) 3974 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3975 if (isa<ArrayType>(T2) && T2Quals) 3976 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3977 if (T2.isMoreQualifiedThan(T1)) 3978 return ImplicitConversionSequence::Better; 3979 else if (T1.isMoreQualifiedThan(T2)) 3980 return ImplicitConversionSequence::Worse; 3981 } 3982 } 3983 3984 // In Microsoft mode, prefer an integral conversion to a 3985 // floating-to-integral conversion if the integral conversion 3986 // is between types of the same size. 3987 // For example: 3988 // void f(float); 3989 // void f(int); 3990 // int main { 3991 // long a; 3992 // f(a); 3993 // } 3994 // Here, MSVC will call f(int) instead of generating a compile error 3995 // as clang will do in standard mode. 3996 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3997 SCS2.Second == ICK_Floating_Integral && 3998 S.Context.getTypeSize(SCS1.getFromType()) == 3999 S.Context.getTypeSize(SCS1.getToType(2))) 4000 return ImplicitConversionSequence::Better; 4001 4002 // Prefer a compatible vector conversion over a lax vector conversion 4003 // For example: 4004 // 4005 // typedef float __v4sf __attribute__((__vector_size__(16))); 4006 // void f(vector float); 4007 // void f(vector signed int); 4008 // int main() { 4009 // __v4sf a; 4010 // f(a); 4011 // } 4012 // Here, we'd like to choose f(vector float) and not 4013 // report an ambiguous call error 4014 if (SCS1.Second == ICK_Vector_Conversion && 4015 SCS2.Second == ICK_Vector_Conversion) { 4016 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4017 SCS1.getFromType(), SCS1.getToType(2)); 4018 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4019 SCS2.getFromType(), SCS2.getToType(2)); 4020 4021 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4022 return SCS1IsCompatibleVectorConversion 4023 ? ImplicitConversionSequence::Better 4024 : ImplicitConversionSequence::Worse; 4025 } 4026 4027 return ImplicitConversionSequence::Indistinguishable; 4028 } 4029 4030 /// CompareQualificationConversions - Compares two standard conversion 4031 /// sequences to determine whether they can be ranked based on their 4032 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4033 static ImplicitConversionSequence::CompareKind 4034 CompareQualificationConversions(Sema &S, 4035 const StandardConversionSequence& SCS1, 4036 const StandardConversionSequence& SCS2) { 4037 // C++ 13.3.3.2p3: 4038 // -- S1 and S2 differ only in their qualification conversion and 4039 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4040 // cv-qualification signature of type T1 is a proper subset of 4041 // the cv-qualification signature of type T2, and S1 is not the 4042 // deprecated string literal array-to-pointer conversion (4.2). 4043 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4044 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4045 return ImplicitConversionSequence::Indistinguishable; 4046 4047 // FIXME: the example in the standard doesn't use a qualification 4048 // conversion (!) 4049 QualType T1 = SCS1.getToType(2); 4050 QualType T2 = SCS2.getToType(2); 4051 T1 = S.Context.getCanonicalType(T1); 4052 T2 = S.Context.getCanonicalType(T2); 4053 Qualifiers T1Quals, T2Quals; 4054 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4055 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4056 4057 // If the types are the same, we won't learn anything by unwrapped 4058 // them. 4059 if (UnqualT1 == UnqualT2) 4060 return ImplicitConversionSequence::Indistinguishable; 4061 4062 // If the type is an array type, promote the element qualifiers to the type 4063 // for comparison. 4064 if (isa<ArrayType>(T1) && T1Quals) 4065 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4066 if (isa<ArrayType>(T2) && T2Quals) 4067 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4068 4069 ImplicitConversionSequence::CompareKind Result 4070 = ImplicitConversionSequence::Indistinguishable; 4071 4072 // Objective-C++ ARC: 4073 // Prefer qualification conversions not involving a change in lifetime 4074 // to qualification conversions that do not change lifetime. 4075 if (SCS1.QualificationIncludesObjCLifetime != 4076 SCS2.QualificationIncludesObjCLifetime) { 4077 Result = SCS1.QualificationIncludesObjCLifetime 4078 ? ImplicitConversionSequence::Worse 4079 : ImplicitConversionSequence::Better; 4080 } 4081 4082 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4083 // Within each iteration of the loop, we check the qualifiers to 4084 // determine if this still looks like a qualification 4085 // conversion. Then, if all is well, we unwrap one more level of 4086 // pointers or pointers-to-members and do it all again 4087 // until there are no more pointers or pointers-to-members left 4088 // to unwrap. This essentially mimics what 4089 // IsQualificationConversion does, but here we're checking for a 4090 // strict subset of qualifiers. 4091 if (T1.getQualifiers().withoutObjCLifetime() == 4092 T2.getQualifiers().withoutObjCLifetime()) 4093 // The qualifiers are the same, so this doesn't tell us anything 4094 // about how the sequences rank. 4095 // ObjC ownership quals are omitted above as they interfere with 4096 // the ARC overload rule. 4097 ; 4098 else if (T2.isMoreQualifiedThan(T1)) { 4099 // T1 has fewer qualifiers, so it could be the better sequence. 4100 if (Result == ImplicitConversionSequence::Worse) 4101 // Neither has qualifiers that are a subset of the other's 4102 // qualifiers. 4103 return ImplicitConversionSequence::Indistinguishable; 4104 4105 Result = ImplicitConversionSequence::Better; 4106 } else if (T1.isMoreQualifiedThan(T2)) { 4107 // T2 has fewer qualifiers, so it could be the better sequence. 4108 if (Result == ImplicitConversionSequence::Better) 4109 // Neither has qualifiers that are a subset of the other's 4110 // qualifiers. 4111 return ImplicitConversionSequence::Indistinguishable; 4112 4113 Result = ImplicitConversionSequence::Worse; 4114 } else { 4115 // Qualifiers are disjoint. 4116 return ImplicitConversionSequence::Indistinguishable; 4117 } 4118 4119 // If the types after this point are equivalent, we're done. 4120 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4121 break; 4122 } 4123 4124 // Check that the winning standard conversion sequence isn't using 4125 // the deprecated string literal array to pointer conversion. 4126 switch (Result) { 4127 case ImplicitConversionSequence::Better: 4128 if (SCS1.DeprecatedStringLiteralToCharPtr) 4129 Result = ImplicitConversionSequence::Indistinguishable; 4130 break; 4131 4132 case ImplicitConversionSequence::Indistinguishable: 4133 break; 4134 4135 case ImplicitConversionSequence::Worse: 4136 if (SCS2.DeprecatedStringLiteralToCharPtr) 4137 Result = ImplicitConversionSequence::Indistinguishable; 4138 break; 4139 } 4140 4141 return Result; 4142 } 4143 4144 /// CompareDerivedToBaseConversions - Compares two standard conversion 4145 /// sequences to determine whether they can be ranked based on their 4146 /// various kinds of derived-to-base conversions (C++ 4147 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4148 /// conversions between Objective-C interface types. 4149 static ImplicitConversionSequence::CompareKind 4150 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4151 const StandardConversionSequence& SCS1, 4152 const StandardConversionSequence& SCS2) { 4153 QualType FromType1 = SCS1.getFromType(); 4154 QualType ToType1 = SCS1.getToType(1); 4155 QualType FromType2 = SCS2.getFromType(); 4156 QualType ToType2 = SCS2.getToType(1); 4157 4158 // Adjust the types we're converting from via the array-to-pointer 4159 // conversion, if we need to. 4160 if (SCS1.First == ICK_Array_To_Pointer) 4161 FromType1 = S.Context.getArrayDecayedType(FromType1); 4162 if (SCS2.First == ICK_Array_To_Pointer) 4163 FromType2 = S.Context.getArrayDecayedType(FromType2); 4164 4165 // Canonicalize all of the types. 4166 FromType1 = S.Context.getCanonicalType(FromType1); 4167 ToType1 = S.Context.getCanonicalType(ToType1); 4168 FromType2 = S.Context.getCanonicalType(FromType2); 4169 ToType2 = S.Context.getCanonicalType(ToType2); 4170 4171 // C++ [over.ics.rank]p4b3: 4172 // 4173 // If class B is derived directly or indirectly from class A and 4174 // class C is derived directly or indirectly from B, 4175 // 4176 // Compare based on pointer conversions. 4177 if (SCS1.Second == ICK_Pointer_Conversion && 4178 SCS2.Second == ICK_Pointer_Conversion && 4179 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4180 FromType1->isPointerType() && FromType2->isPointerType() && 4181 ToType1->isPointerType() && ToType2->isPointerType()) { 4182 QualType FromPointee1 = 4183 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4184 QualType ToPointee1 = 4185 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4186 QualType FromPointee2 = 4187 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4188 QualType ToPointee2 = 4189 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4190 4191 // -- conversion of C* to B* is better than conversion of C* to A*, 4192 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4193 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4194 return ImplicitConversionSequence::Better; 4195 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4196 return ImplicitConversionSequence::Worse; 4197 } 4198 4199 // -- conversion of B* to A* is better than conversion of C* to A*, 4200 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4201 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4202 return ImplicitConversionSequence::Better; 4203 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4204 return ImplicitConversionSequence::Worse; 4205 } 4206 } else if (SCS1.Second == ICK_Pointer_Conversion && 4207 SCS2.Second == ICK_Pointer_Conversion) { 4208 const ObjCObjectPointerType *FromPtr1 4209 = FromType1->getAs<ObjCObjectPointerType>(); 4210 const ObjCObjectPointerType *FromPtr2 4211 = FromType2->getAs<ObjCObjectPointerType>(); 4212 const ObjCObjectPointerType *ToPtr1 4213 = ToType1->getAs<ObjCObjectPointerType>(); 4214 const ObjCObjectPointerType *ToPtr2 4215 = ToType2->getAs<ObjCObjectPointerType>(); 4216 4217 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4218 // Apply the same conversion ranking rules for Objective-C pointer types 4219 // that we do for C++ pointers to class types. However, we employ the 4220 // Objective-C pseudo-subtyping relationship used for assignment of 4221 // Objective-C pointer types. 4222 bool FromAssignLeft 4223 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4224 bool FromAssignRight 4225 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4226 bool ToAssignLeft 4227 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4228 bool ToAssignRight 4229 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4230 4231 // A conversion to an a non-id object pointer type or qualified 'id' 4232 // type is better than a conversion to 'id'. 4233 if (ToPtr1->isObjCIdType() && 4234 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4235 return ImplicitConversionSequence::Worse; 4236 if (ToPtr2->isObjCIdType() && 4237 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4238 return ImplicitConversionSequence::Better; 4239 4240 // A conversion to a non-id object pointer type is better than a 4241 // conversion to a qualified 'id' type 4242 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4243 return ImplicitConversionSequence::Worse; 4244 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4245 return ImplicitConversionSequence::Better; 4246 4247 // A conversion to an a non-Class object pointer type or qualified 'Class' 4248 // type is better than a conversion to 'Class'. 4249 if (ToPtr1->isObjCClassType() && 4250 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4251 return ImplicitConversionSequence::Worse; 4252 if (ToPtr2->isObjCClassType() && 4253 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4254 return ImplicitConversionSequence::Better; 4255 4256 // A conversion to a non-Class object pointer type is better than a 4257 // conversion to a qualified 'Class' type. 4258 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4259 return ImplicitConversionSequence::Worse; 4260 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4261 return ImplicitConversionSequence::Better; 4262 4263 // -- "conversion of C* to B* is better than conversion of C* to A*," 4264 if (S.Context.hasSameType(FromType1, FromType2) && 4265 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4266 (ToAssignLeft != ToAssignRight)) { 4267 if (FromPtr1->isSpecialized()) { 4268 // "conversion of B<A> * to B * is better than conversion of B * to 4269 // C *. 4270 bool IsFirstSame = 4271 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4272 bool IsSecondSame = 4273 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4274 if (IsFirstSame) { 4275 if (!IsSecondSame) 4276 return ImplicitConversionSequence::Better; 4277 } else if (IsSecondSame) 4278 return ImplicitConversionSequence::Worse; 4279 } 4280 return ToAssignLeft? ImplicitConversionSequence::Worse 4281 : ImplicitConversionSequence::Better; 4282 } 4283 4284 // -- "conversion of B* to A* is better than conversion of C* to A*," 4285 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4286 (FromAssignLeft != FromAssignRight)) 4287 return FromAssignLeft? ImplicitConversionSequence::Better 4288 : ImplicitConversionSequence::Worse; 4289 } 4290 } 4291 4292 // Ranking of member-pointer types. 4293 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4294 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4295 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4296 const MemberPointerType * FromMemPointer1 = 4297 FromType1->getAs<MemberPointerType>(); 4298 const MemberPointerType * ToMemPointer1 = 4299 ToType1->getAs<MemberPointerType>(); 4300 const MemberPointerType * FromMemPointer2 = 4301 FromType2->getAs<MemberPointerType>(); 4302 const MemberPointerType * ToMemPointer2 = 4303 ToType2->getAs<MemberPointerType>(); 4304 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4305 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4306 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4307 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4308 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4309 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4310 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4311 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4312 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4313 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4314 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4315 return ImplicitConversionSequence::Worse; 4316 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4317 return ImplicitConversionSequence::Better; 4318 } 4319 // conversion of B::* to C::* is better than conversion of A::* to C::* 4320 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4321 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4322 return ImplicitConversionSequence::Better; 4323 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4324 return ImplicitConversionSequence::Worse; 4325 } 4326 } 4327 4328 if (SCS1.Second == ICK_Derived_To_Base) { 4329 // -- conversion of C to B is better than conversion of C to A, 4330 // -- binding of an expression of type C to a reference of type 4331 // B& is better than binding an expression of type C to a 4332 // reference of type A&, 4333 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4334 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4335 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4336 return ImplicitConversionSequence::Better; 4337 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4338 return ImplicitConversionSequence::Worse; 4339 } 4340 4341 // -- conversion of B to A is better than conversion of C to A. 4342 // -- binding of an expression of type B to a reference of type 4343 // A& is better than binding an expression of type C to a 4344 // reference of type A&, 4345 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4346 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4347 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4348 return ImplicitConversionSequence::Better; 4349 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4350 return ImplicitConversionSequence::Worse; 4351 } 4352 } 4353 4354 return ImplicitConversionSequence::Indistinguishable; 4355 } 4356 4357 /// Determine whether the given type is valid, e.g., it is not an invalid 4358 /// C++ class. 4359 static bool isTypeValid(QualType T) { 4360 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4361 return !Record->isInvalidDecl(); 4362 4363 return true; 4364 } 4365 4366 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4367 /// determine whether they are reference-related, 4368 /// reference-compatible, reference-compatible with added 4369 /// qualification, or incompatible, for use in C++ initialization by 4370 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4371 /// type, and the first type (T1) is the pointee type of the reference 4372 /// type being initialized. 4373 Sema::ReferenceCompareResult 4374 Sema::CompareReferenceRelationship(SourceLocation Loc, 4375 QualType OrigT1, QualType OrigT2, 4376 bool &DerivedToBase, 4377 bool &ObjCConversion, 4378 bool &ObjCLifetimeConversion, 4379 bool &FunctionConversion) { 4380 assert(!OrigT1->isReferenceType() && 4381 "T1 must be the pointee type of the reference type"); 4382 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4383 4384 QualType T1 = Context.getCanonicalType(OrigT1); 4385 QualType T2 = Context.getCanonicalType(OrigT2); 4386 Qualifiers T1Quals, T2Quals; 4387 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4388 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4389 4390 // C++ [dcl.init.ref]p4: 4391 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4392 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4393 // T1 is a base class of T2. 4394 DerivedToBase = false; 4395 ObjCConversion = false; 4396 ObjCLifetimeConversion = false; 4397 QualType ConvertedT2; 4398 if (UnqualT1 == UnqualT2) { 4399 // Nothing to do. 4400 } else if (isCompleteType(Loc, OrigT2) && 4401 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4402 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4403 DerivedToBase = true; 4404 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4405 UnqualT2->isObjCObjectOrInterfaceType() && 4406 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4407 ObjCConversion = true; 4408 else if (UnqualT2->isFunctionType() && 4409 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4410 // C++1z [dcl.init.ref]p4: 4411 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4412 // function" and T1 is "function" 4413 // 4414 // We extend this to also apply to 'noreturn', so allow any function 4415 // conversion between function types. 4416 FunctionConversion = true; 4417 return Ref_Compatible; 4418 } else 4419 return Ref_Incompatible; 4420 4421 // At this point, we know that T1 and T2 are reference-related (at 4422 // least). 4423 4424 // If the type is an array type, promote the element qualifiers to the type 4425 // for comparison. 4426 if (isa<ArrayType>(T1) && T1Quals) 4427 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4428 if (isa<ArrayType>(T2) && T2Quals) 4429 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4430 4431 // C++ [dcl.init.ref]p4: 4432 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4433 // reference-related to T2 and cv1 is the same cv-qualification 4434 // as, or greater cv-qualification than, cv2. For purposes of 4435 // overload resolution, cases for which cv1 is greater 4436 // cv-qualification than cv2 are identified as 4437 // reference-compatible with added qualification (see 13.3.3.2). 4438 // 4439 // Note that we also require equivalence of Objective-C GC and address-space 4440 // qualifiers when performing these computations, so that e.g., an int in 4441 // address space 1 is not reference-compatible with an int in address 4442 // space 2. 4443 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4444 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4445 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4446 ObjCLifetimeConversion = true; 4447 4448 T1Quals.removeObjCLifetime(); 4449 T2Quals.removeObjCLifetime(); 4450 } 4451 4452 // MS compiler ignores __unaligned qualifier for references; do the same. 4453 T1Quals.removeUnaligned(); 4454 T2Quals.removeUnaligned(); 4455 4456 if (T1Quals.compatiblyIncludes(T2Quals)) 4457 return Ref_Compatible; 4458 else 4459 return Ref_Related; 4460 } 4461 4462 /// Look for a user-defined conversion to a value reference-compatible 4463 /// with DeclType. Return true if something definite is found. 4464 static bool 4465 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4466 QualType DeclType, SourceLocation DeclLoc, 4467 Expr *Init, QualType T2, bool AllowRvalues, 4468 bool AllowExplicit) { 4469 assert(T2->isRecordType() && "Can only find conversions of record types."); 4470 CXXRecordDecl *T2RecordDecl 4471 = dyn_cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4472 4473 OverloadCandidateSet CandidateSet( 4474 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4475 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4476 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4477 NamedDecl *D = *I; 4478 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4479 if (isa<UsingShadowDecl>(D)) 4480 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4481 4482 FunctionTemplateDecl *ConvTemplate 4483 = dyn_cast<FunctionTemplateDecl>(D); 4484 CXXConversionDecl *Conv; 4485 if (ConvTemplate) 4486 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4487 else 4488 Conv = cast<CXXConversionDecl>(D); 4489 4490 // If this is an explicit conversion, and we're not allowed to consider 4491 // explicit conversions, skip it. 4492 if (!AllowExplicit && Conv->isExplicit()) 4493 continue; 4494 4495 if (AllowRvalues) { 4496 bool DerivedToBase = false; 4497 bool ObjCConversion = false; 4498 bool ObjCLifetimeConversion = false; 4499 bool FunctionConversion = false; 4500 4501 // If we are initializing an rvalue reference, don't permit conversion 4502 // functions that return lvalues. 4503 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4504 const ReferenceType *RefType 4505 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4506 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4507 continue; 4508 } 4509 4510 if (!ConvTemplate && 4511 S.CompareReferenceRelationship( 4512 DeclLoc, 4513 Conv->getConversionType() 4514 .getNonReferenceType() 4515 .getUnqualifiedType(), 4516 DeclType.getNonReferenceType().getUnqualifiedType(), 4517 DerivedToBase, ObjCConversion, ObjCLifetimeConversion, 4518 FunctionConversion) == Sema::Ref_Incompatible) 4519 continue; 4520 } else { 4521 // If the conversion function doesn't return a reference type, 4522 // it can't be considered for this conversion. An rvalue reference 4523 // is only acceptable if its referencee is a function type. 4524 4525 const ReferenceType *RefType = 4526 Conv->getConversionType()->getAs<ReferenceType>(); 4527 if (!RefType || 4528 (!RefType->isLValueReferenceType() && 4529 !RefType->getPointeeType()->isFunctionType())) 4530 continue; 4531 } 4532 4533 if (ConvTemplate) 4534 S.AddTemplateConversionCandidate( 4535 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4536 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4537 else 4538 S.AddConversionCandidate( 4539 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4540 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4541 } 4542 4543 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4544 4545 OverloadCandidateSet::iterator Best; 4546 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4547 case OR_Success: 4548 // C++ [over.ics.ref]p1: 4549 // 4550 // [...] If the parameter binds directly to the result of 4551 // applying a conversion function to the argument 4552 // expression, the implicit conversion sequence is a 4553 // user-defined conversion sequence (13.3.3.1.2), with the 4554 // second standard conversion sequence either an identity 4555 // conversion or, if the conversion function returns an 4556 // entity of a type that is a derived class of the parameter 4557 // type, a derived-to-base Conversion. 4558 if (!Best->FinalConversion.DirectBinding) 4559 return false; 4560 4561 ICS.setUserDefined(); 4562 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4563 ICS.UserDefined.After = Best->FinalConversion; 4564 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4565 ICS.UserDefined.ConversionFunction = Best->Function; 4566 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4567 ICS.UserDefined.EllipsisConversion = false; 4568 assert(ICS.UserDefined.After.ReferenceBinding && 4569 ICS.UserDefined.After.DirectBinding && 4570 "Expected a direct reference binding!"); 4571 return true; 4572 4573 case OR_Ambiguous: 4574 ICS.setAmbiguous(); 4575 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4576 Cand != CandidateSet.end(); ++Cand) 4577 if (Cand->Best) 4578 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4579 return true; 4580 4581 case OR_No_Viable_Function: 4582 case OR_Deleted: 4583 // There was no suitable conversion, or we found a deleted 4584 // conversion; continue with other checks. 4585 return false; 4586 } 4587 4588 llvm_unreachable("Invalid OverloadResult!"); 4589 } 4590 4591 /// Compute an implicit conversion sequence for reference 4592 /// initialization. 4593 static ImplicitConversionSequence 4594 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4595 SourceLocation DeclLoc, 4596 bool SuppressUserConversions, 4597 bool AllowExplicit) { 4598 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4599 4600 // Most paths end in a failed conversion. 4601 ImplicitConversionSequence ICS; 4602 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4603 4604 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4605 QualType T2 = Init->getType(); 4606 4607 // If the initializer is the address of an overloaded function, try 4608 // to resolve the overloaded function. If all goes well, T2 is the 4609 // type of the resulting function. 4610 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4611 DeclAccessPair Found; 4612 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4613 false, Found)) 4614 T2 = Fn->getType(); 4615 } 4616 4617 // Compute some basic properties of the types and the initializer. 4618 bool isRValRef = DeclType->isRValueReferenceType(); 4619 bool DerivedToBase = false; 4620 bool ObjCConversion = false; 4621 bool ObjCLifetimeConversion = false; 4622 bool FunctionConversion = false; 4623 Expr::Classification InitCategory = Init->Classify(S.Context); 4624 Sema::ReferenceCompareResult RefRelationship = S.CompareReferenceRelationship( 4625 DeclLoc, T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion, 4626 FunctionConversion); 4627 4628 // C++0x [dcl.init.ref]p5: 4629 // A reference to type "cv1 T1" is initialized by an expression 4630 // of type "cv2 T2" as follows: 4631 4632 // -- If reference is an lvalue reference and the initializer expression 4633 if (!isRValRef) { 4634 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4635 // reference-compatible with "cv2 T2," or 4636 // 4637 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4638 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4639 // C++ [over.ics.ref]p1: 4640 // When a parameter of reference type binds directly (8.5.3) 4641 // to an argument expression, the implicit conversion sequence 4642 // is the identity conversion, unless the argument expression 4643 // has a type that is a derived class of the parameter type, 4644 // in which case the implicit conversion sequence is a 4645 // derived-to-base Conversion (13.3.3.1). 4646 ICS.setStandard(); 4647 ICS.Standard.First = ICK_Identity; 4648 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4649 : ObjCConversion? ICK_Compatible_Conversion 4650 : ICK_Identity; 4651 ICS.Standard.Third = ICK_Identity; 4652 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4653 ICS.Standard.setToType(0, T2); 4654 ICS.Standard.setToType(1, T1); 4655 ICS.Standard.setToType(2, T1); 4656 ICS.Standard.ReferenceBinding = true; 4657 ICS.Standard.DirectBinding = true; 4658 ICS.Standard.IsLvalueReference = !isRValRef; 4659 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4660 ICS.Standard.BindsToRvalue = false; 4661 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4662 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4663 ICS.Standard.CopyConstructor = nullptr; 4664 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4665 4666 // Nothing more to do: the inaccessibility/ambiguity check for 4667 // derived-to-base conversions is suppressed when we're 4668 // computing the implicit conversion sequence (C++ 4669 // [over.best.ics]p2). 4670 return ICS; 4671 } 4672 4673 // -- has a class type (i.e., T2 is a class type), where T1 is 4674 // not reference-related to T2, and can be implicitly 4675 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4676 // is reference-compatible with "cv3 T3" 92) (this 4677 // conversion is selected by enumerating the applicable 4678 // conversion functions (13.3.1.6) and choosing the best 4679 // one through overload resolution (13.3)), 4680 if (!SuppressUserConversions && T2->isRecordType() && 4681 S.isCompleteType(DeclLoc, T2) && 4682 RefRelationship == Sema::Ref_Incompatible) { 4683 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4684 Init, T2, /*AllowRvalues=*/false, 4685 AllowExplicit)) 4686 return ICS; 4687 } 4688 } 4689 4690 // -- Otherwise, the reference shall be an lvalue reference to a 4691 // non-volatile const type (i.e., cv1 shall be const), or the reference 4692 // shall be an rvalue reference. 4693 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4694 return ICS; 4695 4696 // -- If the initializer expression 4697 // 4698 // -- is an xvalue, class prvalue, array prvalue or function 4699 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4700 if (RefRelationship == Sema::Ref_Compatible && 4701 (InitCategory.isXValue() || 4702 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4703 (InitCategory.isLValue() && T2->isFunctionType()))) { 4704 ICS.setStandard(); 4705 ICS.Standard.First = ICK_Identity; 4706 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4707 : ObjCConversion? ICK_Compatible_Conversion 4708 : ICK_Identity; 4709 ICS.Standard.Third = ICK_Identity; 4710 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4711 ICS.Standard.setToType(0, T2); 4712 ICS.Standard.setToType(1, T1); 4713 ICS.Standard.setToType(2, T1); 4714 ICS.Standard.ReferenceBinding = true; 4715 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4716 // binding unless we're binding to a class prvalue. 4717 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4718 // allow the use of rvalue references in C++98/03 for the benefit of 4719 // standard library implementors; therefore, we need the xvalue check here. 4720 ICS.Standard.DirectBinding = 4721 S.getLangOpts().CPlusPlus11 || 4722 !(InitCategory.isPRValue() || T2->isRecordType()); 4723 ICS.Standard.IsLvalueReference = !isRValRef; 4724 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4725 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4726 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4727 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4728 ICS.Standard.CopyConstructor = nullptr; 4729 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4730 return ICS; 4731 } 4732 4733 // -- has a class type (i.e., T2 is a class type), where T1 is not 4734 // reference-related to T2, and can be implicitly converted to 4735 // an xvalue, class prvalue, or function lvalue of type 4736 // "cv3 T3", where "cv1 T1" is reference-compatible with 4737 // "cv3 T3", 4738 // 4739 // then the reference is bound to the value of the initializer 4740 // expression in the first case and to the result of the conversion 4741 // in the second case (or, in either case, to an appropriate base 4742 // class subobject). 4743 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4744 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4745 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4746 Init, T2, /*AllowRvalues=*/true, 4747 AllowExplicit)) { 4748 // In the second case, if the reference is an rvalue reference 4749 // and the second standard conversion sequence of the 4750 // user-defined conversion sequence includes an lvalue-to-rvalue 4751 // conversion, the program is ill-formed. 4752 if (ICS.isUserDefined() && isRValRef && 4753 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4754 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4755 4756 return ICS; 4757 } 4758 4759 // A temporary of function type cannot be created; don't even try. 4760 if (T1->isFunctionType()) 4761 return ICS; 4762 4763 // -- Otherwise, a temporary of type "cv1 T1" is created and 4764 // initialized from the initializer expression using the 4765 // rules for a non-reference copy initialization (8.5). The 4766 // reference is then bound to the temporary. If T1 is 4767 // reference-related to T2, cv1 must be the same 4768 // cv-qualification as, or greater cv-qualification than, 4769 // cv2; otherwise, the program is ill-formed. 4770 if (RefRelationship == Sema::Ref_Related) { 4771 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4772 // we would be reference-compatible or reference-compatible with 4773 // added qualification. But that wasn't the case, so the reference 4774 // initialization fails. 4775 // 4776 // Note that we only want to check address spaces and cvr-qualifiers here. 4777 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4778 Qualifiers T1Quals = T1.getQualifiers(); 4779 Qualifiers T2Quals = T2.getQualifiers(); 4780 T1Quals.removeObjCGCAttr(); 4781 T1Quals.removeObjCLifetime(); 4782 T2Quals.removeObjCGCAttr(); 4783 T2Quals.removeObjCLifetime(); 4784 // MS compiler ignores __unaligned qualifier for references; do the same. 4785 T1Quals.removeUnaligned(); 4786 T2Quals.removeUnaligned(); 4787 if (!T1Quals.compatiblyIncludes(T2Quals)) 4788 return ICS; 4789 } 4790 4791 // If at least one of the types is a class type, the types are not 4792 // related, and we aren't allowed any user conversions, the 4793 // reference binding fails. This case is important for breaking 4794 // recursion, since TryImplicitConversion below will attempt to 4795 // create a temporary through the use of a copy constructor. 4796 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4797 (T1->isRecordType() || T2->isRecordType())) 4798 return ICS; 4799 4800 // If T1 is reference-related to T2 and the reference is an rvalue 4801 // reference, the initializer expression shall not be an lvalue. 4802 if (RefRelationship >= Sema::Ref_Related && 4803 isRValRef && Init->Classify(S.Context).isLValue()) 4804 return ICS; 4805 4806 // C++ [over.ics.ref]p2: 4807 // When a parameter of reference type is not bound directly to 4808 // an argument expression, the conversion sequence is the one 4809 // required to convert the argument expression to the 4810 // underlying type of the reference according to 4811 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4812 // to copy-initializing a temporary of the underlying type with 4813 // the argument expression. Any difference in top-level 4814 // cv-qualification is subsumed by the initialization itself 4815 // and does not constitute a conversion. 4816 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4817 /*AllowExplicit=*/false, 4818 /*InOverloadResolution=*/false, 4819 /*CStyle=*/false, 4820 /*AllowObjCWritebackConversion=*/false, 4821 /*AllowObjCConversionOnExplicit=*/false); 4822 4823 // Of course, that's still a reference binding. 4824 if (ICS.isStandard()) { 4825 ICS.Standard.ReferenceBinding = true; 4826 ICS.Standard.IsLvalueReference = !isRValRef; 4827 ICS.Standard.BindsToFunctionLvalue = false; 4828 ICS.Standard.BindsToRvalue = true; 4829 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4830 ICS.Standard.ObjCLifetimeConversionBinding = false; 4831 } else if (ICS.isUserDefined()) { 4832 const ReferenceType *LValRefType = 4833 ICS.UserDefined.ConversionFunction->getReturnType() 4834 ->getAs<LValueReferenceType>(); 4835 4836 // C++ [over.ics.ref]p3: 4837 // Except for an implicit object parameter, for which see 13.3.1, a 4838 // standard conversion sequence cannot be formed if it requires [...] 4839 // binding an rvalue reference to an lvalue other than a function 4840 // lvalue. 4841 // Note that the function case is not possible here. 4842 if (DeclType->isRValueReferenceType() && LValRefType) { 4843 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4844 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4845 // reference to an rvalue! 4846 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4847 return ICS; 4848 } 4849 4850 ICS.UserDefined.After.ReferenceBinding = true; 4851 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4852 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4853 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4854 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4855 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4856 } 4857 4858 return ICS; 4859 } 4860 4861 static ImplicitConversionSequence 4862 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4863 bool SuppressUserConversions, 4864 bool InOverloadResolution, 4865 bool AllowObjCWritebackConversion, 4866 bool AllowExplicit = false); 4867 4868 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4869 /// initializer list From. 4870 static ImplicitConversionSequence 4871 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4872 bool SuppressUserConversions, 4873 bool InOverloadResolution, 4874 bool AllowObjCWritebackConversion) { 4875 // C++11 [over.ics.list]p1: 4876 // When an argument is an initializer list, it is not an expression and 4877 // special rules apply for converting it to a parameter type. 4878 4879 ImplicitConversionSequence Result; 4880 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4881 4882 // We need a complete type for what follows. Incomplete types can never be 4883 // initialized from init lists. 4884 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4885 return Result; 4886 4887 // Per DR1467: 4888 // If the parameter type is a class X and the initializer list has a single 4889 // element of type cv U, where U is X or a class derived from X, the 4890 // implicit conversion sequence is the one required to convert the element 4891 // to the parameter type. 4892 // 4893 // Otherwise, if the parameter type is a character array [... ] 4894 // and the initializer list has a single element that is an 4895 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4896 // implicit conversion sequence is the identity conversion. 4897 if (From->getNumInits() == 1) { 4898 if (ToType->isRecordType()) { 4899 QualType InitType = From->getInit(0)->getType(); 4900 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4901 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4902 return TryCopyInitialization(S, From->getInit(0), ToType, 4903 SuppressUserConversions, 4904 InOverloadResolution, 4905 AllowObjCWritebackConversion); 4906 } 4907 // FIXME: Check the other conditions here: array of character type, 4908 // initializer is a string literal. 4909 if (ToType->isArrayType()) { 4910 InitializedEntity Entity = 4911 InitializedEntity::InitializeParameter(S.Context, ToType, 4912 /*Consumed=*/false); 4913 if (S.CanPerformCopyInitialization(Entity, From)) { 4914 Result.setStandard(); 4915 Result.Standard.setAsIdentityConversion(); 4916 Result.Standard.setFromType(ToType); 4917 Result.Standard.setAllToTypes(ToType); 4918 return Result; 4919 } 4920 } 4921 } 4922 4923 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4924 // C++11 [over.ics.list]p2: 4925 // If the parameter type is std::initializer_list<X> or "array of X" and 4926 // all the elements can be implicitly converted to X, the implicit 4927 // conversion sequence is the worst conversion necessary to convert an 4928 // element of the list to X. 4929 // 4930 // C++14 [over.ics.list]p3: 4931 // Otherwise, if the parameter type is "array of N X", if the initializer 4932 // list has exactly N elements or if it has fewer than N elements and X is 4933 // default-constructible, and if all the elements of the initializer list 4934 // can be implicitly converted to X, the implicit conversion sequence is 4935 // the worst conversion necessary to convert an element of the list to X. 4936 // 4937 // FIXME: We're missing a lot of these checks. 4938 bool toStdInitializerList = false; 4939 QualType X; 4940 if (ToType->isArrayType()) 4941 X = S.Context.getAsArrayType(ToType)->getElementType(); 4942 else 4943 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4944 if (!X.isNull()) { 4945 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4946 Expr *Init = From->getInit(i); 4947 ImplicitConversionSequence ICS = 4948 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4949 InOverloadResolution, 4950 AllowObjCWritebackConversion); 4951 // If a single element isn't convertible, fail. 4952 if (ICS.isBad()) { 4953 Result = ICS; 4954 break; 4955 } 4956 // Otherwise, look for the worst conversion. 4957 if (Result.isBad() || CompareImplicitConversionSequences( 4958 S, From->getBeginLoc(), ICS, Result) == 4959 ImplicitConversionSequence::Worse) 4960 Result = ICS; 4961 } 4962 4963 // For an empty list, we won't have computed any conversion sequence. 4964 // Introduce the identity conversion sequence. 4965 if (From->getNumInits() == 0) { 4966 Result.setStandard(); 4967 Result.Standard.setAsIdentityConversion(); 4968 Result.Standard.setFromType(ToType); 4969 Result.Standard.setAllToTypes(ToType); 4970 } 4971 4972 Result.setStdInitializerListElement(toStdInitializerList); 4973 return Result; 4974 } 4975 4976 // C++14 [over.ics.list]p4: 4977 // C++11 [over.ics.list]p3: 4978 // Otherwise, if the parameter is a non-aggregate class X and overload 4979 // resolution chooses a single best constructor [...] the implicit 4980 // conversion sequence is a user-defined conversion sequence. If multiple 4981 // constructors are viable but none is better than the others, the 4982 // implicit conversion sequence is a user-defined conversion sequence. 4983 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4984 // This function can deal with initializer lists. 4985 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4986 /*AllowExplicit=*/false, 4987 InOverloadResolution, /*CStyle=*/false, 4988 AllowObjCWritebackConversion, 4989 /*AllowObjCConversionOnExplicit=*/false); 4990 } 4991 4992 // C++14 [over.ics.list]p5: 4993 // C++11 [over.ics.list]p4: 4994 // Otherwise, if the parameter has an aggregate type which can be 4995 // initialized from the initializer list [...] the implicit conversion 4996 // sequence is a user-defined conversion sequence. 4997 if (ToType->isAggregateType()) { 4998 // Type is an aggregate, argument is an init list. At this point it comes 4999 // down to checking whether the initialization works. 5000 // FIXME: Find out whether this parameter is consumed or not. 5001 InitializedEntity Entity = 5002 InitializedEntity::InitializeParameter(S.Context, ToType, 5003 /*Consumed=*/false); 5004 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5005 From)) { 5006 Result.setUserDefined(); 5007 Result.UserDefined.Before.setAsIdentityConversion(); 5008 // Initializer lists don't have a type. 5009 Result.UserDefined.Before.setFromType(QualType()); 5010 Result.UserDefined.Before.setAllToTypes(QualType()); 5011 5012 Result.UserDefined.After.setAsIdentityConversion(); 5013 Result.UserDefined.After.setFromType(ToType); 5014 Result.UserDefined.After.setAllToTypes(ToType); 5015 Result.UserDefined.ConversionFunction = nullptr; 5016 } 5017 return Result; 5018 } 5019 5020 // C++14 [over.ics.list]p6: 5021 // C++11 [over.ics.list]p5: 5022 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5023 if (ToType->isReferenceType()) { 5024 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5025 // mention initializer lists in any way. So we go by what list- 5026 // initialization would do and try to extrapolate from that. 5027 5028 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5029 5030 // If the initializer list has a single element that is reference-related 5031 // to the parameter type, we initialize the reference from that. 5032 if (From->getNumInits() == 1) { 5033 Expr *Init = From->getInit(0); 5034 5035 QualType T2 = Init->getType(); 5036 5037 // If the initializer is the address of an overloaded function, try 5038 // to resolve the overloaded function. If all goes well, T2 is the 5039 // type of the resulting function. 5040 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5041 DeclAccessPair Found; 5042 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5043 Init, ToType, false, Found)) 5044 T2 = Fn->getType(); 5045 } 5046 5047 // Compute some basic properties of the types and the initializer. 5048 bool dummy1 = false; 5049 bool dummy2 = false; 5050 bool dummy3 = false; 5051 bool dummy4 = false; 5052 Sema::ReferenceCompareResult RefRelationship = 5053 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, 5054 dummy2, dummy3, dummy4); 5055 5056 if (RefRelationship >= Sema::Ref_Related) { 5057 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5058 SuppressUserConversions, 5059 /*AllowExplicit=*/false); 5060 } 5061 } 5062 5063 // Otherwise, we bind the reference to a temporary created from the 5064 // initializer list. 5065 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5066 InOverloadResolution, 5067 AllowObjCWritebackConversion); 5068 if (Result.isFailure()) 5069 return Result; 5070 assert(!Result.isEllipsis() && 5071 "Sub-initialization cannot result in ellipsis conversion."); 5072 5073 // Can we even bind to a temporary? 5074 if (ToType->isRValueReferenceType() || 5075 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5076 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5077 Result.UserDefined.After; 5078 SCS.ReferenceBinding = true; 5079 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5080 SCS.BindsToRvalue = true; 5081 SCS.BindsToFunctionLvalue = false; 5082 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5083 SCS.ObjCLifetimeConversionBinding = false; 5084 } else 5085 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5086 From, ToType); 5087 return Result; 5088 } 5089 5090 // C++14 [over.ics.list]p7: 5091 // C++11 [over.ics.list]p6: 5092 // Otherwise, if the parameter type is not a class: 5093 if (!ToType->isRecordType()) { 5094 // - if the initializer list has one element that is not itself an 5095 // initializer list, the implicit conversion sequence is the one 5096 // required to convert the element to the parameter type. 5097 unsigned NumInits = From->getNumInits(); 5098 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5099 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5100 SuppressUserConversions, 5101 InOverloadResolution, 5102 AllowObjCWritebackConversion); 5103 // - if the initializer list has no elements, the implicit conversion 5104 // sequence is the identity conversion. 5105 else if (NumInits == 0) { 5106 Result.setStandard(); 5107 Result.Standard.setAsIdentityConversion(); 5108 Result.Standard.setFromType(ToType); 5109 Result.Standard.setAllToTypes(ToType); 5110 } 5111 return Result; 5112 } 5113 5114 // C++14 [over.ics.list]p8: 5115 // C++11 [over.ics.list]p7: 5116 // In all cases other than those enumerated above, no conversion is possible 5117 return Result; 5118 } 5119 5120 /// TryCopyInitialization - Try to copy-initialize a value of type 5121 /// ToType from the expression From. Return the implicit conversion 5122 /// sequence required to pass this argument, which may be a bad 5123 /// conversion sequence (meaning that the argument cannot be passed to 5124 /// a parameter of this type). If @p SuppressUserConversions, then we 5125 /// do not permit any user-defined conversion sequences. 5126 static ImplicitConversionSequence 5127 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5128 bool SuppressUserConversions, 5129 bool InOverloadResolution, 5130 bool AllowObjCWritebackConversion, 5131 bool AllowExplicit) { 5132 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5133 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5134 InOverloadResolution,AllowObjCWritebackConversion); 5135 5136 if (ToType->isReferenceType()) 5137 return TryReferenceInit(S, From, ToType, 5138 /*FIXME:*/ From->getBeginLoc(), 5139 SuppressUserConversions, AllowExplicit); 5140 5141 return TryImplicitConversion(S, From, ToType, 5142 SuppressUserConversions, 5143 /*AllowExplicit=*/false, 5144 InOverloadResolution, 5145 /*CStyle=*/false, 5146 AllowObjCWritebackConversion, 5147 /*AllowObjCConversionOnExplicit=*/false); 5148 } 5149 5150 static bool TryCopyInitialization(const CanQualType FromQTy, 5151 const CanQualType ToQTy, 5152 Sema &S, 5153 SourceLocation Loc, 5154 ExprValueKind FromVK) { 5155 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5156 ImplicitConversionSequence ICS = 5157 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5158 5159 return !ICS.isBad(); 5160 } 5161 5162 /// TryObjectArgumentInitialization - Try to initialize the object 5163 /// parameter of the given member function (@c Method) from the 5164 /// expression @p From. 5165 static ImplicitConversionSequence 5166 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5167 Expr::Classification FromClassification, 5168 CXXMethodDecl *Method, 5169 CXXRecordDecl *ActingContext) { 5170 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5171 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5172 // const volatile object. 5173 Qualifiers Quals = Method->getMethodQualifiers(); 5174 if (isa<CXXDestructorDecl>(Method)) { 5175 Quals.addConst(); 5176 Quals.addVolatile(); 5177 } 5178 5179 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5180 5181 // Set up the conversion sequence as a "bad" conversion, to allow us 5182 // to exit early. 5183 ImplicitConversionSequence ICS; 5184 5185 // We need to have an object of class type. 5186 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5187 FromType = PT->getPointeeType(); 5188 5189 // When we had a pointer, it's implicitly dereferenced, so we 5190 // better have an lvalue. 5191 assert(FromClassification.isLValue()); 5192 } 5193 5194 assert(FromType->isRecordType()); 5195 5196 // C++0x [over.match.funcs]p4: 5197 // For non-static member functions, the type of the implicit object 5198 // parameter is 5199 // 5200 // - "lvalue reference to cv X" for functions declared without a 5201 // ref-qualifier or with the & ref-qualifier 5202 // - "rvalue reference to cv X" for functions declared with the && 5203 // ref-qualifier 5204 // 5205 // where X is the class of which the function is a member and cv is the 5206 // cv-qualification on the member function declaration. 5207 // 5208 // However, when finding an implicit conversion sequence for the argument, we 5209 // are not allowed to perform user-defined conversions 5210 // (C++ [over.match.funcs]p5). We perform a simplified version of 5211 // reference binding here, that allows class rvalues to bind to 5212 // non-constant references. 5213 5214 // First check the qualifiers. 5215 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5216 if (ImplicitParamType.getCVRQualifiers() 5217 != FromTypeCanon.getLocalCVRQualifiers() && 5218 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5219 ICS.setBad(BadConversionSequence::bad_qualifiers, 5220 FromType, ImplicitParamType); 5221 return ICS; 5222 } 5223 5224 if (FromTypeCanon.getQualifiers().hasAddressSpace()) { 5225 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5226 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5227 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5228 ICS.setBad(BadConversionSequence::bad_qualifiers, 5229 FromType, ImplicitParamType); 5230 return ICS; 5231 } 5232 } 5233 5234 // Check that we have either the same type or a derived type. It 5235 // affects the conversion rank. 5236 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5237 ImplicitConversionKind SecondKind; 5238 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5239 SecondKind = ICK_Identity; 5240 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5241 SecondKind = ICK_Derived_To_Base; 5242 else { 5243 ICS.setBad(BadConversionSequence::unrelated_class, 5244 FromType, ImplicitParamType); 5245 return ICS; 5246 } 5247 5248 // Check the ref-qualifier. 5249 switch (Method->getRefQualifier()) { 5250 case RQ_None: 5251 // Do nothing; we don't care about lvalueness or rvalueness. 5252 break; 5253 5254 case RQ_LValue: 5255 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5256 // non-const lvalue reference cannot bind to an rvalue 5257 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5258 ImplicitParamType); 5259 return ICS; 5260 } 5261 break; 5262 5263 case RQ_RValue: 5264 if (!FromClassification.isRValue()) { 5265 // rvalue reference cannot bind to an lvalue 5266 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5267 ImplicitParamType); 5268 return ICS; 5269 } 5270 break; 5271 } 5272 5273 // Success. Mark this as a reference binding. 5274 ICS.setStandard(); 5275 ICS.Standard.setAsIdentityConversion(); 5276 ICS.Standard.Second = SecondKind; 5277 ICS.Standard.setFromType(FromType); 5278 ICS.Standard.setAllToTypes(ImplicitParamType); 5279 ICS.Standard.ReferenceBinding = true; 5280 ICS.Standard.DirectBinding = true; 5281 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5282 ICS.Standard.BindsToFunctionLvalue = false; 5283 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5284 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5285 = (Method->getRefQualifier() == RQ_None); 5286 return ICS; 5287 } 5288 5289 /// PerformObjectArgumentInitialization - Perform initialization of 5290 /// the implicit object parameter for the given Method with the given 5291 /// expression. 5292 ExprResult 5293 Sema::PerformObjectArgumentInitialization(Expr *From, 5294 NestedNameSpecifier *Qualifier, 5295 NamedDecl *FoundDecl, 5296 CXXMethodDecl *Method) { 5297 QualType FromRecordType, DestType; 5298 QualType ImplicitParamRecordType = 5299 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5300 5301 Expr::Classification FromClassification; 5302 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5303 FromRecordType = PT->getPointeeType(); 5304 DestType = Method->getThisType(); 5305 FromClassification = Expr::Classification::makeSimpleLValue(); 5306 } else { 5307 FromRecordType = From->getType(); 5308 DestType = ImplicitParamRecordType; 5309 FromClassification = From->Classify(Context); 5310 5311 // When performing member access on an rvalue, materialize a temporary. 5312 if (From->isRValue()) { 5313 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5314 Method->getRefQualifier() != 5315 RefQualifierKind::RQ_RValue); 5316 } 5317 } 5318 5319 // Note that we always use the true parent context when performing 5320 // the actual argument initialization. 5321 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5322 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5323 Method->getParent()); 5324 if (ICS.isBad()) { 5325 switch (ICS.Bad.Kind) { 5326 case BadConversionSequence::bad_qualifiers: { 5327 Qualifiers FromQs = FromRecordType.getQualifiers(); 5328 Qualifiers ToQs = DestType.getQualifiers(); 5329 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5330 if (CVR) { 5331 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5332 << Method->getDeclName() << FromRecordType << (CVR - 1) 5333 << From->getSourceRange(); 5334 Diag(Method->getLocation(), diag::note_previous_decl) 5335 << Method->getDeclName(); 5336 return ExprError(); 5337 } 5338 break; 5339 } 5340 5341 case BadConversionSequence::lvalue_ref_to_rvalue: 5342 case BadConversionSequence::rvalue_ref_to_lvalue: { 5343 bool IsRValueQualified = 5344 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5345 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5346 << Method->getDeclName() << FromClassification.isRValue() 5347 << IsRValueQualified; 5348 Diag(Method->getLocation(), diag::note_previous_decl) 5349 << Method->getDeclName(); 5350 return ExprError(); 5351 } 5352 5353 case BadConversionSequence::no_conversion: 5354 case BadConversionSequence::unrelated_class: 5355 break; 5356 } 5357 5358 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5359 << ImplicitParamRecordType << FromRecordType 5360 << From->getSourceRange(); 5361 } 5362 5363 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5364 ExprResult FromRes = 5365 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5366 if (FromRes.isInvalid()) 5367 return ExprError(); 5368 From = FromRes.get(); 5369 } 5370 5371 if (!Context.hasSameType(From->getType(), DestType)) { 5372 CastKind CK; 5373 if (FromRecordType.getAddressSpace() != DestType.getAddressSpace()) 5374 CK = CK_AddressSpaceConversion; 5375 else 5376 CK = CK_NoOp; 5377 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5378 } 5379 return From; 5380 } 5381 5382 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5383 /// expression From to bool (C++0x [conv]p3). 5384 static ImplicitConversionSequence 5385 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5386 return TryImplicitConversion(S, From, S.Context.BoolTy, 5387 /*SuppressUserConversions=*/false, 5388 /*AllowExplicit=*/true, 5389 /*InOverloadResolution=*/false, 5390 /*CStyle=*/false, 5391 /*AllowObjCWritebackConversion=*/false, 5392 /*AllowObjCConversionOnExplicit=*/false); 5393 } 5394 5395 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5396 /// of the expression From to bool (C++0x [conv]p3). 5397 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5398 if (checkPlaceholderForOverload(*this, From)) 5399 return ExprError(); 5400 5401 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5402 if (!ICS.isBad()) 5403 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5404 5405 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5406 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5407 << From->getType() << From->getSourceRange(); 5408 return ExprError(); 5409 } 5410 5411 /// Check that the specified conversion is permitted in a converted constant 5412 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5413 /// is acceptable. 5414 static bool CheckConvertedConstantConversions(Sema &S, 5415 StandardConversionSequence &SCS) { 5416 // Since we know that the target type is an integral or unscoped enumeration 5417 // type, most conversion kinds are impossible. All possible First and Third 5418 // conversions are fine. 5419 switch (SCS.Second) { 5420 case ICK_Identity: 5421 case ICK_Function_Conversion: 5422 case ICK_Integral_Promotion: 5423 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5424 case ICK_Zero_Queue_Conversion: 5425 return true; 5426 5427 case ICK_Boolean_Conversion: 5428 // Conversion from an integral or unscoped enumeration type to bool is 5429 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5430 // conversion, so we allow it in a converted constant expression. 5431 // 5432 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5433 // a lot of popular code. We should at least add a warning for this 5434 // (non-conforming) extension. 5435 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5436 SCS.getToType(2)->isBooleanType(); 5437 5438 case ICK_Pointer_Conversion: 5439 case ICK_Pointer_Member: 5440 // C++1z: null pointer conversions and null member pointer conversions are 5441 // only permitted if the source type is std::nullptr_t. 5442 return SCS.getFromType()->isNullPtrType(); 5443 5444 case ICK_Floating_Promotion: 5445 case ICK_Complex_Promotion: 5446 case ICK_Floating_Conversion: 5447 case ICK_Complex_Conversion: 5448 case ICK_Floating_Integral: 5449 case ICK_Compatible_Conversion: 5450 case ICK_Derived_To_Base: 5451 case ICK_Vector_Conversion: 5452 case ICK_Vector_Splat: 5453 case ICK_Complex_Real: 5454 case ICK_Block_Pointer_Conversion: 5455 case ICK_TransparentUnionConversion: 5456 case ICK_Writeback_Conversion: 5457 case ICK_Zero_Event_Conversion: 5458 case ICK_C_Only_Conversion: 5459 case ICK_Incompatible_Pointer_Conversion: 5460 return false; 5461 5462 case ICK_Lvalue_To_Rvalue: 5463 case ICK_Array_To_Pointer: 5464 case ICK_Function_To_Pointer: 5465 llvm_unreachable("found a first conversion kind in Second"); 5466 5467 case ICK_Qualification: 5468 llvm_unreachable("found a third conversion kind in Second"); 5469 5470 case ICK_Num_Conversion_Kinds: 5471 break; 5472 } 5473 5474 llvm_unreachable("unknown conversion kind"); 5475 } 5476 5477 /// CheckConvertedConstantExpression - Check that the expression From is a 5478 /// converted constant expression of type T, perform the conversion and produce 5479 /// the converted expression, per C++11 [expr.const]p3. 5480 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5481 QualType T, APValue &Value, 5482 Sema::CCEKind CCE, 5483 bool RequireInt) { 5484 assert(S.getLangOpts().CPlusPlus11 && 5485 "converted constant expression outside C++11"); 5486 5487 if (checkPlaceholderForOverload(S, From)) 5488 return ExprError(); 5489 5490 // C++1z [expr.const]p3: 5491 // A converted constant expression of type T is an expression, 5492 // implicitly converted to type T, where the converted 5493 // expression is a constant expression and the implicit conversion 5494 // sequence contains only [... list of conversions ...]. 5495 // C++1z [stmt.if]p2: 5496 // If the if statement is of the form if constexpr, the value of the 5497 // condition shall be a contextually converted constant expression of type 5498 // bool. 5499 ImplicitConversionSequence ICS = 5500 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5501 ? TryContextuallyConvertToBool(S, From) 5502 : TryCopyInitialization(S, From, T, 5503 /*SuppressUserConversions=*/false, 5504 /*InOverloadResolution=*/false, 5505 /*AllowObjCWritebackConversion=*/false, 5506 /*AllowExplicit=*/false); 5507 StandardConversionSequence *SCS = nullptr; 5508 switch (ICS.getKind()) { 5509 case ImplicitConversionSequence::StandardConversion: 5510 SCS = &ICS.Standard; 5511 break; 5512 case ImplicitConversionSequence::UserDefinedConversion: 5513 // We are converting to a non-class type, so the Before sequence 5514 // must be trivial. 5515 SCS = &ICS.UserDefined.After; 5516 break; 5517 case ImplicitConversionSequence::AmbiguousConversion: 5518 case ImplicitConversionSequence::BadConversion: 5519 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5520 return S.Diag(From->getBeginLoc(), 5521 diag::err_typecheck_converted_constant_expression) 5522 << From->getType() << From->getSourceRange() << T; 5523 return ExprError(); 5524 5525 case ImplicitConversionSequence::EllipsisConversion: 5526 llvm_unreachable("ellipsis conversion in converted constant expression"); 5527 } 5528 5529 // Check that we would only use permitted conversions. 5530 if (!CheckConvertedConstantConversions(S, *SCS)) { 5531 return S.Diag(From->getBeginLoc(), 5532 diag::err_typecheck_converted_constant_expression_disallowed) 5533 << From->getType() << From->getSourceRange() << T; 5534 } 5535 // [...] and where the reference binding (if any) binds directly. 5536 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5537 return S.Diag(From->getBeginLoc(), 5538 diag::err_typecheck_converted_constant_expression_indirect) 5539 << From->getType() << From->getSourceRange() << T; 5540 } 5541 5542 ExprResult Result = 5543 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5544 if (Result.isInvalid()) 5545 return Result; 5546 5547 // C++2a [intro.execution]p5: 5548 // A full-expression is [...] a constant-expression [...] 5549 Result = 5550 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5551 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5552 if (Result.isInvalid()) 5553 return Result; 5554 5555 // Check for a narrowing implicit conversion. 5556 APValue PreNarrowingValue; 5557 QualType PreNarrowingType; 5558 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5559 PreNarrowingType)) { 5560 case NK_Dependent_Narrowing: 5561 // Implicit conversion to a narrower type, but the expression is 5562 // value-dependent so we can't tell whether it's actually narrowing. 5563 case NK_Variable_Narrowing: 5564 // Implicit conversion to a narrower type, and the value is not a constant 5565 // expression. We'll diagnose this in a moment. 5566 case NK_Not_Narrowing: 5567 break; 5568 5569 case NK_Constant_Narrowing: 5570 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5571 << CCE << /*Constant*/ 1 5572 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5573 break; 5574 5575 case NK_Type_Narrowing: 5576 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5577 << CCE << /*Constant*/ 0 << From->getType() << T; 5578 break; 5579 } 5580 5581 if (Result.get()->isValueDependent()) { 5582 Value = APValue(); 5583 return Result; 5584 } 5585 5586 // Check the expression is a constant expression. 5587 SmallVector<PartialDiagnosticAt, 8> Notes; 5588 Expr::EvalResult Eval; 5589 Eval.Diag = &Notes; 5590 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5591 ? Expr::EvaluateForMangling 5592 : Expr::EvaluateForCodeGen; 5593 5594 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5595 (RequireInt && !Eval.Val.isInt())) { 5596 // The expression can't be folded, so we can't keep it at this position in 5597 // the AST. 5598 Result = ExprError(); 5599 } else { 5600 Value = Eval.Val; 5601 5602 if (Notes.empty()) { 5603 // It's a constant expression. 5604 return ConstantExpr::Create(S.Context, Result.get(), Value); 5605 } 5606 } 5607 5608 // It's not a constant expression. Produce an appropriate diagnostic. 5609 if (Notes.size() == 1 && 5610 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5611 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5612 else { 5613 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5614 << CCE << From->getSourceRange(); 5615 for (unsigned I = 0; I < Notes.size(); ++I) 5616 S.Diag(Notes[I].first, Notes[I].second); 5617 } 5618 return ExprError(); 5619 } 5620 5621 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5622 APValue &Value, CCEKind CCE) { 5623 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5624 } 5625 5626 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5627 llvm::APSInt &Value, 5628 CCEKind CCE) { 5629 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5630 5631 APValue V; 5632 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5633 if (!R.isInvalid() && !R.get()->isValueDependent()) 5634 Value = V.getInt(); 5635 return R; 5636 } 5637 5638 5639 /// dropPointerConversions - If the given standard conversion sequence 5640 /// involves any pointer conversions, remove them. This may change 5641 /// the result type of the conversion sequence. 5642 static void dropPointerConversion(StandardConversionSequence &SCS) { 5643 if (SCS.Second == ICK_Pointer_Conversion) { 5644 SCS.Second = ICK_Identity; 5645 SCS.Third = ICK_Identity; 5646 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5647 } 5648 } 5649 5650 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5651 /// convert the expression From to an Objective-C pointer type. 5652 static ImplicitConversionSequence 5653 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5654 // Do an implicit conversion to 'id'. 5655 QualType Ty = S.Context.getObjCIdType(); 5656 ImplicitConversionSequence ICS 5657 = TryImplicitConversion(S, From, Ty, 5658 // FIXME: Are these flags correct? 5659 /*SuppressUserConversions=*/false, 5660 /*AllowExplicit=*/true, 5661 /*InOverloadResolution=*/false, 5662 /*CStyle=*/false, 5663 /*AllowObjCWritebackConversion=*/false, 5664 /*AllowObjCConversionOnExplicit=*/true); 5665 5666 // Strip off any final conversions to 'id'. 5667 switch (ICS.getKind()) { 5668 case ImplicitConversionSequence::BadConversion: 5669 case ImplicitConversionSequence::AmbiguousConversion: 5670 case ImplicitConversionSequence::EllipsisConversion: 5671 break; 5672 5673 case ImplicitConversionSequence::UserDefinedConversion: 5674 dropPointerConversion(ICS.UserDefined.After); 5675 break; 5676 5677 case ImplicitConversionSequence::StandardConversion: 5678 dropPointerConversion(ICS.Standard); 5679 break; 5680 } 5681 5682 return ICS; 5683 } 5684 5685 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5686 /// conversion of the expression From to an Objective-C pointer type. 5687 /// Returns a valid but null ExprResult if no conversion sequence exists. 5688 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5689 if (checkPlaceholderForOverload(*this, From)) 5690 return ExprError(); 5691 5692 QualType Ty = Context.getObjCIdType(); 5693 ImplicitConversionSequence ICS = 5694 TryContextuallyConvertToObjCPointer(*this, From); 5695 if (!ICS.isBad()) 5696 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5697 return ExprResult(); 5698 } 5699 5700 /// Determine whether the provided type is an integral type, or an enumeration 5701 /// type of a permitted flavor. 5702 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5703 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5704 : T->isIntegralOrUnscopedEnumerationType(); 5705 } 5706 5707 static ExprResult 5708 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5709 Sema::ContextualImplicitConverter &Converter, 5710 QualType T, UnresolvedSetImpl &ViableConversions) { 5711 5712 if (Converter.Suppress) 5713 return ExprError(); 5714 5715 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5716 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5717 CXXConversionDecl *Conv = 5718 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5719 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5720 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5721 } 5722 return From; 5723 } 5724 5725 static bool 5726 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5727 Sema::ContextualImplicitConverter &Converter, 5728 QualType T, bool HadMultipleCandidates, 5729 UnresolvedSetImpl &ExplicitConversions) { 5730 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5731 DeclAccessPair Found = ExplicitConversions[0]; 5732 CXXConversionDecl *Conversion = 5733 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5734 5735 // The user probably meant to invoke the given explicit 5736 // conversion; use it. 5737 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5738 std::string TypeStr; 5739 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5740 5741 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5742 << FixItHint::CreateInsertion(From->getBeginLoc(), 5743 "static_cast<" + TypeStr + ">(") 5744 << FixItHint::CreateInsertion( 5745 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5746 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5747 5748 // If we aren't in a SFINAE context, build a call to the 5749 // explicit conversion function. 5750 if (SemaRef.isSFINAEContext()) 5751 return true; 5752 5753 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5754 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5755 HadMultipleCandidates); 5756 if (Result.isInvalid()) 5757 return true; 5758 // Record usage of conversion in an implicit cast. 5759 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5760 CK_UserDefinedConversion, Result.get(), 5761 nullptr, Result.get()->getValueKind()); 5762 } 5763 return false; 5764 } 5765 5766 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5767 Sema::ContextualImplicitConverter &Converter, 5768 QualType T, bool HadMultipleCandidates, 5769 DeclAccessPair &Found) { 5770 CXXConversionDecl *Conversion = 5771 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5772 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5773 5774 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5775 if (!Converter.SuppressConversion) { 5776 if (SemaRef.isSFINAEContext()) 5777 return true; 5778 5779 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5780 << From->getSourceRange(); 5781 } 5782 5783 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5784 HadMultipleCandidates); 5785 if (Result.isInvalid()) 5786 return true; 5787 // Record usage of conversion in an implicit cast. 5788 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5789 CK_UserDefinedConversion, Result.get(), 5790 nullptr, Result.get()->getValueKind()); 5791 return false; 5792 } 5793 5794 static ExprResult finishContextualImplicitConversion( 5795 Sema &SemaRef, SourceLocation Loc, Expr *From, 5796 Sema::ContextualImplicitConverter &Converter) { 5797 if (!Converter.match(From->getType()) && !Converter.Suppress) 5798 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5799 << From->getSourceRange(); 5800 5801 return SemaRef.DefaultLvalueConversion(From); 5802 } 5803 5804 static void 5805 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5806 UnresolvedSetImpl &ViableConversions, 5807 OverloadCandidateSet &CandidateSet) { 5808 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5809 DeclAccessPair FoundDecl = ViableConversions[I]; 5810 NamedDecl *D = FoundDecl.getDecl(); 5811 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5812 if (isa<UsingShadowDecl>(D)) 5813 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5814 5815 CXXConversionDecl *Conv; 5816 FunctionTemplateDecl *ConvTemplate; 5817 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5818 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5819 else 5820 Conv = cast<CXXConversionDecl>(D); 5821 5822 if (ConvTemplate) 5823 SemaRef.AddTemplateConversionCandidate( 5824 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5825 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5826 else 5827 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5828 ToType, CandidateSet, 5829 /*AllowObjCConversionOnExplicit=*/false, 5830 /*AllowExplicit*/ true); 5831 } 5832 } 5833 5834 /// Attempt to convert the given expression to a type which is accepted 5835 /// by the given converter. 5836 /// 5837 /// This routine will attempt to convert an expression of class type to a 5838 /// type accepted by the specified converter. In C++11 and before, the class 5839 /// must have a single non-explicit conversion function converting to a matching 5840 /// type. In C++1y, there can be multiple such conversion functions, but only 5841 /// one target type. 5842 /// 5843 /// \param Loc The source location of the construct that requires the 5844 /// conversion. 5845 /// 5846 /// \param From The expression we're converting from. 5847 /// 5848 /// \param Converter Used to control and diagnose the conversion process. 5849 /// 5850 /// \returns The expression, converted to an integral or enumeration type if 5851 /// successful. 5852 ExprResult Sema::PerformContextualImplicitConversion( 5853 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5854 // We can't perform any more checking for type-dependent expressions. 5855 if (From->isTypeDependent()) 5856 return From; 5857 5858 // Process placeholders immediately. 5859 if (From->hasPlaceholderType()) { 5860 ExprResult result = CheckPlaceholderExpr(From); 5861 if (result.isInvalid()) 5862 return result; 5863 From = result.get(); 5864 } 5865 5866 // If the expression already has a matching type, we're golden. 5867 QualType T = From->getType(); 5868 if (Converter.match(T)) 5869 return DefaultLvalueConversion(From); 5870 5871 // FIXME: Check for missing '()' if T is a function type? 5872 5873 // We can only perform contextual implicit conversions on objects of class 5874 // type. 5875 const RecordType *RecordTy = T->getAs<RecordType>(); 5876 if (!RecordTy || !getLangOpts().CPlusPlus) { 5877 if (!Converter.Suppress) 5878 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5879 return From; 5880 } 5881 5882 // We must have a complete class type. 5883 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5884 ContextualImplicitConverter &Converter; 5885 Expr *From; 5886 5887 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5888 : Converter(Converter), From(From) {} 5889 5890 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5891 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5892 } 5893 } IncompleteDiagnoser(Converter, From); 5894 5895 if (Converter.Suppress ? !isCompleteType(Loc, T) 5896 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5897 return From; 5898 5899 // Look for a conversion to an integral or enumeration type. 5900 UnresolvedSet<4> 5901 ViableConversions; // These are *potentially* viable in C++1y. 5902 UnresolvedSet<4> ExplicitConversions; 5903 const auto &Conversions = 5904 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5905 5906 bool HadMultipleCandidates = 5907 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5908 5909 // To check that there is only one target type, in C++1y: 5910 QualType ToType; 5911 bool HasUniqueTargetType = true; 5912 5913 // Collect explicit or viable (potentially in C++1y) conversions. 5914 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5915 NamedDecl *D = (*I)->getUnderlyingDecl(); 5916 CXXConversionDecl *Conversion; 5917 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5918 if (ConvTemplate) { 5919 if (getLangOpts().CPlusPlus14) 5920 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5921 else 5922 continue; // C++11 does not consider conversion operator templates(?). 5923 } else 5924 Conversion = cast<CXXConversionDecl>(D); 5925 5926 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5927 "Conversion operator templates are considered potentially " 5928 "viable in C++1y"); 5929 5930 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5931 if (Converter.match(CurToType) || ConvTemplate) { 5932 5933 if (Conversion->isExplicit()) { 5934 // FIXME: For C++1y, do we need this restriction? 5935 // cf. diagnoseNoViableConversion() 5936 if (!ConvTemplate) 5937 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5938 } else { 5939 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5940 if (ToType.isNull()) 5941 ToType = CurToType.getUnqualifiedType(); 5942 else if (HasUniqueTargetType && 5943 (CurToType.getUnqualifiedType() != ToType)) 5944 HasUniqueTargetType = false; 5945 } 5946 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5947 } 5948 } 5949 } 5950 5951 if (getLangOpts().CPlusPlus14) { 5952 // C++1y [conv]p6: 5953 // ... An expression e of class type E appearing in such a context 5954 // is said to be contextually implicitly converted to a specified 5955 // type T and is well-formed if and only if e can be implicitly 5956 // converted to a type T that is determined as follows: E is searched 5957 // for conversion functions whose return type is cv T or reference to 5958 // cv T such that T is allowed by the context. There shall be 5959 // exactly one such T. 5960 5961 // If no unique T is found: 5962 if (ToType.isNull()) { 5963 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5964 HadMultipleCandidates, 5965 ExplicitConversions)) 5966 return ExprError(); 5967 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5968 } 5969 5970 // If more than one unique Ts are found: 5971 if (!HasUniqueTargetType) 5972 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5973 ViableConversions); 5974 5975 // If one unique T is found: 5976 // First, build a candidate set from the previously recorded 5977 // potentially viable conversions. 5978 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5979 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5980 CandidateSet); 5981 5982 // Then, perform overload resolution over the candidate set. 5983 OverloadCandidateSet::iterator Best; 5984 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5985 case OR_Success: { 5986 // Apply this conversion. 5987 DeclAccessPair Found = 5988 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5989 if (recordConversion(*this, Loc, From, Converter, T, 5990 HadMultipleCandidates, Found)) 5991 return ExprError(); 5992 break; 5993 } 5994 case OR_Ambiguous: 5995 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5996 ViableConversions); 5997 case OR_No_Viable_Function: 5998 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5999 HadMultipleCandidates, 6000 ExplicitConversions)) 6001 return ExprError(); 6002 LLVM_FALLTHROUGH; 6003 case OR_Deleted: 6004 // We'll complain below about a non-integral condition type. 6005 break; 6006 } 6007 } else { 6008 switch (ViableConversions.size()) { 6009 case 0: { 6010 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6011 HadMultipleCandidates, 6012 ExplicitConversions)) 6013 return ExprError(); 6014 6015 // We'll complain below about a non-integral condition type. 6016 break; 6017 } 6018 case 1: { 6019 // Apply this conversion. 6020 DeclAccessPair Found = ViableConversions[0]; 6021 if (recordConversion(*this, Loc, From, Converter, T, 6022 HadMultipleCandidates, Found)) 6023 return ExprError(); 6024 break; 6025 } 6026 default: 6027 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6028 ViableConversions); 6029 } 6030 } 6031 6032 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6033 } 6034 6035 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6036 /// an acceptable non-member overloaded operator for a call whose 6037 /// arguments have types T1 (and, if non-empty, T2). This routine 6038 /// implements the check in C++ [over.match.oper]p3b2 concerning 6039 /// enumeration types. 6040 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6041 FunctionDecl *Fn, 6042 ArrayRef<Expr *> Args) { 6043 QualType T1 = Args[0]->getType(); 6044 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6045 6046 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6047 return true; 6048 6049 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6050 return true; 6051 6052 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 6053 if (Proto->getNumParams() < 1) 6054 return false; 6055 6056 if (T1->isEnumeralType()) { 6057 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6058 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6059 return true; 6060 } 6061 6062 if (Proto->getNumParams() < 2) 6063 return false; 6064 6065 if (!T2.isNull() && T2->isEnumeralType()) { 6066 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6067 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6068 return true; 6069 } 6070 6071 return false; 6072 } 6073 6074 /// AddOverloadCandidate - Adds the given function to the set of 6075 /// candidate functions, using the given function call arguments. If 6076 /// @p SuppressUserConversions, then don't allow user-defined 6077 /// conversions via constructors or conversion operators. 6078 /// 6079 /// \param PartialOverloading true if we are performing "partial" overloading 6080 /// based on an incomplete set of function arguments. This feature is used by 6081 /// code completion. 6082 void Sema::AddOverloadCandidate( 6083 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6084 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6085 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6086 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6087 OverloadCandidateParamOrder PO) { 6088 const FunctionProtoType *Proto 6089 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6090 assert(Proto && "Functions without a prototype cannot be overloaded"); 6091 assert(!Function->getDescribedFunctionTemplate() && 6092 "Use AddTemplateOverloadCandidate for function templates"); 6093 6094 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6095 if (!isa<CXXConstructorDecl>(Method)) { 6096 // If we get here, it's because we're calling a member function 6097 // that is named without a member access expression (e.g., 6098 // "this->f") that was either written explicitly or created 6099 // implicitly. This can happen with a qualified call to a member 6100 // function, e.g., X::f(). We use an empty type for the implied 6101 // object argument (C++ [over.call.func]p3), and the acting context 6102 // is irrelevant. 6103 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6104 Expr::Classification::makeSimpleLValue(), Args, 6105 CandidateSet, SuppressUserConversions, 6106 PartialOverloading, EarlyConversions, PO); 6107 return; 6108 } 6109 // We treat a constructor like a non-member function, since its object 6110 // argument doesn't participate in overload resolution. 6111 } 6112 6113 if (!CandidateSet.isNewCandidate(Function, PO)) 6114 return; 6115 6116 // C++11 [class.copy]p11: [DR1402] 6117 // A defaulted move constructor that is defined as deleted is ignored by 6118 // overload resolution. 6119 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6120 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6121 Constructor->isMoveConstructor()) 6122 return; 6123 6124 // Overload resolution is always an unevaluated context. 6125 EnterExpressionEvaluationContext Unevaluated( 6126 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6127 6128 // C++ [over.match.oper]p3: 6129 // if no operand has a class type, only those non-member functions in the 6130 // lookup set that have a first parameter of type T1 or "reference to 6131 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6132 // is a right operand) a second parameter of type T2 or "reference to 6133 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6134 // candidate functions. 6135 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6136 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6137 return; 6138 6139 // Add this candidate 6140 OverloadCandidate &Candidate = 6141 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6142 Candidate.FoundDecl = FoundDecl; 6143 Candidate.Function = Function; 6144 Candidate.Viable = true; 6145 Candidate.RewriteKind = 6146 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6147 Candidate.IsSurrogate = false; 6148 Candidate.IsADLCandidate = IsADLCandidate; 6149 Candidate.IgnoreObjectArgument = false; 6150 Candidate.ExplicitCallArguments = Args.size(); 6151 6152 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6153 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6154 Candidate.Viable = false; 6155 Candidate.FailureKind = ovl_non_default_multiversion_function; 6156 return; 6157 } 6158 6159 if (Constructor) { 6160 // C++ [class.copy]p3: 6161 // A member function template is never instantiated to perform the copy 6162 // of a class object to an object of its class type. 6163 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6164 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6165 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6166 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6167 ClassType))) { 6168 Candidate.Viable = false; 6169 Candidate.FailureKind = ovl_fail_illegal_constructor; 6170 return; 6171 } 6172 6173 // C++ [over.match.funcs]p8: (proposed DR resolution) 6174 // A constructor inherited from class type C that has a first parameter 6175 // of type "reference to P" (including such a constructor instantiated 6176 // from a template) is excluded from the set of candidate functions when 6177 // constructing an object of type cv D if the argument list has exactly 6178 // one argument and D is reference-related to P and P is reference-related 6179 // to C. 6180 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6181 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6182 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6183 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6184 QualType C = Context.getRecordType(Constructor->getParent()); 6185 QualType D = Context.getRecordType(Shadow->getParent()); 6186 SourceLocation Loc = Args.front()->getExprLoc(); 6187 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6188 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6189 Candidate.Viable = false; 6190 Candidate.FailureKind = ovl_fail_inhctor_slice; 6191 return; 6192 } 6193 } 6194 6195 // Check that the constructor is capable of constructing an object in the 6196 // destination address space. 6197 if (!Qualifiers::isAddressSpaceSupersetOf( 6198 Constructor->getMethodQualifiers().getAddressSpace(), 6199 CandidateSet.getDestAS())) { 6200 Candidate.Viable = false; 6201 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6202 } 6203 } 6204 6205 unsigned NumParams = Proto->getNumParams(); 6206 6207 // (C++ 13.3.2p2): A candidate function having fewer than m 6208 // parameters is viable only if it has an ellipsis in its parameter 6209 // list (8.3.5). 6210 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6211 !Proto->isVariadic()) { 6212 Candidate.Viable = false; 6213 Candidate.FailureKind = ovl_fail_too_many_arguments; 6214 return; 6215 } 6216 6217 // (C++ 13.3.2p2): A candidate function having more than m parameters 6218 // is viable only if the (m+1)st parameter has a default argument 6219 // (8.3.6). For the purposes of overload resolution, the 6220 // parameter list is truncated on the right, so that there are 6221 // exactly m parameters. 6222 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6223 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6224 // Not enough arguments. 6225 Candidate.Viable = false; 6226 Candidate.FailureKind = ovl_fail_too_few_arguments; 6227 return; 6228 } 6229 6230 // (CUDA B.1): Check for invalid calls between targets. 6231 if (getLangOpts().CUDA) 6232 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6233 // Skip the check for callers that are implicit members, because in this 6234 // case we may not yet know what the member's target is; the target is 6235 // inferred for the member automatically, based on the bases and fields of 6236 // the class. 6237 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6238 Candidate.Viable = false; 6239 Candidate.FailureKind = ovl_fail_bad_target; 6240 return; 6241 } 6242 6243 // Determine the implicit conversion sequences for each of the 6244 // arguments. 6245 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6246 unsigned ConvIdx = 6247 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6248 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6249 // We already formed a conversion sequence for this parameter during 6250 // template argument deduction. 6251 } else if (ArgIdx < NumParams) { 6252 // (C++ 13.3.2p3): for F to be a viable function, there shall 6253 // exist for each argument an implicit conversion sequence 6254 // (13.3.3.1) that converts that argument to the corresponding 6255 // parameter of F. 6256 QualType ParamType = Proto->getParamType(ArgIdx); 6257 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6258 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6259 /*InOverloadResolution=*/true, 6260 /*AllowObjCWritebackConversion=*/ 6261 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6262 if (Candidate.Conversions[ConvIdx].isBad()) { 6263 Candidate.Viable = false; 6264 Candidate.FailureKind = ovl_fail_bad_conversion; 6265 return; 6266 } 6267 } else { 6268 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6269 // argument for which there is no corresponding parameter is 6270 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6271 Candidate.Conversions[ConvIdx].setEllipsis(); 6272 } 6273 } 6274 6275 if (!AllowExplicit) { 6276 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function); 6277 if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) { 6278 Candidate.Viable = false; 6279 Candidate.FailureKind = ovl_fail_explicit_resolved; 6280 return; 6281 } 6282 } 6283 6284 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6285 Candidate.Viable = false; 6286 Candidate.FailureKind = ovl_fail_enable_if; 6287 Candidate.DeductionFailure.Data = FailedAttr; 6288 return; 6289 } 6290 6291 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6292 Candidate.Viable = false; 6293 Candidate.FailureKind = ovl_fail_ext_disabled; 6294 return; 6295 } 6296 } 6297 6298 ObjCMethodDecl * 6299 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6300 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6301 if (Methods.size() <= 1) 6302 return nullptr; 6303 6304 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6305 bool Match = true; 6306 ObjCMethodDecl *Method = Methods[b]; 6307 unsigned NumNamedArgs = Sel.getNumArgs(); 6308 // Method might have more arguments than selector indicates. This is due 6309 // to addition of c-style arguments in method. 6310 if (Method->param_size() > NumNamedArgs) 6311 NumNamedArgs = Method->param_size(); 6312 if (Args.size() < NumNamedArgs) 6313 continue; 6314 6315 for (unsigned i = 0; i < NumNamedArgs; i++) { 6316 // We can't do any type-checking on a type-dependent argument. 6317 if (Args[i]->isTypeDependent()) { 6318 Match = false; 6319 break; 6320 } 6321 6322 ParmVarDecl *param = Method->parameters()[i]; 6323 Expr *argExpr = Args[i]; 6324 assert(argExpr && "SelectBestMethod(): missing expression"); 6325 6326 // Strip the unbridged-cast placeholder expression off unless it's 6327 // a consumed argument. 6328 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6329 !param->hasAttr<CFConsumedAttr>()) 6330 argExpr = stripARCUnbridgedCast(argExpr); 6331 6332 // If the parameter is __unknown_anytype, move on to the next method. 6333 if (param->getType() == Context.UnknownAnyTy) { 6334 Match = false; 6335 break; 6336 } 6337 6338 ImplicitConversionSequence ConversionState 6339 = TryCopyInitialization(*this, argExpr, param->getType(), 6340 /*SuppressUserConversions*/false, 6341 /*InOverloadResolution=*/true, 6342 /*AllowObjCWritebackConversion=*/ 6343 getLangOpts().ObjCAutoRefCount, 6344 /*AllowExplicit*/false); 6345 // This function looks for a reasonably-exact match, so we consider 6346 // incompatible pointer conversions to be a failure here. 6347 if (ConversionState.isBad() || 6348 (ConversionState.isStandard() && 6349 ConversionState.Standard.Second == 6350 ICK_Incompatible_Pointer_Conversion)) { 6351 Match = false; 6352 break; 6353 } 6354 } 6355 // Promote additional arguments to variadic methods. 6356 if (Match && Method->isVariadic()) { 6357 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6358 if (Args[i]->isTypeDependent()) { 6359 Match = false; 6360 break; 6361 } 6362 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6363 nullptr); 6364 if (Arg.isInvalid()) { 6365 Match = false; 6366 break; 6367 } 6368 } 6369 } else { 6370 // Check for extra arguments to non-variadic methods. 6371 if (Args.size() != NumNamedArgs) 6372 Match = false; 6373 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6374 // Special case when selectors have no argument. In this case, select 6375 // one with the most general result type of 'id'. 6376 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6377 QualType ReturnT = Methods[b]->getReturnType(); 6378 if (ReturnT->isObjCIdType()) 6379 return Methods[b]; 6380 } 6381 } 6382 } 6383 6384 if (Match) 6385 return Method; 6386 } 6387 return nullptr; 6388 } 6389 6390 static bool 6391 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6392 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6393 bool MissingImplicitThis, Expr *&ConvertedThis, 6394 SmallVectorImpl<Expr *> &ConvertedArgs) { 6395 if (ThisArg) { 6396 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6397 assert(!isa<CXXConstructorDecl>(Method) && 6398 "Shouldn't have `this` for ctors!"); 6399 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6400 ExprResult R = S.PerformObjectArgumentInitialization( 6401 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6402 if (R.isInvalid()) 6403 return false; 6404 ConvertedThis = R.get(); 6405 } else { 6406 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6407 (void)MD; 6408 assert((MissingImplicitThis || MD->isStatic() || 6409 isa<CXXConstructorDecl>(MD)) && 6410 "Expected `this` for non-ctor instance methods"); 6411 } 6412 ConvertedThis = nullptr; 6413 } 6414 6415 // Ignore any variadic arguments. Converting them is pointless, since the 6416 // user can't refer to them in the function condition. 6417 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6418 6419 // Convert the arguments. 6420 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6421 ExprResult R; 6422 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6423 S.Context, Function->getParamDecl(I)), 6424 SourceLocation(), Args[I]); 6425 6426 if (R.isInvalid()) 6427 return false; 6428 6429 ConvertedArgs.push_back(R.get()); 6430 } 6431 6432 if (Trap.hasErrorOccurred()) 6433 return false; 6434 6435 // Push default arguments if needed. 6436 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6437 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6438 ParmVarDecl *P = Function->getParamDecl(i); 6439 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6440 ? P->getUninstantiatedDefaultArg() 6441 : P->getDefaultArg(); 6442 // This can only happen in code completion, i.e. when PartialOverloading 6443 // is true. 6444 if (!DefArg) 6445 return false; 6446 ExprResult R = 6447 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6448 S.Context, Function->getParamDecl(i)), 6449 SourceLocation(), DefArg); 6450 if (R.isInvalid()) 6451 return false; 6452 ConvertedArgs.push_back(R.get()); 6453 } 6454 6455 if (Trap.hasErrorOccurred()) 6456 return false; 6457 } 6458 return true; 6459 } 6460 6461 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6462 bool MissingImplicitThis) { 6463 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6464 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6465 return nullptr; 6466 6467 SFINAETrap Trap(*this); 6468 SmallVector<Expr *, 16> ConvertedArgs; 6469 // FIXME: We should look into making enable_if late-parsed. 6470 Expr *DiscardedThis; 6471 if (!convertArgsForAvailabilityChecks( 6472 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6473 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6474 return *EnableIfAttrs.begin(); 6475 6476 for (auto *EIA : EnableIfAttrs) { 6477 APValue Result; 6478 // FIXME: This doesn't consider value-dependent cases, because doing so is 6479 // very difficult. Ideally, we should handle them more gracefully. 6480 if (EIA->getCond()->isValueDependent() || 6481 !EIA->getCond()->EvaluateWithSubstitution( 6482 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6483 return EIA; 6484 6485 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6486 return EIA; 6487 } 6488 return nullptr; 6489 } 6490 6491 template <typename CheckFn> 6492 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6493 bool ArgDependent, SourceLocation Loc, 6494 CheckFn &&IsSuccessful) { 6495 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6496 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6497 if (ArgDependent == DIA->getArgDependent()) 6498 Attrs.push_back(DIA); 6499 } 6500 6501 // Common case: No diagnose_if attributes, so we can quit early. 6502 if (Attrs.empty()) 6503 return false; 6504 6505 auto WarningBegin = std::stable_partition( 6506 Attrs.begin(), Attrs.end(), 6507 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6508 6509 // Note that diagnose_if attributes are late-parsed, so they appear in the 6510 // correct order (unlike enable_if attributes). 6511 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6512 IsSuccessful); 6513 if (ErrAttr != WarningBegin) { 6514 const DiagnoseIfAttr *DIA = *ErrAttr; 6515 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6516 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6517 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6518 return true; 6519 } 6520 6521 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6522 if (IsSuccessful(DIA)) { 6523 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6524 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6525 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6526 } 6527 6528 return false; 6529 } 6530 6531 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6532 const Expr *ThisArg, 6533 ArrayRef<const Expr *> Args, 6534 SourceLocation Loc) { 6535 return diagnoseDiagnoseIfAttrsWith( 6536 *this, Function, /*ArgDependent=*/true, Loc, 6537 [&](const DiagnoseIfAttr *DIA) { 6538 APValue Result; 6539 // It's sane to use the same Args for any redecl of this function, since 6540 // EvaluateWithSubstitution only cares about the position of each 6541 // argument in the arg list, not the ParmVarDecl* it maps to. 6542 if (!DIA->getCond()->EvaluateWithSubstitution( 6543 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6544 return false; 6545 return Result.isInt() && Result.getInt().getBoolValue(); 6546 }); 6547 } 6548 6549 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6550 SourceLocation Loc) { 6551 return diagnoseDiagnoseIfAttrsWith( 6552 *this, ND, /*ArgDependent=*/false, Loc, 6553 [&](const DiagnoseIfAttr *DIA) { 6554 bool Result; 6555 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6556 Result; 6557 }); 6558 } 6559 6560 /// Add all of the function declarations in the given function set to 6561 /// the overload candidate set. 6562 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6563 ArrayRef<Expr *> Args, 6564 OverloadCandidateSet &CandidateSet, 6565 TemplateArgumentListInfo *ExplicitTemplateArgs, 6566 bool SuppressUserConversions, 6567 bool PartialOverloading, 6568 bool FirstArgumentIsBase) { 6569 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6570 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6571 ArrayRef<Expr *> FunctionArgs = Args; 6572 6573 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6574 FunctionDecl *FD = 6575 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6576 6577 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6578 QualType ObjectType; 6579 Expr::Classification ObjectClassification; 6580 if (Args.size() > 0) { 6581 if (Expr *E = Args[0]) { 6582 // Use the explicit base to restrict the lookup: 6583 ObjectType = E->getType(); 6584 // Pointers in the object arguments are implicitly dereferenced, so we 6585 // always classify them as l-values. 6586 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6587 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6588 else 6589 ObjectClassification = E->Classify(Context); 6590 } // .. else there is an implicit base. 6591 FunctionArgs = Args.slice(1); 6592 } 6593 if (FunTmpl) { 6594 AddMethodTemplateCandidate( 6595 FunTmpl, F.getPair(), 6596 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6597 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6598 FunctionArgs, CandidateSet, SuppressUserConversions, 6599 PartialOverloading); 6600 } else { 6601 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6602 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6603 ObjectClassification, FunctionArgs, CandidateSet, 6604 SuppressUserConversions, PartialOverloading); 6605 } 6606 } else { 6607 // This branch handles both standalone functions and static methods. 6608 6609 // Slice the first argument (which is the base) when we access 6610 // static method as non-static. 6611 if (Args.size() > 0 && 6612 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6613 !isa<CXXConstructorDecl>(FD)))) { 6614 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6615 FunctionArgs = Args.slice(1); 6616 } 6617 if (FunTmpl) { 6618 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6619 ExplicitTemplateArgs, FunctionArgs, 6620 CandidateSet, SuppressUserConversions, 6621 PartialOverloading); 6622 } else { 6623 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6624 SuppressUserConversions, PartialOverloading); 6625 } 6626 } 6627 } 6628 } 6629 6630 /// AddMethodCandidate - Adds a named decl (which is some kind of 6631 /// method) as a method candidate to the given overload set. 6632 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6633 Expr::Classification ObjectClassification, 6634 ArrayRef<Expr *> Args, 6635 OverloadCandidateSet &CandidateSet, 6636 bool SuppressUserConversions, 6637 OverloadCandidateParamOrder PO) { 6638 NamedDecl *Decl = FoundDecl.getDecl(); 6639 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6640 6641 if (isa<UsingShadowDecl>(Decl)) 6642 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6643 6644 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6645 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6646 "Expected a member function template"); 6647 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6648 /*ExplicitArgs*/ nullptr, ObjectType, 6649 ObjectClassification, Args, CandidateSet, 6650 SuppressUserConversions, false, PO); 6651 } else { 6652 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6653 ObjectType, ObjectClassification, Args, CandidateSet, 6654 SuppressUserConversions, false, None, PO); 6655 } 6656 } 6657 6658 /// AddMethodCandidate - Adds the given C++ member function to the set 6659 /// of candidate functions, using the given function call arguments 6660 /// and the object argument (@c Object). For example, in a call 6661 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6662 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6663 /// allow user-defined conversions via constructors or conversion 6664 /// operators. 6665 void 6666 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6667 CXXRecordDecl *ActingContext, QualType ObjectType, 6668 Expr::Classification ObjectClassification, 6669 ArrayRef<Expr *> Args, 6670 OverloadCandidateSet &CandidateSet, 6671 bool SuppressUserConversions, 6672 bool PartialOverloading, 6673 ConversionSequenceList EarlyConversions, 6674 OverloadCandidateParamOrder PO) { 6675 const FunctionProtoType *Proto 6676 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6677 assert(Proto && "Methods without a prototype cannot be overloaded"); 6678 assert(!isa<CXXConstructorDecl>(Method) && 6679 "Use AddOverloadCandidate for constructors"); 6680 6681 if (!CandidateSet.isNewCandidate(Method, PO)) 6682 return; 6683 6684 // C++11 [class.copy]p23: [DR1402] 6685 // A defaulted move assignment operator that is defined as deleted is 6686 // ignored by overload resolution. 6687 if (Method->isDefaulted() && Method->isDeleted() && 6688 Method->isMoveAssignmentOperator()) 6689 return; 6690 6691 // Overload resolution is always an unevaluated context. 6692 EnterExpressionEvaluationContext Unevaluated( 6693 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6694 6695 // Add this candidate 6696 OverloadCandidate &Candidate = 6697 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6698 Candidate.FoundDecl = FoundDecl; 6699 Candidate.Function = Method; 6700 Candidate.RewriteKind = 6701 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6702 Candidate.IsSurrogate = false; 6703 Candidate.IgnoreObjectArgument = false; 6704 Candidate.ExplicitCallArguments = Args.size(); 6705 6706 unsigned NumParams = Proto->getNumParams(); 6707 6708 // (C++ 13.3.2p2): A candidate function having fewer than m 6709 // parameters is viable only if it has an ellipsis in its parameter 6710 // list (8.3.5). 6711 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6712 !Proto->isVariadic()) { 6713 Candidate.Viable = false; 6714 Candidate.FailureKind = ovl_fail_too_many_arguments; 6715 return; 6716 } 6717 6718 // (C++ 13.3.2p2): A candidate function having more than m parameters 6719 // is viable only if the (m+1)st parameter has a default argument 6720 // (8.3.6). For the purposes of overload resolution, the 6721 // parameter list is truncated on the right, so that there are 6722 // exactly m parameters. 6723 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6724 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6725 // Not enough arguments. 6726 Candidate.Viable = false; 6727 Candidate.FailureKind = ovl_fail_too_few_arguments; 6728 return; 6729 } 6730 6731 Candidate.Viable = true; 6732 6733 if (Method->isStatic() || ObjectType.isNull()) 6734 // The implicit object argument is ignored. 6735 Candidate.IgnoreObjectArgument = true; 6736 else { 6737 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6738 // Determine the implicit conversion sequence for the object 6739 // parameter. 6740 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6741 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6742 Method, ActingContext); 6743 if (Candidate.Conversions[ConvIdx].isBad()) { 6744 Candidate.Viable = false; 6745 Candidate.FailureKind = ovl_fail_bad_conversion; 6746 return; 6747 } 6748 } 6749 6750 // (CUDA B.1): Check for invalid calls between targets. 6751 if (getLangOpts().CUDA) 6752 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6753 if (!IsAllowedCUDACall(Caller, Method)) { 6754 Candidate.Viable = false; 6755 Candidate.FailureKind = ovl_fail_bad_target; 6756 return; 6757 } 6758 6759 // Determine the implicit conversion sequences for each of the 6760 // arguments. 6761 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6762 unsigned ConvIdx = 6763 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6764 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6765 // We already formed a conversion sequence for this parameter during 6766 // template argument deduction. 6767 } else if (ArgIdx < NumParams) { 6768 // (C++ 13.3.2p3): for F to be a viable function, there shall 6769 // exist for each argument an implicit conversion sequence 6770 // (13.3.3.1) that converts that argument to the corresponding 6771 // parameter of F. 6772 QualType ParamType = Proto->getParamType(ArgIdx); 6773 Candidate.Conversions[ConvIdx] 6774 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6775 SuppressUserConversions, 6776 /*InOverloadResolution=*/true, 6777 /*AllowObjCWritebackConversion=*/ 6778 getLangOpts().ObjCAutoRefCount); 6779 if (Candidate.Conversions[ConvIdx].isBad()) { 6780 Candidate.Viable = false; 6781 Candidate.FailureKind = ovl_fail_bad_conversion; 6782 return; 6783 } 6784 } else { 6785 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6786 // argument for which there is no corresponding parameter is 6787 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6788 Candidate.Conversions[ConvIdx].setEllipsis(); 6789 } 6790 } 6791 6792 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6793 Candidate.Viable = false; 6794 Candidate.FailureKind = ovl_fail_enable_if; 6795 Candidate.DeductionFailure.Data = FailedAttr; 6796 return; 6797 } 6798 6799 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6800 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6801 Candidate.Viable = false; 6802 Candidate.FailureKind = ovl_non_default_multiversion_function; 6803 } 6804 } 6805 6806 /// Add a C++ member function template as a candidate to the candidate 6807 /// set, using template argument deduction to produce an appropriate member 6808 /// function template specialization. 6809 void Sema::AddMethodTemplateCandidate( 6810 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 6811 CXXRecordDecl *ActingContext, 6812 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 6813 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 6814 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6815 bool PartialOverloading, OverloadCandidateParamOrder PO) { 6816 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 6817 return; 6818 6819 // C++ [over.match.funcs]p7: 6820 // In each case where a candidate is a function template, candidate 6821 // function template specializations are generated using template argument 6822 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6823 // candidate functions in the usual way.113) A given name can refer to one 6824 // or more function templates and also to a set of overloaded non-template 6825 // functions. In such a case, the candidate functions generated from each 6826 // function template are combined with the set of non-template candidate 6827 // functions. 6828 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6829 FunctionDecl *Specialization = nullptr; 6830 ConversionSequenceList Conversions; 6831 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6832 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6833 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6834 return CheckNonDependentConversions( 6835 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6836 SuppressUserConversions, ActingContext, ObjectType, 6837 ObjectClassification, PO); 6838 })) { 6839 OverloadCandidate &Candidate = 6840 CandidateSet.addCandidate(Conversions.size(), Conversions); 6841 Candidate.FoundDecl = FoundDecl; 6842 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6843 Candidate.Viable = false; 6844 Candidate.RewriteKind = 6845 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6846 Candidate.IsSurrogate = false; 6847 Candidate.IgnoreObjectArgument = 6848 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6849 ObjectType.isNull(); 6850 Candidate.ExplicitCallArguments = Args.size(); 6851 if (Result == TDK_NonDependentConversionFailure) 6852 Candidate.FailureKind = ovl_fail_bad_conversion; 6853 else { 6854 Candidate.FailureKind = ovl_fail_bad_deduction; 6855 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6856 Info); 6857 } 6858 return; 6859 } 6860 6861 // Add the function template specialization produced by template argument 6862 // deduction as a candidate. 6863 assert(Specialization && "Missing member function template specialization?"); 6864 assert(isa<CXXMethodDecl>(Specialization) && 6865 "Specialization is not a member function?"); 6866 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6867 ActingContext, ObjectType, ObjectClassification, Args, 6868 CandidateSet, SuppressUserConversions, PartialOverloading, 6869 Conversions, PO); 6870 } 6871 6872 /// Add a C++ function template specialization as a candidate 6873 /// in the candidate set, using template argument deduction to produce 6874 /// an appropriate function template specialization. 6875 void Sema::AddTemplateOverloadCandidate( 6876 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6877 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6878 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6879 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 6880 OverloadCandidateParamOrder PO) { 6881 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 6882 return; 6883 6884 // C++ [over.match.funcs]p7: 6885 // In each case where a candidate is a function template, candidate 6886 // function template specializations are generated using template argument 6887 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6888 // candidate functions in the usual way.113) A given name can refer to one 6889 // or more function templates and also to a set of overloaded non-template 6890 // functions. In such a case, the candidate functions generated from each 6891 // function template are combined with the set of non-template candidate 6892 // functions. 6893 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6894 FunctionDecl *Specialization = nullptr; 6895 ConversionSequenceList Conversions; 6896 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6897 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6898 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6899 return CheckNonDependentConversions( 6900 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 6901 SuppressUserConversions, nullptr, QualType(), {}, PO); 6902 })) { 6903 OverloadCandidate &Candidate = 6904 CandidateSet.addCandidate(Conversions.size(), Conversions); 6905 Candidate.FoundDecl = FoundDecl; 6906 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6907 Candidate.Viable = false; 6908 Candidate.RewriteKind = 6909 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6910 Candidate.IsSurrogate = false; 6911 Candidate.IsADLCandidate = IsADLCandidate; 6912 // Ignore the object argument if there is one, since we don't have an object 6913 // type. 6914 Candidate.IgnoreObjectArgument = 6915 isa<CXXMethodDecl>(Candidate.Function) && 6916 !isa<CXXConstructorDecl>(Candidate.Function); 6917 Candidate.ExplicitCallArguments = Args.size(); 6918 if (Result == TDK_NonDependentConversionFailure) 6919 Candidate.FailureKind = ovl_fail_bad_conversion; 6920 else { 6921 Candidate.FailureKind = ovl_fail_bad_deduction; 6922 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6923 Info); 6924 } 6925 return; 6926 } 6927 6928 // Add the function template specialization produced by template argument 6929 // deduction as a candidate. 6930 assert(Specialization && "Missing function template specialization?"); 6931 AddOverloadCandidate( 6932 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 6933 PartialOverloading, AllowExplicit, 6934 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 6935 } 6936 6937 /// Check that implicit conversion sequences can be formed for each argument 6938 /// whose corresponding parameter has a non-dependent type, per DR1391's 6939 /// [temp.deduct.call]p10. 6940 bool Sema::CheckNonDependentConversions( 6941 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6942 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6943 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6944 CXXRecordDecl *ActingContext, QualType ObjectType, 6945 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 6946 // FIXME: The cases in which we allow explicit conversions for constructor 6947 // arguments never consider calling a constructor template. It's not clear 6948 // that is correct. 6949 const bool AllowExplicit = false; 6950 6951 auto *FD = FunctionTemplate->getTemplatedDecl(); 6952 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6953 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6954 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6955 6956 Conversions = 6957 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6958 6959 // Overload resolution is always an unevaluated context. 6960 EnterExpressionEvaluationContext Unevaluated( 6961 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6962 6963 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6964 // require that, but this check should never result in a hard error, and 6965 // overload resolution is permitted to sidestep instantiations. 6966 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6967 !ObjectType.isNull()) { 6968 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6969 Conversions[ConvIdx] = TryObjectArgumentInitialization( 6970 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6971 Method, ActingContext); 6972 if (Conversions[ConvIdx].isBad()) 6973 return true; 6974 } 6975 6976 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6977 ++I) { 6978 QualType ParamType = ParamTypes[I]; 6979 if (!ParamType->isDependentType()) { 6980 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 6981 ? 0 6982 : (ThisConversions + I); 6983 Conversions[ConvIdx] 6984 = TryCopyInitialization(*this, Args[I], ParamType, 6985 SuppressUserConversions, 6986 /*InOverloadResolution=*/true, 6987 /*AllowObjCWritebackConversion=*/ 6988 getLangOpts().ObjCAutoRefCount, 6989 AllowExplicit); 6990 if (Conversions[ConvIdx].isBad()) 6991 return true; 6992 } 6993 } 6994 6995 return false; 6996 } 6997 6998 /// Determine whether this is an allowable conversion from the result 6999 /// of an explicit conversion operator to the expected type, per C++ 7000 /// [over.match.conv]p1 and [over.match.ref]p1. 7001 /// 7002 /// \param ConvType The return type of the conversion function. 7003 /// 7004 /// \param ToType The type we are converting to. 7005 /// 7006 /// \param AllowObjCPointerConversion Allow a conversion from one 7007 /// Objective-C pointer to another. 7008 /// 7009 /// \returns true if the conversion is allowable, false otherwise. 7010 static bool isAllowableExplicitConversion(Sema &S, 7011 QualType ConvType, QualType ToType, 7012 bool AllowObjCPointerConversion) { 7013 QualType ToNonRefType = ToType.getNonReferenceType(); 7014 7015 // Easy case: the types are the same. 7016 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7017 return true; 7018 7019 // Allow qualification conversions. 7020 bool ObjCLifetimeConversion; 7021 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7022 ObjCLifetimeConversion)) 7023 return true; 7024 7025 // If we're not allowed to consider Objective-C pointer conversions, 7026 // we're done. 7027 if (!AllowObjCPointerConversion) 7028 return false; 7029 7030 // Is this an Objective-C pointer conversion? 7031 bool IncompatibleObjC = false; 7032 QualType ConvertedType; 7033 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7034 IncompatibleObjC); 7035 } 7036 7037 /// AddConversionCandidate - Add a C++ conversion function as a 7038 /// candidate in the candidate set (C++ [over.match.conv], 7039 /// C++ [over.match.copy]). From is the expression we're converting from, 7040 /// and ToType is the type that we're eventually trying to convert to 7041 /// (which may or may not be the same type as the type that the 7042 /// conversion function produces). 7043 void Sema::AddConversionCandidate( 7044 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7045 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7046 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7047 bool AllowExplicit, bool AllowResultConversion) { 7048 assert(!Conversion->getDescribedFunctionTemplate() && 7049 "Conversion function templates use AddTemplateConversionCandidate"); 7050 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7051 if (!CandidateSet.isNewCandidate(Conversion)) 7052 return; 7053 7054 // If the conversion function has an undeduced return type, trigger its 7055 // deduction now. 7056 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7057 if (DeduceReturnType(Conversion, From->getExprLoc())) 7058 return; 7059 ConvType = Conversion->getConversionType().getNonReferenceType(); 7060 } 7061 7062 // If we don't allow any conversion of the result type, ignore conversion 7063 // functions that don't convert to exactly (possibly cv-qualified) T. 7064 if (!AllowResultConversion && 7065 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7066 return; 7067 7068 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7069 // operator is only a candidate if its return type is the target type or 7070 // can be converted to the target type with a qualification conversion. 7071 if (Conversion->isExplicit() && 7072 !isAllowableExplicitConversion(*this, ConvType, ToType, 7073 AllowObjCConversionOnExplicit)) 7074 return; 7075 7076 // Overload resolution is always an unevaluated context. 7077 EnterExpressionEvaluationContext Unevaluated( 7078 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7079 7080 // Add this candidate 7081 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7082 Candidate.FoundDecl = FoundDecl; 7083 Candidate.Function = Conversion; 7084 Candidate.IsSurrogate = false; 7085 Candidate.IgnoreObjectArgument = false; 7086 Candidate.FinalConversion.setAsIdentityConversion(); 7087 Candidate.FinalConversion.setFromType(ConvType); 7088 Candidate.FinalConversion.setAllToTypes(ToType); 7089 Candidate.Viable = true; 7090 Candidate.ExplicitCallArguments = 1; 7091 7092 // C++ [over.match.funcs]p4: 7093 // For conversion functions, the function is considered to be a member of 7094 // the class of the implicit implied object argument for the purpose of 7095 // defining the type of the implicit object parameter. 7096 // 7097 // Determine the implicit conversion sequence for the implicit 7098 // object parameter. 7099 QualType ImplicitParamType = From->getType(); 7100 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7101 ImplicitParamType = FromPtrType->getPointeeType(); 7102 CXXRecordDecl *ConversionContext 7103 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7104 7105 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7106 *this, CandidateSet.getLocation(), From->getType(), 7107 From->Classify(Context), Conversion, ConversionContext); 7108 7109 if (Candidate.Conversions[0].isBad()) { 7110 Candidate.Viable = false; 7111 Candidate.FailureKind = ovl_fail_bad_conversion; 7112 return; 7113 } 7114 7115 // We won't go through a user-defined type conversion function to convert a 7116 // derived to base as such conversions are given Conversion Rank. They only 7117 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7118 QualType FromCanon 7119 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7120 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7121 if (FromCanon == ToCanon || 7122 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7123 Candidate.Viable = false; 7124 Candidate.FailureKind = ovl_fail_trivial_conversion; 7125 return; 7126 } 7127 7128 // To determine what the conversion from the result of calling the 7129 // conversion function to the type we're eventually trying to 7130 // convert to (ToType), we need to synthesize a call to the 7131 // conversion function and attempt copy initialization from it. This 7132 // makes sure that we get the right semantics with respect to 7133 // lvalues/rvalues and the type. Fortunately, we can allocate this 7134 // call on the stack and we don't need its arguments to be 7135 // well-formed. 7136 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7137 VK_LValue, From->getBeginLoc()); 7138 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7139 Context.getPointerType(Conversion->getType()), 7140 CK_FunctionToPointerDecay, 7141 &ConversionRef, VK_RValue); 7142 7143 QualType ConversionType = Conversion->getConversionType(); 7144 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7145 Candidate.Viable = false; 7146 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7147 return; 7148 } 7149 7150 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7151 7152 // Note that it is safe to allocate CallExpr on the stack here because 7153 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7154 // allocator). 7155 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7156 7157 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7158 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7159 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7160 7161 ImplicitConversionSequence ICS = 7162 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7163 /*SuppressUserConversions=*/true, 7164 /*InOverloadResolution=*/false, 7165 /*AllowObjCWritebackConversion=*/false); 7166 7167 switch (ICS.getKind()) { 7168 case ImplicitConversionSequence::StandardConversion: 7169 Candidate.FinalConversion = ICS.Standard; 7170 7171 // C++ [over.ics.user]p3: 7172 // If the user-defined conversion is specified by a specialization of a 7173 // conversion function template, the second standard conversion sequence 7174 // shall have exact match rank. 7175 if (Conversion->getPrimaryTemplate() && 7176 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7177 Candidate.Viable = false; 7178 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7179 return; 7180 } 7181 7182 // C++0x [dcl.init.ref]p5: 7183 // In the second case, if the reference is an rvalue reference and 7184 // the second standard conversion sequence of the user-defined 7185 // conversion sequence includes an lvalue-to-rvalue conversion, the 7186 // program is ill-formed. 7187 if (ToType->isRValueReferenceType() && 7188 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7189 Candidate.Viable = false; 7190 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7191 return; 7192 } 7193 break; 7194 7195 case ImplicitConversionSequence::BadConversion: 7196 Candidate.Viable = false; 7197 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7198 return; 7199 7200 default: 7201 llvm_unreachable( 7202 "Can only end up with a standard conversion sequence or failure"); 7203 } 7204 7205 if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() != 7206 ExplicitSpecKind::ResolvedFalse) { 7207 Candidate.Viable = false; 7208 Candidate.FailureKind = ovl_fail_explicit_resolved; 7209 return; 7210 } 7211 7212 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7213 Candidate.Viable = false; 7214 Candidate.FailureKind = ovl_fail_enable_if; 7215 Candidate.DeductionFailure.Data = FailedAttr; 7216 return; 7217 } 7218 7219 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7220 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7221 Candidate.Viable = false; 7222 Candidate.FailureKind = ovl_non_default_multiversion_function; 7223 } 7224 } 7225 7226 /// Adds a conversion function template specialization 7227 /// candidate to the overload set, using template argument deduction 7228 /// to deduce the template arguments of the conversion function 7229 /// template from the type that we are converting to (C++ 7230 /// [temp.deduct.conv]). 7231 void Sema::AddTemplateConversionCandidate( 7232 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7233 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7234 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7235 bool AllowExplicit, bool AllowResultConversion) { 7236 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7237 "Only conversion function templates permitted here"); 7238 7239 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7240 return; 7241 7242 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7243 CXXConversionDecl *Specialization = nullptr; 7244 if (TemplateDeductionResult Result 7245 = DeduceTemplateArguments(FunctionTemplate, ToType, 7246 Specialization, Info)) { 7247 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7248 Candidate.FoundDecl = FoundDecl; 7249 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7250 Candidate.Viable = false; 7251 Candidate.FailureKind = ovl_fail_bad_deduction; 7252 Candidate.IsSurrogate = false; 7253 Candidate.IgnoreObjectArgument = false; 7254 Candidate.ExplicitCallArguments = 1; 7255 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7256 Info); 7257 return; 7258 } 7259 7260 // Add the conversion function template specialization produced by 7261 // template argument deduction as a candidate. 7262 assert(Specialization && "Missing function template specialization?"); 7263 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7264 CandidateSet, AllowObjCConversionOnExplicit, 7265 AllowExplicit, AllowResultConversion); 7266 } 7267 7268 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7269 /// converts the given @c Object to a function pointer via the 7270 /// conversion function @c Conversion, and then attempts to call it 7271 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7272 /// the type of function that we'll eventually be calling. 7273 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7274 DeclAccessPair FoundDecl, 7275 CXXRecordDecl *ActingContext, 7276 const FunctionProtoType *Proto, 7277 Expr *Object, 7278 ArrayRef<Expr *> Args, 7279 OverloadCandidateSet& CandidateSet) { 7280 if (!CandidateSet.isNewCandidate(Conversion)) 7281 return; 7282 7283 // Overload resolution is always an unevaluated context. 7284 EnterExpressionEvaluationContext Unevaluated( 7285 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7286 7287 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7288 Candidate.FoundDecl = FoundDecl; 7289 Candidate.Function = nullptr; 7290 Candidate.Surrogate = Conversion; 7291 Candidate.Viable = true; 7292 Candidate.IsSurrogate = true; 7293 Candidate.IgnoreObjectArgument = false; 7294 Candidate.ExplicitCallArguments = Args.size(); 7295 7296 // Determine the implicit conversion sequence for the implicit 7297 // object parameter. 7298 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7299 *this, CandidateSet.getLocation(), Object->getType(), 7300 Object->Classify(Context), Conversion, ActingContext); 7301 if (ObjectInit.isBad()) { 7302 Candidate.Viable = false; 7303 Candidate.FailureKind = ovl_fail_bad_conversion; 7304 Candidate.Conversions[0] = ObjectInit; 7305 return; 7306 } 7307 7308 // The first conversion is actually a user-defined conversion whose 7309 // first conversion is ObjectInit's standard conversion (which is 7310 // effectively a reference binding). Record it as such. 7311 Candidate.Conversions[0].setUserDefined(); 7312 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7313 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7314 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7315 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7316 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7317 Candidate.Conversions[0].UserDefined.After 7318 = Candidate.Conversions[0].UserDefined.Before; 7319 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7320 7321 // Find the 7322 unsigned NumParams = Proto->getNumParams(); 7323 7324 // (C++ 13.3.2p2): A candidate function having fewer than m 7325 // parameters is viable only if it has an ellipsis in its parameter 7326 // list (8.3.5). 7327 if (Args.size() > NumParams && !Proto->isVariadic()) { 7328 Candidate.Viable = false; 7329 Candidate.FailureKind = ovl_fail_too_many_arguments; 7330 return; 7331 } 7332 7333 // Function types don't have any default arguments, so just check if 7334 // we have enough arguments. 7335 if (Args.size() < NumParams) { 7336 // Not enough arguments. 7337 Candidate.Viable = false; 7338 Candidate.FailureKind = ovl_fail_too_few_arguments; 7339 return; 7340 } 7341 7342 // Determine the implicit conversion sequences for each of the 7343 // arguments. 7344 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7345 if (ArgIdx < NumParams) { 7346 // (C++ 13.3.2p3): for F to be a viable function, there shall 7347 // exist for each argument an implicit conversion sequence 7348 // (13.3.3.1) that converts that argument to the corresponding 7349 // parameter of F. 7350 QualType ParamType = Proto->getParamType(ArgIdx); 7351 Candidate.Conversions[ArgIdx + 1] 7352 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7353 /*SuppressUserConversions=*/false, 7354 /*InOverloadResolution=*/false, 7355 /*AllowObjCWritebackConversion=*/ 7356 getLangOpts().ObjCAutoRefCount); 7357 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7358 Candidate.Viable = false; 7359 Candidate.FailureKind = ovl_fail_bad_conversion; 7360 return; 7361 } 7362 } else { 7363 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7364 // argument for which there is no corresponding parameter is 7365 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7366 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7367 } 7368 } 7369 7370 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7371 Candidate.Viable = false; 7372 Candidate.FailureKind = ovl_fail_enable_if; 7373 Candidate.DeductionFailure.Data = FailedAttr; 7374 return; 7375 } 7376 } 7377 7378 /// Add all of the non-member operator function declarations in the given 7379 /// function set to the overload candidate set. 7380 void Sema::AddNonMemberOperatorCandidates( 7381 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7382 OverloadCandidateSet &CandidateSet, 7383 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7384 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7385 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7386 ArrayRef<Expr *> FunctionArgs = Args; 7387 7388 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7389 FunctionDecl *FD = 7390 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7391 7392 // Don't consider rewritten functions if we're not rewriting. 7393 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7394 continue; 7395 7396 assert(!isa<CXXMethodDecl>(FD) && 7397 "unqualified operator lookup found a member function"); 7398 7399 if (FunTmpl) { 7400 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7401 FunctionArgs, CandidateSet); 7402 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7403 AddTemplateOverloadCandidate( 7404 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7405 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7406 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7407 } else { 7408 if (ExplicitTemplateArgs) 7409 continue; 7410 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7411 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7412 AddOverloadCandidate(FD, F.getPair(), 7413 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7414 false, false, true, false, ADLCallKind::NotADL, 7415 None, OverloadCandidateParamOrder::Reversed); 7416 } 7417 } 7418 } 7419 7420 /// Add overload candidates for overloaded operators that are 7421 /// member functions. 7422 /// 7423 /// Add the overloaded operator candidates that are member functions 7424 /// for the operator Op that was used in an operator expression such 7425 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7426 /// CandidateSet will store the added overload candidates. (C++ 7427 /// [over.match.oper]). 7428 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7429 SourceLocation OpLoc, 7430 ArrayRef<Expr *> Args, 7431 OverloadCandidateSet &CandidateSet, 7432 OverloadCandidateParamOrder PO) { 7433 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7434 7435 // C++ [over.match.oper]p3: 7436 // For a unary operator @ with an operand of a type whose 7437 // cv-unqualified version is T1, and for a binary operator @ with 7438 // a left operand of a type whose cv-unqualified version is T1 and 7439 // a right operand of a type whose cv-unqualified version is T2, 7440 // three sets of candidate functions, designated member 7441 // candidates, non-member candidates and built-in candidates, are 7442 // constructed as follows: 7443 QualType T1 = Args[0]->getType(); 7444 7445 // -- If T1 is a complete class type or a class currently being 7446 // defined, the set of member candidates is the result of the 7447 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7448 // the set of member candidates is empty. 7449 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7450 // Complete the type if it can be completed. 7451 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7452 return; 7453 // If the type is neither complete nor being defined, bail out now. 7454 if (!T1Rec->getDecl()->getDefinition()) 7455 return; 7456 7457 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7458 LookupQualifiedName(Operators, T1Rec->getDecl()); 7459 Operators.suppressDiagnostics(); 7460 7461 for (LookupResult::iterator Oper = Operators.begin(), 7462 OperEnd = Operators.end(); 7463 Oper != OperEnd; 7464 ++Oper) 7465 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7466 Args[0]->Classify(Context), Args.slice(1), 7467 CandidateSet, /*SuppressUserConversion=*/false, PO); 7468 } 7469 } 7470 7471 /// AddBuiltinCandidate - Add a candidate for a built-in 7472 /// operator. ResultTy and ParamTys are the result and parameter types 7473 /// of the built-in candidate, respectively. Args and NumArgs are the 7474 /// arguments being passed to the candidate. IsAssignmentOperator 7475 /// should be true when this built-in candidate is an assignment 7476 /// operator. NumContextualBoolArguments is the number of arguments 7477 /// (at the beginning of the argument list) that will be contextually 7478 /// converted to bool. 7479 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7480 OverloadCandidateSet& CandidateSet, 7481 bool IsAssignmentOperator, 7482 unsigned NumContextualBoolArguments) { 7483 // Overload resolution is always an unevaluated context. 7484 EnterExpressionEvaluationContext Unevaluated( 7485 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7486 7487 // Add this candidate 7488 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7489 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7490 Candidate.Function = nullptr; 7491 Candidate.IsSurrogate = false; 7492 Candidate.IgnoreObjectArgument = false; 7493 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7494 7495 // Determine the implicit conversion sequences for each of the 7496 // arguments. 7497 Candidate.Viable = true; 7498 Candidate.ExplicitCallArguments = Args.size(); 7499 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7500 // C++ [over.match.oper]p4: 7501 // For the built-in assignment operators, conversions of the 7502 // left operand are restricted as follows: 7503 // -- no temporaries are introduced to hold the left operand, and 7504 // -- no user-defined conversions are applied to the left 7505 // operand to achieve a type match with the left-most 7506 // parameter of a built-in candidate. 7507 // 7508 // We block these conversions by turning off user-defined 7509 // conversions, since that is the only way that initialization of 7510 // a reference to a non-class type can occur from something that 7511 // is not of the same type. 7512 if (ArgIdx < NumContextualBoolArguments) { 7513 assert(ParamTys[ArgIdx] == Context.BoolTy && 7514 "Contextual conversion to bool requires bool type"); 7515 Candidate.Conversions[ArgIdx] 7516 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7517 } else { 7518 Candidate.Conversions[ArgIdx] 7519 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7520 ArgIdx == 0 && IsAssignmentOperator, 7521 /*InOverloadResolution=*/false, 7522 /*AllowObjCWritebackConversion=*/ 7523 getLangOpts().ObjCAutoRefCount); 7524 } 7525 if (Candidate.Conversions[ArgIdx].isBad()) { 7526 Candidate.Viable = false; 7527 Candidate.FailureKind = ovl_fail_bad_conversion; 7528 break; 7529 } 7530 } 7531 } 7532 7533 namespace { 7534 7535 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7536 /// candidate operator functions for built-in operators (C++ 7537 /// [over.built]). The types are separated into pointer types and 7538 /// enumeration types. 7539 class BuiltinCandidateTypeSet { 7540 /// TypeSet - A set of types. 7541 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7542 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7543 7544 /// PointerTypes - The set of pointer types that will be used in the 7545 /// built-in candidates. 7546 TypeSet PointerTypes; 7547 7548 /// MemberPointerTypes - The set of member pointer types that will be 7549 /// used in the built-in candidates. 7550 TypeSet MemberPointerTypes; 7551 7552 /// EnumerationTypes - The set of enumeration types that will be 7553 /// used in the built-in candidates. 7554 TypeSet EnumerationTypes; 7555 7556 /// The set of vector types that will be used in the built-in 7557 /// candidates. 7558 TypeSet VectorTypes; 7559 7560 /// A flag indicating non-record types are viable candidates 7561 bool HasNonRecordTypes; 7562 7563 /// A flag indicating whether either arithmetic or enumeration types 7564 /// were present in the candidate set. 7565 bool HasArithmeticOrEnumeralTypes; 7566 7567 /// A flag indicating whether the nullptr type was present in the 7568 /// candidate set. 7569 bool HasNullPtrType; 7570 7571 /// Sema - The semantic analysis instance where we are building the 7572 /// candidate type set. 7573 Sema &SemaRef; 7574 7575 /// Context - The AST context in which we will build the type sets. 7576 ASTContext &Context; 7577 7578 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7579 const Qualifiers &VisibleQuals); 7580 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7581 7582 public: 7583 /// iterator - Iterates through the types that are part of the set. 7584 typedef TypeSet::iterator iterator; 7585 7586 BuiltinCandidateTypeSet(Sema &SemaRef) 7587 : HasNonRecordTypes(false), 7588 HasArithmeticOrEnumeralTypes(false), 7589 HasNullPtrType(false), 7590 SemaRef(SemaRef), 7591 Context(SemaRef.Context) { } 7592 7593 void AddTypesConvertedFrom(QualType Ty, 7594 SourceLocation Loc, 7595 bool AllowUserConversions, 7596 bool AllowExplicitConversions, 7597 const Qualifiers &VisibleTypeConversionsQuals); 7598 7599 /// pointer_begin - First pointer type found; 7600 iterator pointer_begin() { return PointerTypes.begin(); } 7601 7602 /// pointer_end - Past the last pointer type found; 7603 iterator pointer_end() { return PointerTypes.end(); } 7604 7605 /// member_pointer_begin - First member pointer type found; 7606 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7607 7608 /// member_pointer_end - Past the last member pointer type found; 7609 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7610 7611 /// enumeration_begin - First enumeration type found; 7612 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7613 7614 /// enumeration_end - Past the last enumeration type found; 7615 iterator enumeration_end() { return EnumerationTypes.end(); } 7616 7617 iterator vector_begin() { return VectorTypes.begin(); } 7618 iterator vector_end() { return VectorTypes.end(); } 7619 7620 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7621 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7622 bool hasNullPtrType() const { return HasNullPtrType; } 7623 }; 7624 7625 } // end anonymous namespace 7626 7627 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7628 /// the set of pointer types along with any more-qualified variants of 7629 /// that type. For example, if @p Ty is "int const *", this routine 7630 /// will add "int const *", "int const volatile *", "int const 7631 /// restrict *", and "int const volatile restrict *" to the set of 7632 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7633 /// false otherwise. 7634 /// 7635 /// FIXME: what to do about extended qualifiers? 7636 bool 7637 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7638 const Qualifiers &VisibleQuals) { 7639 7640 // Insert this type. 7641 if (!PointerTypes.insert(Ty)) 7642 return false; 7643 7644 QualType PointeeTy; 7645 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7646 bool buildObjCPtr = false; 7647 if (!PointerTy) { 7648 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7649 PointeeTy = PTy->getPointeeType(); 7650 buildObjCPtr = true; 7651 } else { 7652 PointeeTy = PointerTy->getPointeeType(); 7653 } 7654 7655 // Don't add qualified variants of arrays. For one, they're not allowed 7656 // (the qualifier would sink to the element type), and for another, the 7657 // only overload situation where it matters is subscript or pointer +- int, 7658 // and those shouldn't have qualifier variants anyway. 7659 if (PointeeTy->isArrayType()) 7660 return true; 7661 7662 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7663 bool hasVolatile = VisibleQuals.hasVolatile(); 7664 bool hasRestrict = VisibleQuals.hasRestrict(); 7665 7666 // Iterate through all strict supersets of BaseCVR. 7667 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7668 if ((CVR | BaseCVR) != CVR) continue; 7669 // Skip over volatile if no volatile found anywhere in the types. 7670 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7671 7672 // Skip over restrict if no restrict found anywhere in the types, or if 7673 // the type cannot be restrict-qualified. 7674 if ((CVR & Qualifiers::Restrict) && 7675 (!hasRestrict || 7676 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7677 continue; 7678 7679 // Build qualified pointee type. 7680 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7681 7682 // Build qualified pointer type. 7683 QualType QPointerTy; 7684 if (!buildObjCPtr) 7685 QPointerTy = Context.getPointerType(QPointeeTy); 7686 else 7687 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7688 7689 // Insert qualified pointer type. 7690 PointerTypes.insert(QPointerTy); 7691 } 7692 7693 return true; 7694 } 7695 7696 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7697 /// to the set of pointer types along with any more-qualified variants of 7698 /// that type. For example, if @p Ty is "int const *", this routine 7699 /// will add "int const *", "int const volatile *", "int const 7700 /// restrict *", and "int const volatile restrict *" to the set of 7701 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7702 /// false otherwise. 7703 /// 7704 /// FIXME: what to do about extended qualifiers? 7705 bool 7706 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7707 QualType Ty) { 7708 // Insert this type. 7709 if (!MemberPointerTypes.insert(Ty)) 7710 return false; 7711 7712 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7713 assert(PointerTy && "type was not a member pointer type!"); 7714 7715 QualType PointeeTy = PointerTy->getPointeeType(); 7716 // Don't add qualified variants of arrays. For one, they're not allowed 7717 // (the qualifier would sink to the element type), and for another, the 7718 // only overload situation where it matters is subscript or pointer +- int, 7719 // and those shouldn't have qualifier variants anyway. 7720 if (PointeeTy->isArrayType()) 7721 return true; 7722 const Type *ClassTy = PointerTy->getClass(); 7723 7724 // Iterate through all strict supersets of the pointee type's CVR 7725 // qualifiers. 7726 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7727 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7728 if ((CVR | BaseCVR) != CVR) continue; 7729 7730 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7731 MemberPointerTypes.insert( 7732 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7733 } 7734 7735 return true; 7736 } 7737 7738 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7739 /// Ty can be implicit converted to the given set of @p Types. We're 7740 /// primarily interested in pointer types and enumeration types. We also 7741 /// take member pointer types, for the conditional operator. 7742 /// AllowUserConversions is true if we should look at the conversion 7743 /// functions of a class type, and AllowExplicitConversions if we 7744 /// should also include the explicit conversion functions of a class 7745 /// type. 7746 void 7747 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7748 SourceLocation Loc, 7749 bool AllowUserConversions, 7750 bool AllowExplicitConversions, 7751 const Qualifiers &VisibleQuals) { 7752 // Only deal with canonical types. 7753 Ty = Context.getCanonicalType(Ty); 7754 7755 // Look through reference types; they aren't part of the type of an 7756 // expression for the purposes of conversions. 7757 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7758 Ty = RefTy->getPointeeType(); 7759 7760 // If we're dealing with an array type, decay to the pointer. 7761 if (Ty->isArrayType()) 7762 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7763 7764 // Otherwise, we don't care about qualifiers on the type. 7765 Ty = Ty.getLocalUnqualifiedType(); 7766 7767 // Flag if we ever add a non-record type. 7768 const RecordType *TyRec = Ty->getAs<RecordType>(); 7769 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7770 7771 // Flag if we encounter an arithmetic type. 7772 HasArithmeticOrEnumeralTypes = 7773 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7774 7775 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7776 PointerTypes.insert(Ty); 7777 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7778 // Insert our type, and its more-qualified variants, into the set 7779 // of types. 7780 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7781 return; 7782 } else if (Ty->isMemberPointerType()) { 7783 // Member pointers are far easier, since the pointee can't be converted. 7784 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7785 return; 7786 } else if (Ty->isEnumeralType()) { 7787 HasArithmeticOrEnumeralTypes = true; 7788 EnumerationTypes.insert(Ty); 7789 } else if (Ty->isVectorType()) { 7790 // We treat vector types as arithmetic types in many contexts as an 7791 // extension. 7792 HasArithmeticOrEnumeralTypes = true; 7793 VectorTypes.insert(Ty); 7794 } else if (Ty->isNullPtrType()) { 7795 HasNullPtrType = true; 7796 } else if (AllowUserConversions && TyRec) { 7797 // No conversion functions in incomplete types. 7798 if (!SemaRef.isCompleteType(Loc, Ty)) 7799 return; 7800 7801 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7802 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7803 if (isa<UsingShadowDecl>(D)) 7804 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7805 7806 // Skip conversion function templates; they don't tell us anything 7807 // about which builtin types we can convert to. 7808 if (isa<FunctionTemplateDecl>(D)) 7809 continue; 7810 7811 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7812 if (AllowExplicitConversions || !Conv->isExplicit()) { 7813 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7814 VisibleQuals); 7815 } 7816 } 7817 } 7818 } 7819 /// Helper function for adjusting address spaces for the pointer or reference 7820 /// operands of builtin operators depending on the argument. 7821 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7822 Expr *Arg) { 7823 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7824 } 7825 7826 /// Helper function for AddBuiltinOperatorCandidates() that adds 7827 /// the volatile- and non-volatile-qualified assignment operators for the 7828 /// given type to the candidate set. 7829 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7830 QualType T, 7831 ArrayRef<Expr *> Args, 7832 OverloadCandidateSet &CandidateSet) { 7833 QualType ParamTypes[2]; 7834 7835 // T& operator=(T&, T) 7836 ParamTypes[0] = S.Context.getLValueReferenceType( 7837 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7838 ParamTypes[1] = T; 7839 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7840 /*IsAssignmentOperator=*/true); 7841 7842 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7843 // volatile T& operator=(volatile T&, T) 7844 ParamTypes[0] = S.Context.getLValueReferenceType( 7845 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7846 Args[0])); 7847 ParamTypes[1] = T; 7848 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7849 /*IsAssignmentOperator=*/true); 7850 } 7851 } 7852 7853 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7854 /// if any, found in visible type conversion functions found in ArgExpr's type. 7855 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7856 Qualifiers VRQuals; 7857 const RecordType *TyRec; 7858 if (const MemberPointerType *RHSMPType = 7859 ArgExpr->getType()->getAs<MemberPointerType>()) 7860 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7861 else 7862 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7863 if (!TyRec) { 7864 // Just to be safe, assume the worst case. 7865 VRQuals.addVolatile(); 7866 VRQuals.addRestrict(); 7867 return VRQuals; 7868 } 7869 7870 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7871 if (!ClassDecl->hasDefinition()) 7872 return VRQuals; 7873 7874 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7875 if (isa<UsingShadowDecl>(D)) 7876 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7877 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7878 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7879 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7880 CanTy = ResTypeRef->getPointeeType(); 7881 // Need to go down the pointer/mempointer chain and add qualifiers 7882 // as see them. 7883 bool done = false; 7884 while (!done) { 7885 if (CanTy.isRestrictQualified()) 7886 VRQuals.addRestrict(); 7887 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7888 CanTy = ResTypePtr->getPointeeType(); 7889 else if (const MemberPointerType *ResTypeMPtr = 7890 CanTy->getAs<MemberPointerType>()) 7891 CanTy = ResTypeMPtr->getPointeeType(); 7892 else 7893 done = true; 7894 if (CanTy.isVolatileQualified()) 7895 VRQuals.addVolatile(); 7896 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7897 return VRQuals; 7898 } 7899 } 7900 } 7901 return VRQuals; 7902 } 7903 7904 namespace { 7905 7906 /// Helper class to manage the addition of builtin operator overload 7907 /// candidates. It provides shared state and utility methods used throughout 7908 /// the process, as well as a helper method to add each group of builtin 7909 /// operator overloads from the standard to a candidate set. 7910 class BuiltinOperatorOverloadBuilder { 7911 // Common instance state available to all overload candidate addition methods. 7912 Sema &S; 7913 ArrayRef<Expr *> Args; 7914 Qualifiers VisibleTypeConversionsQuals; 7915 bool HasArithmeticOrEnumeralCandidateType; 7916 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7917 OverloadCandidateSet &CandidateSet; 7918 7919 static constexpr int ArithmeticTypesCap = 24; 7920 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7921 7922 // Define some indices used to iterate over the arithmetic types in 7923 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7924 // types are that preserved by promotion (C++ [over.built]p2). 7925 unsigned FirstIntegralType, 7926 LastIntegralType; 7927 unsigned FirstPromotedIntegralType, 7928 LastPromotedIntegralType; 7929 unsigned FirstPromotedArithmeticType, 7930 LastPromotedArithmeticType; 7931 unsigned NumArithmeticTypes; 7932 7933 void InitArithmeticTypes() { 7934 // Start of promoted types. 7935 FirstPromotedArithmeticType = 0; 7936 ArithmeticTypes.push_back(S.Context.FloatTy); 7937 ArithmeticTypes.push_back(S.Context.DoubleTy); 7938 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7939 if (S.Context.getTargetInfo().hasFloat128Type()) 7940 ArithmeticTypes.push_back(S.Context.Float128Ty); 7941 7942 // Start of integral types. 7943 FirstIntegralType = ArithmeticTypes.size(); 7944 FirstPromotedIntegralType = ArithmeticTypes.size(); 7945 ArithmeticTypes.push_back(S.Context.IntTy); 7946 ArithmeticTypes.push_back(S.Context.LongTy); 7947 ArithmeticTypes.push_back(S.Context.LongLongTy); 7948 if (S.Context.getTargetInfo().hasInt128Type()) 7949 ArithmeticTypes.push_back(S.Context.Int128Ty); 7950 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7951 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7952 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7953 if (S.Context.getTargetInfo().hasInt128Type()) 7954 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7955 LastPromotedIntegralType = ArithmeticTypes.size(); 7956 LastPromotedArithmeticType = ArithmeticTypes.size(); 7957 // End of promoted types. 7958 7959 ArithmeticTypes.push_back(S.Context.BoolTy); 7960 ArithmeticTypes.push_back(S.Context.CharTy); 7961 ArithmeticTypes.push_back(S.Context.WCharTy); 7962 if (S.Context.getLangOpts().Char8) 7963 ArithmeticTypes.push_back(S.Context.Char8Ty); 7964 ArithmeticTypes.push_back(S.Context.Char16Ty); 7965 ArithmeticTypes.push_back(S.Context.Char32Ty); 7966 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7967 ArithmeticTypes.push_back(S.Context.ShortTy); 7968 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7969 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7970 LastIntegralType = ArithmeticTypes.size(); 7971 NumArithmeticTypes = ArithmeticTypes.size(); 7972 // End of integral types. 7973 // FIXME: What about complex? What about half? 7974 7975 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7976 "Enough inline storage for all arithmetic types."); 7977 } 7978 7979 /// Helper method to factor out the common pattern of adding overloads 7980 /// for '++' and '--' builtin operators. 7981 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7982 bool HasVolatile, 7983 bool HasRestrict) { 7984 QualType ParamTypes[2] = { 7985 S.Context.getLValueReferenceType(CandidateTy), 7986 S.Context.IntTy 7987 }; 7988 7989 // Non-volatile version. 7990 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7991 7992 // Use a heuristic to reduce number of builtin candidates in the set: 7993 // add volatile version only if there are conversions to a volatile type. 7994 if (HasVolatile) { 7995 ParamTypes[0] = 7996 S.Context.getLValueReferenceType( 7997 S.Context.getVolatileType(CandidateTy)); 7998 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7999 } 8000 8001 // Add restrict version only if there are conversions to a restrict type 8002 // and our candidate type is a non-restrict-qualified pointer. 8003 if (HasRestrict && CandidateTy->isAnyPointerType() && 8004 !CandidateTy.isRestrictQualified()) { 8005 ParamTypes[0] 8006 = S.Context.getLValueReferenceType( 8007 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8008 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8009 8010 if (HasVolatile) { 8011 ParamTypes[0] 8012 = S.Context.getLValueReferenceType( 8013 S.Context.getCVRQualifiedType(CandidateTy, 8014 (Qualifiers::Volatile | 8015 Qualifiers::Restrict))); 8016 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8017 } 8018 } 8019 8020 } 8021 8022 public: 8023 BuiltinOperatorOverloadBuilder( 8024 Sema &S, ArrayRef<Expr *> Args, 8025 Qualifiers VisibleTypeConversionsQuals, 8026 bool HasArithmeticOrEnumeralCandidateType, 8027 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8028 OverloadCandidateSet &CandidateSet) 8029 : S(S), Args(Args), 8030 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8031 HasArithmeticOrEnumeralCandidateType( 8032 HasArithmeticOrEnumeralCandidateType), 8033 CandidateTypes(CandidateTypes), 8034 CandidateSet(CandidateSet) { 8035 8036 InitArithmeticTypes(); 8037 } 8038 8039 // Increment is deprecated for bool since C++17. 8040 // 8041 // C++ [over.built]p3: 8042 // 8043 // For every pair (T, VQ), where T is an arithmetic type other 8044 // than bool, and VQ is either volatile or empty, there exist 8045 // candidate operator functions of the form 8046 // 8047 // VQ T& operator++(VQ T&); 8048 // T operator++(VQ T&, int); 8049 // 8050 // C++ [over.built]p4: 8051 // 8052 // For every pair (T, VQ), where T is an arithmetic type other 8053 // than bool, and VQ is either volatile or empty, there exist 8054 // candidate operator functions of the form 8055 // 8056 // VQ T& operator--(VQ T&); 8057 // T operator--(VQ T&, int); 8058 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8059 if (!HasArithmeticOrEnumeralCandidateType) 8060 return; 8061 8062 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8063 const auto TypeOfT = ArithmeticTypes[Arith]; 8064 if (TypeOfT == S.Context.BoolTy) { 8065 if (Op == OO_MinusMinus) 8066 continue; 8067 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8068 continue; 8069 } 8070 addPlusPlusMinusMinusStyleOverloads( 8071 TypeOfT, 8072 VisibleTypeConversionsQuals.hasVolatile(), 8073 VisibleTypeConversionsQuals.hasRestrict()); 8074 } 8075 } 8076 8077 // C++ [over.built]p5: 8078 // 8079 // For every pair (T, VQ), where T is a cv-qualified or 8080 // cv-unqualified object type, and VQ is either volatile or 8081 // empty, there exist candidate operator functions of the form 8082 // 8083 // T*VQ& operator++(T*VQ&); 8084 // T*VQ& operator--(T*VQ&); 8085 // T* operator++(T*VQ&, int); 8086 // T* operator--(T*VQ&, int); 8087 void addPlusPlusMinusMinusPointerOverloads() { 8088 for (BuiltinCandidateTypeSet::iterator 8089 Ptr = CandidateTypes[0].pointer_begin(), 8090 PtrEnd = CandidateTypes[0].pointer_end(); 8091 Ptr != PtrEnd; ++Ptr) { 8092 // Skip pointer types that aren't pointers to object types. 8093 if (!(*Ptr)->getPointeeType()->isObjectType()) 8094 continue; 8095 8096 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8097 (!(*Ptr).isVolatileQualified() && 8098 VisibleTypeConversionsQuals.hasVolatile()), 8099 (!(*Ptr).isRestrictQualified() && 8100 VisibleTypeConversionsQuals.hasRestrict())); 8101 } 8102 } 8103 8104 // C++ [over.built]p6: 8105 // For every cv-qualified or cv-unqualified object type T, there 8106 // exist candidate operator functions of the form 8107 // 8108 // T& operator*(T*); 8109 // 8110 // C++ [over.built]p7: 8111 // For every function type T that does not have cv-qualifiers or a 8112 // ref-qualifier, there exist candidate operator functions of the form 8113 // T& operator*(T*); 8114 void addUnaryStarPointerOverloads() { 8115 for (BuiltinCandidateTypeSet::iterator 8116 Ptr = CandidateTypes[0].pointer_begin(), 8117 PtrEnd = CandidateTypes[0].pointer_end(); 8118 Ptr != PtrEnd; ++Ptr) { 8119 QualType ParamTy = *Ptr; 8120 QualType PointeeTy = ParamTy->getPointeeType(); 8121 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8122 continue; 8123 8124 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8125 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8126 continue; 8127 8128 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8129 } 8130 } 8131 8132 // C++ [over.built]p9: 8133 // For every promoted arithmetic type T, there exist candidate 8134 // operator functions of the form 8135 // 8136 // T operator+(T); 8137 // T operator-(T); 8138 void addUnaryPlusOrMinusArithmeticOverloads() { 8139 if (!HasArithmeticOrEnumeralCandidateType) 8140 return; 8141 8142 for (unsigned Arith = FirstPromotedArithmeticType; 8143 Arith < LastPromotedArithmeticType; ++Arith) { 8144 QualType ArithTy = ArithmeticTypes[Arith]; 8145 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8146 } 8147 8148 // Extension: We also add these operators for vector types. 8149 for (BuiltinCandidateTypeSet::iterator 8150 Vec = CandidateTypes[0].vector_begin(), 8151 VecEnd = CandidateTypes[0].vector_end(); 8152 Vec != VecEnd; ++Vec) { 8153 QualType VecTy = *Vec; 8154 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8155 } 8156 } 8157 8158 // C++ [over.built]p8: 8159 // For every type T, there exist candidate operator functions of 8160 // the form 8161 // 8162 // T* operator+(T*); 8163 void addUnaryPlusPointerOverloads() { 8164 for (BuiltinCandidateTypeSet::iterator 8165 Ptr = CandidateTypes[0].pointer_begin(), 8166 PtrEnd = CandidateTypes[0].pointer_end(); 8167 Ptr != PtrEnd; ++Ptr) { 8168 QualType ParamTy = *Ptr; 8169 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8170 } 8171 } 8172 8173 // C++ [over.built]p10: 8174 // For every promoted integral type T, there exist candidate 8175 // operator functions of the form 8176 // 8177 // T operator~(T); 8178 void addUnaryTildePromotedIntegralOverloads() { 8179 if (!HasArithmeticOrEnumeralCandidateType) 8180 return; 8181 8182 for (unsigned Int = FirstPromotedIntegralType; 8183 Int < LastPromotedIntegralType; ++Int) { 8184 QualType IntTy = ArithmeticTypes[Int]; 8185 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8186 } 8187 8188 // Extension: We also add this operator for vector types. 8189 for (BuiltinCandidateTypeSet::iterator 8190 Vec = CandidateTypes[0].vector_begin(), 8191 VecEnd = CandidateTypes[0].vector_end(); 8192 Vec != VecEnd; ++Vec) { 8193 QualType VecTy = *Vec; 8194 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8195 } 8196 } 8197 8198 // C++ [over.match.oper]p16: 8199 // For every pointer to member type T or type std::nullptr_t, there 8200 // exist candidate operator functions of the form 8201 // 8202 // bool operator==(T,T); 8203 // bool operator!=(T,T); 8204 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8205 /// Set of (canonical) types that we've already handled. 8206 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8207 8208 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8209 for (BuiltinCandidateTypeSet::iterator 8210 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8211 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8212 MemPtr != MemPtrEnd; 8213 ++MemPtr) { 8214 // Don't add the same builtin candidate twice. 8215 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8216 continue; 8217 8218 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8219 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8220 } 8221 8222 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8223 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8224 if (AddedTypes.insert(NullPtrTy).second) { 8225 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8226 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8227 } 8228 } 8229 } 8230 } 8231 8232 // C++ [over.built]p15: 8233 // 8234 // For every T, where T is an enumeration type or a pointer type, 8235 // there exist candidate operator functions of the form 8236 // 8237 // bool operator<(T, T); 8238 // bool operator>(T, T); 8239 // bool operator<=(T, T); 8240 // bool operator>=(T, T); 8241 // bool operator==(T, T); 8242 // bool operator!=(T, T); 8243 // R operator<=>(T, T) 8244 void addGenericBinaryPointerOrEnumeralOverloads() { 8245 // C++ [over.match.oper]p3: 8246 // [...]the built-in candidates include all of the candidate operator 8247 // functions defined in 13.6 that, compared to the given operator, [...] 8248 // do not have the same parameter-type-list as any non-template non-member 8249 // candidate. 8250 // 8251 // Note that in practice, this only affects enumeration types because there 8252 // aren't any built-in candidates of record type, and a user-defined operator 8253 // must have an operand of record or enumeration type. Also, the only other 8254 // overloaded operator with enumeration arguments, operator=, 8255 // cannot be overloaded for enumeration types, so this is the only place 8256 // where we must suppress candidates like this. 8257 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8258 UserDefinedBinaryOperators; 8259 8260 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8261 if (CandidateTypes[ArgIdx].enumeration_begin() != 8262 CandidateTypes[ArgIdx].enumeration_end()) { 8263 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8264 CEnd = CandidateSet.end(); 8265 C != CEnd; ++C) { 8266 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8267 continue; 8268 8269 if (C->Function->isFunctionTemplateSpecialization()) 8270 continue; 8271 8272 // We interpret "same parameter-type-list" as applying to the 8273 // "synthesized candidate, with the order of the two parameters 8274 // reversed", not to the original function. 8275 bool Reversed = C->RewriteKind & CRK_Reversed; 8276 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8277 ->getType() 8278 .getUnqualifiedType(); 8279 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8280 ->getType() 8281 .getUnqualifiedType(); 8282 8283 // Skip if either parameter isn't of enumeral type. 8284 if (!FirstParamType->isEnumeralType() || 8285 !SecondParamType->isEnumeralType()) 8286 continue; 8287 8288 // Add this operator to the set of known user-defined operators. 8289 UserDefinedBinaryOperators.insert( 8290 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8291 S.Context.getCanonicalType(SecondParamType))); 8292 } 8293 } 8294 } 8295 8296 /// Set of (canonical) types that we've already handled. 8297 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8298 8299 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8300 for (BuiltinCandidateTypeSet::iterator 8301 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8302 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8303 Ptr != PtrEnd; ++Ptr) { 8304 // Don't add the same builtin candidate twice. 8305 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8306 continue; 8307 8308 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8309 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8310 } 8311 for (BuiltinCandidateTypeSet::iterator 8312 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8313 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8314 Enum != EnumEnd; ++Enum) { 8315 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8316 8317 // Don't add the same builtin candidate twice, or if a user defined 8318 // candidate exists. 8319 if (!AddedTypes.insert(CanonType).second || 8320 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8321 CanonType))) 8322 continue; 8323 QualType ParamTypes[2] = { *Enum, *Enum }; 8324 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8325 } 8326 } 8327 } 8328 8329 // C++ [over.built]p13: 8330 // 8331 // For every cv-qualified or cv-unqualified object type T 8332 // there exist candidate operator functions of the form 8333 // 8334 // T* operator+(T*, ptrdiff_t); 8335 // T& operator[](T*, ptrdiff_t); [BELOW] 8336 // T* operator-(T*, ptrdiff_t); 8337 // T* operator+(ptrdiff_t, T*); 8338 // T& operator[](ptrdiff_t, T*); [BELOW] 8339 // 8340 // C++ [over.built]p14: 8341 // 8342 // For every T, where T is a pointer to object type, there 8343 // exist candidate operator functions of the form 8344 // 8345 // ptrdiff_t operator-(T, T); 8346 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8347 /// Set of (canonical) types that we've already handled. 8348 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8349 8350 for (int Arg = 0; Arg < 2; ++Arg) { 8351 QualType AsymmetricParamTypes[2] = { 8352 S.Context.getPointerDiffType(), 8353 S.Context.getPointerDiffType(), 8354 }; 8355 for (BuiltinCandidateTypeSet::iterator 8356 Ptr = CandidateTypes[Arg].pointer_begin(), 8357 PtrEnd = CandidateTypes[Arg].pointer_end(); 8358 Ptr != PtrEnd; ++Ptr) { 8359 QualType PointeeTy = (*Ptr)->getPointeeType(); 8360 if (!PointeeTy->isObjectType()) 8361 continue; 8362 8363 AsymmetricParamTypes[Arg] = *Ptr; 8364 if (Arg == 0 || Op == OO_Plus) { 8365 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8366 // T* operator+(ptrdiff_t, T*); 8367 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8368 } 8369 if (Op == OO_Minus) { 8370 // ptrdiff_t operator-(T, T); 8371 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8372 continue; 8373 8374 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8375 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8376 } 8377 } 8378 } 8379 } 8380 8381 // C++ [over.built]p12: 8382 // 8383 // For every pair of promoted arithmetic types L and R, there 8384 // exist candidate operator functions of the form 8385 // 8386 // LR operator*(L, R); 8387 // LR operator/(L, R); 8388 // LR operator+(L, R); 8389 // LR operator-(L, R); 8390 // bool operator<(L, R); 8391 // bool operator>(L, R); 8392 // bool operator<=(L, R); 8393 // bool operator>=(L, R); 8394 // bool operator==(L, R); 8395 // bool operator!=(L, R); 8396 // 8397 // where LR is the result of the usual arithmetic conversions 8398 // between types L and R. 8399 // 8400 // C++ [over.built]p24: 8401 // 8402 // For every pair of promoted arithmetic types L and R, there exist 8403 // candidate operator functions of the form 8404 // 8405 // LR operator?(bool, L, R); 8406 // 8407 // where LR is the result of the usual arithmetic conversions 8408 // between types L and R. 8409 // Our candidates ignore the first parameter. 8410 void addGenericBinaryArithmeticOverloads() { 8411 if (!HasArithmeticOrEnumeralCandidateType) 8412 return; 8413 8414 for (unsigned Left = FirstPromotedArithmeticType; 8415 Left < LastPromotedArithmeticType; ++Left) { 8416 for (unsigned Right = FirstPromotedArithmeticType; 8417 Right < LastPromotedArithmeticType; ++Right) { 8418 QualType LandR[2] = { ArithmeticTypes[Left], 8419 ArithmeticTypes[Right] }; 8420 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8421 } 8422 } 8423 8424 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8425 // conditional operator for vector types. 8426 for (BuiltinCandidateTypeSet::iterator 8427 Vec1 = CandidateTypes[0].vector_begin(), 8428 Vec1End = CandidateTypes[0].vector_end(); 8429 Vec1 != Vec1End; ++Vec1) { 8430 for (BuiltinCandidateTypeSet::iterator 8431 Vec2 = CandidateTypes[1].vector_begin(), 8432 Vec2End = CandidateTypes[1].vector_end(); 8433 Vec2 != Vec2End; ++Vec2) { 8434 QualType LandR[2] = { *Vec1, *Vec2 }; 8435 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8436 } 8437 } 8438 } 8439 8440 // C++2a [over.built]p14: 8441 // 8442 // For every integral type T there exists a candidate operator function 8443 // of the form 8444 // 8445 // std::strong_ordering operator<=>(T, T) 8446 // 8447 // C++2a [over.built]p15: 8448 // 8449 // For every pair of floating-point types L and R, there exists a candidate 8450 // operator function of the form 8451 // 8452 // std::partial_ordering operator<=>(L, R); 8453 // 8454 // FIXME: The current specification for integral types doesn't play nice with 8455 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8456 // comparisons. Under the current spec this can lead to ambiguity during 8457 // overload resolution. For example: 8458 // 8459 // enum A : int {a}; 8460 // auto x = (a <=> (long)42); 8461 // 8462 // error: call is ambiguous for arguments 'A' and 'long'. 8463 // note: candidate operator<=>(int, int) 8464 // note: candidate operator<=>(long, long) 8465 // 8466 // To avoid this error, this function deviates from the specification and adds 8467 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8468 // arithmetic types (the same as the generic relational overloads). 8469 // 8470 // For now this function acts as a placeholder. 8471 void addThreeWayArithmeticOverloads() { 8472 addGenericBinaryArithmeticOverloads(); 8473 } 8474 8475 // C++ [over.built]p17: 8476 // 8477 // For every pair of promoted integral types L and R, there 8478 // exist candidate operator functions of the form 8479 // 8480 // LR operator%(L, R); 8481 // LR operator&(L, R); 8482 // LR operator^(L, R); 8483 // LR operator|(L, R); 8484 // L operator<<(L, R); 8485 // L operator>>(L, R); 8486 // 8487 // where LR is the result of the usual arithmetic conversions 8488 // between types L and R. 8489 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8490 if (!HasArithmeticOrEnumeralCandidateType) 8491 return; 8492 8493 for (unsigned Left = FirstPromotedIntegralType; 8494 Left < LastPromotedIntegralType; ++Left) { 8495 for (unsigned Right = FirstPromotedIntegralType; 8496 Right < LastPromotedIntegralType; ++Right) { 8497 QualType LandR[2] = { ArithmeticTypes[Left], 8498 ArithmeticTypes[Right] }; 8499 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8500 } 8501 } 8502 } 8503 8504 // C++ [over.built]p20: 8505 // 8506 // For every pair (T, VQ), where T is an enumeration or 8507 // pointer to member type and VQ is either volatile or 8508 // empty, there exist candidate operator functions of the form 8509 // 8510 // VQ T& operator=(VQ T&, T); 8511 void addAssignmentMemberPointerOrEnumeralOverloads() { 8512 /// Set of (canonical) types that we've already handled. 8513 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8514 8515 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8516 for (BuiltinCandidateTypeSet::iterator 8517 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8518 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8519 Enum != EnumEnd; ++Enum) { 8520 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8521 continue; 8522 8523 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8524 } 8525 8526 for (BuiltinCandidateTypeSet::iterator 8527 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8528 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8529 MemPtr != MemPtrEnd; ++MemPtr) { 8530 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8531 continue; 8532 8533 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8534 } 8535 } 8536 } 8537 8538 // C++ [over.built]p19: 8539 // 8540 // For every pair (T, VQ), where T is any type and VQ is either 8541 // volatile or empty, there exist candidate operator functions 8542 // of the form 8543 // 8544 // T*VQ& operator=(T*VQ&, T*); 8545 // 8546 // C++ [over.built]p21: 8547 // 8548 // For every pair (T, VQ), where T is a cv-qualified or 8549 // cv-unqualified object type and VQ is either volatile or 8550 // empty, there exist candidate operator functions of the form 8551 // 8552 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8553 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8554 void addAssignmentPointerOverloads(bool isEqualOp) { 8555 /// Set of (canonical) types that we've already handled. 8556 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8557 8558 for (BuiltinCandidateTypeSet::iterator 8559 Ptr = CandidateTypes[0].pointer_begin(), 8560 PtrEnd = CandidateTypes[0].pointer_end(); 8561 Ptr != PtrEnd; ++Ptr) { 8562 // If this is operator=, keep track of the builtin candidates we added. 8563 if (isEqualOp) 8564 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8565 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8566 continue; 8567 8568 // non-volatile version 8569 QualType ParamTypes[2] = { 8570 S.Context.getLValueReferenceType(*Ptr), 8571 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8572 }; 8573 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8574 /*IsAssignmentOperator=*/ isEqualOp); 8575 8576 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8577 VisibleTypeConversionsQuals.hasVolatile(); 8578 if (NeedVolatile) { 8579 // volatile version 8580 ParamTypes[0] = 8581 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8582 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8583 /*IsAssignmentOperator=*/isEqualOp); 8584 } 8585 8586 if (!(*Ptr).isRestrictQualified() && 8587 VisibleTypeConversionsQuals.hasRestrict()) { 8588 // restrict version 8589 ParamTypes[0] 8590 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8591 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8592 /*IsAssignmentOperator=*/isEqualOp); 8593 8594 if (NeedVolatile) { 8595 // volatile restrict version 8596 ParamTypes[0] 8597 = S.Context.getLValueReferenceType( 8598 S.Context.getCVRQualifiedType(*Ptr, 8599 (Qualifiers::Volatile | 8600 Qualifiers::Restrict))); 8601 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8602 /*IsAssignmentOperator=*/isEqualOp); 8603 } 8604 } 8605 } 8606 8607 if (isEqualOp) { 8608 for (BuiltinCandidateTypeSet::iterator 8609 Ptr = CandidateTypes[1].pointer_begin(), 8610 PtrEnd = CandidateTypes[1].pointer_end(); 8611 Ptr != PtrEnd; ++Ptr) { 8612 // Make sure we don't add the same candidate twice. 8613 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8614 continue; 8615 8616 QualType ParamTypes[2] = { 8617 S.Context.getLValueReferenceType(*Ptr), 8618 *Ptr, 8619 }; 8620 8621 // non-volatile version 8622 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8623 /*IsAssignmentOperator=*/true); 8624 8625 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8626 VisibleTypeConversionsQuals.hasVolatile(); 8627 if (NeedVolatile) { 8628 // volatile version 8629 ParamTypes[0] = 8630 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8631 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8632 /*IsAssignmentOperator=*/true); 8633 } 8634 8635 if (!(*Ptr).isRestrictQualified() && 8636 VisibleTypeConversionsQuals.hasRestrict()) { 8637 // restrict version 8638 ParamTypes[0] 8639 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8640 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8641 /*IsAssignmentOperator=*/true); 8642 8643 if (NeedVolatile) { 8644 // volatile restrict version 8645 ParamTypes[0] 8646 = S.Context.getLValueReferenceType( 8647 S.Context.getCVRQualifiedType(*Ptr, 8648 (Qualifiers::Volatile | 8649 Qualifiers::Restrict))); 8650 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8651 /*IsAssignmentOperator=*/true); 8652 } 8653 } 8654 } 8655 } 8656 } 8657 8658 // C++ [over.built]p18: 8659 // 8660 // For every triple (L, VQ, R), where L is an arithmetic type, 8661 // VQ is either volatile or empty, and R is a promoted 8662 // arithmetic type, there exist candidate operator functions of 8663 // the form 8664 // 8665 // VQ L& operator=(VQ L&, R); 8666 // VQ L& operator*=(VQ L&, R); 8667 // VQ L& operator/=(VQ L&, R); 8668 // VQ L& operator+=(VQ L&, R); 8669 // VQ L& operator-=(VQ L&, R); 8670 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8671 if (!HasArithmeticOrEnumeralCandidateType) 8672 return; 8673 8674 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8675 for (unsigned Right = FirstPromotedArithmeticType; 8676 Right < LastPromotedArithmeticType; ++Right) { 8677 QualType ParamTypes[2]; 8678 ParamTypes[1] = ArithmeticTypes[Right]; 8679 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8680 S, ArithmeticTypes[Left], Args[0]); 8681 // Add this built-in operator as a candidate (VQ is empty). 8682 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8683 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8684 /*IsAssignmentOperator=*/isEqualOp); 8685 8686 // Add this built-in operator as a candidate (VQ is 'volatile'). 8687 if (VisibleTypeConversionsQuals.hasVolatile()) { 8688 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8689 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8690 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8691 /*IsAssignmentOperator=*/isEqualOp); 8692 } 8693 } 8694 } 8695 8696 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8697 for (BuiltinCandidateTypeSet::iterator 8698 Vec1 = CandidateTypes[0].vector_begin(), 8699 Vec1End = CandidateTypes[0].vector_end(); 8700 Vec1 != Vec1End; ++Vec1) { 8701 for (BuiltinCandidateTypeSet::iterator 8702 Vec2 = CandidateTypes[1].vector_begin(), 8703 Vec2End = CandidateTypes[1].vector_end(); 8704 Vec2 != Vec2End; ++Vec2) { 8705 QualType ParamTypes[2]; 8706 ParamTypes[1] = *Vec2; 8707 // Add this built-in operator as a candidate (VQ is empty). 8708 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8709 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8710 /*IsAssignmentOperator=*/isEqualOp); 8711 8712 // Add this built-in operator as a candidate (VQ is 'volatile'). 8713 if (VisibleTypeConversionsQuals.hasVolatile()) { 8714 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8715 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8716 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8717 /*IsAssignmentOperator=*/isEqualOp); 8718 } 8719 } 8720 } 8721 } 8722 8723 // C++ [over.built]p22: 8724 // 8725 // For every triple (L, VQ, R), where L is an integral type, VQ 8726 // is either volatile or empty, and R is a promoted integral 8727 // type, there exist candidate operator functions of the form 8728 // 8729 // VQ L& operator%=(VQ L&, R); 8730 // VQ L& operator<<=(VQ L&, R); 8731 // VQ L& operator>>=(VQ L&, R); 8732 // VQ L& operator&=(VQ L&, R); 8733 // VQ L& operator^=(VQ L&, R); 8734 // VQ L& operator|=(VQ L&, R); 8735 void addAssignmentIntegralOverloads() { 8736 if (!HasArithmeticOrEnumeralCandidateType) 8737 return; 8738 8739 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8740 for (unsigned Right = FirstPromotedIntegralType; 8741 Right < LastPromotedIntegralType; ++Right) { 8742 QualType ParamTypes[2]; 8743 ParamTypes[1] = ArithmeticTypes[Right]; 8744 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8745 S, ArithmeticTypes[Left], Args[0]); 8746 // Add this built-in operator as a candidate (VQ is empty). 8747 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8748 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8749 if (VisibleTypeConversionsQuals.hasVolatile()) { 8750 // Add this built-in operator as a candidate (VQ is 'volatile'). 8751 ParamTypes[0] = LeftBaseTy; 8752 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8753 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8754 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8755 } 8756 } 8757 } 8758 } 8759 8760 // C++ [over.operator]p23: 8761 // 8762 // There also exist candidate operator functions of the form 8763 // 8764 // bool operator!(bool); 8765 // bool operator&&(bool, bool); 8766 // bool operator||(bool, bool); 8767 void addExclaimOverload() { 8768 QualType ParamTy = S.Context.BoolTy; 8769 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8770 /*IsAssignmentOperator=*/false, 8771 /*NumContextualBoolArguments=*/1); 8772 } 8773 void addAmpAmpOrPipePipeOverload() { 8774 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8775 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8776 /*IsAssignmentOperator=*/false, 8777 /*NumContextualBoolArguments=*/2); 8778 } 8779 8780 // C++ [over.built]p13: 8781 // 8782 // For every cv-qualified or cv-unqualified object type T there 8783 // exist candidate operator functions of the form 8784 // 8785 // T* operator+(T*, ptrdiff_t); [ABOVE] 8786 // T& operator[](T*, ptrdiff_t); 8787 // T* operator-(T*, ptrdiff_t); [ABOVE] 8788 // T* operator+(ptrdiff_t, T*); [ABOVE] 8789 // T& operator[](ptrdiff_t, T*); 8790 void addSubscriptOverloads() { 8791 for (BuiltinCandidateTypeSet::iterator 8792 Ptr = CandidateTypes[0].pointer_begin(), 8793 PtrEnd = CandidateTypes[0].pointer_end(); 8794 Ptr != PtrEnd; ++Ptr) { 8795 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8796 QualType PointeeType = (*Ptr)->getPointeeType(); 8797 if (!PointeeType->isObjectType()) 8798 continue; 8799 8800 // T& operator[](T*, ptrdiff_t) 8801 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8802 } 8803 8804 for (BuiltinCandidateTypeSet::iterator 8805 Ptr = CandidateTypes[1].pointer_begin(), 8806 PtrEnd = CandidateTypes[1].pointer_end(); 8807 Ptr != PtrEnd; ++Ptr) { 8808 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8809 QualType PointeeType = (*Ptr)->getPointeeType(); 8810 if (!PointeeType->isObjectType()) 8811 continue; 8812 8813 // T& operator[](ptrdiff_t, T*) 8814 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8815 } 8816 } 8817 8818 // C++ [over.built]p11: 8819 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8820 // C1 is the same type as C2 or is a derived class of C2, T is an object 8821 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8822 // there exist candidate operator functions of the form 8823 // 8824 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8825 // 8826 // where CV12 is the union of CV1 and CV2. 8827 void addArrowStarOverloads() { 8828 for (BuiltinCandidateTypeSet::iterator 8829 Ptr = CandidateTypes[0].pointer_begin(), 8830 PtrEnd = CandidateTypes[0].pointer_end(); 8831 Ptr != PtrEnd; ++Ptr) { 8832 QualType C1Ty = (*Ptr); 8833 QualType C1; 8834 QualifierCollector Q1; 8835 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8836 if (!isa<RecordType>(C1)) 8837 continue; 8838 // heuristic to reduce number of builtin candidates in the set. 8839 // Add volatile/restrict version only if there are conversions to a 8840 // volatile/restrict type. 8841 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8842 continue; 8843 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8844 continue; 8845 for (BuiltinCandidateTypeSet::iterator 8846 MemPtr = CandidateTypes[1].member_pointer_begin(), 8847 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8848 MemPtr != MemPtrEnd; ++MemPtr) { 8849 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8850 QualType C2 = QualType(mptr->getClass(), 0); 8851 C2 = C2.getUnqualifiedType(); 8852 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8853 break; 8854 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8855 // build CV12 T& 8856 QualType T = mptr->getPointeeType(); 8857 if (!VisibleTypeConversionsQuals.hasVolatile() && 8858 T.isVolatileQualified()) 8859 continue; 8860 if (!VisibleTypeConversionsQuals.hasRestrict() && 8861 T.isRestrictQualified()) 8862 continue; 8863 T = Q1.apply(S.Context, T); 8864 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8865 } 8866 } 8867 } 8868 8869 // Note that we don't consider the first argument, since it has been 8870 // contextually converted to bool long ago. The candidates below are 8871 // therefore added as binary. 8872 // 8873 // C++ [over.built]p25: 8874 // For every type T, where T is a pointer, pointer-to-member, or scoped 8875 // enumeration type, there exist candidate operator functions of the form 8876 // 8877 // T operator?(bool, T, T); 8878 // 8879 void addConditionalOperatorOverloads() { 8880 /// Set of (canonical) types that we've already handled. 8881 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8882 8883 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8884 for (BuiltinCandidateTypeSet::iterator 8885 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8886 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8887 Ptr != PtrEnd; ++Ptr) { 8888 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8889 continue; 8890 8891 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8892 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8893 } 8894 8895 for (BuiltinCandidateTypeSet::iterator 8896 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8897 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8898 MemPtr != MemPtrEnd; ++MemPtr) { 8899 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8900 continue; 8901 8902 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8903 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8904 } 8905 8906 if (S.getLangOpts().CPlusPlus11) { 8907 for (BuiltinCandidateTypeSet::iterator 8908 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8909 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8910 Enum != EnumEnd; ++Enum) { 8911 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 8912 continue; 8913 8914 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8915 continue; 8916 8917 QualType ParamTypes[2] = { *Enum, *Enum }; 8918 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8919 } 8920 } 8921 } 8922 } 8923 }; 8924 8925 } // end anonymous namespace 8926 8927 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8928 /// operator overloads to the candidate set (C++ [over.built]), based 8929 /// on the operator @p Op and the arguments given. For example, if the 8930 /// operator is a binary '+', this routine might add "int 8931 /// operator+(int, int)" to cover integer addition. 8932 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8933 SourceLocation OpLoc, 8934 ArrayRef<Expr *> Args, 8935 OverloadCandidateSet &CandidateSet) { 8936 // Find all of the types that the arguments can convert to, but only 8937 // if the operator we're looking at has built-in operator candidates 8938 // that make use of these types. Also record whether we encounter non-record 8939 // candidate types or either arithmetic or enumeral candidate types. 8940 Qualifiers VisibleTypeConversionsQuals; 8941 VisibleTypeConversionsQuals.addConst(); 8942 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8943 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8944 8945 bool HasNonRecordCandidateType = false; 8946 bool HasArithmeticOrEnumeralCandidateType = false; 8947 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8948 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8949 CandidateTypes.emplace_back(*this); 8950 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8951 OpLoc, 8952 true, 8953 (Op == OO_Exclaim || 8954 Op == OO_AmpAmp || 8955 Op == OO_PipePipe), 8956 VisibleTypeConversionsQuals); 8957 HasNonRecordCandidateType = HasNonRecordCandidateType || 8958 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8959 HasArithmeticOrEnumeralCandidateType = 8960 HasArithmeticOrEnumeralCandidateType || 8961 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8962 } 8963 8964 // Exit early when no non-record types have been added to the candidate set 8965 // for any of the arguments to the operator. 8966 // 8967 // We can't exit early for !, ||, or &&, since there we have always have 8968 // 'bool' overloads. 8969 if (!HasNonRecordCandidateType && 8970 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8971 return; 8972 8973 // Setup an object to manage the common state for building overloads. 8974 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8975 VisibleTypeConversionsQuals, 8976 HasArithmeticOrEnumeralCandidateType, 8977 CandidateTypes, CandidateSet); 8978 8979 // Dispatch over the operation to add in only those overloads which apply. 8980 switch (Op) { 8981 case OO_None: 8982 case NUM_OVERLOADED_OPERATORS: 8983 llvm_unreachable("Expected an overloaded operator"); 8984 8985 case OO_New: 8986 case OO_Delete: 8987 case OO_Array_New: 8988 case OO_Array_Delete: 8989 case OO_Call: 8990 llvm_unreachable( 8991 "Special operators don't use AddBuiltinOperatorCandidates"); 8992 8993 case OO_Comma: 8994 case OO_Arrow: 8995 case OO_Coawait: 8996 // C++ [over.match.oper]p3: 8997 // -- For the operator ',', the unary operator '&', the 8998 // operator '->', or the operator 'co_await', the 8999 // built-in candidates set is empty. 9000 break; 9001 9002 case OO_Plus: // '+' is either unary or binary 9003 if (Args.size() == 1) 9004 OpBuilder.addUnaryPlusPointerOverloads(); 9005 LLVM_FALLTHROUGH; 9006 9007 case OO_Minus: // '-' is either unary or binary 9008 if (Args.size() == 1) { 9009 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9010 } else { 9011 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9012 OpBuilder.addGenericBinaryArithmeticOverloads(); 9013 } 9014 break; 9015 9016 case OO_Star: // '*' is either unary or binary 9017 if (Args.size() == 1) 9018 OpBuilder.addUnaryStarPointerOverloads(); 9019 else 9020 OpBuilder.addGenericBinaryArithmeticOverloads(); 9021 break; 9022 9023 case OO_Slash: 9024 OpBuilder.addGenericBinaryArithmeticOverloads(); 9025 break; 9026 9027 case OO_PlusPlus: 9028 case OO_MinusMinus: 9029 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9030 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9031 break; 9032 9033 case OO_EqualEqual: 9034 case OO_ExclaimEqual: 9035 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9036 LLVM_FALLTHROUGH; 9037 9038 case OO_Less: 9039 case OO_Greater: 9040 case OO_LessEqual: 9041 case OO_GreaterEqual: 9042 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9043 OpBuilder.addGenericBinaryArithmeticOverloads(); 9044 break; 9045 9046 case OO_Spaceship: 9047 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9048 OpBuilder.addThreeWayArithmeticOverloads(); 9049 break; 9050 9051 case OO_Percent: 9052 case OO_Caret: 9053 case OO_Pipe: 9054 case OO_LessLess: 9055 case OO_GreaterGreater: 9056 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9057 break; 9058 9059 case OO_Amp: // '&' is either unary or binary 9060 if (Args.size() == 1) 9061 // C++ [over.match.oper]p3: 9062 // -- For the operator ',', the unary operator '&', or the 9063 // operator '->', the built-in candidates set is empty. 9064 break; 9065 9066 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9067 break; 9068 9069 case OO_Tilde: 9070 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9071 break; 9072 9073 case OO_Equal: 9074 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9075 LLVM_FALLTHROUGH; 9076 9077 case OO_PlusEqual: 9078 case OO_MinusEqual: 9079 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9080 LLVM_FALLTHROUGH; 9081 9082 case OO_StarEqual: 9083 case OO_SlashEqual: 9084 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9085 break; 9086 9087 case OO_PercentEqual: 9088 case OO_LessLessEqual: 9089 case OO_GreaterGreaterEqual: 9090 case OO_AmpEqual: 9091 case OO_CaretEqual: 9092 case OO_PipeEqual: 9093 OpBuilder.addAssignmentIntegralOverloads(); 9094 break; 9095 9096 case OO_Exclaim: 9097 OpBuilder.addExclaimOverload(); 9098 break; 9099 9100 case OO_AmpAmp: 9101 case OO_PipePipe: 9102 OpBuilder.addAmpAmpOrPipePipeOverload(); 9103 break; 9104 9105 case OO_Subscript: 9106 OpBuilder.addSubscriptOverloads(); 9107 break; 9108 9109 case OO_ArrowStar: 9110 OpBuilder.addArrowStarOverloads(); 9111 break; 9112 9113 case OO_Conditional: 9114 OpBuilder.addConditionalOperatorOverloads(); 9115 OpBuilder.addGenericBinaryArithmeticOverloads(); 9116 break; 9117 } 9118 } 9119 9120 /// Add function candidates found via argument-dependent lookup 9121 /// to the set of overloading candidates. 9122 /// 9123 /// This routine performs argument-dependent name lookup based on the 9124 /// given function name (which may also be an operator name) and adds 9125 /// all of the overload candidates found by ADL to the overload 9126 /// candidate set (C++ [basic.lookup.argdep]). 9127 void 9128 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9129 SourceLocation Loc, 9130 ArrayRef<Expr *> Args, 9131 TemplateArgumentListInfo *ExplicitTemplateArgs, 9132 OverloadCandidateSet& CandidateSet, 9133 bool PartialOverloading) { 9134 ADLResult Fns; 9135 9136 // FIXME: This approach for uniquing ADL results (and removing 9137 // redundant candidates from the set) relies on pointer-equality, 9138 // which means we need to key off the canonical decl. However, 9139 // always going back to the canonical decl might not get us the 9140 // right set of default arguments. What default arguments are 9141 // we supposed to consider on ADL candidates, anyway? 9142 9143 // FIXME: Pass in the explicit template arguments? 9144 ArgumentDependentLookup(Name, Loc, Args, Fns); 9145 9146 // Erase all of the candidates we already knew about. 9147 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9148 CandEnd = CandidateSet.end(); 9149 Cand != CandEnd; ++Cand) 9150 if (Cand->Function) { 9151 Fns.erase(Cand->Function); 9152 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9153 Fns.erase(FunTmpl); 9154 } 9155 9156 // For each of the ADL candidates we found, add it to the overload 9157 // set. 9158 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9159 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9160 9161 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9162 if (ExplicitTemplateArgs) 9163 continue; 9164 9165 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, 9166 /*SuppressUserConversions=*/false, PartialOverloading, 9167 /*AllowExplicit*/ true, 9168 /*AllowExplicitConversions*/ false, 9169 ADLCallKind::UsesADL); 9170 } else { 9171 AddTemplateOverloadCandidate( 9172 cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args, 9173 CandidateSet, 9174 /*SuppressUserConversions=*/false, PartialOverloading, 9175 /*AllowExplicit*/true, ADLCallKind::UsesADL); 9176 } 9177 } 9178 } 9179 9180 namespace { 9181 enum class Comparison { Equal, Better, Worse }; 9182 } 9183 9184 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9185 /// overload resolution. 9186 /// 9187 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9188 /// Cand1's first N enable_if attributes have precisely the same conditions as 9189 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9190 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9191 /// 9192 /// Note that you can have a pair of candidates such that Cand1's enable_if 9193 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9194 /// worse than Cand1's. 9195 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9196 const FunctionDecl *Cand2) { 9197 // Common case: One (or both) decls don't have enable_if attrs. 9198 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9199 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9200 if (!Cand1Attr || !Cand2Attr) { 9201 if (Cand1Attr == Cand2Attr) 9202 return Comparison::Equal; 9203 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9204 } 9205 9206 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9207 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9208 9209 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9210 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9211 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9212 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9213 9214 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9215 // has fewer enable_if attributes than Cand2, and vice versa. 9216 if (!Cand1A) 9217 return Comparison::Worse; 9218 if (!Cand2A) 9219 return Comparison::Better; 9220 9221 Cand1ID.clear(); 9222 Cand2ID.clear(); 9223 9224 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9225 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9226 if (Cand1ID != Cand2ID) 9227 return Comparison::Worse; 9228 } 9229 9230 return Comparison::Equal; 9231 } 9232 9233 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9234 const OverloadCandidate &Cand2) { 9235 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9236 !Cand2.Function->isMultiVersion()) 9237 return false; 9238 9239 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9240 // is obviously better. 9241 if (Cand1.Function->isInvalidDecl()) return false; 9242 if (Cand2.Function->isInvalidDecl()) return true; 9243 9244 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9245 // cpu_dispatch, else arbitrarily based on the identifiers. 9246 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9247 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9248 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9249 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9250 9251 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9252 return false; 9253 9254 if (Cand1CPUDisp && !Cand2CPUDisp) 9255 return true; 9256 if (Cand2CPUDisp && !Cand1CPUDisp) 9257 return false; 9258 9259 if (Cand1CPUSpec && Cand2CPUSpec) { 9260 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9261 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9262 9263 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9264 FirstDiff = std::mismatch( 9265 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9266 Cand2CPUSpec->cpus_begin(), 9267 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9268 return LHS->getName() == RHS->getName(); 9269 }); 9270 9271 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9272 "Two different cpu-specific versions should not have the same " 9273 "identifier list, otherwise they'd be the same decl!"); 9274 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9275 } 9276 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9277 } 9278 9279 /// isBetterOverloadCandidate - Determines whether the first overload 9280 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9281 bool clang::isBetterOverloadCandidate( 9282 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9283 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9284 // Define viable functions to be better candidates than non-viable 9285 // functions. 9286 if (!Cand2.Viable) 9287 return Cand1.Viable; 9288 else if (!Cand1.Viable) 9289 return false; 9290 9291 // C++ [over.match.best]p1: 9292 // 9293 // -- if F is a static member function, ICS1(F) is defined such 9294 // that ICS1(F) is neither better nor worse than ICS1(G) for 9295 // any function G, and, symmetrically, ICS1(G) is neither 9296 // better nor worse than ICS1(F). 9297 unsigned StartArg = 0; 9298 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9299 StartArg = 1; 9300 9301 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9302 // We don't allow incompatible pointer conversions in C++. 9303 if (!S.getLangOpts().CPlusPlus) 9304 return ICS.isStandard() && 9305 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9306 9307 // The only ill-formed conversion we allow in C++ is the string literal to 9308 // char* conversion, which is only considered ill-formed after C++11. 9309 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9310 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9311 }; 9312 9313 // Define functions that don't require ill-formed conversions for a given 9314 // argument to be better candidates than functions that do. 9315 unsigned NumArgs = Cand1.Conversions.size(); 9316 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9317 bool HasBetterConversion = false; 9318 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9319 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9320 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9321 if (Cand1Bad != Cand2Bad) { 9322 if (Cand1Bad) 9323 return false; 9324 HasBetterConversion = true; 9325 } 9326 } 9327 9328 if (HasBetterConversion) 9329 return true; 9330 9331 // C++ [over.match.best]p1: 9332 // A viable function F1 is defined to be a better function than another 9333 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9334 // conversion sequence than ICSi(F2), and then... 9335 bool HasWorseConversion = false; 9336 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9337 switch (CompareImplicitConversionSequences(S, Loc, 9338 Cand1.Conversions[ArgIdx], 9339 Cand2.Conversions[ArgIdx])) { 9340 case ImplicitConversionSequence::Better: 9341 // Cand1 has a better conversion sequence. 9342 HasBetterConversion = true; 9343 break; 9344 9345 case ImplicitConversionSequence::Worse: 9346 if (Cand1.Function && Cand1.Function == Cand2.Function && 9347 (Cand2.RewriteKind & CRK_Reversed) != 0) { 9348 // Work around large-scale breakage caused by considering reversed 9349 // forms of operator== in C++20: 9350 // 9351 // When comparing a function against its reversed form, if we have a 9352 // better conversion for one argument and a worse conversion for the 9353 // other, we prefer the non-reversed form. 9354 // 9355 // This prevents a conversion function from being considered ambiguous 9356 // with its own reversed form in various where it's only incidentally 9357 // heterogeneous. 9358 // 9359 // We diagnose this as an extension from CreateOverloadedBinOp. 9360 HasWorseConversion = true; 9361 break; 9362 } 9363 9364 // Cand1 can't be better than Cand2. 9365 return false; 9366 9367 case ImplicitConversionSequence::Indistinguishable: 9368 // Do nothing. 9369 break; 9370 } 9371 } 9372 9373 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9374 // ICSj(F2), or, if not that, 9375 if (HasBetterConversion) 9376 return true; 9377 if (HasWorseConversion) 9378 return false; 9379 9380 // -- the context is an initialization by user-defined conversion 9381 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9382 // from the return type of F1 to the destination type (i.e., 9383 // the type of the entity being initialized) is a better 9384 // conversion sequence than the standard conversion sequence 9385 // from the return type of F2 to the destination type. 9386 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9387 Cand1.Function && Cand2.Function && 9388 isa<CXXConversionDecl>(Cand1.Function) && 9389 isa<CXXConversionDecl>(Cand2.Function)) { 9390 // First check whether we prefer one of the conversion functions over the 9391 // other. This only distinguishes the results in non-standard, extension 9392 // cases such as the conversion from a lambda closure type to a function 9393 // pointer or block. 9394 ImplicitConversionSequence::CompareKind Result = 9395 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9396 if (Result == ImplicitConversionSequence::Indistinguishable) 9397 Result = CompareStandardConversionSequences(S, Loc, 9398 Cand1.FinalConversion, 9399 Cand2.FinalConversion); 9400 9401 if (Result != ImplicitConversionSequence::Indistinguishable) 9402 return Result == ImplicitConversionSequence::Better; 9403 9404 // FIXME: Compare kind of reference binding if conversion functions 9405 // convert to a reference type used in direct reference binding, per 9406 // C++14 [over.match.best]p1 section 2 bullet 3. 9407 } 9408 9409 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9410 // as combined with the resolution to CWG issue 243. 9411 // 9412 // When the context is initialization by constructor ([over.match.ctor] or 9413 // either phase of [over.match.list]), a constructor is preferred over 9414 // a conversion function. 9415 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9416 Cand1.Function && Cand2.Function && 9417 isa<CXXConstructorDecl>(Cand1.Function) != 9418 isa<CXXConstructorDecl>(Cand2.Function)) 9419 return isa<CXXConstructorDecl>(Cand1.Function); 9420 9421 // -- F1 is a non-template function and F2 is a function template 9422 // specialization, or, if not that, 9423 bool Cand1IsSpecialization = Cand1.Function && 9424 Cand1.Function->getPrimaryTemplate(); 9425 bool Cand2IsSpecialization = Cand2.Function && 9426 Cand2.Function->getPrimaryTemplate(); 9427 if (Cand1IsSpecialization != Cand2IsSpecialization) 9428 return Cand2IsSpecialization; 9429 9430 // -- F1 and F2 are function template specializations, and the function 9431 // template for F1 is more specialized than the template for F2 9432 // according to the partial ordering rules described in 14.5.5.2, or, 9433 // if not that, 9434 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9435 if (FunctionTemplateDecl *BetterTemplate 9436 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9437 Cand2.Function->getPrimaryTemplate(), 9438 Loc, 9439 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9440 : TPOC_Call, 9441 Cand1.ExplicitCallArguments, 9442 Cand2.ExplicitCallArguments)) 9443 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9444 } 9445 9446 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9447 // class B of D, and for all arguments the corresponding parameters of 9448 // F1 and F2 have the same type. 9449 // FIXME: Implement the "all parameters have the same type" check. 9450 bool Cand1IsInherited = 9451 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9452 bool Cand2IsInherited = 9453 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9454 if (Cand1IsInherited != Cand2IsInherited) 9455 return Cand2IsInherited; 9456 else if (Cand1IsInherited) { 9457 assert(Cand2IsInherited); 9458 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9459 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9460 if (Cand1Class->isDerivedFrom(Cand2Class)) 9461 return true; 9462 if (Cand2Class->isDerivedFrom(Cand1Class)) 9463 return false; 9464 // Inherited from sibling base classes: still ambiguous. 9465 } 9466 9467 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9468 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9469 // with reversed order of parameters and F1 is not 9470 // 9471 // We rank reversed + different operator as worse than just reversed, but 9472 // that comparison can never happen, because we only consider reversing for 9473 // the maximally-rewritten operator (== or <=>). 9474 if (Cand1.RewriteKind != Cand2.RewriteKind) 9475 return Cand1.RewriteKind < Cand2.RewriteKind; 9476 9477 // Check C++17 tie-breakers for deduction guides. 9478 { 9479 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9480 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9481 if (Guide1 && Guide2) { 9482 // -- F1 is generated from a deduction-guide and F2 is not 9483 if (Guide1->isImplicit() != Guide2->isImplicit()) 9484 return Guide2->isImplicit(); 9485 9486 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9487 if (Guide1->isCopyDeductionCandidate()) 9488 return true; 9489 } 9490 } 9491 9492 // Check for enable_if value-based overload resolution. 9493 if (Cand1.Function && Cand2.Function) { 9494 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9495 if (Cmp != Comparison::Equal) 9496 return Cmp == Comparison::Better; 9497 } 9498 9499 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9500 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9501 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9502 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9503 } 9504 9505 bool HasPS1 = Cand1.Function != nullptr && 9506 functionHasPassObjectSizeParams(Cand1.Function); 9507 bool HasPS2 = Cand2.Function != nullptr && 9508 functionHasPassObjectSizeParams(Cand2.Function); 9509 if (HasPS1 != HasPS2 && HasPS1) 9510 return true; 9511 9512 return isBetterMultiversionCandidate(Cand1, Cand2); 9513 } 9514 9515 /// Determine whether two declarations are "equivalent" for the purposes of 9516 /// name lookup and overload resolution. This applies when the same internal/no 9517 /// linkage entity is defined by two modules (probably by textually including 9518 /// the same header). In such a case, we don't consider the declarations to 9519 /// declare the same entity, but we also don't want lookups with both 9520 /// declarations visible to be ambiguous in some cases (this happens when using 9521 /// a modularized libstdc++). 9522 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9523 const NamedDecl *B) { 9524 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9525 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9526 if (!VA || !VB) 9527 return false; 9528 9529 // The declarations must be declaring the same name as an internal linkage 9530 // entity in different modules. 9531 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9532 VB->getDeclContext()->getRedeclContext()) || 9533 getOwningModule(const_cast<ValueDecl *>(VA)) == 9534 getOwningModule(const_cast<ValueDecl *>(VB)) || 9535 VA->isExternallyVisible() || VB->isExternallyVisible()) 9536 return false; 9537 9538 // Check that the declarations appear to be equivalent. 9539 // 9540 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9541 // For constants and functions, we should check the initializer or body is 9542 // the same. For non-constant variables, we shouldn't allow it at all. 9543 if (Context.hasSameType(VA->getType(), VB->getType())) 9544 return true; 9545 9546 // Enum constants within unnamed enumerations will have different types, but 9547 // may still be similar enough to be interchangeable for our purposes. 9548 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9549 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9550 // Only handle anonymous enums. If the enumerations were named and 9551 // equivalent, they would have been merged to the same type. 9552 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9553 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9554 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9555 !Context.hasSameType(EnumA->getIntegerType(), 9556 EnumB->getIntegerType())) 9557 return false; 9558 // Allow this only if the value is the same for both enumerators. 9559 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9560 } 9561 } 9562 9563 // Nothing else is sufficiently similar. 9564 return false; 9565 } 9566 9567 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9568 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9569 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9570 9571 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9572 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9573 << !M << (M ? M->getFullModuleName() : ""); 9574 9575 for (auto *E : Equiv) { 9576 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9577 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9578 << !M << (M ? M->getFullModuleName() : ""); 9579 } 9580 } 9581 9582 /// Computes the best viable function (C++ 13.3.3) 9583 /// within an overload candidate set. 9584 /// 9585 /// \param Loc The location of the function name (or operator symbol) for 9586 /// which overload resolution occurs. 9587 /// 9588 /// \param Best If overload resolution was successful or found a deleted 9589 /// function, \p Best points to the candidate function found. 9590 /// 9591 /// \returns The result of overload resolution. 9592 OverloadingResult 9593 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9594 iterator &Best) { 9595 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9596 std::transform(begin(), end(), std::back_inserter(Candidates), 9597 [](OverloadCandidate &Cand) { return &Cand; }); 9598 9599 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9600 // are accepted by both clang and NVCC. However, during a particular 9601 // compilation mode only one call variant is viable. We need to 9602 // exclude non-viable overload candidates from consideration based 9603 // only on their host/device attributes. Specifically, if one 9604 // candidate call is WrongSide and the other is SameSide, we ignore 9605 // the WrongSide candidate. 9606 if (S.getLangOpts().CUDA) { 9607 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9608 bool ContainsSameSideCandidate = 9609 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9610 // Check viable function only. 9611 return Cand->Viable && Cand->Function && 9612 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9613 Sema::CFP_SameSide; 9614 }); 9615 if (ContainsSameSideCandidate) { 9616 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9617 // Check viable function only to avoid unnecessary data copying/moving. 9618 return Cand->Viable && Cand->Function && 9619 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9620 Sema::CFP_WrongSide; 9621 }; 9622 llvm::erase_if(Candidates, IsWrongSideCandidate); 9623 } 9624 } 9625 9626 // Find the best viable function. 9627 Best = end(); 9628 for (auto *Cand : Candidates) { 9629 Cand->Best = false; 9630 if (Cand->Viable) 9631 if (Best == end() || 9632 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9633 Best = Cand; 9634 } 9635 9636 // If we didn't find any viable functions, abort. 9637 if (Best == end()) 9638 return OR_No_Viable_Function; 9639 9640 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9641 9642 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 9643 PendingBest.push_back(&*Best); 9644 Best->Best = true; 9645 9646 // Make sure that this function is better than every other viable 9647 // function. If not, we have an ambiguity. 9648 while (!PendingBest.empty()) { 9649 auto *Curr = PendingBest.pop_back_val(); 9650 for (auto *Cand : Candidates) { 9651 if (Cand->Viable && !Cand->Best && 9652 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 9653 PendingBest.push_back(Cand); 9654 Cand->Best = true; 9655 9656 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 9657 Curr->Function)) 9658 EquivalentCands.push_back(Cand->Function); 9659 else 9660 Best = end(); 9661 } 9662 } 9663 } 9664 9665 // If we found more than one best candidate, this is ambiguous. 9666 if (Best == end()) 9667 return OR_Ambiguous; 9668 9669 // Best is the best viable function. 9670 if (Best->Function && Best->Function->isDeleted()) 9671 return OR_Deleted; 9672 9673 if (!EquivalentCands.empty()) 9674 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9675 EquivalentCands); 9676 9677 return OR_Success; 9678 } 9679 9680 namespace { 9681 9682 enum OverloadCandidateKind { 9683 oc_function, 9684 oc_method, 9685 oc_reversed_binary_operator, 9686 oc_constructor, 9687 oc_implicit_default_constructor, 9688 oc_implicit_copy_constructor, 9689 oc_implicit_move_constructor, 9690 oc_implicit_copy_assignment, 9691 oc_implicit_move_assignment, 9692 oc_inherited_constructor 9693 }; 9694 9695 enum OverloadCandidateSelect { 9696 ocs_non_template, 9697 ocs_template, 9698 ocs_described_template, 9699 }; 9700 9701 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9702 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9703 OverloadCandidateRewriteKind CRK, 9704 std::string &Description) { 9705 9706 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9707 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9708 isTemplate = true; 9709 Description = S.getTemplateArgumentBindingsText( 9710 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9711 } 9712 9713 OverloadCandidateSelect Select = [&]() { 9714 if (!Description.empty()) 9715 return ocs_described_template; 9716 return isTemplate ? ocs_template : ocs_non_template; 9717 }(); 9718 9719 OverloadCandidateKind Kind = [&]() { 9720 if (CRK & CRK_Reversed) 9721 return oc_reversed_binary_operator; 9722 9723 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9724 if (!Ctor->isImplicit()) { 9725 if (isa<ConstructorUsingShadowDecl>(Found)) 9726 return oc_inherited_constructor; 9727 else 9728 return oc_constructor; 9729 } 9730 9731 if (Ctor->isDefaultConstructor()) 9732 return oc_implicit_default_constructor; 9733 9734 if (Ctor->isMoveConstructor()) 9735 return oc_implicit_move_constructor; 9736 9737 assert(Ctor->isCopyConstructor() && 9738 "unexpected sort of implicit constructor"); 9739 return oc_implicit_copy_constructor; 9740 } 9741 9742 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9743 // This actually gets spelled 'candidate function' for now, but 9744 // it doesn't hurt to split it out. 9745 if (!Meth->isImplicit()) 9746 return oc_method; 9747 9748 if (Meth->isMoveAssignmentOperator()) 9749 return oc_implicit_move_assignment; 9750 9751 if (Meth->isCopyAssignmentOperator()) 9752 return oc_implicit_copy_assignment; 9753 9754 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9755 return oc_method; 9756 } 9757 9758 return oc_function; 9759 }(); 9760 9761 return std::make_pair(Kind, Select); 9762 } 9763 9764 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9765 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9766 // set. 9767 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9768 S.Diag(FoundDecl->getLocation(), 9769 diag::note_ovl_candidate_inherited_constructor) 9770 << Shadow->getNominatedBaseClass(); 9771 } 9772 9773 } // end anonymous namespace 9774 9775 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9776 const FunctionDecl *FD) { 9777 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9778 bool AlwaysTrue; 9779 if (EnableIf->getCond()->isValueDependent() || 9780 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9781 return false; 9782 if (!AlwaysTrue) 9783 return false; 9784 } 9785 return true; 9786 } 9787 9788 /// Returns true if we can take the address of the function. 9789 /// 9790 /// \param Complain - If true, we'll emit a diagnostic 9791 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9792 /// we in overload resolution? 9793 /// \param Loc - The location of the statement we're complaining about. Ignored 9794 /// if we're not complaining, or if we're in overload resolution. 9795 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9796 bool Complain, 9797 bool InOverloadResolution, 9798 SourceLocation Loc) { 9799 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9800 if (Complain) { 9801 if (InOverloadResolution) 9802 S.Diag(FD->getBeginLoc(), 9803 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9804 else 9805 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9806 } 9807 return false; 9808 } 9809 9810 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9811 return P->hasAttr<PassObjectSizeAttr>(); 9812 }); 9813 if (I == FD->param_end()) 9814 return true; 9815 9816 if (Complain) { 9817 // Add one to ParamNo because it's user-facing 9818 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9819 if (InOverloadResolution) 9820 S.Diag(FD->getLocation(), 9821 diag::note_ovl_candidate_has_pass_object_size_params) 9822 << ParamNo; 9823 else 9824 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9825 << FD << ParamNo; 9826 } 9827 return false; 9828 } 9829 9830 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9831 const FunctionDecl *FD) { 9832 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9833 /*InOverloadResolution=*/true, 9834 /*Loc=*/SourceLocation()); 9835 } 9836 9837 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9838 bool Complain, 9839 SourceLocation Loc) { 9840 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9841 /*InOverloadResolution=*/false, 9842 Loc); 9843 } 9844 9845 // Notes the location of an overload candidate. 9846 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9847 OverloadCandidateRewriteKind RewriteKind, 9848 QualType DestType, bool TakingAddress) { 9849 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9850 return; 9851 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9852 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9853 return; 9854 9855 std::string FnDesc; 9856 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9857 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 9858 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9859 << (unsigned)KSPair.first << (unsigned)KSPair.second 9860 << Fn << FnDesc; 9861 9862 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9863 Diag(Fn->getLocation(), PD); 9864 MaybeEmitInheritedConstructorNote(*this, Found); 9865 } 9866 9867 // Notes the location of all overload candidates designated through 9868 // OverloadedExpr 9869 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9870 bool TakingAddress) { 9871 assert(OverloadedExpr->getType() == Context.OverloadTy); 9872 9873 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9874 OverloadExpr *OvlExpr = Ovl.Expression; 9875 9876 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9877 IEnd = OvlExpr->decls_end(); 9878 I != IEnd; ++I) { 9879 if (FunctionTemplateDecl *FunTmpl = 9880 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9881 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 9882 TakingAddress); 9883 } else if (FunctionDecl *Fun 9884 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9885 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 9886 } 9887 } 9888 } 9889 9890 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9891 /// "lead" diagnostic; it will be given two arguments, the source and 9892 /// target types of the conversion. 9893 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9894 Sema &S, 9895 SourceLocation CaretLoc, 9896 const PartialDiagnostic &PDiag) const { 9897 S.Diag(CaretLoc, PDiag) 9898 << Ambiguous.getFromType() << Ambiguous.getToType(); 9899 // FIXME: The note limiting machinery is borrowed from 9900 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9901 // refactoring here. 9902 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9903 unsigned CandsShown = 0; 9904 AmbiguousConversionSequence::const_iterator I, E; 9905 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9906 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9907 break; 9908 ++CandsShown; 9909 S.NoteOverloadCandidate(I->first, I->second); 9910 } 9911 if (I != E) 9912 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9913 } 9914 9915 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9916 unsigned I, bool TakingCandidateAddress) { 9917 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9918 assert(Conv.isBad()); 9919 assert(Cand->Function && "for now, candidate must be a function"); 9920 FunctionDecl *Fn = Cand->Function; 9921 9922 // There's a conversion slot for the object argument if this is a 9923 // non-constructor method. Note that 'I' corresponds the 9924 // conversion-slot index. 9925 bool isObjectArgument = false; 9926 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9927 if (I == 0) 9928 isObjectArgument = true; 9929 else 9930 I--; 9931 } 9932 9933 std::string FnDesc; 9934 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9935 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->RewriteKind, 9936 FnDesc); 9937 9938 Expr *FromExpr = Conv.Bad.FromExpr; 9939 QualType FromTy = Conv.Bad.getFromType(); 9940 QualType ToTy = Conv.Bad.getToType(); 9941 9942 if (FromTy == S.Context.OverloadTy) { 9943 assert(FromExpr && "overload set argument came from implicit argument?"); 9944 Expr *E = FromExpr->IgnoreParens(); 9945 if (isa<UnaryOperator>(E)) 9946 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9947 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9948 9949 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9950 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9951 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9952 << Name << I + 1; 9953 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9954 return; 9955 } 9956 9957 // Do some hand-waving analysis to see if the non-viability is due 9958 // to a qualifier mismatch. 9959 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9960 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9961 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9962 CToTy = RT->getPointeeType(); 9963 else { 9964 // TODO: detect and diagnose the full richness of const mismatches. 9965 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9966 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9967 CFromTy = FromPT->getPointeeType(); 9968 CToTy = ToPT->getPointeeType(); 9969 } 9970 } 9971 9972 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9973 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9974 Qualifiers FromQs = CFromTy.getQualifiers(); 9975 Qualifiers ToQs = CToTy.getQualifiers(); 9976 9977 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9978 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9979 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9980 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9981 << ToTy << (unsigned)isObjectArgument << I + 1; 9982 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9983 return; 9984 } 9985 9986 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9987 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9988 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9989 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9990 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9991 << (unsigned)isObjectArgument << I + 1; 9992 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9993 return; 9994 } 9995 9996 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9997 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9998 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9999 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10000 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10001 << (unsigned)isObjectArgument << I + 1; 10002 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10003 return; 10004 } 10005 10006 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10007 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10008 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10009 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10010 << FromQs.hasUnaligned() << I + 1; 10011 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10012 return; 10013 } 10014 10015 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10016 assert(CVR && "unexpected qualifiers mismatch"); 10017 10018 if (isObjectArgument) { 10019 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10020 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10021 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10022 << (CVR - 1); 10023 } else { 10024 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10025 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10026 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10027 << (CVR - 1) << I + 1; 10028 } 10029 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10030 return; 10031 } 10032 10033 // Special diagnostic for failure to convert an initializer list, since 10034 // telling the user that it has type void is not useful. 10035 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10036 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10037 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10038 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10039 << ToTy << (unsigned)isObjectArgument << I + 1; 10040 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10041 return; 10042 } 10043 10044 // Diagnose references or pointers to incomplete types differently, 10045 // since it's far from impossible that the incompleteness triggered 10046 // the failure. 10047 QualType TempFromTy = FromTy.getNonReferenceType(); 10048 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10049 TempFromTy = PTy->getPointeeType(); 10050 if (TempFromTy->isIncompleteType()) { 10051 // Emit the generic diagnostic and, optionally, add the hints to it. 10052 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10053 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10054 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10055 << ToTy << (unsigned)isObjectArgument << I + 1 10056 << (unsigned)(Cand->Fix.Kind); 10057 10058 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10059 return; 10060 } 10061 10062 // Diagnose base -> derived pointer conversions. 10063 unsigned BaseToDerivedConversion = 0; 10064 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10065 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10066 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10067 FromPtrTy->getPointeeType()) && 10068 !FromPtrTy->getPointeeType()->isIncompleteType() && 10069 !ToPtrTy->getPointeeType()->isIncompleteType() && 10070 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10071 FromPtrTy->getPointeeType())) 10072 BaseToDerivedConversion = 1; 10073 } 10074 } else if (const ObjCObjectPointerType *FromPtrTy 10075 = FromTy->getAs<ObjCObjectPointerType>()) { 10076 if (const ObjCObjectPointerType *ToPtrTy 10077 = ToTy->getAs<ObjCObjectPointerType>()) 10078 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10079 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10080 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10081 FromPtrTy->getPointeeType()) && 10082 FromIface->isSuperClassOf(ToIface)) 10083 BaseToDerivedConversion = 2; 10084 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10085 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10086 !FromTy->isIncompleteType() && 10087 !ToRefTy->getPointeeType()->isIncompleteType() && 10088 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10089 BaseToDerivedConversion = 3; 10090 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 10091 ToTy.getNonReferenceType().getCanonicalType() == 10092 FromTy.getNonReferenceType().getCanonicalType()) { 10093 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10094 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10095 << (unsigned)isObjectArgument << I + 1 10096 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10097 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10098 return; 10099 } 10100 } 10101 10102 if (BaseToDerivedConversion) { 10103 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10104 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10105 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10106 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10107 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10108 return; 10109 } 10110 10111 if (isa<ObjCObjectPointerType>(CFromTy) && 10112 isa<PointerType>(CToTy)) { 10113 Qualifiers FromQs = CFromTy.getQualifiers(); 10114 Qualifiers ToQs = CToTy.getQualifiers(); 10115 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10116 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10117 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10118 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10119 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10120 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10121 return; 10122 } 10123 } 10124 10125 if (TakingCandidateAddress && 10126 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10127 return; 10128 10129 // Emit the generic diagnostic and, optionally, add the hints to it. 10130 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10131 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10132 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10133 << ToTy << (unsigned)isObjectArgument << I + 1 10134 << (unsigned)(Cand->Fix.Kind); 10135 10136 // If we can fix the conversion, suggest the FixIts. 10137 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10138 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10139 FDiag << *HI; 10140 S.Diag(Fn->getLocation(), FDiag); 10141 10142 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10143 } 10144 10145 /// Additional arity mismatch diagnosis specific to a function overload 10146 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10147 /// over a candidate in any candidate set. 10148 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10149 unsigned NumArgs) { 10150 FunctionDecl *Fn = Cand->Function; 10151 unsigned MinParams = Fn->getMinRequiredArguments(); 10152 10153 // With invalid overloaded operators, it's possible that we think we 10154 // have an arity mismatch when in fact it looks like we have the 10155 // right number of arguments, because only overloaded operators have 10156 // the weird behavior of overloading member and non-member functions. 10157 // Just don't report anything. 10158 if (Fn->isInvalidDecl() && 10159 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10160 return true; 10161 10162 if (NumArgs < MinParams) { 10163 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10164 (Cand->FailureKind == ovl_fail_bad_deduction && 10165 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10166 } else { 10167 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10168 (Cand->FailureKind == ovl_fail_bad_deduction && 10169 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10170 } 10171 10172 return false; 10173 } 10174 10175 /// General arity mismatch diagnosis over a candidate in a candidate set. 10176 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10177 unsigned NumFormalArgs) { 10178 assert(isa<FunctionDecl>(D) && 10179 "The templated declaration should at least be a function" 10180 " when diagnosing bad template argument deduction due to too many" 10181 " or too few arguments"); 10182 10183 FunctionDecl *Fn = cast<FunctionDecl>(D); 10184 10185 // TODO: treat calls to a missing default constructor as a special case 10186 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 10187 unsigned MinParams = Fn->getMinRequiredArguments(); 10188 10189 // at least / at most / exactly 10190 unsigned mode, modeCount; 10191 if (NumFormalArgs < MinParams) { 10192 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10193 FnTy->isTemplateVariadic()) 10194 mode = 0; // "at least" 10195 else 10196 mode = 2; // "exactly" 10197 modeCount = MinParams; 10198 } else { 10199 if (MinParams != FnTy->getNumParams()) 10200 mode = 1; // "at most" 10201 else 10202 mode = 2; // "exactly" 10203 modeCount = FnTy->getNumParams(); 10204 } 10205 10206 std::string Description; 10207 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10208 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10209 10210 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10211 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10212 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10213 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10214 else 10215 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10216 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10217 << Description << mode << modeCount << NumFormalArgs; 10218 10219 MaybeEmitInheritedConstructorNote(S, Found); 10220 } 10221 10222 /// Arity mismatch diagnosis specific to a function overload candidate. 10223 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10224 unsigned NumFormalArgs) { 10225 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10226 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10227 } 10228 10229 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10230 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10231 return TD; 10232 llvm_unreachable("Unsupported: Getting the described template declaration" 10233 " for bad deduction diagnosis"); 10234 } 10235 10236 /// Diagnose a failed template-argument deduction. 10237 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10238 DeductionFailureInfo &DeductionFailure, 10239 unsigned NumArgs, 10240 bool TakingCandidateAddress) { 10241 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10242 NamedDecl *ParamD; 10243 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10244 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10245 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10246 switch (DeductionFailure.Result) { 10247 case Sema::TDK_Success: 10248 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10249 10250 case Sema::TDK_Incomplete: { 10251 assert(ParamD && "no parameter found for incomplete deduction result"); 10252 S.Diag(Templated->getLocation(), 10253 diag::note_ovl_candidate_incomplete_deduction) 10254 << ParamD->getDeclName(); 10255 MaybeEmitInheritedConstructorNote(S, Found); 10256 return; 10257 } 10258 10259 case Sema::TDK_IncompletePack: { 10260 assert(ParamD && "no parameter found for incomplete deduction result"); 10261 S.Diag(Templated->getLocation(), 10262 diag::note_ovl_candidate_incomplete_deduction_pack) 10263 << ParamD->getDeclName() 10264 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10265 << *DeductionFailure.getFirstArg(); 10266 MaybeEmitInheritedConstructorNote(S, Found); 10267 return; 10268 } 10269 10270 case Sema::TDK_Underqualified: { 10271 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10272 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10273 10274 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10275 10276 // Param will have been canonicalized, but it should just be a 10277 // qualified version of ParamD, so move the qualifiers to that. 10278 QualifierCollector Qs; 10279 Qs.strip(Param); 10280 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10281 assert(S.Context.hasSameType(Param, NonCanonParam)); 10282 10283 // Arg has also been canonicalized, but there's nothing we can do 10284 // about that. It also doesn't matter as much, because it won't 10285 // have any template parameters in it (because deduction isn't 10286 // done on dependent types). 10287 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10288 10289 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10290 << ParamD->getDeclName() << Arg << NonCanonParam; 10291 MaybeEmitInheritedConstructorNote(S, Found); 10292 return; 10293 } 10294 10295 case Sema::TDK_Inconsistent: { 10296 assert(ParamD && "no parameter found for inconsistent deduction result"); 10297 int which = 0; 10298 if (isa<TemplateTypeParmDecl>(ParamD)) 10299 which = 0; 10300 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10301 // Deduction might have failed because we deduced arguments of two 10302 // different types for a non-type template parameter. 10303 // FIXME: Use a different TDK value for this. 10304 QualType T1 = 10305 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10306 QualType T2 = 10307 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10308 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10309 S.Diag(Templated->getLocation(), 10310 diag::note_ovl_candidate_inconsistent_deduction_types) 10311 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10312 << *DeductionFailure.getSecondArg() << T2; 10313 MaybeEmitInheritedConstructorNote(S, Found); 10314 return; 10315 } 10316 10317 which = 1; 10318 } else { 10319 which = 2; 10320 } 10321 10322 S.Diag(Templated->getLocation(), 10323 diag::note_ovl_candidate_inconsistent_deduction) 10324 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10325 << *DeductionFailure.getSecondArg(); 10326 MaybeEmitInheritedConstructorNote(S, Found); 10327 return; 10328 } 10329 10330 case Sema::TDK_InvalidExplicitArguments: 10331 assert(ParamD && "no parameter found for invalid explicit arguments"); 10332 if (ParamD->getDeclName()) 10333 S.Diag(Templated->getLocation(), 10334 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10335 << ParamD->getDeclName(); 10336 else { 10337 int index = 0; 10338 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10339 index = TTP->getIndex(); 10340 else if (NonTypeTemplateParmDecl *NTTP 10341 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10342 index = NTTP->getIndex(); 10343 else 10344 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10345 S.Diag(Templated->getLocation(), 10346 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10347 << (index + 1); 10348 } 10349 MaybeEmitInheritedConstructorNote(S, Found); 10350 return; 10351 10352 case Sema::TDK_TooManyArguments: 10353 case Sema::TDK_TooFewArguments: 10354 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10355 return; 10356 10357 case Sema::TDK_InstantiationDepth: 10358 S.Diag(Templated->getLocation(), 10359 diag::note_ovl_candidate_instantiation_depth); 10360 MaybeEmitInheritedConstructorNote(S, Found); 10361 return; 10362 10363 case Sema::TDK_SubstitutionFailure: { 10364 // Format the template argument list into the argument string. 10365 SmallString<128> TemplateArgString; 10366 if (TemplateArgumentList *Args = 10367 DeductionFailure.getTemplateArgumentList()) { 10368 TemplateArgString = " "; 10369 TemplateArgString += S.getTemplateArgumentBindingsText( 10370 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10371 } 10372 10373 // If this candidate was disabled by enable_if, say so. 10374 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10375 if (PDiag && PDiag->second.getDiagID() == 10376 diag::err_typename_nested_not_found_enable_if) { 10377 // FIXME: Use the source range of the condition, and the fully-qualified 10378 // name of the enable_if template. These are both present in PDiag. 10379 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10380 << "'enable_if'" << TemplateArgString; 10381 return; 10382 } 10383 10384 // We found a specific requirement that disabled the enable_if. 10385 if (PDiag && PDiag->second.getDiagID() == 10386 diag::err_typename_nested_not_found_requirement) { 10387 S.Diag(Templated->getLocation(), 10388 diag::note_ovl_candidate_disabled_by_requirement) 10389 << PDiag->second.getStringArg(0) << TemplateArgString; 10390 return; 10391 } 10392 10393 // Format the SFINAE diagnostic into the argument string. 10394 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10395 // formatted message in another diagnostic. 10396 SmallString<128> SFINAEArgString; 10397 SourceRange R; 10398 if (PDiag) { 10399 SFINAEArgString = ": "; 10400 R = SourceRange(PDiag->first, PDiag->first); 10401 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10402 } 10403 10404 S.Diag(Templated->getLocation(), 10405 diag::note_ovl_candidate_substitution_failure) 10406 << TemplateArgString << SFINAEArgString << R; 10407 MaybeEmitInheritedConstructorNote(S, Found); 10408 return; 10409 } 10410 10411 case Sema::TDK_DeducedMismatch: 10412 case Sema::TDK_DeducedMismatchNested: { 10413 // Format the template argument list into the argument string. 10414 SmallString<128> TemplateArgString; 10415 if (TemplateArgumentList *Args = 10416 DeductionFailure.getTemplateArgumentList()) { 10417 TemplateArgString = " "; 10418 TemplateArgString += S.getTemplateArgumentBindingsText( 10419 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10420 } 10421 10422 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10423 << (*DeductionFailure.getCallArgIndex() + 1) 10424 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10425 << TemplateArgString 10426 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10427 break; 10428 } 10429 10430 case Sema::TDK_NonDeducedMismatch: { 10431 // FIXME: Provide a source location to indicate what we couldn't match. 10432 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10433 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10434 if (FirstTA.getKind() == TemplateArgument::Template && 10435 SecondTA.getKind() == TemplateArgument::Template) { 10436 TemplateName FirstTN = FirstTA.getAsTemplate(); 10437 TemplateName SecondTN = SecondTA.getAsTemplate(); 10438 if (FirstTN.getKind() == TemplateName::Template && 10439 SecondTN.getKind() == TemplateName::Template) { 10440 if (FirstTN.getAsTemplateDecl()->getName() == 10441 SecondTN.getAsTemplateDecl()->getName()) { 10442 // FIXME: This fixes a bad diagnostic where both templates are named 10443 // the same. This particular case is a bit difficult since: 10444 // 1) It is passed as a string to the diagnostic printer. 10445 // 2) The diagnostic printer only attempts to find a better 10446 // name for types, not decls. 10447 // Ideally, this should folded into the diagnostic printer. 10448 S.Diag(Templated->getLocation(), 10449 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10450 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10451 return; 10452 } 10453 } 10454 } 10455 10456 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10457 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10458 return; 10459 10460 // FIXME: For generic lambda parameters, check if the function is a lambda 10461 // call operator, and if so, emit a prettier and more informative 10462 // diagnostic that mentions 'auto' and lambda in addition to 10463 // (or instead of?) the canonical template type parameters. 10464 S.Diag(Templated->getLocation(), 10465 diag::note_ovl_candidate_non_deduced_mismatch) 10466 << FirstTA << SecondTA; 10467 return; 10468 } 10469 // TODO: diagnose these individually, then kill off 10470 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10471 case Sema::TDK_MiscellaneousDeductionFailure: 10472 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10473 MaybeEmitInheritedConstructorNote(S, Found); 10474 return; 10475 case Sema::TDK_CUDATargetMismatch: 10476 S.Diag(Templated->getLocation(), 10477 diag::note_cuda_ovl_candidate_target_mismatch); 10478 return; 10479 } 10480 } 10481 10482 /// Diagnose a failed template-argument deduction, for function calls. 10483 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10484 unsigned NumArgs, 10485 bool TakingCandidateAddress) { 10486 unsigned TDK = Cand->DeductionFailure.Result; 10487 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10488 if (CheckArityMismatch(S, Cand, NumArgs)) 10489 return; 10490 } 10491 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10492 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10493 } 10494 10495 /// CUDA: diagnose an invalid call across targets. 10496 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10497 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10498 FunctionDecl *Callee = Cand->Function; 10499 10500 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10501 CalleeTarget = S.IdentifyCUDATarget(Callee); 10502 10503 std::string FnDesc; 10504 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10505 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, Cand->RewriteKind, 10506 FnDesc); 10507 10508 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10509 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10510 << FnDesc /* Ignored */ 10511 << CalleeTarget << CallerTarget; 10512 10513 // This could be an implicit constructor for which we could not infer the 10514 // target due to a collsion. Diagnose that case. 10515 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10516 if (Meth != nullptr && Meth->isImplicit()) { 10517 CXXRecordDecl *ParentClass = Meth->getParent(); 10518 Sema::CXXSpecialMember CSM; 10519 10520 switch (FnKindPair.first) { 10521 default: 10522 return; 10523 case oc_implicit_default_constructor: 10524 CSM = Sema::CXXDefaultConstructor; 10525 break; 10526 case oc_implicit_copy_constructor: 10527 CSM = Sema::CXXCopyConstructor; 10528 break; 10529 case oc_implicit_move_constructor: 10530 CSM = Sema::CXXMoveConstructor; 10531 break; 10532 case oc_implicit_copy_assignment: 10533 CSM = Sema::CXXCopyAssignment; 10534 break; 10535 case oc_implicit_move_assignment: 10536 CSM = Sema::CXXMoveAssignment; 10537 break; 10538 }; 10539 10540 bool ConstRHS = false; 10541 if (Meth->getNumParams()) { 10542 if (const ReferenceType *RT = 10543 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10544 ConstRHS = RT->getPointeeType().isConstQualified(); 10545 } 10546 } 10547 10548 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10549 /* ConstRHS */ ConstRHS, 10550 /* Diagnose */ true); 10551 } 10552 } 10553 10554 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10555 FunctionDecl *Callee = Cand->Function; 10556 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10557 10558 S.Diag(Callee->getLocation(), 10559 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10560 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10561 } 10562 10563 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10564 ExplicitSpecifier ES; 10565 const char *DeclName; 10566 switch (Cand->Function->getDeclKind()) { 10567 case Decl::Kind::CXXConstructor: 10568 ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier(); 10569 DeclName = "constructor"; 10570 break; 10571 case Decl::Kind::CXXConversion: 10572 ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier(); 10573 DeclName = "conversion operator"; 10574 break; 10575 case Decl::Kind::CXXDeductionGuide: 10576 ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier(); 10577 DeclName = "deductiong guide"; 10578 break; 10579 default: 10580 llvm_unreachable("invalid Decl"); 10581 } 10582 assert(ES.getExpr() && "null expression should be handled before"); 10583 S.Diag(Cand->Function->getLocation(), 10584 diag::note_ovl_candidate_explicit_forbidden) 10585 << DeclName; 10586 S.Diag(ES.getExpr()->getBeginLoc(), 10587 diag::note_explicit_bool_resolved_to_true); 10588 } 10589 10590 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10591 FunctionDecl *Callee = Cand->Function; 10592 10593 S.Diag(Callee->getLocation(), 10594 diag::note_ovl_candidate_disabled_by_extension) 10595 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10596 } 10597 10598 /// Generates a 'note' diagnostic for an overload candidate. We've 10599 /// already generated a primary error at the call site. 10600 /// 10601 /// It really does need to be a single diagnostic with its caret 10602 /// pointed at the candidate declaration. Yes, this creates some 10603 /// major challenges of technical writing. Yes, this makes pointing 10604 /// out problems with specific arguments quite awkward. It's still 10605 /// better than generating twenty screens of text for every failed 10606 /// overload. 10607 /// 10608 /// It would be great to be able to express per-candidate problems 10609 /// more richly for those diagnostic clients that cared, but we'd 10610 /// still have to be just as careful with the default diagnostics. 10611 /// \param CtorDestAS Addr space of object being constructed (for ctor 10612 /// candidates only). 10613 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10614 unsigned NumArgs, 10615 bool TakingCandidateAddress, 10616 LangAS CtorDestAS = LangAS::Default) { 10617 FunctionDecl *Fn = Cand->Function; 10618 10619 // Note deleted candidates, but only if they're viable. 10620 if (Cand->Viable) { 10621 if (Fn->isDeleted()) { 10622 std::string FnDesc; 10623 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10624 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->RewriteKind, 10625 FnDesc); 10626 10627 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10628 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10629 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10630 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10631 return; 10632 } 10633 10634 // We don't really have anything else to say about viable candidates. 10635 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->RewriteKind); 10636 return; 10637 } 10638 10639 switch (Cand->FailureKind) { 10640 case ovl_fail_too_many_arguments: 10641 case ovl_fail_too_few_arguments: 10642 return DiagnoseArityMismatch(S, Cand, NumArgs); 10643 10644 case ovl_fail_bad_deduction: 10645 return DiagnoseBadDeduction(S, Cand, NumArgs, 10646 TakingCandidateAddress); 10647 10648 case ovl_fail_illegal_constructor: { 10649 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10650 << (Fn->getPrimaryTemplate() ? 1 : 0); 10651 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10652 return; 10653 } 10654 10655 case ovl_fail_object_addrspace_mismatch: { 10656 Qualifiers QualsForPrinting; 10657 QualsForPrinting.setAddressSpace(CtorDestAS); 10658 S.Diag(Fn->getLocation(), 10659 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 10660 << QualsForPrinting; 10661 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10662 return; 10663 } 10664 10665 case ovl_fail_trivial_conversion: 10666 case ovl_fail_bad_final_conversion: 10667 case ovl_fail_final_conversion_not_exact: 10668 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->RewriteKind); 10669 10670 case ovl_fail_bad_conversion: { 10671 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10672 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10673 if (Cand->Conversions[I].isBad()) 10674 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10675 10676 // FIXME: this currently happens when we're called from SemaInit 10677 // when user-conversion overload fails. Figure out how to handle 10678 // those conditions and diagnose them well. 10679 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->RewriteKind); 10680 } 10681 10682 case ovl_fail_bad_target: 10683 return DiagnoseBadTarget(S, Cand); 10684 10685 case ovl_fail_enable_if: 10686 return DiagnoseFailedEnableIfAttr(S, Cand); 10687 10688 case ovl_fail_explicit_resolved: 10689 return DiagnoseFailedExplicitSpec(S, Cand); 10690 10691 case ovl_fail_ext_disabled: 10692 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10693 10694 case ovl_fail_inhctor_slice: 10695 // It's generally not interesting to note copy/move constructors here. 10696 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10697 return; 10698 S.Diag(Fn->getLocation(), 10699 diag::note_ovl_candidate_inherited_constructor_slice) 10700 << (Fn->getPrimaryTemplate() ? 1 : 0) 10701 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10702 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10703 return; 10704 10705 case ovl_fail_addr_not_available: { 10706 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10707 (void)Available; 10708 assert(!Available); 10709 break; 10710 } 10711 case ovl_non_default_multiversion_function: 10712 // Do nothing, these should simply be ignored. 10713 break; 10714 } 10715 } 10716 10717 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10718 // Desugar the type of the surrogate down to a function type, 10719 // retaining as many typedefs as possible while still showing 10720 // the function type (and, therefore, its parameter types). 10721 QualType FnType = Cand->Surrogate->getConversionType(); 10722 bool isLValueReference = false; 10723 bool isRValueReference = false; 10724 bool isPointer = false; 10725 if (const LValueReferenceType *FnTypeRef = 10726 FnType->getAs<LValueReferenceType>()) { 10727 FnType = FnTypeRef->getPointeeType(); 10728 isLValueReference = true; 10729 } else if (const RValueReferenceType *FnTypeRef = 10730 FnType->getAs<RValueReferenceType>()) { 10731 FnType = FnTypeRef->getPointeeType(); 10732 isRValueReference = true; 10733 } 10734 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10735 FnType = FnTypePtr->getPointeeType(); 10736 isPointer = true; 10737 } 10738 // Desugar down to a function type. 10739 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10740 // Reconstruct the pointer/reference as appropriate. 10741 if (isPointer) FnType = S.Context.getPointerType(FnType); 10742 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10743 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10744 10745 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10746 << FnType; 10747 } 10748 10749 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10750 SourceLocation OpLoc, 10751 OverloadCandidate *Cand) { 10752 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10753 std::string TypeStr("operator"); 10754 TypeStr += Opc; 10755 TypeStr += "("; 10756 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10757 if (Cand->Conversions.size() == 1) { 10758 TypeStr += ")"; 10759 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 10760 } else { 10761 TypeStr += ", "; 10762 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10763 TypeStr += ")"; 10764 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 10765 } 10766 } 10767 10768 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10769 OverloadCandidate *Cand) { 10770 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10771 if (ICS.isBad()) break; // all meaningless after first invalid 10772 if (!ICS.isAmbiguous()) continue; 10773 10774 ICS.DiagnoseAmbiguousConversion( 10775 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10776 } 10777 } 10778 10779 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10780 if (Cand->Function) 10781 return Cand->Function->getLocation(); 10782 if (Cand->IsSurrogate) 10783 return Cand->Surrogate->getLocation(); 10784 return SourceLocation(); 10785 } 10786 10787 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10788 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10789 case Sema::TDK_Success: 10790 case Sema::TDK_NonDependentConversionFailure: 10791 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10792 10793 case Sema::TDK_Invalid: 10794 case Sema::TDK_Incomplete: 10795 case Sema::TDK_IncompletePack: 10796 return 1; 10797 10798 case Sema::TDK_Underqualified: 10799 case Sema::TDK_Inconsistent: 10800 return 2; 10801 10802 case Sema::TDK_SubstitutionFailure: 10803 case Sema::TDK_DeducedMismatch: 10804 case Sema::TDK_DeducedMismatchNested: 10805 case Sema::TDK_NonDeducedMismatch: 10806 case Sema::TDK_MiscellaneousDeductionFailure: 10807 case Sema::TDK_CUDATargetMismatch: 10808 return 3; 10809 10810 case Sema::TDK_InstantiationDepth: 10811 return 4; 10812 10813 case Sema::TDK_InvalidExplicitArguments: 10814 return 5; 10815 10816 case Sema::TDK_TooManyArguments: 10817 case Sema::TDK_TooFewArguments: 10818 return 6; 10819 } 10820 llvm_unreachable("Unhandled deduction result"); 10821 } 10822 10823 namespace { 10824 struct CompareOverloadCandidatesForDisplay { 10825 Sema &S; 10826 SourceLocation Loc; 10827 size_t NumArgs; 10828 OverloadCandidateSet::CandidateSetKind CSK; 10829 10830 CompareOverloadCandidatesForDisplay( 10831 Sema &S, SourceLocation Loc, size_t NArgs, 10832 OverloadCandidateSet::CandidateSetKind CSK) 10833 : S(S), NumArgs(NArgs), CSK(CSK) {} 10834 10835 bool operator()(const OverloadCandidate *L, 10836 const OverloadCandidate *R) { 10837 // Fast-path this check. 10838 if (L == R) return false; 10839 10840 // Order first by viability. 10841 if (L->Viable) { 10842 if (!R->Viable) return true; 10843 10844 // TODO: introduce a tri-valued comparison for overload 10845 // candidates. Would be more worthwhile if we had a sort 10846 // that could exploit it. 10847 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10848 return true; 10849 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10850 return false; 10851 } else if (R->Viable) 10852 return false; 10853 10854 assert(L->Viable == R->Viable); 10855 10856 // Criteria by which we can sort non-viable candidates: 10857 if (!L->Viable) { 10858 // 1. Arity mismatches come after other candidates. 10859 if (L->FailureKind == ovl_fail_too_many_arguments || 10860 L->FailureKind == ovl_fail_too_few_arguments) { 10861 if (R->FailureKind == ovl_fail_too_many_arguments || 10862 R->FailureKind == ovl_fail_too_few_arguments) { 10863 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10864 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10865 if (LDist == RDist) { 10866 if (L->FailureKind == R->FailureKind) 10867 // Sort non-surrogates before surrogates. 10868 return !L->IsSurrogate && R->IsSurrogate; 10869 // Sort candidates requiring fewer parameters than there were 10870 // arguments given after candidates requiring more parameters 10871 // than there were arguments given. 10872 return L->FailureKind == ovl_fail_too_many_arguments; 10873 } 10874 return LDist < RDist; 10875 } 10876 return false; 10877 } 10878 if (R->FailureKind == ovl_fail_too_many_arguments || 10879 R->FailureKind == ovl_fail_too_few_arguments) 10880 return true; 10881 10882 // 2. Bad conversions come first and are ordered by the number 10883 // of bad conversions and quality of good conversions. 10884 if (L->FailureKind == ovl_fail_bad_conversion) { 10885 if (R->FailureKind != ovl_fail_bad_conversion) 10886 return true; 10887 10888 // The conversion that can be fixed with a smaller number of changes, 10889 // comes first. 10890 unsigned numLFixes = L->Fix.NumConversionsFixed; 10891 unsigned numRFixes = R->Fix.NumConversionsFixed; 10892 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10893 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10894 if (numLFixes != numRFixes) { 10895 return numLFixes < numRFixes; 10896 } 10897 10898 // If there's any ordering between the defined conversions... 10899 // FIXME: this might not be transitive. 10900 assert(L->Conversions.size() == R->Conversions.size()); 10901 10902 int leftBetter = 0; 10903 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10904 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10905 switch (CompareImplicitConversionSequences(S, Loc, 10906 L->Conversions[I], 10907 R->Conversions[I])) { 10908 case ImplicitConversionSequence::Better: 10909 leftBetter++; 10910 break; 10911 10912 case ImplicitConversionSequence::Worse: 10913 leftBetter--; 10914 break; 10915 10916 case ImplicitConversionSequence::Indistinguishable: 10917 break; 10918 } 10919 } 10920 if (leftBetter > 0) return true; 10921 if (leftBetter < 0) return false; 10922 10923 } else if (R->FailureKind == ovl_fail_bad_conversion) 10924 return false; 10925 10926 if (L->FailureKind == ovl_fail_bad_deduction) { 10927 if (R->FailureKind != ovl_fail_bad_deduction) 10928 return true; 10929 10930 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10931 return RankDeductionFailure(L->DeductionFailure) 10932 < RankDeductionFailure(R->DeductionFailure); 10933 } else if (R->FailureKind == ovl_fail_bad_deduction) 10934 return false; 10935 10936 // TODO: others? 10937 } 10938 10939 // Sort everything else by location. 10940 SourceLocation LLoc = GetLocationForCandidate(L); 10941 SourceLocation RLoc = GetLocationForCandidate(R); 10942 10943 // Put candidates without locations (e.g. builtins) at the end. 10944 if (LLoc.isInvalid()) return false; 10945 if (RLoc.isInvalid()) return true; 10946 10947 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10948 } 10949 }; 10950 } 10951 10952 /// CompleteNonViableCandidate - Normally, overload resolution only 10953 /// computes up to the first bad conversion. Produces the FixIt set if 10954 /// possible. 10955 static void 10956 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10957 ArrayRef<Expr *> Args, 10958 OverloadCandidateSet::CandidateSetKind CSK) { 10959 assert(!Cand->Viable); 10960 10961 // Don't do anything on failures other than bad conversion. 10962 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10963 10964 // We only want the FixIts if all the arguments can be corrected. 10965 bool Unfixable = false; 10966 // Use a implicit copy initialization to check conversion fixes. 10967 Cand->Fix.setConversionChecker(TryCopyInitialization); 10968 10969 // Attempt to fix the bad conversion. 10970 unsigned ConvCount = Cand->Conversions.size(); 10971 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10972 ++ConvIdx) { 10973 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10974 if (Cand->Conversions[ConvIdx].isInitialized() && 10975 Cand->Conversions[ConvIdx].isBad()) { 10976 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10977 break; 10978 } 10979 } 10980 10981 // FIXME: this should probably be preserved from the overload 10982 // operation somehow. 10983 bool SuppressUserConversions = false; 10984 10985 unsigned ConvIdx = 0; 10986 unsigned ArgIdx = 0; 10987 ArrayRef<QualType> ParamTypes; 10988 10989 if (Cand->IsSurrogate) { 10990 QualType ConvType 10991 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10992 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10993 ConvType = ConvPtrType->getPointeeType(); 10994 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 10995 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 10996 ConvIdx = 1; 10997 } else if (Cand->Function) { 10998 ParamTypes = 10999 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11000 if (isa<CXXMethodDecl>(Cand->Function) && 11001 !isa<CXXConstructorDecl>(Cand->Function)) { 11002 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11003 ConvIdx = 1; 11004 if (CSK == OverloadCandidateSet::CSK_Operator) 11005 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11006 ArgIdx = 1; 11007 } 11008 } else { 11009 // Builtin operator. 11010 assert(ConvCount <= 3); 11011 ParamTypes = Cand->BuiltinParamTypes; 11012 } 11013 11014 // Fill in the rest of the conversions. 11015 bool Reversed = Cand->RewriteKind & CRK_Reversed; 11016 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11017 ConvIdx != ConvCount; 11018 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11019 if (Cand->Conversions[ConvIdx].isInitialized()) { 11020 // We've already checked this conversion. 11021 } else if (ArgIdx < ParamTypes.size()) { 11022 if (ParamTypes[ParamIdx]->isDependentType()) 11023 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11024 Args[ArgIdx]->getType()); 11025 else { 11026 Cand->Conversions[ConvIdx] = 11027 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11028 SuppressUserConversions, 11029 /*InOverloadResolution=*/true, 11030 /*AllowObjCWritebackConversion=*/ 11031 S.getLangOpts().ObjCAutoRefCount); 11032 // Store the FixIt in the candidate if it exists. 11033 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11034 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11035 } 11036 } else 11037 Cand->Conversions[ConvIdx].setEllipsis(); 11038 } 11039 } 11040 11041 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11042 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11043 SourceLocation OpLoc, 11044 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11045 // Sort the candidates by viability and position. Sorting directly would 11046 // be prohibitive, so we make a set of pointers and sort those. 11047 SmallVector<OverloadCandidate*, 32> Cands; 11048 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11049 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11050 if (!Filter(*Cand)) 11051 continue; 11052 switch (OCD) { 11053 case OCD_AllCandidates: 11054 if (!Cand->Viable) { 11055 if (!Cand->Function && !Cand->IsSurrogate) { 11056 // This a non-viable builtin candidate. We do not, in general, 11057 // want to list every possible builtin candidate. 11058 continue; 11059 } 11060 CompleteNonViableCandidate(S, Cand, Args, Kind); 11061 } 11062 break; 11063 11064 case OCD_ViableCandidates: 11065 if (!Cand->Viable) 11066 continue; 11067 break; 11068 11069 case OCD_AmbiguousCandidates: 11070 if (!Cand->Best) 11071 continue; 11072 break; 11073 } 11074 11075 Cands.push_back(Cand); 11076 } 11077 11078 llvm::stable_sort( 11079 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11080 11081 return Cands; 11082 } 11083 11084 /// When overload resolution fails, prints diagnostic messages containing the 11085 /// candidates in the candidate set. 11086 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11087 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11088 StringRef Opc, SourceLocation OpLoc, 11089 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11090 11091 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11092 11093 S.Diag(PD.first, PD.second); 11094 11095 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11096 } 11097 11098 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11099 ArrayRef<OverloadCandidate *> Cands, 11100 StringRef Opc, SourceLocation OpLoc) { 11101 bool ReportedAmbiguousConversions = false; 11102 11103 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11104 unsigned CandsShown = 0; 11105 auto I = Cands.begin(), E = Cands.end(); 11106 for (; I != E; ++I) { 11107 OverloadCandidate *Cand = *I; 11108 11109 // Set an arbitrary limit on the number of candidate functions we'll spam 11110 // the user with. FIXME: This limit should depend on details of the 11111 // candidate list. 11112 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11113 break; 11114 } 11115 ++CandsShown; 11116 11117 if (Cand->Function) 11118 NoteFunctionCandidate(S, Cand, Args.size(), 11119 /*TakingCandidateAddress=*/false, DestAS); 11120 else if (Cand->IsSurrogate) 11121 NoteSurrogateCandidate(S, Cand); 11122 else { 11123 assert(Cand->Viable && 11124 "Non-viable built-in candidates are not added to Cands."); 11125 // Generally we only see ambiguities including viable builtin 11126 // operators if overload resolution got screwed up by an 11127 // ambiguous user-defined conversion. 11128 // 11129 // FIXME: It's quite possible for different conversions to see 11130 // different ambiguities, though. 11131 if (!ReportedAmbiguousConversions) { 11132 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11133 ReportedAmbiguousConversions = true; 11134 } 11135 11136 // If this is a viable builtin, print it. 11137 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11138 } 11139 } 11140 11141 if (I != E) 11142 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11143 } 11144 11145 static SourceLocation 11146 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11147 return Cand->Specialization ? Cand->Specialization->getLocation() 11148 : SourceLocation(); 11149 } 11150 11151 namespace { 11152 struct CompareTemplateSpecCandidatesForDisplay { 11153 Sema &S; 11154 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11155 11156 bool operator()(const TemplateSpecCandidate *L, 11157 const TemplateSpecCandidate *R) { 11158 // Fast-path this check. 11159 if (L == R) 11160 return false; 11161 11162 // Assuming that both candidates are not matches... 11163 11164 // Sort by the ranking of deduction failures. 11165 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11166 return RankDeductionFailure(L->DeductionFailure) < 11167 RankDeductionFailure(R->DeductionFailure); 11168 11169 // Sort everything else by location. 11170 SourceLocation LLoc = GetLocationForCandidate(L); 11171 SourceLocation RLoc = GetLocationForCandidate(R); 11172 11173 // Put candidates without locations (e.g. builtins) at the end. 11174 if (LLoc.isInvalid()) 11175 return false; 11176 if (RLoc.isInvalid()) 11177 return true; 11178 11179 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11180 } 11181 }; 11182 } 11183 11184 /// Diagnose a template argument deduction failure. 11185 /// We are treating these failures as overload failures due to bad 11186 /// deductions. 11187 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11188 bool ForTakingAddress) { 11189 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11190 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11191 } 11192 11193 void TemplateSpecCandidateSet::destroyCandidates() { 11194 for (iterator i = begin(), e = end(); i != e; ++i) { 11195 i->DeductionFailure.Destroy(); 11196 } 11197 } 11198 11199 void TemplateSpecCandidateSet::clear() { 11200 destroyCandidates(); 11201 Candidates.clear(); 11202 } 11203 11204 /// NoteCandidates - When no template specialization match is found, prints 11205 /// diagnostic messages containing the non-matching specializations that form 11206 /// the candidate set. 11207 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11208 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11209 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11210 // Sort the candidates by position (assuming no candidate is a match). 11211 // Sorting directly would be prohibitive, so we make a set of pointers 11212 // and sort those. 11213 SmallVector<TemplateSpecCandidate *, 32> Cands; 11214 Cands.reserve(size()); 11215 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11216 if (Cand->Specialization) 11217 Cands.push_back(Cand); 11218 // Otherwise, this is a non-matching builtin candidate. We do not, 11219 // in general, want to list every possible builtin candidate. 11220 } 11221 11222 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11223 11224 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11225 // for generalization purposes (?). 11226 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11227 11228 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11229 unsigned CandsShown = 0; 11230 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11231 TemplateSpecCandidate *Cand = *I; 11232 11233 // Set an arbitrary limit on the number of candidates we'll spam 11234 // the user with. FIXME: This limit should depend on details of the 11235 // candidate list. 11236 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11237 break; 11238 ++CandsShown; 11239 11240 assert(Cand->Specialization && 11241 "Non-matching built-in candidates are not added to Cands."); 11242 Cand->NoteDeductionFailure(S, ForTakingAddress); 11243 } 11244 11245 if (I != E) 11246 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11247 } 11248 11249 // [PossiblyAFunctionType] --> [Return] 11250 // NonFunctionType --> NonFunctionType 11251 // R (A) --> R(A) 11252 // R (*)(A) --> R (A) 11253 // R (&)(A) --> R (A) 11254 // R (S::*)(A) --> R (A) 11255 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11256 QualType Ret = PossiblyAFunctionType; 11257 if (const PointerType *ToTypePtr = 11258 PossiblyAFunctionType->getAs<PointerType>()) 11259 Ret = ToTypePtr->getPointeeType(); 11260 else if (const ReferenceType *ToTypeRef = 11261 PossiblyAFunctionType->getAs<ReferenceType>()) 11262 Ret = ToTypeRef->getPointeeType(); 11263 else if (const MemberPointerType *MemTypePtr = 11264 PossiblyAFunctionType->getAs<MemberPointerType>()) 11265 Ret = MemTypePtr->getPointeeType(); 11266 Ret = 11267 Context.getCanonicalType(Ret).getUnqualifiedType(); 11268 return Ret; 11269 } 11270 11271 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11272 bool Complain = true) { 11273 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11274 S.DeduceReturnType(FD, Loc, Complain)) 11275 return true; 11276 11277 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11278 if (S.getLangOpts().CPlusPlus17 && 11279 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11280 !S.ResolveExceptionSpec(Loc, FPT)) 11281 return true; 11282 11283 return false; 11284 } 11285 11286 namespace { 11287 // A helper class to help with address of function resolution 11288 // - allows us to avoid passing around all those ugly parameters 11289 class AddressOfFunctionResolver { 11290 Sema& S; 11291 Expr* SourceExpr; 11292 const QualType& TargetType; 11293 QualType TargetFunctionType; // Extracted function type from target type 11294 11295 bool Complain; 11296 //DeclAccessPair& ResultFunctionAccessPair; 11297 ASTContext& Context; 11298 11299 bool TargetTypeIsNonStaticMemberFunction; 11300 bool FoundNonTemplateFunction; 11301 bool StaticMemberFunctionFromBoundPointer; 11302 bool HasComplained; 11303 11304 OverloadExpr::FindResult OvlExprInfo; 11305 OverloadExpr *OvlExpr; 11306 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11307 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11308 TemplateSpecCandidateSet FailedCandidates; 11309 11310 public: 11311 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11312 const QualType &TargetType, bool Complain) 11313 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11314 Complain(Complain), Context(S.getASTContext()), 11315 TargetTypeIsNonStaticMemberFunction( 11316 !!TargetType->getAs<MemberPointerType>()), 11317 FoundNonTemplateFunction(false), 11318 StaticMemberFunctionFromBoundPointer(false), 11319 HasComplained(false), 11320 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11321 OvlExpr(OvlExprInfo.Expression), 11322 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11323 ExtractUnqualifiedFunctionTypeFromTargetType(); 11324 11325 if (TargetFunctionType->isFunctionType()) { 11326 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11327 if (!UME->isImplicitAccess() && 11328 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11329 StaticMemberFunctionFromBoundPointer = true; 11330 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11331 DeclAccessPair dap; 11332 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11333 OvlExpr, false, &dap)) { 11334 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11335 if (!Method->isStatic()) { 11336 // If the target type is a non-function type and the function found 11337 // is a non-static member function, pretend as if that was the 11338 // target, it's the only possible type to end up with. 11339 TargetTypeIsNonStaticMemberFunction = true; 11340 11341 // And skip adding the function if its not in the proper form. 11342 // We'll diagnose this due to an empty set of functions. 11343 if (!OvlExprInfo.HasFormOfMemberPointer) 11344 return; 11345 } 11346 11347 Matches.push_back(std::make_pair(dap, Fn)); 11348 } 11349 return; 11350 } 11351 11352 if (OvlExpr->hasExplicitTemplateArgs()) 11353 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11354 11355 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11356 // C++ [over.over]p4: 11357 // If more than one function is selected, [...] 11358 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11359 if (FoundNonTemplateFunction) 11360 EliminateAllTemplateMatches(); 11361 else 11362 EliminateAllExceptMostSpecializedTemplate(); 11363 } 11364 } 11365 11366 if (S.getLangOpts().CUDA && Matches.size() > 1) 11367 EliminateSuboptimalCudaMatches(); 11368 } 11369 11370 bool hasComplained() const { return HasComplained; } 11371 11372 private: 11373 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11374 QualType Discard; 11375 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11376 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11377 } 11378 11379 /// \return true if A is considered a better overload candidate for the 11380 /// desired type than B. 11381 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11382 // If A doesn't have exactly the correct type, we don't want to classify it 11383 // as "better" than anything else. This way, the user is required to 11384 // disambiguate for us if there are multiple candidates and no exact match. 11385 return candidateHasExactlyCorrectType(A) && 11386 (!candidateHasExactlyCorrectType(B) || 11387 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11388 } 11389 11390 /// \return true if we were able to eliminate all but one overload candidate, 11391 /// false otherwise. 11392 bool eliminiateSuboptimalOverloadCandidates() { 11393 // Same algorithm as overload resolution -- one pass to pick the "best", 11394 // another pass to be sure that nothing is better than the best. 11395 auto Best = Matches.begin(); 11396 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11397 if (isBetterCandidate(I->second, Best->second)) 11398 Best = I; 11399 11400 const FunctionDecl *BestFn = Best->second; 11401 auto IsBestOrInferiorToBest = [this, BestFn]( 11402 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11403 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11404 }; 11405 11406 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11407 // option, so we can potentially give the user a better error 11408 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11409 return false; 11410 Matches[0] = *Best; 11411 Matches.resize(1); 11412 return true; 11413 } 11414 11415 bool isTargetTypeAFunction() const { 11416 return TargetFunctionType->isFunctionType(); 11417 } 11418 11419 // [ToType] [Return] 11420 11421 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11422 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11423 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11424 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11425 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11426 } 11427 11428 // return true if any matching specializations were found 11429 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11430 const DeclAccessPair& CurAccessFunPair) { 11431 if (CXXMethodDecl *Method 11432 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11433 // Skip non-static function templates when converting to pointer, and 11434 // static when converting to member pointer. 11435 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11436 return false; 11437 } 11438 else if (TargetTypeIsNonStaticMemberFunction) 11439 return false; 11440 11441 // C++ [over.over]p2: 11442 // If the name is a function template, template argument deduction is 11443 // done (14.8.2.2), and if the argument deduction succeeds, the 11444 // resulting template argument list is used to generate a single 11445 // function template specialization, which is added to the set of 11446 // overloaded functions considered. 11447 FunctionDecl *Specialization = nullptr; 11448 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11449 if (Sema::TemplateDeductionResult Result 11450 = S.DeduceTemplateArguments(FunctionTemplate, 11451 &OvlExplicitTemplateArgs, 11452 TargetFunctionType, Specialization, 11453 Info, /*IsAddressOfFunction*/true)) { 11454 // Make a note of the failed deduction for diagnostics. 11455 FailedCandidates.addCandidate() 11456 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11457 MakeDeductionFailureInfo(Context, Result, Info)); 11458 return false; 11459 } 11460 11461 // Template argument deduction ensures that we have an exact match or 11462 // compatible pointer-to-function arguments that would be adjusted by ICS. 11463 // This function template specicalization works. 11464 assert(S.isSameOrCompatibleFunctionType( 11465 Context.getCanonicalType(Specialization->getType()), 11466 Context.getCanonicalType(TargetFunctionType))); 11467 11468 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11469 return false; 11470 11471 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11472 return true; 11473 } 11474 11475 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11476 const DeclAccessPair& CurAccessFunPair) { 11477 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11478 // Skip non-static functions when converting to pointer, and static 11479 // when converting to member pointer. 11480 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11481 return false; 11482 } 11483 else if (TargetTypeIsNonStaticMemberFunction) 11484 return false; 11485 11486 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11487 if (S.getLangOpts().CUDA) 11488 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11489 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11490 return false; 11491 if (FunDecl->isMultiVersion()) { 11492 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11493 if (TA && !TA->isDefaultVersion()) 11494 return false; 11495 } 11496 11497 // If any candidate has a placeholder return type, trigger its deduction 11498 // now. 11499 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11500 Complain)) { 11501 HasComplained |= Complain; 11502 return false; 11503 } 11504 11505 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11506 return false; 11507 11508 // If we're in C, we need to support types that aren't exactly identical. 11509 if (!S.getLangOpts().CPlusPlus || 11510 candidateHasExactlyCorrectType(FunDecl)) { 11511 Matches.push_back(std::make_pair( 11512 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11513 FoundNonTemplateFunction = true; 11514 return true; 11515 } 11516 } 11517 11518 return false; 11519 } 11520 11521 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11522 bool Ret = false; 11523 11524 // If the overload expression doesn't have the form of a pointer to 11525 // member, don't try to convert it to a pointer-to-member type. 11526 if (IsInvalidFormOfPointerToMemberFunction()) 11527 return false; 11528 11529 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11530 E = OvlExpr->decls_end(); 11531 I != E; ++I) { 11532 // Look through any using declarations to find the underlying function. 11533 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11534 11535 // C++ [over.over]p3: 11536 // Non-member functions and static member functions match 11537 // targets of type "pointer-to-function" or "reference-to-function." 11538 // Nonstatic member functions match targets of 11539 // type "pointer-to-member-function." 11540 // Note that according to DR 247, the containing class does not matter. 11541 if (FunctionTemplateDecl *FunctionTemplate 11542 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11543 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11544 Ret = true; 11545 } 11546 // If we have explicit template arguments supplied, skip non-templates. 11547 else if (!OvlExpr->hasExplicitTemplateArgs() && 11548 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11549 Ret = true; 11550 } 11551 assert(Ret || Matches.empty()); 11552 return Ret; 11553 } 11554 11555 void EliminateAllExceptMostSpecializedTemplate() { 11556 // [...] and any given function template specialization F1 is 11557 // eliminated if the set contains a second function template 11558 // specialization whose function template is more specialized 11559 // than the function template of F1 according to the partial 11560 // ordering rules of 14.5.5.2. 11561 11562 // The algorithm specified above is quadratic. We instead use a 11563 // two-pass algorithm (similar to the one used to identify the 11564 // best viable function in an overload set) that identifies the 11565 // best function template (if it exists). 11566 11567 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11568 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11569 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11570 11571 // TODO: It looks like FailedCandidates does not serve much purpose 11572 // here, since the no_viable diagnostic has index 0. 11573 UnresolvedSetIterator Result = S.getMostSpecialized( 11574 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11575 SourceExpr->getBeginLoc(), S.PDiag(), 11576 S.PDiag(diag::err_addr_ovl_ambiguous) 11577 << Matches[0].second->getDeclName(), 11578 S.PDiag(diag::note_ovl_candidate) 11579 << (unsigned)oc_function << (unsigned)ocs_described_template, 11580 Complain, TargetFunctionType); 11581 11582 if (Result != MatchesCopy.end()) { 11583 // Make it the first and only element 11584 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11585 Matches[0].second = cast<FunctionDecl>(*Result); 11586 Matches.resize(1); 11587 } else 11588 HasComplained |= Complain; 11589 } 11590 11591 void EliminateAllTemplateMatches() { 11592 // [...] any function template specializations in the set are 11593 // eliminated if the set also contains a non-template function, [...] 11594 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11595 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11596 ++I; 11597 else { 11598 Matches[I] = Matches[--N]; 11599 Matches.resize(N); 11600 } 11601 } 11602 } 11603 11604 void EliminateSuboptimalCudaMatches() { 11605 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11606 } 11607 11608 public: 11609 void ComplainNoMatchesFound() const { 11610 assert(Matches.empty()); 11611 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11612 << OvlExpr->getName() << TargetFunctionType 11613 << OvlExpr->getSourceRange(); 11614 if (FailedCandidates.empty()) 11615 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11616 /*TakingAddress=*/true); 11617 else { 11618 // We have some deduction failure messages. Use them to diagnose 11619 // the function templates, and diagnose the non-template candidates 11620 // normally. 11621 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11622 IEnd = OvlExpr->decls_end(); 11623 I != IEnd; ++I) 11624 if (FunctionDecl *Fun = 11625 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11626 if (!functionHasPassObjectSizeParams(Fun)) 11627 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 11628 /*TakingAddress=*/true); 11629 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11630 } 11631 } 11632 11633 bool IsInvalidFormOfPointerToMemberFunction() const { 11634 return TargetTypeIsNonStaticMemberFunction && 11635 !OvlExprInfo.HasFormOfMemberPointer; 11636 } 11637 11638 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11639 // TODO: Should we condition this on whether any functions might 11640 // have matched, or is it more appropriate to do that in callers? 11641 // TODO: a fixit wouldn't hurt. 11642 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11643 << TargetType << OvlExpr->getSourceRange(); 11644 } 11645 11646 bool IsStaticMemberFunctionFromBoundPointer() const { 11647 return StaticMemberFunctionFromBoundPointer; 11648 } 11649 11650 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11651 S.Diag(OvlExpr->getBeginLoc(), 11652 diag::err_invalid_form_pointer_member_function) 11653 << OvlExpr->getSourceRange(); 11654 } 11655 11656 void ComplainOfInvalidConversion() const { 11657 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11658 << OvlExpr->getName() << TargetType; 11659 } 11660 11661 void ComplainMultipleMatchesFound() const { 11662 assert(Matches.size() > 1); 11663 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11664 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11665 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11666 /*TakingAddress=*/true); 11667 } 11668 11669 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11670 11671 int getNumMatches() const { return Matches.size(); } 11672 11673 FunctionDecl* getMatchingFunctionDecl() const { 11674 if (Matches.size() != 1) return nullptr; 11675 return Matches[0].second; 11676 } 11677 11678 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11679 if (Matches.size() != 1) return nullptr; 11680 return &Matches[0].first; 11681 } 11682 }; 11683 } 11684 11685 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11686 /// an overloaded function (C++ [over.over]), where @p From is an 11687 /// expression with overloaded function type and @p ToType is the type 11688 /// we're trying to resolve to. For example: 11689 /// 11690 /// @code 11691 /// int f(double); 11692 /// int f(int); 11693 /// 11694 /// int (*pfd)(double) = f; // selects f(double) 11695 /// @endcode 11696 /// 11697 /// This routine returns the resulting FunctionDecl if it could be 11698 /// resolved, and NULL otherwise. When @p Complain is true, this 11699 /// routine will emit diagnostics if there is an error. 11700 FunctionDecl * 11701 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11702 QualType TargetType, 11703 bool Complain, 11704 DeclAccessPair &FoundResult, 11705 bool *pHadMultipleCandidates) { 11706 assert(AddressOfExpr->getType() == Context.OverloadTy); 11707 11708 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11709 Complain); 11710 int NumMatches = Resolver.getNumMatches(); 11711 FunctionDecl *Fn = nullptr; 11712 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11713 if (NumMatches == 0 && ShouldComplain) { 11714 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11715 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11716 else 11717 Resolver.ComplainNoMatchesFound(); 11718 } 11719 else if (NumMatches > 1 && ShouldComplain) 11720 Resolver.ComplainMultipleMatchesFound(); 11721 else if (NumMatches == 1) { 11722 Fn = Resolver.getMatchingFunctionDecl(); 11723 assert(Fn); 11724 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11725 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11726 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11727 if (Complain) { 11728 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11729 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11730 else 11731 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11732 } 11733 } 11734 11735 if (pHadMultipleCandidates) 11736 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11737 return Fn; 11738 } 11739 11740 /// Given an expression that refers to an overloaded function, try to 11741 /// resolve that function to a single function that can have its address taken. 11742 /// This will modify `Pair` iff it returns non-null. 11743 /// 11744 /// This routine can only realistically succeed if all but one candidates in the 11745 /// overload set for SrcExpr cannot have their addresses taken. 11746 FunctionDecl * 11747 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11748 DeclAccessPair &Pair) { 11749 OverloadExpr::FindResult R = OverloadExpr::find(E); 11750 OverloadExpr *Ovl = R.Expression; 11751 FunctionDecl *Result = nullptr; 11752 DeclAccessPair DAP; 11753 // Don't use the AddressOfResolver because we're specifically looking for 11754 // cases where we have one overload candidate that lacks 11755 // enable_if/pass_object_size/... 11756 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11757 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11758 if (!FD) 11759 return nullptr; 11760 11761 if (!checkAddressOfFunctionIsAvailable(FD)) 11762 continue; 11763 11764 // We have more than one result; quit. 11765 if (Result) 11766 return nullptr; 11767 DAP = I.getPair(); 11768 Result = FD; 11769 } 11770 11771 if (Result) 11772 Pair = DAP; 11773 return Result; 11774 } 11775 11776 /// Given an overloaded function, tries to turn it into a non-overloaded 11777 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11778 /// will perform access checks, diagnose the use of the resultant decl, and, if 11779 /// requested, potentially perform a function-to-pointer decay. 11780 /// 11781 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11782 /// Otherwise, returns true. This may emit diagnostics and return true. 11783 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11784 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11785 Expr *E = SrcExpr.get(); 11786 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11787 11788 DeclAccessPair DAP; 11789 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11790 if (!Found || Found->isCPUDispatchMultiVersion() || 11791 Found->isCPUSpecificMultiVersion()) 11792 return false; 11793 11794 // Emitting multiple diagnostics for a function that is both inaccessible and 11795 // unavailable is consistent with our behavior elsewhere. So, always check 11796 // for both. 11797 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11798 CheckAddressOfMemberAccess(E, DAP); 11799 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11800 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11801 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11802 else 11803 SrcExpr = Fixed; 11804 return true; 11805 } 11806 11807 /// Given an expression that refers to an overloaded function, try to 11808 /// resolve that overloaded function expression down to a single function. 11809 /// 11810 /// This routine can only resolve template-ids that refer to a single function 11811 /// template, where that template-id refers to a single template whose template 11812 /// arguments are either provided by the template-id or have defaults, 11813 /// as described in C++0x [temp.arg.explicit]p3. 11814 /// 11815 /// If no template-ids are found, no diagnostics are emitted and NULL is 11816 /// returned. 11817 FunctionDecl * 11818 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11819 bool Complain, 11820 DeclAccessPair *FoundResult) { 11821 // C++ [over.over]p1: 11822 // [...] [Note: any redundant set of parentheses surrounding the 11823 // overloaded function name is ignored (5.1). ] 11824 // C++ [over.over]p1: 11825 // [...] The overloaded function name can be preceded by the & 11826 // operator. 11827 11828 // If we didn't actually find any template-ids, we're done. 11829 if (!ovl->hasExplicitTemplateArgs()) 11830 return nullptr; 11831 11832 TemplateArgumentListInfo ExplicitTemplateArgs; 11833 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11834 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11835 11836 // Look through all of the overloaded functions, searching for one 11837 // whose type matches exactly. 11838 FunctionDecl *Matched = nullptr; 11839 for (UnresolvedSetIterator I = ovl->decls_begin(), 11840 E = ovl->decls_end(); I != E; ++I) { 11841 // C++0x [temp.arg.explicit]p3: 11842 // [...] In contexts where deduction is done and fails, or in contexts 11843 // where deduction is not done, if a template argument list is 11844 // specified and it, along with any default template arguments, 11845 // identifies a single function template specialization, then the 11846 // template-id is an lvalue for the function template specialization. 11847 FunctionTemplateDecl *FunctionTemplate 11848 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11849 11850 // C++ [over.over]p2: 11851 // If the name is a function template, template argument deduction is 11852 // done (14.8.2.2), and if the argument deduction succeeds, the 11853 // resulting template argument list is used to generate a single 11854 // function template specialization, which is added to the set of 11855 // overloaded functions considered. 11856 FunctionDecl *Specialization = nullptr; 11857 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11858 if (TemplateDeductionResult Result 11859 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11860 Specialization, Info, 11861 /*IsAddressOfFunction*/true)) { 11862 // Make a note of the failed deduction for diagnostics. 11863 // TODO: Actually use the failed-deduction info? 11864 FailedCandidates.addCandidate() 11865 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11866 MakeDeductionFailureInfo(Context, Result, Info)); 11867 continue; 11868 } 11869 11870 assert(Specialization && "no specialization and no error?"); 11871 11872 // Multiple matches; we can't resolve to a single declaration. 11873 if (Matched) { 11874 if (Complain) { 11875 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11876 << ovl->getName(); 11877 NoteAllOverloadCandidates(ovl); 11878 } 11879 return nullptr; 11880 } 11881 11882 Matched = Specialization; 11883 if (FoundResult) *FoundResult = I.getPair(); 11884 } 11885 11886 if (Matched && 11887 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11888 return nullptr; 11889 11890 return Matched; 11891 } 11892 11893 // Resolve and fix an overloaded expression that can be resolved 11894 // because it identifies a single function template specialization. 11895 // 11896 // Last three arguments should only be supplied if Complain = true 11897 // 11898 // Return true if it was logically possible to so resolve the 11899 // expression, regardless of whether or not it succeeded. Always 11900 // returns true if 'complain' is set. 11901 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11902 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11903 bool complain, SourceRange OpRangeForComplaining, 11904 QualType DestTypeForComplaining, 11905 unsigned DiagIDForComplaining) { 11906 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11907 11908 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11909 11910 DeclAccessPair found; 11911 ExprResult SingleFunctionExpression; 11912 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11913 ovl.Expression, /*complain*/ false, &found)) { 11914 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11915 SrcExpr = ExprError(); 11916 return true; 11917 } 11918 11919 // It is only correct to resolve to an instance method if we're 11920 // resolving a form that's permitted to be a pointer to member. 11921 // Otherwise we'll end up making a bound member expression, which 11922 // is illegal in all the contexts we resolve like this. 11923 if (!ovl.HasFormOfMemberPointer && 11924 isa<CXXMethodDecl>(fn) && 11925 cast<CXXMethodDecl>(fn)->isInstance()) { 11926 if (!complain) return false; 11927 11928 Diag(ovl.Expression->getExprLoc(), 11929 diag::err_bound_member_function) 11930 << 0 << ovl.Expression->getSourceRange(); 11931 11932 // TODO: I believe we only end up here if there's a mix of 11933 // static and non-static candidates (otherwise the expression 11934 // would have 'bound member' type, not 'overload' type). 11935 // Ideally we would note which candidate was chosen and why 11936 // the static candidates were rejected. 11937 SrcExpr = ExprError(); 11938 return true; 11939 } 11940 11941 // Fix the expression to refer to 'fn'. 11942 SingleFunctionExpression = 11943 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11944 11945 // If desired, do function-to-pointer decay. 11946 if (doFunctionPointerConverion) { 11947 SingleFunctionExpression = 11948 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11949 if (SingleFunctionExpression.isInvalid()) { 11950 SrcExpr = ExprError(); 11951 return true; 11952 } 11953 } 11954 } 11955 11956 if (!SingleFunctionExpression.isUsable()) { 11957 if (complain) { 11958 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11959 << ovl.Expression->getName() 11960 << DestTypeForComplaining 11961 << OpRangeForComplaining 11962 << ovl.Expression->getQualifierLoc().getSourceRange(); 11963 NoteAllOverloadCandidates(SrcExpr.get()); 11964 11965 SrcExpr = ExprError(); 11966 return true; 11967 } 11968 11969 return false; 11970 } 11971 11972 SrcExpr = SingleFunctionExpression; 11973 return true; 11974 } 11975 11976 /// Add a single candidate to the overload set. 11977 static void AddOverloadedCallCandidate(Sema &S, 11978 DeclAccessPair FoundDecl, 11979 TemplateArgumentListInfo *ExplicitTemplateArgs, 11980 ArrayRef<Expr *> Args, 11981 OverloadCandidateSet &CandidateSet, 11982 bool PartialOverloading, 11983 bool KnownValid) { 11984 NamedDecl *Callee = FoundDecl.getDecl(); 11985 if (isa<UsingShadowDecl>(Callee)) 11986 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11987 11988 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11989 if (ExplicitTemplateArgs) { 11990 assert(!KnownValid && "Explicit template arguments?"); 11991 return; 11992 } 11993 // Prevent ill-formed function decls to be added as overload candidates. 11994 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11995 return; 11996 11997 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11998 /*SuppressUserConversions=*/false, 11999 PartialOverloading); 12000 return; 12001 } 12002 12003 if (FunctionTemplateDecl *FuncTemplate 12004 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12005 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12006 ExplicitTemplateArgs, Args, CandidateSet, 12007 /*SuppressUserConversions=*/false, 12008 PartialOverloading); 12009 return; 12010 } 12011 12012 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12013 } 12014 12015 /// Add the overload candidates named by callee and/or found by argument 12016 /// dependent lookup to the given overload set. 12017 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12018 ArrayRef<Expr *> Args, 12019 OverloadCandidateSet &CandidateSet, 12020 bool PartialOverloading) { 12021 12022 #ifndef NDEBUG 12023 // Verify that ArgumentDependentLookup is consistent with the rules 12024 // in C++0x [basic.lookup.argdep]p3: 12025 // 12026 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12027 // and let Y be the lookup set produced by argument dependent 12028 // lookup (defined as follows). If X contains 12029 // 12030 // -- a declaration of a class member, or 12031 // 12032 // -- a block-scope function declaration that is not a 12033 // using-declaration, or 12034 // 12035 // -- a declaration that is neither a function or a function 12036 // template 12037 // 12038 // then Y is empty. 12039 12040 if (ULE->requiresADL()) { 12041 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12042 E = ULE->decls_end(); I != E; ++I) { 12043 assert(!(*I)->getDeclContext()->isRecord()); 12044 assert(isa<UsingShadowDecl>(*I) || 12045 !(*I)->getDeclContext()->isFunctionOrMethod()); 12046 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12047 } 12048 } 12049 #endif 12050 12051 // It would be nice to avoid this copy. 12052 TemplateArgumentListInfo TABuffer; 12053 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12054 if (ULE->hasExplicitTemplateArgs()) { 12055 ULE->copyTemplateArgumentsInto(TABuffer); 12056 ExplicitTemplateArgs = &TABuffer; 12057 } 12058 12059 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12060 E = ULE->decls_end(); I != E; ++I) 12061 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12062 CandidateSet, PartialOverloading, 12063 /*KnownValid*/ true); 12064 12065 if (ULE->requiresADL()) 12066 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12067 Args, ExplicitTemplateArgs, 12068 CandidateSet, PartialOverloading); 12069 } 12070 12071 /// Determine whether a declaration with the specified name could be moved into 12072 /// a different namespace. 12073 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12074 switch (Name.getCXXOverloadedOperator()) { 12075 case OO_New: case OO_Array_New: 12076 case OO_Delete: case OO_Array_Delete: 12077 return false; 12078 12079 default: 12080 return true; 12081 } 12082 } 12083 12084 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12085 /// template, where the non-dependent name was declared after the template 12086 /// was defined. This is common in code written for a compilers which do not 12087 /// correctly implement two-stage name lookup. 12088 /// 12089 /// Returns true if a viable candidate was found and a diagnostic was issued. 12090 static bool 12091 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12092 const CXXScopeSpec &SS, LookupResult &R, 12093 OverloadCandidateSet::CandidateSetKind CSK, 12094 TemplateArgumentListInfo *ExplicitTemplateArgs, 12095 ArrayRef<Expr *> Args, 12096 bool *DoDiagnoseEmptyLookup = nullptr) { 12097 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12098 return false; 12099 12100 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12101 if (DC->isTransparentContext()) 12102 continue; 12103 12104 SemaRef.LookupQualifiedName(R, DC); 12105 12106 if (!R.empty()) { 12107 R.suppressDiagnostics(); 12108 12109 if (isa<CXXRecordDecl>(DC)) { 12110 // Don't diagnose names we find in classes; we get much better 12111 // diagnostics for these from DiagnoseEmptyLookup. 12112 R.clear(); 12113 if (DoDiagnoseEmptyLookup) 12114 *DoDiagnoseEmptyLookup = true; 12115 return false; 12116 } 12117 12118 OverloadCandidateSet Candidates(FnLoc, CSK); 12119 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12120 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12121 ExplicitTemplateArgs, Args, 12122 Candidates, false, /*KnownValid*/ false); 12123 12124 OverloadCandidateSet::iterator Best; 12125 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12126 // No viable functions. Don't bother the user with notes for functions 12127 // which don't work and shouldn't be found anyway. 12128 R.clear(); 12129 return false; 12130 } 12131 12132 // Find the namespaces where ADL would have looked, and suggest 12133 // declaring the function there instead. 12134 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12135 Sema::AssociatedClassSet AssociatedClasses; 12136 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12137 AssociatedNamespaces, 12138 AssociatedClasses); 12139 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12140 if (canBeDeclaredInNamespace(R.getLookupName())) { 12141 DeclContext *Std = SemaRef.getStdNamespace(); 12142 for (Sema::AssociatedNamespaceSet::iterator 12143 it = AssociatedNamespaces.begin(), 12144 end = AssociatedNamespaces.end(); it != end; ++it) { 12145 // Never suggest declaring a function within namespace 'std'. 12146 if (Std && Std->Encloses(*it)) 12147 continue; 12148 12149 // Never suggest declaring a function within a namespace with a 12150 // reserved name, like __gnu_cxx. 12151 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12152 if (NS && 12153 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12154 continue; 12155 12156 SuggestedNamespaces.insert(*it); 12157 } 12158 } 12159 12160 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12161 << R.getLookupName(); 12162 if (SuggestedNamespaces.empty()) { 12163 SemaRef.Diag(Best->Function->getLocation(), 12164 diag::note_not_found_by_two_phase_lookup) 12165 << R.getLookupName() << 0; 12166 } else if (SuggestedNamespaces.size() == 1) { 12167 SemaRef.Diag(Best->Function->getLocation(), 12168 diag::note_not_found_by_two_phase_lookup) 12169 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12170 } else { 12171 // FIXME: It would be useful to list the associated namespaces here, 12172 // but the diagnostics infrastructure doesn't provide a way to produce 12173 // a localized representation of a list of items. 12174 SemaRef.Diag(Best->Function->getLocation(), 12175 diag::note_not_found_by_two_phase_lookup) 12176 << R.getLookupName() << 2; 12177 } 12178 12179 // Try to recover by calling this function. 12180 return true; 12181 } 12182 12183 R.clear(); 12184 } 12185 12186 return false; 12187 } 12188 12189 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12190 /// template, where the non-dependent operator was declared after the template 12191 /// was defined. 12192 /// 12193 /// Returns true if a viable candidate was found and a diagnostic was issued. 12194 static bool 12195 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12196 SourceLocation OpLoc, 12197 ArrayRef<Expr *> Args) { 12198 DeclarationName OpName = 12199 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12200 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12201 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12202 OverloadCandidateSet::CSK_Operator, 12203 /*ExplicitTemplateArgs=*/nullptr, Args); 12204 } 12205 12206 namespace { 12207 class BuildRecoveryCallExprRAII { 12208 Sema &SemaRef; 12209 public: 12210 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12211 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12212 SemaRef.IsBuildingRecoveryCallExpr = true; 12213 } 12214 12215 ~BuildRecoveryCallExprRAII() { 12216 SemaRef.IsBuildingRecoveryCallExpr = false; 12217 } 12218 }; 12219 12220 } 12221 12222 /// Attempts to recover from a call where no functions were found. 12223 /// 12224 /// Returns true if new candidates were found. 12225 static ExprResult 12226 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12227 UnresolvedLookupExpr *ULE, 12228 SourceLocation LParenLoc, 12229 MutableArrayRef<Expr *> Args, 12230 SourceLocation RParenLoc, 12231 bool EmptyLookup, bool AllowTypoCorrection) { 12232 // Do not try to recover if it is already building a recovery call. 12233 // This stops infinite loops for template instantiations like 12234 // 12235 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12236 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12237 // 12238 if (SemaRef.IsBuildingRecoveryCallExpr) 12239 return ExprError(); 12240 BuildRecoveryCallExprRAII RCE(SemaRef); 12241 12242 CXXScopeSpec SS; 12243 SS.Adopt(ULE->getQualifierLoc()); 12244 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12245 12246 TemplateArgumentListInfo TABuffer; 12247 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12248 if (ULE->hasExplicitTemplateArgs()) { 12249 ULE->copyTemplateArgumentsInto(TABuffer); 12250 ExplicitTemplateArgs = &TABuffer; 12251 } 12252 12253 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12254 Sema::LookupOrdinaryName); 12255 bool DoDiagnoseEmptyLookup = EmptyLookup; 12256 if (!DiagnoseTwoPhaseLookup( 12257 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12258 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12259 NoTypoCorrectionCCC NoTypoValidator{}; 12260 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12261 ExplicitTemplateArgs != nullptr, 12262 dyn_cast<MemberExpr>(Fn)); 12263 CorrectionCandidateCallback &Validator = 12264 AllowTypoCorrection 12265 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12266 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12267 if (!DoDiagnoseEmptyLookup || 12268 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12269 Args)) 12270 return ExprError(); 12271 } 12272 12273 assert(!R.empty() && "lookup results empty despite recovery"); 12274 12275 // If recovery created an ambiguity, just bail out. 12276 if (R.isAmbiguous()) { 12277 R.suppressDiagnostics(); 12278 return ExprError(); 12279 } 12280 12281 // Build an implicit member call if appropriate. Just drop the 12282 // casts and such from the call, we don't really care. 12283 ExprResult NewFn = ExprError(); 12284 if ((*R.begin())->isCXXClassMember()) 12285 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12286 ExplicitTemplateArgs, S); 12287 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12288 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12289 ExplicitTemplateArgs); 12290 else 12291 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12292 12293 if (NewFn.isInvalid()) 12294 return ExprError(); 12295 12296 // This shouldn't cause an infinite loop because we're giving it 12297 // an expression with viable lookup results, which should never 12298 // end up here. 12299 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12300 MultiExprArg(Args.data(), Args.size()), 12301 RParenLoc); 12302 } 12303 12304 /// Constructs and populates an OverloadedCandidateSet from 12305 /// the given function. 12306 /// \returns true when an the ExprResult output parameter has been set. 12307 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12308 UnresolvedLookupExpr *ULE, 12309 MultiExprArg Args, 12310 SourceLocation RParenLoc, 12311 OverloadCandidateSet *CandidateSet, 12312 ExprResult *Result) { 12313 #ifndef NDEBUG 12314 if (ULE->requiresADL()) { 12315 // To do ADL, we must have found an unqualified name. 12316 assert(!ULE->getQualifier() && "qualified name with ADL"); 12317 12318 // We don't perform ADL for implicit declarations of builtins. 12319 // Verify that this was correctly set up. 12320 FunctionDecl *F; 12321 if (ULE->decls_begin() != ULE->decls_end() && 12322 ULE->decls_begin() + 1 == ULE->decls_end() && 12323 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12324 F->getBuiltinID() && F->isImplicit()) 12325 llvm_unreachable("performing ADL for builtin"); 12326 12327 // We don't perform ADL in C. 12328 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12329 } 12330 #endif 12331 12332 UnbridgedCastsSet UnbridgedCasts; 12333 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12334 *Result = ExprError(); 12335 return true; 12336 } 12337 12338 // Add the functions denoted by the callee to the set of candidate 12339 // functions, including those from argument-dependent lookup. 12340 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12341 12342 if (getLangOpts().MSVCCompat && 12343 CurContext->isDependentContext() && !isSFINAEContext() && 12344 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12345 12346 OverloadCandidateSet::iterator Best; 12347 if (CandidateSet->empty() || 12348 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12349 OR_No_Viable_Function) { 12350 // In Microsoft mode, if we are inside a template class member function 12351 // then create a type dependent CallExpr. The goal is to postpone name 12352 // lookup to instantiation time to be able to search into type dependent 12353 // base classes. 12354 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12355 VK_RValue, RParenLoc); 12356 CE->setTypeDependent(true); 12357 CE->setValueDependent(true); 12358 CE->setInstantiationDependent(true); 12359 *Result = CE; 12360 return true; 12361 } 12362 } 12363 12364 if (CandidateSet->empty()) 12365 return false; 12366 12367 UnbridgedCasts.restore(); 12368 return false; 12369 } 12370 12371 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12372 /// the completed call expression. If overload resolution fails, emits 12373 /// diagnostics and returns ExprError() 12374 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12375 UnresolvedLookupExpr *ULE, 12376 SourceLocation LParenLoc, 12377 MultiExprArg Args, 12378 SourceLocation RParenLoc, 12379 Expr *ExecConfig, 12380 OverloadCandidateSet *CandidateSet, 12381 OverloadCandidateSet::iterator *Best, 12382 OverloadingResult OverloadResult, 12383 bool AllowTypoCorrection) { 12384 if (CandidateSet->empty()) 12385 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12386 RParenLoc, /*EmptyLookup=*/true, 12387 AllowTypoCorrection); 12388 12389 switch (OverloadResult) { 12390 case OR_Success: { 12391 FunctionDecl *FDecl = (*Best)->Function; 12392 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12393 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12394 return ExprError(); 12395 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12396 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12397 ExecConfig, /*IsExecConfig=*/false, 12398 (*Best)->IsADLCandidate); 12399 } 12400 12401 case OR_No_Viable_Function: { 12402 // Try to recover by looking for viable functions which the user might 12403 // have meant to call. 12404 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12405 Args, RParenLoc, 12406 /*EmptyLookup=*/false, 12407 AllowTypoCorrection); 12408 if (!Recovery.isInvalid()) 12409 return Recovery; 12410 12411 // If the user passes in a function that we can't take the address of, we 12412 // generally end up emitting really bad error messages. Here, we attempt to 12413 // emit better ones. 12414 for (const Expr *Arg : Args) { 12415 if (!Arg->getType()->isFunctionType()) 12416 continue; 12417 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12418 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12419 if (FD && 12420 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12421 Arg->getExprLoc())) 12422 return ExprError(); 12423 } 12424 } 12425 12426 CandidateSet->NoteCandidates( 12427 PartialDiagnosticAt( 12428 Fn->getBeginLoc(), 12429 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12430 << ULE->getName() << Fn->getSourceRange()), 12431 SemaRef, OCD_AllCandidates, Args); 12432 break; 12433 } 12434 12435 case OR_Ambiguous: 12436 CandidateSet->NoteCandidates( 12437 PartialDiagnosticAt(Fn->getBeginLoc(), 12438 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12439 << ULE->getName() << Fn->getSourceRange()), 12440 SemaRef, OCD_AmbiguousCandidates, Args); 12441 break; 12442 12443 case OR_Deleted: { 12444 CandidateSet->NoteCandidates( 12445 PartialDiagnosticAt(Fn->getBeginLoc(), 12446 SemaRef.PDiag(diag::err_ovl_deleted_call) 12447 << ULE->getName() << Fn->getSourceRange()), 12448 SemaRef, OCD_AllCandidates, Args); 12449 12450 // We emitted an error for the unavailable/deleted function call but keep 12451 // the call in the AST. 12452 FunctionDecl *FDecl = (*Best)->Function; 12453 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12454 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12455 ExecConfig, /*IsExecConfig=*/false, 12456 (*Best)->IsADLCandidate); 12457 } 12458 } 12459 12460 // Overload resolution failed. 12461 return ExprError(); 12462 } 12463 12464 static void markUnaddressableCandidatesUnviable(Sema &S, 12465 OverloadCandidateSet &CS) { 12466 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12467 if (I->Viable && 12468 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12469 I->Viable = false; 12470 I->FailureKind = ovl_fail_addr_not_available; 12471 } 12472 } 12473 } 12474 12475 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12476 /// (which eventually refers to the declaration Func) and the call 12477 /// arguments Args/NumArgs, attempt to resolve the function call down 12478 /// to a specific function. If overload resolution succeeds, returns 12479 /// the call expression produced by overload resolution. 12480 /// Otherwise, emits diagnostics and returns ExprError. 12481 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12482 UnresolvedLookupExpr *ULE, 12483 SourceLocation LParenLoc, 12484 MultiExprArg Args, 12485 SourceLocation RParenLoc, 12486 Expr *ExecConfig, 12487 bool AllowTypoCorrection, 12488 bool CalleesAddressIsTaken) { 12489 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12490 OverloadCandidateSet::CSK_Normal); 12491 ExprResult result; 12492 12493 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12494 &result)) 12495 return result; 12496 12497 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12498 // functions that aren't addressible are considered unviable. 12499 if (CalleesAddressIsTaken) 12500 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12501 12502 OverloadCandidateSet::iterator Best; 12503 OverloadingResult OverloadResult = 12504 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12505 12506 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 12507 ExecConfig, &CandidateSet, &Best, 12508 OverloadResult, AllowTypoCorrection); 12509 } 12510 12511 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12512 return Functions.size() > 1 || 12513 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12514 } 12515 12516 /// Create a unary operation that may resolve to an overloaded 12517 /// operator. 12518 /// 12519 /// \param OpLoc The location of the operator itself (e.g., '*'). 12520 /// 12521 /// \param Opc The UnaryOperatorKind that describes this operator. 12522 /// 12523 /// \param Fns The set of non-member functions that will be 12524 /// considered by overload resolution. The caller needs to build this 12525 /// set based on the context using, e.g., 12526 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12527 /// set should not contain any member functions; those will be added 12528 /// by CreateOverloadedUnaryOp(). 12529 /// 12530 /// \param Input The input argument. 12531 ExprResult 12532 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12533 const UnresolvedSetImpl &Fns, 12534 Expr *Input, bool PerformADL) { 12535 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12536 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12537 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12538 // TODO: provide better source location info. 12539 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12540 12541 if (checkPlaceholderForOverload(*this, Input)) 12542 return ExprError(); 12543 12544 Expr *Args[2] = { Input, nullptr }; 12545 unsigned NumArgs = 1; 12546 12547 // For post-increment and post-decrement, add the implicit '0' as 12548 // the second argument, so that we know this is a post-increment or 12549 // post-decrement. 12550 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12551 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12552 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12553 SourceLocation()); 12554 NumArgs = 2; 12555 } 12556 12557 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12558 12559 if (Input->isTypeDependent()) { 12560 if (Fns.empty()) 12561 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12562 VK_RValue, OK_Ordinary, OpLoc, false); 12563 12564 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12565 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12566 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12567 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12568 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12569 Context.DependentTy, VK_RValue, OpLoc, 12570 FPOptions()); 12571 } 12572 12573 // Build an empty overload set. 12574 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12575 12576 // Add the candidates from the given function set. 12577 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 12578 12579 // Add operator candidates that are member functions. 12580 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12581 12582 // Add candidates from ADL. 12583 if (PerformADL) { 12584 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12585 /*ExplicitTemplateArgs*/nullptr, 12586 CandidateSet); 12587 } 12588 12589 // Add builtin operator candidates. 12590 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12591 12592 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12593 12594 // Perform overload resolution. 12595 OverloadCandidateSet::iterator Best; 12596 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12597 case OR_Success: { 12598 // We found a built-in operator or an overloaded operator. 12599 FunctionDecl *FnDecl = Best->Function; 12600 12601 if (FnDecl) { 12602 Expr *Base = nullptr; 12603 // We matched an overloaded operator. Build a call to that 12604 // operator. 12605 12606 // Convert the arguments. 12607 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12608 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12609 12610 ExprResult InputRes = 12611 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12612 Best->FoundDecl, Method); 12613 if (InputRes.isInvalid()) 12614 return ExprError(); 12615 Base = Input = InputRes.get(); 12616 } else { 12617 // Convert the arguments. 12618 ExprResult InputInit 12619 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12620 Context, 12621 FnDecl->getParamDecl(0)), 12622 SourceLocation(), 12623 Input); 12624 if (InputInit.isInvalid()) 12625 return ExprError(); 12626 Input = InputInit.get(); 12627 } 12628 12629 // Build the actual expression node. 12630 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12631 Base, HadMultipleCandidates, 12632 OpLoc); 12633 if (FnExpr.isInvalid()) 12634 return ExprError(); 12635 12636 // Determine the result type. 12637 QualType ResultTy = FnDecl->getReturnType(); 12638 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12639 ResultTy = ResultTy.getNonLValueExprType(Context); 12640 12641 Args[0] = Input; 12642 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12643 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 12644 FPOptions(), Best->IsADLCandidate); 12645 12646 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12647 return ExprError(); 12648 12649 if (CheckFunctionCall(FnDecl, TheCall, 12650 FnDecl->getType()->castAs<FunctionProtoType>())) 12651 return ExprError(); 12652 12653 return MaybeBindToTemporary(TheCall); 12654 } else { 12655 // We matched a built-in operator. Convert the arguments, then 12656 // break out so that we will build the appropriate built-in 12657 // operator node. 12658 ExprResult InputRes = PerformImplicitConversion( 12659 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12660 CCK_ForBuiltinOverloadedOp); 12661 if (InputRes.isInvalid()) 12662 return ExprError(); 12663 Input = InputRes.get(); 12664 break; 12665 } 12666 } 12667 12668 case OR_No_Viable_Function: 12669 // This is an erroneous use of an operator which can be overloaded by 12670 // a non-member function. Check for non-member operators which were 12671 // defined too late to be candidates. 12672 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12673 // FIXME: Recover by calling the found function. 12674 return ExprError(); 12675 12676 // No viable function; fall through to handling this as a 12677 // built-in operator, which will produce an error message for us. 12678 break; 12679 12680 case OR_Ambiguous: 12681 CandidateSet.NoteCandidates( 12682 PartialDiagnosticAt(OpLoc, 12683 PDiag(diag::err_ovl_ambiguous_oper_unary) 12684 << UnaryOperator::getOpcodeStr(Opc) 12685 << Input->getType() << Input->getSourceRange()), 12686 *this, OCD_AmbiguousCandidates, ArgsArray, 12687 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12688 return ExprError(); 12689 12690 case OR_Deleted: 12691 CandidateSet.NoteCandidates( 12692 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 12693 << UnaryOperator::getOpcodeStr(Opc) 12694 << Input->getSourceRange()), 12695 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 12696 OpLoc); 12697 return ExprError(); 12698 } 12699 12700 // Either we found no viable overloaded operator or we matched a 12701 // built-in operator. In either case, fall through to trying to 12702 // build a built-in operation. 12703 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12704 } 12705 12706 /// Create a binary operation that may resolve to an overloaded 12707 /// operator. 12708 /// 12709 /// \param OpLoc The location of the operator itself (e.g., '+'). 12710 /// 12711 /// \param Opc The BinaryOperatorKind that describes this operator. 12712 /// 12713 /// \param Fns The set of non-member functions that will be 12714 /// considered by overload resolution. The caller needs to build this 12715 /// set based on the context using, e.g., 12716 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12717 /// set should not contain any member functions; those will be added 12718 /// by CreateOverloadedBinOp(). 12719 /// 12720 /// \param LHS Left-hand argument. 12721 /// \param RHS Right-hand argument. 12722 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12723 BinaryOperatorKind Opc, 12724 const UnresolvedSetImpl &Fns, Expr *LHS, 12725 Expr *RHS, bool PerformADL, 12726 bool AllowRewrittenCandidates) { 12727 Expr *Args[2] = { LHS, RHS }; 12728 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12729 12730 if (!getLangOpts().CPlusPlus2a) 12731 AllowRewrittenCandidates = false; 12732 12733 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12734 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12735 12736 // If either side is type-dependent, create an appropriate dependent 12737 // expression. 12738 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12739 if (Fns.empty()) { 12740 // If there are no functions to store, just build a dependent 12741 // BinaryOperator or CompoundAssignment. 12742 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12743 return new (Context) BinaryOperator( 12744 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12745 OpLoc, FPFeatures); 12746 12747 return new (Context) CompoundAssignOperator( 12748 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12749 Context.DependentTy, Context.DependentTy, OpLoc, 12750 FPFeatures); 12751 } 12752 12753 // FIXME: save results of ADL from here? 12754 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12755 // TODO: provide better source location info in DNLoc component. 12756 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12757 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12758 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12759 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12760 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 12761 Context.DependentTy, VK_RValue, OpLoc, 12762 FPFeatures); 12763 } 12764 12765 // Always do placeholder-like conversions on the RHS. 12766 if (checkPlaceholderForOverload(*this, Args[1])) 12767 return ExprError(); 12768 12769 // Do placeholder-like conversion on the LHS; note that we should 12770 // not get here with a PseudoObject LHS. 12771 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12772 if (checkPlaceholderForOverload(*this, Args[0])) 12773 return ExprError(); 12774 12775 // If this is the assignment operator, we only perform overload resolution 12776 // if the left-hand side is a class or enumeration type. This is actually 12777 // a hack. The standard requires that we do overload resolution between the 12778 // various built-in candidates, but as DR507 points out, this can lead to 12779 // problems. So we do it this way, which pretty much follows what GCC does. 12780 // Note that we go the traditional code path for compound assignment forms. 12781 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12782 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12783 12784 // If this is the .* operator, which is not overloadable, just 12785 // create a built-in binary operator. 12786 if (Opc == BO_PtrMemD) 12787 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12788 12789 // Build an empty overload set. 12790 OverloadCandidateSet CandidateSet( 12791 OpLoc, OverloadCandidateSet::CSK_Operator, 12792 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 12793 12794 OverloadedOperatorKind ExtraOp = 12795 AllowRewrittenCandidates ? getRewrittenOverloadedOperator(Op) : OO_None; 12796 12797 // Add the candidates from the given function set. This also adds the 12798 // rewritten candidates using these functions if necessary. 12799 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 12800 12801 // Add operator candidates that are member functions. 12802 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12803 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 12804 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 12805 OverloadCandidateParamOrder::Reversed); 12806 12807 // In C++20, also add any rewritten member candidates. 12808 if (ExtraOp) { 12809 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 12810 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 12811 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 12812 CandidateSet, 12813 OverloadCandidateParamOrder::Reversed); 12814 } 12815 12816 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12817 // performed for an assignment operator (nor for operator[] nor operator->, 12818 // which don't get here). 12819 if (Opc != BO_Assign && PerformADL) { 12820 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12821 /*ExplicitTemplateArgs*/ nullptr, 12822 CandidateSet); 12823 if (ExtraOp) { 12824 DeclarationName ExtraOpName = 12825 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 12826 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 12827 /*ExplicitTemplateArgs*/ nullptr, 12828 CandidateSet); 12829 } 12830 } 12831 12832 // Add builtin operator candidates. 12833 // 12834 // FIXME: We don't add any rewritten candidates here. This is strictly 12835 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 12836 // resulting in our selecting a rewritten builtin candidate. For example: 12837 // 12838 // enum class E { e }; 12839 // bool operator!=(E, E) requires false; 12840 // bool k = E::e != E::e; 12841 // 12842 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 12843 // it seems unreasonable to consider rewritten builtin candidates. A core 12844 // issue has been filed proposing to removed this requirement. 12845 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12846 12847 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12848 12849 // Perform overload resolution. 12850 OverloadCandidateSet::iterator Best; 12851 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12852 case OR_Success: { 12853 // We found a built-in operator or an overloaded operator. 12854 FunctionDecl *FnDecl = Best->Function; 12855 12856 bool IsReversed = (Best->RewriteKind & CRK_Reversed); 12857 if (IsReversed) 12858 std::swap(Args[0], Args[1]); 12859 12860 if (FnDecl) { 12861 Expr *Base = nullptr; 12862 // We matched an overloaded operator. Build a call to that 12863 // operator. 12864 12865 OverloadedOperatorKind ChosenOp = 12866 FnDecl->getDeclName().getCXXOverloadedOperator(); 12867 12868 // C++2a [over.match.oper]p9: 12869 // If a rewritten operator== candidate is selected by overload 12870 // resolution for an operator@, its return type shall be cv bool 12871 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 12872 !FnDecl->getReturnType()->isBooleanType()) { 12873 Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool) 12874 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 12875 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12876 Diag(FnDecl->getLocation(), diag::note_declared_at); 12877 return ExprError(); 12878 } 12879 12880 if (AllowRewrittenCandidates && !IsReversed && 12881 CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) { 12882 // We could have reversed this operator, but didn't. Check if the 12883 // reversed form was a viable candidate, and if so, if it had a 12884 // better conversion for either parameter. If so, this call is 12885 // formally ambiguous, and allowing it is an extension. 12886 for (OverloadCandidate &Cand : CandidateSet) { 12887 if (Cand.Viable && Cand.Function == FnDecl && 12888 Cand.RewriteKind & CRK_Reversed) { 12889 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 12890 if (CompareImplicitConversionSequences( 12891 *this, OpLoc, Cand.Conversions[ArgIdx], 12892 Best->Conversions[ArgIdx]) == 12893 ImplicitConversionSequence::Better) { 12894 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 12895 << BinaryOperator::getOpcodeStr(Opc) 12896 << Args[0]->getType() << Args[1]->getType() 12897 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12898 Diag(FnDecl->getLocation(), 12899 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 12900 } 12901 } 12902 break; 12903 } 12904 } 12905 } 12906 12907 // Convert the arguments. 12908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12909 // Best->Access is only meaningful for class members. 12910 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12911 12912 ExprResult Arg1 = 12913 PerformCopyInitialization( 12914 InitializedEntity::InitializeParameter(Context, 12915 FnDecl->getParamDecl(0)), 12916 SourceLocation(), Args[1]); 12917 if (Arg1.isInvalid()) 12918 return ExprError(); 12919 12920 ExprResult Arg0 = 12921 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12922 Best->FoundDecl, Method); 12923 if (Arg0.isInvalid()) 12924 return ExprError(); 12925 Base = Args[0] = Arg0.getAs<Expr>(); 12926 Args[1] = RHS = Arg1.getAs<Expr>(); 12927 } else { 12928 // Convert the arguments. 12929 ExprResult Arg0 = PerformCopyInitialization( 12930 InitializedEntity::InitializeParameter(Context, 12931 FnDecl->getParamDecl(0)), 12932 SourceLocation(), Args[0]); 12933 if (Arg0.isInvalid()) 12934 return ExprError(); 12935 12936 ExprResult Arg1 = 12937 PerformCopyInitialization( 12938 InitializedEntity::InitializeParameter(Context, 12939 FnDecl->getParamDecl(1)), 12940 SourceLocation(), Args[1]); 12941 if (Arg1.isInvalid()) 12942 return ExprError(); 12943 Args[0] = LHS = Arg0.getAs<Expr>(); 12944 Args[1] = RHS = Arg1.getAs<Expr>(); 12945 } 12946 12947 // Build the actual expression node. 12948 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12949 Best->FoundDecl, Base, 12950 HadMultipleCandidates, OpLoc); 12951 if (FnExpr.isInvalid()) 12952 return ExprError(); 12953 12954 // Determine the result type. 12955 QualType ResultTy = FnDecl->getReturnType(); 12956 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12957 ResultTy = ResultTy.getNonLValueExprType(Context); 12958 12959 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 12960 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 12961 FPFeatures, Best->IsADLCandidate); 12962 12963 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12964 FnDecl)) 12965 return ExprError(); 12966 12967 ArrayRef<const Expr *> ArgsArray(Args, 2); 12968 const Expr *ImplicitThis = nullptr; 12969 // Cut off the implicit 'this'. 12970 if (isa<CXXMethodDecl>(FnDecl)) { 12971 ImplicitThis = ArgsArray[0]; 12972 ArgsArray = ArgsArray.slice(1); 12973 } 12974 12975 // Check for a self move. 12976 if (Op == OO_Equal) 12977 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12978 12979 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12980 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12981 VariadicDoesNotApply); 12982 12983 ExprResult R = MaybeBindToTemporary(TheCall); 12984 if (R.isInvalid()) 12985 return ExprError(); 12986 12987 // For a rewritten candidate, we've already reversed the arguments 12988 // if needed. Perform the rest of the rewrite now. 12989 if ((Best->RewriteKind & CRK_DifferentOperator) || 12990 (Op == OO_Spaceship && IsReversed)) { 12991 if (Op == OO_ExclaimEqual) { 12992 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 12993 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 12994 } else { 12995 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 12996 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12997 Expr *ZeroLiteral = 12998 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 12999 13000 Sema::CodeSynthesisContext Ctx; 13001 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13002 Ctx.Entity = FnDecl; 13003 pushCodeSynthesisContext(Ctx); 13004 13005 R = CreateOverloadedBinOp( 13006 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13007 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13008 /*AllowRewrittenCandidates=*/false); 13009 13010 popCodeSynthesisContext(); 13011 } 13012 if (R.isInvalid()) 13013 return ExprError(); 13014 } else { 13015 assert(ChosenOp == Op && "unexpected operator name"); 13016 } 13017 13018 // Make a note in the AST if we did any rewriting. 13019 if (Best->RewriteKind != CRK_None) 13020 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13021 13022 return R; 13023 } else { 13024 // We matched a built-in operator. Convert the arguments, then 13025 // break out so that we will build the appropriate built-in 13026 // operator node. 13027 ExprResult ArgsRes0 = PerformImplicitConversion( 13028 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13029 AA_Passing, CCK_ForBuiltinOverloadedOp); 13030 if (ArgsRes0.isInvalid()) 13031 return ExprError(); 13032 Args[0] = ArgsRes0.get(); 13033 13034 ExprResult ArgsRes1 = PerformImplicitConversion( 13035 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13036 AA_Passing, CCK_ForBuiltinOverloadedOp); 13037 if (ArgsRes1.isInvalid()) 13038 return ExprError(); 13039 Args[1] = ArgsRes1.get(); 13040 break; 13041 } 13042 } 13043 13044 case OR_No_Viable_Function: { 13045 // C++ [over.match.oper]p9: 13046 // If the operator is the operator , [...] and there are no 13047 // viable functions, then the operator is assumed to be the 13048 // built-in operator and interpreted according to clause 5. 13049 if (Opc == BO_Comma) 13050 break; 13051 13052 // For class as left operand for assignment or compound assignment 13053 // operator do not fall through to handling in built-in, but report that 13054 // no overloaded assignment operator found 13055 ExprResult Result = ExprError(); 13056 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13057 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13058 Args, OpLoc); 13059 if (Args[0]->getType()->isRecordType() && 13060 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13061 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13062 << BinaryOperator::getOpcodeStr(Opc) 13063 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13064 if (Args[0]->getType()->isIncompleteType()) { 13065 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13066 << Args[0]->getType() 13067 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13068 } 13069 } else { 13070 // This is an erroneous use of an operator which can be overloaded by 13071 // a non-member function. Check for non-member operators which were 13072 // defined too late to be candidates. 13073 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13074 // FIXME: Recover by calling the found function. 13075 return ExprError(); 13076 13077 // No viable function; try to create a built-in operation, which will 13078 // produce an error. Then, show the non-viable candidates. 13079 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13080 } 13081 assert(Result.isInvalid() && 13082 "C++ binary operator overloading is missing candidates!"); 13083 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13084 return Result; 13085 } 13086 13087 case OR_Ambiguous: 13088 CandidateSet.NoteCandidates( 13089 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13090 << BinaryOperator::getOpcodeStr(Opc) 13091 << Args[0]->getType() 13092 << Args[1]->getType() 13093 << Args[0]->getSourceRange() 13094 << Args[1]->getSourceRange()), 13095 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13096 OpLoc); 13097 return ExprError(); 13098 13099 case OR_Deleted: 13100 if (isImplicitlyDeleted(Best->Function)) { 13101 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13102 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13103 << Context.getRecordType(Method->getParent()) 13104 << getSpecialMember(Method); 13105 13106 // The user probably meant to call this special member. Just 13107 // explain why it's deleted. 13108 NoteDeletedFunction(Method); 13109 return ExprError(); 13110 } 13111 CandidateSet.NoteCandidates( 13112 PartialDiagnosticAt( 13113 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13114 << getOperatorSpelling(Best->Function->getDeclName() 13115 .getCXXOverloadedOperator()) 13116 << Args[0]->getSourceRange() 13117 << Args[1]->getSourceRange()), 13118 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13119 OpLoc); 13120 return ExprError(); 13121 } 13122 13123 // We matched a built-in operator; build it. 13124 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13125 } 13126 13127 ExprResult 13128 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13129 SourceLocation RLoc, 13130 Expr *Base, Expr *Idx) { 13131 Expr *Args[2] = { Base, Idx }; 13132 DeclarationName OpName = 13133 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13134 13135 // If either side is type-dependent, create an appropriate dependent 13136 // expression. 13137 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13138 13139 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13140 // CHECKME: no 'operator' keyword? 13141 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13142 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13143 UnresolvedLookupExpr *Fn 13144 = UnresolvedLookupExpr::Create(Context, NamingClass, 13145 NestedNameSpecifierLoc(), OpNameInfo, 13146 /*ADL*/ true, /*Overloaded*/ false, 13147 UnresolvedSetIterator(), 13148 UnresolvedSetIterator()); 13149 // Can't add any actual overloads yet 13150 13151 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 13152 Context.DependentTy, VK_RValue, RLoc, 13153 FPOptions()); 13154 } 13155 13156 // Handle placeholders on both operands. 13157 if (checkPlaceholderForOverload(*this, Args[0])) 13158 return ExprError(); 13159 if (checkPlaceholderForOverload(*this, Args[1])) 13160 return ExprError(); 13161 13162 // Build an empty overload set. 13163 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13164 13165 // Subscript can only be overloaded as a member function. 13166 13167 // Add operator candidates that are member functions. 13168 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13169 13170 // Add builtin operator candidates. 13171 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13172 13173 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13174 13175 // Perform overload resolution. 13176 OverloadCandidateSet::iterator Best; 13177 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13178 case OR_Success: { 13179 // We found a built-in operator or an overloaded operator. 13180 FunctionDecl *FnDecl = Best->Function; 13181 13182 if (FnDecl) { 13183 // We matched an overloaded operator. Build a call to that 13184 // operator. 13185 13186 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13187 13188 // Convert the arguments. 13189 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13190 ExprResult Arg0 = 13191 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13192 Best->FoundDecl, Method); 13193 if (Arg0.isInvalid()) 13194 return ExprError(); 13195 Args[0] = Arg0.get(); 13196 13197 // Convert the arguments. 13198 ExprResult InputInit 13199 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13200 Context, 13201 FnDecl->getParamDecl(0)), 13202 SourceLocation(), 13203 Args[1]); 13204 if (InputInit.isInvalid()) 13205 return ExprError(); 13206 13207 Args[1] = InputInit.getAs<Expr>(); 13208 13209 // Build the actual expression node. 13210 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13211 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13212 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13213 Best->FoundDecl, 13214 Base, 13215 HadMultipleCandidates, 13216 OpLocInfo.getLoc(), 13217 OpLocInfo.getInfo()); 13218 if (FnExpr.isInvalid()) 13219 return ExprError(); 13220 13221 // Determine the result type 13222 QualType ResultTy = FnDecl->getReturnType(); 13223 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13224 ResultTy = ResultTy.getNonLValueExprType(Context); 13225 13226 CXXOperatorCallExpr *TheCall = 13227 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 13228 Args, ResultTy, VK, RLoc, FPOptions()); 13229 13230 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 13231 return ExprError(); 13232 13233 if (CheckFunctionCall(Method, TheCall, 13234 Method->getType()->castAs<FunctionProtoType>())) 13235 return ExprError(); 13236 13237 return MaybeBindToTemporary(TheCall); 13238 } else { 13239 // We matched a built-in operator. Convert the arguments, then 13240 // break out so that we will build the appropriate built-in 13241 // operator node. 13242 ExprResult ArgsRes0 = PerformImplicitConversion( 13243 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13244 AA_Passing, CCK_ForBuiltinOverloadedOp); 13245 if (ArgsRes0.isInvalid()) 13246 return ExprError(); 13247 Args[0] = ArgsRes0.get(); 13248 13249 ExprResult ArgsRes1 = PerformImplicitConversion( 13250 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13251 AA_Passing, CCK_ForBuiltinOverloadedOp); 13252 if (ArgsRes1.isInvalid()) 13253 return ExprError(); 13254 Args[1] = ArgsRes1.get(); 13255 13256 break; 13257 } 13258 } 13259 13260 case OR_No_Viable_Function: { 13261 PartialDiagnostic PD = CandidateSet.empty() 13262 ? (PDiag(diag::err_ovl_no_oper) 13263 << Args[0]->getType() << /*subscript*/ 0 13264 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 13265 : (PDiag(diag::err_ovl_no_viable_subscript) 13266 << Args[0]->getType() << Args[0]->getSourceRange() 13267 << Args[1]->getSourceRange()); 13268 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 13269 OCD_AllCandidates, Args, "[]", LLoc); 13270 return ExprError(); 13271 } 13272 13273 case OR_Ambiguous: 13274 CandidateSet.NoteCandidates( 13275 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13276 << "[]" << Args[0]->getType() 13277 << Args[1]->getType() 13278 << Args[0]->getSourceRange() 13279 << Args[1]->getSourceRange()), 13280 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 13281 return ExprError(); 13282 13283 case OR_Deleted: 13284 CandidateSet.NoteCandidates( 13285 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 13286 << "[]" << Args[0]->getSourceRange() 13287 << Args[1]->getSourceRange()), 13288 *this, OCD_AllCandidates, Args, "[]", LLoc); 13289 return ExprError(); 13290 } 13291 13292 // We matched a built-in operator; build it. 13293 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 13294 } 13295 13296 /// BuildCallToMemberFunction - Build a call to a member 13297 /// function. MemExpr is the expression that refers to the member 13298 /// function (and includes the object parameter), Args/NumArgs are the 13299 /// arguments to the function call (not including the object 13300 /// parameter). The caller needs to validate that the member 13301 /// expression refers to a non-static member function or an overloaded 13302 /// member function. 13303 ExprResult 13304 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 13305 SourceLocation LParenLoc, 13306 MultiExprArg Args, 13307 SourceLocation RParenLoc) { 13308 assert(MemExprE->getType() == Context.BoundMemberTy || 13309 MemExprE->getType() == Context.OverloadTy); 13310 13311 // Dig out the member expression. This holds both the object 13312 // argument and the member function we're referring to. 13313 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 13314 13315 // Determine whether this is a call to a pointer-to-member function. 13316 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 13317 assert(op->getType() == Context.BoundMemberTy); 13318 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 13319 13320 QualType fnType = 13321 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 13322 13323 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 13324 QualType resultType = proto->getCallResultType(Context); 13325 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 13326 13327 // Check that the object type isn't more qualified than the 13328 // member function we're calling. 13329 Qualifiers funcQuals = proto->getMethodQuals(); 13330 13331 QualType objectType = op->getLHS()->getType(); 13332 if (op->getOpcode() == BO_PtrMemI) 13333 objectType = objectType->castAs<PointerType>()->getPointeeType(); 13334 Qualifiers objectQuals = objectType.getQualifiers(); 13335 13336 Qualifiers difference = objectQuals - funcQuals; 13337 difference.removeObjCGCAttr(); 13338 difference.removeAddressSpace(); 13339 if (difference) { 13340 std::string qualsString = difference.getAsString(); 13341 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 13342 << fnType.getUnqualifiedType() 13343 << qualsString 13344 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 13345 } 13346 13347 CXXMemberCallExpr *call = 13348 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 13349 valueKind, RParenLoc, proto->getNumParams()); 13350 13351 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 13352 call, nullptr)) 13353 return ExprError(); 13354 13355 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 13356 return ExprError(); 13357 13358 if (CheckOtherCall(call, proto)) 13359 return ExprError(); 13360 13361 return MaybeBindToTemporary(call); 13362 } 13363 13364 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 13365 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 13366 RParenLoc); 13367 13368 UnbridgedCastsSet UnbridgedCasts; 13369 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13370 return ExprError(); 13371 13372 MemberExpr *MemExpr; 13373 CXXMethodDecl *Method = nullptr; 13374 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 13375 NestedNameSpecifier *Qualifier = nullptr; 13376 if (isa<MemberExpr>(NakedMemExpr)) { 13377 MemExpr = cast<MemberExpr>(NakedMemExpr); 13378 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 13379 FoundDecl = MemExpr->getFoundDecl(); 13380 Qualifier = MemExpr->getQualifier(); 13381 UnbridgedCasts.restore(); 13382 } else { 13383 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 13384 Qualifier = UnresExpr->getQualifier(); 13385 13386 QualType ObjectType = UnresExpr->getBaseType(); 13387 Expr::Classification ObjectClassification 13388 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 13389 : UnresExpr->getBase()->Classify(Context); 13390 13391 // Add overload candidates 13392 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 13393 OverloadCandidateSet::CSK_Normal); 13394 13395 // FIXME: avoid copy. 13396 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13397 if (UnresExpr->hasExplicitTemplateArgs()) { 13398 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13399 TemplateArgs = &TemplateArgsBuffer; 13400 } 13401 13402 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 13403 E = UnresExpr->decls_end(); I != E; ++I) { 13404 13405 NamedDecl *Func = *I; 13406 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 13407 if (isa<UsingShadowDecl>(Func)) 13408 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 13409 13410 13411 // Microsoft supports direct constructor calls. 13412 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 13413 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 13414 CandidateSet, 13415 /*SuppressUserConversions*/ false); 13416 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 13417 // If explicit template arguments were provided, we can't call a 13418 // non-template member function. 13419 if (TemplateArgs) 13420 continue; 13421 13422 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 13423 ObjectClassification, Args, CandidateSet, 13424 /*SuppressUserConversions=*/false); 13425 } else { 13426 AddMethodTemplateCandidate( 13427 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 13428 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 13429 /*SuppressUserConversions=*/false); 13430 } 13431 } 13432 13433 DeclarationName DeclName = UnresExpr->getMemberName(); 13434 13435 UnbridgedCasts.restore(); 13436 13437 OverloadCandidateSet::iterator Best; 13438 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 13439 Best)) { 13440 case OR_Success: 13441 Method = cast<CXXMethodDecl>(Best->Function); 13442 FoundDecl = Best->FoundDecl; 13443 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13444 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13445 return ExprError(); 13446 // If FoundDecl is different from Method (such as if one is a template 13447 // and the other a specialization), make sure DiagnoseUseOfDecl is 13448 // called on both. 13449 // FIXME: This would be more comprehensively addressed by modifying 13450 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13451 // being used. 13452 if (Method != FoundDecl.getDecl() && 13453 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13454 return ExprError(); 13455 break; 13456 13457 case OR_No_Viable_Function: 13458 CandidateSet.NoteCandidates( 13459 PartialDiagnosticAt( 13460 UnresExpr->getMemberLoc(), 13461 PDiag(diag::err_ovl_no_viable_member_function_in_call) 13462 << DeclName << MemExprE->getSourceRange()), 13463 *this, OCD_AllCandidates, Args); 13464 // FIXME: Leaking incoming expressions! 13465 return ExprError(); 13466 13467 case OR_Ambiguous: 13468 CandidateSet.NoteCandidates( 13469 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13470 PDiag(diag::err_ovl_ambiguous_member_call) 13471 << DeclName << MemExprE->getSourceRange()), 13472 *this, OCD_AmbiguousCandidates, Args); 13473 // FIXME: Leaking incoming expressions! 13474 return ExprError(); 13475 13476 case OR_Deleted: 13477 CandidateSet.NoteCandidates( 13478 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13479 PDiag(diag::err_ovl_deleted_member_call) 13480 << DeclName << MemExprE->getSourceRange()), 13481 *this, OCD_AllCandidates, Args); 13482 // FIXME: Leaking incoming expressions! 13483 return ExprError(); 13484 } 13485 13486 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13487 13488 // If overload resolution picked a static member, build a 13489 // non-member call based on that function. 13490 if (Method->isStatic()) { 13491 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13492 RParenLoc); 13493 } 13494 13495 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13496 } 13497 13498 QualType ResultType = Method->getReturnType(); 13499 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13500 ResultType = ResultType.getNonLValueExprType(Context); 13501 13502 assert(Method && "Member call to something that isn't a method?"); 13503 const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); 13504 CXXMemberCallExpr *TheCall = 13505 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13506 RParenLoc, Proto->getNumParams()); 13507 13508 // Check for a valid return type. 13509 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13510 TheCall, Method)) 13511 return ExprError(); 13512 13513 // Convert the object argument (for a non-static member function call). 13514 // We only need to do this if there was actually an overload; otherwise 13515 // it was done at lookup. 13516 if (!Method->isStatic()) { 13517 ExprResult ObjectArg = 13518 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13519 FoundDecl, Method); 13520 if (ObjectArg.isInvalid()) 13521 return ExprError(); 13522 MemExpr->setBase(ObjectArg.get()); 13523 } 13524 13525 // Convert the rest of the arguments 13526 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13527 RParenLoc)) 13528 return ExprError(); 13529 13530 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13531 13532 if (CheckFunctionCall(Method, TheCall, Proto)) 13533 return ExprError(); 13534 13535 // In the case the method to call was not selected by the overloading 13536 // resolution process, we still need to handle the enable_if attribute. Do 13537 // that here, so it will not hide previous -- and more relevant -- errors. 13538 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13539 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13540 Diag(MemE->getMemberLoc(), 13541 diag::err_ovl_no_viable_member_function_in_call) 13542 << Method << Method->getSourceRange(); 13543 Diag(Method->getLocation(), 13544 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13545 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13546 return ExprError(); 13547 } 13548 } 13549 13550 if ((isa<CXXConstructorDecl>(CurContext) || 13551 isa<CXXDestructorDecl>(CurContext)) && 13552 TheCall->getMethodDecl()->isPure()) { 13553 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13554 13555 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13556 MemExpr->performsVirtualDispatch(getLangOpts())) { 13557 Diag(MemExpr->getBeginLoc(), 13558 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13559 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13560 << MD->getParent()->getDeclName(); 13561 13562 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13563 if (getLangOpts().AppleKext) 13564 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13565 << MD->getParent()->getDeclName() << MD->getDeclName(); 13566 } 13567 } 13568 13569 if (CXXDestructorDecl *DD = 13570 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13571 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13572 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13573 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13574 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13575 MemExpr->getMemberLoc()); 13576 } 13577 13578 return MaybeBindToTemporary(TheCall); 13579 } 13580 13581 /// BuildCallToObjectOfClassType - Build a call to an object of class 13582 /// type (C++ [over.call.object]), which can end up invoking an 13583 /// overloaded function call operator (@c operator()) or performing a 13584 /// user-defined conversion on the object argument. 13585 ExprResult 13586 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13587 SourceLocation LParenLoc, 13588 MultiExprArg Args, 13589 SourceLocation RParenLoc) { 13590 if (checkPlaceholderForOverload(*this, Obj)) 13591 return ExprError(); 13592 ExprResult Object = Obj; 13593 13594 UnbridgedCastsSet UnbridgedCasts; 13595 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13596 return ExprError(); 13597 13598 assert(Object.get()->getType()->isRecordType() && 13599 "Requires object type argument"); 13600 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13601 13602 // C++ [over.call.object]p1: 13603 // If the primary-expression E in the function call syntax 13604 // evaluates to a class object of type "cv T", then the set of 13605 // candidate functions includes at least the function call 13606 // operators of T. The function call operators of T are obtained by 13607 // ordinary lookup of the name operator() in the context of 13608 // (E).operator(). 13609 OverloadCandidateSet CandidateSet(LParenLoc, 13610 OverloadCandidateSet::CSK_Operator); 13611 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13612 13613 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13614 diag::err_incomplete_object_call, Object.get())) 13615 return true; 13616 13617 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13618 LookupQualifiedName(R, Record->getDecl()); 13619 R.suppressDiagnostics(); 13620 13621 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13622 Oper != OperEnd; ++Oper) { 13623 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13624 Object.get()->Classify(Context), Args, CandidateSet, 13625 /*SuppressUserConversion=*/false); 13626 } 13627 13628 // C++ [over.call.object]p2: 13629 // In addition, for each (non-explicit in C++0x) conversion function 13630 // declared in T of the form 13631 // 13632 // operator conversion-type-id () cv-qualifier; 13633 // 13634 // where cv-qualifier is the same cv-qualification as, or a 13635 // greater cv-qualification than, cv, and where conversion-type-id 13636 // denotes the type "pointer to function of (P1,...,Pn) returning 13637 // R", or the type "reference to pointer to function of 13638 // (P1,...,Pn) returning R", or the type "reference to function 13639 // of (P1,...,Pn) returning R", a surrogate call function [...] 13640 // is also considered as a candidate function. Similarly, 13641 // surrogate call functions are added to the set of candidate 13642 // functions for each conversion function declared in an 13643 // accessible base class provided the function is not hidden 13644 // within T by another intervening declaration. 13645 const auto &Conversions = 13646 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13647 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13648 NamedDecl *D = *I; 13649 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13650 if (isa<UsingShadowDecl>(D)) 13651 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13652 13653 // Skip over templated conversion functions; they aren't 13654 // surrogates. 13655 if (isa<FunctionTemplateDecl>(D)) 13656 continue; 13657 13658 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13659 if (!Conv->isExplicit()) { 13660 // Strip the reference type (if any) and then the pointer type (if 13661 // any) to get down to what might be a function type. 13662 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13663 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13664 ConvType = ConvPtrType->getPointeeType(); 13665 13666 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13667 { 13668 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13669 Object.get(), Args, CandidateSet); 13670 } 13671 } 13672 } 13673 13674 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13675 13676 // Perform overload resolution. 13677 OverloadCandidateSet::iterator Best; 13678 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13679 Best)) { 13680 case OR_Success: 13681 // Overload resolution succeeded; we'll build the appropriate call 13682 // below. 13683 break; 13684 13685 case OR_No_Viable_Function: { 13686 PartialDiagnostic PD = 13687 CandidateSet.empty() 13688 ? (PDiag(diag::err_ovl_no_oper) 13689 << Object.get()->getType() << /*call*/ 1 13690 << Object.get()->getSourceRange()) 13691 : (PDiag(diag::err_ovl_no_viable_object_call) 13692 << Object.get()->getType() << Object.get()->getSourceRange()); 13693 CandidateSet.NoteCandidates( 13694 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 13695 OCD_AllCandidates, Args); 13696 break; 13697 } 13698 case OR_Ambiguous: 13699 CandidateSet.NoteCandidates( 13700 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13701 PDiag(diag::err_ovl_ambiguous_object_call) 13702 << Object.get()->getType() 13703 << Object.get()->getSourceRange()), 13704 *this, OCD_AmbiguousCandidates, Args); 13705 break; 13706 13707 case OR_Deleted: 13708 CandidateSet.NoteCandidates( 13709 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13710 PDiag(diag::err_ovl_deleted_object_call) 13711 << Object.get()->getType() 13712 << Object.get()->getSourceRange()), 13713 *this, OCD_AllCandidates, Args); 13714 break; 13715 } 13716 13717 if (Best == CandidateSet.end()) 13718 return true; 13719 13720 UnbridgedCasts.restore(); 13721 13722 if (Best->Function == nullptr) { 13723 // Since there is no function declaration, this is one of the 13724 // surrogate candidates. Dig out the conversion function. 13725 CXXConversionDecl *Conv 13726 = cast<CXXConversionDecl>( 13727 Best->Conversions[0].UserDefined.ConversionFunction); 13728 13729 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13730 Best->FoundDecl); 13731 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13732 return ExprError(); 13733 assert(Conv == Best->FoundDecl.getDecl() && 13734 "Found Decl & conversion-to-functionptr should be same, right?!"); 13735 // We selected one of the surrogate functions that converts the 13736 // object parameter to a function pointer. Perform the conversion 13737 // on the object argument, then let BuildCallExpr finish the job. 13738 13739 // Create an implicit member expr to refer to the conversion operator. 13740 // and then call it. 13741 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13742 Conv, HadMultipleCandidates); 13743 if (Call.isInvalid()) 13744 return ExprError(); 13745 // Record usage of conversion in an implicit cast. 13746 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13747 CK_UserDefinedConversion, Call.get(), 13748 nullptr, VK_RValue); 13749 13750 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13751 } 13752 13753 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13754 13755 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13756 // that calls this method, using Object for the implicit object 13757 // parameter and passing along the remaining arguments. 13758 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13759 13760 // An error diagnostic has already been printed when parsing the declaration. 13761 if (Method->isInvalidDecl()) 13762 return ExprError(); 13763 13764 const FunctionProtoType *Proto = 13765 Method->getType()->getAs<FunctionProtoType>(); 13766 13767 unsigned NumParams = Proto->getNumParams(); 13768 13769 DeclarationNameInfo OpLocInfo( 13770 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13771 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13772 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13773 Obj, HadMultipleCandidates, 13774 OpLocInfo.getLoc(), 13775 OpLocInfo.getInfo()); 13776 if (NewFn.isInvalid()) 13777 return true; 13778 13779 // The number of argument slots to allocate in the call. If we have default 13780 // arguments we need to allocate space for them as well. We additionally 13781 // need one more slot for the object parameter. 13782 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 13783 13784 // Build the full argument list for the method call (the implicit object 13785 // parameter is placed at the beginning of the list). 13786 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 13787 13788 bool IsError = false; 13789 13790 // Initialize the implicit object parameter. 13791 ExprResult ObjRes = 13792 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13793 Best->FoundDecl, Method); 13794 if (ObjRes.isInvalid()) 13795 IsError = true; 13796 else 13797 Object = ObjRes; 13798 MethodArgs[0] = Object.get(); 13799 13800 // Check the argument types. 13801 for (unsigned i = 0; i != NumParams; i++) { 13802 Expr *Arg; 13803 if (i < Args.size()) { 13804 Arg = Args[i]; 13805 13806 // Pass the argument. 13807 13808 ExprResult InputInit 13809 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13810 Context, 13811 Method->getParamDecl(i)), 13812 SourceLocation(), Arg); 13813 13814 IsError |= InputInit.isInvalid(); 13815 Arg = InputInit.getAs<Expr>(); 13816 } else { 13817 ExprResult DefArg 13818 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13819 if (DefArg.isInvalid()) { 13820 IsError = true; 13821 break; 13822 } 13823 13824 Arg = DefArg.getAs<Expr>(); 13825 } 13826 13827 MethodArgs[i + 1] = Arg; 13828 } 13829 13830 // If this is a variadic call, handle args passed through "...". 13831 if (Proto->isVariadic()) { 13832 // Promote the arguments (C99 6.5.2.2p7). 13833 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13834 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13835 nullptr); 13836 IsError |= Arg.isInvalid(); 13837 MethodArgs[i + 1] = Arg.get(); 13838 } 13839 } 13840 13841 if (IsError) 13842 return true; 13843 13844 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13845 13846 // Once we've built TheCall, all of the expressions are properly owned. 13847 QualType ResultTy = Method->getReturnType(); 13848 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13849 ResultTy = ResultTy.getNonLValueExprType(Context); 13850 13851 CXXOperatorCallExpr *TheCall = 13852 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 13853 ResultTy, VK, RParenLoc, FPOptions()); 13854 13855 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13856 return true; 13857 13858 if (CheckFunctionCall(Method, TheCall, Proto)) 13859 return true; 13860 13861 return MaybeBindToTemporary(TheCall); 13862 } 13863 13864 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13865 /// (if one exists), where @c Base is an expression of class type and 13866 /// @c Member is the name of the member we're trying to find. 13867 ExprResult 13868 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13869 bool *NoArrowOperatorFound) { 13870 assert(Base->getType()->isRecordType() && 13871 "left-hand side must have class type"); 13872 13873 if (checkPlaceholderForOverload(*this, Base)) 13874 return ExprError(); 13875 13876 SourceLocation Loc = Base->getExprLoc(); 13877 13878 // C++ [over.ref]p1: 13879 // 13880 // [...] An expression x->m is interpreted as (x.operator->())->m 13881 // for a class object x of type T if T::operator->() exists and if 13882 // the operator is selected as the best match function by the 13883 // overload resolution mechanism (13.3). 13884 DeclarationName OpName = 13885 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13886 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13887 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13888 13889 if (RequireCompleteType(Loc, Base->getType(), 13890 diag::err_typecheck_incomplete_tag, Base)) 13891 return ExprError(); 13892 13893 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13894 LookupQualifiedName(R, BaseRecord->getDecl()); 13895 R.suppressDiagnostics(); 13896 13897 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13898 Oper != OperEnd; ++Oper) { 13899 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13900 None, CandidateSet, /*SuppressUserConversion=*/false); 13901 } 13902 13903 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13904 13905 // Perform overload resolution. 13906 OverloadCandidateSet::iterator Best; 13907 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13908 case OR_Success: 13909 // Overload resolution succeeded; we'll build the call below. 13910 break; 13911 13912 case OR_No_Viable_Function: { 13913 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 13914 if (CandidateSet.empty()) { 13915 QualType BaseType = Base->getType(); 13916 if (NoArrowOperatorFound) { 13917 // Report this specific error to the caller instead of emitting a 13918 // diagnostic, as requested. 13919 *NoArrowOperatorFound = true; 13920 return ExprError(); 13921 } 13922 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13923 << BaseType << Base->getSourceRange(); 13924 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13925 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13926 << FixItHint::CreateReplacement(OpLoc, "."); 13927 } 13928 } else 13929 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13930 << "operator->" << Base->getSourceRange(); 13931 CandidateSet.NoteCandidates(*this, Base, Cands); 13932 return ExprError(); 13933 } 13934 case OR_Ambiguous: 13935 CandidateSet.NoteCandidates( 13936 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 13937 << "->" << Base->getType() 13938 << Base->getSourceRange()), 13939 *this, OCD_AmbiguousCandidates, Base); 13940 return ExprError(); 13941 13942 case OR_Deleted: 13943 CandidateSet.NoteCandidates( 13944 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13945 << "->" << Base->getSourceRange()), 13946 *this, OCD_AllCandidates, Base); 13947 return ExprError(); 13948 } 13949 13950 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13951 13952 // Convert the object parameter. 13953 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13954 ExprResult BaseResult = 13955 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13956 Best->FoundDecl, Method); 13957 if (BaseResult.isInvalid()) 13958 return ExprError(); 13959 Base = BaseResult.get(); 13960 13961 // Build the operator call. 13962 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13963 Base, HadMultipleCandidates, OpLoc); 13964 if (FnExpr.isInvalid()) 13965 return ExprError(); 13966 13967 QualType ResultTy = Method->getReturnType(); 13968 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13969 ResultTy = ResultTy.getNonLValueExprType(Context); 13970 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13971 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 13972 13973 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13974 return ExprError(); 13975 13976 if (CheckFunctionCall(Method, TheCall, 13977 Method->getType()->castAs<FunctionProtoType>())) 13978 return ExprError(); 13979 13980 return MaybeBindToTemporary(TheCall); 13981 } 13982 13983 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13984 /// a literal operator described by the provided lookup results. 13985 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13986 DeclarationNameInfo &SuffixInfo, 13987 ArrayRef<Expr*> Args, 13988 SourceLocation LitEndLoc, 13989 TemplateArgumentListInfo *TemplateArgs) { 13990 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13991 13992 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13993 OverloadCandidateSet::CSK_Normal); 13994 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 13995 TemplateArgs); 13996 13997 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13998 13999 // Perform overload resolution. This will usually be trivial, but might need 14000 // to perform substitutions for a literal operator template. 14001 OverloadCandidateSet::iterator Best; 14002 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14003 case OR_Success: 14004 case OR_Deleted: 14005 break; 14006 14007 case OR_No_Viable_Function: 14008 CandidateSet.NoteCandidates( 14009 PartialDiagnosticAt(UDSuffixLoc, 14010 PDiag(diag::err_ovl_no_viable_function_in_call) 14011 << R.getLookupName()), 14012 *this, OCD_AllCandidates, Args); 14013 return ExprError(); 14014 14015 case OR_Ambiguous: 14016 CandidateSet.NoteCandidates( 14017 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14018 << R.getLookupName()), 14019 *this, OCD_AmbiguousCandidates, Args); 14020 return ExprError(); 14021 } 14022 14023 FunctionDecl *FD = Best->Function; 14024 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14025 nullptr, HadMultipleCandidates, 14026 SuffixInfo.getLoc(), 14027 SuffixInfo.getInfo()); 14028 if (Fn.isInvalid()) 14029 return true; 14030 14031 // Check the argument types. This should almost always be a no-op, except 14032 // that array-to-pointer decay is applied to string literals. 14033 Expr *ConvArgs[2]; 14034 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14035 ExprResult InputInit = PerformCopyInitialization( 14036 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14037 SourceLocation(), Args[ArgIdx]); 14038 if (InputInit.isInvalid()) 14039 return true; 14040 ConvArgs[ArgIdx] = InputInit.get(); 14041 } 14042 14043 QualType ResultTy = FD->getReturnType(); 14044 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14045 ResultTy = ResultTy.getNonLValueExprType(Context); 14046 14047 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14048 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14049 VK, LitEndLoc, UDSuffixLoc); 14050 14051 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14052 return ExprError(); 14053 14054 if (CheckFunctionCall(FD, UDL, nullptr)) 14055 return ExprError(); 14056 14057 return MaybeBindToTemporary(UDL); 14058 } 14059 14060 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14061 /// given LookupResult is non-empty, it is assumed to describe a member which 14062 /// will be invoked. Otherwise, the function will be found via argument 14063 /// dependent lookup. 14064 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14065 /// otherwise CallExpr is set to ExprError() and some non-success value 14066 /// is returned. 14067 Sema::ForRangeStatus 14068 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14069 SourceLocation RangeLoc, 14070 const DeclarationNameInfo &NameInfo, 14071 LookupResult &MemberLookup, 14072 OverloadCandidateSet *CandidateSet, 14073 Expr *Range, ExprResult *CallExpr) { 14074 Scope *S = nullptr; 14075 14076 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14077 if (!MemberLookup.empty()) { 14078 ExprResult MemberRef = 14079 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14080 /*IsPtr=*/false, CXXScopeSpec(), 14081 /*TemplateKWLoc=*/SourceLocation(), 14082 /*FirstQualifierInScope=*/nullptr, 14083 MemberLookup, 14084 /*TemplateArgs=*/nullptr, S); 14085 if (MemberRef.isInvalid()) { 14086 *CallExpr = ExprError(); 14087 return FRS_DiagnosticIssued; 14088 } 14089 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14090 if (CallExpr->isInvalid()) { 14091 *CallExpr = ExprError(); 14092 return FRS_DiagnosticIssued; 14093 } 14094 } else { 14095 UnresolvedSet<0> FoundNames; 14096 UnresolvedLookupExpr *Fn = 14097 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 14098 NestedNameSpecifierLoc(), NameInfo, 14099 /*NeedsADL=*/true, /*Overloaded=*/false, 14100 FoundNames.begin(), FoundNames.end()); 14101 14102 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14103 CandidateSet, CallExpr); 14104 if (CandidateSet->empty() || CandidateSetError) { 14105 *CallExpr = ExprError(); 14106 return FRS_NoViableFunction; 14107 } 14108 OverloadCandidateSet::iterator Best; 14109 OverloadingResult OverloadResult = 14110 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14111 14112 if (OverloadResult == OR_No_Viable_Function) { 14113 *CallExpr = ExprError(); 14114 return FRS_NoViableFunction; 14115 } 14116 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14117 Loc, nullptr, CandidateSet, &Best, 14118 OverloadResult, 14119 /*AllowTypoCorrection=*/false); 14120 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14121 *CallExpr = ExprError(); 14122 return FRS_DiagnosticIssued; 14123 } 14124 } 14125 return FRS_Success; 14126 } 14127 14128 14129 /// FixOverloadedFunctionReference - E is an expression that refers to 14130 /// a C++ overloaded function (possibly with some parentheses and 14131 /// perhaps a '&' around it). We have resolved the overloaded function 14132 /// to the function declaration Fn, so patch up the expression E to 14133 /// refer (possibly indirectly) to Fn. Returns the new expr. 14134 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14135 FunctionDecl *Fn) { 14136 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14137 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14138 Found, Fn); 14139 if (SubExpr == PE->getSubExpr()) 14140 return PE; 14141 14142 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14143 } 14144 14145 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14146 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14147 Found, Fn); 14148 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 14149 SubExpr->getType()) && 14150 "Implicit cast type cannot be determined from overload"); 14151 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 14152 if (SubExpr == ICE->getSubExpr()) 14153 return ICE; 14154 14155 return ImplicitCastExpr::Create(Context, ICE->getType(), 14156 ICE->getCastKind(), 14157 SubExpr, nullptr, 14158 ICE->getValueKind()); 14159 } 14160 14161 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14162 if (!GSE->isResultDependent()) { 14163 Expr *SubExpr = 14164 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14165 if (SubExpr == GSE->getResultExpr()) 14166 return GSE; 14167 14168 // Replace the resulting type information before rebuilding the generic 14169 // selection expression. 14170 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14171 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14172 unsigned ResultIdx = GSE->getResultIndex(); 14173 AssocExprs[ResultIdx] = SubExpr; 14174 14175 return GenericSelectionExpr::Create( 14176 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14177 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14178 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14179 ResultIdx); 14180 } 14181 // Rather than fall through to the unreachable, return the original generic 14182 // selection expression. 14183 return GSE; 14184 } 14185 14186 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14187 assert(UnOp->getOpcode() == UO_AddrOf && 14188 "Can only take the address of an overloaded function"); 14189 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14190 if (Method->isStatic()) { 14191 // Do nothing: static member functions aren't any different 14192 // from non-member functions. 14193 } else { 14194 // Fix the subexpression, which really has to be an 14195 // UnresolvedLookupExpr holding an overloaded member function 14196 // or template. 14197 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14198 Found, Fn); 14199 if (SubExpr == UnOp->getSubExpr()) 14200 return UnOp; 14201 14202 assert(isa<DeclRefExpr>(SubExpr) 14203 && "fixed to something other than a decl ref"); 14204 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 14205 && "fixed to a member ref with no nested name qualifier"); 14206 14207 // We have taken the address of a pointer to member 14208 // function. Perform the computation here so that we get the 14209 // appropriate pointer to member type. 14210 QualType ClassType 14211 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14212 QualType MemPtrType 14213 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 14214 // Under the MS ABI, lock down the inheritance model now. 14215 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14216 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 14217 14218 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 14219 VK_RValue, OK_Ordinary, 14220 UnOp->getOperatorLoc(), false); 14221 } 14222 } 14223 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14224 Found, Fn); 14225 if (SubExpr == UnOp->getSubExpr()) 14226 return UnOp; 14227 14228 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 14229 Context.getPointerType(SubExpr->getType()), 14230 VK_RValue, OK_Ordinary, 14231 UnOp->getOperatorLoc(), false); 14232 } 14233 14234 // C++ [except.spec]p17: 14235 // An exception-specification is considered to be needed when: 14236 // - in an expression the function is the unique lookup result or the 14237 // selected member of a set of overloaded functions 14238 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 14239 ResolveExceptionSpec(E->getExprLoc(), FPT); 14240 14241 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14242 // FIXME: avoid copy. 14243 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14244 if (ULE->hasExplicitTemplateArgs()) { 14245 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 14246 TemplateArgs = &TemplateArgsBuffer; 14247 } 14248 14249 DeclRefExpr *DRE = 14250 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 14251 ULE->getQualifierLoc(), Found.getDecl(), 14252 ULE->getTemplateKeywordLoc(), TemplateArgs); 14253 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 14254 return DRE; 14255 } 14256 14257 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 14258 // FIXME: avoid copy. 14259 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14260 if (MemExpr->hasExplicitTemplateArgs()) { 14261 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14262 TemplateArgs = &TemplateArgsBuffer; 14263 } 14264 14265 Expr *Base; 14266 14267 // If we're filling in a static method where we used to have an 14268 // implicit member access, rewrite to a simple decl ref. 14269 if (MemExpr->isImplicitAccess()) { 14270 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14271 DeclRefExpr *DRE = BuildDeclRefExpr( 14272 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 14273 MemExpr->getQualifierLoc(), Found.getDecl(), 14274 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 14275 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 14276 return DRE; 14277 } else { 14278 SourceLocation Loc = MemExpr->getMemberLoc(); 14279 if (MemExpr->getQualifier()) 14280 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 14281 Base = 14282 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 14283 } 14284 } else 14285 Base = MemExpr->getBase(); 14286 14287 ExprValueKind valueKind; 14288 QualType type; 14289 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14290 valueKind = VK_LValue; 14291 type = Fn->getType(); 14292 } else { 14293 valueKind = VK_RValue; 14294 type = Context.BoundMemberTy; 14295 } 14296 14297 return BuildMemberExpr( 14298 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 14299 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 14300 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 14301 type, valueKind, OK_Ordinary, TemplateArgs); 14302 } 14303 14304 llvm_unreachable("Invalid reference to overloaded function"); 14305 } 14306 14307 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 14308 DeclAccessPair Found, 14309 FunctionDecl *Fn) { 14310 return FixOverloadedFunctionReference(E.get(), Found, Fn); 14311 } 14312