1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/ADT/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 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) DeclRefExpr(Fn, false, Fn->getType(), 66 VK_LValue, Loc, LocInfo); 67 if (HadMultipleCandidates) 68 DRE->setHadMultipleCandidates(true); 69 70 S.MarkDeclRefReferenced(DRE); 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_Conversion, 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()->isObjCObjectPointerType() || 226 getFromType()->isBlockPointerType() || 227 getFromType()->isNullPtrType() || 228 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 229 return true; 230 231 return false; 232 } 233 234 /// isPointerConversionToVoidPointer - Determines whether this 235 /// conversion is a conversion of a pointer to a void pointer. This is 236 /// used as part of the ranking of standard conversion sequences (C++ 237 /// 13.3.3.2p4). 238 bool 239 StandardConversionSequence:: 240 isPointerConversionToVoidPointer(ASTContext& Context) const { 241 QualType FromType = getFromType(); 242 QualType ToType = getToType(1); 243 244 // Note that FromType has not necessarily been transformed by the 245 // array-to-pointer implicit conversion, so check for its presence 246 // and redo the conversion to get a pointer. 247 if (First == ICK_Array_To_Pointer) 248 FromType = Context.getArrayDecayedType(FromType); 249 250 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 251 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 252 return ToPtrType->getPointeeType()->isVoidType(); 253 254 return false; 255 } 256 257 /// Skip any implicit casts which could be either part of a narrowing conversion 258 /// or after one in an implicit conversion. 259 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 260 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 261 switch (ICE->getCastKind()) { 262 case CK_NoOp: 263 case CK_IntegralCast: 264 case CK_IntegralToBoolean: 265 case CK_IntegralToFloating: 266 case CK_BooleanToSignedIntegral: 267 case CK_FloatingToIntegral: 268 case CK_FloatingToBoolean: 269 case CK_FloatingCast: 270 Converted = ICE->getSubExpr(); 271 continue; 272 273 default: 274 return Converted; 275 } 276 } 277 278 return Converted; 279 } 280 281 /// Check if this standard conversion sequence represents a narrowing 282 /// conversion, according to C++11 [dcl.init.list]p7. 283 /// 284 /// \param Ctx The AST context. 285 /// \param Converted The result of applying this standard conversion sequence. 286 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 287 /// value of the expression prior to the narrowing conversion. 288 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 289 /// type of the expression prior to the narrowing conversion. 290 NarrowingKind 291 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 292 const Expr *Converted, 293 APValue &ConstantValue, 294 QualType &ConstantType) const { 295 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 296 297 // C++11 [dcl.init.list]p7: 298 // A narrowing conversion is an implicit conversion ... 299 QualType FromType = getToType(0); 300 QualType ToType = getToType(1); 301 302 // A conversion to an enumeration type is narrowing if the conversion to 303 // the underlying type is narrowing. This only arises for expressions of 304 // the form 'Enum{init}'. 305 if (auto *ET = ToType->getAs<EnumType>()) 306 ToType = ET->getDecl()->getIntegerType(); 307 308 switch (Second) { 309 // 'bool' is an integral type; dispatch to the right place to handle it. 310 case ICK_Boolean_Conversion: 311 if (FromType->isRealFloatingType()) 312 goto FloatingIntegralConversion; 313 if (FromType->isIntegralOrUnscopedEnumerationType()) 314 goto IntegralConversion; 315 // Boolean conversions can be from pointers and pointers to members 316 // [conv.bool], and those aren't considered narrowing conversions. 317 return NK_Not_Narrowing; 318 319 // -- from a floating-point type to an integer type, or 320 // 321 // -- from an integer type or unscoped enumeration type to a floating-point 322 // type, except where the source is a constant expression and the actual 323 // value after conversion will fit into the target type and will produce 324 // the original value when converted back to the original type, or 325 case ICK_Floating_Integral: 326 FloatingIntegralConversion: 327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 328 return NK_Type_Narrowing; 329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 330 llvm::APSInt IntConstantValue; 331 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 332 333 // If it's value-dependent, we can't tell whether it's narrowing. 334 if (Initializer->isValueDependent()) 335 return NK_Dependent_Narrowing; 336 337 if (Initializer && 338 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 339 // Convert the integer to the floating type. 340 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 341 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 342 llvm::APFloat::rmNearestTiesToEven); 343 // And back. 344 llvm::APSInt ConvertedValue = IntConstantValue; 345 bool ignored; 346 Result.convertToInteger(ConvertedValue, 347 llvm::APFloat::rmTowardZero, &ignored); 348 // If the resulting value is different, this was a narrowing conversion. 349 if (IntConstantValue != ConvertedValue) { 350 ConstantValue = APValue(IntConstantValue); 351 ConstantType = Initializer->getType(); 352 return NK_Constant_Narrowing; 353 } 354 } else { 355 // Variables are always narrowings. 356 return NK_Variable_Narrowing; 357 } 358 } 359 return NK_Not_Narrowing; 360 361 // -- from long double to double or float, or from double to float, except 362 // where the source is a constant expression and the actual value after 363 // conversion is within the range of values that can be represented (even 364 // if it cannot be represented exactly), or 365 case ICK_Floating_Conversion: 366 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 367 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 368 // FromType is larger than ToType. 369 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 370 371 // If it's value-dependent, we can't tell whether it's narrowing. 372 if (Initializer->isValueDependent()) 373 return NK_Dependent_Narrowing; 374 375 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 376 // Constant! 377 assert(ConstantValue.isFloat()); 378 llvm::APFloat FloatVal = ConstantValue.getFloat(); 379 // Convert the source value into the target type. 380 bool ignored; 381 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 382 Ctx.getFloatTypeSemantics(ToType), 383 llvm::APFloat::rmNearestTiesToEven, &ignored); 384 // If there was no overflow, the source value is within the range of 385 // values that can be represented. 386 if (ConvertStatus & llvm::APFloat::opOverflow) { 387 ConstantType = Initializer->getType(); 388 return NK_Constant_Narrowing; 389 } 390 } else { 391 return NK_Variable_Narrowing; 392 } 393 } 394 return NK_Not_Narrowing; 395 396 // -- from an integer type or unscoped enumeration type to an integer type 397 // that cannot represent all the values of the original type, except where 398 // the source is a constant expression and the actual value after 399 // conversion will fit into the target type and will produce the original 400 // value when converted back to the original type. 401 case ICK_Integral_Conversion: 402 IntegralConversion: { 403 assert(FromType->isIntegralOrUnscopedEnumerationType()); 404 assert(ToType->isIntegralOrUnscopedEnumerationType()); 405 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 406 const unsigned FromWidth = Ctx.getIntWidth(FromType); 407 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 408 const unsigned ToWidth = Ctx.getIntWidth(ToType); 409 410 if (FromWidth > ToWidth || 411 (FromWidth == ToWidth && FromSigned != ToSigned) || 412 (FromSigned && !ToSigned)) { 413 // Not all values of FromType can be represented in ToType. 414 llvm::APSInt InitializerValue; 415 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 416 417 // If it's value-dependent, we can't tell whether it's narrowing. 418 if (Initializer->isValueDependent()) 419 return NK_Dependent_Narrowing; 420 421 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 422 // Such conversions on variables are always narrowing. 423 return NK_Variable_Narrowing; 424 } 425 bool Narrowing = false; 426 if (FromWidth < ToWidth) { 427 // Negative -> unsigned is narrowing. Otherwise, more bits is never 428 // narrowing. 429 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 430 Narrowing = true; 431 } else { 432 // Add a bit to the InitializerValue so we don't have to worry about 433 // signed vs. unsigned comparisons. 434 InitializerValue = InitializerValue.extend( 435 InitializerValue.getBitWidth() + 1); 436 // Convert the initializer to and from the target width and signed-ness. 437 llvm::APSInt ConvertedValue = InitializerValue; 438 ConvertedValue = ConvertedValue.trunc(ToWidth); 439 ConvertedValue.setIsSigned(ToSigned); 440 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 441 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 442 // If the result is different, this was a narrowing conversion. 443 if (ConvertedValue != InitializerValue) 444 Narrowing = true; 445 } 446 if (Narrowing) { 447 ConstantType = Initializer->getType(); 448 ConstantValue = APValue(InitializerValue); 449 return NK_Constant_Narrowing; 450 } 451 } 452 return NK_Not_Narrowing; 453 } 454 455 default: 456 // Other kinds of conversions are not narrowings. 457 return NK_Not_Narrowing; 458 } 459 } 460 461 /// dump - Print this standard conversion sequence to standard 462 /// error. Useful for debugging overloading issues. 463 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 464 raw_ostream &OS = llvm::errs(); 465 bool PrintedSomething = false; 466 if (First != ICK_Identity) { 467 OS << GetImplicitConversionName(First); 468 PrintedSomething = true; 469 } 470 471 if (Second != ICK_Identity) { 472 if (PrintedSomething) { 473 OS << " -> "; 474 } 475 OS << GetImplicitConversionName(Second); 476 477 if (CopyConstructor) { 478 OS << " (by copy constructor)"; 479 } else if (DirectBinding) { 480 OS << " (direct reference binding)"; 481 } else if (ReferenceBinding) { 482 OS << " (reference binding)"; 483 } 484 PrintedSomething = true; 485 } 486 487 if (Third != ICK_Identity) { 488 if (PrintedSomething) { 489 OS << " -> "; 490 } 491 OS << GetImplicitConversionName(Third); 492 PrintedSomething = true; 493 } 494 495 if (!PrintedSomething) { 496 OS << "No conversions required"; 497 } 498 } 499 500 /// dump - Print this user-defined conversion sequence to standard 501 /// error. Useful for debugging overloading issues. 502 void UserDefinedConversionSequence::dump() const { 503 raw_ostream &OS = llvm::errs(); 504 if (Before.First || Before.Second || Before.Third) { 505 Before.dump(); 506 OS << " -> "; 507 } 508 if (ConversionFunction) 509 OS << '\'' << *ConversionFunction << '\''; 510 else 511 OS << "aggregate initialization"; 512 if (After.First || After.Second || After.Third) { 513 OS << " -> "; 514 After.dump(); 515 } 516 } 517 518 /// dump - Print this implicit conversion sequence to standard 519 /// error. Useful for debugging overloading issues. 520 void ImplicitConversionSequence::dump() const { 521 raw_ostream &OS = llvm::errs(); 522 if (isStdInitializerListElement()) 523 OS << "Worst std::initializer_list element conversion: "; 524 switch (ConversionKind) { 525 case StandardConversion: 526 OS << "Standard conversion: "; 527 Standard.dump(); 528 break; 529 case UserDefinedConversion: 530 OS << "User-defined conversion: "; 531 UserDefined.dump(); 532 break; 533 case EllipsisConversion: 534 OS << "Ellipsis conversion"; 535 break; 536 case AmbiguousConversion: 537 OS << "Ambiguous conversion"; 538 break; 539 case BadConversion: 540 OS << "Bad conversion"; 541 break; 542 } 543 544 OS << "\n"; 545 } 546 547 void AmbiguousConversionSequence::construct() { 548 new (&conversions()) ConversionSet(); 549 } 550 551 void AmbiguousConversionSequence::destruct() { 552 conversions().~ConversionSet(); 553 } 554 555 void 556 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 557 FromTypePtr = O.FromTypePtr; 558 ToTypePtr = O.ToTypePtr; 559 new (&conversions()) ConversionSet(O.conversions()); 560 } 561 562 namespace { 563 // Structure used by DeductionFailureInfo to store 564 // template argument information. 565 struct DFIArguments { 566 TemplateArgument FirstArg; 567 TemplateArgument SecondArg; 568 }; 569 // Structure used by DeductionFailureInfo to store 570 // template parameter and template argument information. 571 struct DFIParamWithArguments : DFIArguments { 572 TemplateParameter Param; 573 }; 574 // Structure used by DeductionFailureInfo to store template argument 575 // information and the index of the problematic call argument. 576 struct DFIDeducedMismatchArgs : DFIArguments { 577 TemplateArgumentList *TemplateArgs; 578 unsigned CallArgIndex; 579 }; 580 } 581 582 /// \brief Convert from Sema's representation of template deduction information 583 /// to the form used in overload-candidate information. 584 DeductionFailureInfo 585 clang::MakeDeductionFailureInfo(ASTContext &Context, 586 Sema::TemplateDeductionResult TDK, 587 TemplateDeductionInfo &Info) { 588 DeductionFailureInfo Result; 589 Result.Result = static_cast<unsigned>(TDK); 590 Result.HasDiagnostic = false; 591 switch (TDK) { 592 case Sema::TDK_Success: 593 case Sema::TDK_Invalid: 594 case Sema::TDK_InstantiationDepth: 595 case Sema::TDK_TooManyArguments: 596 case Sema::TDK_TooFewArguments: 597 case Sema::TDK_MiscellaneousDeductionFailure: 598 case Sema::TDK_CUDATargetMismatch: 599 Result.Data = nullptr; 600 break; 601 602 case Sema::TDK_Incomplete: 603 case Sema::TDK_InvalidExplicitArguments: 604 Result.Data = Info.Param.getOpaqueValue(); 605 break; 606 607 case Sema::TDK_DeducedMismatch: { 608 // FIXME: Should allocate from normal heap so that we can free this later. 609 auto *Saved = new (Context) DFIDeducedMismatchArgs; 610 Saved->FirstArg = Info.FirstArg; 611 Saved->SecondArg = Info.SecondArg; 612 Saved->TemplateArgs = Info.take(); 613 Saved->CallArgIndex = Info.CallArgIndex; 614 Result.Data = Saved; 615 break; 616 } 617 618 case Sema::TDK_NonDeducedMismatch: { 619 // FIXME: Should allocate from normal heap so that we can free this later. 620 DFIArguments *Saved = new (Context) DFIArguments; 621 Saved->FirstArg = Info.FirstArg; 622 Saved->SecondArg = Info.SecondArg; 623 Result.Data = Saved; 624 break; 625 } 626 627 case Sema::TDK_Inconsistent: 628 case Sema::TDK_Underqualified: { 629 // FIXME: Should allocate from normal heap so that we can free this later. 630 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 631 Saved->Param = Info.Param; 632 Saved->FirstArg = Info.FirstArg; 633 Saved->SecondArg = Info.SecondArg; 634 Result.Data = Saved; 635 break; 636 } 637 638 case Sema::TDK_SubstitutionFailure: 639 Result.Data = Info.take(); 640 if (Info.hasSFINAEDiagnostic()) { 641 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 642 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 643 Info.takeSFINAEDiagnostic(*Diag); 644 Result.HasDiagnostic = true; 645 } 646 break; 647 648 case Sema::TDK_FailedOverloadResolution: 649 Result.Data = Info.Expression; 650 break; 651 } 652 653 return Result; 654 } 655 656 void DeductionFailureInfo::Destroy() { 657 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 658 case Sema::TDK_Success: 659 case Sema::TDK_Invalid: 660 case Sema::TDK_InstantiationDepth: 661 case Sema::TDK_Incomplete: 662 case Sema::TDK_TooManyArguments: 663 case Sema::TDK_TooFewArguments: 664 case Sema::TDK_InvalidExplicitArguments: 665 case Sema::TDK_FailedOverloadResolution: 666 case Sema::TDK_CUDATargetMismatch: 667 break; 668 669 case Sema::TDK_Inconsistent: 670 case Sema::TDK_Underqualified: 671 case Sema::TDK_DeducedMismatch: 672 case Sema::TDK_NonDeducedMismatch: 673 // FIXME: Destroy the data? 674 Data = nullptr; 675 break; 676 677 case Sema::TDK_SubstitutionFailure: 678 // FIXME: Destroy the template argument list? 679 Data = nullptr; 680 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 681 Diag->~PartialDiagnosticAt(); 682 HasDiagnostic = false; 683 } 684 break; 685 686 // Unhandled 687 case Sema::TDK_MiscellaneousDeductionFailure: 688 break; 689 } 690 } 691 692 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 693 if (HasDiagnostic) 694 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 695 return nullptr; 696 } 697 698 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 699 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 700 case Sema::TDK_Success: 701 case Sema::TDK_Invalid: 702 case Sema::TDK_InstantiationDepth: 703 case Sema::TDK_TooManyArguments: 704 case Sema::TDK_TooFewArguments: 705 case Sema::TDK_SubstitutionFailure: 706 case Sema::TDK_DeducedMismatch: 707 case Sema::TDK_NonDeducedMismatch: 708 case Sema::TDK_FailedOverloadResolution: 709 case Sema::TDK_CUDATargetMismatch: 710 return TemplateParameter(); 711 712 case Sema::TDK_Incomplete: 713 case Sema::TDK_InvalidExplicitArguments: 714 return TemplateParameter::getFromOpaqueValue(Data); 715 716 case Sema::TDK_Inconsistent: 717 case Sema::TDK_Underqualified: 718 return static_cast<DFIParamWithArguments*>(Data)->Param; 719 720 // Unhandled 721 case Sema::TDK_MiscellaneousDeductionFailure: 722 break; 723 } 724 725 return TemplateParameter(); 726 } 727 728 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 729 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 730 case Sema::TDK_Success: 731 case Sema::TDK_Invalid: 732 case Sema::TDK_InstantiationDepth: 733 case Sema::TDK_TooManyArguments: 734 case Sema::TDK_TooFewArguments: 735 case Sema::TDK_Incomplete: 736 case Sema::TDK_InvalidExplicitArguments: 737 case Sema::TDK_Inconsistent: 738 case Sema::TDK_Underqualified: 739 case Sema::TDK_NonDeducedMismatch: 740 case Sema::TDK_FailedOverloadResolution: 741 case Sema::TDK_CUDATargetMismatch: 742 return nullptr; 743 744 case Sema::TDK_DeducedMismatch: 745 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 746 747 case Sema::TDK_SubstitutionFailure: 748 return static_cast<TemplateArgumentList*>(Data); 749 750 // Unhandled 751 case Sema::TDK_MiscellaneousDeductionFailure: 752 break; 753 } 754 755 return nullptr; 756 } 757 758 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 759 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 760 case Sema::TDK_Success: 761 case Sema::TDK_Invalid: 762 case Sema::TDK_InstantiationDepth: 763 case Sema::TDK_Incomplete: 764 case Sema::TDK_TooManyArguments: 765 case Sema::TDK_TooFewArguments: 766 case Sema::TDK_InvalidExplicitArguments: 767 case Sema::TDK_SubstitutionFailure: 768 case Sema::TDK_FailedOverloadResolution: 769 case Sema::TDK_CUDATargetMismatch: 770 return nullptr; 771 772 case Sema::TDK_Inconsistent: 773 case Sema::TDK_Underqualified: 774 case Sema::TDK_DeducedMismatch: 775 case Sema::TDK_NonDeducedMismatch: 776 return &static_cast<DFIArguments*>(Data)->FirstArg; 777 778 // Unhandled 779 case Sema::TDK_MiscellaneousDeductionFailure: 780 break; 781 } 782 783 return nullptr; 784 } 785 786 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 787 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 788 case Sema::TDK_Success: 789 case Sema::TDK_Invalid: 790 case Sema::TDK_InstantiationDepth: 791 case Sema::TDK_Incomplete: 792 case Sema::TDK_TooManyArguments: 793 case Sema::TDK_TooFewArguments: 794 case Sema::TDK_InvalidExplicitArguments: 795 case Sema::TDK_SubstitutionFailure: 796 case Sema::TDK_FailedOverloadResolution: 797 case Sema::TDK_CUDATargetMismatch: 798 return nullptr; 799 800 case Sema::TDK_Inconsistent: 801 case Sema::TDK_Underqualified: 802 case Sema::TDK_DeducedMismatch: 803 case Sema::TDK_NonDeducedMismatch: 804 return &static_cast<DFIArguments*>(Data)->SecondArg; 805 806 // Unhandled 807 case Sema::TDK_MiscellaneousDeductionFailure: 808 break; 809 } 810 811 return nullptr; 812 } 813 814 Expr *DeductionFailureInfo::getExpr() { 815 if (static_cast<Sema::TemplateDeductionResult>(Result) == 816 Sema::TDK_FailedOverloadResolution) 817 return static_cast<Expr*>(Data); 818 819 return nullptr; 820 } 821 822 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 823 if (static_cast<Sema::TemplateDeductionResult>(Result) == 824 Sema::TDK_DeducedMismatch) 825 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 826 827 return llvm::None; 828 } 829 830 void OverloadCandidateSet::destroyCandidates() { 831 for (iterator i = begin(), e = end(); i != e; ++i) { 832 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 833 i->Conversions[ii].~ImplicitConversionSequence(); 834 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 835 i->DeductionFailure.Destroy(); 836 } 837 } 838 839 void OverloadCandidateSet::clear() { 840 destroyCandidates(); 841 ConversionSequenceAllocator.Reset(); 842 NumInlineSequences = 0; 843 Candidates.clear(); 844 Functions.clear(); 845 } 846 847 namespace { 848 class UnbridgedCastsSet { 849 struct Entry { 850 Expr **Addr; 851 Expr *Saved; 852 }; 853 SmallVector<Entry, 2> Entries; 854 855 public: 856 void save(Sema &S, Expr *&E) { 857 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 858 Entry entry = { &E, E }; 859 Entries.push_back(entry); 860 E = S.stripARCUnbridgedCast(E); 861 } 862 863 void restore() { 864 for (SmallVectorImpl<Entry>::iterator 865 i = Entries.begin(), e = Entries.end(); i != e; ++i) 866 *i->Addr = i->Saved; 867 } 868 }; 869 } 870 871 /// checkPlaceholderForOverload - Do any interesting placeholder-like 872 /// preprocessing on the given expression. 873 /// 874 /// \param unbridgedCasts a collection to which to add unbridged casts; 875 /// without this, they will be immediately diagnosed as errors 876 /// 877 /// Return true on unrecoverable error. 878 static bool 879 checkPlaceholderForOverload(Sema &S, Expr *&E, 880 UnbridgedCastsSet *unbridgedCasts = nullptr) { 881 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 882 // We can't handle overloaded expressions here because overload 883 // resolution might reasonably tweak them. 884 if (placeholder->getKind() == BuiltinType::Overload) return false; 885 886 // If the context potentially accepts unbridged ARC casts, strip 887 // the unbridged cast and add it to the collection for later restoration. 888 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 889 unbridgedCasts) { 890 unbridgedCasts->save(S, E); 891 return false; 892 } 893 894 // Go ahead and check everything else. 895 ExprResult result = S.CheckPlaceholderExpr(E); 896 if (result.isInvalid()) 897 return true; 898 899 E = result.get(); 900 return false; 901 } 902 903 // Nothing to do. 904 return false; 905 } 906 907 /// checkArgPlaceholdersForOverload - Check a set of call operands for 908 /// placeholders. 909 static bool checkArgPlaceholdersForOverload(Sema &S, 910 MultiExprArg Args, 911 UnbridgedCastsSet &unbridged) { 912 for (unsigned i = 0, e = Args.size(); i != e; ++i) 913 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 914 return true; 915 916 return false; 917 } 918 919 // IsOverload - Determine whether the given New declaration is an 920 // overload of the declarations in Old. This routine returns false if 921 // New and Old cannot be overloaded, e.g., if New has the same 922 // signature as some function in Old (C++ 1.3.10) or if the Old 923 // declarations aren't functions (or function templates) at all. When 924 // it does return false, MatchedDecl will point to the decl that New 925 // cannot be overloaded with. This decl may be a UsingShadowDecl on 926 // top of the underlying declaration. 927 // 928 // Example: Given the following input: 929 // 930 // void f(int, float); // #1 931 // void f(int, int); // #2 932 // int f(int, int); // #3 933 // 934 // When we process #1, there is no previous declaration of "f", 935 // so IsOverload will not be used. 936 // 937 // When we process #2, Old contains only the FunctionDecl for #1. By 938 // comparing the parameter types, we see that #1 and #2 are overloaded 939 // (since they have different signatures), so this routine returns 940 // false; MatchedDecl is unchanged. 941 // 942 // When we process #3, Old is an overload set containing #1 and #2. We 943 // compare the signatures of #3 to #1 (they're overloaded, so we do 944 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 945 // identical (return types of functions are not part of the 946 // signature), IsOverload returns false and MatchedDecl will be set to 947 // point to the FunctionDecl for #2. 948 // 949 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 950 // into a class by a using declaration. The rules for whether to hide 951 // shadow declarations ignore some properties which otherwise figure 952 // into a function template's signature. 953 Sema::OverloadKind 954 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 955 NamedDecl *&Match, bool NewIsUsingDecl) { 956 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 957 I != E; ++I) { 958 NamedDecl *OldD = *I; 959 960 bool OldIsUsingDecl = false; 961 if (isa<UsingShadowDecl>(OldD)) { 962 OldIsUsingDecl = true; 963 964 // We can always introduce two using declarations into the same 965 // context, even if they have identical signatures. 966 if (NewIsUsingDecl) continue; 967 968 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 969 } 970 971 // A using-declaration does not conflict with another declaration 972 // if one of them is hidden. 973 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 974 continue; 975 976 // If either declaration was introduced by a using declaration, 977 // we'll need to use slightly different rules for matching. 978 // Essentially, these rules are the normal rules, except that 979 // function templates hide function templates with different 980 // return types or template parameter lists. 981 bool UseMemberUsingDeclRules = 982 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 983 !New->getFriendObjectKind(); 984 985 if (FunctionDecl *OldF = OldD->getAsFunction()) { 986 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 987 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 988 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 989 continue; 990 } 991 992 if (!isa<FunctionTemplateDecl>(OldD) && 993 !shouldLinkPossiblyHiddenDecl(*I, New)) 994 continue; 995 996 Match = *I; 997 return Ovl_Match; 998 } 999 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1000 // We can overload with these, which can show up when doing 1001 // redeclaration checks for UsingDecls. 1002 assert(Old.getLookupKind() == LookupUsingDeclName); 1003 } else if (isa<TagDecl>(OldD)) { 1004 // We can always overload with tags by hiding them. 1005 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1006 // Optimistically assume that an unresolved using decl will 1007 // overload; if it doesn't, we'll have to diagnose during 1008 // template instantiation. 1009 // 1010 // Exception: if the scope is dependent and this is not a class 1011 // member, the using declaration can only introduce an enumerator. 1012 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1013 Match = *I; 1014 return Ovl_NonFunction; 1015 } 1016 } else { 1017 // (C++ 13p1): 1018 // Only function declarations can be overloaded; object and type 1019 // declarations cannot be overloaded. 1020 Match = *I; 1021 return Ovl_NonFunction; 1022 } 1023 } 1024 1025 return Ovl_Overload; 1026 } 1027 1028 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1029 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1030 // C++ [basic.start.main]p2: This function shall not be overloaded. 1031 if (New->isMain()) 1032 return false; 1033 1034 // MSVCRT user defined entry points cannot be overloaded. 1035 if (New->isMSVCRTEntryPoint()) 1036 return false; 1037 1038 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1039 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1040 1041 // C++ [temp.fct]p2: 1042 // A function template can be overloaded with other function templates 1043 // and with normal (non-template) functions. 1044 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1045 return true; 1046 1047 // Is the function New an overload of the function Old? 1048 QualType OldQType = Context.getCanonicalType(Old->getType()); 1049 QualType NewQType = Context.getCanonicalType(New->getType()); 1050 1051 // Compare the signatures (C++ 1.3.10) of the two functions to 1052 // determine whether they are overloads. If we find any mismatch 1053 // in the signature, they are overloads. 1054 1055 // If either of these functions is a K&R-style function (no 1056 // prototype), then we consider them to have matching signatures. 1057 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1058 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1059 return false; 1060 1061 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1062 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1063 1064 // The signature of a function includes the types of its 1065 // parameters (C++ 1.3.10), which includes the presence or absence 1066 // of the ellipsis; see C++ DR 357). 1067 if (OldQType != NewQType && 1068 (OldType->getNumParams() != NewType->getNumParams() || 1069 OldType->isVariadic() != NewType->isVariadic() || 1070 !FunctionParamTypesAreEqual(OldType, NewType))) 1071 return true; 1072 1073 // C++ [temp.over.link]p4: 1074 // The signature of a function template consists of its function 1075 // signature, its return type and its template parameter list. The names 1076 // of the template parameters are significant only for establishing the 1077 // relationship between the template parameters and the rest of the 1078 // signature. 1079 // 1080 // We check the return type and template parameter lists for function 1081 // templates first; the remaining checks follow. 1082 // 1083 // However, we don't consider either of these when deciding whether 1084 // a member introduced by a shadow declaration is hidden. 1085 if (!UseMemberUsingDeclRules && NewTemplate && 1086 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1087 OldTemplate->getTemplateParameters(), 1088 false, TPL_TemplateMatch) || 1089 OldType->getReturnType() != NewType->getReturnType())) 1090 return true; 1091 1092 // If the function is a class member, its signature includes the 1093 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1094 // 1095 // As part of this, also check whether one of the member functions 1096 // is static, in which case they are not overloads (C++ 1097 // 13.1p2). While not part of the definition of the signature, 1098 // this check is important to determine whether these functions 1099 // can be overloaded. 1100 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1101 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1102 if (OldMethod && NewMethod && 1103 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1104 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1105 if (!UseMemberUsingDeclRules && 1106 (OldMethod->getRefQualifier() == RQ_None || 1107 NewMethod->getRefQualifier() == RQ_None)) { 1108 // C++0x [over.load]p2: 1109 // - Member function declarations with the same name and the same 1110 // parameter-type-list as well as member function template 1111 // declarations with the same name, the same parameter-type-list, and 1112 // the same template parameter lists cannot be overloaded if any of 1113 // them, but not all, have a ref-qualifier (8.3.5). 1114 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1115 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1116 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1117 } 1118 return true; 1119 } 1120 1121 // We may not have applied the implicit const for a constexpr member 1122 // function yet (because we haven't yet resolved whether this is a static 1123 // or non-static member function). Add it now, on the assumption that this 1124 // is a redeclaration of OldMethod. 1125 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1126 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1127 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1128 !isa<CXXConstructorDecl>(NewMethod)) 1129 NewQuals |= Qualifiers::Const; 1130 1131 // We do not allow overloading based off of '__restrict'. 1132 OldQuals &= ~Qualifiers::Restrict; 1133 NewQuals &= ~Qualifiers::Restrict; 1134 if (OldQuals != NewQuals) 1135 return true; 1136 } 1137 1138 // Though pass_object_size is placed on parameters and takes an argument, we 1139 // consider it to be a function-level modifier for the sake of function 1140 // identity. Either the function has one or more parameters with 1141 // pass_object_size or it doesn't. 1142 if (functionHasPassObjectSizeParams(New) != 1143 functionHasPassObjectSizeParams(Old)) 1144 return true; 1145 1146 // enable_if attributes are an order-sensitive part of the signature. 1147 for (specific_attr_iterator<EnableIfAttr> 1148 NewI = New->specific_attr_begin<EnableIfAttr>(), 1149 NewE = New->specific_attr_end<EnableIfAttr>(), 1150 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1151 OldE = Old->specific_attr_end<EnableIfAttr>(); 1152 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1153 if (NewI == NewE || OldI == OldE) 1154 return true; 1155 llvm::FoldingSetNodeID NewID, OldID; 1156 NewI->getCond()->Profile(NewID, Context, true); 1157 OldI->getCond()->Profile(OldID, Context, true); 1158 if (NewID != OldID) 1159 return true; 1160 } 1161 1162 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1163 // Don't allow overloading of destructors. (In theory we could, but it 1164 // would be a giant change to clang.) 1165 if (isa<CXXDestructorDecl>(New)) 1166 return false; 1167 1168 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1169 OldTarget = IdentifyCUDATarget(Old); 1170 if (NewTarget == CFT_InvalidTarget) 1171 return false; 1172 1173 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1174 1175 // Allow overloading of functions with same signature and different CUDA 1176 // target attributes. 1177 return NewTarget != OldTarget; 1178 } 1179 1180 // The signatures match; this is not an overload. 1181 return false; 1182 } 1183 1184 /// \brief Checks availability of the function depending on the current 1185 /// function context. Inside an unavailable function, unavailability is ignored. 1186 /// 1187 /// \returns true if \arg FD is unavailable and current context is inside 1188 /// an available function, false otherwise. 1189 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1190 if (!FD->isUnavailable()) 1191 return false; 1192 1193 // Walk up the context of the caller. 1194 Decl *C = cast<Decl>(CurContext); 1195 do { 1196 if (C->isUnavailable()) 1197 return false; 1198 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1199 return true; 1200 } 1201 1202 /// \brief Tries a user-defined conversion from From to ToType. 1203 /// 1204 /// Produces an implicit conversion sequence for when a standard conversion 1205 /// is not an option. See TryImplicitConversion for more information. 1206 static ImplicitConversionSequence 1207 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1208 bool SuppressUserConversions, 1209 bool AllowExplicit, 1210 bool InOverloadResolution, 1211 bool CStyle, 1212 bool AllowObjCWritebackConversion, 1213 bool AllowObjCConversionOnExplicit) { 1214 ImplicitConversionSequence ICS; 1215 1216 if (SuppressUserConversions) { 1217 // We're not in the case above, so there is no conversion that 1218 // we can perform. 1219 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1220 return ICS; 1221 } 1222 1223 // Attempt user-defined conversion. 1224 OverloadCandidateSet Conversions(From->getExprLoc(), 1225 OverloadCandidateSet::CSK_Normal); 1226 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1227 Conversions, AllowExplicit, 1228 AllowObjCConversionOnExplicit)) { 1229 case OR_Success: 1230 case OR_Deleted: 1231 ICS.setUserDefined(); 1232 // C++ [over.ics.user]p4: 1233 // A conversion of an expression of class type to the same class 1234 // type is given Exact Match rank, and a conversion of an 1235 // expression of class type to a base class of that type is 1236 // given Conversion rank, in spite of the fact that a copy 1237 // constructor (i.e., a user-defined conversion function) is 1238 // called for those cases. 1239 if (CXXConstructorDecl *Constructor 1240 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1241 QualType FromCanon 1242 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1243 QualType ToCanon 1244 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1245 if (Constructor->isCopyConstructor() && 1246 (FromCanon == ToCanon || 1247 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1248 // Turn this into a "standard" conversion sequence, so that it 1249 // gets ranked with standard conversion sequences. 1250 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1251 ICS.setStandard(); 1252 ICS.Standard.setAsIdentityConversion(); 1253 ICS.Standard.setFromType(From->getType()); 1254 ICS.Standard.setAllToTypes(ToType); 1255 ICS.Standard.CopyConstructor = Constructor; 1256 ICS.Standard.FoundCopyConstructor = Found; 1257 if (ToCanon != FromCanon) 1258 ICS.Standard.Second = ICK_Derived_To_Base; 1259 } 1260 } 1261 break; 1262 1263 case OR_Ambiguous: 1264 ICS.setAmbiguous(); 1265 ICS.Ambiguous.setFromType(From->getType()); 1266 ICS.Ambiguous.setToType(ToType); 1267 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1268 Cand != Conversions.end(); ++Cand) 1269 if (Cand->Viable) 1270 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1271 break; 1272 1273 // Fall through. 1274 case OR_No_Viable_Function: 1275 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1276 break; 1277 } 1278 1279 return ICS; 1280 } 1281 1282 /// TryImplicitConversion - Attempt to perform an implicit conversion 1283 /// from the given expression (Expr) to the given type (ToType). This 1284 /// function returns an implicit conversion sequence that can be used 1285 /// to perform the initialization. Given 1286 /// 1287 /// void f(float f); 1288 /// void g(int i) { f(i); } 1289 /// 1290 /// this routine would produce an implicit conversion sequence to 1291 /// describe the initialization of f from i, which will be a standard 1292 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1293 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1294 // 1295 /// Note that this routine only determines how the conversion can be 1296 /// performed; it does not actually perform the conversion. As such, 1297 /// it will not produce any diagnostics if no conversion is available, 1298 /// but will instead return an implicit conversion sequence of kind 1299 /// "BadConversion". 1300 /// 1301 /// If @p SuppressUserConversions, then user-defined conversions are 1302 /// not permitted. 1303 /// If @p AllowExplicit, then explicit user-defined conversions are 1304 /// permitted. 1305 /// 1306 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1307 /// writeback conversion, which allows __autoreleasing id* parameters to 1308 /// be initialized with __strong id* or __weak id* arguments. 1309 static ImplicitConversionSequence 1310 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1311 bool SuppressUserConversions, 1312 bool AllowExplicit, 1313 bool InOverloadResolution, 1314 bool CStyle, 1315 bool AllowObjCWritebackConversion, 1316 bool AllowObjCConversionOnExplicit) { 1317 ImplicitConversionSequence ICS; 1318 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1319 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1320 ICS.setStandard(); 1321 return ICS; 1322 } 1323 1324 if (!S.getLangOpts().CPlusPlus) { 1325 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1326 return ICS; 1327 } 1328 1329 // C++ [over.ics.user]p4: 1330 // A conversion of an expression of class type to the same class 1331 // type is given Exact Match rank, and a conversion of an 1332 // expression of class type to a base class of that type is 1333 // given Conversion rank, in spite of the fact that a copy/move 1334 // constructor (i.e., a user-defined conversion function) is 1335 // called for those cases. 1336 QualType FromType = From->getType(); 1337 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1338 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1339 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1340 ICS.setStandard(); 1341 ICS.Standard.setAsIdentityConversion(); 1342 ICS.Standard.setFromType(FromType); 1343 ICS.Standard.setAllToTypes(ToType); 1344 1345 // We don't actually check at this point whether there is a valid 1346 // copy/move constructor, since overloading just assumes that it 1347 // exists. When we actually perform initialization, we'll find the 1348 // appropriate constructor to copy the returned object, if needed. 1349 ICS.Standard.CopyConstructor = nullptr; 1350 1351 // Determine whether this is considered a derived-to-base conversion. 1352 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1353 ICS.Standard.Second = ICK_Derived_To_Base; 1354 1355 return ICS; 1356 } 1357 1358 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1359 AllowExplicit, InOverloadResolution, CStyle, 1360 AllowObjCWritebackConversion, 1361 AllowObjCConversionOnExplicit); 1362 } 1363 1364 ImplicitConversionSequence 1365 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1366 bool SuppressUserConversions, 1367 bool AllowExplicit, 1368 bool InOverloadResolution, 1369 bool CStyle, 1370 bool AllowObjCWritebackConversion) { 1371 return ::TryImplicitConversion(*this, From, ToType, 1372 SuppressUserConversions, AllowExplicit, 1373 InOverloadResolution, CStyle, 1374 AllowObjCWritebackConversion, 1375 /*AllowObjCConversionOnExplicit=*/false); 1376 } 1377 1378 /// PerformImplicitConversion - Perform an implicit conversion of the 1379 /// expression From to the type ToType. Returns the 1380 /// converted expression. Flavor is the kind of conversion we're 1381 /// performing, used in the error message. If @p AllowExplicit, 1382 /// explicit user-defined conversions are permitted. 1383 ExprResult 1384 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1385 AssignmentAction Action, bool AllowExplicit) { 1386 ImplicitConversionSequence ICS; 1387 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1388 } 1389 1390 ExprResult 1391 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1392 AssignmentAction Action, bool AllowExplicit, 1393 ImplicitConversionSequence& ICS) { 1394 if (checkPlaceholderForOverload(*this, From)) 1395 return ExprError(); 1396 1397 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1398 bool AllowObjCWritebackConversion 1399 = getLangOpts().ObjCAutoRefCount && 1400 (Action == AA_Passing || Action == AA_Sending); 1401 if (getLangOpts().ObjC1) 1402 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1403 ToType, From->getType(), From); 1404 ICS = ::TryImplicitConversion(*this, From, ToType, 1405 /*SuppressUserConversions=*/false, 1406 AllowExplicit, 1407 /*InOverloadResolution=*/false, 1408 /*CStyle=*/false, 1409 AllowObjCWritebackConversion, 1410 /*AllowObjCConversionOnExplicit=*/false); 1411 return PerformImplicitConversion(From, ToType, ICS, Action); 1412 } 1413 1414 /// \brief Determine whether the conversion from FromType to ToType is a valid 1415 /// conversion that strips "noexcept" or "noreturn" off the nested function 1416 /// type. 1417 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1418 QualType &ResultTy) { 1419 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1420 return false; 1421 1422 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1423 // or F(t noexcept) -> F(t) 1424 // where F adds one of the following at most once: 1425 // - a pointer 1426 // - a member pointer 1427 // - a block pointer 1428 // Changes here need matching changes in FindCompositePointerType. 1429 CanQualType CanTo = Context.getCanonicalType(ToType); 1430 CanQualType CanFrom = Context.getCanonicalType(FromType); 1431 Type::TypeClass TyClass = CanTo->getTypeClass(); 1432 if (TyClass != CanFrom->getTypeClass()) return false; 1433 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1434 if (TyClass == Type::Pointer) { 1435 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1436 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1437 } else if (TyClass == Type::BlockPointer) { 1438 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1439 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1440 } else if (TyClass == Type::MemberPointer) { 1441 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1442 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1443 // A function pointer conversion cannot change the class of the function. 1444 if (ToMPT->getClass() != FromMPT->getClass()) 1445 return false; 1446 CanTo = ToMPT->getPointeeType(); 1447 CanFrom = FromMPT->getPointeeType(); 1448 } else { 1449 return false; 1450 } 1451 1452 TyClass = CanTo->getTypeClass(); 1453 if (TyClass != CanFrom->getTypeClass()) return false; 1454 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1455 return false; 1456 } 1457 1458 const auto *FromFn = cast<FunctionType>(CanFrom); 1459 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1460 1461 const auto *ToFn = cast<FunctionType>(CanTo); 1462 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1463 1464 bool Changed = false; 1465 1466 // Drop 'noreturn' if not present in target type. 1467 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1468 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1469 Changed = true; 1470 } 1471 1472 // Drop 'noexcept' if not present in target type. 1473 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1474 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1475 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) { 1476 FromFn = cast<FunctionType>( 1477 Context.getFunctionType(FromFPT->getReturnType(), 1478 FromFPT->getParamTypes(), 1479 FromFPT->getExtProtoInfo().withExceptionSpec( 1480 FunctionProtoType::ExceptionSpecInfo())) 1481 .getTypePtr()); 1482 Changed = true; 1483 } 1484 } 1485 1486 if (!Changed) 1487 return false; 1488 1489 assert(QualType(FromFn, 0).isCanonical()); 1490 if (QualType(FromFn, 0) != CanTo) return false; 1491 1492 ResultTy = ToType; 1493 return true; 1494 } 1495 1496 /// \brief Determine whether the conversion from FromType to ToType is a valid 1497 /// vector conversion. 1498 /// 1499 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1500 /// conversion. 1501 static bool IsVectorConversion(Sema &S, QualType FromType, 1502 QualType ToType, ImplicitConversionKind &ICK) { 1503 // We need at least one of these types to be a vector type to have a vector 1504 // conversion. 1505 if (!ToType->isVectorType() && !FromType->isVectorType()) 1506 return false; 1507 1508 // Identical types require no conversions. 1509 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1510 return false; 1511 1512 // There are no conversions between extended vector types, only identity. 1513 if (ToType->isExtVectorType()) { 1514 // There are no conversions between extended vector types other than the 1515 // identity conversion. 1516 if (FromType->isExtVectorType()) 1517 return false; 1518 1519 // Vector splat from any arithmetic type to a vector. 1520 if (FromType->isArithmeticType()) { 1521 ICK = ICK_Vector_Splat; 1522 return true; 1523 } 1524 } 1525 1526 // We can perform the conversion between vector types in the following cases: 1527 // 1)vector types are equivalent AltiVec and GCC vector types 1528 // 2)lax vector conversions are permitted and the vector types are of the 1529 // same size 1530 if (ToType->isVectorType() && FromType->isVectorType()) { 1531 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1532 S.isLaxVectorConversion(FromType, ToType)) { 1533 ICK = ICK_Vector_Conversion; 1534 return true; 1535 } 1536 } 1537 1538 return false; 1539 } 1540 1541 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1542 bool InOverloadResolution, 1543 StandardConversionSequence &SCS, 1544 bool CStyle); 1545 1546 /// IsStandardConversion - Determines whether there is a standard 1547 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1548 /// expression From to the type ToType. Standard conversion sequences 1549 /// only consider non-class types; for conversions that involve class 1550 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1551 /// contain the standard conversion sequence required to perform this 1552 /// conversion and this routine will return true. Otherwise, this 1553 /// routine will return false and the value of SCS is unspecified. 1554 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1555 bool InOverloadResolution, 1556 StandardConversionSequence &SCS, 1557 bool CStyle, 1558 bool AllowObjCWritebackConversion) { 1559 QualType FromType = From->getType(); 1560 1561 // Standard conversions (C++ [conv]) 1562 SCS.setAsIdentityConversion(); 1563 SCS.IncompatibleObjC = false; 1564 SCS.setFromType(FromType); 1565 SCS.CopyConstructor = nullptr; 1566 1567 // There are no standard conversions for class types in C++, so 1568 // abort early. When overloading in C, however, we do permit them. 1569 if (S.getLangOpts().CPlusPlus && 1570 (FromType->isRecordType() || ToType->isRecordType())) 1571 return false; 1572 1573 // The first conversion can be an lvalue-to-rvalue conversion, 1574 // array-to-pointer conversion, or function-to-pointer conversion 1575 // (C++ 4p1). 1576 1577 if (FromType == S.Context.OverloadTy) { 1578 DeclAccessPair AccessPair; 1579 if (FunctionDecl *Fn 1580 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1581 AccessPair)) { 1582 // We were able to resolve the address of the overloaded function, 1583 // so we can convert to the type of that function. 1584 FromType = Fn->getType(); 1585 SCS.setFromType(FromType); 1586 1587 // we can sometimes resolve &foo<int> regardless of ToType, so check 1588 // if the type matches (identity) or we are converting to bool 1589 if (!S.Context.hasSameUnqualifiedType( 1590 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1591 QualType resultTy; 1592 // if the function type matches except for [[noreturn]], it's ok 1593 if (!S.IsFunctionConversion(FromType, 1594 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1595 // otherwise, only a boolean conversion is standard 1596 if (!ToType->isBooleanType()) 1597 return false; 1598 } 1599 1600 // Check if the "from" expression is taking the address of an overloaded 1601 // function and recompute the FromType accordingly. Take advantage of the 1602 // fact that non-static member functions *must* have such an address-of 1603 // expression. 1604 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1605 if (Method && !Method->isStatic()) { 1606 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1607 "Non-unary operator on non-static member address"); 1608 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1609 == UO_AddrOf && 1610 "Non-address-of operator on non-static member address"); 1611 const Type *ClassType 1612 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1613 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1614 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1615 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1616 UO_AddrOf && 1617 "Non-address-of operator for overloaded function expression"); 1618 FromType = S.Context.getPointerType(FromType); 1619 } 1620 1621 // Check that we've computed the proper type after overload resolution. 1622 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1623 // be calling it from within an NDEBUG block. 1624 assert(S.Context.hasSameType( 1625 FromType, 1626 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1627 } else { 1628 return false; 1629 } 1630 } 1631 // Lvalue-to-rvalue conversion (C++11 4.1): 1632 // A glvalue (3.10) of a non-function, non-array type T can 1633 // be converted to a prvalue. 1634 bool argIsLValue = From->isGLValue(); 1635 if (argIsLValue && 1636 !FromType->isFunctionType() && !FromType->isArrayType() && 1637 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1638 SCS.First = ICK_Lvalue_To_Rvalue; 1639 1640 // C11 6.3.2.1p2: 1641 // ... if the lvalue has atomic type, the value has the non-atomic version 1642 // of the type of the lvalue ... 1643 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1644 FromType = Atomic->getValueType(); 1645 1646 // If T is a non-class type, the type of the rvalue is the 1647 // cv-unqualified version of T. Otherwise, the type of the rvalue 1648 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1649 // just strip the qualifiers because they don't matter. 1650 FromType = FromType.getUnqualifiedType(); 1651 } else if (FromType->isArrayType()) { 1652 // Array-to-pointer conversion (C++ 4.2) 1653 SCS.First = ICK_Array_To_Pointer; 1654 1655 // An lvalue or rvalue of type "array of N T" or "array of unknown 1656 // bound of T" can be converted to an rvalue of type "pointer to 1657 // T" (C++ 4.2p1). 1658 FromType = S.Context.getArrayDecayedType(FromType); 1659 1660 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1661 // This conversion is deprecated in C++03 (D.4) 1662 SCS.DeprecatedStringLiteralToCharPtr = true; 1663 1664 // For the purpose of ranking in overload resolution 1665 // (13.3.3.1.1), this conversion is considered an 1666 // array-to-pointer conversion followed by a qualification 1667 // conversion (4.4). (C++ 4.2p2) 1668 SCS.Second = ICK_Identity; 1669 SCS.Third = ICK_Qualification; 1670 SCS.QualificationIncludesObjCLifetime = false; 1671 SCS.setAllToTypes(FromType); 1672 return true; 1673 } 1674 } else if (FromType->isFunctionType() && argIsLValue) { 1675 // Function-to-pointer conversion (C++ 4.3). 1676 SCS.First = ICK_Function_To_Pointer; 1677 1678 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1679 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1680 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1681 return false; 1682 1683 // An lvalue of function type T can be converted to an rvalue of 1684 // type "pointer to T." The result is a pointer to the 1685 // function. (C++ 4.3p1). 1686 FromType = S.Context.getPointerType(FromType); 1687 } else { 1688 // We don't require any conversions for the first step. 1689 SCS.First = ICK_Identity; 1690 } 1691 SCS.setToType(0, FromType); 1692 1693 // The second conversion can be an integral promotion, floating 1694 // point promotion, integral conversion, floating point conversion, 1695 // floating-integral conversion, pointer conversion, 1696 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1697 // For overloading in C, this can also be a "compatible-type" 1698 // conversion. 1699 bool IncompatibleObjC = false; 1700 ImplicitConversionKind SecondICK = ICK_Identity; 1701 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1702 // The unqualified versions of the types are the same: there's no 1703 // conversion to do. 1704 SCS.Second = ICK_Identity; 1705 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1706 // Integral promotion (C++ 4.5). 1707 SCS.Second = ICK_Integral_Promotion; 1708 FromType = ToType.getUnqualifiedType(); 1709 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1710 // Floating point promotion (C++ 4.6). 1711 SCS.Second = ICK_Floating_Promotion; 1712 FromType = ToType.getUnqualifiedType(); 1713 } else if (S.IsComplexPromotion(FromType, ToType)) { 1714 // Complex promotion (Clang extension) 1715 SCS.Second = ICK_Complex_Promotion; 1716 FromType = ToType.getUnqualifiedType(); 1717 } else if (ToType->isBooleanType() && 1718 (FromType->isArithmeticType() || 1719 FromType->isAnyPointerType() || 1720 FromType->isBlockPointerType() || 1721 FromType->isMemberPointerType() || 1722 FromType->isNullPtrType())) { 1723 // Boolean conversions (C++ 4.12). 1724 SCS.Second = ICK_Boolean_Conversion; 1725 FromType = S.Context.BoolTy; 1726 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1727 ToType->isIntegralType(S.Context)) { 1728 // Integral conversions (C++ 4.7). 1729 SCS.Second = ICK_Integral_Conversion; 1730 FromType = ToType.getUnqualifiedType(); 1731 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1732 // Complex conversions (C99 6.3.1.6) 1733 SCS.Second = ICK_Complex_Conversion; 1734 FromType = ToType.getUnqualifiedType(); 1735 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1736 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1737 // Complex-real conversions (C99 6.3.1.7) 1738 SCS.Second = ICK_Complex_Real; 1739 FromType = ToType.getUnqualifiedType(); 1740 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1741 // FIXME: disable conversions between long double and __float128 if 1742 // their representation is different until there is back end support 1743 // We of course allow this conversion if long double is really double. 1744 if (&S.Context.getFloatTypeSemantics(FromType) != 1745 &S.Context.getFloatTypeSemantics(ToType)) { 1746 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1747 ToType == S.Context.LongDoubleTy) || 1748 (FromType == S.Context.LongDoubleTy && 1749 ToType == S.Context.Float128Ty)); 1750 if (Float128AndLongDouble && 1751 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1752 &llvm::APFloat::IEEEdouble())) 1753 return false; 1754 } 1755 // Floating point conversions (C++ 4.8). 1756 SCS.Second = ICK_Floating_Conversion; 1757 FromType = ToType.getUnqualifiedType(); 1758 } else if ((FromType->isRealFloatingType() && 1759 ToType->isIntegralType(S.Context)) || 1760 (FromType->isIntegralOrUnscopedEnumerationType() && 1761 ToType->isRealFloatingType())) { 1762 // Floating-integral conversions (C++ 4.9). 1763 SCS.Second = ICK_Floating_Integral; 1764 FromType = ToType.getUnqualifiedType(); 1765 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1766 SCS.Second = ICK_Block_Pointer_Conversion; 1767 } else if (AllowObjCWritebackConversion && 1768 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1769 SCS.Second = ICK_Writeback_Conversion; 1770 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1771 FromType, IncompatibleObjC)) { 1772 // Pointer conversions (C++ 4.10). 1773 SCS.Second = ICK_Pointer_Conversion; 1774 SCS.IncompatibleObjC = IncompatibleObjC; 1775 FromType = FromType.getUnqualifiedType(); 1776 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1777 InOverloadResolution, FromType)) { 1778 // Pointer to member conversions (4.11). 1779 SCS.Second = ICK_Pointer_Member; 1780 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1781 SCS.Second = SecondICK; 1782 FromType = ToType.getUnqualifiedType(); 1783 } else if (!S.getLangOpts().CPlusPlus && 1784 S.Context.typesAreCompatible(ToType, FromType)) { 1785 // Compatible conversions (Clang extension for C function overloading) 1786 SCS.Second = ICK_Compatible_Conversion; 1787 FromType = ToType.getUnqualifiedType(); 1788 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1789 InOverloadResolution, 1790 SCS, CStyle)) { 1791 SCS.Second = ICK_TransparentUnionConversion; 1792 FromType = ToType; 1793 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1794 CStyle)) { 1795 // tryAtomicConversion has updated the standard conversion sequence 1796 // appropriately. 1797 return true; 1798 } else if (ToType->isEventT() && 1799 From->isIntegerConstantExpr(S.getASTContext()) && 1800 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1801 SCS.Second = ICK_Zero_Event_Conversion; 1802 FromType = ToType; 1803 } else { 1804 // No second conversion required. 1805 SCS.Second = ICK_Identity; 1806 } 1807 SCS.setToType(1, FromType); 1808 1809 // The third conversion can be a function pointer conversion or a 1810 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1811 bool ObjCLifetimeConversion; 1812 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1813 // Function pointer conversions (removing 'noexcept') including removal of 1814 // 'noreturn' (Clang extension). 1815 SCS.Third = ICK_Function_Conversion; 1816 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1817 ObjCLifetimeConversion)) { 1818 SCS.Third = ICK_Qualification; 1819 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1820 FromType = ToType; 1821 } else { 1822 // No conversion required 1823 SCS.Third = ICK_Identity; 1824 } 1825 1826 // C++ [over.best.ics]p6: 1827 // [...] Any difference in top-level cv-qualification is 1828 // subsumed by the initialization itself and does not constitute 1829 // a conversion. [...] 1830 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1831 QualType CanonTo = S.Context.getCanonicalType(ToType); 1832 if (CanonFrom.getLocalUnqualifiedType() 1833 == CanonTo.getLocalUnqualifiedType() && 1834 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1835 FromType = ToType; 1836 CanonFrom = CanonTo; 1837 } 1838 1839 SCS.setToType(2, FromType); 1840 1841 if (CanonFrom == CanonTo) 1842 return true; 1843 1844 // If we have not converted the argument type to the parameter type, 1845 // this is a bad conversion sequence, unless we're resolving an overload in C. 1846 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1847 return false; 1848 1849 ExprResult ER = ExprResult{From}; 1850 Sema::AssignConvertType Conv = 1851 S.CheckSingleAssignmentConstraints(ToType, ER, 1852 /*Diagnose=*/false, 1853 /*DiagnoseCFAudited=*/false, 1854 /*ConvertRHS=*/false); 1855 ImplicitConversionKind SecondConv; 1856 switch (Conv) { 1857 case Sema::Compatible: 1858 SecondConv = ICK_C_Only_Conversion; 1859 break; 1860 // For our purposes, discarding qualifiers is just as bad as using an 1861 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1862 // qualifiers, as well. 1863 case Sema::CompatiblePointerDiscardsQualifiers: 1864 case Sema::IncompatiblePointer: 1865 case Sema::IncompatiblePointerSign: 1866 SecondConv = ICK_Incompatible_Pointer_Conversion; 1867 break; 1868 default: 1869 return false; 1870 } 1871 1872 // First can only be an lvalue conversion, so we pretend that this was the 1873 // second conversion. First should already be valid from earlier in the 1874 // function. 1875 SCS.Second = SecondConv; 1876 SCS.setToType(1, ToType); 1877 1878 // Third is Identity, because Second should rank us worse than any other 1879 // conversion. This could also be ICK_Qualification, but it's simpler to just 1880 // lump everything in with the second conversion, and we don't gain anything 1881 // from making this ICK_Qualification. 1882 SCS.Third = ICK_Identity; 1883 SCS.setToType(2, ToType); 1884 return true; 1885 } 1886 1887 static bool 1888 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1889 QualType &ToType, 1890 bool InOverloadResolution, 1891 StandardConversionSequence &SCS, 1892 bool CStyle) { 1893 1894 const RecordType *UT = ToType->getAsUnionType(); 1895 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1896 return false; 1897 // The field to initialize within the transparent union. 1898 RecordDecl *UD = UT->getDecl(); 1899 // It's compatible if the expression matches any of the fields. 1900 for (const auto *it : UD->fields()) { 1901 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1902 CStyle, /*ObjCWritebackConversion=*/false)) { 1903 ToType = it->getType(); 1904 return true; 1905 } 1906 } 1907 return false; 1908 } 1909 1910 /// IsIntegralPromotion - Determines whether the conversion from the 1911 /// expression From (whose potentially-adjusted type is FromType) to 1912 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1913 /// sets PromotedType to the promoted type. 1914 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1915 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1916 // All integers are built-in. 1917 if (!To) { 1918 return false; 1919 } 1920 1921 // An rvalue of type char, signed char, unsigned char, short int, or 1922 // unsigned short int can be converted to an rvalue of type int if 1923 // int can represent all the values of the source type; otherwise, 1924 // the source rvalue can be converted to an rvalue of type unsigned 1925 // int (C++ 4.5p1). 1926 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1927 !FromType->isEnumeralType()) { 1928 if (// We can promote any signed, promotable integer type to an int 1929 (FromType->isSignedIntegerType() || 1930 // We can promote any unsigned integer type whose size is 1931 // less than int to an int. 1932 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1933 return To->getKind() == BuiltinType::Int; 1934 } 1935 1936 return To->getKind() == BuiltinType::UInt; 1937 } 1938 1939 // C++11 [conv.prom]p3: 1940 // A prvalue of an unscoped enumeration type whose underlying type is not 1941 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1942 // following types that can represent all the values of the enumeration 1943 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1944 // unsigned int, long int, unsigned long int, long long int, or unsigned 1945 // long long int. If none of the types in that list can represent all the 1946 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1947 // type can be converted to an rvalue a prvalue of the extended integer type 1948 // with lowest integer conversion rank (4.13) greater than the rank of long 1949 // long in which all the values of the enumeration can be represented. If 1950 // there are two such extended types, the signed one is chosen. 1951 // C++11 [conv.prom]p4: 1952 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1953 // can be converted to a prvalue of its underlying type. Moreover, if 1954 // integral promotion can be applied to its underlying type, a prvalue of an 1955 // unscoped enumeration type whose underlying type is fixed can also be 1956 // converted to a prvalue of the promoted underlying type. 1957 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1958 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1959 // provided for a scoped enumeration. 1960 if (FromEnumType->getDecl()->isScoped()) 1961 return false; 1962 1963 // We can perform an integral promotion to the underlying type of the enum, 1964 // even if that's not the promoted type. Note that the check for promoting 1965 // the underlying type is based on the type alone, and does not consider 1966 // the bitfield-ness of the actual source expression. 1967 if (FromEnumType->getDecl()->isFixed()) { 1968 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1969 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1970 IsIntegralPromotion(nullptr, Underlying, ToType); 1971 } 1972 1973 // We have already pre-calculated the promotion type, so this is trivial. 1974 if (ToType->isIntegerType() && 1975 isCompleteType(From->getLocStart(), FromType)) 1976 return Context.hasSameUnqualifiedType( 1977 ToType, FromEnumType->getDecl()->getPromotionType()); 1978 } 1979 1980 // C++0x [conv.prom]p2: 1981 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1982 // to an rvalue a prvalue of the first of the following types that can 1983 // represent all the values of its underlying type: int, unsigned int, 1984 // long int, unsigned long int, long long int, or unsigned long long int. 1985 // If none of the types in that list can represent all the values of its 1986 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1987 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1988 // type. 1989 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1990 ToType->isIntegerType()) { 1991 // Determine whether the type we're converting from is signed or 1992 // unsigned. 1993 bool FromIsSigned = FromType->isSignedIntegerType(); 1994 uint64_t FromSize = Context.getTypeSize(FromType); 1995 1996 // The types we'll try to promote to, in the appropriate 1997 // order. Try each of these types. 1998 QualType PromoteTypes[6] = { 1999 Context.IntTy, Context.UnsignedIntTy, 2000 Context.LongTy, Context.UnsignedLongTy , 2001 Context.LongLongTy, Context.UnsignedLongLongTy 2002 }; 2003 for (int Idx = 0; Idx < 6; ++Idx) { 2004 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2005 if (FromSize < ToSize || 2006 (FromSize == ToSize && 2007 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2008 // We found the type that we can promote to. If this is the 2009 // type we wanted, we have a promotion. Otherwise, no 2010 // promotion. 2011 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2012 } 2013 } 2014 } 2015 2016 // An rvalue for an integral bit-field (9.6) can be converted to an 2017 // rvalue of type int if int can represent all the values of the 2018 // bit-field; otherwise, it can be converted to unsigned int if 2019 // unsigned int can represent all the values of the bit-field. If 2020 // the bit-field is larger yet, no integral promotion applies to 2021 // it. If the bit-field has an enumerated type, it is treated as any 2022 // other value of that type for promotion purposes (C++ 4.5p3). 2023 // FIXME: We should delay checking of bit-fields until we actually perform the 2024 // conversion. 2025 if (From) { 2026 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2027 llvm::APSInt BitWidth; 2028 if (FromType->isIntegralType(Context) && 2029 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2030 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2031 ToSize = Context.getTypeSize(ToType); 2032 2033 // Are we promoting to an int from a bitfield that fits in an int? 2034 if (BitWidth < ToSize || 2035 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2036 return To->getKind() == BuiltinType::Int; 2037 } 2038 2039 // Are we promoting to an unsigned int from an unsigned bitfield 2040 // that fits into an unsigned int? 2041 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2042 return To->getKind() == BuiltinType::UInt; 2043 } 2044 2045 return false; 2046 } 2047 } 2048 } 2049 2050 // An rvalue of type bool can be converted to an rvalue of type int, 2051 // with false becoming zero and true becoming one (C++ 4.5p4). 2052 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2053 return true; 2054 } 2055 2056 return false; 2057 } 2058 2059 /// IsFloatingPointPromotion - Determines whether the conversion from 2060 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2061 /// returns true and sets PromotedType to the promoted type. 2062 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2063 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2064 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2065 /// An rvalue of type float can be converted to an rvalue of type 2066 /// double. (C++ 4.6p1). 2067 if (FromBuiltin->getKind() == BuiltinType::Float && 2068 ToBuiltin->getKind() == BuiltinType::Double) 2069 return true; 2070 2071 // C99 6.3.1.5p1: 2072 // When a float is promoted to double or long double, or a 2073 // double is promoted to long double [...]. 2074 if (!getLangOpts().CPlusPlus && 2075 (FromBuiltin->getKind() == BuiltinType::Float || 2076 FromBuiltin->getKind() == BuiltinType::Double) && 2077 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2078 ToBuiltin->getKind() == BuiltinType::Float128)) 2079 return true; 2080 2081 // Half can be promoted to float. 2082 if (!getLangOpts().NativeHalfType && 2083 FromBuiltin->getKind() == BuiltinType::Half && 2084 ToBuiltin->getKind() == BuiltinType::Float) 2085 return true; 2086 } 2087 2088 return false; 2089 } 2090 2091 /// \brief Determine if a conversion is a complex promotion. 2092 /// 2093 /// A complex promotion is defined as a complex -> complex conversion 2094 /// where the conversion between the underlying real types is a 2095 /// floating-point or integral promotion. 2096 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2097 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2098 if (!FromComplex) 2099 return false; 2100 2101 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2102 if (!ToComplex) 2103 return false; 2104 2105 return IsFloatingPointPromotion(FromComplex->getElementType(), 2106 ToComplex->getElementType()) || 2107 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2108 ToComplex->getElementType()); 2109 } 2110 2111 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2112 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2113 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2114 /// if non-empty, will be a pointer to ToType that may or may not have 2115 /// the right set of qualifiers on its pointee. 2116 /// 2117 static QualType 2118 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2119 QualType ToPointee, QualType ToType, 2120 ASTContext &Context, 2121 bool StripObjCLifetime = false) { 2122 assert((FromPtr->getTypeClass() == Type::Pointer || 2123 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2124 "Invalid similarly-qualified pointer type"); 2125 2126 /// Conversions to 'id' subsume cv-qualifier conversions. 2127 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2128 return ToType.getUnqualifiedType(); 2129 2130 QualType CanonFromPointee 2131 = Context.getCanonicalType(FromPtr->getPointeeType()); 2132 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2133 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2134 2135 if (StripObjCLifetime) 2136 Quals.removeObjCLifetime(); 2137 2138 // Exact qualifier match -> return the pointer type we're converting to. 2139 if (CanonToPointee.getLocalQualifiers() == Quals) { 2140 // ToType is exactly what we need. Return it. 2141 if (!ToType.isNull()) 2142 return ToType.getUnqualifiedType(); 2143 2144 // Build a pointer to ToPointee. It has the right qualifiers 2145 // already. 2146 if (isa<ObjCObjectPointerType>(ToType)) 2147 return Context.getObjCObjectPointerType(ToPointee); 2148 return Context.getPointerType(ToPointee); 2149 } 2150 2151 // Just build a canonical type that has the right qualifiers. 2152 QualType QualifiedCanonToPointee 2153 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2154 2155 if (isa<ObjCObjectPointerType>(ToType)) 2156 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2157 return Context.getPointerType(QualifiedCanonToPointee); 2158 } 2159 2160 static bool isNullPointerConstantForConversion(Expr *Expr, 2161 bool InOverloadResolution, 2162 ASTContext &Context) { 2163 // Handle value-dependent integral null pointer constants correctly. 2164 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2165 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2166 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2167 return !InOverloadResolution; 2168 2169 return Expr->isNullPointerConstant(Context, 2170 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2171 : Expr::NPC_ValueDependentIsNull); 2172 } 2173 2174 /// IsPointerConversion - Determines whether the conversion of the 2175 /// expression From, which has the (possibly adjusted) type FromType, 2176 /// can be converted to the type ToType via a pointer conversion (C++ 2177 /// 4.10). If so, returns true and places the converted type (that 2178 /// might differ from ToType in its cv-qualifiers at some level) into 2179 /// ConvertedType. 2180 /// 2181 /// This routine also supports conversions to and from block pointers 2182 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2183 /// pointers to interfaces. FIXME: Once we've determined the 2184 /// appropriate overloading rules for Objective-C, we may want to 2185 /// split the Objective-C checks into a different routine; however, 2186 /// GCC seems to consider all of these conversions to be pointer 2187 /// conversions, so for now they live here. IncompatibleObjC will be 2188 /// set if the conversion is an allowed Objective-C conversion that 2189 /// should result in a warning. 2190 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2191 bool InOverloadResolution, 2192 QualType& ConvertedType, 2193 bool &IncompatibleObjC) { 2194 IncompatibleObjC = false; 2195 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2196 IncompatibleObjC)) 2197 return true; 2198 2199 // Conversion from a null pointer constant to any Objective-C pointer type. 2200 if (ToType->isObjCObjectPointerType() && 2201 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2202 ConvertedType = ToType; 2203 return true; 2204 } 2205 2206 // Blocks: Block pointers can be converted to void*. 2207 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2208 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2209 ConvertedType = ToType; 2210 return true; 2211 } 2212 // Blocks: A null pointer constant can be converted to a block 2213 // pointer type. 2214 if (ToType->isBlockPointerType() && 2215 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2216 ConvertedType = ToType; 2217 return true; 2218 } 2219 2220 // If the left-hand-side is nullptr_t, the right side can be a null 2221 // pointer constant. 2222 if (ToType->isNullPtrType() && 2223 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2224 ConvertedType = ToType; 2225 return true; 2226 } 2227 2228 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2229 if (!ToTypePtr) 2230 return false; 2231 2232 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2233 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2234 ConvertedType = ToType; 2235 return true; 2236 } 2237 2238 // Beyond this point, both types need to be pointers 2239 // , including objective-c pointers. 2240 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2241 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2242 !getLangOpts().ObjCAutoRefCount) { 2243 ConvertedType = BuildSimilarlyQualifiedPointerType( 2244 FromType->getAs<ObjCObjectPointerType>(), 2245 ToPointeeType, 2246 ToType, Context); 2247 return true; 2248 } 2249 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2250 if (!FromTypePtr) 2251 return false; 2252 2253 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2254 2255 // If the unqualified pointee types are the same, this can't be a 2256 // pointer conversion, so don't do all of the work below. 2257 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2258 return false; 2259 2260 // An rvalue of type "pointer to cv T," where T is an object type, 2261 // can be converted to an rvalue of type "pointer to cv void" (C++ 2262 // 4.10p2). 2263 if (FromPointeeType->isIncompleteOrObjectType() && 2264 ToPointeeType->isVoidType()) { 2265 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2266 ToPointeeType, 2267 ToType, Context, 2268 /*StripObjCLifetime=*/true); 2269 return true; 2270 } 2271 2272 // MSVC allows implicit function to void* type conversion. 2273 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2274 ToPointeeType->isVoidType()) { 2275 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2276 ToPointeeType, 2277 ToType, Context); 2278 return true; 2279 } 2280 2281 // When we're overloading in C, we allow a special kind of pointer 2282 // conversion for compatible-but-not-identical pointee types. 2283 if (!getLangOpts().CPlusPlus && 2284 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2285 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2286 ToPointeeType, 2287 ToType, Context); 2288 return true; 2289 } 2290 2291 // C++ [conv.ptr]p3: 2292 // 2293 // An rvalue of type "pointer to cv D," where D is a class type, 2294 // can be converted to an rvalue of type "pointer to cv B," where 2295 // B is a base class (clause 10) of D. If B is an inaccessible 2296 // (clause 11) or ambiguous (10.2) base class of D, a program that 2297 // necessitates this conversion is ill-formed. The result of the 2298 // conversion is a pointer to the base class sub-object of the 2299 // derived class object. The null pointer value is converted to 2300 // the null pointer value of the destination type. 2301 // 2302 // Note that we do not check for ambiguity or inaccessibility 2303 // here. That is handled by CheckPointerConversion. 2304 if (getLangOpts().CPlusPlus && 2305 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2306 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2307 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2308 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2309 ToPointeeType, 2310 ToType, Context); 2311 return true; 2312 } 2313 2314 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2315 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2316 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2317 ToPointeeType, 2318 ToType, Context); 2319 return true; 2320 } 2321 2322 return false; 2323 } 2324 2325 /// \brief Adopt the given qualifiers for the given type. 2326 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2327 Qualifiers TQs = T.getQualifiers(); 2328 2329 // Check whether qualifiers already match. 2330 if (TQs == Qs) 2331 return T; 2332 2333 if (Qs.compatiblyIncludes(TQs)) 2334 return Context.getQualifiedType(T, Qs); 2335 2336 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2337 } 2338 2339 /// isObjCPointerConversion - Determines whether this is an 2340 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2341 /// with the same arguments and return values. 2342 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2343 QualType& ConvertedType, 2344 bool &IncompatibleObjC) { 2345 if (!getLangOpts().ObjC1) 2346 return false; 2347 2348 // The set of qualifiers on the type we're converting from. 2349 Qualifiers FromQualifiers = FromType.getQualifiers(); 2350 2351 // First, we handle all conversions on ObjC object pointer types. 2352 const ObjCObjectPointerType* ToObjCPtr = 2353 ToType->getAs<ObjCObjectPointerType>(); 2354 const ObjCObjectPointerType *FromObjCPtr = 2355 FromType->getAs<ObjCObjectPointerType>(); 2356 2357 if (ToObjCPtr && FromObjCPtr) { 2358 // If the pointee types are the same (ignoring qualifications), 2359 // then this is not a pointer conversion. 2360 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2361 FromObjCPtr->getPointeeType())) 2362 return false; 2363 2364 // Conversion between Objective-C pointers. 2365 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2366 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2367 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2368 if (getLangOpts().CPlusPlus && LHS && RHS && 2369 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2370 FromObjCPtr->getPointeeType())) 2371 return false; 2372 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2373 ToObjCPtr->getPointeeType(), 2374 ToType, Context); 2375 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2376 return true; 2377 } 2378 2379 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2380 // Okay: this is some kind of implicit downcast of Objective-C 2381 // interfaces, which is permitted. However, we're going to 2382 // complain about it. 2383 IncompatibleObjC = true; 2384 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2385 ToObjCPtr->getPointeeType(), 2386 ToType, Context); 2387 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2388 return true; 2389 } 2390 } 2391 // Beyond this point, both types need to be C pointers or block pointers. 2392 QualType ToPointeeType; 2393 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2394 ToPointeeType = ToCPtr->getPointeeType(); 2395 else if (const BlockPointerType *ToBlockPtr = 2396 ToType->getAs<BlockPointerType>()) { 2397 // Objective C++: We're able to convert from a pointer to any object 2398 // to a block pointer type. 2399 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2400 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2401 return true; 2402 } 2403 ToPointeeType = ToBlockPtr->getPointeeType(); 2404 } 2405 else if (FromType->getAs<BlockPointerType>() && 2406 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2407 // Objective C++: We're able to convert from a block pointer type to a 2408 // pointer to any object. 2409 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2410 return true; 2411 } 2412 else 2413 return false; 2414 2415 QualType FromPointeeType; 2416 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2417 FromPointeeType = FromCPtr->getPointeeType(); 2418 else if (const BlockPointerType *FromBlockPtr = 2419 FromType->getAs<BlockPointerType>()) 2420 FromPointeeType = FromBlockPtr->getPointeeType(); 2421 else 2422 return false; 2423 2424 // If we have pointers to pointers, recursively check whether this 2425 // is an Objective-C conversion. 2426 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2427 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2428 IncompatibleObjC)) { 2429 // We always complain about this conversion. 2430 IncompatibleObjC = true; 2431 ConvertedType = Context.getPointerType(ConvertedType); 2432 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2433 return true; 2434 } 2435 // Allow conversion of pointee being objective-c pointer to another one; 2436 // as in I* to id. 2437 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2438 ToPointeeType->getAs<ObjCObjectPointerType>() && 2439 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2440 IncompatibleObjC)) { 2441 2442 ConvertedType = Context.getPointerType(ConvertedType); 2443 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2444 return true; 2445 } 2446 2447 // If we have pointers to functions or blocks, check whether the only 2448 // differences in the argument and result types are in Objective-C 2449 // pointer conversions. If so, we permit the conversion (but 2450 // complain about it). 2451 const FunctionProtoType *FromFunctionType 2452 = FromPointeeType->getAs<FunctionProtoType>(); 2453 const FunctionProtoType *ToFunctionType 2454 = ToPointeeType->getAs<FunctionProtoType>(); 2455 if (FromFunctionType && ToFunctionType) { 2456 // If the function types are exactly the same, this isn't an 2457 // Objective-C pointer conversion. 2458 if (Context.getCanonicalType(FromPointeeType) 2459 == Context.getCanonicalType(ToPointeeType)) 2460 return false; 2461 2462 // Perform the quick checks that will tell us whether these 2463 // function types are obviously different. 2464 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2465 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2466 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2467 return false; 2468 2469 bool HasObjCConversion = false; 2470 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2471 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2472 // Okay, the types match exactly. Nothing to do. 2473 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2474 ToFunctionType->getReturnType(), 2475 ConvertedType, IncompatibleObjC)) { 2476 // Okay, we have an Objective-C pointer conversion. 2477 HasObjCConversion = true; 2478 } else { 2479 // Function types are too different. Abort. 2480 return false; 2481 } 2482 2483 // Check argument types. 2484 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2485 ArgIdx != NumArgs; ++ArgIdx) { 2486 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2487 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2488 if (Context.getCanonicalType(FromArgType) 2489 == Context.getCanonicalType(ToArgType)) { 2490 // Okay, the types match exactly. Nothing to do. 2491 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2492 ConvertedType, IncompatibleObjC)) { 2493 // Okay, we have an Objective-C pointer conversion. 2494 HasObjCConversion = true; 2495 } else { 2496 // Argument types are too different. Abort. 2497 return false; 2498 } 2499 } 2500 2501 if (HasObjCConversion) { 2502 // We had an Objective-C conversion. Allow this pointer 2503 // conversion, but complain about it. 2504 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2505 IncompatibleObjC = true; 2506 return true; 2507 } 2508 } 2509 2510 return false; 2511 } 2512 2513 /// \brief Determine whether this is an Objective-C writeback conversion, 2514 /// used for parameter passing when performing automatic reference counting. 2515 /// 2516 /// \param FromType The type we're converting form. 2517 /// 2518 /// \param ToType The type we're converting to. 2519 /// 2520 /// \param ConvertedType The type that will be produced after applying 2521 /// this conversion. 2522 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2523 QualType &ConvertedType) { 2524 if (!getLangOpts().ObjCAutoRefCount || 2525 Context.hasSameUnqualifiedType(FromType, ToType)) 2526 return false; 2527 2528 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2529 QualType ToPointee; 2530 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2531 ToPointee = ToPointer->getPointeeType(); 2532 else 2533 return false; 2534 2535 Qualifiers ToQuals = ToPointee.getQualifiers(); 2536 if (!ToPointee->isObjCLifetimeType() || 2537 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2538 !ToQuals.withoutObjCLifetime().empty()) 2539 return false; 2540 2541 // Argument must be a pointer to __strong to __weak. 2542 QualType FromPointee; 2543 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2544 FromPointee = FromPointer->getPointeeType(); 2545 else 2546 return false; 2547 2548 Qualifiers FromQuals = FromPointee.getQualifiers(); 2549 if (!FromPointee->isObjCLifetimeType() || 2550 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2551 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2552 return false; 2553 2554 // Make sure that we have compatible qualifiers. 2555 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2556 if (!ToQuals.compatiblyIncludes(FromQuals)) 2557 return false; 2558 2559 // Remove qualifiers from the pointee type we're converting from; they 2560 // aren't used in the compatibility check belong, and we'll be adding back 2561 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2562 FromPointee = FromPointee.getUnqualifiedType(); 2563 2564 // The unqualified form of the pointee types must be compatible. 2565 ToPointee = ToPointee.getUnqualifiedType(); 2566 bool IncompatibleObjC; 2567 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2568 FromPointee = ToPointee; 2569 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2570 IncompatibleObjC)) 2571 return false; 2572 2573 /// \brief Construct the type we're converting to, which is a pointer to 2574 /// __autoreleasing pointee. 2575 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2576 ConvertedType = Context.getPointerType(FromPointee); 2577 return true; 2578 } 2579 2580 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2581 QualType& ConvertedType) { 2582 QualType ToPointeeType; 2583 if (const BlockPointerType *ToBlockPtr = 2584 ToType->getAs<BlockPointerType>()) 2585 ToPointeeType = ToBlockPtr->getPointeeType(); 2586 else 2587 return false; 2588 2589 QualType FromPointeeType; 2590 if (const BlockPointerType *FromBlockPtr = 2591 FromType->getAs<BlockPointerType>()) 2592 FromPointeeType = FromBlockPtr->getPointeeType(); 2593 else 2594 return false; 2595 // We have pointer to blocks, check whether the only 2596 // differences in the argument and result types are in Objective-C 2597 // pointer conversions. If so, we permit the conversion. 2598 2599 const FunctionProtoType *FromFunctionType 2600 = FromPointeeType->getAs<FunctionProtoType>(); 2601 const FunctionProtoType *ToFunctionType 2602 = ToPointeeType->getAs<FunctionProtoType>(); 2603 2604 if (!FromFunctionType || !ToFunctionType) 2605 return false; 2606 2607 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2608 return true; 2609 2610 // Perform the quick checks that will tell us whether these 2611 // function types are obviously different. 2612 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2613 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2614 return false; 2615 2616 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2617 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2618 if (FromEInfo != ToEInfo) 2619 return false; 2620 2621 bool IncompatibleObjC = false; 2622 if (Context.hasSameType(FromFunctionType->getReturnType(), 2623 ToFunctionType->getReturnType())) { 2624 // Okay, the types match exactly. Nothing to do. 2625 } else { 2626 QualType RHS = FromFunctionType->getReturnType(); 2627 QualType LHS = ToFunctionType->getReturnType(); 2628 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2629 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2630 LHS = LHS.getUnqualifiedType(); 2631 2632 if (Context.hasSameType(RHS,LHS)) { 2633 // OK exact match. 2634 } else if (isObjCPointerConversion(RHS, LHS, 2635 ConvertedType, IncompatibleObjC)) { 2636 if (IncompatibleObjC) 2637 return false; 2638 // Okay, we have an Objective-C pointer conversion. 2639 } 2640 else 2641 return false; 2642 } 2643 2644 // Check argument types. 2645 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2646 ArgIdx != NumArgs; ++ArgIdx) { 2647 IncompatibleObjC = false; 2648 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2649 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2650 if (Context.hasSameType(FromArgType, ToArgType)) { 2651 // Okay, the types match exactly. Nothing to do. 2652 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2653 ConvertedType, IncompatibleObjC)) { 2654 if (IncompatibleObjC) 2655 return false; 2656 // Okay, we have an Objective-C pointer conversion. 2657 } else 2658 // Argument types are too different. Abort. 2659 return false; 2660 } 2661 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType, 2662 ToFunctionType)) 2663 return false; 2664 2665 ConvertedType = ToType; 2666 return true; 2667 } 2668 2669 enum { 2670 ft_default, 2671 ft_different_class, 2672 ft_parameter_arity, 2673 ft_parameter_mismatch, 2674 ft_return_type, 2675 ft_qualifer_mismatch, 2676 ft_noexcept 2677 }; 2678 2679 /// Attempts to get the FunctionProtoType from a Type. Handles 2680 /// MemberFunctionPointers properly. 2681 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2682 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2683 return FPT; 2684 2685 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2686 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2687 2688 return nullptr; 2689 } 2690 2691 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2692 /// function types. Catches different number of parameter, mismatch in 2693 /// parameter types, and different return types. 2694 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2695 QualType FromType, QualType ToType) { 2696 // If either type is not valid, include no extra info. 2697 if (FromType.isNull() || ToType.isNull()) { 2698 PDiag << ft_default; 2699 return; 2700 } 2701 2702 // Get the function type from the pointers. 2703 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2704 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2705 *ToMember = ToType->getAs<MemberPointerType>(); 2706 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2707 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2708 << QualType(FromMember->getClass(), 0); 2709 return; 2710 } 2711 FromType = FromMember->getPointeeType(); 2712 ToType = ToMember->getPointeeType(); 2713 } 2714 2715 if (FromType->isPointerType()) 2716 FromType = FromType->getPointeeType(); 2717 if (ToType->isPointerType()) 2718 ToType = ToType->getPointeeType(); 2719 2720 // Remove references. 2721 FromType = FromType.getNonReferenceType(); 2722 ToType = ToType.getNonReferenceType(); 2723 2724 // Don't print extra info for non-specialized template functions. 2725 if (FromType->isInstantiationDependentType() && 2726 !FromType->getAs<TemplateSpecializationType>()) { 2727 PDiag << ft_default; 2728 return; 2729 } 2730 2731 // No extra info for same types. 2732 if (Context.hasSameType(FromType, ToType)) { 2733 PDiag << ft_default; 2734 return; 2735 } 2736 2737 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2738 *ToFunction = tryGetFunctionProtoType(ToType); 2739 2740 // Both types need to be function types. 2741 if (!FromFunction || !ToFunction) { 2742 PDiag << ft_default; 2743 return; 2744 } 2745 2746 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2747 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2748 << FromFunction->getNumParams(); 2749 return; 2750 } 2751 2752 // Handle different parameter types. 2753 unsigned ArgPos; 2754 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2755 PDiag << ft_parameter_mismatch << ArgPos + 1 2756 << ToFunction->getParamType(ArgPos) 2757 << FromFunction->getParamType(ArgPos); 2758 return; 2759 } 2760 2761 // Handle different return type. 2762 if (!Context.hasSameType(FromFunction->getReturnType(), 2763 ToFunction->getReturnType())) { 2764 PDiag << ft_return_type << ToFunction->getReturnType() 2765 << FromFunction->getReturnType(); 2766 return; 2767 } 2768 2769 unsigned FromQuals = FromFunction->getTypeQuals(), 2770 ToQuals = ToFunction->getTypeQuals(); 2771 if (FromQuals != ToQuals) { 2772 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2773 return; 2774 } 2775 2776 // Handle exception specification differences on canonical type (in C++17 2777 // onwards). 2778 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2779 ->isNothrow(Context) != 2780 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2781 ->isNothrow(Context)) { 2782 PDiag << ft_noexcept; 2783 return; 2784 } 2785 2786 // Unable to find a difference, so add no extra info. 2787 PDiag << ft_default; 2788 } 2789 2790 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2791 /// for equality of their argument types. Caller has already checked that 2792 /// they have same number of arguments. If the parameters are different, 2793 /// ArgPos will have the parameter index of the first different parameter. 2794 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2795 const FunctionProtoType *NewType, 2796 unsigned *ArgPos) { 2797 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2798 N = NewType->param_type_begin(), 2799 E = OldType->param_type_end(); 2800 O && (O != E); ++O, ++N) { 2801 if (!Context.hasSameType(O->getUnqualifiedType(), 2802 N->getUnqualifiedType())) { 2803 if (ArgPos) 2804 *ArgPos = O - OldType->param_type_begin(); 2805 return false; 2806 } 2807 } 2808 return true; 2809 } 2810 2811 /// CheckPointerConversion - Check the pointer conversion from the 2812 /// expression From to the type ToType. This routine checks for 2813 /// ambiguous or inaccessible derived-to-base pointer 2814 /// conversions for which IsPointerConversion has already returned 2815 /// true. It returns true and produces a diagnostic if there was an 2816 /// error, or returns false otherwise. 2817 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2818 CastKind &Kind, 2819 CXXCastPath& BasePath, 2820 bool IgnoreBaseAccess, 2821 bool Diagnose) { 2822 QualType FromType = From->getType(); 2823 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2824 2825 Kind = CK_BitCast; 2826 2827 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2828 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2829 Expr::NPCK_ZeroExpression) { 2830 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2831 DiagRuntimeBehavior(From->getExprLoc(), From, 2832 PDiag(diag::warn_impcast_bool_to_null_pointer) 2833 << ToType << From->getSourceRange()); 2834 else if (!isUnevaluatedContext()) 2835 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2836 << ToType << From->getSourceRange(); 2837 } 2838 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2839 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2840 QualType FromPointeeType = FromPtrType->getPointeeType(), 2841 ToPointeeType = ToPtrType->getPointeeType(); 2842 2843 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2844 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2845 // We must have a derived-to-base conversion. Check an 2846 // ambiguous or inaccessible conversion. 2847 unsigned InaccessibleID = 0; 2848 unsigned AmbigiousID = 0; 2849 if (Diagnose) { 2850 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2851 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2852 } 2853 if (CheckDerivedToBaseConversion( 2854 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2855 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2856 &BasePath, IgnoreBaseAccess)) 2857 return true; 2858 2859 // The conversion was successful. 2860 Kind = CK_DerivedToBase; 2861 } 2862 2863 if (Diagnose && !IsCStyleOrFunctionalCast && 2864 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2865 assert(getLangOpts().MSVCCompat && 2866 "this should only be possible with MSVCCompat!"); 2867 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2868 << From->getSourceRange(); 2869 } 2870 } 2871 } else if (const ObjCObjectPointerType *ToPtrType = 2872 ToType->getAs<ObjCObjectPointerType>()) { 2873 if (const ObjCObjectPointerType *FromPtrType = 2874 FromType->getAs<ObjCObjectPointerType>()) { 2875 // Objective-C++ conversions are always okay. 2876 // FIXME: We should have a different class of conversions for the 2877 // Objective-C++ implicit conversions. 2878 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2879 return false; 2880 } else if (FromType->isBlockPointerType()) { 2881 Kind = CK_BlockPointerToObjCPointerCast; 2882 } else { 2883 Kind = CK_CPointerToObjCPointerCast; 2884 } 2885 } else if (ToType->isBlockPointerType()) { 2886 if (!FromType->isBlockPointerType()) 2887 Kind = CK_AnyPointerToBlockPointerCast; 2888 } 2889 2890 // We shouldn't fall into this case unless it's valid for other 2891 // reasons. 2892 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2893 Kind = CK_NullToPointer; 2894 2895 return false; 2896 } 2897 2898 /// IsMemberPointerConversion - Determines whether the conversion of the 2899 /// expression From, which has the (possibly adjusted) type FromType, can be 2900 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2901 /// If so, returns true and places the converted type (that might differ from 2902 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2903 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2904 QualType ToType, 2905 bool InOverloadResolution, 2906 QualType &ConvertedType) { 2907 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2908 if (!ToTypePtr) 2909 return false; 2910 2911 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2912 if (From->isNullPointerConstant(Context, 2913 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2914 : Expr::NPC_ValueDependentIsNull)) { 2915 ConvertedType = ToType; 2916 return true; 2917 } 2918 2919 // Otherwise, both types have to be member pointers. 2920 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2921 if (!FromTypePtr) 2922 return false; 2923 2924 // A pointer to member of B can be converted to a pointer to member of D, 2925 // where D is derived from B (C++ 4.11p2). 2926 QualType FromClass(FromTypePtr->getClass(), 0); 2927 QualType ToClass(ToTypePtr->getClass(), 0); 2928 2929 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2930 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2931 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2932 ToClass.getTypePtr()); 2933 return true; 2934 } 2935 2936 return false; 2937 } 2938 2939 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2940 /// expression From to the type ToType. This routine checks for ambiguous or 2941 /// virtual or inaccessible base-to-derived member pointer conversions 2942 /// for which IsMemberPointerConversion has already returned true. It returns 2943 /// true and produces a diagnostic if there was an error, or returns false 2944 /// otherwise. 2945 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2946 CastKind &Kind, 2947 CXXCastPath &BasePath, 2948 bool IgnoreBaseAccess) { 2949 QualType FromType = From->getType(); 2950 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2951 if (!FromPtrType) { 2952 // This must be a null pointer to member pointer conversion 2953 assert(From->isNullPointerConstant(Context, 2954 Expr::NPC_ValueDependentIsNull) && 2955 "Expr must be null pointer constant!"); 2956 Kind = CK_NullToMemberPointer; 2957 return false; 2958 } 2959 2960 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2961 assert(ToPtrType && "No member pointer cast has a target type " 2962 "that is not a member pointer."); 2963 2964 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2965 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2966 2967 // FIXME: What about dependent types? 2968 assert(FromClass->isRecordType() && "Pointer into non-class."); 2969 assert(ToClass->isRecordType() && "Pointer into non-class."); 2970 2971 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2972 /*DetectVirtual=*/true); 2973 bool DerivationOkay = 2974 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2975 assert(DerivationOkay && 2976 "Should not have been called if derivation isn't OK."); 2977 (void)DerivationOkay; 2978 2979 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2980 getUnqualifiedType())) { 2981 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2982 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2983 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2984 return true; 2985 } 2986 2987 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2988 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2989 << FromClass << ToClass << QualType(VBase, 0) 2990 << From->getSourceRange(); 2991 return true; 2992 } 2993 2994 if (!IgnoreBaseAccess) 2995 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2996 Paths.front(), 2997 diag::err_downcast_from_inaccessible_base); 2998 2999 // Must be a base to derived member conversion. 3000 BuildBasePathArray(Paths, BasePath); 3001 Kind = CK_BaseToDerivedMemberPointer; 3002 return false; 3003 } 3004 3005 /// Determine whether the lifetime conversion between the two given 3006 /// qualifiers sets is nontrivial. 3007 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3008 Qualifiers ToQuals) { 3009 // Converting anything to const __unsafe_unretained is trivial. 3010 if (ToQuals.hasConst() && 3011 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3012 return false; 3013 3014 return true; 3015 } 3016 3017 /// IsQualificationConversion - Determines whether the conversion from 3018 /// an rvalue of type FromType to ToType is a qualification conversion 3019 /// (C++ 4.4). 3020 /// 3021 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3022 /// when the qualification conversion involves a change in the Objective-C 3023 /// object lifetime. 3024 bool 3025 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3026 bool CStyle, bool &ObjCLifetimeConversion) { 3027 FromType = Context.getCanonicalType(FromType); 3028 ToType = Context.getCanonicalType(ToType); 3029 ObjCLifetimeConversion = false; 3030 3031 // If FromType and ToType are the same type, this is not a 3032 // qualification conversion. 3033 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3034 return false; 3035 3036 // (C++ 4.4p4): 3037 // A conversion can add cv-qualifiers at levels other than the first 3038 // in multi-level pointers, subject to the following rules: [...] 3039 bool PreviousToQualsIncludeConst = true; 3040 bool UnwrappedAnyPointer = false; 3041 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 3042 // Within each iteration of the loop, we check the qualifiers to 3043 // determine if this still looks like a qualification 3044 // conversion. Then, if all is well, we unwrap one more level of 3045 // pointers or pointers-to-members and do it all again 3046 // until there are no more pointers or pointers-to-members left to 3047 // unwrap. 3048 UnwrappedAnyPointer = true; 3049 3050 Qualifiers FromQuals = FromType.getQualifiers(); 3051 Qualifiers ToQuals = ToType.getQualifiers(); 3052 3053 // Ignore __unaligned qualifier if this type is void. 3054 if (ToType.getUnqualifiedType()->isVoidType()) 3055 FromQuals.removeUnaligned(); 3056 3057 // Objective-C ARC: 3058 // Check Objective-C lifetime conversions. 3059 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3060 UnwrappedAnyPointer) { 3061 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3062 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3063 ObjCLifetimeConversion = true; 3064 FromQuals.removeObjCLifetime(); 3065 ToQuals.removeObjCLifetime(); 3066 } else { 3067 // Qualification conversions cannot cast between different 3068 // Objective-C lifetime qualifiers. 3069 return false; 3070 } 3071 } 3072 3073 // Allow addition/removal of GC attributes but not changing GC attributes. 3074 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3075 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3076 FromQuals.removeObjCGCAttr(); 3077 ToQuals.removeObjCGCAttr(); 3078 } 3079 3080 // -- for every j > 0, if const is in cv 1,j then const is in cv 3081 // 2,j, and similarly for volatile. 3082 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3083 return false; 3084 3085 // -- if the cv 1,j and cv 2,j are different, then const is in 3086 // every cv for 0 < k < j. 3087 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3088 && !PreviousToQualsIncludeConst) 3089 return false; 3090 3091 // Keep track of whether all prior cv-qualifiers in the "to" type 3092 // include const. 3093 PreviousToQualsIncludeConst 3094 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3095 } 3096 3097 // We are left with FromType and ToType being the pointee types 3098 // after unwrapping the original FromType and ToType the same number 3099 // of types. If we unwrapped any pointers, and if FromType and 3100 // ToType have the same unqualified type (since we checked 3101 // qualifiers above), then this is a qualification conversion. 3102 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3103 } 3104 3105 /// \brief - Determine whether this is a conversion from a scalar type to an 3106 /// atomic type. 3107 /// 3108 /// If successful, updates \c SCS's second and third steps in the conversion 3109 /// sequence to finish the conversion. 3110 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3111 bool InOverloadResolution, 3112 StandardConversionSequence &SCS, 3113 bool CStyle) { 3114 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3115 if (!ToAtomic) 3116 return false; 3117 3118 StandardConversionSequence InnerSCS; 3119 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3120 InOverloadResolution, InnerSCS, 3121 CStyle, /*AllowObjCWritebackConversion=*/false)) 3122 return false; 3123 3124 SCS.Second = InnerSCS.Second; 3125 SCS.setToType(1, InnerSCS.getToType(1)); 3126 SCS.Third = InnerSCS.Third; 3127 SCS.QualificationIncludesObjCLifetime 3128 = InnerSCS.QualificationIncludesObjCLifetime; 3129 SCS.setToType(2, InnerSCS.getToType(2)); 3130 return true; 3131 } 3132 3133 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3134 CXXConstructorDecl *Constructor, 3135 QualType Type) { 3136 const FunctionProtoType *CtorType = 3137 Constructor->getType()->getAs<FunctionProtoType>(); 3138 if (CtorType->getNumParams() > 0) { 3139 QualType FirstArg = CtorType->getParamType(0); 3140 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3141 return true; 3142 } 3143 return false; 3144 } 3145 3146 static OverloadingResult 3147 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3148 CXXRecordDecl *To, 3149 UserDefinedConversionSequence &User, 3150 OverloadCandidateSet &CandidateSet, 3151 bool AllowExplicit) { 3152 for (auto *D : S.LookupConstructors(To)) { 3153 auto Info = getConstructorInfo(D); 3154 if (!Info) 3155 continue; 3156 3157 bool Usable = !Info.Constructor->isInvalidDecl() && 3158 S.isInitListConstructor(Info.Constructor) && 3159 (AllowExplicit || !Info.Constructor->isExplicit()); 3160 if (Usable) { 3161 // If the first argument is (a reference to) the target type, 3162 // suppress conversions. 3163 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3164 S.Context, Info.Constructor, ToType); 3165 if (Info.ConstructorTmpl) 3166 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3167 /*ExplicitArgs*/ nullptr, From, 3168 CandidateSet, SuppressUserConversions); 3169 else 3170 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3171 CandidateSet, SuppressUserConversions); 3172 } 3173 } 3174 3175 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3176 3177 OverloadCandidateSet::iterator Best; 3178 switch (auto Result = 3179 CandidateSet.BestViableFunction(S, From->getLocStart(), 3180 Best, true)) { 3181 case OR_Deleted: 3182 case OR_Success: { 3183 // Record the standard conversion we used and the conversion function. 3184 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3185 QualType ThisType = Constructor->getThisType(S.Context); 3186 // Initializer lists don't have conversions as such. 3187 User.Before.setAsIdentityConversion(); 3188 User.HadMultipleCandidates = HadMultipleCandidates; 3189 User.ConversionFunction = Constructor; 3190 User.FoundConversionFunction = Best->FoundDecl; 3191 User.After.setAsIdentityConversion(); 3192 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3193 User.After.setAllToTypes(ToType); 3194 return Result; 3195 } 3196 3197 case OR_No_Viable_Function: 3198 return OR_No_Viable_Function; 3199 case OR_Ambiguous: 3200 return OR_Ambiguous; 3201 } 3202 3203 llvm_unreachable("Invalid OverloadResult!"); 3204 } 3205 3206 /// Determines whether there is a user-defined conversion sequence 3207 /// (C++ [over.ics.user]) that converts expression From to the type 3208 /// ToType. If such a conversion exists, User will contain the 3209 /// user-defined conversion sequence that performs such a conversion 3210 /// and this routine will return true. Otherwise, this routine returns 3211 /// false and User is unspecified. 3212 /// 3213 /// \param AllowExplicit true if the conversion should consider C++0x 3214 /// "explicit" conversion functions as well as non-explicit conversion 3215 /// functions (C++0x [class.conv.fct]p2). 3216 /// 3217 /// \param AllowObjCConversionOnExplicit true if the conversion should 3218 /// allow an extra Objective-C pointer conversion on uses of explicit 3219 /// constructors. Requires \c AllowExplicit to also be set. 3220 static OverloadingResult 3221 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3222 UserDefinedConversionSequence &User, 3223 OverloadCandidateSet &CandidateSet, 3224 bool AllowExplicit, 3225 bool AllowObjCConversionOnExplicit) { 3226 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3227 3228 // Whether we will only visit constructors. 3229 bool ConstructorsOnly = false; 3230 3231 // If the type we are conversion to is a class type, enumerate its 3232 // constructors. 3233 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3234 // C++ [over.match.ctor]p1: 3235 // When objects of class type are direct-initialized (8.5), or 3236 // copy-initialized from an expression of the same or a 3237 // derived class type (8.5), overload resolution selects the 3238 // constructor. [...] For copy-initialization, the candidate 3239 // functions are all the converting constructors (12.3.1) of 3240 // that class. The argument list is the expression-list within 3241 // the parentheses of the initializer. 3242 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3243 (From->getType()->getAs<RecordType>() && 3244 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3245 ConstructorsOnly = true; 3246 3247 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3248 // We're not going to find any constructors. 3249 } else if (CXXRecordDecl *ToRecordDecl 3250 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3251 3252 Expr **Args = &From; 3253 unsigned NumArgs = 1; 3254 bool ListInitializing = false; 3255 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3256 // But first, see if there is an init-list-constructor that will work. 3257 OverloadingResult Result = IsInitializerListConstructorConversion( 3258 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3259 if (Result != OR_No_Viable_Function) 3260 return Result; 3261 // Never mind. 3262 CandidateSet.clear(); 3263 3264 // If we're list-initializing, we pass the individual elements as 3265 // arguments, not the entire list. 3266 Args = InitList->getInits(); 3267 NumArgs = InitList->getNumInits(); 3268 ListInitializing = true; 3269 } 3270 3271 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3272 auto Info = getConstructorInfo(D); 3273 if (!Info) 3274 continue; 3275 3276 bool Usable = !Info.Constructor->isInvalidDecl(); 3277 if (ListInitializing) 3278 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3279 else 3280 Usable = Usable && 3281 Info.Constructor->isConvertingConstructor(AllowExplicit); 3282 if (Usable) { 3283 bool SuppressUserConversions = !ConstructorsOnly; 3284 if (SuppressUserConversions && ListInitializing) { 3285 SuppressUserConversions = false; 3286 if (NumArgs == 1) { 3287 // If the first argument is (a reference to) the target type, 3288 // suppress conversions. 3289 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3290 S.Context, Info.Constructor, ToType); 3291 } 3292 } 3293 if (Info.ConstructorTmpl) 3294 S.AddTemplateOverloadCandidate( 3295 Info.ConstructorTmpl, Info.FoundDecl, 3296 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3297 CandidateSet, SuppressUserConversions); 3298 else 3299 // Allow one user-defined conversion when user specifies a 3300 // From->ToType conversion via an static cast (c-style, etc). 3301 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3302 llvm::makeArrayRef(Args, NumArgs), 3303 CandidateSet, SuppressUserConversions); 3304 } 3305 } 3306 } 3307 } 3308 3309 // Enumerate conversion functions, if we're allowed to. 3310 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3311 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3312 // No conversion functions from incomplete types. 3313 } else if (const RecordType *FromRecordType 3314 = From->getType()->getAs<RecordType>()) { 3315 if (CXXRecordDecl *FromRecordDecl 3316 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3317 // Add all of the conversion functions as candidates. 3318 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3319 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3320 DeclAccessPair FoundDecl = I.getPair(); 3321 NamedDecl *D = FoundDecl.getDecl(); 3322 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3323 if (isa<UsingShadowDecl>(D)) 3324 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3325 3326 CXXConversionDecl *Conv; 3327 FunctionTemplateDecl *ConvTemplate; 3328 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3329 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3330 else 3331 Conv = cast<CXXConversionDecl>(D); 3332 3333 if (AllowExplicit || !Conv->isExplicit()) { 3334 if (ConvTemplate) 3335 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3336 ActingContext, From, ToType, 3337 CandidateSet, 3338 AllowObjCConversionOnExplicit); 3339 else 3340 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3341 From, ToType, CandidateSet, 3342 AllowObjCConversionOnExplicit); 3343 } 3344 } 3345 } 3346 } 3347 3348 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3349 3350 OverloadCandidateSet::iterator Best; 3351 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3352 Best, true)) { 3353 case OR_Success: 3354 case OR_Deleted: 3355 // Record the standard conversion we used and the conversion function. 3356 if (CXXConstructorDecl *Constructor 3357 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3358 // C++ [over.ics.user]p1: 3359 // If the user-defined conversion is specified by a 3360 // constructor (12.3.1), the initial standard conversion 3361 // sequence converts the source type to the type required by 3362 // the argument of the constructor. 3363 // 3364 QualType ThisType = Constructor->getThisType(S.Context); 3365 if (isa<InitListExpr>(From)) { 3366 // Initializer lists don't have conversions as such. 3367 User.Before.setAsIdentityConversion(); 3368 } else { 3369 if (Best->Conversions[0].isEllipsis()) 3370 User.EllipsisConversion = true; 3371 else { 3372 User.Before = Best->Conversions[0].Standard; 3373 User.EllipsisConversion = false; 3374 } 3375 } 3376 User.HadMultipleCandidates = HadMultipleCandidates; 3377 User.ConversionFunction = Constructor; 3378 User.FoundConversionFunction = Best->FoundDecl; 3379 User.After.setAsIdentityConversion(); 3380 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3381 User.After.setAllToTypes(ToType); 3382 return Result; 3383 } 3384 if (CXXConversionDecl *Conversion 3385 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3386 // C++ [over.ics.user]p1: 3387 // 3388 // [...] If the user-defined conversion is specified by a 3389 // conversion function (12.3.2), the initial standard 3390 // conversion sequence converts the source type to the 3391 // implicit object parameter of the conversion function. 3392 User.Before = Best->Conversions[0].Standard; 3393 User.HadMultipleCandidates = HadMultipleCandidates; 3394 User.ConversionFunction = Conversion; 3395 User.FoundConversionFunction = Best->FoundDecl; 3396 User.EllipsisConversion = false; 3397 3398 // C++ [over.ics.user]p2: 3399 // The second standard conversion sequence converts the 3400 // result of the user-defined conversion to the target type 3401 // for the sequence. Since an implicit conversion sequence 3402 // is an initialization, the special rules for 3403 // initialization by user-defined conversion apply when 3404 // selecting the best user-defined conversion for a 3405 // user-defined conversion sequence (see 13.3.3 and 3406 // 13.3.3.1). 3407 User.After = Best->FinalConversion; 3408 return Result; 3409 } 3410 llvm_unreachable("Not a constructor or conversion function?"); 3411 3412 case OR_No_Viable_Function: 3413 return OR_No_Viable_Function; 3414 3415 case OR_Ambiguous: 3416 return OR_Ambiguous; 3417 } 3418 3419 llvm_unreachable("Invalid OverloadResult!"); 3420 } 3421 3422 bool 3423 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3424 ImplicitConversionSequence ICS; 3425 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3426 OverloadCandidateSet::CSK_Normal); 3427 OverloadingResult OvResult = 3428 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3429 CandidateSet, false, false); 3430 if (OvResult == OR_Ambiguous) 3431 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3432 << From->getType() << ToType << From->getSourceRange(); 3433 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3434 if (!RequireCompleteType(From->getLocStart(), ToType, 3435 diag::err_typecheck_nonviable_condition_incomplete, 3436 From->getType(), From->getSourceRange())) 3437 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3438 << false << From->getType() << From->getSourceRange() << ToType; 3439 } else 3440 return false; 3441 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3442 return true; 3443 } 3444 3445 /// \brief Compare the user-defined conversion functions or constructors 3446 /// of two user-defined conversion sequences to determine whether any ordering 3447 /// is possible. 3448 static ImplicitConversionSequence::CompareKind 3449 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3450 FunctionDecl *Function2) { 3451 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3452 return ImplicitConversionSequence::Indistinguishable; 3453 3454 // Objective-C++: 3455 // If both conversion functions are implicitly-declared conversions from 3456 // a lambda closure type to a function pointer and a block pointer, 3457 // respectively, always prefer the conversion to a function pointer, 3458 // because the function pointer is more lightweight and is more likely 3459 // to keep code working. 3460 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3461 if (!Conv1) 3462 return ImplicitConversionSequence::Indistinguishable; 3463 3464 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3465 if (!Conv2) 3466 return ImplicitConversionSequence::Indistinguishable; 3467 3468 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3469 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3470 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3471 if (Block1 != Block2) 3472 return Block1 ? ImplicitConversionSequence::Worse 3473 : ImplicitConversionSequence::Better; 3474 } 3475 3476 return ImplicitConversionSequence::Indistinguishable; 3477 } 3478 3479 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3480 const ImplicitConversionSequence &ICS) { 3481 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3482 (ICS.isUserDefined() && 3483 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3484 } 3485 3486 /// CompareImplicitConversionSequences - Compare two implicit 3487 /// conversion sequences to determine whether one is better than the 3488 /// other or if they are indistinguishable (C++ 13.3.3.2). 3489 static ImplicitConversionSequence::CompareKind 3490 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3491 const ImplicitConversionSequence& ICS1, 3492 const ImplicitConversionSequence& ICS2) 3493 { 3494 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3495 // conversion sequences (as defined in 13.3.3.1) 3496 // -- a standard conversion sequence (13.3.3.1.1) is a better 3497 // conversion sequence than a user-defined conversion sequence or 3498 // an ellipsis conversion sequence, and 3499 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3500 // conversion sequence than an ellipsis conversion sequence 3501 // (13.3.3.1.3). 3502 // 3503 // C++0x [over.best.ics]p10: 3504 // For the purpose of ranking implicit conversion sequences as 3505 // described in 13.3.3.2, the ambiguous conversion sequence is 3506 // treated as a user-defined sequence that is indistinguishable 3507 // from any other user-defined conversion sequence. 3508 3509 // String literal to 'char *' conversion has been deprecated in C++03. It has 3510 // been removed from C++11. We still accept this conversion, if it happens at 3511 // the best viable function. Otherwise, this conversion is considered worse 3512 // than ellipsis conversion. Consider this as an extension; this is not in the 3513 // standard. For example: 3514 // 3515 // int &f(...); // #1 3516 // void f(char*); // #2 3517 // void g() { int &r = f("foo"); } 3518 // 3519 // In C++03, we pick #2 as the best viable function. 3520 // In C++11, we pick #1 as the best viable function, because ellipsis 3521 // conversion is better than string-literal to char* conversion (since there 3522 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3523 // convert arguments, #2 would be the best viable function in C++11. 3524 // If the best viable function has this conversion, a warning will be issued 3525 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3526 3527 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3528 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3529 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3530 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3531 ? ImplicitConversionSequence::Worse 3532 : ImplicitConversionSequence::Better; 3533 3534 if (ICS1.getKindRank() < ICS2.getKindRank()) 3535 return ImplicitConversionSequence::Better; 3536 if (ICS2.getKindRank() < ICS1.getKindRank()) 3537 return ImplicitConversionSequence::Worse; 3538 3539 // The following checks require both conversion sequences to be of 3540 // the same kind. 3541 if (ICS1.getKind() != ICS2.getKind()) 3542 return ImplicitConversionSequence::Indistinguishable; 3543 3544 ImplicitConversionSequence::CompareKind Result = 3545 ImplicitConversionSequence::Indistinguishable; 3546 3547 // Two implicit conversion sequences of the same form are 3548 // indistinguishable conversion sequences unless one of the 3549 // following rules apply: (C++ 13.3.3.2p3): 3550 3551 // List-initialization sequence L1 is a better conversion sequence than 3552 // list-initialization sequence L2 if: 3553 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3554 // if not that, 3555 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3556 // and N1 is smaller than N2., 3557 // even if one of the other rules in this paragraph would otherwise apply. 3558 if (!ICS1.isBad()) { 3559 if (ICS1.isStdInitializerListElement() && 3560 !ICS2.isStdInitializerListElement()) 3561 return ImplicitConversionSequence::Better; 3562 if (!ICS1.isStdInitializerListElement() && 3563 ICS2.isStdInitializerListElement()) 3564 return ImplicitConversionSequence::Worse; 3565 } 3566 3567 if (ICS1.isStandard()) 3568 // Standard conversion sequence S1 is a better conversion sequence than 3569 // standard conversion sequence S2 if [...] 3570 Result = CompareStandardConversionSequences(S, Loc, 3571 ICS1.Standard, ICS2.Standard); 3572 else if (ICS1.isUserDefined()) { 3573 // User-defined conversion sequence U1 is a better conversion 3574 // sequence than another user-defined conversion sequence U2 if 3575 // they contain the same user-defined conversion function or 3576 // constructor and if the second standard conversion sequence of 3577 // U1 is better than the second standard conversion sequence of 3578 // U2 (C++ 13.3.3.2p3). 3579 if (ICS1.UserDefined.ConversionFunction == 3580 ICS2.UserDefined.ConversionFunction) 3581 Result = CompareStandardConversionSequences(S, Loc, 3582 ICS1.UserDefined.After, 3583 ICS2.UserDefined.After); 3584 else 3585 Result = compareConversionFunctions(S, 3586 ICS1.UserDefined.ConversionFunction, 3587 ICS2.UserDefined.ConversionFunction); 3588 } 3589 3590 return Result; 3591 } 3592 3593 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3594 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3595 Qualifiers Quals; 3596 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3597 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3598 } 3599 3600 return Context.hasSameUnqualifiedType(T1, T2); 3601 } 3602 3603 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3604 // determine if one is a proper subset of the other. 3605 static ImplicitConversionSequence::CompareKind 3606 compareStandardConversionSubsets(ASTContext &Context, 3607 const StandardConversionSequence& SCS1, 3608 const StandardConversionSequence& SCS2) { 3609 ImplicitConversionSequence::CompareKind Result 3610 = ImplicitConversionSequence::Indistinguishable; 3611 3612 // the identity conversion sequence is considered to be a subsequence of 3613 // any non-identity conversion sequence 3614 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3615 return ImplicitConversionSequence::Better; 3616 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3617 return ImplicitConversionSequence::Worse; 3618 3619 if (SCS1.Second != SCS2.Second) { 3620 if (SCS1.Second == ICK_Identity) 3621 Result = ImplicitConversionSequence::Better; 3622 else if (SCS2.Second == ICK_Identity) 3623 Result = ImplicitConversionSequence::Worse; 3624 else 3625 return ImplicitConversionSequence::Indistinguishable; 3626 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3627 return ImplicitConversionSequence::Indistinguishable; 3628 3629 if (SCS1.Third == SCS2.Third) { 3630 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3631 : ImplicitConversionSequence::Indistinguishable; 3632 } 3633 3634 if (SCS1.Third == ICK_Identity) 3635 return Result == ImplicitConversionSequence::Worse 3636 ? ImplicitConversionSequence::Indistinguishable 3637 : ImplicitConversionSequence::Better; 3638 3639 if (SCS2.Third == ICK_Identity) 3640 return Result == ImplicitConversionSequence::Better 3641 ? ImplicitConversionSequence::Indistinguishable 3642 : ImplicitConversionSequence::Worse; 3643 3644 return ImplicitConversionSequence::Indistinguishable; 3645 } 3646 3647 /// \brief Determine whether one of the given reference bindings is better 3648 /// than the other based on what kind of bindings they are. 3649 static bool 3650 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3651 const StandardConversionSequence &SCS2) { 3652 // C++0x [over.ics.rank]p3b4: 3653 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3654 // implicit object parameter of a non-static member function declared 3655 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3656 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3657 // lvalue reference to a function lvalue and S2 binds an rvalue 3658 // reference*. 3659 // 3660 // FIXME: Rvalue references. We're going rogue with the above edits, 3661 // because the semantics in the current C++0x working paper (N3225 at the 3662 // time of this writing) break the standard definition of std::forward 3663 // and std::reference_wrapper when dealing with references to functions. 3664 // Proposed wording changes submitted to CWG for consideration. 3665 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3666 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3667 return false; 3668 3669 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3670 SCS2.IsLvalueReference) || 3671 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3672 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3673 } 3674 3675 /// CompareStandardConversionSequences - Compare two standard 3676 /// conversion sequences to determine whether one is better than the 3677 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3678 static ImplicitConversionSequence::CompareKind 3679 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3680 const StandardConversionSequence& SCS1, 3681 const StandardConversionSequence& SCS2) 3682 { 3683 // Standard conversion sequence S1 is a better conversion sequence 3684 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3685 3686 // -- S1 is a proper subsequence of S2 (comparing the conversion 3687 // sequences in the canonical form defined by 13.3.3.1.1, 3688 // excluding any Lvalue Transformation; the identity conversion 3689 // sequence is considered to be a subsequence of any 3690 // non-identity conversion sequence) or, if not that, 3691 if (ImplicitConversionSequence::CompareKind CK 3692 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3693 return CK; 3694 3695 // -- the rank of S1 is better than the rank of S2 (by the rules 3696 // defined below), or, if not that, 3697 ImplicitConversionRank Rank1 = SCS1.getRank(); 3698 ImplicitConversionRank Rank2 = SCS2.getRank(); 3699 if (Rank1 < Rank2) 3700 return ImplicitConversionSequence::Better; 3701 else if (Rank2 < Rank1) 3702 return ImplicitConversionSequence::Worse; 3703 3704 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3705 // are indistinguishable unless one of the following rules 3706 // applies: 3707 3708 // A conversion that is not a conversion of a pointer, or 3709 // pointer to member, to bool is better than another conversion 3710 // that is such a conversion. 3711 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3712 return SCS2.isPointerConversionToBool() 3713 ? ImplicitConversionSequence::Better 3714 : ImplicitConversionSequence::Worse; 3715 3716 // C++ [over.ics.rank]p4b2: 3717 // 3718 // If class B is derived directly or indirectly from class A, 3719 // conversion of B* to A* is better than conversion of B* to 3720 // void*, and conversion of A* to void* is better than conversion 3721 // of B* to void*. 3722 bool SCS1ConvertsToVoid 3723 = SCS1.isPointerConversionToVoidPointer(S.Context); 3724 bool SCS2ConvertsToVoid 3725 = SCS2.isPointerConversionToVoidPointer(S.Context); 3726 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3727 // Exactly one of the conversion sequences is a conversion to 3728 // a void pointer; it's the worse conversion. 3729 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3730 : ImplicitConversionSequence::Worse; 3731 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3732 // Neither conversion sequence converts to a void pointer; compare 3733 // their derived-to-base conversions. 3734 if (ImplicitConversionSequence::CompareKind DerivedCK 3735 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3736 return DerivedCK; 3737 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3738 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3739 // Both conversion sequences are conversions to void 3740 // pointers. Compare the source types to determine if there's an 3741 // inheritance relationship in their sources. 3742 QualType FromType1 = SCS1.getFromType(); 3743 QualType FromType2 = SCS2.getFromType(); 3744 3745 // Adjust the types we're converting from via the array-to-pointer 3746 // conversion, if we need to. 3747 if (SCS1.First == ICK_Array_To_Pointer) 3748 FromType1 = S.Context.getArrayDecayedType(FromType1); 3749 if (SCS2.First == ICK_Array_To_Pointer) 3750 FromType2 = S.Context.getArrayDecayedType(FromType2); 3751 3752 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3753 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3754 3755 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3756 return ImplicitConversionSequence::Better; 3757 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3758 return ImplicitConversionSequence::Worse; 3759 3760 // Objective-C++: If one interface is more specific than the 3761 // other, it is the better one. 3762 const ObjCObjectPointerType* FromObjCPtr1 3763 = FromType1->getAs<ObjCObjectPointerType>(); 3764 const ObjCObjectPointerType* FromObjCPtr2 3765 = FromType2->getAs<ObjCObjectPointerType>(); 3766 if (FromObjCPtr1 && FromObjCPtr2) { 3767 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3768 FromObjCPtr2); 3769 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3770 FromObjCPtr1); 3771 if (AssignLeft != AssignRight) { 3772 return AssignLeft? ImplicitConversionSequence::Better 3773 : ImplicitConversionSequence::Worse; 3774 } 3775 } 3776 } 3777 3778 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3779 // bullet 3). 3780 if (ImplicitConversionSequence::CompareKind QualCK 3781 = CompareQualificationConversions(S, SCS1, SCS2)) 3782 return QualCK; 3783 3784 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3785 // Check for a better reference binding based on the kind of bindings. 3786 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3787 return ImplicitConversionSequence::Better; 3788 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3789 return ImplicitConversionSequence::Worse; 3790 3791 // C++ [over.ics.rank]p3b4: 3792 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3793 // which the references refer are the same type except for 3794 // top-level cv-qualifiers, and the type to which the reference 3795 // initialized by S2 refers is more cv-qualified than the type 3796 // to which the reference initialized by S1 refers. 3797 QualType T1 = SCS1.getToType(2); 3798 QualType T2 = SCS2.getToType(2); 3799 T1 = S.Context.getCanonicalType(T1); 3800 T2 = S.Context.getCanonicalType(T2); 3801 Qualifiers T1Quals, T2Quals; 3802 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3803 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3804 if (UnqualT1 == UnqualT2) { 3805 // Objective-C++ ARC: If the references refer to objects with different 3806 // lifetimes, prefer bindings that don't change lifetime. 3807 if (SCS1.ObjCLifetimeConversionBinding != 3808 SCS2.ObjCLifetimeConversionBinding) { 3809 return SCS1.ObjCLifetimeConversionBinding 3810 ? ImplicitConversionSequence::Worse 3811 : ImplicitConversionSequence::Better; 3812 } 3813 3814 // If the type is an array type, promote the element qualifiers to the 3815 // type for comparison. 3816 if (isa<ArrayType>(T1) && T1Quals) 3817 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3818 if (isa<ArrayType>(T2) && T2Quals) 3819 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3820 if (T2.isMoreQualifiedThan(T1)) 3821 return ImplicitConversionSequence::Better; 3822 else if (T1.isMoreQualifiedThan(T2)) 3823 return ImplicitConversionSequence::Worse; 3824 } 3825 } 3826 3827 // In Microsoft mode, prefer an integral conversion to a 3828 // floating-to-integral conversion if the integral conversion 3829 // is between types of the same size. 3830 // For example: 3831 // void f(float); 3832 // void f(int); 3833 // int main { 3834 // long a; 3835 // f(a); 3836 // } 3837 // Here, MSVC will call f(int) instead of generating a compile error 3838 // as clang will do in standard mode. 3839 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3840 SCS2.Second == ICK_Floating_Integral && 3841 S.Context.getTypeSize(SCS1.getFromType()) == 3842 S.Context.getTypeSize(SCS1.getToType(2))) 3843 return ImplicitConversionSequence::Better; 3844 3845 return ImplicitConversionSequence::Indistinguishable; 3846 } 3847 3848 /// CompareQualificationConversions - Compares two standard conversion 3849 /// sequences to determine whether they can be ranked based on their 3850 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3851 static ImplicitConversionSequence::CompareKind 3852 CompareQualificationConversions(Sema &S, 3853 const StandardConversionSequence& SCS1, 3854 const StandardConversionSequence& SCS2) { 3855 // C++ 13.3.3.2p3: 3856 // -- S1 and S2 differ only in their qualification conversion and 3857 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3858 // cv-qualification signature of type T1 is a proper subset of 3859 // the cv-qualification signature of type T2, and S1 is not the 3860 // deprecated string literal array-to-pointer conversion (4.2). 3861 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3862 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3863 return ImplicitConversionSequence::Indistinguishable; 3864 3865 // FIXME: the example in the standard doesn't use a qualification 3866 // conversion (!) 3867 QualType T1 = SCS1.getToType(2); 3868 QualType T2 = SCS2.getToType(2); 3869 T1 = S.Context.getCanonicalType(T1); 3870 T2 = S.Context.getCanonicalType(T2); 3871 Qualifiers T1Quals, T2Quals; 3872 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3873 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3874 3875 // If the types are the same, we won't learn anything by unwrapped 3876 // them. 3877 if (UnqualT1 == UnqualT2) 3878 return ImplicitConversionSequence::Indistinguishable; 3879 3880 // If the type is an array type, promote the element qualifiers to the type 3881 // for comparison. 3882 if (isa<ArrayType>(T1) && T1Quals) 3883 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3884 if (isa<ArrayType>(T2) && T2Quals) 3885 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3886 3887 ImplicitConversionSequence::CompareKind Result 3888 = ImplicitConversionSequence::Indistinguishable; 3889 3890 // Objective-C++ ARC: 3891 // Prefer qualification conversions not involving a change in lifetime 3892 // to qualification conversions that do not change lifetime. 3893 if (SCS1.QualificationIncludesObjCLifetime != 3894 SCS2.QualificationIncludesObjCLifetime) { 3895 Result = SCS1.QualificationIncludesObjCLifetime 3896 ? ImplicitConversionSequence::Worse 3897 : ImplicitConversionSequence::Better; 3898 } 3899 3900 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3901 // Within each iteration of the loop, we check the qualifiers to 3902 // determine if this still looks like a qualification 3903 // conversion. Then, if all is well, we unwrap one more level of 3904 // pointers or pointers-to-members and do it all again 3905 // until there are no more pointers or pointers-to-members left 3906 // to unwrap. This essentially mimics what 3907 // IsQualificationConversion does, but here we're checking for a 3908 // strict subset of qualifiers. 3909 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3910 // The qualifiers are the same, so this doesn't tell us anything 3911 // about how the sequences rank. 3912 ; 3913 else if (T2.isMoreQualifiedThan(T1)) { 3914 // T1 has fewer qualifiers, so it could be the better sequence. 3915 if (Result == ImplicitConversionSequence::Worse) 3916 // Neither has qualifiers that are a subset of the other's 3917 // qualifiers. 3918 return ImplicitConversionSequence::Indistinguishable; 3919 3920 Result = ImplicitConversionSequence::Better; 3921 } else if (T1.isMoreQualifiedThan(T2)) { 3922 // T2 has fewer qualifiers, so it could be the better sequence. 3923 if (Result == ImplicitConversionSequence::Better) 3924 // Neither has qualifiers that are a subset of the other's 3925 // qualifiers. 3926 return ImplicitConversionSequence::Indistinguishable; 3927 3928 Result = ImplicitConversionSequence::Worse; 3929 } else { 3930 // Qualifiers are disjoint. 3931 return ImplicitConversionSequence::Indistinguishable; 3932 } 3933 3934 // If the types after this point are equivalent, we're done. 3935 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3936 break; 3937 } 3938 3939 // Check that the winning standard conversion sequence isn't using 3940 // the deprecated string literal array to pointer conversion. 3941 switch (Result) { 3942 case ImplicitConversionSequence::Better: 3943 if (SCS1.DeprecatedStringLiteralToCharPtr) 3944 Result = ImplicitConversionSequence::Indistinguishable; 3945 break; 3946 3947 case ImplicitConversionSequence::Indistinguishable: 3948 break; 3949 3950 case ImplicitConversionSequence::Worse: 3951 if (SCS2.DeprecatedStringLiteralToCharPtr) 3952 Result = ImplicitConversionSequence::Indistinguishable; 3953 break; 3954 } 3955 3956 return Result; 3957 } 3958 3959 /// CompareDerivedToBaseConversions - Compares two standard conversion 3960 /// sequences to determine whether they can be ranked based on their 3961 /// various kinds of derived-to-base conversions (C++ 3962 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3963 /// conversions between Objective-C interface types. 3964 static ImplicitConversionSequence::CompareKind 3965 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3966 const StandardConversionSequence& SCS1, 3967 const StandardConversionSequence& SCS2) { 3968 QualType FromType1 = SCS1.getFromType(); 3969 QualType ToType1 = SCS1.getToType(1); 3970 QualType FromType2 = SCS2.getFromType(); 3971 QualType ToType2 = SCS2.getToType(1); 3972 3973 // Adjust the types we're converting from via the array-to-pointer 3974 // conversion, if we need to. 3975 if (SCS1.First == ICK_Array_To_Pointer) 3976 FromType1 = S.Context.getArrayDecayedType(FromType1); 3977 if (SCS2.First == ICK_Array_To_Pointer) 3978 FromType2 = S.Context.getArrayDecayedType(FromType2); 3979 3980 // Canonicalize all of the types. 3981 FromType1 = S.Context.getCanonicalType(FromType1); 3982 ToType1 = S.Context.getCanonicalType(ToType1); 3983 FromType2 = S.Context.getCanonicalType(FromType2); 3984 ToType2 = S.Context.getCanonicalType(ToType2); 3985 3986 // C++ [over.ics.rank]p4b3: 3987 // 3988 // If class B is derived directly or indirectly from class A and 3989 // class C is derived directly or indirectly from B, 3990 // 3991 // Compare based on pointer conversions. 3992 if (SCS1.Second == ICK_Pointer_Conversion && 3993 SCS2.Second == ICK_Pointer_Conversion && 3994 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3995 FromType1->isPointerType() && FromType2->isPointerType() && 3996 ToType1->isPointerType() && ToType2->isPointerType()) { 3997 QualType FromPointee1 3998 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3999 QualType ToPointee1 4000 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4001 QualType FromPointee2 4002 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4003 QualType ToPointee2 4004 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4005 4006 // -- conversion of C* to B* is better than conversion of C* to A*, 4007 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4008 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4009 return ImplicitConversionSequence::Better; 4010 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4011 return ImplicitConversionSequence::Worse; 4012 } 4013 4014 // -- conversion of B* to A* is better than conversion of C* to A*, 4015 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4016 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4017 return ImplicitConversionSequence::Better; 4018 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4019 return ImplicitConversionSequence::Worse; 4020 } 4021 } else if (SCS1.Second == ICK_Pointer_Conversion && 4022 SCS2.Second == ICK_Pointer_Conversion) { 4023 const ObjCObjectPointerType *FromPtr1 4024 = FromType1->getAs<ObjCObjectPointerType>(); 4025 const ObjCObjectPointerType *FromPtr2 4026 = FromType2->getAs<ObjCObjectPointerType>(); 4027 const ObjCObjectPointerType *ToPtr1 4028 = ToType1->getAs<ObjCObjectPointerType>(); 4029 const ObjCObjectPointerType *ToPtr2 4030 = ToType2->getAs<ObjCObjectPointerType>(); 4031 4032 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4033 // Apply the same conversion ranking rules for Objective-C pointer types 4034 // that we do for C++ pointers to class types. However, we employ the 4035 // Objective-C pseudo-subtyping relationship used for assignment of 4036 // Objective-C pointer types. 4037 bool FromAssignLeft 4038 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4039 bool FromAssignRight 4040 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4041 bool ToAssignLeft 4042 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4043 bool ToAssignRight 4044 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4045 4046 // A conversion to an a non-id object pointer type or qualified 'id' 4047 // type is better than a conversion to 'id'. 4048 if (ToPtr1->isObjCIdType() && 4049 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4050 return ImplicitConversionSequence::Worse; 4051 if (ToPtr2->isObjCIdType() && 4052 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4053 return ImplicitConversionSequence::Better; 4054 4055 // A conversion to a non-id object pointer type is better than a 4056 // conversion to a qualified 'id' type 4057 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4058 return ImplicitConversionSequence::Worse; 4059 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4060 return ImplicitConversionSequence::Better; 4061 4062 // A conversion to an a non-Class object pointer type or qualified 'Class' 4063 // type is better than a conversion to 'Class'. 4064 if (ToPtr1->isObjCClassType() && 4065 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4066 return ImplicitConversionSequence::Worse; 4067 if (ToPtr2->isObjCClassType() && 4068 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4069 return ImplicitConversionSequence::Better; 4070 4071 // A conversion to a non-Class object pointer type is better than a 4072 // conversion to a qualified 'Class' type. 4073 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4074 return ImplicitConversionSequence::Worse; 4075 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4076 return ImplicitConversionSequence::Better; 4077 4078 // -- "conversion of C* to B* is better than conversion of C* to A*," 4079 if (S.Context.hasSameType(FromType1, FromType2) && 4080 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4081 (ToAssignLeft != ToAssignRight)) 4082 return ToAssignLeft? ImplicitConversionSequence::Worse 4083 : ImplicitConversionSequence::Better; 4084 4085 // -- "conversion of B* to A* is better than conversion of C* to A*," 4086 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4087 (FromAssignLeft != FromAssignRight)) 4088 return FromAssignLeft? ImplicitConversionSequence::Better 4089 : ImplicitConversionSequence::Worse; 4090 } 4091 } 4092 4093 // Ranking of member-pointer types. 4094 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4095 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4096 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4097 const MemberPointerType * FromMemPointer1 = 4098 FromType1->getAs<MemberPointerType>(); 4099 const MemberPointerType * ToMemPointer1 = 4100 ToType1->getAs<MemberPointerType>(); 4101 const MemberPointerType * FromMemPointer2 = 4102 FromType2->getAs<MemberPointerType>(); 4103 const MemberPointerType * ToMemPointer2 = 4104 ToType2->getAs<MemberPointerType>(); 4105 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4106 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4107 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4108 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4109 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4110 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4111 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4112 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4113 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4114 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4115 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4116 return ImplicitConversionSequence::Worse; 4117 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4118 return ImplicitConversionSequence::Better; 4119 } 4120 // conversion of B::* to C::* is better than conversion of A::* to C::* 4121 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4122 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4123 return ImplicitConversionSequence::Better; 4124 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4125 return ImplicitConversionSequence::Worse; 4126 } 4127 } 4128 4129 if (SCS1.Second == ICK_Derived_To_Base) { 4130 // -- conversion of C to B is better than conversion of C to A, 4131 // -- binding of an expression of type C to a reference of type 4132 // B& is better than binding an expression of type C to a 4133 // reference of type A&, 4134 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4135 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4136 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4137 return ImplicitConversionSequence::Better; 4138 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4139 return ImplicitConversionSequence::Worse; 4140 } 4141 4142 // -- conversion of B to A is better than conversion of C to A. 4143 // -- binding of an expression of type B to a reference of type 4144 // A& is better than binding an expression of type C to a 4145 // reference of type A&, 4146 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4147 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4148 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4149 return ImplicitConversionSequence::Better; 4150 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4151 return ImplicitConversionSequence::Worse; 4152 } 4153 } 4154 4155 return ImplicitConversionSequence::Indistinguishable; 4156 } 4157 4158 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4159 /// C++ class. 4160 static bool isTypeValid(QualType T) { 4161 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4162 return !Record->isInvalidDecl(); 4163 4164 return true; 4165 } 4166 4167 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4168 /// determine whether they are reference-related, 4169 /// reference-compatible, reference-compatible with added 4170 /// qualification, or incompatible, for use in C++ initialization by 4171 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4172 /// type, and the first type (T1) is the pointee type of the reference 4173 /// type being initialized. 4174 Sema::ReferenceCompareResult 4175 Sema::CompareReferenceRelationship(SourceLocation Loc, 4176 QualType OrigT1, QualType OrigT2, 4177 bool &DerivedToBase, 4178 bool &ObjCConversion, 4179 bool &ObjCLifetimeConversion) { 4180 assert(!OrigT1->isReferenceType() && 4181 "T1 must be the pointee type of the reference type"); 4182 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4183 4184 QualType T1 = Context.getCanonicalType(OrigT1); 4185 QualType T2 = Context.getCanonicalType(OrigT2); 4186 Qualifiers T1Quals, T2Quals; 4187 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4188 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4189 4190 // C++ [dcl.init.ref]p4: 4191 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4192 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4193 // T1 is a base class of T2. 4194 DerivedToBase = false; 4195 ObjCConversion = false; 4196 ObjCLifetimeConversion = false; 4197 QualType ConvertedT2; 4198 if (UnqualT1 == UnqualT2) { 4199 // Nothing to do. 4200 } else if (isCompleteType(Loc, OrigT2) && 4201 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4202 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4203 DerivedToBase = true; 4204 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4205 UnqualT2->isObjCObjectOrInterfaceType() && 4206 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4207 ObjCConversion = true; 4208 else if (UnqualT2->isFunctionType() && 4209 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4210 // C++1z [dcl.init.ref]p4: 4211 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4212 // function" and T1 is "function" 4213 // 4214 // We extend this to also apply to 'noreturn', so allow any function 4215 // conversion between function types. 4216 return Ref_Compatible; 4217 else 4218 return Ref_Incompatible; 4219 4220 // At this point, we know that T1 and T2 are reference-related (at 4221 // least). 4222 4223 // If the type is an array type, promote the element qualifiers to the type 4224 // for comparison. 4225 if (isa<ArrayType>(T1) && T1Quals) 4226 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4227 if (isa<ArrayType>(T2) && T2Quals) 4228 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4229 4230 // C++ [dcl.init.ref]p4: 4231 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4232 // reference-related to T2 and cv1 is the same cv-qualification 4233 // as, or greater cv-qualification than, cv2. For purposes of 4234 // overload resolution, cases for which cv1 is greater 4235 // cv-qualification than cv2 are identified as 4236 // reference-compatible with added qualification (see 13.3.3.2). 4237 // 4238 // Note that we also require equivalence of Objective-C GC and address-space 4239 // qualifiers when performing these computations, so that e.g., an int in 4240 // address space 1 is not reference-compatible with an int in address 4241 // space 2. 4242 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4243 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4244 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4245 ObjCLifetimeConversion = true; 4246 4247 T1Quals.removeObjCLifetime(); 4248 T2Quals.removeObjCLifetime(); 4249 } 4250 4251 // MS compiler ignores __unaligned qualifier for references; do the same. 4252 T1Quals.removeUnaligned(); 4253 T2Quals.removeUnaligned(); 4254 4255 if (T1Quals.compatiblyIncludes(T2Quals)) 4256 return Ref_Compatible; 4257 else 4258 return Ref_Related; 4259 } 4260 4261 /// \brief Look for a user-defined conversion to an value reference-compatible 4262 /// with DeclType. Return true if something definite is found. 4263 static bool 4264 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4265 QualType DeclType, SourceLocation DeclLoc, 4266 Expr *Init, QualType T2, bool AllowRvalues, 4267 bool AllowExplicit) { 4268 assert(T2->isRecordType() && "Can only find conversions of record types."); 4269 CXXRecordDecl *T2RecordDecl 4270 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4271 4272 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4273 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4274 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4275 NamedDecl *D = *I; 4276 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4277 if (isa<UsingShadowDecl>(D)) 4278 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4279 4280 FunctionTemplateDecl *ConvTemplate 4281 = dyn_cast<FunctionTemplateDecl>(D); 4282 CXXConversionDecl *Conv; 4283 if (ConvTemplate) 4284 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4285 else 4286 Conv = cast<CXXConversionDecl>(D); 4287 4288 // If this is an explicit conversion, and we're not allowed to consider 4289 // explicit conversions, skip it. 4290 if (!AllowExplicit && Conv->isExplicit()) 4291 continue; 4292 4293 if (AllowRvalues) { 4294 bool DerivedToBase = false; 4295 bool ObjCConversion = false; 4296 bool ObjCLifetimeConversion = false; 4297 4298 // If we are initializing an rvalue reference, don't permit conversion 4299 // functions that return lvalues. 4300 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4301 const ReferenceType *RefType 4302 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4303 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4304 continue; 4305 } 4306 4307 if (!ConvTemplate && 4308 S.CompareReferenceRelationship( 4309 DeclLoc, 4310 Conv->getConversionType().getNonReferenceType() 4311 .getUnqualifiedType(), 4312 DeclType.getNonReferenceType().getUnqualifiedType(), 4313 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4314 Sema::Ref_Incompatible) 4315 continue; 4316 } else { 4317 // If the conversion function doesn't return a reference type, 4318 // it can't be considered for this conversion. An rvalue reference 4319 // is only acceptable if its referencee is a function type. 4320 4321 const ReferenceType *RefType = 4322 Conv->getConversionType()->getAs<ReferenceType>(); 4323 if (!RefType || 4324 (!RefType->isLValueReferenceType() && 4325 !RefType->getPointeeType()->isFunctionType())) 4326 continue; 4327 } 4328 4329 if (ConvTemplate) 4330 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4331 Init, DeclType, CandidateSet, 4332 /*AllowObjCConversionOnExplicit=*/false); 4333 else 4334 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4335 DeclType, CandidateSet, 4336 /*AllowObjCConversionOnExplicit=*/false); 4337 } 4338 4339 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4340 4341 OverloadCandidateSet::iterator Best; 4342 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4343 case OR_Success: 4344 // C++ [over.ics.ref]p1: 4345 // 4346 // [...] If the parameter binds directly to the result of 4347 // applying a conversion function to the argument 4348 // expression, the implicit conversion sequence is a 4349 // user-defined conversion sequence (13.3.3.1.2), with the 4350 // second standard conversion sequence either an identity 4351 // conversion or, if the conversion function returns an 4352 // entity of a type that is a derived class of the parameter 4353 // type, a derived-to-base Conversion. 4354 if (!Best->FinalConversion.DirectBinding) 4355 return false; 4356 4357 ICS.setUserDefined(); 4358 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4359 ICS.UserDefined.After = Best->FinalConversion; 4360 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4361 ICS.UserDefined.ConversionFunction = Best->Function; 4362 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4363 ICS.UserDefined.EllipsisConversion = false; 4364 assert(ICS.UserDefined.After.ReferenceBinding && 4365 ICS.UserDefined.After.DirectBinding && 4366 "Expected a direct reference binding!"); 4367 return true; 4368 4369 case OR_Ambiguous: 4370 ICS.setAmbiguous(); 4371 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4372 Cand != CandidateSet.end(); ++Cand) 4373 if (Cand->Viable) 4374 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4375 return true; 4376 4377 case OR_No_Viable_Function: 4378 case OR_Deleted: 4379 // There was no suitable conversion, or we found a deleted 4380 // conversion; continue with other checks. 4381 return false; 4382 } 4383 4384 llvm_unreachable("Invalid OverloadResult!"); 4385 } 4386 4387 /// \brief Compute an implicit conversion sequence for reference 4388 /// initialization. 4389 static ImplicitConversionSequence 4390 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4391 SourceLocation DeclLoc, 4392 bool SuppressUserConversions, 4393 bool AllowExplicit) { 4394 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4395 4396 // Most paths end in a failed conversion. 4397 ImplicitConversionSequence ICS; 4398 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4399 4400 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4401 QualType T2 = Init->getType(); 4402 4403 // If the initializer is the address of an overloaded function, try 4404 // to resolve the overloaded function. If all goes well, T2 is the 4405 // type of the resulting function. 4406 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4407 DeclAccessPair Found; 4408 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4409 false, Found)) 4410 T2 = Fn->getType(); 4411 } 4412 4413 // Compute some basic properties of the types and the initializer. 4414 bool isRValRef = DeclType->isRValueReferenceType(); 4415 bool DerivedToBase = false; 4416 bool ObjCConversion = false; 4417 bool ObjCLifetimeConversion = false; 4418 Expr::Classification InitCategory = Init->Classify(S.Context); 4419 Sema::ReferenceCompareResult RefRelationship 4420 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4421 ObjCConversion, ObjCLifetimeConversion); 4422 4423 4424 // C++0x [dcl.init.ref]p5: 4425 // A reference to type "cv1 T1" is initialized by an expression 4426 // of type "cv2 T2" as follows: 4427 4428 // -- If reference is an lvalue reference and the initializer expression 4429 if (!isRValRef) { 4430 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4431 // reference-compatible with "cv2 T2," or 4432 // 4433 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4434 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4435 // C++ [over.ics.ref]p1: 4436 // When a parameter of reference type binds directly (8.5.3) 4437 // to an argument expression, the implicit conversion sequence 4438 // is the identity conversion, unless the argument expression 4439 // has a type that is a derived class of the parameter type, 4440 // in which case the implicit conversion sequence is a 4441 // derived-to-base Conversion (13.3.3.1). 4442 ICS.setStandard(); 4443 ICS.Standard.First = ICK_Identity; 4444 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4445 : ObjCConversion? ICK_Compatible_Conversion 4446 : ICK_Identity; 4447 ICS.Standard.Third = ICK_Identity; 4448 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4449 ICS.Standard.setToType(0, T2); 4450 ICS.Standard.setToType(1, T1); 4451 ICS.Standard.setToType(2, T1); 4452 ICS.Standard.ReferenceBinding = true; 4453 ICS.Standard.DirectBinding = true; 4454 ICS.Standard.IsLvalueReference = !isRValRef; 4455 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4456 ICS.Standard.BindsToRvalue = false; 4457 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4458 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4459 ICS.Standard.CopyConstructor = nullptr; 4460 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4461 4462 // Nothing more to do: the inaccessibility/ambiguity check for 4463 // derived-to-base conversions is suppressed when we're 4464 // computing the implicit conversion sequence (C++ 4465 // [over.best.ics]p2). 4466 return ICS; 4467 } 4468 4469 // -- has a class type (i.e., T2 is a class type), where T1 is 4470 // not reference-related to T2, and can be implicitly 4471 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4472 // is reference-compatible with "cv3 T3" 92) (this 4473 // conversion is selected by enumerating the applicable 4474 // conversion functions (13.3.1.6) and choosing the best 4475 // one through overload resolution (13.3)), 4476 if (!SuppressUserConversions && T2->isRecordType() && 4477 S.isCompleteType(DeclLoc, T2) && 4478 RefRelationship == Sema::Ref_Incompatible) { 4479 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4480 Init, T2, /*AllowRvalues=*/false, 4481 AllowExplicit)) 4482 return ICS; 4483 } 4484 } 4485 4486 // -- Otherwise, the reference shall be an lvalue reference to a 4487 // non-volatile const type (i.e., cv1 shall be const), or the reference 4488 // shall be an rvalue reference. 4489 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4490 return ICS; 4491 4492 // -- If the initializer expression 4493 // 4494 // -- is an xvalue, class prvalue, array prvalue or function 4495 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4496 if (RefRelationship == Sema::Ref_Compatible && 4497 (InitCategory.isXValue() || 4498 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4499 (InitCategory.isLValue() && T2->isFunctionType()))) { 4500 ICS.setStandard(); 4501 ICS.Standard.First = ICK_Identity; 4502 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4503 : ObjCConversion? ICK_Compatible_Conversion 4504 : ICK_Identity; 4505 ICS.Standard.Third = ICK_Identity; 4506 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4507 ICS.Standard.setToType(0, T2); 4508 ICS.Standard.setToType(1, T1); 4509 ICS.Standard.setToType(2, T1); 4510 ICS.Standard.ReferenceBinding = true; 4511 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4512 // binding unless we're binding to a class prvalue. 4513 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4514 // allow the use of rvalue references in C++98/03 for the benefit of 4515 // standard library implementors; therefore, we need the xvalue check here. 4516 ICS.Standard.DirectBinding = 4517 S.getLangOpts().CPlusPlus11 || 4518 !(InitCategory.isPRValue() || T2->isRecordType()); 4519 ICS.Standard.IsLvalueReference = !isRValRef; 4520 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4521 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4522 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4523 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4524 ICS.Standard.CopyConstructor = nullptr; 4525 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4526 return ICS; 4527 } 4528 4529 // -- has a class type (i.e., T2 is a class type), where T1 is not 4530 // reference-related to T2, and can be implicitly converted to 4531 // an xvalue, class prvalue, or function lvalue of type 4532 // "cv3 T3", where "cv1 T1" is reference-compatible with 4533 // "cv3 T3", 4534 // 4535 // then the reference is bound to the value of the initializer 4536 // expression in the first case and to the result of the conversion 4537 // in the second case (or, in either case, to an appropriate base 4538 // class subobject). 4539 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4540 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4541 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4542 Init, T2, /*AllowRvalues=*/true, 4543 AllowExplicit)) { 4544 // In the second case, if the reference is an rvalue reference 4545 // and the second standard conversion sequence of the 4546 // user-defined conversion sequence includes an lvalue-to-rvalue 4547 // conversion, the program is ill-formed. 4548 if (ICS.isUserDefined() && isRValRef && 4549 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4550 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4551 4552 return ICS; 4553 } 4554 4555 // A temporary of function type cannot be created; don't even try. 4556 if (T1->isFunctionType()) 4557 return ICS; 4558 4559 // -- Otherwise, a temporary of type "cv1 T1" is created and 4560 // initialized from the initializer expression using the 4561 // rules for a non-reference copy initialization (8.5). The 4562 // reference is then bound to the temporary. If T1 is 4563 // reference-related to T2, cv1 must be the same 4564 // cv-qualification as, or greater cv-qualification than, 4565 // cv2; otherwise, the program is ill-formed. 4566 if (RefRelationship == Sema::Ref_Related) { 4567 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4568 // we would be reference-compatible or reference-compatible with 4569 // added qualification. But that wasn't the case, so the reference 4570 // initialization fails. 4571 // 4572 // Note that we only want to check address spaces and cvr-qualifiers here. 4573 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4574 Qualifiers T1Quals = T1.getQualifiers(); 4575 Qualifiers T2Quals = T2.getQualifiers(); 4576 T1Quals.removeObjCGCAttr(); 4577 T1Quals.removeObjCLifetime(); 4578 T2Quals.removeObjCGCAttr(); 4579 T2Quals.removeObjCLifetime(); 4580 // MS compiler ignores __unaligned qualifier for references; do the same. 4581 T1Quals.removeUnaligned(); 4582 T2Quals.removeUnaligned(); 4583 if (!T1Quals.compatiblyIncludes(T2Quals)) 4584 return ICS; 4585 } 4586 4587 // If at least one of the types is a class type, the types are not 4588 // related, and we aren't allowed any user conversions, the 4589 // reference binding fails. This case is important for breaking 4590 // recursion, since TryImplicitConversion below will attempt to 4591 // create a temporary through the use of a copy constructor. 4592 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4593 (T1->isRecordType() || T2->isRecordType())) 4594 return ICS; 4595 4596 // If T1 is reference-related to T2 and the reference is an rvalue 4597 // reference, the initializer expression shall not be an lvalue. 4598 if (RefRelationship >= Sema::Ref_Related && 4599 isRValRef && Init->Classify(S.Context).isLValue()) 4600 return ICS; 4601 4602 // C++ [over.ics.ref]p2: 4603 // When a parameter of reference type is not bound directly to 4604 // an argument expression, the conversion sequence is the one 4605 // required to convert the argument expression to the 4606 // underlying type of the reference according to 4607 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4608 // to copy-initializing a temporary of the underlying type with 4609 // the argument expression. Any difference in top-level 4610 // cv-qualification is subsumed by the initialization itself 4611 // and does not constitute a conversion. 4612 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4613 /*AllowExplicit=*/false, 4614 /*InOverloadResolution=*/false, 4615 /*CStyle=*/false, 4616 /*AllowObjCWritebackConversion=*/false, 4617 /*AllowObjCConversionOnExplicit=*/false); 4618 4619 // Of course, that's still a reference binding. 4620 if (ICS.isStandard()) { 4621 ICS.Standard.ReferenceBinding = true; 4622 ICS.Standard.IsLvalueReference = !isRValRef; 4623 ICS.Standard.BindsToFunctionLvalue = false; 4624 ICS.Standard.BindsToRvalue = true; 4625 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4626 ICS.Standard.ObjCLifetimeConversionBinding = false; 4627 } else if (ICS.isUserDefined()) { 4628 const ReferenceType *LValRefType = 4629 ICS.UserDefined.ConversionFunction->getReturnType() 4630 ->getAs<LValueReferenceType>(); 4631 4632 // C++ [over.ics.ref]p3: 4633 // Except for an implicit object parameter, for which see 13.3.1, a 4634 // standard conversion sequence cannot be formed if it requires [...] 4635 // binding an rvalue reference to an lvalue other than a function 4636 // lvalue. 4637 // Note that the function case is not possible here. 4638 if (DeclType->isRValueReferenceType() && LValRefType) { 4639 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4640 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4641 // reference to an rvalue! 4642 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4643 return ICS; 4644 } 4645 4646 ICS.UserDefined.After.ReferenceBinding = true; 4647 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4648 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4649 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4650 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4651 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4652 } 4653 4654 return ICS; 4655 } 4656 4657 static ImplicitConversionSequence 4658 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4659 bool SuppressUserConversions, 4660 bool InOverloadResolution, 4661 bool AllowObjCWritebackConversion, 4662 bool AllowExplicit = false); 4663 4664 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4665 /// initializer list From. 4666 static ImplicitConversionSequence 4667 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4668 bool SuppressUserConversions, 4669 bool InOverloadResolution, 4670 bool AllowObjCWritebackConversion) { 4671 // C++11 [over.ics.list]p1: 4672 // When an argument is an initializer list, it is not an expression and 4673 // special rules apply for converting it to a parameter type. 4674 4675 ImplicitConversionSequence Result; 4676 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4677 4678 // We need a complete type for what follows. Incomplete types can never be 4679 // initialized from init lists. 4680 if (!S.isCompleteType(From->getLocStart(), ToType)) 4681 return Result; 4682 4683 // Per DR1467: 4684 // If the parameter type is a class X and the initializer list has a single 4685 // element of type cv U, where U is X or a class derived from X, the 4686 // implicit conversion sequence is the one required to convert the element 4687 // to the parameter type. 4688 // 4689 // Otherwise, if the parameter type is a character array [... ] 4690 // and the initializer list has a single element that is an 4691 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4692 // implicit conversion sequence is the identity conversion. 4693 if (From->getNumInits() == 1) { 4694 if (ToType->isRecordType()) { 4695 QualType InitType = From->getInit(0)->getType(); 4696 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4697 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4698 return TryCopyInitialization(S, From->getInit(0), ToType, 4699 SuppressUserConversions, 4700 InOverloadResolution, 4701 AllowObjCWritebackConversion); 4702 } 4703 // FIXME: Check the other conditions here: array of character type, 4704 // initializer is a string literal. 4705 if (ToType->isArrayType()) { 4706 InitializedEntity Entity = 4707 InitializedEntity::InitializeParameter(S.Context, ToType, 4708 /*Consumed=*/false); 4709 if (S.CanPerformCopyInitialization(Entity, From)) { 4710 Result.setStandard(); 4711 Result.Standard.setAsIdentityConversion(); 4712 Result.Standard.setFromType(ToType); 4713 Result.Standard.setAllToTypes(ToType); 4714 return Result; 4715 } 4716 } 4717 } 4718 4719 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4720 // C++11 [over.ics.list]p2: 4721 // If the parameter type is std::initializer_list<X> or "array of X" and 4722 // all the elements can be implicitly converted to X, the implicit 4723 // conversion sequence is the worst conversion necessary to convert an 4724 // element of the list to X. 4725 // 4726 // C++14 [over.ics.list]p3: 4727 // Otherwise, if the parameter type is "array of N X", if the initializer 4728 // list has exactly N elements or if it has fewer than N elements and X is 4729 // default-constructible, and if all the elements of the initializer list 4730 // can be implicitly converted to X, the implicit conversion sequence is 4731 // the worst conversion necessary to convert an element of the list to X. 4732 // 4733 // FIXME: We're missing a lot of these checks. 4734 bool toStdInitializerList = false; 4735 QualType X; 4736 if (ToType->isArrayType()) 4737 X = S.Context.getAsArrayType(ToType)->getElementType(); 4738 else 4739 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4740 if (!X.isNull()) { 4741 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4742 Expr *Init = From->getInit(i); 4743 ImplicitConversionSequence ICS = 4744 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4745 InOverloadResolution, 4746 AllowObjCWritebackConversion); 4747 // If a single element isn't convertible, fail. 4748 if (ICS.isBad()) { 4749 Result = ICS; 4750 break; 4751 } 4752 // Otherwise, look for the worst conversion. 4753 if (Result.isBad() || 4754 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4755 Result) == 4756 ImplicitConversionSequence::Worse) 4757 Result = ICS; 4758 } 4759 4760 // For an empty list, we won't have computed any conversion sequence. 4761 // Introduce the identity conversion sequence. 4762 if (From->getNumInits() == 0) { 4763 Result.setStandard(); 4764 Result.Standard.setAsIdentityConversion(); 4765 Result.Standard.setFromType(ToType); 4766 Result.Standard.setAllToTypes(ToType); 4767 } 4768 4769 Result.setStdInitializerListElement(toStdInitializerList); 4770 return Result; 4771 } 4772 4773 // C++14 [over.ics.list]p4: 4774 // C++11 [over.ics.list]p3: 4775 // Otherwise, if the parameter is a non-aggregate class X and overload 4776 // resolution chooses a single best constructor [...] the implicit 4777 // conversion sequence is a user-defined conversion sequence. If multiple 4778 // constructors are viable but none is better than the others, the 4779 // implicit conversion sequence is a user-defined conversion sequence. 4780 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4781 // This function can deal with initializer lists. 4782 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4783 /*AllowExplicit=*/false, 4784 InOverloadResolution, /*CStyle=*/false, 4785 AllowObjCWritebackConversion, 4786 /*AllowObjCConversionOnExplicit=*/false); 4787 } 4788 4789 // C++14 [over.ics.list]p5: 4790 // C++11 [over.ics.list]p4: 4791 // Otherwise, if the parameter has an aggregate type which can be 4792 // initialized from the initializer list [...] the implicit conversion 4793 // sequence is a user-defined conversion sequence. 4794 if (ToType->isAggregateType()) { 4795 // Type is an aggregate, argument is an init list. At this point it comes 4796 // down to checking whether the initialization works. 4797 // FIXME: Find out whether this parameter is consumed or not. 4798 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4799 // need to call into the initialization code here; overload resolution 4800 // should not be doing that. 4801 InitializedEntity Entity = 4802 InitializedEntity::InitializeParameter(S.Context, ToType, 4803 /*Consumed=*/false); 4804 if (S.CanPerformCopyInitialization(Entity, From)) { 4805 Result.setUserDefined(); 4806 Result.UserDefined.Before.setAsIdentityConversion(); 4807 // Initializer lists don't have a type. 4808 Result.UserDefined.Before.setFromType(QualType()); 4809 Result.UserDefined.Before.setAllToTypes(QualType()); 4810 4811 Result.UserDefined.After.setAsIdentityConversion(); 4812 Result.UserDefined.After.setFromType(ToType); 4813 Result.UserDefined.After.setAllToTypes(ToType); 4814 Result.UserDefined.ConversionFunction = nullptr; 4815 } 4816 return Result; 4817 } 4818 4819 // C++14 [over.ics.list]p6: 4820 // C++11 [over.ics.list]p5: 4821 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4822 if (ToType->isReferenceType()) { 4823 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4824 // mention initializer lists in any way. So we go by what list- 4825 // initialization would do and try to extrapolate from that. 4826 4827 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4828 4829 // If the initializer list has a single element that is reference-related 4830 // to the parameter type, we initialize the reference from that. 4831 if (From->getNumInits() == 1) { 4832 Expr *Init = From->getInit(0); 4833 4834 QualType T2 = Init->getType(); 4835 4836 // If the initializer is the address of an overloaded function, try 4837 // to resolve the overloaded function. If all goes well, T2 is the 4838 // type of the resulting function. 4839 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4840 DeclAccessPair Found; 4841 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4842 Init, ToType, false, Found)) 4843 T2 = Fn->getType(); 4844 } 4845 4846 // Compute some basic properties of the types and the initializer. 4847 bool dummy1 = false; 4848 bool dummy2 = false; 4849 bool dummy3 = false; 4850 Sema::ReferenceCompareResult RefRelationship 4851 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4852 dummy2, dummy3); 4853 4854 if (RefRelationship >= Sema::Ref_Related) { 4855 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4856 SuppressUserConversions, 4857 /*AllowExplicit=*/false); 4858 } 4859 } 4860 4861 // Otherwise, we bind the reference to a temporary created from the 4862 // initializer list. 4863 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4864 InOverloadResolution, 4865 AllowObjCWritebackConversion); 4866 if (Result.isFailure()) 4867 return Result; 4868 assert(!Result.isEllipsis() && 4869 "Sub-initialization cannot result in ellipsis conversion."); 4870 4871 // Can we even bind to a temporary? 4872 if (ToType->isRValueReferenceType() || 4873 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4874 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4875 Result.UserDefined.After; 4876 SCS.ReferenceBinding = true; 4877 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4878 SCS.BindsToRvalue = true; 4879 SCS.BindsToFunctionLvalue = false; 4880 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4881 SCS.ObjCLifetimeConversionBinding = false; 4882 } else 4883 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4884 From, ToType); 4885 return Result; 4886 } 4887 4888 // C++14 [over.ics.list]p7: 4889 // C++11 [over.ics.list]p6: 4890 // Otherwise, if the parameter type is not a class: 4891 if (!ToType->isRecordType()) { 4892 // - if the initializer list has one element that is not itself an 4893 // initializer list, the implicit conversion sequence is the one 4894 // required to convert the element to the parameter type. 4895 unsigned NumInits = From->getNumInits(); 4896 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4897 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4898 SuppressUserConversions, 4899 InOverloadResolution, 4900 AllowObjCWritebackConversion); 4901 // - if the initializer list has no elements, the implicit conversion 4902 // sequence is the identity conversion. 4903 else if (NumInits == 0) { 4904 Result.setStandard(); 4905 Result.Standard.setAsIdentityConversion(); 4906 Result.Standard.setFromType(ToType); 4907 Result.Standard.setAllToTypes(ToType); 4908 } 4909 return Result; 4910 } 4911 4912 // C++14 [over.ics.list]p8: 4913 // C++11 [over.ics.list]p7: 4914 // In all cases other than those enumerated above, no conversion is possible 4915 return Result; 4916 } 4917 4918 /// TryCopyInitialization - Try to copy-initialize a value of type 4919 /// ToType from the expression From. Return the implicit conversion 4920 /// sequence required to pass this argument, which may be a bad 4921 /// conversion sequence (meaning that the argument cannot be passed to 4922 /// a parameter of this type). If @p SuppressUserConversions, then we 4923 /// do not permit any user-defined conversion sequences. 4924 static ImplicitConversionSequence 4925 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4926 bool SuppressUserConversions, 4927 bool InOverloadResolution, 4928 bool AllowObjCWritebackConversion, 4929 bool AllowExplicit) { 4930 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4931 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4932 InOverloadResolution,AllowObjCWritebackConversion); 4933 4934 if (ToType->isReferenceType()) 4935 return TryReferenceInit(S, From, ToType, 4936 /*FIXME:*/From->getLocStart(), 4937 SuppressUserConversions, 4938 AllowExplicit); 4939 4940 return TryImplicitConversion(S, From, ToType, 4941 SuppressUserConversions, 4942 /*AllowExplicit=*/false, 4943 InOverloadResolution, 4944 /*CStyle=*/false, 4945 AllowObjCWritebackConversion, 4946 /*AllowObjCConversionOnExplicit=*/false); 4947 } 4948 4949 static bool TryCopyInitialization(const CanQualType FromQTy, 4950 const CanQualType ToQTy, 4951 Sema &S, 4952 SourceLocation Loc, 4953 ExprValueKind FromVK) { 4954 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4955 ImplicitConversionSequence ICS = 4956 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4957 4958 return !ICS.isBad(); 4959 } 4960 4961 /// TryObjectArgumentInitialization - Try to initialize the object 4962 /// parameter of the given member function (@c Method) from the 4963 /// expression @p From. 4964 static ImplicitConversionSequence 4965 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4966 Expr::Classification FromClassification, 4967 CXXMethodDecl *Method, 4968 CXXRecordDecl *ActingContext) { 4969 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4970 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4971 // const volatile object. 4972 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4973 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4974 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4975 4976 // Set up the conversion sequence as a "bad" conversion, to allow us 4977 // to exit early. 4978 ImplicitConversionSequence ICS; 4979 4980 // We need to have an object of class type. 4981 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4982 FromType = PT->getPointeeType(); 4983 4984 // When we had a pointer, it's implicitly dereferenced, so we 4985 // better have an lvalue. 4986 assert(FromClassification.isLValue()); 4987 } 4988 4989 assert(FromType->isRecordType()); 4990 4991 // C++0x [over.match.funcs]p4: 4992 // For non-static member functions, the type of the implicit object 4993 // parameter is 4994 // 4995 // - "lvalue reference to cv X" for functions declared without a 4996 // ref-qualifier or with the & ref-qualifier 4997 // - "rvalue reference to cv X" for functions declared with the && 4998 // ref-qualifier 4999 // 5000 // where X is the class of which the function is a member and cv is the 5001 // cv-qualification on the member function declaration. 5002 // 5003 // However, when finding an implicit conversion sequence for the argument, we 5004 // are not allowed to perform user-defined conversions 5005 // (C++ [over.match.funcs]p5). We perform a simplified version of 5006 // reference binding here, that allows class rvalues to bind to 5007 // non-constant references. 5008 5009 // First check the qualifiers. 5010 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5011 if (ImplicitParamType.getCVRQualifiers() 5012 != FromTypeCanon.getLocalCVRQualifiers() && 5013 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5014 ICS.setBad(BadConversionSequence::bad_qualifiers, 5015 FromType, ImplicitParamType); 5016 return ICS; 5017 } 5018 5019 // Check that we have either the same type or a derived type. It 5020 // affects the conversion rank. 5021 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5022 ImplicitConversionKind SecondKind; 5023 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5024 SecondKind = ICK_Identity; 5025 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5026 SecondKind = ICK_Derived_To_Base; 5027 else { 5028 ICS.setBad(BadConversionSequence::unrelated_class, 5029 FromType, ImplicitParamType); 5030 return ICS; 5031 } 5032 5033 // Check the ref-qualifier. 5034 switch (Method->getRefQualifier()) { 5035 case RQ_None: 5036 // Do nothing; we don't care about lvalueness or rvalueness. 5037 break; 5038 5039 case RQ_LValue: 5040 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 5041 // non-const lvalue reference cannot bind to an rvalue 5042 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5043 ImplicitParamType); 5044 return ICS; 5045 } 5046 break; 5047 5048 case RQ_RValue: 5049 if (!FromClassification.isRValue()) { 5050 // rvalue reference cannot bind to an lvalue 5051 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5052 ImplicitParamType); 5053 return ICS; 5054 } 5055 break; 5056 } 5057 5058 // Success. Mark this as a reference binding. 5059 ICS.setStandard(); 5060 ICS.Standard.setAsIdentityConversion(); 5061 ICS.Standard.Second = SecondKind; 5062 ICS.Standard.setFromType(FromType); 5063 ICS.Standard.setAllToTypes(ImplicitParamType); 5064 ICS.Standard.ReferenceBinding = true; 5065 ICS.Standard.DirectBinding = true; 5066 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5067 ICS.Standard.BindsToFunctionLvalue = false; 5068 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5069 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5070 = (Method->getRefQualifier() == RQ_None); 5071 return ICS; 5072 } 5073 5074 /// PerformObjectArgumentInitialization - Perform initialization of 5075 /// the implicit object parameter for the given Method with the given 5076 /// expression. 5077 ExprResult 5078 Sema::PerformObjectArgumentInitialization(Expr *From, 5079 NestedNameSpecifier *Qualifier, 5080 NamedDecl *FoundDecl, 5081 CXXMethodDecl *Method) { 5082 QualType FromRecordType, DestType; 5083 QualType ImplicitParamRecordType = 5084 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5085 5086 Expr::Classification FromClassification; 5087 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5088 FromRecordType = PT->getPointeeType(); 5089 DestType = Method->getThisType(Context); 5090 FromClassification = Expr::Classification::makeSimpleLValue(); 5091 } else { 5092 FromRecordType = From->getType(); 5093 DestType = ImplicitParamRecordType; 5094 FromClassification = From->Classify(Context); 5095 } 5096 5097 // Note that we always use the true parent context when performing 5098 // the actual argument initialization. 5099 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5100 *this, From->getLocStart(), From->getType(), FromClassification, Method, 5101 Method->getParent()); 5102 if (ICS.isBad()) { 5103 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 5104 Qualifiers FromQs = FromRecordType.getQualifiers(); 5105 Qualifiers ToQs = DestType.getQualifiers(); 5106 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5107 if (CVR) { 5108 Diag(From->getLocStart(), 5109 diag::err_member_function_call_bad_cvr) 5110 << Method->getDeclName() << FromRecordType << (CVR - 1) 5111 << From->getSourceRange(); 5112 Diag(Method->getLocation(), diag::note_previous_decl) 5113 << Method->getDeclName(); 5114 return ExprError(); 5115 } 5116 } 5117 5118 return Diag(From->getLocStart(), 5119 diag::err_implicit_object_parameter_init) 5120 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5121 } 5122 5123 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5124 ExprResult FromRes = 5125 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5126 if (FromRes.isInvalid()) 5127 return ExprError(); 5128 From = FromRes.get(); 5129 } 5130 5131 if (!Context.hasSameType(From->getType(), DestType)) 5132 From = ImpCastExprToType(From, DestType, CK_NoOp, 5133 From->getValueKind()).get(); 5134 return From; 5135 } 5136 5137 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5138 /// expression From to bool (C++0x [conv]p3). 5139 static ImplicitConversionSequence 5140 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5141 return TryImplicitConversion(S, From, S.Context.BoolTy, 5142 /*SuppressUserConversions=*/false, 5143 /*AllowExplicit=*/true, 5144 /*InOverloadResolution=*/false, 5145 /*CStyle=*/false, 5146 /*AllowObjCWritebackConversion=*/false, 5147 /*AllowObjCConversionOnExplicit=*/false); 5148 } 5149 5150 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5151 /// of the expression From to bool (C++0x [conv]p3). 5152 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5153 if (checkPlaceholderForOverload(*this, From)) 5154 return ExprError(); 5155 5156 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5157 if (!ICS.isBad()) 5158 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5159 5160 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5161 return Diag(From->getLocStart(), 5162 diag::err_typecheck_bool_condition) 5163 << From->getType() << From->getSourceRange(); 5164 return ExprError(); 5165 } 5166 5167 /// Check that the specified conversion is permitted in a converted constant 5168 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5169 /// is acceptable. 5170 static bool CheckConvertedConstantConversions(Sema &S, 5171 StandardConversionSequence &SCS) { 5172 // Since we know that the target type is an integral or unscoped enumeration 5173 // type, most conversion kinds are impossible. All possible First and Third 5174 // conversions are fine. 5175 switch (SCS.Second) { 5176 case ICK_Identity: 5177 case ICK_Function_Conversion: 5178 case ICK_Integral_Promotion: 5179 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5180 return true; 5181 5182 case ICK_Boolean_Conversion: 5183 // Conversion from an integral or unscoped enumeration type to bool is 5184 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5185 // conversion, so we allow it in a converted constant expression. 5186 // 5187 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5188 // a lot of popular code. We should at least add a warning for this 5189 // (non-conforming) extension. 5190 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5191 SCS.getToType(2)->isBooleanType(); 5192 5193 case ICK_Pointer_Conversion: 5194 case ICK_Pointer_Member: 5195 // C++1z: null pointer conversions and null member pointer conversions are 5196 // only permitted if the source type is std::nullptr_t. 5197 return SCS.getFromType()->isNullPtrType(); 5198 5199 case ICK_Floating_Promotion: 5200 case ICK_Complex_Promotion: 5201 case ICK_Floating_Conversion: 5202 case ICK_Complex_Conversion: 5203 case ICK_Floating_Integral: 5204 case ICK_Compatible_Conversion: 5205 case ICK_Derived_To_Base: 5206 case ICK_Vector_Conversion: 5207 case ICK_Vector_Splat: 5208 case ICK_Complex_Real: 5209 case ICK_Block_Pointer_Conversion: 5210 case ICK_TransparentUnionConversion: 5211 case ICK_Writeback_Conversion: 5212 case ICK_Zero_Event_Conversion: 5213 case ICK_C_Only_Conversion: 5214 case ICK_Incompatible_Pointer_Conversion: 5215 return false; 5216 5217 case ICK_Lvalue_To_Rvalue: 5218 case ICK_Array_To_Pointer: 5219 case ICK_Function_To_Pointer: 5220 llvm_unreachable("found a first conversion kind in Second"); 5221 5222 case ICK_Qualification: 5223 llvm_unreachable("found a third conversion kind in Second"); 5224 5225 case ICK_Num_Conversion_Kinds: 5226 break; 5227 } 5228 5229 llvm_unreachable("unknown conversion kind"); 5230 } 5231 5232 /// CheckConvertedConstantExpression - Check that the expression From is a 5233 /// converted constant expression of type T, perform the conversion and produce 5234 /// the converted expression, per C++11 [expr.const]p3. 5235 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5236 QualType T, APValue &Value, 5237 Sema::CCEKind CCE, 5238 bool RequireInt) { 5239 assert(S.getLangOpts().CPlusPlus11 && 5240 "converted constant expression outside C++11"); 5241 5242 if (checkPlaceholderForOverload(S, From)) 5243 return ExprError(); 5244 5245 // C++1z [expr.const]p3: 5246 // A converted constant expression of type T is an expression, 5247 // implicitly converted to type T, where the converted 5248 // expression is a constant expression and the implicit conversion 5249 // sequence contains only [... list of conversions ...]. 5250 // C++1z [stmt.if]p2: 5251 // If the if statement is of the form if constexpr, the value of the 5252 // condition shall be a contextually converted constant expression of type 5253 // bool. 5254 ImplicitConversionSequence ICS = 5255 CCE == Sema::CCEK_ConstexprIf 5256 ? TryContextuallyConvertToBool(S, From) 5257 : TryCopyInitialization(S, From, T, 5258 /*SuppressUserConversions=*/false, 5259 /*InOverloadResolution=*/false, 5260 /*AllowObjcWritebackConversion=*/false, 5261 /*AllowExplicit=*/false); 5262 StandardConversionSequence *SCS = nullptr; 5263 switch (ICS.getKind()) { 5264 case ImplicitConversionSequence::StandardConversion: 5265 SCS = &ICS.Standard; 5266 break; 5267 case ImplicitConversionSequence::UserDefinedConversion: 5268 // We are converting to a non-class type, so the Before sequence 5269 // must be trivial. 5270 SCS = &ICS.UserDefined.After; 5271 break; 5272 case ImplicitConversionSequence::AmbiguousConversion: 5273 case ImplicitConversionSequence::BadConversion: 5274 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5275 return S.Diag(From->getLocStart(), 5276 diag::err_typecheck_converted_constant_expression) 5277 << From->getType() << From->getSourceRange() << T; 5278 return ExprError(); 5279 5280 case ImplicitConversionSequence::EllipsisConversion: 5281 llvm_unreachable("ellipsis conversion in converted constant expression"); 5282 } 5283 5284 // Check that we would only use permitted conversions. 5285 if (!CheckConvertedConstantConversions(S, *SCS)) { 5286 return S.Diag(From->getLocStart(), 5287 diag::err_typecheck_converted_constant_expression_disallowed) 5288 << From->getType() << From->getSourceRange() << T; 5289 } 5290 // [...] and where the reference binding (if any) binds directly. 5291 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5292 return S.Diag(From->getLocStart(), 5293 diag::err_typecheck_converted_constant_expression_indirect) 5294 << From->getType() << From->getSourceRange() << T; 5295 } 5296 5297 ExprResult Result = 5298 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5299 if (Result.isInvalid()) 5300 return Result; 5301 5302 // Check for a narrowing implicit conversion. 5303 APValue PreNarrowingValue; 5304 QualType PreNarrowingType; 5305 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5306 PreNarrowingType)) { 5307 case NK_Dependent_Narrowing: 5308 // Implicit conversion to a narrower type, but the expression is 5309 // value-dependent so we can't tell whether it's actually narrowing. 5310 case NK_Variable_Narrowing: 5311 // Implicit conversion to a narrower type, and the value is not a constant 5312 // expression. We'll diagnose this in a moment. 5313 case NK_Not_Narrowing: 5314 break; 5315 5316 case NK_Constant_Narrowing: 5317 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5318 << CCE << /*Constant*/1 5319 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5320 break; 5321 5322 case NK_Type_Narrowing: 5323 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5324 << CCE << /*Constant*/0 << From->getType() << T; 5325 break; 5326 } 5327 5328 if (Result.get()->isValueDependent()) { 5329 Value = APValue(); 5330 return Result; 5331 } 5332 5333 // Check the expression is a constant expression. 5334 SmallVector<PartialDiagnosticAt, 8> Notes; 5335 Expr::EvalResult Eval; 5336 Eval.Diag = &Notes; 5337 5338 if ((T->isReferenceType() 5339 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5340 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5341 (RequireInt && !Eval.Val.isInt())) { 5342 // The expression can't be folded, so we can't keep it at this position in 5343 // the AST. 5344 Result = ExprError(); 5345 } else { 5346 Value = Eval.Val; 5347 5348 if (Notes.empty()) { 5349 // It's a constant expression. 5350 return Result; 5351 } 5352 } 5353 5354 // It's not a constant expression. Produce an appropriate diagnostic. 5355 if (Notes.size() == 1 && 5356 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5357 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5358 else { 5359 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5360 << CCE << From->getSourceRange(); 5361 for (unsigned I = 0; I < Notes.size(); ++I) 5362 S.Diag(Notes[I].first, Notes[I].second); 5363 } 5364 return ExprError(); 5365 } 5366 5367 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5368 APValue &Value, CCEKind CCE) { 5369 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5370 } 5371 5372 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5373 llvm::APSInt &Value, 5374 CCEKind CCE) { 5375 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5376 5377 APValue V; 5378 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5379 if (!R.isInvalid()) 5380 Value = V.getInt(); 5381 return R; 5382 } 5383 5384 5385 /// dropPointerConversions - If the given standard conversion sequence 5386 /// involves any pointer conversions, remove them. This may change 5387 /// the result type of the conversion sequence. 5388 static void dropPointerConversion(StandardConversionSequence &SCS) { 5389 if (SCS.Second == ICK_Pointer_Conversion) { 5390 SCS.Second = ICK_Identity; 5391 SCS.Third = ICK_Identity; 5392 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5393 } 5394 } 5395 5396 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5397 /// convert the expression From to an Objective-C pointer type. 5398 static ImplicitConversionSequence 5399 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5400 // Do an implicit conversion to 'id'. 5401 QualType Ty = S.Context.getObjCIdType(); 5402 ImplicitConversionSequence ICS 5403 = TryImplicitConversion(S, From, Ty, 5404 // FIXME: Are these flags correct? 5405 /*SuppressUserConversions=*/false, 5406 /*AllowExplicit=*/true, 5407 /*InOverloadResolution=*/false, 5408 /*CStyle=*/false, 5409 /*AllowObjCWritebackConversion=*/false, 5410 /*AllowObjCConversionOnExplicit=*/true); 5411 5412 // Strip off any final conversions to 'id'. 5413 switch (ICS.getKind()) { 5414 case ImplicitConversionSequence::BadConversion: 5415 case ImplicitConversionSequence::AmbiguousConversion: 5416 case ImplicitConversionSequence::EllipsisConversion: 5417 break; 5418 5419 case ImplicitConversionSequence::UserDefinedConversion: 5420 dropPointerConversion(ICS.UserDefined.After); 5421 break; 5422 5423 case ImplicitConversionSequence::StandardConversion: 5424 dropPointerConversion(ICS.Standard); 5425 break; 5426 } 5427 5428 return ICS; 5429 } 5430 5431 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5432 /// conversion of the expression From to an Objective-C pointer type. 5433 /// Returns a valid but null ExprResult if no conversion sequence exists. 5434 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5435 if (checkPlaceholderForOverload(*this, From)) 5436 return ExprError(); 5437 5438 QualType Ty = Context.getObjCIdType(); 5439 ImplicitConversionSequence ICS = 5440 TryContextuallyConvertToObjCPointer(*this, From); 5441 if (!ICS.isBad()) 5442 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5443 return ExprResult(); 5444 } 5445 5446 /// Determine whether the provided type is an integral type, or an enumeration 5447 /// type of a permitted flavor. 5448 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5449 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5450 : T->isIntegralOrUnscopedEnumerationType(); 5451 } 5452 5453 static ExprResult 5454 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5455 Sema::ContextualImplicitConverter &Converter, 5456 QualType T, UnresolvedSetImpl &ViableConversions) { 5457 5458 if (Converter.Suppress) 5459 return ExprError(); 5460 5461 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5462 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5463 CXXConversionDecl *Conv = 5464 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5465 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5466 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5467 } 5468 return From; 5469 } 5470 5471 static bool 5472 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5473 Sema::ContextualImplicitConverter &Converter, 5474 QualType T, bool HadMultipleCandidates, 5475 UnresolvedSetImpl &ExplicitConversions) { 5476 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5477 DeclAccessPair Found = ExplicitConversions[0]; 5478 CXXConversionDecl *Conversion = 5479 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5480 5481 // The user probably meant to invoke the given explicit 5482 // conversion; use it. 5483 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5484 std::string TypeStr; 5485 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5486 5487 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5488 << FixItHint::CreateInsertion(From->getLocStart(), 5489 "static_cast<" + TypeStr + ">(") 5490 << FixItHint::CreateInsertion( 5491 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5492 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5493 5494 // If we aren't in a SFINAE context, build a call to the 5495 // explicit conversion function. 5496 if (SemaRef.isSFINAEContext()) 5497 return true; 5498 5499 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5500 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5501 HadMultipleCandidates); 5502 if (Result.isInvalid()) 5503 return true; 5504 // Record usage of conversion in an implicit cast. 5505 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5506 CK_UserDefinedConversion, Result.get(), 5507 nullptr, Result.get()->getValueKind()); 5508 } 5509 return false; 5510 } 5511 5512 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5513 Sema::ContextualImplicitConverter &Converter, 5514 QualType T, bool HadMultipleCandidates, 5515 DeclAccessPair &Found) { 5516 CXXConversionDecl *Conversion = 5517 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5518 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5519 5520 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5521 if (!Converter.SuppressConversion) { 5522 if (SemaRef.isSFINAEContext()) 5523 return true; 5524 5525 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5526 << From->getSourceRange(); 5527 } 5528 5529 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5530 HadMultipleCandidates); 5531 if (Result.isInvalid()) 5532 return true; 5533 // Record usage of conversion in an implicit cast. 5534 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5535 CK_UserDefinedConversion, Result.get(), 5536 nullptr, Result.get()->getValueKind()); 5537 return false; 5538 } 5539 5540 static ExprResult finishContextualImplicitConversion( 5541 Sema &SemaRef, SourceLocation Loc, Expr *From, 5542 Sema::ContextualImplicitConverter &Converter) { 5543 if (!Converter.match(From->getType()) && !Converter.Suppress) 5544 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5545 << From->getSourceRange(); 5546 5547 return SemaRef.DefaultLvalueConversion(From); 5548 } 5549 5550 static void 5551 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5552 UnresolvedSetImpl &ViableConversions, 5553 OverloadCandidateSet &CandidateSet) { 5554 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5555 DeclAccessPair FoundDecl = ViableConversions[I]; 5556 NamedDecl *D = FoundDecl.getDecl(); 5557 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5558 if (isa<UsingShadowDecl>(D)) 5559 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5560 5561 CXXConversionDecl *Conv; 5562 FunctionTemplateDecl *ConvTemplate; 5563 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5564 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5565 else 5566 Conv = cast<CXXConversionDecl>(D); 5567 5568 if (ConvTemplate) 5569 SemaRef.AddTemplateConversionCandidate( 5570 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5571 /*AllowObjCConversionOnExplicit=*/false); 5572 else 5573 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5574 ToType, CandidateSet, 5575 /*AllowObjCConversionOnExplicit=*/false); 5576 } 5577 } 5578 5579 /// \brief Attempt to convert the given expression to a type which is accepted 5580 /// by the given converter. 5581 /// 5582 /// This routine will attempt to convert an expression of class type to a 5583 /// type accepted by the specified converter. In C++11 and before, the class 5584 /// must have a single non-explicit conversion function converting to a matching 5585 /// type. In C++1y, there can be multiple such conversion functions, but only 5586 /// one target type. 5587 /// 5588 /// \param Loc The source location of the construct that requires the 5589 /// conversion. 5590 /// 5591 /// \param From The expression we're converting from. 5592 /// 5593 /// \param Converter Used to control and diagnose the conversion process. 5594 /// 5595 /// \returns The expression, converted to an integral or enumeration type if 5596 /// successful. 5597 ExprResult Sema::PerformContextualImplicitConversion( 5598 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5599 // We can't perform any more checking for type-dependent expressions. 5600 if (From->isTypeDependent()) 5601 return From; 5602 5603 // Process placeholders immediately. 5604 if (From->hasPlaceholderType()) { 5605 ExprResult result = CheckPlaceholderExpr(From); 5606 if (result.isInvalid()) 5607 return result; 5608 From = result.get(); 5609 } 5610 5611 // If the expression already has a matching type, we're golden. 5612 QualType T = From->getType(); 5613 if (Converter.match(T)) 5614 return DefaultLvalueConversion(From); 5615 5616 // FIXME: Check for missing '()' if T is a function type? 5617 5618 // We can only perform contextual implicit conversions on objects of class 5619 // type. 5620 const RecordType *RecordTy = T->getAs<RecordType>(); 5621 if (!RecordTy || !getLangOpts().CPlusPlus) { 5622 if (!Converter.Suppress) 5623 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5624 return From; 5625 } 5626 5627 // We must have a complete class type. 5628 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5629 ContextualImplicitConverter &Converter; 5630 Expr *From; 5631 5632 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5633 : Converter(Converter), From(From) {} 5634 5635 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5636 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5637 } 5638 } IncompleteDiagnoser(Converter, From); 5639 5640 if (Converter.Suppress ? !isCompleteType(Loc, T) 5641 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5642 return From; 5643 5644 // Look for a conversion to an integral or enumeration type. 5645 UnresolvedSet<4> 5646 ViableConversions; // These are *potentially* viable in C++1y. 5647 UnresolvedSet<4> ExplicitConversions; 5648 const auto &Conversions = 5649 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5650 5651 bool HadMultipleCandidates = 5652 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5653 5654 // To check that there is only one target type, in C++1y: 5655 QualType ToType; 5656 bool HasUniqueTargetType = true; 5657 5658 // Collect explicit or viable (potentially in C++1y) conversions. 5659 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5660 NamedDecl *D = (*I)->getUnderlyingDecl(); 5661 CXXConversionDecl *Conversion; 5662 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5663 if (ConvTemplate) { 5664 if (getLangOpts().CPlusPlus14) 5665 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5666 else 5667 continue; // C++11 does not consider conversion operator templates(?). 5668 } else 5669 Conversion = cast<CXXConversionDecl>(D); 5670 5671 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5672 "Conversion operator templates are considered potentially " 5673 "viable in C++1y"); 5674 5675 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5676 if (Converter.match(CurToType) || ConvTemplate) { 5677 5678 if (Conversion->isExplicit()) { 5679 // FIXME: For C++1y, do we need this restriction? 5680 // cf. diagnoseNoViableConversion() 5681 if (!ConvTemplate) 5682 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5683 } else { 5684 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5685 if (ToType.isNull()) 5686 ToType = CurToType.getUnqualifiedType(); 5687 else if (HasUniqueTargetType && 5688 (CurToType.getUnqualifiedType() != ToType)) 5689 HasUniqueTargetType = false; 5690 } 5691 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5692 } 5693 } 5694 } 5695 5696 if (getLangOpts().CPlusPlus14) { 5697 // C++1y [conv]p6: 5698 // ... An expression e of class type E appearing in such a context 5699 // is said to be contextually implicitly converted to a specified 5700 // type T and is well-formed if and only if e can be implicitly 5701 // converted to a type T that is determined as follows: E is searched 5702 // for conversion functions whose return type is cv T or reference to 5703 // cv T such that T is allowed by the context. There shall be 5704 // exactly one such T. 5705 5706 // If no unique T is found: 5707 if (ToType.isNull()) { 5708 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5709 HadMultipleCandidates, 5710 ExplicitConversions)) 5711 return ExprError(); 5712 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5713 } 5714 5715 // If more than one unique Ts are found: 5716 if (!HasUniqueTargetType) 5717 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5718 ViableConversions); 5719 5720 // If one unique T is found: 5721 // First, build a candidate set from the previously recorded 5722 // potentially viable conversions. 5723 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5724 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5725 CandidateSet); 5726 5727 // Then, perform overload resolution over the candidate set. 5728 OverloadCandidateSet::iterator Best; 5729 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5730 case OR_Success: { 5731 // Apply this conversion. 5732 DeclAccessPair Found = 5733 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5734 if (recordConversion(*this, Loc, From, Converter, T, 5735 HadMultipleCandidates, Found)) 5736 return ExprError(); 5737 break; 5738 } 5739 case OR_Ambiguous: 5740 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5741 ViableConversions); 5742 case OR_No_Viable_Function: 5743 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5744 HadMultipleCandidates, 5745 ExplicitConversions)) 5746 return ExprError(); 5747 // fall through 'OR_Deleted' case. 5748 case OR_Deleted: 5749 // We'll complain below about a non-integral condition type. 5750 break; 5751 } 5752 } else { 5753 switch (ViableConversions.size()) { 5754 case 0: { 5755 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5756 HadMultipleCandidates, 5757 ExplicitConversions)) 5758 return ExprError(); 5759 5760 // We'll complain below about a non-integral condition type. 5761 break; 5762 } 5763 case 1: { 5764 // Apply this conversion. 5765 DeclAccessPair Found = ViableConversions[0]; 5766 if (recordConversion(*this, Loc, From, Converter, T, 5767 HadMultipleCandidates, Found)) 5768 return ExprError(); 5769 break; 5770 } 5771 default: 5772 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5773 ViableConversions); 5774 } 5775 } 5776 5777 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5778 } 5779 5780 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5781 /// an acceptable non-member overloaded operator for a call whose 5782 /// arguments have types T1 (and, if non-empty, T2). This routine 5783 /// implements the check in C++ [over.match.oper]p3b2 concerning 5784 /// enumeration types. 5785 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5786 FunctionDecl *Fn, 5787 ArrayRef<Expr *> Args) { 5788 QualType T1 = Args[0]->getType(); 5789 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5790 5791 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5792 return true; 5793 5794 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5795 return true; 5796 5797 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5798 if (Proto->getNumParams() < 1) 5799 return false; 5800 5801 if (T1->isEnumeralType()) { 5802 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5803 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5804 return true; 5805 } 5806 5807 if (Proto->getNumParams() < 2) 5808 return false; 5809 5810 if (!T2.isNull() && T2->isEnumeralType()) { 5811 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5812 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5813 return true; 5814 } 5815 5816 return false; 5817 } 5818 5819 /// AddOverloadCandidate - Adds the given function to the set of 5820 /// candidate functions, using the given function call arguments. If 5821 /// @p SuppressUserConversions, then don't allow user-defined 5822 /// conversions via constructors or conversion operators. 5823 /// 5824 /// \param PartialOverloading true if we are performing "partial" overloading 5825 /// based on an incomplete set of function arguments. This feature is used by 5826 /// code completion. 5827 void 5828 Sema::AddOverloadCandidate(FunctionDecl *Function, 5829 DeclAccessPair FoundDecl, 5830 ArrayRef<Expr *> Args, 5831 OverloadCandidateSet &CandidateSet, 5832 bool SuppressUserConversions, 5833 bool PartialOverloading, 5834 bool AllowExplicit) { 5835 const FunctionProtoType *Proto 5836 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5837 assert(Proto && "Functions without a prototype cannot be overloaded"); 5838 assert(!Function->getDescribedFunctionTemplate() && 5839 "Use AddTemplateOverloadCandidate for function templates"); 5840 5841 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5842 if (!isa<CXXConstructorDecl>(Method)) { 5843 // If we get here, it's because we're calling a member function 5844 // that is named without a member access expression (e.g., 5845 // "this->f") that was either written explicitly or created 5846 // implicitly. This can happen with a qualified call to a member 5847 // function, e.g., X::f(). We use an empty type for the implied 5848 // object argument (C++ [over.call.func]p3), and the acting context 5849 // is irrelevant. 5850 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5851 QualType(), Expr::Classification::makeSimpleLValue(), 5852 Args, CandidateSet, SuppressUserConversions, 5853 PartialOverloading); 5854 return; 5855 } 5856 // We treat a constructor like a non-member function, since its object 5857 // argument doesn't participate in overload resolution. 5858 } 5859 5860 if (!CandidateSet.isNewCandidate(Function)) 5861 return; 5862 5863 // C++ [over.match.oper]p3: 5864 // if no operand has a class type, only those non-member functions in the 5865 // lookup set that have a first parameter of type T1 or "reference to 5866 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5867 // is a right operand) a second parameter of type T2 or "reference to 5868 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5869 // candidate functions. 5870 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5871 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5872 return; 5873 5874 // C++11 [class.copy]p11: [DR1402] 5875 // A defaulted move constructor that is defined as deleted is ignored by 5876 // overload resolution. 5877 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5878 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5879 Constructor->isMoveConstructor()) 5880 return; 5881 5882 // Overload resolution is always an unevaluated context. 5883 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5884 5885 // Add this candidate 5886 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5887 Candidate.FoundDecl = FoundDecl; 5888 Candidate.Function = Function; 5889 Candidate.Viable = true; 5890 Candidate.IsSurrogate = false; 5891 Candidate.IgnoreObjectArgument = false; 5892 Candidate.ExplicitCallArguments = Args.size(); 5893 5894 if (Constructor) { 5895 // C++ [class.copy]p3: 5896 // A member function template is never instantiated to perform the copy 5897 // of a class object to an object of its class type. 5898 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5899 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5900 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5901 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5902 ClassType))) { 5903 Candidate.Viable = false; 5904 Candidate.FailureKind = ovl_fail_illegal_constructor; 5905 return; 5906 } 5907 } 5908 5909 unsigned NumParams = Proto->getNumParams(); 5910 5911 // (C++ 13.3.2p2): A candidate function having fewer than m 5912 // parameters is viable only if it has an ellipsis in its parameter 5913 // list (8.3.5). 5914 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5915 !Proto->isVariadic()) { 5916 Candidate.Viable = false; 5917 Candidate.FailureKind = ovl_fail_too_many_arguments; 5918 return; 5919 } 5920 5921 // (C++ 13.3.2p2): A candidate function having more than m parameters 5922 // is viable only if the (m+1)st parameter has a default argument 5923 // (8.3.6). For the purposes of overload resolution, the 5924 // parameter list is truncated on the right, so that there are 5925 // exactly m parameters. 5926 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5927 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5928 // Not enough arguments. 5929 Candidate.Viable = false; 5930 Candidate.FailureKind = ovl_fail_too_few_arguments; 5931 return; 5932 } 5933 5934 // (CUDA B.1): Check for invalid calls between targets. 5935 if (getLangOpts().CUDA) 5936 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5937 // Skip the check for callers that are implicit members, because in this 5938 // case we may not yet know what the member's target is; the target is 5939 // inferred for the member automatically, based on the bases and fields of 5940 // the class. 5941 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 5942 Candidate.Viable = false; 5943 Candidate.FailureKind = ovl_fail_bad_target; 5944 return; 5945 } 5946 5947 // Determine the implicit conversion sequences for each of the 5948 // arguments. 5949 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5950 if (ArgIdx < NumParams) { 5951 // (C++ 13.3.2p3): for F to be a viable function, there shall 5952 // exist for each argument an implicit conversion sequence 5953 // (13.3.3.1) that converts that argument to the corresponding 5954 // parameter of F. 5955 QualType ParamType = Proto->getParamType(ArgIdx); 5956 Candidate.Conversions[ArgIdx] 5957 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5958 SuppressUserConversions, 5959 /*InOverloadResolution=*/true, 5960 /*AllowObjCWritebackConversion=*/ 5961 getLangOpts().ObjCAutoRefCount, 5962 AllowExplicit); 5963 if (Candidate.Conversions[ArgIdx].isBad()) { 5964 Candidate.Viable = false; 5965 Candidate.FailureKind = ovl_fail_bad_conversion; 5966 return; 5967 } 5968 } else { 5969 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5970 // argument for which there is no corresponding parameter is 5971 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5972 Candidate.Conversions[ArgIdx].setEllipsis(); 5973 } 5974 } 5975 5976 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5977 Candidate.Viable = false; 5978 Candidate.FailureKind = ovl_fail_enable_if; 5979 Candidate.DeductionFailure.Data = FailedAttr; 5980 return; 5981 } 5982 5983 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 5984 Candidate.Viable = false; 5985 Candidate.FailureKind = ovl_fail_ext_disabled; 5986 return; 5987 } 5988 } 5989 5990 ObjCMethodDecl * 5991 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 5992 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 5993 if (Methods.size() <= 1) 5994 return nullptr; 5995 5996 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5997 bool Match = true; 5998 ObjCMethodDecl *Method = Methods[b]; 5999 unsigned NumNamedArgs = Sel.getNumArgs(); 6000 // Method might have more arguments than selector indicates. This is due 6001 // to addition of c-style arguments in method. 6002 if (Method->param_size() > NumNamedArgs) 6003 NumNamedArgs = Method->param_size(); 6004 if (Args.size() < NumNamedArgs) 6005 continue; 6006 6007 for (unsigned i = 0; i < NumNamedArgs; i++) { 6008 // We can't do any type-checking on a type-dependent argument. 6009 if (Args[i]->isTypeDependent()) { 6010 Match = false; 6011 break; 6012 } 6013 6014 ParmVarDecl *param = Method->parameters()[i]; 6015 Expr *argExpr = Args[i]; 6016 assert(argExpr && "SelectBestMethod(): missing expression"); 6017 6018 // Strip the unbridged-cast placeholder expression off unless it's 6019 // a consumed argument. 6020 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6021 !param->hasAttr<CFConsumedAttr>()) 6022 argExpr = stripARCUnbridgedCast(argExpr); 6023 6024 // If the parameter is __unknown_anytype, move on to the next method. 6025 if (param->getType() == Context.UnknownAnyTy) { 6026 Match = false; 6027 break; 6028 } 6029 6030 ImplicitConversionSequence ConversionState 6031 = TryCopyInitialization(*this, argExpr, param->getType(), 6032 /*SuppressUserConversions*/false, 6033 /*InOverloadResolution=*/true, 6034 /*AllowObjCWritebackConversion=*/ 6035 getLangOpts().ObjCAutoRefCount, 6036 /*AllowExplicit*/false); 6037 // This function looks for a reasonably-exact match, so we consider 6038 // incompatible pointer conversions to be a failure here. 6039 if (ConversionState.isBad() || 6040 (ConversionState.isStandard() && 6041 ConversionState.Standard.Second == 6042 ICK_Incompatible_Pointer_Conversion)) { 6043 Match = false; 6044 break; 6045 } 6046 } 6047 // Promote additional arguments to variadic methods. 6048 if (Match && Method->isVariadic()) { 6049 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6050 if (Args[i]->isTypeDependent()) { 6051 Match = false; 6052 break; 6053 } 6054 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6055 nullptr); 6056 if (Arg.isInvalid()) { 6057 Match = false; 6058 break; 6059 } 6060 } 6061 } else { 6062 // Check for extra arguments to non-variadic methods. 6063 if (Args.size() != NumNamedArgs) 6064 Match = false; 6065 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6066 // Special case when selectors have no argument. In this case, select 6067 // one with the most general result type of 'id'. 6068 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6069 QualType ReturnT = Methods[b]->getReturnType(); 6070 if (ReturnT->isObjCIdType()) 6071 return Methods[b]; 6072 } 6073 } 6074 } 6075 6076 if (Match) 6077 return Method; 6078 } 6079 return nullptr; 6080 } 6081 6082 // specific_attr_iterator iterates over enable_if attributes in reverse, and 6083 // enable_if is order-sensitive. As a result, we need to reverse things 6084 // sometimes. Size of 4 elements is arbitrary. 6085 static SmallVector<EnableIfAttr *, 4> 6086 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 6087 SmallVector<EnableIfAttr *, 4> Result; 6088 if (!Function->hasAttrs()) 6089 return Result; 6090 6091 const auto &FuncAttrs = Function->getAttrs(); 6092 for (Attr *Attr : FuncAttrs) 6093 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 6094 Result.push_back(EnableIf); 6095 6096 std::reverse(Result.begin(), Result.end()); 6097 return Result; 6098 } 6099 6100 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6101 bool MissingImplicitThis) { 6102 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 6103 if (EnableIfAttrs.empty()) 6104 return nullptr; 6105 6106 SFINAETrap Trap(*this); 6107 SmallVector<Expr *, 16> ConvertedArgs; 6108 bool InitializationFailed = false; 6109 6110 // Ignore any variadic arguments. Converting them is pointless, since the 6111 // user can't refer to them in the enable_if condition. 6112 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6113 6114 // Convert the arguments. 6115 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6116 ExprResult R; 6117 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 6118 !cast<CXXMethodDecl>(Function)->isStatic() && 6119 !isa<CXXConstructorDecl>(Function)) { 6120 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6121 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 6122 Method, Method); 6123 } else { 6124 R = PerformCopyInitialization(InitializedEntity::InitializeParameter( 6125 Context, Function->getParamDecl(I)), 6126 SourceLocation(), Args[I]); 6127 } 6128 6129 if (R.isInvalid()) { 6130 InitializationFailed = true; 6131 break; 6132 } 6133 6134 ConvertedArgs.push_back(R.get()); 6135 } 6136 6137 if (InitializationFailed || Trap.hasErrorOccurred()) 6138 return EnableIfAttrs[0]; 6139 6140 // Push default arguments if needed. 6141 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6142 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6143 ParmVarDecl *P = Function->getParamDecl(i); 6144 ExprResult R = PerformCopyInitialization( 6145 InitializedEntity::InitializeParameter(Context, 6146 Function->getParamDecl(i)), 6147 SourceLocation(), 6148 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6149 : P->getDefaultArg()); 6150 if (R.isInvalid()) { 6151 InitializationFailed = true; 6152 break; 6153 } 6154 ConvertedArgs.push_back(R.get()); 6155 } 6156 6157 if (InitializationFailed || Trap.hasErrorOccurred()) 6158 return EnableIfAttrs[0]; 6159 } 6160 6161 for (auto *EIA : EnableIfAttrs) { 6162 APValue Result; 6163 // FIXME: This doesn't consider value-dependent cases, because doing so is 6164 // very difficult. Ideally, we should handle them more gracefully. 6165 if (!EIA->getCond()->EvaluateWithSubstitution( 6166 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6167 return EIA; 6168 6169 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6170 return EIA; 6171 } 6172 return nullptr; 6173 } 6174 6175 /// \brief Add all of the function declarations in the given function set to 6176 /// the overload candidate set. 6177 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6178 ArrayRef<Expr *> Args, 6179 OverloadCandidateSet& CandidateSet, 6180 TemplateArgumentListInfo *ExplicitTemplateArgs, 6181 bool SuppressUserConversions, 6182 bool PartialOverloading) { 6183 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6184 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6185 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6186 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6187 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6188 cast<CXXMethodDecl>(FD)->getParent(), 6189 Args[0]->getType(), Args[0]->Classify(Context), 6190 Args.slice(1), CandidateSet, 6191 SuppressUserConversions, PartialOverloading); 6192 else 6193 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6194 SuppressUserConversions, PartialOverloading); 6195 } else { 6196 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6197 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6198 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6199 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6200 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6201 ExplicitTemplateArgs, 6202 Args[0]->getType(), 6203 Args[0]->Classify(Context), Args.slice(1), 6204 CandidateSet, SuppressUserConversions, 6205 PartialOverloading); 6206 else 6207 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6208 ExplicitTemplateArgs, Args, 6209 CandidateSet, SuppressUserConversions, 6210 PartialOverloading); 6211 } 6212 } 6213 } 6214 6215 /// AddMethodCandidate - Adds a named decl (which is some kind of 6216 /// method) as a method candidate to the given overload set. 6217 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6218 QualType ObjectType, 6219 Expr::Classification ObjectClassification, 6220 ArrayRef<Expr *> Args, 6221 OverloadCandidateSet& CandidateSet, 6222 bool SuppressUserConversions) { 6223 NamedDecl *Decl = FoundDecl.getDecl(); 6224 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6225 6226 if (isa<UsingShadowDecl>(Decl)) 6227 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6228 6229 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6230 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6231 "Expected a member function template"); 6232 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6233 /*ExplicitArgs*/ nullptr, 6234 ObjectType, ObjectClassification, 6235 Args, CandidateSet, 6236 SuppressUserConversions); 6237 } else { 6238 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6239 ObjectType, ObjectClassification, 6240 Args, 6241 CandidateSet, SuppressUserConversions); 6242 } 6243 } 6244 6245 /// AddMethodCandidate - Adds the given C++ member function to the set 6246 /// of candidate functions, using the given function call arguments 6247 /// and the object argument (@c Object). For example, in a call 6248 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6249 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6250 /// allow user-defined conversions via constructors or conversion 6251 /// operators. 6252 void 6253 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6254 CXXRecordDecl *ActingContext, QualType ObjectType, 6255 Expr::Classification ObjectClassification, 6256 ArrayRef<Expr *> Args, 6257 OverloadCandidateSet &CandidateSet, 6258 bool SuppressUserConversions, 6259 bool PartialOverloading) { 6260 const FunctionProtoType *Proto 6261 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6262 assert(Proto && "Methods without a prototype cannot be overloaded"); 6263 assert(!isa<CXXConstructorDecl>(Method) && 6264 "Use AddOverloadCandidate for constructors"); 6265 6266 if (!CandidateSet.isNewCandidate(Method)) 6267 return; 6268 6269 // C++11 [class.copy]p23: [DR1402] 6270 // A defaulted move assignment operator that is defined as deleted is 6271 // ignored by overload resolution. 6272 if (Method->isDefaulted() && Method->isDeleted() && 6273 Method->isMoveAssignmentOperator()) 6274 return; 6275 6276 // Overload resolution is always an unevaluated context. 6277 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6278 6279 // Add this candidate 6280 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6281 Candidate.FoundDecl = FoundDecl; 6282 Candidate.Function = Method; 6283 Candidate.IsSurrogate = false; 6284 Candidate.IgnoreObjectArgument = false; 6285 Candidate.ExplicitCallArguments = Args.size(); 6286 6287 unsigned NumParams = Proto->getNumParams(); 6288 6289 // (C++ 13.3.2p2): A candidate function having fewer than m 6290 // parameters is viable only if it has an ellipsis in its parameter 6291 // list (8.3.5). 6292 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6293 !Proto->isVariadic()) { 6294 Candidate.Viable = false; 6295 Candidate.FailureKind = ovl_fail_too_many_arguments; 6296 return; 6297 } 6298 6299 // (C++ 13.3.2p2): A candidate function having more than m parameters 6300 // is viable only if the (m+1)st parameter has a default argument 6301 // (8.3.6). For the purposes of overload resolution, the 6302 // parameter list is truncated on the right, so that there are 6303 // exactly m parameters. 6304 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6305 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6306 // Not enough arguments. 6307 Candidate.Viable = false; 6308 Candidate.FailureKind = ovl_fail_too_few_arguments; 6309 return; 6310 } 6311 6312 Candidate.Viable = true; 6313 6314 if (Method->isStatic() || ObjectType.isNull()) 6315 // The implicit object argument is ignored. 6316 Candidate.IgnoreObjectArgument = true; 6317 else { 6318 // Determine the implicit conversion sequence for the object 6319 // parameter. 6320 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6321 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6322 Method, ActingContext); 6323 if (Candidate.Conversions[0].isBad()) { 6324 Candidate.Viable = false; 6325 Candidate.FailureKind = ovl_fail_bad_conversion; 6326 return; 6327 } 6328 } 6329 6330 // (CUDA B.1): Check for invalid calls between targets. 6331 if (getLangOpts().CUDA) 6332 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6333 if (!IsAllowedCUDACall(Caller, Method)) { 6334 Candidate.Viable = false; 6335 Candidate.FailureKind = ovl_fail_bad_target; 6336 return; 6337 } 6338 6339 // Determine the implicit conversion sequences for each of the 6340 // arguments. 6341 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6342 if (ArgIdx < NumParams) { 6343 // (C++ 13.3.2p3): for F to be a viable function, there shall 6344 // exist for each argument an implicit conversion sequence 6345 // (13.3.3.1) that converts that argument to the corresponding 6346 // parameter of F. 6347 QualType ParamType = Proto->getParamType(ArgIdx); 6348 Candidate.Conversions[ArgIdx + 1] 6349 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6350 SuppressUserConversions, 6351 /*InOverloadResolution=*/true, 6352 /*AllowObjCWritebackConversion=*/ 6353 getLangOpts().ObjCAutoRefCount); 6354 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6355 Candidate.Viable = false; 6356 Candidate.FailureKind = ovl_fail_bad_conversion; 6357 return; 6358 } 6359 } else { 6360 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6361 // argument for which there is no corresponding parameter is 6362 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6363 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6364 } 6365 } 6366 6367 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6368 Candidate.Viable = false; 6369 Candidate.FailureKind = ovl_fail_enable_if; 6370 Candidate.DeductionFailure.Data = FailedAttr; 6371 return; 6372 } 6373 } 6374 6375 /// \brief Add a C++ member function template as a candidate to the candidate 6376 /// set, using template argument deduction to produce an appropriate member 6377 /// function template specialization. 6378 void 6379 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6380 DeclAccessPair FoundDecl, 6381 CXXRecordDecl *ActingContext, 6382 TemplateArgumentListInfo *ExplicitTemplateArgs, 6383 QualType ObjectType, 6384 Expr::Classification ObjectClassification, 6385 ArrayRef<Expr *> Args, 6386 OverloadCandidateSet& CandidateSet, 6387 bool SuppressUserConversions, 6388 bool PartialOverloading) { 6389 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6390 return; 6391 6392 // C++ [over.match.funcs]p7: 6393 // In each case where a candidate is a function template, candidate 6394 // function template specializations are generated using template argument 6395 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6396 // candidate functions in the usual way.113) A given name can refer to one 6397 // or more function templates and also to a set of overloaded non-template 6398 // functions. In such a case, the candidate functions generated from each 6399 // function template are combined with the set of non-template candidate 6400 // functions. 6401 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6402 FunctionDecl *Specialization = nullptr; 6403 if (TemplateDeductionResult Result 6404 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6405 Specialization, Info, PartialOverloading)) { 6406 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6407 Candidate.FoundDecl = FoundDecl; 6408 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6409 Candidate.Viable = false; 6410 Candidate.FailureKind = ovl_fail_bad_deduction; 6411 Candidate.IsSurrogate = false; 6412 Candidate.IgnoreObjectArgument = false; 6413 Candidate.ExplicitCallArguments = Args.size(); 6414 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6415 Info); 6416 return; 6417 } 6418 6419 // Add the function template specialization produced by template argument 6420 // deduction as a candidate. 6421 assert(Specialization && "Missing member function template specialization?"); 6422 assert(isa<CXXMethodDecl>(Specialization) && 6423 "Specialization is not a member function?"); 6424 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6425 ActingContext, ObjectType, ObjectClassification, Args, 6426 CandidateSet, SuppressUserConversions, PartialOverloading); 6427 } 6428 6429 /// \brief Add a C++ function template specialization as a candidate 6430 /// in the candidate set, using template argument deduction to produce 6431 /// an appropriate function template specialization. 6432 void 6433 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6434 DeclAccessPair FoundDecl, 6435 TemplateArgumentListInfo *ExplicitTemplateArgs, 6436 ArrayRef<Expr *> Args, 6437 OverloadCandidateSet& CandidateSet, 6438 bool SuppressUserConversions, 6439 bool PartialOverloading) { 6440 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6441 return; 6442 6443 // C++ [over.match.funcs]p7: 6444 // In each case where a candidate is a function template, candidate 6445 // function template specializations are generated using template argument 6446 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6447 // candidate functions in the usual way.113) A given name can refer to one 6448 // or more function templates and also to a set of overloaded non-template 6449 // functions. In such a case, the candidate functions generated from each 6450 // function template are combined with the set of non-template candidate 6451 // functions. 6452 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6453 FunctionDecl *Specialization = nullptr; 6454 if (TemplateDeductionResult Result 6455 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6456 Specialization, Info, PartialOverloading)) { 6457 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6458 Candidate.FoundDecl = FoundDecl; 6459 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6460 Candidate.Viable = false; 6461 Candidate.FailureKind = ovl_fail_bad_deduction; 6462 Candidate.IsSurrogate = false; 6463 Candidate.IgnoreObjectArgument = false; 6464 Candidate.ExplicitCallArguments = Args.size(); 6465 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6466 Info); 6467 return; 6468 } 6469 6470 // Add the function template specialization produced by template argument 6471 // deduction as a candidate. 6472 assert(Specialization && "Missing function template specialization?"); 6473 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6474 SuppressUserConversions, PartialOverloading); 6475 } 6476 6477 /// Determine whether this is an allowable conversion from the result 6478 /// of an explicit conversion operator to the expected type, per C++ 6479 /// [over.match.conv]p1 and [over.match.ref]p1. 6480 /// 6481 /// \param ConvType The return type of the conversion function. 6482 /// 6483 /// \param ToType The type we are converting to. 6484 /// 6485 /// \param AllowObjCPointerConversion Allow a conversion from one 6486 /// Objective-C pointer to another. 6487 /// 6488 /// \returns true if the conversion is allowable, false otherwise. 6489 static bool isAllowableExplicitConversion(Sema &S, 6490 QualType ConvType, QualType ToType, 6491 bool AllowObjCPointerConversion) { 6492 QualType ToNonRefType = ToType.getNonReferenceType(); 6493 6494 // Easy case: the types are the same. 6495 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6496 return true; 6497 6498 // Allow qualification conversions. 6499 bool ObjCLifetimeConversion; 6500 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6501 ObjCLifetimeConversion)) 6502 return true; 6503 6504 // If we're not allowed to consider Objective-C pointer conversions, 6505 // we're done. 6506 if (!AllowObjCPointerConversion) 6507 return false; 6508 6509 // Is this an Objective-C pointer conversion? 6510 bool IncompatibleObjC = false; 6511 QualType ConvertedType; 6512 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6513 IncompatibleObjC); 6514 } 6515 6516 /// AddConversionCandidate - Add a C++ conversion function as a 6517 /// candidate in the candidate set (C++ [over.match.conv], 6518 /// C++ [over.match.copy]). From is the expression we're converting from, 6519 /// and ToType is the type that we're eventually trying to convert to 6520 /// (which may or may not be the same type as the type that the 6521 /// conversion function produces). 6522 void 6523 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6524 DeclAccessPair FoundDecl, 6525 CXXRecordDecl *ActingContext, 6526 Expr *From, QualType ToType, 6527 OverloadCandidateSet& CandidateSet, 6528 bool AllowObjCConversionOnExplicit) { 6529 assert(!Conversion->getDescribedFunctionTemplate() && 6530 "Conversion function templates use AddTemplateConversionCandidate"); 6531 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6532 if (!CandidateSet.isNewCandidate(Conversion)) 6533 return; 6534 6535 // If the conversion function has an undeduced return type, trigger its 6536 // deduction now. 6537 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6538 if (DeduceReturnType(Conversion, From->getExprLoc())) 6539 return; 6540 ConvType = Conversion->getConversionType().getNonReferenceType(); 6541 } 6542 6543 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6544 // operator is only a candidate if its return type is the target type or 6545 // can be converted to the target type with a qualification conversion. 6546 if (Conversion->isExplicit() && 6547 !isAllowableExplicitConversion(*this, ConvType, ToType, 6548 AllowObjCConversionOnExplicit)) 6549 return; 6550 6551 // Overload resolution is always an unevaluated context. 6552 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6553 6554 // Add this candidate 6555 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6556 Candidate.FoundDecl = FoundDecl; 6557 Candidate.Function = Conversion; 6558 Candidate.IsSurrogate = false; 6559 Candidate.IgnoreObjectArgument = false; 6560 Candidate.FinalConversion.setAsIdentityConversion(); 6561 Candidate.FinalConversion.setFromType(ConvType); 6562 Candidate.FinalConversion.setAllToTypes(ToType); 6563 Candidate.Viable = true; 6564 Candidate.ExplicitCallArguments = 1; 6565 6566 // C++ [over.match.funcs]p4: 6567 // For conversion functions, the function is considered to be a member of 6568 // the class of the implicit implied object argument for the purpose of 6569 // defining the type of the implicit object parameter. 6570 // 6571 // Determine the implicit conversion sequence for the implicit 6572 // object parameter. 6573 QualType ImplicitParamType = From->getType(); 6574 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6575 ImplicitParamType = FromPtrType->getPointeeType(); 6576 CXXRecordDecl *ConversionContext 6577 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6578 6579 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6580 *this, CandidateSet.getLocation(), From->getType(), 6581 From->Classify(Context), Conversion, ConversionContext); 6582 6583 if (Candidate.Conversions[0].isBad()) { 6584 Candidate.Viable = false; 6585 Candidate.FailureKind = ovl_fail_bad_conversion; 6586 return; 6587 } 6588 6589 // We won't go through a user-defined type conversion function to convert a 6590 // derived to base as such conversions are given Conversion Rank. They only 6591 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6592 QualType FromCanon 6593 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6594 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6595 if (FromCanon == ToCanon || 6596 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6597 Candidate.Viable = false; 6598 Candidate.FailureKind = ovl_fail_trivial_conversion; 6599 return; 6600 } 6601 6602 // To determine what the conversion from the result of calling the 6603 // conversion function to the type we're eventually trying to 6604 // convert to (ToType), we need to synthesize a call to the 6605 // conversion function and attempt copy initialization from it. This 6606 // makes sure that we get the right semantics with respect to 6607 // lvalues/rvalues and the type. Fortunately, we can allocate this 6608 // call on the stack and we don't need its arguments to be 6609 // well-formed. 6610 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6611 VK_LValue, From->getLocStart()); 6612 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6613 Context.getPointerType(Conversion->getType()), 6614 CK_FunctionToPointerDecay, 6615 &ConversionRef, VK_RValue); 6616 6617 QualType ConversionType = Conversion->getConversionType(); 6618 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6619 Candidate.Viable = false; 6620 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6621 return; 6622 } 6623 6624 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6625 6626 // Note that it is safe to allocate CallExpr on the stack here because 6627 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6628 // allocator). 6629 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6630 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6631 From->getLocStart()); 6632 ImplicitConversionSequence ICS = 6633 TryCopyInitialization(*this, &Call, ToType, 6634 /*SuppressUserConversions=*/true, 6635 /*InOverloadResolution=*/false, 6636 /*AllowObjCWritebackConversion=*/false); 6637 6638 switch (ICS.getKind()) { 6639 case ImplicitConversionSequence::StandardConversion: 6640 Candidate.FinalConversion = ICS.Standard; 6641 6642 // C++ [over.ics.user]p3: 6643 // If the user-defined conversion is specified by a specialization of a 6644 // conversion function template, the second standard conversion sequence 6645 // shall have exact match rank. 6646 if (Conversion->getPrimaryTemplate() && 6647 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6648 Candidate.Viable = false; 6649 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6650 return; 6651 } 6652 6653 // C++0x [dcl.init.ref]p5: 6654 // In the second case, if the reference is an rvalue reference and 6655 // the second standard conversion sequence of the user-defined 6656 // conversion sequence includes an lvalue-to-rvalue conversion, the 6657 // program is ill-formed. 6658 if (ToType->isRValueReferenceType() && 6659 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6660 Candidate.Viable = false; 6661 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6662 return; 6663 } 6664 break; 6665 6666 case ImplicitConversionSequence::BadConversion: 6667 Candidate.Viable = false; 6668 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6669 return; 6670 6671 default: 6672 llvm_unreachable( 6673 "Can only end up with a standard conversion sequence or failure"); 6674 } 6675 6676 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6677 Candidate.Viable = false; 6678 Candidate.FailureKind = ovl_fail_enable_if; 6679 Candidate.DeductionFailure.Data = FailedAttr; 6680 return; 6681 } 6682 } 6683 6684 /// \brief Adds a conversion function template specialization 6685 /// candidate to the overload set, using template argument deduction 6686 /// to deduce the template arguments of the conversion function 6687 /// template from the type that we are converting to (C++ 6688 /// [temp.deduct.conv]). 6689 void 6690 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6691 DeclAccessPair FoundDecl, 6692 CXXRecordDecl *ActingDC, 6693 Expr *From, QualType ToType, 6694 OverloadCandidateSet &CandidateSet, 6695 bool AllowObjCConversionOnExplicit) { 6696 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6697 "Only conversion function templates permitted here"); 6698 6699 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6700 return; 6701 6702 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6703 CXXConversionDecl *Specialization = nullptr; 6704 if (TemplateDeductionResult Result 6705 = DeduceTemplateArguments(FunctionTemplate, ToType, 6706 Specialization, Info)) { 6707 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6708 Candidate.FoundDecl = FoundDecl; 6709 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6710 Candidate.Viable = false; 6711 Candidate.FailureKind = ovl_fail_bad_deduction; 6712 Candidate.IsSurrogate = false; 6713 Candidate.IgnoreObjectArgument = false; 6714 Candidate.ExplicitCallArguments = 1; 6715 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6716 Info); 6717 return; 6718 } 6719 6720 // Add the conversion function template specialization produced by 6721 // template argument deduction as a candidate. 6722 assert(Specialization && "Missing function template specialization?"); 6723 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6724 CandidateSet, AllowObjCConversionOnExplicit); 6725 } 6726 6727 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6728 /// converts the given @c Object to a function pointer via the 6729 /// conversion function @c Conversion, and then attempts to call it 6730 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6731 /// the type of function that we'll eventually be calling. 6732 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6733 DeclAccessPair FoundDecl, 6734 CXXRecordDecl *ActingContext, 6735 const FunctionProtoType *Proto, 6736 Expr *Object, 6737 ArrayRef<Expr *> Args, 6738 OverloadCandidateSet& CandidateSet) { 6739 if (!CandidateSet.isNewCandidate(Conversion)) 6740 return; 6741 6742 // Overload resolution is always an unevaluated context. 6743 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6744 6745 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6746 Candidate.FoundDecl = FoundDecl; 6747 Candidate.Function = nullptr; 6748 Candidate.Surrogate = Conversion; 6749 Candidate.Viable = true; 6750 Candidate.IsSurrogate = true; 6751 Candidate.IgnoreObjectArgument = false; 6752 Candidate.ExplicitCallArguments = Args.size(); 6753 6754 // Determine the implicit conversion sequence for the implicit 6755 // object parameter. 6756 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6757 *this, CandidateSet.getLocation(), Object->getType(), 6758 Object->Classify(Context), Conversion, ActingContext); 6759 if (ObjectInit.isBad()) { 6760 Candidate.Viable = false; 6761 Candidate.FailureKind = ovl_fail_bad_conversion; 6762 Candidate.Conversions[0] = ObjectInit; 6763 return; 6764 } 6765 6766 // The first conversion is actually a user-defined conversion whose 6767 // first conversion is ObjectInit's standard conversion (which is 6768 // effectively a reference binding). Record it as such. 6769 Candidate.Conversions[0].setUserDefined(); 6770 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6771 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6772 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6773 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6774 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6775 Candidate.Conversions[0].UserDefined.After 6776 = Candidate.Conversions[0].UserDefined.Before; 6777 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6778 6779 // Find the 6780 unsigned NumParams = Proto->getNumParams(); 6781 6782 // (C++ 13.3.2p2): A candidate function having fewer than m 6783 // parameters is viable only if it has an ellipsis in its parameter 6784 // list (8.3.5). 6785 if (Args.size() > NumParams && !Proto->isVariadic()) { 6786 Candidate.Viable = false; 6787 Candidate.FailureKind = ovl_fail_too_many_arguments; 6788 return; 6789 } 6790 6791 // Function types don't have any default arguments, so just check if 6792 // we have enough arguments. 6793 if (Args.size() < NumParams) { 6794 // Not enough arguments. 6795 Candidate.Viable = false; 6796 Candidate.FailureKind = ovl_fail_too_few_arguments; 6797 return; 6798 } 6799 6800 // Determine the implicit conversion sequences for each of the 6801 // arguments. 6802 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6803 if (ArgIdx < NumParams) { 6804 // (C++ 13.3.2p3): for F to be a viable function, there shall 6805 // exist for each argument an implicit conversion sequence 6806 // (13.3.3.1) that converts that argument to the corresponding 6807 // parameter of F. 6808 QualType ParamType = Proto->getParamType(ArgIdx); 6809 Candidate.Conversions[ArgIdx + 1] 6810 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6811 /*SuppressUserConversions=*/false, 6812 /*InOverloadResolution=*/false, 6813 /*AllowObjCWritebackConversion=*/ 6814 getLangOpts().ObjCAutoRefCount); 6815 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6816 Candidate.Viable = false; 6817 Candidate.FailureKind = ovl_fail_bad_conversion; 6818 return; 6819 } 6820 } else { 6821 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6822 // argument for which there is no corresponding parameter is 6823 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6824 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6825 } 6826 } 6827 6828 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6829 Candidate.Viable = false; 6830 Candidate.FailureKind = ovl_fail_enable_if; 6831 Candidate.DeductionFailure.Data = FailedAttr; 6832 return; 6833 } 6834 } 6835 6836 /// \brief Add overload candidates for overloaded operators that are 6837 /// member functions. 6838 /// 6839 /// Add the overloaded operator candidates that are member functions 6840 /// for the operator Op that was used in an operator expression such 6841 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6842 /// CandidateSet will store the added overload candidates. (C++ 6843 /// [over.match.oper]). 6844 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6845 SourceLocation OpLoc, 6846 ArrayRef<Expr *> Args, 6847 OverloadCandidateSet& CandidateSet, 6848 SourceRange OpRange) { 6849 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6850 6851 // C++ [over.match.oper]p3: 6852 // For a unary operator @ with an operand of a type whose 6853 // cv-unqualified version is T1, and for a binary operator @ with 6854 // a left operand of a type whose cv-unqualified version is T1 and 6855 // a right operand of a type whose cv-unqualified version is T2, 6856 // three sets of candidate functions, designated member 6857 // candidates, non-member candidates and built-in candidates, are 6858 // constructed as follows: 6859 QualType T1 = Args[0]->getType(); 6860 6861 // -- If T1 is a complete class type or a class currently being 6862 // defined, the set of member candidates is the result of the 6863 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6864 // the set of member candidates is empty. 6865 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6866 // Complete the type if it can be completed. 6867 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 6868 return; 6869 // If the type is neither complete nor being defined, bail out now. 6870 if (!T1Rec->getDecl()->getDefinition()) 6871 return; 6872 6873 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6874 LookupQualifiedName(Operators, T1Rec->getDecl()); 6875 Operators.suppressDiagnostics(); 6876 6877 for (LookupResult::iterator Oper = Operators.begin(), 6878 OperEnd = Operators.end(); 6879 Oper != OperEnd; 6880 ++Oper) 6881 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6882 Args[0]->Classify(Context), 6883 Args.slice(1), 6884 CandidateSet, 6885 /* SuppressUserConversions = */ false); 6886 } 6887 } 6888 6889 /// AddBuiltinCandidate - Add a candidate for a built-in 6890 /// operator. ResultTy and ParamTys are the result and parameter types 6891 /// of the built-in candidate, respectively. Args and NumArgs are the 6892 /// arguments being passed to the candidate. IsAssignmentOperator 6893 /// should be true when this built-in candidate is an assignment 6894 /// operator. NumContextualBoolArguments is the number of arguments 6895 /// (at the beginning of the argument list) that will be contextually 6896 /// converted to bool. 6897 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6898 ArrayRef<Expr *> Args, 6899 OverloadCandidateSet& CandidateSet, 6900 bool IsAssignmentOperator, 6901 unsigned NumContextualBoolArguments) { 6902 // Overload resolution is always an unevaluated context. 6903 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6904 6905 // Add this candidate 6906 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6907 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6908 Candidate.Function = nullptr; 6909 Candidate.IsSurrogate = false; 6910 Candidate.IgnoreObjectArgument = false; 6911 Candidate.BuiltinTypes.ResultTy = ResultTy; 6912 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6913 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6914 6915 // Determine the implicit conversion sequences for each of the 6916 // arguments. 6917 Candidate.Viable = true; 6918 Candidate.ExplicitCallArguments = Args.size(); 6919 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6920 // C++ [over.match.oper]p4: 6921 // For the built-in assignment operators, conversions of the 6922 // left operand are restricted as follows: 6923 // -- no temporaries are introduced to hold the left operand, and 6924 // -- no user-defined conversions are applied to the left 6925 // operand to achieve a type match with the left-most 6926 // parameter of a built-in candidate. 6927 // 6928 // We block these conversions by turning off user-defined 6929 // conversions, since that is the only way that initialization of 6930 // a reference to a non-class type can occur from something that 6931 // is not of the same type. 6932 if (ArgIdx < NumContextualBoolArguments) { 6933 assert(ParamTys[ArgIdx] == Context.BoolTy && 6934 "Contextual conversion to bool requires bool type"); 6935 Candidate.Conversions[ArgIdx] 6936 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6937 } else { 6938 Candidate.Conversions[ArgIdx] 6939 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6940 ArgIdx == 0 && IsAssignmentOperator, 6941 /*InOverloadResolution=*/false, 6942 /*AllowObjCWritebackConversion=*/ 6943 getLangOpts().ObjCAutoRefCount); 6944 } 6945 if (Candidate.Conversions[ArgIdx].isBad()) { 6946 Candidate.Viable = false; 6947 Candidate.FailureKind = ovl_fail_bad_conversion; 6948 break; 6949 } 6950 } 6951 } 6952 6953 namespace { 6954 6955 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6956 /// candidate operator functions for built-in operators (C++ 6957 /// [over.built]). The types are separated into pointer types and 6958 /// enumeration types. 6959 class BuiltinCandidateTypeSet { 6960 /// TypeSet - A set of types. 6961 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 6962 llvm::SmallPtrSet<QualType, 8>> TypeSet; 6963 6964 /// PointerTypes - The set of pointer types that will be used in the 6965 /// built-in candidates. 6966 TypeSet PointerTypes; 6967 6968 /// MemberPointerTypes - The set of member pointer types that will be 6969 /// used in the built-in candidates. 6970 TypeSet MemberPointerTypes; 6971 6972 /// EnumerationTypes - The set of enumeration types that will be 6973 /// used in the built-in candidates. 6974 TypeSet EnumerationTypes; 6975 6976 /// \brief The set of vector types that will be used in the built-in 6977 /// candidates. 6978 TypeSet VectorTypes; 6979 6980 /// \brief A flag indicating non-record types are viable candidates 6981 bool HasNonRecordTypes; 6982 6983 /// \brief A flag indicating whether either arithmetic or enumeration types 6984 /// were present in the candidate set. 6985 bool HasArithmeticOrEnumeralTypes; 6986 6987 /// \brief A flag indicating whether the nullptr type was present in the 6988 /// candidate set. 6989 bool HasNullPtrType; 6990 6991 /// Sema - The semantic analysis instance where we are building the 6992 /// candidate type set. 6993 Sema &SemaRef; 6994 6995 /// Context - The AST context in which we will build the type sets. 6996 ASTContext &Context; 6997 6998 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6999 const Qualifiers &VisibleQuals); 7000 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7001 7002 public: 7003 /// iterator - Iterates through the types that are part of the set. 7004 typedef TypeSet::iterator iterator; 7005 7006 BuiltinCandidateTypeSet(Sema &SemaRef) 7007 : HasNonRecordTypes(false), 7008 HasArithmeticOrEnumeralTypes(false), 7009 HasNullPtrType(false), 7010 SemaRef(SemaRef), 7011 Context(SemaRef.Context) { } 7012 7013 void AddTypesConvertedFrom(QualType Ty, 7014 SourceLocation Loc, 7015 bool AllowUserConversions, 7016 bool AllowExplicitConversions, 7017 const Qualifiers &VisibleTypeConversionsQuals); 7018 7019 /// pointer_begin - First pointer type found; 7020 iterator pointer_begin() { return PointerTypes.begin(); } 7021 7022 /// pointer_end - Past the last pointer type found; 7023 iterator pointer_end() { return PointerTypes.end(); } 7024 7025 /// member_pointer_begin - First member pointer type found; 7026 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7027 7028 /// member_pointer_end - Past the last member pointer type found; 7029 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7030 7031 /// enumeration_begin - First enumeration type found; 7032 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7033 7034 /// enumeration_end - Past the last enumeration type found; 7035 iterator enumeration_end() { return EnumerationTypes.end(); } 7036 7037 iterator vector_begin() { return VectorTypes.begin(); } 7038 iterator vector_end() { return VectorTypes.end(); } 7039 7040 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7041 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7042 bool hasNullPtrType() const { return HasNullPtrType; } 7043 }; 7044 7045 } // end anonymous namespace 7046 7047 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7048 /// the set of pointer types along with any more-qualified variants of 7049 /// that type. For example, if @p Ty is "int const *", this routine 7050 /// will add "int const *", "int const volatile *", "int const 7051 /// restrict *", and "int const volatile restrict *" to the set of 7052 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7053 /// false otherwise. 7054 /// 7055 /// FIXME: what to do about extended qualifiers? 7056 bool 7057 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7058 const Qualifiers &VisibleQuals) { 7059 7060 // Insert this type. 7061 if (!PointerTypes.insert(Ty)) 7062 return false; 7063 7064 QualType PointeeTy; 7065 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7066 bool buildObjCPtr = false; 7067 if (!PointerTy) { 7068 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7069 PointeeTy = PTy->getPointeeType(); 7070 buildObjCPtr = true; 7071 } else { 7072 PointeeTy = PointerTy->getPointeeType(); 7073 } 7074 7075 // Don't add qualified variants of arrays. For one, they're not allowed 7076 // (the qualifier would sink to the element type), and for another, the 7077 // only overload situation where it matters is subscript or pointer +- int, 7078 // and those shouldn't have qualifier variants anyway. 7079 if (PointeeTy->isArrayType()) 7080 return true; 7081 7082 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7083 bool hasVolatile = VisibleQuals.hasVolatile(); 7084 bool hasRestrict = VisibleQuals.hasRestrict(); 7085 7086 // Iterate through all strict supersets of BaseCVR. 7087 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7088 if ((CVR | BaseCVR) != CVR) continue; 7089 // Skip over volatile if no volatile found anywhere in the types. 7090 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7091 7092 // Skip over restrict if no restrict found anywhere in the types, or if 7093 // the type cannot be restrict-qualified. 7094 if ((CVR & Qualifiers::Restrict) && 7095 (!hasRestrict || 7096 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7097 continue; 7098 7099 // Build qualified pointee type. 7100 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7101 7102 // Build qualified pointer type. 7103 QualType QPointerTy; 7104 if (!buildObjCPtr) 7105 QPointerTy = Context.getPointerType(QPointeeTy); 7106 else 7107 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7108 7109 // Insert qualified pointer type. 7110 PointerTypes.insert(QPointerTy); 7111 } 7112 7113 return true; 7114 } 7115 7116 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7117 /// to the set of pointer types along with any more-qualified variants of 7118 /// that type. For example, if @p Ty is "int const *", this routine 7119 /// will add "int const *", "int const volatile *", "int const 7120 /// restrict *", and "int const volatile restrict *" to the set of 7121 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7122 /// false otherwise. 7123 /// 7124 /// FIXME: what to do about extended qualifiers? 7125 bool 7126 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7127 QualType Ty) { 7128 // Insert this type. 7129 if (!MemberPointerTypes.insert(Ty)) 7130 return false; 7131 7132 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7133 assert(PointerTy && "type was not a member pointer type!"); 7134 7135 QualType PointeeTy = PointerTy->getPointeeType(); 7136 // Don't add qualified variants of arrays. For one, they're not allowed 7137 // (the qualifier would sink to the element type), and for another, the 7138 // only overload situation where it matters is subscript or pointer +- int, 7139 // and those shouldn't have qualifier variants anyway. 7140 if (PointeeTy->isArrayType()) 7141 return true; 7142 const Type *ClassTy = PointerTy->getClass(); 7143 7144 // Iterate through all strict supersets of the pointee type's CVR 7145 // qualifiers. 7146 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7147 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7148 if ((CVR | BaseCVR) != CVR) continue; 7149 7150 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7151 MemberPointerTypes.insert( 7152 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7153 } 7154 7155 return true; 7156 } 7157 7158 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7159 /// Ty can be implicit converted to the given set of @p Types. We're 7160 /// primarily interested in pointer types and enumeration types. We also 7161 /// take member pointer types, for the conditional operator. 7162 /// AllowUserConversions is true if we should look at the conversion 7163 /// functions of a class type, and AllowExplicitConversions if we 7164 /// should also include the explicit conversion functions of a class 7165 /// type. 7166 void 7167 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7168 SourceLocation Loc, 7169 bool AllowUserConversions, 7170 bool AllowExplicitConversions, 7171 const Qualifiers &VisibleQuals) { 7172 // Only deal with canonical types. 7173 Ty = Context.getCanonicalType(Ty); 7174 7175 // Look through reference types; they aren't part of the type of an 7176 // expression for the purposes of conversions. 7177 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7178 Ty = RefTy->getPointeeType(); 7179 7180 // If we're dealing with an array type, decay to the pointer. 7181 if (Ty->isArrayType()) 7182 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7183 7184 // Otherwise, we don't care about qualifiers on the type. 7185 Ty = Ty.getLocalUnqualifiedType(); 7186 7187 // Flag if we ever add a non-record type. 7188 const RecordType *TyRec = Ty->getAs<RecordType>(); 7189 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7190 7191 // Flag if we encounter an arithmetic type. 7192 HasArithmeticOrEnumeralTypes = 7193 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7194 7195 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7196 PointerTypes.insert(Ty); 7197 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7198 // Insert our type, and its more-qualified variants, into the set 7199 // of types. 7200 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7201 return; 7202 } else if (Ty->isMemberPointerType()) { 7203 // Member pointers are far easier, since the pointee can't be converted. 7204 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7205 return; 7206 } else if (Ty->isEnumeralType()) { 7207 HasArithmeticOrEnumeralTypes = true; 7208 EnumerationTypes.insert(Ty); 7209 } else if (Ty->isVectorType()) { 7210 // We treat vector types as arithmetic types in many contexts as an 7211 // extension. 7212 HasArithmeticOrEnumeralTypes = true; 7213 VectorTypes.insert(Ty); 7214 } else if (Ty->isNullPtrType()) { 7215 HasNullPtrType = true; 7216 } else if (AllowUserConversions && TyRec) { 7217 // No conversion functions in incomplete types. 7218 if (!SemaRef.isCompleteType(Loc, Ty)) 7219 return; 7220 7221 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7222 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7223 if (isa<UsingShadowDecl>(D)) 7224 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7225 7226 // Skip conversion function templates; they don't tell us anything 7227 // about which builtin types we can convert to. 7228 if (isa<FunctionTemplateDecl>(D)) 7229 continue; 7230 7231 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7232 if (AllowExplicitConversions || !Conv->isExplicit()) { 7233 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7234 VisibleQuals); 7235 } 7236 } 7237 } 7238 } 7239 7240 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7241 /// the volatile- and non-volatile-qualified assignment operators for the 7242 /// given type to the candidate set. 7243 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7244 QualType T, 7245 ArrayRef<Expr *> Args, 7246 OverloadCandidateSet &CandidateSet) { 7247 QualType ParamTypes[2]; 7248 7249 // T& operator=(T&, T) 7250 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7251 ParamTypes[1] = T; 7252 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7253 /*IsAssignmentOperator=*/true); 7254 7255 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7256 // volatile T& operator=(volatile T&, T) 7257 ParamTypes[0] 7258 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7259 ParamTypes[1] = T; 7260 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7261 /*IsAssignmentOperator=*/true); 7262 } 7263 } 7264 7265 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7266 /// if any, found in visible type conversion functions found in ArgExpr's type. 7267 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7268 Qualifiers VRQuals; 7269 const RecordType *TyRec; 7270 if (const MemberPointerType *RHSMPType = 7271 ArgExpr->getType()->getAs<MemberPointerType>()) 7272 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7273 else 7274 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7275 if (!TyRec) { 7276 // Just to be safe, assume the worst case. 7277 VRQuals.addVolatile(); 7278 VRQuals.addRestrict(); 7279 return VRQuals; 7280 } 7281 7282 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7283 if (!ClassDecl->hasDefinition()) 7284 return VRQuals; 7285 7286 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7287 if (isa<UsingShadowDecl>(D)) 7288 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7289 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7290 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7291 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7292 CanTy = ResTypeRef->getPointeeType(); 7293 // Need to go down the pointer/mempointer chain and add qualifiers 7294 // as see them. 7295 bool done = false; 7296 while (!done) { 7297 if (CanTy.isRestrictQualified()) 7298 VRQuals.addRestrict(); 7299 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7300 CanTy = ResTypePtr->getPointeeType(); 7301 else if (const MemberPointerType *ResTypeMPtr = 7302 CanTy->getAs<MemberPointerType>()) 7303 CanTy = ResTypeMPtr->getPointeeType(); 7304 else 7305 done = true; 7306 if (CanTy.isVolatileQualified()) 7307 VRQuals.addVolatile(); 7308 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7309 return VRQuals; 7310 } 7311 } 7312 } 7313 return VRQuals; 7314 } 7315 7316 namespace { 7317 7318 /// \brief Helper class to manage the addition of builtin operator overload 7319 /// candidates. It provides shared state and utility methods used throughout 7320 /// the process, as well as a helper method to add each group of builtin 7321 /// operator overloads from the standard to a candidate set. 7322 class BuiltinOperatorOverloadBuilder { 7323 // Common instance state available to all overload candidate addition methods. 7324 Sema &S; 7325 ArrayRef<Expr *> Args; 7326 Qualifiers VisibleTypeConversionsQuals; 7327 bool HasArithmeticOrEnumeralCandidateType; 7328 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7329 OverloadCandidateSet &CandidateSet; 7330 7331 // Define some constants used to index and iterate over the arithemetic types 7332 // provided via the getArithmeticType() method below. 7333 // The "promoted arithmetic types" are the arithmetic 7334 // types are that preserved by promotion (C++ [over.built]p2). 7335 static const unsigned FirstIntegralType = 4; 7336 static const unsigned LastIntegralType = 21; 7337 static const unsigned FirstPromotedIntegralType = 4, 7338 LastPromotedIntegralType = 12; 7339 static const unsigned FirstPromotedArithmeticType = 0, 7340 LastPromotedArithmeticType = 12; 7341 static const unsigned NumArithmeticTypes = 21; 7342 7343 /// \brief Get the canonical type for a given arithmetic type index. 7344 CanQualType getArithmeticType(unsigned index) { 7345 assert(index < NumArithmeticTypes); 7346 static CanQualType ASTContext::* const 7347 ArithmeticTypes[NumArithmeticTypes] = { 7348 // Start of promoted types. 7349 &ASTContext::FloatTy, 7350 &ASTContext::DoubleTy, 7351 &ASTContext::LongDoubleTy, 7352 &ASTContext::Float128Ty, 7353 7354 // Start of integral types. 7355 &ASTContext::IntTy, 7356 &ASTContext::LongTy, 7357 &ASTContext::LongLongTy, 7358 &ASTContext::Int128Ty, 7359 &ASTContext::UnsignedIntTy, 7360 &ASTContext::UnsignedLongTy, 7361 &ASTContext::UnsignedLongLongTy, 7362 &ASTContext::UnsignedInt128Ty, 7363 // End of promoted types. 7364 7365 &ASTContext::BoolTy, 7366 &ASTContext::CharTy, 7367 &ASTContext::WCharTy, 7368 &ASTContext::Char16Ty, 7369 &ASTContext::Char32Ty, 7370 &ASTContext::SignedCharTy, 7371 &ASTContext::ShortTy, 7372 &ASTContext::UnsignedCharTy, 7373 &ASTContext::UnsignedShortTy, 7374 // End of integral types. 7375 // FIXME: What about complex? What about half? 7376 }; 7377 return S.Context.*ArithmeticTypes[index]; 7378 } 7379 7380 /// \brief Gets the canonical type resulting from the usual arithemetic 7381 /// converions for the given arithmetic types. 7382 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7383 // Accelerator table for performing the usual arithmetic conversions. 7384 // The rules are basically: 7385 // - if either is floating-point, use the wider floating-point 7386 // - if same signedness, use the higher rank 7387 // - if same size, use unsigned of the higher rank 7388 // - use the larger type 7389 // These rules, together with the axiom that higher ranks are 7390 // never smaller, are sufficient to precompute all of these results 7391 // *except* when dealing with signed types of higher rank. 7392 // (we could precompute SLL x UI for all known platforms, but it's 7393 // better not to make any assumptions). 7394 // We assume that int128 has a higher rank than long long on all platforms. 7395 enum PromotedType : int8_t { 7396 Dep=-1, 7397 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7398 }; 7399 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7400 [LastPromotedArithmeticType] = { 7401 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7402 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7403 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7404 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7405 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7406 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7407 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7408 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7409 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7410 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7411 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7412 }; 7413 7414 assert(L < LastPromotedArithmeticType); 7415 assert(R < LastPromotedArithmeticType); 7416 int Idx = ConversionsTable[L][R]; 7417 7418 // Fast path: the table gives us a concrete answer. 7419 if (Idx != Dep) return getArithmeticType(Idx); 7420 7421 // Slow path: we need to compare widths. 7422 // An invariant is that the signed type has higher rank. 7423 CanQualType LT = getArithmeticType(L), 7424 RT = getArithmeticType(R); 7425 unsigned LW = S.Context.getIntWidth(LT), 7426 RW = S.Context.getIntWidth(RT); 7427 7428 // If they're different widths, use the signed type. 7429 if (LW > RW) return LT; 7430 else if (LW < RW) return RT; 7431 7432 // Otherwise, use the unsigned type of the signed type's rank. 7433 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7434 assert(L == SLL || R == SLL); 7435 return S.Context.UnsignedLongLongTy; 7436 } 7437 7438 /// \brief Helper method to factor out the common pattern of adding overloads 7439 /// for '++' and '--' builtin operators. 7440 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7441 bool HasVolatile, 7442 bool HasRestrict) { 7443 QualType ParamTypes[2] = { 7444 S.Context.getLValueReferenceType(CandidateTy), 7445 S.Context.IntTy 7446 }; 7447 7448 // Non-volatile version. 7449 if (Args.size() == 1) 7450 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7451 else 7452 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7453 7454 // Use a heuristic to reduce number of builtin candidates in the set: 7455 // add volatile version only if there are conversions to a volatile type. 7456 if (HasVolatile) { 7457 ParamTypes[0] = 7458 S.Context.getLValueReferenceType( 7459 S.Context.getVolatileType(CandidateTy)); 7460 if (Args.size() == 1) 7461 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7462 else 7463 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7464 } 7465 7466 // Add restrict version only if there are conversions to a restrict type 7467 // and our candidate type is a non-restrict-qualified pointer. 7468 if (HasRestrict && CandidateTy->isAnyPointerType() && 7469 !CandidateTy.isRestrictQualified()) { 7470 ParamTypes[0] 7471 = S.Context.getLValueReferenceType( 7472 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7473 if (Args.size() == 1) 7474 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7475 else 7476 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7477 7478 if (HasVolatile) { 7479 ParamTypes[0] 7480 = S.Context.getLValueReferenceType( 7481 S.Context.getCVRQualifiedType(CandidateTy, 7482 (Qualifiers::Volatile | 7483 Qualifiers::Restrict))); 7484 if (Args.size() == 1) 7485 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7486 else 7487 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7488 } 7489 } 7490 7491 } 7492 7493 public: 7494 BuiltinOperatorOverloadBuilder( 7495 Sema &S, ArrayRef<Expr *> Args, 7496 Qualifiers VisibleTypeConversionsQuals, 7497 bool HasArithmeticOrEnumeralCandidateType, 7498 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7499 OverloadCandidateSet &CandidateSet) 7500 : S(S), Args(Args), 7501 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7502 HasArithmeticOrEnumeralCandidateType( 7503 HasArithmeticOrEnumeralCandidateType), 7504 CandidateTypes(CandidateTypes), 7505 CandidateSet(CandidateSet) { 7506 // Validate some of our static helper constants in debug builds. 7507 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7508 "Invalid first promoted integral type"); 7509 assert(getArithmeticType(LastPromotedIntegralType - 1) 7510 == S.Context.UnsignedInt128Ty && 7511 "Invalid last promoted integral type"); 7512 assert(getArithmeticType(FirstPromotedArithmeticType) 7513 == S.Context.FloatTy && 7514 "Invalid first promoted arithmetic type"); 7515 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7516 == S.Context.UnsignedInt128Ty && 7517 "Invalid last promoted arithmetic type"); 7518 } 7519 7520 // C++ [over.built]p3: 7521 // 7522 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7523 // is either volatile or empty, there exist candidate operator 7524 // functions of the form 7525 // 7526 // VQ T& operator++(VQ T&); 7527 // T operator++(VQ T&, int); 7528 // 7529 // C++ [over.built]p4: 7530 // 7531 // For every pair (T, VQ), where T is an arithmetic type other 7532 // than bool, and VQ is either volatile or empty, there exist 7533 // candidate operator functions of the form 7534 // 7535 // VQ T& operator--(VQ T&); 7536 // T operator--(VQ T&, int); 7537 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7538 if (!HasArithmeticOrEnumeralCandidateType) 7539 return; 7540 7541 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7542 Arith < NumArithmeticTypes; ++Arith) { 7543 addPlusPlusMinusMinusStyleOverloads( 7544 getArithmeticType(Arith), 7545 VisibleTypeConversionsQuals.hasVolatile(), 7546 VisibleTypeConversionsQuals.hasRestrict()); 7547 } 7548 } 7549 7550 // C++ [over.built]p5: 7551 // 7552 // For every pair (T, VQ), where T is a cv-qualified or 7553 // cv-unqualified object type, and VQ is either volatile or 7554 // empty, there exist candidate operator functions of the form 7555 // 7556 // T*VQ& operator++(T*VQ&); 7557 // T*VQ& operator--(T*VQ&); 7558 // T* operator++(T*VQ&, int); 7559 // T* operator--(T*VQ&, int); 7560 void addPlusPlusMinusMinusPointerOverloads() { 7561 for (BuiltinCandidateTypeSet::iterator 7562 Ptr = CandidateTypes[0].pointer_begin(), 7563 PtrEnd = CandidateTypes[0].pointer_end(); 7564 Ptr != PtrEnd; ++Ptr) { 7565 // Skip pointer types that aren't pointers to object types. 7566 if (!(*Ptr)->getPointeeType()->isObjectType()) 7567 continue; 7568 7569 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7570 (!(*Ptr).isVolatileQualified() && 7571 VisibleTypeConversionsQuals.hasVolatile()), 7572 (!(*Ptr).isRestrictQualified() && 7573 VisibleTypeConversionsQuals.hasRestrict())); 7574 } 7575 } 7576 7577 // C++ [over.built]p6: 7578 // For every cv-qualified or cv-unqualified object type T, there 7579 // exist candidate operator functions of the form 7580 // 7581 // T& operator*(T*); 7582 // 7583 // C++ [over.built]p7: 7584 // For every function type T that does not have cv-qualifiers or a 7585 // ref-qualifier, there exist candidate operator functions of the form 7586 // T& operator*(T*); 7587 void addUnaryStarPointerOverloads() { 7588 for (BuiltinCandidateTypeSet::iterator 7589 Ptr = CandidateTypes[0].pointer_begin(), 7590 PtrEnd = CandidateTypes[0].pointer_end(); 7591 Ptr != PtrEnd; ++Ptr) { 7592 QualType ParamTy = *Ptr; 7593 QualType PointeeTy = ParamTy->getPointeeType(); 7594 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7595 continue; 7596 7597 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7598 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7599 continue; 7600 7601 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7602 &ParamTy, Args, CandidateSet); 7603 } 7604 } 7605 7606 // C++ [over.built]p9: 7607 // For every promoted arithmetic type T, there exist candidate 7608 // operator functions of the form 7609 // 7610 // T operator+(T); 7611 // T operator-(T); 7612 void addUnaryPlusOrMinusArithmeticOverloads() { 7613 if (!HasArithmeticOrEnumeralCandidateType) 7614 return; 7615 7616 for (unsigned Arith = FirstPromotedArithmeticType; 7617 Arith < LastPromotedArithmeticType; ++Arith) { 7618 QualType ArithTy = getArithmeticType(Arith); 7619 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7620 } 7621 7622 // Extension: We also add these operators for vector types. 7623 for (BuiltinCandidateTypeSet::iterator 7624 Vec = CandidateTypes[0].vector_begin(), 7625 VecEnd = CandidateTypes[0].vector_end(); 7626 Vec != VecEnd; ++Vec) { 7627 QualType VecTy = *Vec; 7628 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7629 } 7630 } 7631 7632 // C++ [over.built]p8: 7633 // For every type T, there exist candidate operator functions of 7634 // the form 7635 // 7636 // T* operator+(T*); 7637 void addUnaryPlusPointerOverloads() { 7638 for (BuiltinCandidateTypeSet::iterator 7639 Ptr = CandidateTypes[0].pointer_begin(), 7640 PtrEnd = CandidateTypes[0].pointer_end(); 7641 Ptr != PtrEnd; ++Ptr) { 7642 QualType ParamTy = *Ptr; 7643 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7644 } 7645 } 7646 7647 // C++ [over.built]p10: 7648 // For every promoted integral type T, there exist candidate 7649 // operator functions of the form 7650 // 7651 // T operator~(T); 7652 void addUnaryTildePromotedIntegralOverloads() { 7653 if (!HasArithmeticOrEnumeralCandidateType) 7654 return; 7655 7656 for (unsigned Int = FirstPromotedIntegralType; 7657 Int < LastPromotedIntegralType; ++Int) { 7658 QualType IntTy = getArithmeticType(Int); 7659 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7660 } 7661 7662 // Extension: We also add this operator for vector types. 7663 for (BuiltinCandidateTypeSet::iterator 7664 Vec = CandidateTypes[0].vector_begin(), 7665 VecEnd = CandidateTypes[0].vector_end(); 7666 Vec != VecEnd; ++Vec) { 7667 QualType VecTy = *Vec; 7668 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7669 } 7670 } 7671 7672 // C++ [over.match.oper]p16: 7673 // For every pointer to member type T or type std::nullptr_t, there 7674 // exist candidate operator functions of the form 7675 // 7676 // bool operator==(T,T); 7677 // bool operator!=(T,T); 7678 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 7679 /// Set of (canonical) types that we've already handled. 7680 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7681 7682 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7683 for (BuiltinCandidateTypeSet::iterator 7684 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7685 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7686 MemPtr != MemPtrEnd; 7687 ++MemPtr) { 7688 // Don't add the same builtin candidate twice. 7689 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7690 continue; 7691 7692 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7693 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7694 } 7695 7696 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7697 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7698 if (AddedTypes.insert(NullPtrTy).second) { 7699 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7700 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7701 CandidateSet); 7702 } 7703 } 7704 } 7705 } 7706 7707 // C++ [over.built]p15: 7708 // 7709 // For every T, where T is an enumeration type or a pointer type, 7710 // there exist candidate operator functions of the form 7711 // 7712 // bool operator<(T, T); 7713 // bool operator>(T, T); 7714 // bool operator<=(T, T); 7715 // bool operator>=(T, T); 7716 // bool operator==(T, T); 7717 // bool operator!=(T, T); 7718 void addRelationalPointerOrEnumeralOverloads() { 7719 // C++ [over.match.oper]p3: 7720 // [...]the built-in candidates include all of the candidate operator 7721 // functions defined in 13.6 that, compared to the given operator, [...] 7722 // do not have the same parameter-type-list as any non-template non-member 7723 // candidate. 7724 // 7725 // Note that in practice, this only affects enumeration types because there 7726 // aren't any built-in candidates of record type, and a user-defined operator 7727 // must have an operand of record or enumeration type. Also, the only other 7728 // overloaded operator with enumeration arguments, operator=, 7729 // cannot be overloaded for enumeration types, so this is the only place 7730 // where we must suppress candidates like this. 7731 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7732 UserDefinedBinaryOperators; 7733 7734 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7735 if (CandidateTypes[ArgIdx].enumeration_begin() != 7736 CandidateTypes[ArgIdx].enumeration_end()) { 7737 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7738 CEnd = CandidateSet.end(); 7739 C != CEnd; ++C) { 7740 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7741 continue; 7742 7743 if (C->Function->isFunctionTemplateSpecialization()) 7744 continue; 7745 7746 QualType FirstParamType = 7747 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7748 QualType SecondParamType = 7749 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7750 7751 // Skip if either parameter isn't of enumeral type. 7752 if (!FirstParamType->isEnumeralType() || 7753 !SecondParamType->isEnumeralType()) 7754 continue; 7755 7756 // Add this operator to the set of known user-defined operators. 7757 UserDefinedBinaryOperators.insert( 7758 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7759 S.Context.getCanonicalType(SecondParamType))); 7760 } 7761 } 7762 } 7763 7764 /// Set of (canonical) types that we've already handled. 7765 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7766 7767 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7768 for (BuiltinCandidateTypeSet::iterator 7769 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7770 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7771 Ptr != PtrEnd; ++Ptr) { 7772 // Don't add the same builtin candidate twice. 7773 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7774 continue; 7775 7776 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7777 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7778 } 7779 for (BuiltinCandidateTypeSet::iterator 7780 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7781 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7782 Enum != EnumEnd; ++Enum) { 7783 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7784 7785 // Don't add the same builtin candidate twice, or if a user defined 7786 // candidate exists. 7787 if (!AddedTypes.insert(CanonType).second || 7788 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7789 CanonType))) 7790 continue; 7791 7792 QualType ParamTypes[2] = { *Enum, *Enum }; 7793 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7794 } 7795 } 7796 } 7797 7798 // C++ [over.built]p13: 7799 // 7800 // For every cv-qualified or cv-unqualified object type T 7801 // there exist candidate operator functions of the form 7802 // 7803 // T* operator+(T*, ptrdiff_t); 7804 // T& operator[](T*, ptrdiff_t); [BELOW] 7805 // T* operator-(T*, ptrdiff_t); 7806 // T* operator+(ptrdiff_t, T*); 7807 // T& operator[](ptrdiff_t, T*); [BELOW] 7808 // 7809 // C++ [over.built]p14: 7810 // 7811 // For every T, where T is a pointer to object type, there 7812 // exist candidate operator functions of the form 7813 // 7814 // ptrdiff_t operator-(T, T); 7815 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7816 /// Set of (canonical) types that we've already handled. 7817 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7818 7819 for (int Arg = 0; Arg < 2; ++Arg) { 7820 QualType AsymmetricParamTypes[2] = { 7821 S.Context.getPointerDiffType(), 7822 S.Context.getPointerDiffType(), 7823 }; 7824 for (BuiltinCandidateTypeSet::iterator 7825 Ptr = CandidateTypes[Arg].pointer_begin(), 7826 PtrEnd = CandidateTypes[Arg].pointer_end(); 7827 Ptr != PtrEnd; ++Ptr) { 7828 QualType PointeeTy = (*Ptr)->getPointeeType(); 7829 if (!PointeeTy->isObjectType()) 7830 continue; 7831 7832 AsymmetricParamTypes[Arg] = *Ptr; 7833 if (Arg == 0 || Op == OO_Plus) { 7834 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7835 // T* operator+(ptrdiff_t, T*); 7836 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7837 } 7838 if (Op == OO_Minus) { 7839 // ptrdiff_t operator-(T, T); 7840 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7841 continue; 7842 7843 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7844 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7845 Args, CandidateSet); 7846 } 7847 } 7848 } 7849 } 7850 7851 // C++ [over.built]p12: 7852 // 7853 // For every pair of promoted arithmetic types L and R, there 7854 // exist candidate operator functions of the form 7855 // 7856 // LR operator*(L, R); 7857 // LR operator/(L, R); 7858 // LR operator+(L, R); 7859 // LR operator-(L, R); 7860 // bool operator<(L, R); 7861 // bool operator>(L, R); 7862 // bool operator<=(L, R); 7863 // bool operator>=(L, R); 7864 // bool operator==(L, R); 7865 // bool operator!=(L, R); 7866 // 7867 // where LR is the result of the usual arithmetic conversions 7868 // between types L and R. 7869 // 7870 // C++ [over.built]p24: 7871 // 7872 // For every pair of promoted arithmetic types L and R, there exist 7873 // candidate operator functions of the form 7874 // 7875 // LR operator?(bool, L, R); 7876 // 7877 // where LR is the result of the usual arithmetic conversions 7878 // between types L and R. 7879 // Our candidates ignore the first parameter. 7880 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7881 if (!HasArithmeticOrEnumeralCandidateType) 7882 return; 7883 7884 for (unsigned Left = FirstPromotedArithmeticType; 7885 Left < LastPromotedArithmeticType; ++Left) { 7886 for (unsigned Right = FirstPromotedArithmeticType; 7887 Right < LastPromotedArithmeticType; ++Right) { 7888 QualType LandR[2] = { getArithmeticType(Left), 7889 getArithmeticType(Right) }; 7890 QualType Result = 7891 isComparison ? S.Context.BoolTy 7892 : getUsualArithmeticConversions(Left, Right); 7893 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7894 } 7895 } 7896 7897 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7898 // conditional operator for vector types. 7899 for (BuiltinCandidateTypeSet::iterator 7900 Vec1 = CandidateTypes[0].vector_begin(), 7901 Vec1End = CandidateTypes[0].vector_end(); 7902 Vec1 != Vec1End; ++Vec1) { 7903 for (BuiltinCandidateTypeSet::iterator 7904 Vec2 = CandidateTypes[1].vector_begin(), 7905 Vec2End = CandidateTypes[1].vector_end(); 7906 Vec2 != Vec2End; ++Vec2) { 7907 QualType LandR[2] = { *Vec1, *Vec2 }; 7908 QualType Result = S.Context.BoolTy; 7909 if (!isComparison) { 7910 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7911 Result = *Vec1; 7912 else 7913 Result = *Vec2; 7914 } 7915 7916 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7917 } 7918 } 7919 } 7920 7921 // C++ [over.built]p17: 7922 // 7923 // For every pair of promoted integral types L and R, there 7924 // exist candidate operator functions of the form 7925 // 7926 // LR operator%(L, R); 7927 // LR operator&(L, R); 7928 // LR operator^(L, R); 7929 // LR operator|(L, R); 7930 // L operator<<(L, R); 7931 // L operator>>(L, R); 7932 // 7933 // where LR is the result of the usual arithmetic conversions 7934 // between types L and R. 7935 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7936 if (!HasArithmeticOrEnumeralCandidateType) 7937 return; 7938 7939 for (unsigned Left = FirstPromotedIntegralType; 7940 Left < LastPromotedIntegralType; ++Left) { 7941 for (unsigned Right = FirstPromotedIntegralType; 7942 Right < LastPromotedIntegralType; ++Right) { 7943 QualType LandR[2] = { getArithmeticType(Left), 7944 getArithmeticType(Right) }; 7945 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7946 ? LandR[0] 7947 : getUsualArithmeticConversions(Left, Right); 7948 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7949 } 7950 } 7951 } 7952 7953 // C++ [over.built]p20: 7954 // 7955 // For every pair (T, VQ), where T is an enumeration or 7956 // pointer to member type and VQ is either volatile or 7957 // empty, there exist candidate operator functions of the form 7958 // 7959 // VQ T& operator=(VQ T&, T); 7960 void addAssignmentMemberPointerOrEnumeralOverloads() { 7961 /// Set of (canonical) types that we've already handled. 7962 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7963 7964 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7965 for (BuiltinCandidateTypeSet::iterator 7966 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7967 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7968 Enum != EnumEnd; ++Enum) { 7969 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7970 continue; 7971 7972 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7973 } 7974 7975 for (BuiltinCandidateTypeSet::iterator 7976 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7977 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7978 MemPtr != MemPtrEnd; ++MemPtr) { 7979 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7980 continue; 7981 7982 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7983 } 7984 } 7985 } 7986 7987 // C++ [over.built]p19: 7988 // 7989 // For every pair (T, VQ), where T is any type and VQ is either 7990 // volatile or empty, there exist candidate operator functions 7991 // of the form 7992 // 7993 // T*VQ& operator=(T*VQ&, T*); 7994 // 7995 // C++ [over.built]p21: 7996 // 7997 // For every pair (T, VQ), where T is a cv-qualified or 7998 // cv-unqualified object type and VQ is either volatile or 7999 // empty, there exist candidate operator functions of the form 8000 // 8001 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8002 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8003 void addAssignmentPointerOverloads(bool isEqualOp) { 8004 /// Set of (canonical) types that we've already handled. 8005 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8006 8007 for (BuiltinCandidateTypeSet::iterator 8008 Ptr = CandidateTypes[0].pointer_begin(), 8009 PtrEnd = CandidateTypes[0].pointer_end(); 8010 Ptr != PtrEnd; ++Ptr) { 8011 // If this is operator=, keep track of the builtin candidates we added. 8012 if (isEqualOp) 8013 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8014 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8015 continue; 8016 8017 // non-volatile version 8018 QualType ParamTypes[2] = { 8019 S.Context.getLValueReferenceType(*Ptr), 8020 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8021 }; 8022 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8023 /*IsAssigmentOperator=*/ isEqualOp); 8024 8025 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8026 VisibleTypeConversionsQuals.hasVolatile(); 8027 if (NeedVolatile) { 8028 // volatile version 8029 ParamTypes[0] = 8030 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8031 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8032 /*IsAssigmentOperator=*/isEqualOp); 8033 } 8034 8035 if (!(*Ptr).isRestrictQualified() && 8036 VisibleTypeConversionsQuals.hasRestrict()) { 8037 // restrict version 8038 ParamTypes[0] 8039 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8040 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8041 /*IsAssigmentOperator=*/isEqualOp); 8042 8043 if (NeedVolatile) { 8044 // volatile restrict version 8045 ParamTypes[0] 8046 = S.Context.getLValueReferenceType( 8047 S.Context.getCVRQualifiedType(*Ptr, 8048 (Qualifiers::Volatile | 8049 Qualifiers::Restrict))); 8050 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8051 /*IsAssigmentOperator=*/isEqualOp); 8052 } 8053 } 8054 } 8055 8056 if (isEqualOp) { 8057 for (BuiltinCandidateTypeSet::iterator 8058 Ptr = CandidateTypes[1].pointer_begin(), 8059 PtrEnd = CandidateTypes[1].pointer_end(); 8060 Ptr != PtrEnd; ++Ptr) { 8061 // Make sure we don't add the same candidate twice. 8062 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8063 continue; 8064 8065 QualType ParamTypes[2] = { 8066 S.Context.getLValueReferenceType(*Ptr), 8067 *Ptr, 8068 }; 8069 8070 // non-volatile version 8071 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8072 /*IsAssigmentOperator=*/true); 8073 8074 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8075 VisibleTypeConversionsQuals.hasVolatile(); 8076 if (NeedVolatile) { 8077 // volatile version 8078 ParamTypes[0] = 8079 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8080 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8081 /*IsAssigmentOperator=*/true); 8082 } 8083 8084 if (!(*Ptr).isRestrictQualified() && 8085 VisibleTypeConversionsQuals.hasRestrict()) { 8086 // restrict version 8087 ParamTypes[0] 8088 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8089 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8090 /*IsAssigmentOperator=*/true); 8091 8092 if (NeedVolatile) { 8093 // volatile restrict version 8094 ParamTypes[0] 8095 = S.Context.getLValueReferenceType( 8096 S.Context.getCVRQualifiedType(*Ptr, 8097 (Qualifiers::Volatile | 8098 Qualifiers::Restrict))); 8099 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8100 /*IsAssigmentOperator=*/true); 8101 } 8102 } 8103 } 8104 } 8105 } 8106 8107 // C++ [over.built]p18: 8108 // 8109 // For every triple (L, VQ, R), where L is an arithmetic type, 8110 // VQ is either volatile or empty, and R is a promoted 8111 // arithmetic type, there exist candidate operator functions of 8112 // the form 8113 // 8114 // VQ L& operator=(VQ L&, R); 8115 // VQ L& operator*=(VQ L&, R); 8116 // VQ L& operator/=(VQ L&, R); 8117 // VQ L& operator+=(VQ L&, R); 8118 // VQ L& operator-=(VQ L&, R); 8119 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8120 if (!HasArithmeticOrEnumeralCandidateType) 8121 return; 8122 8123 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8124 for (unsigned Right = FirstPromotedArithmeticType; 8125 Right < LastPromotedArithmeticType; ++Right) { 8126 QualType ParamTypes[2]; 8127 ParamTypes[1] = getArithmeticType(Right); 8128 8129 // Add this built-in operator as a candidate (VQ is empty). 8130 ParamTypes[0] = 8131 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8132 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8133 /*IsAssigmentOperator=*/isEqualOp); 8134 8135 // Add this built-in operator as a candidate (VQ is 'volatile'). 8136 if (VisibleTypeConversionsQuals.hasVolatile()) { 8137 ParamTypes[0] = 8138 S.Context.getVolatileType(getArithmeticType(Left)); 8139 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8140 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8141 /*IsAssigmentOperator=*/isEqualOp); 8142 } 8143 } 8144 } 8145 8146 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8147 for (BuiltinCandidateTypeSet::iterator 8148 Vec1 = CandidateTypes[0].vector_begin(), 8149 Vec1End = CandidateTypes[0].vector_end(); 8150 Vec1 != Vec1End; ++Vec1) { 8151 for (BuiltinCandidateTypeSet::iterator 8152 Vec2 = CandidateTypes[1].vector_begin(), 8153 Vec2End = CandidateTypes[1].vector_end(); 8154 Vec2 != Vec2End; ++Vec2) { 8155 QualType ParamTypes[2]; 8156 ParamTypes[1] = *Vec2; 8157 // Add this built-in operator as a candidate (VQ is empty). 8158 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8159 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8160 /*IsAssigmentOperator=*/isEqualOp); 8161 8162 // Add this built-in operator as a candidate (VQ is 'volatile'). 8163 if (VisibleTypeConversionsQuals.hasVolatile()) { 8164 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8165 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8166 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8167 /*IsAssigmentOperator=*/isEqualOp); 8168 } 8169 } 8170 } 8171 } 8172 8173 // C++ [over.built]p22: 8174 // 8175 // For every triple (L, VQ, R), where L is an integral type, VQ 8176 // is either volatile or empty, and R is a promoted integral 8177 // type, there exist candidate operator functions of the form 8178 // 8179 // VQ L& operator%=(VQ L&, R); 8180 // VQ L& operator<<=(VQ L&, R); 8181 // VQ L& operator>>=(VQ L&, R); 8182 // VQ L& operator&=(VQ L&, R); 8183 // VQ L& operator^=(VQ L&, R); 8184 // VQ L& operator|=(VQ L&, R); 8185 void addAssignmentIntegralOverloads() { 8186 if (!HasArithmeticOrEnumeralCandidateType) 8187 return; 8188 8189 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8190 for (unsigned Right = FirstPromotedIntegralType; 8191 Right < LastPromotedIntegralType; ++Right) { 8192 QualType ParamTypes[2]; 8193 ParamTypes[1] = getArithmeticType(Right); 8194 8195 // Add this built-in operator as a candidate (VQ is empty). 8196 ParamTypes[0] = 8197 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8198 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8199 if (VisibleTypeConversionsQuals.hasVolatile()) { 8200 // Add this built-in operator as a candidate (VQ is 'volatile'). 8201 ParamTypes[0] = getArithmeticType(Left); 8202 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8203 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8204 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8205 } 8206 } 8207 } 8208 } 8209 8210 // C++ [over.operator]p23: 8211 // 8212 // There also exist candidate operator functions of the form 8213 // 8214 // bool operator!(bool); 8215 // bool operator&&(bool, bool); 8216 // bool operator||(bool, bool); 8217 void addExclaimOverload() { 8218 QualType ParamTy = S.Context.BoolTy; 8219 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8220 /*IsAssignmentOperator=*/false, 8221 /*NumContextualBoolArguments=*/1); 8222 } 8223 void addAmpAmpOrPipePipeOverload() { 8224 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8225 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8226 /*IsAssignmentOperator=*/false, 8227 /*NumContextualBoolArguments=*/2); 8228 } 8229 8230 // C++ [over.built]p13: 8231 // 8232 // For every cv-qualified or cv-unqualified object type T there 8233 // exist candidate operator functions of the form 8234 // 8235 // T* operator+(T*, ptrdiff_t); [ABOVE] 8236 // T& operator[](T*, ptrdiff_t); 8237 // T* operator-(T*, ptrdiff_t); [ABOVE] 8238 // T* operator+(ptrdiff_t, T*); [ABOVE] 8239 // T& operator[](ptrdiff_t, T*); 8240 void addSubscriptOverloads() { 8241 for (BuiltinCandidateTypeSet::iterator 8242 Ptr = CandidateTypes[0].pointer_begin(), 8243 PtrEnd = CandidateTypes[0].pointer_end(); 8244 Ptr != PtrEnd; ++Ptr) { 8245 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8246 QualType PointeeType = (*Ptr)->getPointeeType(); 8247 if (!PointeeType->isObjectType()) 8248 continue; 8249 8250 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8251 8252 // T& operator[](T*, ptrdiff_t) 8253 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8254 } 8255 8256 for (BuiltinCandidateTypeSet::iterator 8257 Ptr = CandidateTypes[1].pointer_begin(), 8258 PtrEnd = CandidateTypes[1].pointer_end(); 8259 Ptr != PtrEnd; ++Ptr) { 8260 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8261 QualType PointeeType = (*Ptr)->getPointeeType(); 8262 if (!PointeeType->isObjectType()) 8263 continue; 8264 8265 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8266 8267 // T& operator[](ptrdiff_t, T*) 8268 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8269 } 8270 } 8271 8272 // C++ [over.built]p11: 8273 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8274 // C1 is the same type as C2 or is a derived class of C2, T is an object 8275 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8276 // there exist candidate operator functions of the form 8277 // 8278 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8279 // 8280 // where CV12 is the union of CV1 and CV2. 8281 void addArrowStarOverloads() { 8282 for (BuiltinCandidateTypeSet::iterator 8283 Ptr = CandidateTypes[0].pointer_begin(), 8284 PtrEnd = CandidateTypes[0].pointer_end(); 8285 Ptr != PtrEnd; ++Ptr) { 8286 QualType C1Ty = (*Ptr); 8287 QualType C1; 8288 QualifierCollector Q1; 8289 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8290 if (!isa<RecordType>(C1)) 8291 continue; 8292 // heuristic to reduce number of builtin candidates in the set. 8293 // Add volatile/restrict version only if there are conversions to a 8294 // volatile/restrict type. 8295 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8296 continue; 8297 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8298 continue; 8299 for (BuiltinCandidateTypeSet::iterator 8300 MemPtr = CandidateTypes[1].member_pointer_begin(), 8301 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8302 MemPtr != MemPtrEnd; ++MemPtr) { 8303 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8304 QualType C2 = QualType(mptr->getClass(), 0); 8305 C2 = C2.getUnqualifiedType(); 8306 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8307 break; 8308 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8309 // build CV12 T& 8310 QualType T = mptr->getPointeeType(); 8311 if (!VisibleTypeConversionsQuals.hasVolatile() && 8312 T.isVolatileQualified()) 8313 continue; 8314 if (!VisibleTypeConversionsQuals.hasRestrict() && 8315 T.isRestrictQualified()) 8316 continue; 8317 T = Q1.apply(S.Context, T); 8318 QualType ResultTy = S.Context.getLValueReferenceType(T); 8319 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8320 } 8321 } 8322 } 8323 8324 // Note that we don't consider the first argument, since it has been 8325 // contextually converted to bool long ago. The candidates below are 8326 // therefore added as binary. 8327 // 8328 // C++ [over.built]p25: 8329 // For every type T, where T is a pointer, pointer-to-member, or scoped 8330 // enumeration type, there exist candidate operator functions of the form 8331 // 8332 // T operator?(bool, T, T); 8333 // 8334 void addConditionalOperatorOverloads() { 8335 /// Set of (canonical) types that we've already handled. 8336 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8337 8338 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8339 for (BuiltinCandidateTypeSet::iterator 8340 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8341 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8342 Ptr != PtrEnd; ++Ptr) { 8343 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8344 continue; 8345 8346 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8347 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8348 } 8349 8350 for (BuiltinCandidateTypeSet::iterator 8351 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8352 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8353 MemPtr != MemPtrEnd; ++MemPtr) { 8354 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8355 continue; 8356 8357 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8358 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8359 } 8360 8361 if (S.getLangOpts().CPlusPlus11) { 8362 for (BuiltinCandidateTypeSet::iterator 8363 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8364 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8365 Enum != EnumEnd; ++Enum) { 8366 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8367 continue; 8368 8369 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8370 continue; 8371 8372 QualType ParamTypes[2] = { *Enum, *Enum }; 8373 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8374 } 8375 } 8376 } 8377 } 8378 }; 8379 8380 } // end anonymous namespace 8381 8382 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8383 /// operator overloads to the candidate set (C++ [over.built]), based 8384 /// on the operator @p Op and the arguments given. For example, if the 8385 /// operator is a binary '+', this routine might add "int 8386 /// operator+(int, int)" to cover integer addition. 8387 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8388 SourceLocation OpLoc, 8389 ArrayRef<Expr *> Args, 8390 OverloadCandidateSet &CandidateSet) { 8391 // Find all of the types that the arguments can convert to, but only 8392 // if the operator we're looking at has built-in operator candidates 8393 // that make use of these types. Also record whether we encounter non-record 8394 // candidate types or either arithmetic or enumeral candidate types. 8395 Qualifiers VisibleTypeConversionsQuals; 8396 VisibleTypeConversionsQuals.addConst(); 8397 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8398 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8399 8400 bool HasNonRecordCandidateType = false; 8401 bool HasArithmeticOrEnumeralCandidateType = false; 8402 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8403 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8404 CandidateTypes.emplace_back(*this); 8405 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8406 OpLoc, 8407 true, 8408 (Op == OO_Exclaim || 8409 Op == OO_AmpAmp || 8410 Op == OO_PipePipe), 8411 VisibleTypeConversionsQuals); 8412 HasNonRecordCandidateType = HasNonRecordCandidateType || 8413 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8414 HasArithmeticOrEnumeralCandidateType = 8415 HasArithmeticOrEnumeralCandidateType || 8416 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8417 } 8418 8419 // Exit early when no non-record types have been added to the candidate set 8420 // for any of the arguments to the operator. 8421 // 8422 // We can't exit early for !, ||, or &&, since there we have always have 8423 // 'bool' overloads. 8424 if (!HasNonRecordCandidateType && 8425 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8426 return; 8427 8428 // Setup an object to manage the common state for building overloads. 8429 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8430 VisibleTypeConversionsQuals, 8431 HasArithmeticOrEnumeralCandidateType, 8432 CandidateTypes, CandidateSet); 8433 8434 // Dispatch over the operation to add in only those overloads which apply. 8435 switch (Op) { 8436 case OO_None: 8437 case NUM_OVERLOADED_OPERATORS: 8438 llvm_unreachable("Expected an overloaded operator"); 8439 8440 case OO_New: 8441 case OO_Delete: 8442 case OO_Array_New: 8443 case OO_Array_Delete: 8444 case OO_Call: 8445 llvm_unreachable( 8446 "Special operators don't use AddBuiltinOperatorCandidates"); 8447 8448 case OO_Comma: 8449 case OO_Arrow: 8450 case OO_Coawait: 8451 // C++ [over.match.oper]p3: 8452 // -- For the operator ',', the unary operator '&', the 8453 // operator '->', or the operator 'co_await', the 8454 // built-in candidates set is empty. 8455 break; 8456 8457 case OO_Plus: // '+' is either unary or binary 8458 if (Args.size() == 1) 8459 OpBuilder.addUnaryPlusPointerOverloads(); 8460 // Fall through. 8461 8462 case OO_Minus: // '-' is either unary or binary 8463 if (Args.size() == 1) { 8464 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8465 } else { 8466 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8467 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8468 } 8469 break; 8470 8471 case OO_Star: // '*' is either unary or binary 8472 if (Args.size() == 1) 8473 OpBuilder.addUnaryStarPointerOverloads(); 8474 else 8475 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8476 break; 8477 8478 case OO_Slash: 8479 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8480 break; 8481 8482 case OO_PlusPlus: 8483 case OO_MinusMinus: 8484 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8485 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8486 break; 8487 8488 case OO_EqualEqual: 8489 case OO_ExclaimEqual: 8490 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8491 // Fall through. 8492 8493 case OO_Less: 8494 case OO_Greater: 8495 case OO_LessEqual: 8496 case OO_GreaterEqual: 8497 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8498 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8499 break; 8500 8501 case OO_Percent: 8502 case OO_Caret: 8503 case OO_Pipe: 8504 case OO_LessLess: 8505 case OO_GreaterGreater: 8506 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8507 break; 8508 8509 case OO_Amp: // '&' is either unary or binary 8510 if (Args.size() == 1) 8511 // C++ [over.match.oper]p3: 8512 // -- For the operator ',', the unary operator '&', or the 8513 // operator '->', the built-in candidates set is empty. 8514 break; 8515 8516 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8517 break; 8518 8519 case OO_Tilde: 8520 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8521 break; 8522 8523 case OO_Equal: 8524 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8525 // Fall through. 8526 8527 case OO_PlusEqual: 8528 case OO_MinusEqual: 8529 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8530 // Fall through. 8531 8532 case OO_StarEqual: 8533 case OO_SlashEqual: 8534 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8535 break; 8536 8537 case OO_PercentEqual: 8538 case OO_LessLessEqual: 8539 case OO_GreaterGreaterEqual: 8540 case OO_AmpEqual: 8541 case OO_CaretEqual: 8542 case OO_PipeEqual: 8543 OpBuilder.addAssignmentIntegralOverloads(); 8544 break; 8545 8546 case OO_Exclaim: 8547 OpBuilder.addExclaimOverload(); 8548 break; 8549 8550 case OO_AmpAmp: 8551 case OO_PipePipe: 8552 OpBuilder.addAmpAmpOrPipePipeOverload(); 8553 break; 8554 8555 case OO_Subscript: 8556 OpBuilder.addSubscriptOverloads(); 8557 break; 8558 8559 case OO_ArrowStar: 8560 OpBuilder.addArrowStarOverloads(); 8561 break; 8562 8563 case OO_Conditional: 8564 OpBuilder.addConditionalOperatorOverloads(); 8565 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8566 break; 8567 } 8568 } 8569 8570 /// \brief Add function candidates found via argument-dependent lookup 8571 /// to the set of overloading candidates. 8572 /// 8573 /// This routine performs argument-dependent name lookup based on the 8574 /// given function name (which may also be an operator name) and adds 8575 /// all of the overload candidates found by ADL to the overload 8576 /// candidate set (C++ [basic.lookup.argdep]). 8577 void 8578 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8579 SourceLocation Loc, 8580 ArrayRef<Expr *> Args, 8581 TemplateArgumentListInfo *ExplicitTemplateArgs, 8582 OverloadCandidateSet& CandidateSet, 8583 bool PartialOverloading) { 8584 ADLResult Fns; 8585 8586 // FIXME: This approach for uniquing ADL results (and removing 8587 // redundant candidates from the set) relies on pointer-equality, 8588 // which means we need to key off the canonical decl. However, 8589 // always going back to the canonical decl might not get us the 8590 // right set of default arguments. What default arguments are 8591 // we supposed to consider on ADL candidates, anyway? 8592 8593 // FIXME: Pass in the explicit template arguments? 8594 ArgumentDependentLookup(Name, Loc, Args, Fns); 8595 8596 // Erase all of the candidates we already knew about. 8597 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8598 CandEnd = CandidateSet.end(); 8599 Cand != CandEnd; ++Cand) 8600 if (Cand->Function) { 8601 Fns.erase(Cand->Function); 8602 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8603 Fns.erase(FunTmpl); 8604 } 8605 8606 // For each of the ADL candidates we found, add it to the overload 8607 // set. 8608 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8609 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8610 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8611 if (ExplicitTemplateArgs) 8612 continue; 8613 8614 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8615 PartialOverloading); 8616 } else 8617 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8618 FoundDecl, ExplicitTemplateArgs, 8619 Args, CandidateSet, PartialOverloading); 8620 } 8621 } 8622 8623 namespace { 8624 enum class Comparison { Equal, Better, Worse }; 8625 } 8626 8627 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8628 /// overload resolution. 8629 /// 8630 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8631 /// Cand1's first N enable_if attributes have precisely the same conditions as 8632 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8633 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8634 /// 8635 /// Note that you can have a pair of candidates such that Cand1's enable_if 8636 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8637 /// worse than Cand1's. 8638 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8639 const FunctionDecl *Cand2) { 8640 // Common case: One (or both) decls don't have enable_if attrs. 8641 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8642 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8643 if (!Cand1Attr || !Cand2Attr) { 8644 if (Cand1Attr == Cand2Attr) 8645 return Comparison::Equal; 8646 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8647 } 8648 8649 // FIXME: The next several lines are just 8650 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8651 // instead of reverse order which is how they're stored in the AST. 8652 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8653 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8654 8655 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8656 // has fewer enable_if attributes than Cand2. 8657 if (Cand1Attrs.size() < Cand2Attrs.size()) 8658 return Comparison::Worse; 8659 8660 auto Cand1I = Cand1Attrs.begin(); 8661 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8662 for (auto &Cand2A : Cand2Attrs) { 8663 Cand1ID.clear(); 8664 Cand2ID.clear(); 8665 8666 auto &Cand1A = *Cand1I++; 8667 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8668 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8669 if (Cand1ID != Cand2ID) 8670 return Comparison::Worse; 8671 } 8672 8673 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8674 } 8675 8676 /// isBetterOverloadCandidate - Determines whether the first overload 8677 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8678 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8679 const OverloadCandidate &Cand2, 8680 SourceLocation Loc, 8681 bool UserDefinedConversion) { 8682 // Define viable functions to be better candidates than non-viable 8683 // functions. 8684 if (!Cand2.Viable) 8685 return Cand1.Viable; 8686 else if (!Cand1.Viable) 8687 return false; 8688 8689 // C++ [over.match.best]p1: 8690 // 8691 // -- if F is a static member function, ICS1(F) is defined such 8692 // that ICS1(F) is neither better nor worse than ICS1(G) for 8693 // any function G, and, symmetrically, ICS1(G) is neither 8694 // better nor worse than ICS1(F). 8695 unsigned StartArg = 0; 8696 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8697 StartArg = 1; 8698 8699 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 8700 // We don't allow incompatible pointer conversions in C++. 8701 if (!S.getLangOpts().CPlusPlus) 8702 return ICS.isStandard() && 8703 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 8704 8705 // The only ill-formed conversion we allow in C++ is the string literal to 8706 // char* conversion, which is only considered ill-formed after C++11. 8707 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 8708 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 8709 }; 8710 8711 // Define functions that don't require ill-formed conversions for a given 8712 // argument to be better candidates than functions that do. 8713 unsigned NumArgs = Cand1.NumConversions; 8714 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8715 bool HasBetterConversion = false; 8716 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8717 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 8718 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 8719 if (Cand1Bad != Cand2Bad) { 8720 if (Cand1Bad) 8721 return false; 8722 HasBetterConversion = true; 8723 } 8724 } 8725 8726 if (HasBetterConversion) 8727 return true; 8728 8729 // C++ [over.match.best]p1: 8730 // A viable function F1 is defined to be a better function than another 8731 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8732 // conversion sequence than ICSi(F2), and then... 8733 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8734 switch (CompareImplicitConversionSequences(S, Loc, 8735 Cand1.Conversions[ArgIdx], 8736 Cand2.Conversions[ArgIdx])) { 8737 case ImplicitConversionSequence::Better: 8738 // Cand1 has a better conversion sequence. 8739 HasBetterConversion = true; 8740 break; 8741 8742 case ImplicitConversionSequence::Worse: 8743 // Cand1 can't be better than Cand2. 8744 return false; 8745 8746 case ImplicitConversionSequence::Indistinguishable: 8747 // Do nothing. 8748 break; 8749 } 8750 } 8751 8752 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8753 // ICSj(F2), or, if not that, 8754 if (HasBetterConversion) 8755 return true; 8756 8757 // -- the context is an initialization by user-defined conversion 8758 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8759 // from the return type of F1 to the destination type (i.e., 8760 // the type of the entity being initialized) is a better 8761 // conversion sequence than the standard conversion sequence 8762 // from the return type of F2 to the destination type. 8763 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8764 isa<CXXConversionDecl>(Cand1.Function) && 8765 isa<CXXConversionDecl>(Cand2.Function)) { 8766 // First check whether we prefer one of the conversion functions over the 8767 // other. This only distinguishes the results in non-standard, extension 8768 // cases such as the conversion from a lambda closure type to a function 8769 // pointer or block. 8770 ImplicitConversionSequence::CompareKind Result = 8771 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8772 if (Result == ImplicitConversionSequence::Indistinguishable) 8773 Result = CompareStandardConversionSequences(S, Loc, 8774 Cand1.FinalConversion, 8775 Cand2.FinalConversion); 8776 8777 if (Result != ImplicitConversionSequence::Indistinguishable) 8778 return Result == ImplicitConversionSequence::Better; 8779 8780 // FIXME: Compare kind of reference binding if conversion functions 8781 // convert to a reference type used in direct reference binding, per 8782 // C++14 [over.match.best]p1 section 2 bullet 3. 8783 } 8784 8785 // -- F1 is a non-template function and F2 is a function template 8786 // specialization, or, if not that, 8787 bool Cand1IsSpecialization = Cand1.Function && 8788 Cand1.Function->getPrimaryTemplate(); 8789 bool Cand2IsSpecialization = Cand2.Function && 8790 Cand2.Function->getPrimaryTemplate(); 8791 if (Cand1IsSpecialization != Cand2IsSpecialization) 8792 return Cand2IsSpecialization; 8793 8794 // -- F1 and F2 are function template specializations, and the function 8795 // template for F1 is more specialized than the template for F2 8796 // according to the partial ordering rules described in 14.5.5.2, or, 8797 // if not that, 8798 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8799 if (FunctionTemplateDecl *BetterTemplate 8800 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8801 Cand2.Function->getPrimaryTemplate(), 8802 Loc, 8803 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8804 : TPOC_Call, 8805 Cand1.ExplicitCallArguments, 8806 Cand2.ExplicitCallArguments)) 8807 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8808 } 8809 8810 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 8811 // A derived-class constructor beats an (inherited) base class constructor. 8812 bool Cand1IsInherited = 8813 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 8814 bool Cand2IsInherited = 8815 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 8816 if (Cand1IsInherited != Cand2IsInherited) 8817 return Cand2IsInherited; 8818 else if (Cand1IsInherited) { 8819 assert(Cand2IsInherited); 8820 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 8821 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 8822 if (Cand1Class->isDerivedFrom(Cand2Class)) 8823 return true; 8824 if (Cand2Class->isDerivedFrom(Cand1Class)) 8825 return false; 8826 // Inherited from sibling base classes: still ambiguous. 8827 } 8828 8829 // Check for enable_if value-based overload resolution. 8830 if (Cand1.Function && Cand2.Function) { 8831 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8832 if (Cmp != Comparison::Equal) 8833 return Cmp == Comparison::Better; 8834 } 8835 8836 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 8837 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8838 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8839 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8840 } 8841 8842 bool HasPS1 = Cand1.Function != nullptr && 8843 functionHasPassObjectSizeParams(Cand1.Function); 8844 bool HasPS2 = Cand2.Function != nullptr && 8845 functionHasPassObjectSizeParams(Cand2.Function); 8846 return HasPS1 != HasPS2 && HasPS1; 8847 } 8848 8849 /// Determine whether two declarations are "equivalent" for the purposes of 8850 /// name lookup and overload resolution. This applies when the same internal/no 8851 /// linkage entity is defined by two modules (probably by textually including 8852 /// the same header). In such a case, we don't consider the declarations to 8853 /// declare the same entity, but we also don't want lookups with both 8854 /// declarations visible to be ambiguous in some cases (this happens when using 8855 /// a modularized libstdc++). 8856 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8857 const NamedDecl *B) { 8858 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8859 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8860 if (!VA || !VB) 8861 return false; 8862 8863 // The declarations must be declaring the same name as an internal linkage 8864 // entity in different modules. 8865 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8866 VB->getDeclContext()->getRedeclContext()) || 8867 getOwningModule(const_cast<ValueDecl *>(VA)) == 8868 getOwningModule(const_cast<ValueDecl *>(VB)) || 8869 VA->isExternallyVisible() || VB->isExternallyVisible()) 8870 return false; 8871 8872 // Check that the declarations appear to be equivalent. 8873 // 8874 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8875 // For constants and functions, we should check the initializer or body is 8876 // the same. For non-constant variables, we shouldn't allow it at all. 8877 if (Context.hasSameType(VA->getType(), VB->getType())) 8878 return true; 8879 8880 // Enum constants within unnamed enumerations will have different types, but 8881 // may still be similar enough to be interchangeable for our purposes. 8882 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8883 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8884 // Only handle anonymous enums. If the enumerations were named and 8885 // equivalent, they would have been merged to the same type. 8886 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8887 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8888 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8889 !Context.hasSameType(EnumA->getIntegerType(), 8890 EnumB->getIntegerType())) 8891 return false; 8892 // Allow this only if the value is the same for both enumerators. 8893 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8894 } 8895 } 8896 8897 // Nothing else is sufficiently similar. 8898 return false; 8899 } 8900 8901 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8902 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8903 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8904 8905 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8906 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8907 << !M << (M ? M->getFullModuleName() : ""); 8908 8909 for (auto *E : Equiv) { 8910 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8911 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8912 << !M << (M ? M->getFullModuleName() : ""); 8913 } 8914 } 8915 8916 /// \brief Computes the best viable function (C++ 13.3.3) 8917 /// within an overload candidate set. 8918 /// 8919 /// \param Loc The location of the function name (or operator symbol) for 8920 /// which overload resolution occurs. 8921 /// 8922 /// \param Best If overload resolution was successful or found a deleted 8923 /// function, \p Best points to the candidate function found. 8924 /// 8925 /// \returns The result of overload resolution. 8926 OverloadingResult 8927 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8928 iterator &Best, 8929 bool UserDefinedConversion) { 8930 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 8931 std::transform(begin(), end(), std::back_inserter(Candidates), 8932 [](OverloadCandidate &Cand) { return &Cand; }); 8933 8934 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 8935 // are accepted by both clang and NVCC. However, during a particular 8936 // compilation mode only one call variant is viable. We need to 8937 // exclude non-viable overload candidates from consideration based 8938 // only on their host/device attributes. Specifically, if one 8939 // candidate call is WrongSide and the other is SameSide, we ignore 8940 // the WrongSide candidate. 8941 if (S.getLangOpts().CUDA) { 8942 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8943 bool ContainsSameSideCandidate = 8944 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 8945 return Cand->Function && 8946 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8947 Sema::CFP_SameSide; 8948 }); 8949 if (ContainsSameSideCandidate) { 8950 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 8951 return Cand->Function && 8952 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8953 Sema::CFP_WrongSide; 8954 }; 8955 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(), 8956 IsWrongSideCandidate), 8957 Candidates.end()); 8958 } 8959 } 8960 8961 // Find the best viable function. 8962 Best = end(); 8963 for (auto *Cand : Candidates) 8964 if (Cand->Viable) 8965 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8966 UserDefinedConversion)) 8967 Best = Cand; 8968 8969 // If we didn't find any viable functions, abort. 8970 if (Best == end()) 8971 return OR_No_Viable_Function; 8972 8973 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8974 8975 // Make sure that this function is better than every other viable 8976 // function. If not, we have an ambiguity. 8977 for (auto *Cand : Candidates) { 8978 if (Cand->Viable && 8979 Cand != Best && 8980 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8981 UserDefinedConversion)) { 8982 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8983 Cand->Function)) { 8984 EquivalentCands.push_back(Cand->Function); 8985 continue; 8986 } 8987 8988 Best = end(); 8989 return OR_Ambiguous; 8990 } 8991 } 8992 8993 // Best is the best viable function. 8994 if (Best->Function && 8995 (Best->Function->isDeleted() || 8996 S.isFunctionConsideredUnavailable(Best->Function))) 8997 return OR_Deleted; 8998 8999 if (!EquivalentCands.empty()) 9000 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9001 EquivalentCands); 9002 9003 return OR_Success; 9004 } 9005 9006 namespace { 9007 9008 enum OverloadCandidateKind { 9009 oc_function, 9010 oc_method, 9011 oc_constructor, 9012 oc_function_template, 9013 oc_method_template, 9014 oc_constructor_template, 9015 oc_implicit_default_constructor, 9016 oc_implicit_copy_constructor, 9017 oc_implicit_move_constructor, 9018 oc_implicit_copy_assignment, 9019 oc_implicit_move_assignment, 9020 oc_inherited_constructor, 9021 oc_inherited_constructor_template 9022 }; 9023 9024 static OverloadCandidateKind 9025 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9026 std::string &Description) { 9027 bool isTemplate = false; 9028 9029 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9030 isTemplate = true; 9031 Description = S.getTemplateArgumentBindingsText( 9032 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9033 } 9034 9035 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9036 if (!Ctor->isImplicit()) { 9037 if (isa<ConstructorUsingShadowDecl>(Found)) 9038 return isTemplate ? oc_inherited_constructor_template 9039 : oc_inherited_constructor; 9040 else 9041 return isTemplate ? oc_constructor_template : oc_constructor; 9042 } 9043 9044 if (Ctor->isDefaultConstructor()) 9045 return oc_implicit_default_constructor; 9046 9047 if (Ctor->isMoveConstructor()) 9048 return oc_implicit_move_constructor; 9049 9050 assert(Ctor->isCopyConstructor() && 9051 "unexpected sort of implicit constructor"); 9052 return oc_implicit_copy_constructor; 9053 } 9054 9055 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9056 // This actually gets spelled 'candidate function' for now, but 9057 // it doesn't hurt to split it out. 9058 if (!Meth->isImplicit()) 9059 return isTemplate ? oc_method_template : oc_method; 9060 9061 if (Meth->isMoveAssignmentOperator()) 9062 return oc_implicit_move_assignment; 9063 9064 if (Meth->isCopyAssignmentOperator()) 9065 return oc_implicit_copy_assignment; 9066 9067 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9068 return oc_method; 9069 } 9070 9071 return isTemplate ? oc_function_template : oc_function; 9072 } 9073 9074 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9075 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9076 // set. 9077 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9078 S.Diag(FoundDecl->getLocation(), 9079 diag::note_ovl_candidate_inherited_constructor) 9080 << Shadow->getNominatedBaseClass(); 9081 } 9082 9083 } // end anonymous namespace 9084 9085 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9086 const FunctionDecl *FD) { 9087 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9088 bool AlwaysTrue; 9089 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9090 return false; 9091 if (!AlwaysTrue) 9092 return false; 9093 } 9094 return true; 9095 } 9096 9097 /// \brief Returns true if we can take the address of the function. 9098 /// 9099 /// \param Complain - If true, we'll emit a diagnostic 9100 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9101 /// we in overload resolution? 9102 /// \param Loc - The location of the statement we're complaining about. Ignored 9103 /// if we're not complaining, or if we're in overload resolution. 9104 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9105 bool Complain, 9106 bool InOverloadResolution, 9107 SourceLocation Loc) { 9108 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9109 if (Complain) { 9110 if (InOverloadResolution) 9111 S.Diag(FD->getLocStart(), 9112 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9113 else 9114 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9115 } 9116 return false; 9117 } 9118 9119 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9120 return P->hasAttr<PassObjectSizeAttr>(); 9121 }); 9122 if (I == FD->param_end()) 9123 return true; 9124 9125 if (Complain) { 9126 // Add one to ParamNo because it's user-facing 9127 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9128 if (InOverloadResolution) 9129 S.Diag(FD->getLocation(), 9130 diag::note_ovl_candidate_has_pass_object_size_params) 9131 << ParamNo; 9132 else 9133 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9134 << FD << ParamNo; 9135 } 9136 return false; 9137 } 9138 9139 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9140 const FunctionDecl *FD) { 9141 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9142 /*InOverloadResolution=*/true, 9143 /*Loc=*/SourceLocation()); 9144 } 9145 9146 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9147 bool Complain, 9148 SourceLocation Loc) { 9149 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9150 /*InOverloadResolution=*/false, 9151 Loc); 9152 } 9153 9154 // Notes the location of an overload candidate. 9155 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9156 QualType DestType, bool TakingAddress) { 9157 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9158 return; 9159 9160 std::string FnDesc; 9161 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9162 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9163 << (unsigned) K << Fn << FnDesc; 9164 9165 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9166 Diag(Fn->getLocation(), PD); 9167 MaybeEmitInheritedConstructorNote(*this, Found); 9168 } 9169 9170 // Notes the location of all overload candidates designated through 9171 // OverloadedExpr 9172 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9173 bool TakingAddress) { 9174 assert(OverloadedExpr->getType() == Context.OverloadTy); 9175 9176 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9177 OverloadExpr *OvlExpr = Ovl.Expression; 9178 9179 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9180 IEnd = OvlExpr->decls_end(); 9181 I != IEnd; ++I) { 9182 if (FunctionTemplateDecl *FunTmpl = 9183 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9184 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9185 TakingAddress); 9186 } else if (FunctionDecl *Fun 9187 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9188 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9189 } 9190 } 9191 } 9192 9193 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9194 /// "lead" diagnostic; it will be given two arguments, the source and 9195 /// target types of the conversion. 9196 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9197 Sema &S, 9198 SourceLocation CaretLoc, 9199 const PartialDiagnostic &PDiag) const { 9200 S.Diag(CaretLoc, PDiag) 9201 << Ambiguous.getFromType() << Ambiguous.getToType(); 9202 // FIXME: The note limiting machinery is borrowed from 9203 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9204 // refactoring here. 9205 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9206 unsigned CandsShown = 0; 9207 AmbiguousConversionSequence::const_iterator I, E; 9208 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9209 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9210 break; 9211 ++CandsShown; 9212 S.NoteOverloadCandidate(I->first, I->second); 9213 } 9214 if (I != E) 9215 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9216 } 9217 9218 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9219 unsigned I, bool TakingCandidateAddress) { 9220 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9221 assert(Conv.isBad()); 9222 assert(Cand->Function && "for now, candidate must be a function"); 9223 FunctionDecl *Fn = Cand->Function; 9224 9225 // There's a conversion slot for the object argument if this is a 9226 // non-constructor method. Note that 'I' corresponds the 9227 // conversion-slot index. 9228 bool isObjectArgument = false; 9229 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9230 if (I == 0) 9231 isObjectArgument = true; 9232 else 9233 I--; 9234 } 9235 9236 std::string FnDesc; 9237 OverloadCandidateKind FnKind = 9238 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9239 9240 Expr *FromExpr = Conv.Bad.FromExpr; 9241 QualType FromTy = Conv.Bad.getFromType(); 9242 QualType ToTy = Conv.Bad.getToType(); 9243 9244 if (FromTy == S.Context.OverloadTy) { 9245 assert(FromExpr && "overload set argument came from implicit argument?"); 9246 Expr *E = FromExpr->IgnoreParens(); 9247 if (isa<UnaryOperator>(E)) 9248 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9249 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9250 9251 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9252 << (unsigned) FnKind << FnDesc 9253 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9254 << ToTy << Name << I+1; 9255 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9256 return; 9257 } 9258 9259 // Do some hand-waving analysis to see if the non-viability is due 9260 // to a qualifier mismatch. 9261 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9262 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9263 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9264 CToTy = RT->getPointeeType(); 9265 else { 9266 // TODO: detect and diagnose the full richness of const mismatches. 9267 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9268 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9269 CFromTy = FromPT->getPointeeType(); 9270 CToTy = ToPT->getPointeeType(); 9271 } 9272 } 9273 9274 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9275 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9276 Qualifiers FromQs = CFromTy.getQualifiers(); 9277 Qualifiers ToQs = CToTy.getQualifiers(); 9278 9279 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9280 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9281 << (unsigned) FnKind << FnDesc 9282 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9283 << FromTy 9284 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9285 << (unsigned) isObjectArgument << I+1; 9286 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9287 return; 9288 } 9289 9290 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9291 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9292 << (unsigned) FnKind << FnDesc 9293 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9294 << FromTy 9295 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9296 << (unsigned) isObjectArgument << I+1; 9297 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9298 return; 9299 } 9300 9301 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9302 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9303 << (unsigned) FnKind << FnDesc 9304 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9305 << FromTy 9306 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9307 << (unsigned) isObjectArgument << I+1; 9308 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9309 return; 9310 } 9311 9312 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9313 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9314 << (unsigned) FnKind << FnDesc 9315 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9316 << FromTy << FromQs.hasUnaligned() << I+1; 9317 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9318 return; 9319 } 9320 9321 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9322 assert(CVR && "unexpected qualifiers mismatch"); 9323 9324 if (isObjectArgument) { 9325 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9326 << (unsigned) FnKind << FnDesc 9327 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9328 << FromTy << (CVR - 1); 9329 } else { 9330 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9331 << (unsigned) FnKind << FnDesc 9332 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9333 << FromTy << (CVR - 1) << I+1; 9334 } 9335 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9336 return; 9337 } 9338 9339 // Special diagnostic for failure to convert an initializer list, since 9340 // telling the user that it has type void is not useful. 9341 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9342 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9343 << (unsigned) FnKind << FnDesc 9344 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9345 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9346 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9347 return; 9348 } 9349 9350 // Diagnose references or pointers to incomplete types differently, 9351 // since it's far from impossible that the incompleteness triggered 9352 // the failure. 9353 QualType TempFromTy = FromTy.getNonReferenceType(); 9354 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9355 TempFromTy = PTy->getPointeeType(); 9356 if (TempFromTy->isIncompleteType()) { 9357 // Emit the generic diagnostic and, optionally, add the hints to it. 9358 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9359 << (unsigned) FnKind << FnDesc 9360 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9361 << FromTy << ToTy << (unsigned) isObjectArgument << I+1 9362 << (unsigned) (Cand->Fix.Kind); 9363 9364 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9365 return; 9366 } 9367 9368 // Diagnose base -> derived pointer conversions. 9369 unsigned BaseToDerivedConversion = 0; 9370 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9371 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9372 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9373 FromPtrTy->getPointeeType()) && 9374 !FromPtrTy->getPointeeType()->isIncompleteType() && 9375 !ToPtrTy->getPointeeType()->isIncompleteType() && 9376 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9377 FromPtrTy->getPointeeType())) 9378 BaseToDerivedConversion = 1; 9379 } 9380 } else if (const ObjCObjectPointerType *FromPtrTy 9381 = FromTy->getAs<ObjCObjectPointerType>()) { 9382 if (const ObjCObjectPointerType *ToPtrTy 9383 = ToTy->getAs<ObjCObjectPointerType>()) 9384 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9385 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9386 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9387 FromPtrTy->getPointeeType()) && 9388 FromIface->isSuperClassOf(ToIface)) 9389 BaseToDerivedConversion = 2; 9390 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9391 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9392 !FromTy->isIncompleteType() && 9393 !ToRefTy->getPointeeType()->isIncompleteType() && 9394 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9395 BaseToDerivedConversion = 3; 9396 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9397 ToTy.getNonReferenceType().getCanonicalType() == 9398 FromTy.getNonReferenceType().getCanonicalType()) { 9399 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9400 << (unsigned) FnKind << FnDesc 9401 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9402 << (unsigned) isObjectArgument << I + 1; 9403 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9404 return; 9405 } 9406 } 9407 9408 if (BaseToDerivedConversion) { 9409 S.Diag(Fn->getLocation(), 9410 diag::note_ovl_candidate_bad_base_to_derived_conv) 9411 << (unsigned) FnKind << FnDesc 9412 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9413 << (BaseToDerivedConversion - 1) 9414 << FromTy << ToTy << I+1; 9415 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9416 return; 9417 } 9418 9419 if (isa<ObjCObjectPointerType>(CFromTy) && 9420 isa<PointerType>(CToTy)) { 9421 Qualifiers FromQs = CFromTy.getQualifiers(); 9422 Qualifiers ToQs = CToTy.getQualifiers(); 9423 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9424 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9425 << (unsigned) FnKind << FnDesc 9426 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9427 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9428 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9429 return; 9430 } 9431 } 9432 9433 if (TakingCandidateAddress && 9434 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9435 return; 9436 9437 // Emit the generic diagnostic and, optionally, add the hints to it. 9438 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9439 FDiag << (unsigned) FnKind << FnDesc 9440 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9441 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9442 << (unsigned) (Cand->Fix.Kind); 9443 9444 // If we can fix the conversion, suggest the FixIts. 9445 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9446 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9447 FDiag << *HI; 9448 S.Diag(Fn->getLocation(), FDiag); 9449 9450 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9451 } 9452 9453 /// Additional arity mismatch diagnosis specific to a function overload 9454 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9455 /// over a candidate in any candidate set. 9456 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9457 unsigned NumArgs) { 9458 FunctionDecl *Fn = Cand->Function; 9459 unsigned MinParams = Fn->getMinRequiredArguments(); 9460 9461 // With invalid overloaded operators, it's possible that we think we 9462 // have an arity mismatch when in fact it looks like we have the 9463 // right number of arguments, because only overloaded operators have 9464 // the weird behavior of overloading member and non-member functions. 9465 // Just don't report anything. 9466 if (Fn->isInvalidDecl() && 9467 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9468 return true; 9469 9470 if (NumArgs < MinParams) { 9471 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9472 (Cand->FailureKind == ovl_fail_bad_deduction && 9473 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9474 } else { 9475 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9476 (Cand->FailureKind == ovl_fail_bad_deduction && 9477 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9478 } 9479 9480 return false; 9481 } 9482 9483 /// General arity mismatch diagnosis over a candidate in a candidate set. 9484 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9485 unsigned NumFormalArgs) { 9486 assert(isa<FunctionDecl>(D) && 9487 "The templated declaration should at least be a function" 9488 " when diagnosing bad template argument deduction due to too many" 9489 " or too few arguments"); 9490 9491 FunctionDecl *Fn = cast<FunctionDecl>(D); 9492 9493 // TODO: treat calls to a missing default constructor as a special case 9494 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9495 unsigned MinParams = Fn->getMinRequiredArguments(); 9496 9497 // at least / at most / exactly 9498 unsigned mode, modeCount; 9499 if (NumFormalArgs < MinParams) { 9500 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9501 FnTy->isTemplateVariadic()) 9502 mode = 0; // "at least" 9503 else 9504 mode = 2; // "exactly" 9505 modeCount = MinParams; 9506 } else { 9507 if (MinParams != FnTy->getNumParams()) 9508 mode = 1; // "at most" 9509 else 9510 mode = 2; // "exactly" 9511 modeCount = FnTy->getNumParams(); 9512 } 9513 9514 std::string Description; 9515 OverloadCandidateKind FnKind = 9516 ClassifyOverloadCandidate(S, Found, Fn, Description); 9517 9518 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9519 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9520 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9521 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9522 else 9523 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9524 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9525 << mode << modeCount << NumFormalArgs; 9526 MaybeEmitInheritedConstructorNote(S, Found); 9527 } 9528 9529 /// Arity mismatch diagnosis specific to a function overload candidate. 9530 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9531 unsigned NumFormalArgs) { 9532 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9533 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9534 } 9535 9536 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9537 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9538 return TD; 9539 llvm_unreachable("Unsupported: Getting the described template declaration" 9540 " for bad deduction diagnosis"); 9541 } 9542 9543 /// Diagnose a failed template-argument deduction. 9544 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9545 DeductionFailureInfo &DeductionFailure, 9546 unsigned NumArgs, 9547 bool TakingCandidateAddress) { 9548 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9549 NamedDecl *ParamD; 9550 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9551 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9552 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9553 switch (DeductionFailure.Result) { 9554 case Sema::TDK_Success: 9555 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9556 9557 case Sema::TDK_Incomplete: { 9558 assert(ParamD && "no parameter found for incomplete deduction result"); 9559 S.Diag(Templated->getLocation(), 9560 diag::note_ovl_candidate_incomplete_deduction) 9561 << ParamD->getDeclName(); 9562 MaybeEmitInheritedConstructorNote(S, Found); 9563 return; 9564 } 9565 9566 case Sema::TDK_Underqualified: { 9567 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9568 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9569 9570 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9571 9572 // Param will have been canonicalized, but it should just be a 9573 // qualified version of ParamD, so move the qualifiers to that. 9574 QualifierCollector Qs; 9575 Qs.strip(Param); 9576 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9577 assert(S.Context.hasSameType(Param, NonCanonParam)); 9578 9579 // Arg has also been canonicalized, but there's nothing we can do 9580 // about that. It also doesn't matter as much, because it won't 9581 // have any template parameters in it (because deduction isn't 9582 // done on dependent types). 9583 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9584 9585 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9586 << ParamD->getDeclName() << Arg << NonCanonParam; 9587 MaybeEmitInheritedConstructorNote(S, Found); 9588 return; 9589 } 9590 9591 case Sema::TDK_Inconsistent: { 9592 assert(ParamD && "no parameter found for inconsistent deduction result"); 9593 int which = 0; 9594 if (isa<TemplateTypeParmDecl>(ParamD)) 9595 which = 0; 9596 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9597 which = 1; 9598 else { 9599 which = 2; 9600 } 9601 9602 S.Diag(Templated->getLocation(), 9603 diag::note_ovl_candidate_inconsistent_deduction) 9604 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9605 << *DeductionFailure.getSecondArg(); 9606 MaybeEmitInheritedConstructorNote(S, Found); 9607 return; 9608 } 9609 9610 case Sema::TDK_InvalidExplicitArguments: 9611 assert(ParamD && "no parameter found for invalid explicit arguments"); 9612 if (ParamD->getDeclName()) 9613 S.Diag(Templated->getLocation(), 9614 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9615 << ParamD->getDeclName(); 9616 else { 9617 int index = 0; 9618 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9619 index = TTP->getIndex(); 9620 else if (NonTypeTemplateParmDecl *NTTP 9621 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9622 index = NTTP->getIndex(); 9623 else 9624 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9625 S.Diag(Templated->getLocation(), 9626 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9627 << (index + 1); 9628 } 9629 MaybeEmitInheritedConstructorNote(S, Found); 9630 return; 9631 9632 case Sema::TDK_TooManyArguments: 9633 case Sema::TDK_TooFewArguments: 9634 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 9635 return; 9636 9637 case Sema::TDK_InstantiationDepth: 9638 S.Diag(Templated->getLocation(), 9639 diag::note_ovl_candidate_instantiation_depth); 9640 MaybeEmitInheritedConstructorNote(S, Found); 9641 return; 9642 9643 case Sema::TDK_SubstitutionFailure: { 9644 // Format the template argument list into the argument string. 9645 SmallString<128> TemplateArgString; 9646 if (TemplateArgumentList *Args = 9647 DeductionFailure.getTemplateArgumentList()) { 9648 TemplateArgString = " "; 9649 TemplateArgString += S.getTemplateArgumentBindingsText( 9650 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9651 } 9652 9653 // If this candidate was disabled by enable_if, say so. 9654 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9655 if (PDiag && PDiag->second.getDiagID() == 9656 diag::err_typename_nested_not_found_enable_if) { 9657 // FIXME: Use the source range of the condition, and the fully-qualified 9658 // name of the enable_if template. These are both present in PDiag. 9659 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9660 << "'enable_if'" << TemplateArgString; 9661 return; 9662 } 9663 9664 // Format the SFINAE diagnostic into the argument string. 9665 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9666 // formatted message in another diagnostic. 9667 SmallString<128> SFINAEArgString; 9668 SourceRange R; 9669 if (PDiag) { 9670 SFINAEArgString = ": "; 9671 R = SourceRange(PDiag->first, PDiag->first); 9672 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9673 } 9674 9675 S.Diag(Templated->getLocation(), 9676 diag::note_ovl_candidate_substitution_failure) 9677 << TemplateArgString << SFINAEArgString << R; 9678 MaybeEmitInheritedConstructorNote(S, Found); 9679 return; 9680 } 9681 9682 case Sema::TDK_FailedOverloadResolution: { 9683 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9684 S.Diag(Templated->getLocation(), 9685 diag::note_ovl_candidate_failed_overload_resolution) 9686 << R.Expression->getName(); 9687 return; 9688 } 9689 9690 case Sema::TDK_DeducedMismatch: { 9691 // Format the template argument list into the argument string. 9692 SmallString<128> TemplateArgString; 9693 if (TemplateArgumentList *Args = 9694 DeductionFailure.getTemplateArgumentList()) { 9695 TemplateArgString = " "; 9696 TemplateArgString += S.getTemplateArgumentBindingsText( 9697 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9698 } 9699 9700 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9701 << (*DeductionFailure.getCallArgIndex() + 1) 9702 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9703 << TemplateArgString; 9704 break; 9705 } 9706 9707 case Sema::TDK_NonDeducedMismatch: { 9708 // FIXME: Provide a source location to indicate what we couldn't match. 9709 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9710 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9711 if (FirstTA.getKind() == TemplateArgument::Template && 9712 SecondTA.getKind() == TemplateArgument::Template) { 9713 TemplateName FirstTN = FirstTA.getAsTemplate(); 9714 TemplateName SecondTN = SecondTA.getAsTemplate(); 9715 if (FirstTN.getKind() == TemplateName::Template && 9716 SecondTN.getKind() == TemplateName::Template) { 9717 if (FirstTN.getAsTemplateDecl()->getName() == 9718 SecondTN.getAsTemplateDecl()->getName()) { 9719 // FIXME: This fixes a bad diagnostic where both templates are named 9720 // the same. This particular case is a bit difficult since: 9721 // 1) It is passed as a string to the diagnostic printer. 9722 // 2) The diagnostic printer only attempts to find a better 9723 // name for types, not decls. 9724 // Ideally, this should folded into the diagnostic printer. 9725 S.Diag(Templated->getLocation(), 9726 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9727 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9728 return; 9729 } 9730 } 9731 } 9732 9733 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9734 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9735 return; 9736 9737 // FIXME: For generic lambda parameters, check if the function is a lambda 9738 // call operator, and if so, emit a prettier and more informative 9739 // diagnostic that mentions 'auto' and lambda in addition to 9740 // (or instead of?) the canonical template type parameters. 9741 S.Diag(Templated->getLocation(), 9742 diag::note_ovl_candidate_non_deduced_mismatch) 9743 << FirstTA << SecondTA; 9744 return; 9745 } 9746 // TODO: diagnose these individually, then kill off 9747 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9748 case Sema::TDK_MiscellaneousDeductionFailure: 9749 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9750 MaybeEmitInheritedConstructorNote(S, Found); 9751 return; 9752 case Sema::TDK_CUDATargetMismatch: 9753 S.Diag(Templated->getLocation(), 9754 diag::note_cuda_ovl_candidate_target_mismatch); 9755 return; 9756 } 9757 } 9758 9759 /// Diagnose a failed template-argument deduction, for function calls. 9760 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9761 unsigned NumArgs, 9762 bool TakingCandidateAddress) { 9763 unsigned TDK = Cand->DeductionFailure.Result; 9764 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9765 if (CheckArityMismatch(S, Cand, NumArgs)) 9766 return; 9767 } 9768 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 9769 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9770 } 9771 9772 /// CUDA: diagnose an invalid call across targets. 9773 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9774 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9775 FunctionDecl *Callee = Cand->Function; 9776 9777 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9778 CalleeTarget = S.IdentifyCUDATarget(Callee); 9779 9780 std::string FnDesc; 9781 OverloadCandidateKind FnKind = 9782 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 9783 9784 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9785 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9786 9787 // This could be an implicit constructor for which we could not infer the 9788 // target due to a collsion. Diagnose that case. 9789 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9790 if (Meth != nullptr && Meth->isImplicit()) { 9791 CXXRecordDecl *ParentClass = Meth->getParent(); 9792 Sema::CXXSpecialMember CSM; 9793 9794 switch (FnKind) { 9795 default: 9796 return; 9797 case oc_implicit_default_constructor: 9798 CSM = Sema::CXXDefaultConstructor; 9799 break; 9800 case oc_implicit_copy_constructor: 9801 CSM = Sema::CXXCopyConstructor; 9802 break; 9803 case oc_implicit_move_constructor: 9804 CSM = Sema::CXXMoveConstructor; 9805 break; 9806 case oc_implicit_copy_assignment: 9807 CSM = Sema::CXXCopyAssignment; 9808 break; 9809 case oc_implicit_move_assignment: 9810 CSM = Sema::CXXMoveAssignment; 9811 break; 9812 }; 9813 9814 bool ConstRHS = false; 9815 if (Meth->getNumParams()) { 9816 if (const ReferenceType *RT = 9817 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9818 ConstRHS = RT->getPointeeType().isConstQualified(); 9819 } 9820 } 9821 9822 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9823 /* ConstRHS */ ConstRHS, 9824 /* Diagnose */ true); 9825 } 9826 } 9827 9828 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9829 FunctionDecl *Callee = Cand->Function; 9830 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9831 9832 S.Diag(Callee->getLocation(), 9833 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9834 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9835 } 9836 9837 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 9838 FunctionDecl *Callee = Cand->Function; 9839 9840 S.Diag(Callee->getLocation(), 9841 diag::note_ovl_candidate_disabled_by_extension); 9842 } 9843 9844 /// Generates a 'note' diagnostic for an overload candidate. We've 9845 /// already generated a primary error at the call site. 9846 /// 9847 /// It really does need to be a single diagnostic with its caret 9848 /// pointed at the candidate declaration. Yes, this creates some 9849 /// major challenges of technical writing. Yes, this makes pointing 9850 /// out problems with specific arguments quite awkward. It's still 9851 /// better than generating twenty screens of text for every failed 9852 /// overload. 9853 /// 9854 /// It would be great to be able to express per-candidate problems 9855 /// more richly for those diagnostic clients that cared, but we'd 9856 /// still have to be just as careful with the default diagnostics. 9857 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9858 unsigned NumArgs, 9859 bool TakingCandidateAddress) { 9860 FunctionDecl *Fn = Cand->Function; 9861 9862 // Note deleted candidates, but only if they're viable. 9863 if (Cand->Viable && (Fn->isDeleted() || 9864 S.isFunctionConsideredUnavailable(Fn))) { 9865 std::string FnDesc; 9866 OverloadCandidateKind FnKind = 9867 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9868 9869 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9870 << FnKind << FnDesc 9871 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9872 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9873 return; 9874 } 9875 9876 // We don't really have anything else to say about viable candidates. 9877 if (Cand->Viable) { 9878 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9879 return; 9880 } 9881 9882 switch (Cand->FailureKind) { 9883 case ovl_fail_too_many_arguments: 9884 case ovl_fail_too_few_arguments: 9885 return DiagnoseArityMismatch(S, Cand, NumArgs); 9886 9887 case ovl_fail_bad_deduction: 9888 return DiagnoseBadDeduction(S, Cand, NumArgs, 9889 TakingCandidateAddress); 9890 9891 case ovl_fail_illegal_constructor: { 9892 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9893 << (Fn->getPrimaryTemplate() ? 1 : 0); 9894 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9895 return; 9896 } 9897 9898 case ovl_fail_trivial_conversion: 9899 case ovl_fail_bad_final_conversion: 9900 case ovl_fail_final_conversion_not_exact: 9901 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9902 9903 case ovl_fail_bad_conversion: { 9904 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9905 for (unsigned N = Cand->NumConversions; I != N; ++I) 9906 if (Cand->Conversions[I].isBad()) 9907 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9908 9909 // FIXME: this currently happens when we're called from SemaInit 9910 // when user-conversion overload fails. Figure out how to handle 9911 // those conditions and diagnose them well. 9912 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9913 } 9914 9915 case ovl_fail_bad_target: 9916 return DiagnoseBadTarget(S, Cand); 9917 9918 case ovl_fail_enable_if: 9919 return DiagnoseFailedEnableIfAttr(S, Cand); 9920 9921 case ovl_fail_ext_disabled: 9922 return DiagnoseOpenCLExtensionDisabled(S, Cand); 9923 9924 case ovl_fail_addr_not_available: { 9925 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 9926 (void)Available; 9927 assert(!Available); 9928 break; 9929 } 9930 } 9931 } 9932 9933 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9934 // Desugar the type of the surrogate down to a function type, 9935 // retaining as many typedefs as possible while still showing 9936 // the function type (and, therefore, its parameter types). 9937 QualType FnType = Cand->Surrogate->getConversionType(); 9938 bool isLValueReference = false; 9939 bool isRValueReference = false; 9940 bool isPointer = false; 9941 if (const LValueReferenceType *FnTypeRef = 9942 FnType->getAs<LValueReferenceType>()) { 9943 FnType = FnTypeRef->getPointeeType(); 9944 isLValueReference = true; 9945 } else if (const RValueReferenceType *FnTypeRef = 9946 FnType->getAs<RValueReferenceType>()) { 9947 FnType = FnTypeRef->getPointeeType(); 9948 isRValueReference = true; 9949 } 9950 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9951 FnType = FnTypePtr->getPointeeType(); 9952 isPointer = true; 9953 } 9954 // Desugar down to a function type. 9955 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9956 // Reconstruct the pointer/reference as appropriate. 9957 if (isPointer) FnType = S.Context.getPointerType(FnType); 9958 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9959 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9960 9961 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9962 << FnType; 9963 } 9964 9965 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9966 SourceLocation OpLoc, 9967 OverloadCandidate *Cand) { 9968 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9969 std::string TypeStr("operator"); 9970 TypeStr += Opc; 9971 TypeStr += "("; 9972 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9973 if (Cand->NumConversions == 1) { 9974 TypeStr += ")"; 9975 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9976 } else { 9977 TypeStr += ", "; 9978 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9979 TypeStr += ")"; 9980 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9981 } 9982 } 9983 9984 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9985 OverloadCandidate *Cand) { 9986 unsigned NoOperands = Cand->NumConversions; 9987 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9988 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9989 if (ICS.isBad()) break; // all meaningless after first invalid 9990 if (!ICS.isAmbiguous()) continue; 9991 9992 ICS.DiagnoseAmbiguousConversion( 9993 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 9994 } 9995 } 9996 9997 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9998 if (Cand->Function) 9999 return Cand->Function->getLocation(); 10000 if (Cand->IsSurrogate) 10001 return Cand->Surrogate->getLocation(); 10002 return SourceLocation(); 10003 } 10004 10005 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10006 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10007 case Sema::TDK_Success: 10008 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10009 10010 case Sema::TDK_Invalid: 10011 case Sema::TDK_Incomplete: 10012 return 1; 10013 10014 case Sema::TDK_Underqualified: 10015 case Sema::TDK_Inconsistent: 10016 return 2; 10017 10018 case Sema::TDK_SubstitutionFailure: 10019 case Sema::TDK_DeducedMismatch: 10020 case Sema::TDK_NonDeducedMismatch: 10021 case Sema::TDK_MiscellaneousDeductionFailure: 10022 case Sema::TDK_CUDATargetMismatch: 10023 return 3; 10024 10025 case Sema::TDK_InstantiationDepth: 10026 case Sema::TDK_FailedOverloadResolution: 10027 return 4; 10028 10029 case Sema::TDK_InvalidExplicitArguments: 10030 return 5; 10031 10032 case Sema::TDK_TooManyArguments: 10033 case Sema::TDK_TooFewArguments: 10034 return 6; 10035 } 10036 llvm_unreachable("Unhandled deduction result"); 10037 } 10038 10039 namespace { 10040 struct CompareOverloadCandidatesForDisplay { 10041 Sema &S; 10042 SourceLocation Loc; 10043 size_t NumArgs; 10044 10045 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 10046 : S(S), NumArgs(nArgs) {} 10047 10048 bool operator()(const OverloadCandidate *L, 10049 const OverloadCandidate *R) { 10050 // Fast-path this check. 10051 if (L == R) return false; 10052 10053 // Order first by viability. 10054 if (L->Viable) { 10055 if (!R->Viable) return true; 10056 10057 // TODO: introduce a tri-valued comparison for overload 10058 // candidates. Would be more worthwhile if we had a sort 10059 // that could exploit it. 10060 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 10061 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 10062 } else if (R->Viable) 10063 return false; 10064 10065 assert(L->Viable == R->Viable); 10066 10067 // Criteria by which we can sort non-viable candidates: 10068 if (!L->Viable) { 10069 // 1. Arity mismatches come after other candidates. 10070 if (L->FailureKind == ovl_fail_too_many_arguments || 10071 L->FailureKind == ovl_fail_too_few_arguments) { 10072 if (R->FailureKind == ovl_fail_too_many_arguments || 10073 R->FailureKind == ovl_fail_too_few_arguments) { 10074 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10075 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10076 if (LDist == RDist) { 10077 if (L->FailureKind == R->FailureKind) 10078 // Sort non-surrogates before surrogates. 10079 return !L->IsSurrogate && R->IsSurrogate; 10080 // Sort candidates requiring fewer parameters than there were 10081 // arguments given after candidates requiring more parameters 10082 // than there were arguments given. 10083 return L->FailureKind == ovl_fail_too_many_arguments; 10084 } 10085 return LDist < RDist; 10086 } 10087 return false; 10088 } 10089 if (R->FailureKind == ovl_fail_too_many_arguments || 10090 R->FailureKind == ovl_fail_too_few_arguments) 10091 return true; 10092 10093 // 2. Bad conversions come first and are ordered by the number 10094 // of bad conversions and quality of good conversions. 10095 if (L->FailureKind == ovl_fail_bad_conversion) { 10096 if (R->FailureKind != ovl_fail_bad_conversion) 10097 return true; 10098 10099 // The conversion that can be fixed with a smaller number of changes, 10100 // comes first. 10101 unsigned numLFixes = L->Fix.NumConversionsFixed; 10102 unsigned numRFixes = R->Fix.NumConversionsFixed; 10103 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10104 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10105 if (numLFixes != numRFixes) { 10106 return numLFixes < numRFixes; 10107 } 10108 10109 // If there's any ordering between the defined conversions... 10110 // FIXME: this might not be transitive. 10111 assert(L->NumConversions == R->NumConversions); 10112 10113 int leftBetter = 0; 10114 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10115 for (unsigned E = L->NumConversions; I != E; ++I) { 10116 switch (CompareImplicitConversionSequences(S, Loc, 10117 L->Conversions[I], 10118 R->Conversions[I])) { 10119 case ImplicitConversionSequence::Better: 10120 leftBetter++; 10121 break; 10122 10123 case ImplicitConversionSequence::Worse: 10124 leftBetter--; 10125 break; 10126 10127 case ImplicitConversionSequence::Indistinguishable: 10128 break; 10129 } 10130 } 10131 if (leftBetter > 0) return true; 10132 if (leftBetter < 0) return false; 10133 10134 } else if (R->FailureKind == ovl_fail_bad_conversion) 10135 return false; 10136 10137 if (L->FailureKind == ovl_fail_bad_deduction) { 10138 if (R->FailureKind != ovl_fail_bad_deduction) 10139 return true; 10140 10141 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10142 return RankDeductionFailure(L->DeductionFailure) 10143 < RankDeductionFailure(R->DeductionFailure); 10144 } else if (R->FailureKind == ovl_fail_bad_deduction) 10145 return false; 10146 10147 // TODO: others? 10148 } 10149 10150 // Sort everything else by location. 10151 SourceLocation LLoc = GetLocationForCandidate(L); 10152 SourceLocation RLoc = GetLocationForCandidate(R); 10153 10154 // Put candidates without locations (e.g. builtins) at the end. 10155 if (LLoc.isInvalid()) return false; 10156 if (RLoc.isInvalid()) return true; 10157 10158 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10159 } 10160 }; 10161 } 10162 10163 /// CompleteNonViableCandidate - Normally, overload resolution only 10164 /// computes up to the first. Produces the FixIt set if possible. 10165 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10166 ArrayRef<Expr *> Args) { 10167 assert(!Cand->Viable); 10168 10169 // Don't do anything on failures other than bad conversion. 10170 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10171 10172 // We only want the FixIts if all the arguments can be corrected. 10173 bool Unfixable = false; 10174 // Use a implicit copy initialization to check conversion fixes. 10175 Cand->Fix.setConversionChecker(TryCopyInitialization); 10176 10177 // Skip forward to the first bad conversion. 10178 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 10179 unsigned ConvCount = Cand->NumConversions; 10180 while (true) { 10181 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10182 ConvIdx++; 10183 if (Cand->Conversions[ConvIdx - 1].isBad()) { 10184 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 10185 break; 10186 } 10187 } 10188 10189 if (ConvIdx == ConvCount) 10190 return; 10191 10192 assert(!Cand->Conversions[ConvIdx].isInitialized() && 10193 "remaining conversion is initialized?"); 10194 10195 // FIXME: this should probably be preserved from the overload 10196 // operation somehow. 10197 bool SuppressUserConversions = false; 10198 10199 const FunctionProtoType* Proto; 10200 unsigned ArgIdx = ConvIdx; 10201 10202 if (Cand->IsSurrogate) { 10203 QualType ConvType 10204 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10205 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10206 ConvType = ConvPtrType->getPointeeType(); 10207 Proto = ConvType->getAs<FunctionProtoType>(); 10208 ArgIdx--; 10209 } else if (Cand->Function) { 10210 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 10211 if (isa<CXXMethodDecl>(Cand->Function) && 10212 !isa<CXXConstructorDecl>(Cand->Function)) 10213 ArgIdx--; 10214 } else { 10215 // Builtin binary operator with a bad first conversion. 10216 assert(ConvCount <= 3); 10217 for (; ConvIdx != ConvCount; ++ConvIdx) 10218 Cand->Conversions[ConvIdx] 10219 = TryCopyInitialization(S, Args[ConvIdx], 10220 Cand->BuiltinTypes.ParamTypes[ConvIdx], 10221 SuppressUserConversions, 10222 /*InOverloadResolution*/ true, 10223 /*AllowObjCWritebackConversion=*/ 10224 S.getLangOpts().ObjCAutoRefCount); 10225 return; 10226 } 10227 10228 // Fill in the rest of the conversions. 10229 unsigned NumParams = Proto->getNumParams(); 10230 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10231 if (ArgIdx < NumParams) { 10232 Cand->Conversions[ConvIdx] = TryCopyInitialization( 10233 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 10234 /*InOverloadResolution=*/true, 10235 /*AllowObjCWritebackConversion=*/ 10236 S.getLangOpts().ObjCAutoRefCount); 10237 // Store the FixIt in the candidate if it exists. 10238 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10239 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10240 } 10241 else 10242 Cand->Conversions[ConvIdx].setEllipsis(); 10243 } 10244 } 10245 10246 /// PrintOverloadCandidates - When overload resolution fails, prints 10247 /// diagnostic messages containing the candidates in the candidate 10248 /// set. 10249 void OverloadCandidateSet::NoteCandidates( 10250 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10251 StringRef Opc, SourceLocation OpLoc, 10252 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10253 // Sort the candidates by viability and position. Sorting directly would 10254 // be prohibitive, so we make a set of pointers and sort those. 10255 SmallVector<OverloadCandidate*, 32> Cands; 10256 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10257 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10258 if (!Filter(*Cand)) 10259 continue; 10260 if (Cand->Viable) 10261 Cands.push_back(Cand); 10262 else if (OCD == OCD_AllCandidates) { 10263 CompleteNonViableCandidate(S, Cand, Args); 10264 if (Cand->Function || Cand->IsSurrogate) 10265 Cands.push_back(Cand); 10266 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10267 // want to list every possible builtin candidate. 10268 } 10269 } 10270 10271 std::sort(Cands.begin(), Cands.end(), 10272 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10273 10274 bool ReportedAmbiguousConversions = false; 10275 10276 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10277 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10278 unsigned CandsShown = 0; 10279 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10280 OverloadCandidate *Cand = *I; 10281 10282 // Set an arbitrary limit on the number of candidate functions we'll spam 10283 // the user with. FIXME: This limit should depend on details of the 10284 // candidate list. 10285 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10286 break; 10287 } 10288 ++CandsShown; 10289 10290 if (Cand->Function) 10291 NoteFunctionCandidate(S, Cand, Args.size(), 10292 /*TakingCandidateAddress=*/false); 10293 else if (Cand->IsSurrogate) 10294 NoteSurrogateCandidate(S, Cand); 10295 else { 10296 assert(Cand->Viable && 10297 "Non-viable built-in candidates are not added to Cands."); 10298 // Generally we only see ambiguities including viable builtin 10299 // operators if overload resolution got screwed up by an 10300 // ambiguous user-defined conversion. 10301 // 10302 // FIXME: It's quite possible for different conversions to see 10303 // different ambiguities, though. 10304 if (!ReportedAmbiguousConversions) { 10305 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10306 ReportedAmbiguousConversions = true; 10307 } 10308 10309 // If this is a viable builtin, print it. 10310 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10311 } 10312 } 10313 10314 if (I != E) 10315 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10316 } 10317 10318 static SourceLocation 10319 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10320 return Cand->Specialization ? Cand->Specialization->getLocation() 10321 : SourceLocation(); 10322 } 10323 10324 namespace { 10325 struct CompareTemplateSpecCandidatesForDisplay { 10326 Sema &S; 10327 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10328 10329 bool operator()(const TemplateSpecCandidate *L, 10330 const TemplateSpecCandidate *R) { 10331 // Fast-path this check. 10332 if (L == R) 10333 return false; 10334 10335 // Assuming that both candidates are not matches... 10336 10337 // Sort by the ranking of deduction failures. 10338 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10339 return RankDeductionFailure(L->DeductionFailure) < 10340 RankDeductionFailure(R->DeductionFailure); 10341 10342 // Sort everything else by location. 10343 SourceLocation LLoc = GetLocationForCandidate(L); 10344 SourceLocation RLoc = GetLocationForCandidate(R); 10345 10346 // Put candidates without locations (e.g. builtins) at the end. 10347 if (LLoc.isInvalid()) 10348 return false; 10349 if (RLoc.isInvalid()) 10350 return true; 10351 10352 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10353 } 10354 }; 10355 } 10356 10357 /// Diagnose a template argument deduction failure. 10358 /// We are treating these failures as overload failures due to bad 10359 /// deductions. 10360 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10361 bool ForTakingAddress) { 10362 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10363 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10364 } 10365 10366 void TemplateSpecCandidateSet::destroyCandidates() { 10367 for (iterator i = begin(), e = end(); i != e; ++i) { 10368 i->DeductionFailure.Destroy(); 10369 } 10370 } 10371 10372 void TemplateSpecCandidateSet::clear() { 10373 destroyCandidates(); 10374 Candidates.clear(); 10375 } 10376 10377 /// NoteCandidates - When no template specialization match is found, prints 10378 /// diagnostic messages containing the non-matching specializations that form 10379 /// the candidate set. 10380 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10381 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10382 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10383 // Sort the candidates by position (assuming no candidate is a match). 10384 // Sorting directly would be prohibitive, so we make a set of pointers 10385 // and sort those. 10386 SmallVector<TemplateSpecCandidate *, 32> Cands; 10387 Cands.reserve(size()); 10388 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10389 if (Cand->Specialization) 10390 Cands.push_back(Cand); 10391 // Otherwise, this is a non-matching builtin candidate. We do not, 10392 // in general, want to list every possible builtin candidate. 10393 } 10394 10395 std::sort(Cands.begin(), Cands.end(), 10396 CompareTemplateSpecCandidatesForDisplay(S)); 10397 10398 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10399 // for generalization purposes (?). 10400 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10401 10402 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10403 unsigned CandsShown = 0; 10404 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10405 TemplateSpecCandidate *Cand = *I; 10406 10407 // Set an arbitrary limit on the number of candidates we'll spam 10408 // the user with. FIXME: This limit should depend on details of the 10409 // candidate list. 10410 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10411 break; 10412 ++CandsShown; 10413 10414 assert(Cand->Specialization && 10415 "Non-matching built-in candidates are not added to Cands."); 10416 Cand->NoteDeductionFailure(S, ForTakingAddress); 10417 } 10418 10419 if (I != E) 10420 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10421 } 10422 10423 // [PossiblyAFunctionType] --> [Return] 10424 // NonFunctionType --> NonFunctionType 10425 // R (A) --> R(A) 10426 // R (*)(A) --> R (A) 10427 // R (&)(A) --> R (A) 10428 // R (S::*)(A) --> R (A) 10429 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10430 QualType Ret = PossiblyAFunctionType; 10431 if (const PointerType *ToTypePtr = 10432 PossiblyAFunctionType->getAs<PointerType>()) 10433 Ret = ToTypePtr->getPointeeType(); 10434 else if (const ReferenceType *ToTypeRef = 10435 PossiblyAFunctionType->getAs<ReferenceType>()) 10436 Ret = ToTypeRef->getPointeeType(); 10437 else if (const MemberPointerType *MemTypePtr = 10438 PossiblyAFunctionType->getAs<MemberPointerType>()) 10439 Ret = MemTypePtr->getPointeeType(); 10440 Ret = 10441 Context.getCanonicalType(Ret).getUnqualifiedType(); 10442 return Ret; 10443 } 10444 10445 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10446 bool Complain = true) { 10447 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10448 S.DeduceReturnType(FD, Loc, Complain)) 10449 return true; 10450 10451 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10452 if (S.getLangOpts().CPlusPlus1z && 10453 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10454 !S.ResolveExceptionSpec(Loc, FPT)) 10455 return true; 10456 10457 return false; 10458 } 10459 10460 namespace { 10461 // A helper class to help with address of function resolution 10462 // - allows us to avoid passing around all those ugly parameters 10463 class AddressOfFunctionResolver { 10464 Sema& S; 10465 Expr* SourceExpr; 10466 const QualType& TargetType; 10467 QualType TargetFunctionType; // Extracted function type from target type 10468 10469 bool Complain; 10470 //DeclAccessPair& ResultFunctionAccessPair; 10471 ASTContext& Context; 10472 10473 bool TargetTypeIsNonStaticMemberFunction; 10474 bool FoundNonTemplateFunction; 10475 bool StaticMemberFunctionFromBoundPointer; 10476 bool HasComplained; 10477 10478 OverloadExpr::FindResult OvlExprInfo; 10479 OverloadExpr *OvlExpr; 10480 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10481 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10482 TemplateSpecCandidateSet FailedCandidates; 10483 10484 public: 10485 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10486 const QualType &TargetType, bool Complain) 10487 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10488 Complain(Complain), Context(S.getASTContext()), 10489 TargetTypeIsNonStaticMemberFunction( 10490 !!TargetType->getAs<MemberPointerType>()), 10491 FoundNonTemplateFunction(false), 10492 StaticMemberFunctionFromBoundPointer(false), 10493 HasComplained(false), 10494 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10495 OvlExpr(OvlExprInfo.Expression), 10496 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10497 ExtractUnqualifiedFunctionTypeFromTargetType(); 10498 10499 if (TargetFunctionType->isFunctionType()) { 10500 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10501 if (!UME->isImplicitAccess() && 10502 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10503 StaticMemberFunctionFromBoundPointer = true; 10504 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10505 DeclAccessPair dap; 10506 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10507 OvlExpr, false, &dap)) { 10508 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10509 if (!Method->isStatic()) { 10510 // If the target type is a non-function type and the function found 10511 // is a non-static member function, pretend as if that was the 10512 // target, it's the only possible type to end up with. 10513 TargetTypeIsNonStaticMemberFunction = true; 10514 10515 // And skip adding the function if its not in the proper form. 10516 // We'll diagnose this due to an empty set of functions. 10517 if (!OvlExprInfo.HasFormOfMemberPointer) 10518 return; 10519 } 10520 10521 Matches.push_back(std::make_pair(dap, Fn)); 10522 } 10523 return; 10524 } 10525 10526 if (OvlExpr->hasExplicitTemplateArgs()) 10527 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10528 10529 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10530 // C++ [over.over]p4: 10531 // If more than one function is selected, [...] 10532 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10533 if (FoundNonTemplateFunction) 10534 EliminateAllTemplateMatches(); 10535 else 10536 EliminateAllExceptMostSpecializedTemplate(); 10537 } 10538 } 10539 10540 if (S.getLangOpts().CUDA && Matches.size() > 1) 10541 EliminateSuboptimalCudaMatches(); 10542 } 10543 10544 bool hasComplained() const { return HasComplained; } 10545 10546 private: 10547 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10548 QualType Discard; 10549 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10550 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 10551 } 10552 10553 /// \return true if A is considered a better overload candidate for the 10554 /// desired type than B. 10555 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10556 // If A doesn't have exactly the correct type, we don't want to classify it 10557 // as "better" than anything else. This way, the user is required to 10558 // disambiguate for us if there are multiple candidates and no exact match. 10559 return candidateHasExactlyCorrectType(A) && 10560 (!candidateHasExactlyCorrectType(B) || 10561 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10562 } 10563 10564 /// \return true if we were able to eliminate all but one overload candidate, 10565 /// false otherwise. 10566 bool eliminiateSuboptimalOverloadCandidates() { 10567 // Same algorithm as overload resolution -- one pass to pick the "best", 10568 // another pass to be sure that nothing is better than the best. 10569 auto Best = Matches.begin(); 10570 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10571 if (isBetterCandidate(I->second, Best->second)) 10572 Best = I; 10573 10574 const FunctionDecl *BestFn = Best->second; 10575 auto IsBestOrInferiorToBest = [this, BestFn]( 10576 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10577 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10578 }; 10579 10580 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10581 // option, so we can potentially give the user a better error 10582 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10583 return false; 10584 Matches[0] = *Best; 10585 Matches.resize(1); 10586 return true; 10587 } 10588 10589 bool isTargetTypeAFunction() const { 10590 return TargetFunctionType->isFunctionType(); 10591 } 10592 10593 // [ToType] [Return] 10594 10595 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10596 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10597 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10598 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10599 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10600 } 10601 10602 // return true if any matching specializations were found 10603 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10604 const DeclAccessPair& CurAccessFunPair) { 10605 if (CXXMethodDecl *Method 10606 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10607 // Skip non-static function templates when converting to pointer, and 10608 // static when converting to member pointer. 10609 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10610 return false; 10611 } 10612 else if (TargetTypeIsNonStaticMemberFunction) 10613 return false; 10614 10615 // C++ [over.over]p2: 10616 // If the name is a function template, template argument deduction is 10617 // done (14.8.2.2), and if the argument deduction succeeds, the 10618 // resulting template argument list is used to generate a single 10619 // function template specialization, which is added to the set of 10620 // overloaded functions considered. 10621 FunctionDecl *Specialization = nullptr; 10622 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10623 if (Sema::TemplateDeductionResult Result 10624 = S.DeduceTemplateArguments(FunctionTemplate, 10625 &OvlExplicitTemplateArgs, 10626 TargetFunctionType, Specialization, 10627 Info, /*IsAddressOfFunction*/true)) { 10628 // Make a note of the failed deduction for diagnostics. 10629 FailedCandidates.addCandidate() 10630 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 10631 MakeDeductionFailureInfo(Context, Result, Info)); 10632 return false; 10633 } 10634 10635 // Template argument deduction ensures that we have an exact match or 10636 // compatible pointer-to-function arguments that would be adjusted by ICS. 10637 // This function template specicalization works. 10638 assert(S.isSameOrCompatibleFunctionType( 10639 Context.getCanonicalType(Specialization->getType()), 10640 Context.getCanonicalType(TargetFunctionType))); 10641 10642 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10643 return false; 10644 10645 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10646 return true; 10647 } 10648 10649 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10650 const DeclAccessPair& CurAccessFunPair) { 10651 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10652 // Skip non-static functions when converting to pointer, and static 10653 // when converting to member pointer. 10654 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10655 return false; 10656 } 10657 else if (TargetTypeIsNonStaticMemberFunction) 10658 return false; 10659 10660 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10661 if (S.getLangOpts().CUDA) 10662 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10663 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 10664 return false; 10665 10666 // If any candidate has a placeholder return type, trigger its deduction 10667 // now. 10668 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(), 10669 Complain)) { 10670 HasComplained |= Complain; 10671 return false; 10672 } 10673 10674 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10675 return false; 10676 10677 // If we're in C, we need to support types that aren't exactly identical. 10678 if (!S.getLangOpts().CPlusPlus || 10679 candidateHasExactlyCorrectType(FunDecl)) { 10680 Matches.push_back(std::make_pair( 10681 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10682 FoundNonTemplateFunction = true; 10683 return true; 10684 } 10685 } 10686 10687 return false; 10688 } 10689 10690 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10691 bool Ret = false; 10692 10693 // If the overload expression doesn't have the form of a pointer to 10694 // member, don't try to convert it to a pointer-to-member type. 10695 if (IsInvalidFormOfPointerToMemberFunction()) 10696 return false; 10697 10698 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10699 E = OvlExpr->decls_end(); 10700 I != E; ++I) { 10701 // Look through any using declarations to find the underlying function. 10702 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10703 10704 // C++ [over.over]p3: 10705 // Non-member functions and static member functions match 10706 // targets of type "pointer-to-function" or "reference-to-function." 10707 // Nonstatic member functions match targets of 10708 // type "pointer-to-member-function." 10709 // Note that according to DR 247, the containing class does not matter. 10710 if (FunctionTemplateDecl *FunctionTemplate 10711 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10712 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10713 Ret = true; 10714 } 10715 // If we have explicit template arguments supplied, skip non-templates. 10716 else if (!OvlExpr->hasExplicitTemplateArgs() && 10717 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10718 Ret = true; 10719 } 10720 assert(Ret || Matches.empty()); 10721 return Ret; 10722 } 10723 10724 void EliminateAllExceptMostSpecializedTemplate() { 10725 // [...] and any given function template specialization F1 is 10726 // eliminated if the set contains a second function template 10727 // specialization whose function template is more specialized 10728 // than the function template of F1 according to the partial 10729 // ordering rules of 14.5.5.2. 10730 10731 // The algorithm specified above is quadratic. We instead use a 10732 // two-pass algorithm (similar to the one used to identify the 10733 // best viable function in an overload set) that identifies the 10734 // best function template (if it exists). 10735 10736 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10737 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10738 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10739 10740 // TODO: It looks like FailedCandidates does not serve much purpose 10741 // here, since the no_viable diagnostic has index 0. 10742 UnresolvedSetIterator Result = S.getMostSpecialized( 10743 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10744 SourceExpr->getLocStart(), S.PDiag(), 10745 S.PDiag(diag::err_addr_ovl_ambiguous) 10746 << Matches[0].second->getDeclName(), 10747 S.PDiag(diag::note_ovl_candidate) 10748 << (unsigned)oc_function_template, 10749 Complain, TargetFunctionType); 10750 10751 if (Result != MatchesCopy.end()) { 10752 // Make it the first and only element 10753 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10754 Matches[0].second = cast<FunctionDecl>(*Result); 10755 Matches.resize(1); 10756 } else 10757 HasComplained |= Complain; 10758 } 10759 10760 void EliminateAllTemplateMatches() { 10761 // [...] any function template specializations in the set are 10762 // eliminated if the set also contains a non-template function, [...] 10763 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10764 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10765 ++I; 10766 else { 10767 Matches[I] = Matches[--N]; 10768 Matches.resize(N); 10769 } 10770 } 10771 } 10772 10773 void EliminateSuboptimalCudaMatches() { 10774 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10775 } 10776 10777 public: 10778 void ComplainNoMatchesFound() const { 10779 assert(Matches.empty()); 10780 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10781 << OvlExpr->getName() << TargetFunctionType 10782 << OvlExpr->getSourceRange(); 10783 if (FailedCandidates.empty()) 10784 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10785 /*TakingAddress=*/true); 10786 else { 10787 // We have some deduction failure messages. Use them to diagnose 10788 // the function templates, and diagnose the non-template candidates 10789 // normally. 10790 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10791 IEnd = OvlExpr->decls_end(); 10792 I != IEnd; ++I) 10793 if (FunctionDecl *Fun = 10794 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10795 if (!functionHasPassObjectSizeParams(Fun)) 10796 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 10797 /*TakingAddress=*/true); 10798 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10799 } 10800 } 10801 10802 bool IsInvalidFormOfPointerToMemberFunction() const { 10803 return TargetTypeIsNonStaticMemberFunction && 10804 !OvlExprInfo.HasFormOfMemberPointer; 10805 } 10806 10807 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10808 // TODO: Should we condition this on whether any functions might 10809 // have matched, or is it more appropriate to do that in callers? 10810 // TODO: a fixit wouldn't hurt. 10811 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10812 << TargetType << OvlExpr->getSourceRange(); 10813 } 10814 10815 bool IsStaticMemberFunctionFromBoundPointer() const { 10816 return StaticMemberFunctionFromBoundPointer; 10817 } 10818 10819 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10820 S.Diag(OvlExpr->getLocStart(), 10821 diag::err_invalid_form_pointer_member_function) 10822 << OvlExpr->getSourceRange(); 10823 } 10824 10825 void ComplainOfInvalidConversion() const { 10826 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10827 << OvlExpr->getName() << TargetType; 10828 } 10829 10830 void ComplainMultipleMatchesFound() const { 10831 assert(Matches.size() > 1); 10832 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10833 << OvlExpr->getName() 10834 << OvlExpr->getSourceRange(); 10835 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10836 /*TakingAddress=*/true); 10837 } 10838 10839 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10840 10841 int getNumMatches() const { return Matches.size(); } 10842 10843 FunctionDecl* getMatchingFunctionDecl() const { 10844 if (Matches.size() != 1) return nullptr; 10845 return Matches[0].second; 10846 } 10847 10848 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10849 if (Matches.size() != 1) return nullptr; 10850 return &Matches[0].first; 10851 } 10852 }; 10853 } 10854 10855 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10856 /// an overloaded function (C++ [over.over]), where @p From is an 10857 /// expression with overloaded function type and @p ToType is the type 10858 /// we're trying to resolve to. For example: 10859 /// 10860 /// @code 10861 /// int f(double); 10862 /// int f(int); 10863 /// 10864 /// int (*pfd)(double) = f; // selects f(double) 10865 /// @endcode 10866 /// 10867 /// This routine returns the resulting FunctionDecl if it could be 10868 /// resolved, and NULL otherwise. When @p Complain is true, this 10869 /// routine will emit diagnostics if there is an error. 10870 FunctionDecl * 10871 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10872 QualType TargetType, 10873 bool Complain, 10874 DeclAccessPair &FoundResult, 10875 bool *pHadMultipleCandidates) { 10876 assert(AddressOfExpr->getType() == Context.OverloadTy); 10877 10878 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10879 Complain); 10880 int NumMatches = Resolver.getNumMatches(); 10881 FunctionDecl *Fn = nullptr; 10882 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10883 if (NumMatches == 0 && ShouldComplain) { 10884 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10885 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10886 else 10887 Resolver.ComplainNoMatchesFound(); 10888 } 10889 else if (NumMatches > 1 && ShouldComplain) 10890 Resolver.ComplainMultipleMatchesFound(); 10891 else if (NumMatches == 1) { 10892 Fn = Resolver.getMatchingFunctionDecl(); 10893 assert(Fn); 10894 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 10895 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 10896 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10897 if (Complain) { 10898 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10899 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10900 else 10901 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10902 } 10903 } 10904 10905 if (pHadMultipleCandidates) 10906 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10907 return Fn; 10908 } 10909 10910 /// \brief Given an expression that refers to an overloaded function, try to 10911 /// resolve that function to a single function that can have its address taken. 10912 /// This will modify `Pair` iff it returns non-null. 10913 /// 10914 /// This routine can only realistically succeed if all but one candidates in the 10915 /// overload set for SrcExpr cannot have their addresses taken. 10916 FunctionDecl * 10917 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 10918 DeclAccessPair &Pair) { 10919 OverloadExpr::FindResult R = OverloadExpr::find(E); 10920 OverloadExpr *Ovl = R.Expression; 10921 FunctionDecl *Result = nullptr; 10922 DeclAccessPair DAP; 10923 // Don't use the AddressOfResolver because we're specifically looking for 10924 // cases where we have one overload candidate that lacks 10925 // enable_if/pass_object_size/... 10926 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 10927 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 10928 if (!FD) 10929 return nullptr; 10930 10931 if (!checkAddressOfFunctionIsAvailable(FD)) 10932 continue; 10933 10934 // We have more than one result; quit. 10935 if (Result) 10936 return nullptr; 10937 DAP = I.getPair(); 10938 Result = FD; 10939 } 10940 10941 if (Result) 10942 Pair = DAP; 10943 return Result; 10944 } 10945 10946 /// \brief Given an overloaded function, tries to turn it into a non-overloaded 10947 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 10948 /// will perform access checks, diagnose the use of the resultant decl, and, if 10949 /// necessary, perform a function-to-pointer decay. 10950 /// 10951 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 10952 /// Otherwise, returns true. This may emit diagnostics and return true. 10953 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 10954 ExprResult &SrcExpr) { 10955 Expr *E = SrcExpr.get(); 10956 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 10957 10958 DeclAccessPair DAP; 10959 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 10960 if (!Found) 10961 return false; 10962 10963 // Emitting multiple diagnostics for a function that is both inaccessible and 10964 // unavailable is consistent with our behavior elsewhere. So, always check 10965 // for both. 10966 DiagnoseUseOfDecl(Found, E->getExprLoc()); 10967 CheckAddressOfMemberAccess(E, DAP); 10968 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 10969 if (Fixed->getType()->isFunctionType()) 10970 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 10971 else 10972 SrcExpr = Fixed; 10973 return true; 10974 } 10975 10976 /// \brief Given an expression that refers to an overloaded function, try to 10977 /// resolve that overloaded function expression down to a single function. 10978 /// 10979 /// This routine can only resolve template-ids that refer to a single function 10980 /// template, where that template-id refers to a single template whose template 10981 /// arguments are either provided by the template-id or have defaults, 10982 /// as described in C++0x [temp.arg.explicit]p3. 10983 /// 10984 /// If no template-ids are found, no diagnostics are emitted and NULL is 10985 /// returned. 10986 FunctionDecl * 10987 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10988 bool Complain, 10989 DeclAccessPair *FoundResult) { 10990 // C++ [over.over]p1: 10991 // [...] [Note: any redundant set of parentheses surrounding the 10992 // overloaded function name is ignored (5.1). ] 10993 // C++ [over.over]p1: 10994 // [...] The overloaded function name can be preceded by the & 10995 // operator. 10996 10997 // If we didn't actually find any template-ids, we're done. 10998 if (!ovl->hasExplicitTemplateArgs()) 10999 return nullptr; 11000 11001 TemplateArgumentListInfo ExplicitTemplateArgs; 11002 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11003 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11004 11005 // Look through all of the overloaded functions, searching for one 11006 // whose type matches exactly. 11007 FunctionDecl *Matched = nullptr; 11008 for (UnresolvedSetIterator I = ovl->decls_begin(), 11009 E = ovl->decls_end(); I != E; ++I) { 11010 // C++0x [temp.arg.explicit]p3: 11011 // [...] In contexts where deduction is done and fails, or in contexts 11012 // where deduction is not done, if a template argument list is 11013 // specified and it, along with any default template arguments, 11014 // identifies a single function template specialization, then the 11015 // template-id is an lvalue for the function template specialization. 11016 FunctionTemplateDecl *FunctionTemplate 11017 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11018 11019 // C++ [over.over]p2: 11020 // If the name is a function template, template argument deduction is 11021 // done (14.8.2.2), and if the argument deduction succeeds, the 11022 // resulting template argument list is used to generate a single 11023 // function template specialization, which is added to the set of 11024 // overloaded functions considered. 11025 FunctionDecl *Specialization = nullptr; 11026 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11027 if (TemplateDeductionResult Result 11028 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11029 Specialization, Info, 11030 /*IsAddressOfFunction*/true)) { 11031 // Make a note of the failed deduction for diagnostics. 11032 // TODO: Actually use the failed-deduction info? 11033 FailedCandidates.addCandidate() 11034 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11035 MakeDeductionFailureInfo(Context, Result, Info)); 11036 continue; 11037 } 11038 11039 assert(Specialization && "no specialization and no error?"); 11040 11041 // Multiple matches; we can't resolve to a single declaration. 11042 if (Matched) { 11043 if (Complain) { 11044 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11045 << ovl->getName(); 11046 NoteAllOverloadCandidates(ovl); 11047 } 11048 return nullptr; 11049 } 11050 11051 Matched = Specialization; 11052 if (FoundResult) *FoundResult = I.getPair(); 11053 } 11054 11055 if (Matched && 11056 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11057 return nullptr; 11058 11059 return Matched; 11060 } 11061 11062 11063 11064 11065 // Resolve and fix an overloaded expression that can be resolved 11066 // because it identifies a single function template specialization. 11067 // 11068 // Last three arguments should only be supplied if Complain = true 11069 // 11070 // Return true if it was logically possible to so resolve the 11071 // expression, regardless of whether or not it succeeded. Always 11072 // returns true if 'complain' is set. 11073 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11074 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11075 bool complain, SourceRange OpRangeForComplaining, 11076 QualType DestTypeForComplaining, 11077 unsigned DiagIDForComplaining) { 11078 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11079 11080 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11081 11082 DeclAccessPair found; 11083 ExprResult SingleFunctionExpression; 11084 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11085 ovl.Expression, /*complain*/ false, &found)) { 11086 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 11087 SrcExpr = ExprError(); 11088 return true; 11089 } 11090 11091 // It is only correct to resolve to an instance method if we're 11092 // resolving a form that's permitted to be a pointer to member. 11093 // Otherwise we'll end up making a bound member expression, which 11094 // is illegal in all the contexts we resolve like this. 11095 if (!ovl.HasFormOfMemberPointer && 11096 isa<CXXMethodDecl>(fn) && 11097 cast<CXXMethodDecl>(fn)->isInstance()) { 11098 if (!complain) return false; 11099 11100 Diag(ovl.Expression->getExprLoc(), 11101 diag::err_bound_member_function) 11102 << 0 << ovl.Expression->getSourceRange(); 11103 11104 // TODO: I believe we only end up here if there's a mix of 11105 // static and non-static candidates (otherwise the expression 11106 // would have 'bound member' type, not 'overload' type). 11107 // Ideally we would note which candidate was chosen and why 11108 // the static candidates were rejected. 11109 SrcExpr = ExprError(); 11110 return true; 11111 } 11112 11113 // Fix the expression to refer to 'fn'. 11114 SingleFunctionExpression = 11115 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11116 11117 // If desired, do function-to-pointer decay. 11118 if (doFunctionPointerConverion) { 11119 SingleFunctionExpression = 11120 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11121 if (SingleFunctionExpression.isInvalid()) { 11122 SrcExpr = ExprError(); 11123 return true; 11124 } 11125 } 11126 } 11127 11128 if (!SingleFunctionExpression.isUsable()) { 11129 if (complain) { 11130 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11131 << ovl.Expression->getName() 11132 << DestTypeForComplaining 11133 << OpRangeForComplaining 11134 << ovl.Expression->getQualifierLoc().getSourceRange(); 11135 NoteAllOverloadCandidates(SrcExpr.get()); 11136 11137 SrcExpr = ExprError(); 11138 return true; 11139 } 11140 11141 return false; 11142 } 11143 11144 SrcExpr = SingleFunctionExpression; 11145 return true; 11146 } 11147 11148 /// \brief Add a single candidate to the overload set. 11149 static void AddOverloadedCallCandidate(Sema &S, 11150 DeclAccessPair FoundDecl, 11151 TemplateArgumentListInfo *ExplicitTemplateArgs, 11152 ArrayRef<Expr *> Args, 11153 OverloadCandidateSet &CandidateSet, 11154 bool PartialOverloading, 11155 bool KnownValid) { 11156 NamedDecl *Callee = FoundDecl.getDecl(); 11157 if (isa<UsingShadowDecl>(Callee)) 11158 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11159 11160 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11161 if (ExplicitTemplateArgs) { 11162 assert(!KnownValid && "Explicit template arguments?"); 11163 return; 11164 } 11165 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11166 /*SuppressUsedConversions=*/false, 11167 PartialOverloading); 11168 return; 11169 } 11170 11171 if (FunctionTemplateDecl *FuncTemplate 11172 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11173 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11174 ExplicitTemplateArgs, Args, CandidateSet, 11175 /*SuppressUsedConversions=*/false, 11176 PartialOverloading); 11177 return; 11178 } 11179 11180 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11181 } 11182 11183 /// \brief Add the overload candidates named by callee and/or found by argument 11184 /// dependent lookup to the given overload set. 11185 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11186 ArrayRef<Expr *> Args, 11187 OverloadCandidateSet &CandidateSet, 11188 bool PartialOverloading) { 11189 11190 #ifndef NDEBUG 11191 // Verify that ArgumentDependentLookup is consistent with the rules 11192 // in C++0x [basic.lookup.argdep]p3: 11193 // 11194 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11195 // and let Y be the lookup set produced by argument dependent 11196 // lookup (defined as follows). If X contains 11197 // 11198 // -- a declaration of a class member, or 11199 // 11200 // -- a block-scope function declaration that is not a 11201 // using-declaration, or 11202 // 11203 // -- a declaration that is neither a function or a function 11204 // template 11205 // 11206 // then Y is empty. 11207 11208 if (ULE->requiresADL()) { 11209 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11210 E = ULE->decls_end(); I != E; ++I) { 11211 assert(!(*I)->getDeclContext()->isRecord()); 11212 assert(isa<UsingShadowDecl>(*I) || 11213 !(*I)->getDeclContext()->isFunctionOrMethod()); 11214 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11215 } 11216 } 11217 #endif 11218 11219 // It would be nice to avoid this copy. 11220 TemplateArgumentListInfo TABuffer; 11221 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11222 if (ULE->hasExplicitTemplateArgs()) { 11223 ULE->copyTemplateArgumentsInto(TABuffer); 11224 ExplicitTemplateArgs = &TABuffer; 11225 } 11226 11227 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11228 E = ULE->decls_end(); I != E; ++I) 11229 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11230 CandidateSet, PartialOverloading, 11231 /*KnownValid*/ true); 11232 11233 if (ULE->requiresADL()) 11234 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11235 Args, ExplicitTemplateArgs, 11236 CandidateSet, PartialOverloading); 11237 } 11238 11239 /// Determine whether a declaration with the specified name could be moved into 11240 /// a different namespace. 11241 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11242 switch (Name.getCXXOverloadedOperator()) { 11243 case OO_New: case OO_Array_New: 11244 case OO_Delete: case OO_Array_Delete: 11245 return false; 11246 11247 default: 11248 return true; 11249 } 11250 } 11251 11252 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11253 /// template, where the non-dependent name was declared after the template 11254 /// was defined. This is common in code written for a compilers which do not 11255 /// correctly implement two-stage name lookup. 11256 /// 11257 /// Returns true if a viable candidate was found and a diagnostic was issued. 11258 static bool 11259 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11260 const CXXScopeSpec &SS, LookupResult &R, 11261 OverloadCandidateSet::CandidateSetKind CSK, 11262 TemplateArgumentListInfo *ExplicitTemplateArgs, 11263 ArrayRef<Expr *> Args, 11264 bool *DoDiagnoseEmptyLookup = nullptr) { 11265 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 11266 return false; 11267 11268 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11269 if (DC->isTransparentContext()) 11270 continue; 11271 11272 SemaRef.LookupQualifiedName(R, DC); 11273 11274 if (!R.empty()) { 11275 R.suppressDiagnostics(); 11276 11277 if (isa<CXXRecordDecl>(DC)) { 11278 // Don't diagnose names we find in classes; we get much better 11279 // diagnostics for these from DiagnoseEmptyLookup. 11280 R.clear(); 11281 if (DoDiagnoseEmptyLookup) 11282 *DoDiagnoseEmptyLookup = true; 11283 return false; 11284 } 11285 11286 OverloadCandidateSet Candidates(FnLoc, CSK); 11287 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11288 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11289 ExplicitTemplateArgs, Args, 11290 Candidates, false, /*KnownValid*/ false); 11291 11292 OverloadCandidateSet::iterator Best; 11293 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11294 // No viable functions. Don't bother the user with notes for functions 11295 // which don't work and shouldn't be found anyway. 11296 R.clear(); 11297 return false; 11298 } 11299 11300 // Find the namespaces where ADL would have looked, and suggest 11301 // declaring the function there instead. 11302 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11303 Sema::AssociatedClassSet AssociatedClasses; 11304 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11305 AssociatedNamespaces, 11306 AssociatedClasses); 11307 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11308 if (canBeDeclaredInNamespace(R.getLookupName())) { 11309 DeclContext *Std = SemaRef.getStdNamespace(); 11310 for (Sema::AssociatedNamespaceSet::iterator 11311 it = AssociatedNamespaces.begin(), 11312 end = AssociatedNamespaces.end(); it != end; ++it) { 11313 // Never suggest declaring a function within namespace 'std'. 11314 if (Std && Std->Encloses(*it)) 11315 continue; 11316 11317 // Never suggest declaring a function within a namespace with a 11318 // reserved name, like __gnu_cxx. 11319 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11320 if (NS && 11321 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11322 continue; 11323 11324 SuggestedNamespaces.insert(*it); 11325 } 11326 } 11327 11328 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11329 << R.getLookupName(); 11330 if (SuggestedNamespaces.empty()) { 11331 SemaRef.Diag(Best->Function->getLocation(), 11332 diag::note_not_found_by_two_phase_lookup) 11333 << R.getLookupName() << 0; 11334 } else if (SuggestedNamespaces.size() == 1) { 11335 SemaRef.Diag(Best->Function->getLocation(), 11336 diag::note_not_found_by_two_phase_lookup) 11337 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11338 } else { 11339 // FIXME: It would be useful to list the associated namespaces here, 11340 // but the diagnostics infrastructure doesn't provide a way to produce 11341 // a localized representation of a list of items. 11342 SemaRef.Diag(Best->Function->getLocation(), 11343 diag::note_not_found_by_two_phase_lookup) 11344 << R.getLookupName() << 2; 11345 } 11346 11347 // Try to recover by calling this function. 11348 return true; 11349 } 11350 11351 R.clear(); 11352 } 11353 11354 return false; 11355 } 11356 11357 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11358 /// template, where the non-dependent operator was declared after the template 11359 /// was defined. 11360 /// 11361 /// Returns true if a viable candidate was found and a diagnostic was issued. 11362 static bool 11363 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11364 SourceLocation OpLoc, 11365 ArrayRef<Expr *> Args) { 11366 DeclarationName OpName = 11367 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11368 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11369 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11370 OverloadCandidateSet::CSK_Operator, 11371 /*ExplicitTemplateArgs=*/nullptr, Args); 11372 } 11373 11374 namespace { 11375 class BuildRecoveryCallExprRAII { 11376 Sema &SemaRef; 11377 public: 11378 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11379 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11380 SemaRef.IsBuildingRecoveryCallExpr = true; 11381 } 11382 11383 ~BuildRecoveryCallExprRAII() { 11384 SemaRef.IsBuildingRecoveryCallExpr = false; 11385 } 11386 }; 11387 11388 } 11389 11390 static std::unique_ptr<CorrectionCandidateCallback> 11391 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11392 bool HasTemplateArgs, bool AllowTypoCorrection) { 11393 if (!AllowTypoCorrection) 11394 return llvm::make_unique<NoTypoCorrectionCCC>(); 11395 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11396 HasTemplateArgs, ME); 11397 } 11398 11399 /// Attempts to recover from a call where no functions were found. 11400 /// 11401 /// Returns true if new candidates were found. 11402 static ExprResult 11403 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11404 UnresolvedLookupExpr *ULE, 11405 SourceLocation LParenLoc, 11406 MutableArrayRef<Expr *> Args, 11407 SourceLocation RParenLoc, 11408 bool EmptyLookup, bool AllowTypoCorrection) { 11409 // Do not try to recover if it is already building a recovery call. 11410 // This stops infinite loops for template instantiations like 11411 // 11412 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11413 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11414 // 11415 if (SemaRef.IsBuildingRecoveryCallExpr) 11416 return ExprError(); 11417 BuildRecoveryCallExprRAII RCE(SemaRef); 11418 11419 CXXScopeSpec SS; 11420 SS.Adopt(ULE->getQualifierLoc()); 11421 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11422 11423 TemplateArgumentListInfo TABuffer; 11424 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11425 if (ULE->hasExplicitTemplateArgs()) { 11426 ULE->copyTemplateArgumentsInto(TABuffer); 11427 ExplicitTemplateArgs = &TABuffer; 11428 } 11429 11430 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11431 Sema::LookupOrdinaryName); 11432 bool DoDiagnoseEmptyLookup = EmptyLookup; 11433 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11434 OverloadCandidateSet::CSK_Normal, 11435 ExplicitTemplateArgs, Args, 11436 &DoDiagnoseEmptyLookup) && 11437 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11438 S, SS, R, 11439 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11440 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11441 ExplicitTemplateArgs, Args))) 11442 return ExprError(); 11443 11444 assert(!R.empty() && "lookup results empty despite recovery"); 11445 11446 // If recovery created an ambiguity, just bail out. 11447 if (R.isAmbiguous()) { 11448 R.suppressDiagnostics(); 11449 return ExprError(); 11450 } 11451 11452 // Build an implicit member call if appropriate. Just drop the 11453 // casts and such from the call, we don't really care. 11454 ExprResult NewFn = ExprError(); 11455 if ((*R.begin())->isCXXClassMember()) 11456 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11457 ExplicitTemplateArgs, S); 11458 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11459 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11460 ExplicitTemplateArgs); 11461 else 11462 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11463 11464 if (NewFn.isInvalid()) 11465 return ExprError(); 11466 11467 // This shouldn't cause an infinite loop because we're giving it 11468 // an expression with viable lookup results, which should never 11469 // end up here. 11470 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11471 MultiExprArg(Args.data(), Args.size()), 11472 RParenLoc); 11473 } 11474 11475 /// \brief Constructs and populates an OverloadedCandidateSet from 11476 /// the given function. 11477 /// \returns true when an the ExprResult output parameter has been set. 11478 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11479 UnresolvedLookupExpr *ULE, 11480 MultiExprArg Args, 11481 SourceLocation RParenLoc, 11482 OverloadCandidateSet *CandidateSet, 11483 ExprResult *Result) { 11484 #ifndef NDEBUG 11485 if (ULE->requiresADL()) { 11486 // To do ADL, we must have found an unqualified name. 11487 assert(!ULE->getQualifier() && "qualified name with ADL"); 11488 11489 // We don't perform ADL for implicit declarations of builtins. 11490 // Verify that this was correctly set up. 11491 FunctionDecl *F; 11492 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11493 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11494 F->getBuiltinID() && F->isImplicit()) 11495 llvm_unreachable("performing ADL for builtin"); 11496 11497 // We don't perform ADL in C. 11498 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11499 } 11500 #endif 11501 11502 UnbridgedCastsSet UnbridgedCasts; 11503 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11504 *Result = ExprError(); 11505 return true; 11506 } 11507 11508 // Add the functions denoted by the callee to the set of candidate 11509 // functions, including those from argument-dependent lookup. 11510 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11511 11512 if (getLangOpts().MSVCCompat && 11513 CurContext->isDependentContext() && !isSFINAEContext() && 11514 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11515 11516 OverloadCandidateSet::iterator Best; 11517 if (CandidateSet->empty() || 11518 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11519 OR_No_Viable_Function) { 11520 // In Microsoft mode, if we are inside a template class member function then 11521 // create a type dependent CallExpr. The goal is to postpone name lookup 11522 // to instantiation time to be able to search into type dependent base 11523 // classes. 11524 CallExpr *CE = new (Context) CallExpr( 11525 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11526 CE->setTypeDependent(true); 11527 CE->setValueDependent(true); 11528 CE->setInstantiationDependent(true); 11529 *Result = CE; 11530 return true; 11531 } 11532 } 11533 11534 if (CandidateSet->empty()) 11535 return false; 11536 11537 UnbridgedCasts.restore(); 11538 return false; 11539 } 11540 11541 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11542 /// the completed call expression. If overload resolution fails, emits 11543 /// diagnostics and returns ExprError() 11544 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11545 UnresolvedLookupExpr *ULE, 11546 SourceLocation LParenLoc, 11547 MultiExprArg Args, 11548 SourceLocation RParenLoc, 11549 Expr *ExecConfig, 11550 OverloadCandidateSet *CandidateSet, 11551 OverloadCandidateSet::iterator *Best, 11552 OverloadingResult OverloadResult, 11553 bool AllowTypoCorrection) { 11554 if (CandidateSet->empty()) 11555 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11556 RParenLoc, /*EmptyLookup=*/true, 11557 AllowTypoCorrection); 11558 11559 switch (OverloadResult) { 11560 case OR_Success: { 11561 FunctionDecl *FDecl = (*Best)->Function; 11562 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11563 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11564 return ExprError(); 11565 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11566 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11567 ExecConfig); 11568 } 11569 11570 case OR_No_Viable_Function: { 11571 // Try to recover by looking for viable functions which the user might 11572 // have meant to call. 11573 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11574 Args, RParenLoc, 11575 /*EmptyLookup=*/false, 11576 AllowTypoCorrection); 11577 if (!Recovery.isInvalid()) 11578 return Recovery; 11579 11580 // If the user passes in a function that we can't take the address of, we 11581 // generally end up emitting really bad error messages. Here, we attempt to 11582 // emit better ones. 11583 for (const Expr *Arg : Args) { 11584 if (!Arg->getType()->isFunctionType()) 11585 continue; 11586 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11587 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11588 if (FD && 11589 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11590 Arg->getExprLoc())) 11591 return ExprError(); 11592 } 11593 } 11594 11595 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11596 << ULE->getName() << Fn->getSourceRange(); 11597 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11598 break; 11599 } 11600 11601 case OR_Ambiguous: 11602 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11603 << ULE->getName() << Fn->getSourceRange(); 11604 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11605 break; 11606 11607 case OR_Deleted: { 11608 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11609 << (*Best)->Function->isDeleted() 11610 << ULE->getName() 11611 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11612 << Fn->getSourceRange(); 11613 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11614 11615 // We emitted an error for the unvailable/deleted function call but keep 11616 // the call in the AST. 11617 FunctionDecl *FDecl = (*Best)->Function; 11618 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11619 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11620 ExecConfig); 11621 } 11622 } 11623 11624 // Overload resolution failed. 11625 return ExprError(); 11626 } 11627 11628 static void markUnaddressableCandidatesUnviable(Sema &S, 11629 OverloadCandidateSet &CS) { 11630 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11631 if (I->Viable && 11632 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11633 I->Viable = false; 11634 I->FailureKind = ovl_fail_addr_not_available; 11635 } 11636 } 11637 } 11638 11639 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11640 /// (which eventually refers to the declaration Func) and the call 11641 /// arguments Args/NumArgs, attempt to resolve the function call down 11642 /// to a specific function. If overload resolution succeeds, returns 11643 /// the call expression produced by overload resolution. 11644 /// Otherwise, emits diagnostics and returns ExprError. 11645 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11646 UnresolvedLookupExpr *ULE, 11647 SourceLocation LParenLoc, 11648 MultiExprArg Args, 11649 SourceLocation RParenLoc, 11650 Expr *ExecConfig, 11651 bool AllowTypoCorrection, 11652 bool CalleesAddressIsTaken) { 11653 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11654 OverloadCandidateSet::CSK_Normal); 11655 ExprResult result; 11656 11657 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11658 &result)) 11659 return result; 11660 11661 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11662 // functions that aren't addressible are considered unviable. 11663 if (CalleesAddressIsTaken) 11664 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11665 11666 OverloadCandidateSet::iterator Best; 11667 OverloadingResult OverloadResult = 11668 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11669 11670 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11671 RParenLoc, ExecConfig, &CandidateSet, 11672 &Best, OverloadResult, 11673 AllowTypoCorrection); 11674 } 11675 11676 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11677 return Functions.size() > 1 || 11678 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11679 } 11680 11681 /// \brief Create a unary operation that may resolve to an overloaded 11682 /// operator. 11683 /// 11684 /// \param OpLoc The location of the operator itself (e.g., '*'). 11685 /// 11686 /// \param Opc The UnaryOperatorKind that describes this operator. 11687 /// 11688 /// \param Fns The set of non-member functions that will be 11689 /// considered by overload resolution. The caller needs to build this 11690 /// set based on the context using, e.g., 11691 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11692 /// set should not contain any member functions; those will be added 11693 /// by CreateOverloadedUnaryOp(). 11694 /// 11695 /// \param Input The input argument. 11696 ExprResult 11697 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11698 const UnresolvedSetImpl &Fns, 11699 Expr *Input) { 11700 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11701 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11702 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11703 // TODO: provide better source location info. 11704 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11705 11706 if (checkPlaceholderForOverload(*this, Input)) 11707 return ExprError(); 11708 11709 Expr *Args[2] = { Input, nullptr }; 11710 unsigned NumArgs = 1; 11711 11712 // For post-increment and post-decrement, add the implicit '0' as 11713 // the second argument, so that we know this is a post-increment or 11714 // post-decrement. 11715 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11716 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11717 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11718 SourceLocation()); 11719 NumArgs = 2; 11720 } 11721 11722 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11723 11724 if (Input->isTypeDependent()) { 11725 if (Fns.empty()) 11726 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11727 VK_RValue, OK_Ordinary, OpLoc); 11728 11729 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11730 UnresolvedLookupExpr *Fn 11731 = UnresolvedLookupExpr::Create(Context, NamingClass, 11732 NestedNameSpecifierLoc(), OpNameInfo, 11733 /*ADL*/ true, IsOverloaded(Fns), 11734 Fns.begin(), Fns.end()); 11735 return new (Context) 11736 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11737 VK_RValue, OpLoc, false); 11738 } 11739 11740 // Build an empty overload set. 11741 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11742 11743 // Add the candidates from the given function set. 11744 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11745 11746 // Add operator candidates that are member functions. 11747 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11748 11749 // Add candidates from ADL. 11750 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11751 /*ExplicitTemplateArgs*/nullptr, 11752 CandidateSet); 11753 11754 // Add builtin operator candidates. 11755 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11756 11757 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11758 11759 // Perform overload resolution. 11760 OverloadCandidateSet::iterator Best; 11761 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11762 case OR_Success: { 11763 // We found a built-in operator or an overloaded operator. 11764 FunctionDecl *FnDecl = Best->Function; 11765 11766 if (FnDecl) { 11767 // We matched an overloaded operator. Build a call to that 11768 // operator. 11769 11770 // Convert the arguments. 11771 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11772 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11773 11774 ExprResult InputRes = 11775 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11776 Best->FoundDecl, Method); 11777 if (InputRes.isInvalid()) 11778 return ExprError(); 11779 Input = InputRes.get(); 11780 } else { 11781 // Convert the arguments. 11782 ExprResult InputInit 11783 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11784 Context, 11785 FnDecl->getParamDecl(0)), 11786 SourceLocation(), 11787 Input); 11788 if (InputInit.isInvalid()) 11789 return ExprError(); 11790 Input = InputInit.get(); 11791 } 11792 11793 // Build the actual expression node. 11794 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11795 HadMultipleCandidates, OpLoc); 11796 if (FnExpr.isInvalid()) 11797 return ExprError(); 11798 11799 // Determine the result type. 11800 QualType ResultTy = FnDecl->getReturnType(); 11801 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11802 ResultTy = ResultTy.getNonLValueExprType(Context); 11803 11804 Args[0] = Input; 11805 CallExpr *TheCall = 11806 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11807 ResultTy, VK, OpLoc, false); 11808 11809 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11810 return ExprError(); 11811 11812 return MaybeBindToTemporary(TheCall); 11813 } else { 11814 // We matched a built-in operator. Convert the arguments, then 11815 // break out so that we will build the appropriate built-in 11816 // operator node. 11817 ExprResult InputRes = 11818 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11819 Best->Conversions[0], AA_Passing); 11820 if (InputRes.isInvalid()) 11821 return ExprError(); 11822 Input = InputRes.get(); 11823 break; 11824 } 11825 } 11826 11827 case OR_No_Viable_Function: 11828 // This is an erroneous use of an operator which can be overloaded by 11829 // a non-member function. Check for non-member operators which were 11830 // defined too late to be candidates. 11831 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11832 // FIXME: Recover by calling the found function. 11833 return ExprError(); 11834 11835 // No viable function; fall through to handling this as a 11836 // built-in operator, which will produce an error message for us. 11837 break; 11838 11839 case OR_Ambiguous: 11840 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11841 << UnaryOperator::getOpcodeStr(Opc) 11842 << Input->getType() 11843 << Input->getSourceRange(); 11844 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11845 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11846 return ExprError(); 11847 11848 case OR_Deleted: 11849 Diag(OpLoc, diag::err_ovl_deleted_oper) 11850 << Best->Function->isDeleted() 11851 << UnaryOperator::getOpcodeStr(Opc) 11852 << getDeletedOrUnavailableSuffix(Best->Function) 11853 << Input->getSourceRange(); 11854 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11855 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11856 return ExprError(); 11857 } 11858 11859 // Either we found no viable overloaded operator or we matched a 11860 // built-in operator. In either case, fall through to trying to 11861 // build a built-in operation. 11862 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11863 } 11864 11865 /// \brief Create a binary operation that may resolve to an overloaded 11866 /// operator. 11867 /// 11868 /// \param OpLoc The location of the operator itself (e.g., '+'). 11869 /// 11870 /// \param Opc The BinaryOperatorKind that describes this operator. 11871 /// 11872 /// \param Fns The set of non-member functions that will be 11873 /// considered by overload resolution. The caller needs to build this 11874 /// set based on the context using, e.g., 11875 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11876 /// set should not contain any member functions; those will be added 11877 /// by CreateOverloadedBinOp(). 11878 /// 11879 /// \param LHS Left-hand argument. 11880 /// \param RHS Right-hand argument. 11881 ExprResult 11882 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11883 BinaryOperatorKind Opc, 11884 const UnresolvedSetImpl &Fns, 11885 Expr *LHS, Expr *RHS) { 11886 Expr *Args[2] = { LHS, RHS }; 11887 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11888 11889 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11890 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11891 11892 // If either side is type-dependent, create an appropriate dependent 11893 // expression. 11894 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11895 if (Fns.empty()) { 11896 // If there are no functions to store, just build a dependent 11897 // BinaryOperator or CompoundAssignment. 11898 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11899 return new (Context) BinaryOperator( 11900 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11901 OpLoc, FPFeatures.fp_contract); 11902 11903 return new (Context) CompoundAssignOperator( 11904 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11905 Context.DependentTy, Context.DependentTy, OpLoc, 11906 FPFeatures.fp_contract); 11907 } 11908 11909 // FIXME: save results of ADL from here? 11910 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11911 // TODO: provide better source location info in DNLoc component. 11912 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11913 UnresolvedLookupExpr *Fn 11914 = UnresolvedLookupExpr::Create(Context, NamingClass, 11915 NestedNameSpecifierLoc(), OpNameInfo, 11916 /*ADL*/ true, IsOverloaded(Fns), 11917 Fns.begin(), Fns.end()); 11918 return new (Context) 11919 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11920 VK_RValue, OpLoc, FPFeatures.fp_contract); 11921 } 11922 11923 // Always do placeholder-like conversions on the RHS. 11924 if (checkPlaceholderForOverload(*this, Args[1])) 11925 return ExprError(); 11926 11927 // Do placeholder-like conversion on the LHS; note that we should 11928 // not get here with a PseudoObject LHS. 11929 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11930 if (checkPlaceholderForOverload(*this, Args[0])) 11931 return ExprError(); 11932 11933 // If this is the assignment operator, we only perform overload resolution 11934 // if the left-hand side is a class or enumeration type. This is actually 11935 // a hack. The standard requires that we do overload resolution between the 11936 // various built-in candidates, but as DR507 points out, this can lead to 11937 // problems. So we do it this way, which pretty much follows what GCC does. 11938 // Note that we go the traditional code path for compound assignment forms. 11939 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11940 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11941 11942 // If this is the .* operator, which is not overloadable, just 11943 // create a built-in binary operator. 11944 if (Opc == BO_PtrMemD) 11945 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11946 11947 // Build an empty overload set. 11948 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11949 11950 // Add the candidates from the given function set. 11951 AddFunctionCandidates(Fns, Args, CandidateSet); 11952 11953 // Add operator candidates that are member functions. 11954 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11955 11956 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11957 // performed for an assignment operator (nor for operator[] nor operator->, 11958 // which don't get here). 11959 if (Opc != BO_Assign) 11960 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11961 /*ExplicitTemplateArgs*/ nullptr, 11962 CandidateSet); 11963 11964 // Add builtin operator candidates. 11965 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11966 11967 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11968 11969 // Perform overload resolution. 11970 OverloadCandidateSet::iterator Best; 11971 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11972 case OR_Success: { 11973 // We found a built-in operator or an overloaded operator. 11974 FunctionDecl *FnDecl = Best->Function; 11975 11976 if (FnDecl) { 11977 // We matched an overloaded operator. Build a call to that 11978 // operator. 11979 11980 // Convert the arguments. 11981 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11982 // Best->Access is only meaningful for class members. 11983 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11984 11985 ExprResult Arg1 = 11986 PerformCopyInitialization( 11987 InitializedEntity::InitializeParameter(Context, 11988 FnDecl->getParamDecl(0)), 11989 SourceLocation(), Args[1]); 11990 if (Arg1.isInvalid()) 11991 return ExprError(); 11992 11993 ExprResult Arg0 = 11994 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11995 Best->FoundDecl, Method); 11996 if (Arg0.isInvalid()) 11997 return ExprError(); 11998 Args[0] = Arg0.getAs<Expr>(); 11999 Args[1] = RHS = Arg1.getAs<Expr>(); 12000 } else { 12001 // Convert the arguments. 12002 ExprResult Arg0 = PerformCopyInitialization( 12003 InitializedEntity::InitializeParameter(Context, 12004 FnDecl->getParamDecl(0)), 12005 SourceLocation(), Args[0]); 12006 if (Arg0.isInvalid()) 12007 return ExprError(); 12008 12009 ExprResult Arg1 = 12010 PerformCopyInitialization( 12011 InitializedEntity::InitializeParameter(Context, 12012 FnDecl->getParamDecl(1)), 12013 SourceLocation(), Args[1]); 12014 if (Arg1.isInvalid()) 12015 return ExprError(); 12016 Args[0] = LHS = Arg0.getAs<Expr>(); 12017 Args[1] = RHS = Arg1.getAs<Expr>(); 12018 } 12019 12020 // Build the actual expression node. 12021 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12022 Best->FoundDecl, 12023 HadMultipleCandidates, OpLoc); 12024 if (FnExpr.isInvalid()) 12025 return ExprError(); 12026 12027 // Determine the result type. 12028 QualType ResultTy = FnDecl->getReturnType(); 12029 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12030 ResultTy = ResultTy.getNonLValueExprType(Context); 12031 12032 CXXOperatorCallExpr *TheCall = 12033 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 12034 Args, ResultTy, VK, OpLoc, 12035 FPFeatures.fp_contract); 12036 12037 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12038 FnDecl)) 12039 return ExprError(); 12040 12041 ArrayRef<const Expr *> ArgsArray(Args, 2); 12042 // Cut off the implicit 'this'. 12043 if (isa<CXXMethodDecl>(FnDecl)) 12044 ArgsArray = ArgsArray.slice(1); 12045 12046 // Check for a self move. 12047 if (Op == OO_Equal) 12048 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12049 12050 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 12051 TheCall->getSourceRange(), VariadicDoesNotApply); 12052 12053 return MaybeBindToTemporary(TheCall); 12054 } else { 12055 // We matched a built-in operator. Convert the arguments, then 12056 // break out so that we will build the appropriate built-in 12057 // operator node. 12058 ExprResult ArgsRes0 = 12059 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12060 Best->Conversions[0], AA_Passing); 12061 if (ArgsRes0.isInvalid()) 12062 return ExprError(); 12063 Args[0] = ArgsRes0.get(); 12064 12065 ExprResult ArgsRes1 = 12066 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12067 Best->Conversions[1], AA_Passing); 12068 if (ArgsRes1.isInvalid()) 12069 return ExprError(); 12070 Args[1] = ArgsRes1.get(); 12071 break; 12072 } 12073 } 12074 12075 case OR_No_Viable_Function: { 12076 // C++ [over.match.oper]p9: 12077 // If the operator is the operator , [...] and there are no 12078 // viable functions, then the operator is assumed to be the 12079 // built-in operator and interpreted according to clause 5. 12080 if (Opc == BO_Comma) 12081 break; 12082 12083 // For class as left operand for assignment or compound assigment 12084 // operator do not fall through to handling in built-in, but report that 12085 // no overloaded assignment operator found 12086 ExprResult Result = ExprError(); 12087 if (Args[0]->getType()->isRecordType() && 12088 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12089 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12090 << BinaryOperator::getOpcodeStr(Opc) 12091 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12092 if (Args[0]->getType()->isIncompleteType()) { 12093 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12094 << Args[0]->getType() 12095 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12096 } 12097 } else { 12098 // This is an erroneous use of an operator which can be overloaded by 12099 // a non-member function. Check for non-member operators which were 12100 // defined too late to be candidates. 12101 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12102 // FIXME: Recover by calling the found function. 12103 return ExprError(); 12104 12105 // No viable function; try to create a built-in operation, which will 12106 // produce an error. Then, show the non-viable candidates. 12107 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12108 } 12109 assert(Result.isInvalid() && 12110 "C++ binary operator overloading is missing candidates!"); 12111 if (Result.isInvalid()) 12112 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12113 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12114 return Result; 12115 } 12116 12117 case OR_Ambiguous: 12118 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12119 << BinaryOperator::getOpcodeStr(Opc) 12120 << Args[0]->getType() << Args[1]->getType() 12121 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12122 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12123 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12124 return ExprError(); 12125 12126 case OR_Deleted: 12127 if (isImplicitlyDeleted(Best->Function)) { 12128 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12129 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12130 << Context.getRecordType(Method->getParent()) 12131 << getSpecialMember(Method); 12132 12133 // The user probably meant to call this special member. Just 12134 // explain why it's deleted. 12135 NoteDeletedFunction(Method); 12136 return ExprError(); 12137 } else { 12138 Diag(OpLoc, diag::err_ovl_deleted_oper) 12139 << Best->Function->isDeleted() 12140 << BinaryOperator::getOpcodeStr(Opc) 12141 << getDeletedOrUnavailableSuffix(Best->Function) 12142 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12143 } 12144 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12145 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12146 return ExprError(); 12147 } 12148 12149 // We matched a built-in operator; build it. 12150 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12151 } 12152 12153 ExprResult 12154 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12155 SourceLocation RLoc, 12156 Expr *Base, Expr *Idx) { 12157 Expr *Args[2] = { Base, Idx }; 12158 DeclarationName OpName = 12159 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12160 12161 // If either side is type-dependent, create an appropriate dependent 12162 // expression. 12163 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12164 12165 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12166 // CHECKME: no 'operator' keyword? 12167 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12168 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12169 UnresolvedLookupExpr *Fn 12170 = UnresolvedLookupExpr::Create(Context, NamingClass, 12171 NestedNameSpecifierLoc(), OpNameInfo, 12172 /*ADL*/ true, /*Overloaded*/ false, 12173 UnresolvedSetIterator(), 12174 UnresolvedSetIterator()); 12175 // Can't add any actual overloads yet 12176 12177 return new (Context) 12178 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12179 Context.DependentTy, VK_RValue, RLoc, false); 12180 } 12181 12182 // Handle placeholders on both operands. 12183 if (checkPlaceholderForOverload(*this, Args[0])) 12184 return ExprError(); 12185 if (checkPlaceholderForOverload(*this, Args[1])) 12186 return ExprError(); 12187 12188 // Build an empty overload set. 12189 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12190 12191 // Subscript can only be overloaded as a member function. 12192 12193 // Add operator candidates that are member functions. 12194 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12195 12196 // Add builtin operator candidates. 12197 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12198 12199 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12200 12201 // Perform overload resolution. 12202 OverloadCandidateSet::iterator Best; 12203 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12204 case OR_Success: { 12205 // We found a built-in operator or an overloaded operator. 12206 FunctionDecl *FnDecl = Best->Function; 12207 12208 if (FnDecl) { 12209 // We matched an overloaded operator. Build a call to that 12210 // operator. 12211 12212 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12213 12214 // Convert the arguments. 12215 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12216 ExprResult Arg0 = 12217 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12218 Best->FoundDecl, Method); 12219 if (Arg0.isInvalid()) 12220 return ExprError(); 12221 Args[0] = Arg0.get(); 12222 12223 // Convert the arguments. 12224 ExprResult InputInit 12225 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12226 Context, 12227 FnDecl->getParamDecl(0)), 12228 SourceLocation(), 12229 Args[1]); 12230 if (InputInit.isInvalid()) 12231 return ExprError(); 12232 12233 Args[1] = InputInit.getAs<Expr>(); 12234 12235 // Build the actual expression node. 12236 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12237 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12238 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12239 Best->FoundDecl, 12240 HadMultipleCandidates, 12241 OpLocInfo.getLoc(), 12242 OpLocInfo.getInfo()); 12243 if (FnExpr.isInvalid()) 12244 return ExprError(); 12245 12246 // Determine the result type 12247 QualType ResultTy = FnDecl->getReturnType(); 12248 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12249 ResultTy = ResultTy.getNonLValueExprType(Context); 12250 12251 CXXOperatorCallExpr *TheCall = 12252 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12253 FnExpr.get(), Args, 12254 ResultTy, VK, RLoc, 12255 false); 12256 12257 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12258 return ExprError(); 12259 12260 return MaybeBindToTemporary(TheCall); 12261 } else { 12262 // We matched a built-in operator. Convert the arguments, then 12263 // break out so that we will build the appropriate built-in 12264 // operator node. 12265 ExprResult ArgsRes0 = 12266 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12267 Best->Conversions[0], AA_Passing); 12268 if (ArgsRes0.isInvalid()) 12269 return ExprError(); 12270 Args[0] = ArgsRes0.get(); 12271 12272 ExprResult ArgsRes1 = 12273 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12274 Best->Conversions[1], AA_Passing); 12275 if (ArgsRes1.isInvalid()) 12276 return ExprError(); 12277 Args[1] = ArgsRes1.get(); 12278 12279 break; 12280 } 12281 } 12282 12283 case OR_No_Viable_Function: { 12284 if (CandidateSet.empty()) 12285 Diag(LLoc, diag::err_ovl_no_oper) 12286 << Args[0]->getType() << /*subscript*/ 0 12287 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12288 else 12289 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12290 << Args[0]->getType() 12291 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12292 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12293 "[]", LLoc); 12294 return ExprError(); 12295 } 12296 12297 case OR_Ambiguous: 12298 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12299 << "[]" 12300 << Args[0]->getType() << Args[1]->getType() 12301 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12302 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12303 "[]", LLoc); 12304 return ExprError(); 12305 12306 case OR_Deleted: 12307 Diag(LLoc, diag::err_ovl_deleted_oper) 12308 << Best->Function->isDeleted() << "[]" 12309 << getDeletedOrUnavailableSuffix(Best->Function) 12310 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12311 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12312 "[]", LLoc); 12313 return ExprError(); 12314 } 12315 12316 // We matched a built-in operator; build it. 12317 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12318 } 12319 12320 /// BuildCallToMemberFunction - Build a call to a member 12321 /// function. MemExpr is the expression that refers to the member 12322 /// function (and includes the object parameter), Args/NumArgs are the 12323 /// arguments to the function call (not including the object 12324 /// parameter). The caller needs to validate that the member 12325 /// expression refers to a non-static member function or an overloaded 12326 /// member function. 12327 ExprResult 12328 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12329 SourceLocation LParenLoc, 12330 MultiExprArg Args, 12331 SourceLocation RParenLoc) { 12332 assert(MemExprE->getType() == Context.BoundMemberTy || 12333 MemExprE->getType() == Context.OverloadTy); 12334 12335 // Dig out the member expression. This holds both the object 12336 // argument and the member function we're referring to. 12337 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12338 12339 // Determine whether this is a call to a pointer-to-member function. 12340 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12341 assert(op->getType() == Context.BoundMemberTy); 12342 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12343 12344 QualType fnType = 12345 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12346 12347 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12348 QualType resultType = proto->getCallResultType(Context); 12349 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12350 12351 // Check that the object type isn't more qualified than the 12352 // member function we're calling. 12353 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12354 12355 QualType objectType = op->getLHS()->getType(); 12356 if (op->getOpcode() == BO_PtrMemI) 12357 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12358 Qualifiers objectQuals = objectType.getQualifiers(); 12359 12360 Qualifiers difference = objectQuals - funcQuals; 12361 difference.removeObjCGCAttr(); 12362 difference.removeAddressSpace(); 12363 if (difference) { 12364 std::string qualsString = difference.getAsString(); 12365 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12366 << fnType.getUnqualifiedType() 12367 << qualsString 12368 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12369 } 12370 12371 CXXMemberCallExpr *call 12372 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12373 resultType, valueKind, RParenLoc); 12374 12375 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12376 call, nullptr)) 12377 return ExprError(); 12378 12379 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12380 return ExprError(); 12381 12382 if (CheckOtherCall(call, proto)) 12383 return ExprError(); 12384 12385 return MaybeBindToTemporary(call); 12386 } 12387 12388 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12389 return new (Context) 12390 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12391 12392 UnbridgedCastsSet UnbridgedCasts; 12393 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12394 return ExprError(); 12395 12396 MemberExpr *MemExpr; 12397 CXXMethodDecl *Method = nullptr; 12398 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12399 NestedNameSpecifier *Qualifier = nullptr; 12400 if (isa<MemberExpr>(NakedMemExpr)) { 12401 MemExpr = cast<MemberExpr>(NakedMemExpr); 12402 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12403 FoundDecl = MemExpr->getFoundDecl(); 12404 Qualifier = MemExpr->getQualifier(); 12405 UnbridgedCasts.restore(); 12406 } else { 12407 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12408 Qualifier = UnresExpr->getQualifier(); 12409 12410 QualType ObjectType = UnresExpr->getBaseType(); 12411 Expr::Classification ObjectClassification 12412 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12413 : UnresExpr->getBase()->Classify(Context); 12414 12415 // Add overload candidates 12416 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12417 OverloadCandidateSet::CSK_Normal); 12418 12419 // FIXME: avoid copy. 12420 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12421 if (UnresExpr->hasExplicitTemplateArgs()) { 12422 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12423 TemplateArgs = &TemplateArgsBuffer; 12424 } 12425 12426 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12427 E = UnresExpr->decls_end(); I != E; ++I) { 12428 12429 NamedDecl *Func = *I; 12430 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12431 if (isa<UsingShadowDecl>(Func)) 12432 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12433 12434 12435 // Microsoft supports direct constructor calls. 12436 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12437 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12438 Args, CandidateSet); 12439 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12440 // If explicit template arguments were provided, we can't call a 12441 // non-template member function. 12442 if (TemplateArgs) 12443 continue; 12444 12445 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12446 ObjectClassification, Args, CandidateSet, 12447 /*SuppressUserConversions=*/false); 12448 } else { 12449 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12450 I.getPair(), ActingDC, TemplateArgs, 12451 ObjectType, ObjectClassification, 12452 Args, CandidateSet, 12453 /*SuppressUsedConversions=*/false); 12454 } 12455 } 12456 12457 DeclarationName DeclName = UnresExpr->getMemberName(); 12458 12459 UnbridgedCasts.restore(); 12460 12461 OverloadCandidateSet::iterator Best; 12462 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12463 Best)) { 12464 case OR_Success: 12465 Method = cast<CXXMethodDecl>(Best->Function); 12466 FoundDecl = Best->FoundDecl; 12467 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12468 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12469 return ExprError(); 12470 // If FoundDecl is different from Method (such as if one is a template 12471 // and the other a specialization), make sure DiagnoseUseOfDecl is 12472 // called on both. 12473 // FIXME: This would be more comprehensively addressed by modifying 12474 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12475 // being used. 12476 if (Method != FoundDecl.getDecl() && 12477 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12478 return ExprError(); 12479 break; 12480 12481 case OR_No_Viable_Function: 12482 Diag(UnresExpr->getMemberLoc(), 12483 diag::err_ovl_no_viable_member_function_in_call) 12484 << DeclName << MemExprE->getSourceRange(); 12485 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12486 // FIXME: Leaking incoming expressions! 12487 return ExprError(); 12488 12489 case OR_Ambiguous: 12490 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12491 << DeclName << MemExprE->getSourceRange(); 12492 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12493 // FIXME: Leaking incoming expressions! 12494 return ExprError(); 12495 12496 case OR_Deleted: 12497 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12498 << Best->Function->isDeleted() 12499 << DeclName 12500 << getDeletedOrUnavailableSuffix(Best->Function) 12501 << MemExprE->getSourceRange(); 12502 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12503 // FIXME: Leaking incoming expressions! 12504 return ExprError(); 12505 } 12506 12507 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12508 12509 // If overload resolution picked a static member, build a 12510 // non-member call based on that function. 12511 if (Method->isStatic()) { 12512 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12513 RParenLoc); 12514 } 12515 12516 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12517 } 12518 12519 QualType ResultType = Method->getReturnType(); 12520 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12521 ResultType = ResultType.getNonLValueExprType(Context); 12522 12523 assert(Method && "Member call to something that isn't a method?"); 12524 CXXMemberCallExpr *TheCall = 12525 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12526 ResultType, VK, RParenLoc); 12527 12528 // Check for a valid return type. 12529 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12530 TheCall, Method)) 12531 return ExprError(); 12532 12533 // Convert the object argument (for a non-static member function call). 12534 // We only need to do this if there was actually an overload; otherwise 12535 // it was done at lookup. 12536 if (!Method->isStatic()) { 12537 ExprResult ObjectArg = 12538 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12539 FoundDecl, Method); 12540 if (ObjectArg.isInvalid()) 12541 return ExprError(); 12542 MemExpr->setBase(ObjectArg.get()); 12543 } 12544 12545 // Convert the rest of the arguments 12546 const FunctionProtoType *Proto = 12547 Method->getType()->getAs<FunctionProtoType>(); 12548 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12549 RParenLoc)) 12550 return ExprError(); 12551 12552 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12553 12554 if (CheckFunctionCall(Method, TheCall, Proto)) 12555 return ExprError(); 12556 12557 // In the case the method to call was not selected by the overloading 12558 // resolution process, we still need to handle the enable_if attribute. Do 12559 // that here, so it will not hide previous -- and more relevant -- errors. 12560 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 12561 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12562 Diag(MemE->getMemberLoc(), 12563 diag::err_ovl_no_viable_member_function_in_call) 12564 << Method << Method->getSourceRange(); 12565 Diag(Method->getLocation(), 12566 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12567 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12568 return ExprError(); 12569 } 12570 } 12571 12572 if ((isa<CXXConstructorDecl>(CurContext) || 12573 isa<CXXDestructorDecl>(CurContext)) && 12574 TheCall->getMethodDecl()->isPure()) { 12575 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12576 12577 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12578 MemExpr->performsVirtualDispatch(getLangOpts())) { 12579 Diag(MemExpr->getLocStart(), 12580 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12581 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12582 << MD->getParent()->getDeclName(); 12583 12584 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12585 if (getLangOpts().AppleKext) 12586 Diag(MemExpr->getLocStart(), 12587 diag::note_pure_qualified_call_kext) 12588 << MD->getParent()->getDeclName() 12589 << MD->getDeclName(); 12590 } 12591 } 12592 12593 if (CXXDestructorDecl *DD = 12594 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12595 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12596 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 12597 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12598 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12599 MemExpr->getMemberLoc()); 12600 } 12601 12602 return MaybeBindToTemporary(TheCall); 12603 } 12604 12605 /// BuildCallToObjectOfClassType - Build a call to an object of class 12606 /// type (C++ [over.call.object]), which can end up invoking an 12607 /// overloaded function call operator (@c operator()) or performing a 12608 /// user-defined conversion on the object argument. 12609 ExprResult 12610 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12611 SourceLocation LParenLoc, 12612 MultiExprArg Args, 12613 SourceLocation RParenLoc) { 12614 if (checkPlaceholderForOverload(*this, Obj)) 12615 return ExprError(); 12616 ExprResult Object = Obj; 12617 12618 UnbridgedCastsSet UnbridgedCasts; 12619 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12620 return ExprError(); 12621 12622 assert(Object.get()->getType()->isRecordType() && 12623 "Requires object type argument"); 12624 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12625 12626 // C++ [over.call.object]p1: 12627 // If the primary-expression E in the function call syntax 12628 // evaluates to a class object of type "cv T", then the set of 12629 // candidate functions includes at least the function call 12630 // operators of T. The function call operators of T are obtained by 12631 // ordinary lookup of the name operator() in the context of 12632 // (E).operator(). 12633 OverloadCandidateSet CandidateSet(LParenLoc, 12634 OverloadCandidateSet::CSK_Operator); 12635 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12636 12637 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12638 diag::err_incomplete_object_call, Object.get())) 12639 return true; 12640 12641 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12642 LookupQualifiedName(R, Record->getDecl()); 12643 R.suppressDiagnostics(); 12644 12645 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12646 Oper != OperEnd; ++Oper) { 12647 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12648 Object.get()->Classify(Context), 12649 Args, CandidateSet, 12650 /*SuppressUserConversions=*/ false); 12651 } 12652 12653 // C++ [over.call.object]p2: 12654 // In addition, for each (non-explicit in C++0x) conversion function 12655 // declared in T of the form 12656 // 12657 // operator conversion-type-id () cv-qualifier; 12658 // 12659 // where cv-qualifier is the same cv-qualification as, or a 12660 // greater cv-qualification than, cv, and where conversion-type-id 12661 // denotes the type "pointer to function of (P1,...,Pn) returning 12662 // R", or the type "reference to pointer to function of 12663 // (P1,...,Pn) returning R", or the type "reference to function 12664 // of (P1,...,Pn) returning R", a surrogate call function [...] 12665 // is also considered as a candidate function. Similarly, 12666 // surrogate call functions are added to the set of candidate 12667 // functions for each conversion function declared in an 12668 // accessible base class provided the function is not hidden 12669 // within T by another intervening declaration. 12670 const auto &Conversions = 12671 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12672 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12673 NamedDecl *D = *I; 12674 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12675 if (isa<UsingShadowDecl>(D)) 12676 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12677 12678 // Skip over templated conversion functions; they aren't 12679 // surrogates. 12680 if (isa<FunctionTemplateDecl>(D)) 12681 continue; 12682 12683 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12684 if (!Conv->isExplicit()) { 12685 // Strip the reference type (if any) and then the pointer type (if 12686 // any) to get down to what might be a function type. 12687 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12688 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12689 ConvType = ConvPtrType->getPointeeType(); 12690 12691 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12692 { 12693 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12694 Object.get(), Args, CandidateSet); 12695 } 12696 } 12697 } 12698 12699 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12700 12701 // Perform overload resolution. 12702 OverloadCandidateSet::iterator Best; 12703 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12704 Best)) { 12705 case OR_Success: 12706 // Overload resolution succeeded; we'll build the appropriate call 12707 // below. 12708 break; 12709 12710 case OR_No_Viable_Function: 12711 if (CandidateSet.empty()) 12712 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12713 << Object.get()->getType() << /*call*/ 1 12714 << Object.get()->getSourceRange(); 12715 else 12716 Diag(Object.get()->getLocStart(), 12717 diag::err_ovl_no_viable_object_call) 12718 << Object.get()->getType() << Object.get()->getSourceRange(); 12719 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12720 break; 12721 12722 case OR_Ambiguous: 12723 Diag(Object.get()->getLocStart(), 12724 diag::err_ovl_ambiguous_object_call) 12725 << Object.get()->getType() << Object.get()->getSourceRange(); 12726 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12727 break; 12728 12729 case OR_Deleted: 12730 Diag(Object.get()->getLocStart(), 12731 diag::err_ovl_deleted_object_call) 12732 << Best->Function->isDeleted() 12733 << Object.get()->getType() 12734 << getDeletedOrUnavailableSuffix(Best->Function) 12735 << Object.get()->getSourceRange(); 12736 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12737 break; 12738 } 12739 12740 if (Best == CandidateSet.end()) 12741 return true; 12742 12743 UnbridgedCasts.restore(); 12744 12745 if (Best->Function == nullptr) { 12746 // Since there is no function declaration, this is one of the 12747 // surrogate candidates. Dig out the conversion function. 12748 CXXConversionDecl *Conv 12749 = cast<CXXConversionDecl>( 12750 Best->Conversions[0].UserDefined.ConversionFunction); 12751 12752 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12753 Best->FoundDecl); 12754 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12755 return ExprError(); 12756 assert(Conv == Best->FoundDecl.getDecl() && 12757 "Found Decl & conversion-to-functionptr should be same, right?!"); 12758 // We selected one of the surrogate functions that converts the 12759 // object parameter to a function pointer. Perform the conversion 12760 // on the object argument, then let ActOnCallExpr finish the job. 12761 12762 // Create an implicit member expr to refer to the conversion operator. 12763 // and then call it. 12764 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12765 Conv, HadMultipleCandidates); 12766 if (Call.isInvalid()) 12767 return ExprError(); 12768 // Record usage of conversion in an implicit cast. 12769 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12770 CK_UserDefinedConversion, Call.get(), 12771 nullptr, VK_RValue); 12772 12773 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12774 } 12775 12776 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12777 12778 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12779 // that calls this method, using Object for the implicit object 12780 // parameter and passing along the remaining arguments. 12781 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12782 12783 // An error diagnostic has already been printed when parsing the declaration. 12784 if (Method->isInvalidDecl()) 12785 return ExprError(); 12786 12787 const FunctionProtoType *Proto = 12788 Method->getType()->getAs<FunctionProtoType>(); 12789 12790 unsigned NumParams = Proto->getNumParams(); 12791 12792 DeclarationNameInfo OpLocInfo( 12793 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12794 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12795 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12796 HadMultipleCandidates, 12797 OpLocInfo.getLoc(), 12798 OpLocInfo.getInfo()); 12799 if (NewFn.isInvalid()) 12800 return true; 12801 12802 // Build the full argument list for the method call (the implicit object 12803 // parameter is placed at the beginning of the list). 12804 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1); 12805 MethodArgs[0] = Object.get(); 12806 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1); 12807 12808 // Once we've built TheCall, all of the expressions are properly 12809 // owned. 12810 QualType ResultTy = Method->getReturnType(); 12811 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12812 ResultTy = ResultTy.getNonLValueExprType(Context); 12813 12814 CXXOperatorCallExpr *TheCall = new (Context) 12815 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, 12816 VK, RParenLoc, false); 12817 12818 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12819 return true; 12820 12821 // We may have default arguments. If so, we need to allocate more 12822 // slots in the call for them. 12823 if (Args.size() < NumParams) 12824 TheCall->setNumArgs(Context, NumParams + 1); 12825 12826 bool IsError = false; 12827 12828 // Initialize the implicit object parameter. 12829 ExprResult ObjRes = 12830 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12831 Best->FoundDecl, Method); 12832 if (ObjRes.isInvalid()) 12833 IsError = true; 12834 else 12835 Object = ObjRes; 12836 TheCall->setArg(0, Object.get()); 12837 12838 // Check the argument types. 12839 for (unsigned i = 0; i != NumParams; i++) { 12840 Expr *Arg; 12841 if (i < Args.size()) { 12842 Arg = Args[i]; 12843 12844 // Pass the argument. 12845 12846 ExprResult InputInit 12847 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12848 Context, 12849 Method->getParamDecl(i)), 12850 SourceLocation(), Arg); 12851 12852 IsError |= InputInit.isInvalid(); 12853 Arg = InputInit.getAs<Expr>(); 12854 } else { 12855 ExprResult DefArg 12856 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12857 if (DefArg.isInvalid()) { 12858 IsError = true; 12859 break; 12860 } 12861 12862 Arg = DefArg.getAs<Expr>(); 12863 } 12864 12865 TheCall->setArg(i + 1, Arg); 12866 } 12867 12868 // If this is a variadic call, handle args passed through "...". 12869 if (Proto->isVariadic()) { 12870 // Promote the arguments (C99 6.5.2.2p7). 12871 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12872 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12873 nullptr); 12874 IsError |= Arg.isInvalid(); 12875 TheCall->setArg(i + 1, Arg.get()); 12876 } 12877 } 12878 12879 if (IsError) return true; 12880 12881 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12882 12883 if (CheckFunctionCall(Method, TheCall, Proto)) 12884 return true; 12885 12886 return MaybeBindToTemporary(TheCall); 12887 } 12888 12889 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12890 /// (if one exists), where @c Base is an expression of class type and 12891 /// @c Member is the name of the member we're trying to find. 12892 ExprResult 12893 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12894 bool *NoArrowOperatorFound) { 12895 assert(Base->getType()->isRecordType() && 12896 "left-hand side must have class type"); 12897 12898 if (checkPlaceholderForOverload(*this, Base)) 12899 return ExprError(); 12900 12901 SourceLocation Loc = Base->getExprLoc(); 12902 12903 // C++ [over.ref]p1: 12904 // 12905 // [...] An expression x->m is interpreted as (x.operator->())->m 12906 // for a class object x of type T if T::operator->() exists and if 12907 // the operator is selected as the best match function by the 12908 // overload resolution mechanism (13.3). 12909 DeclarationName OpName = 12910 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12911 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12912 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12913 12914 if (RequireCompleteType(Loc, Base->getType(), 12915 diag::err_typecheck_incomplete_tag, Base)) 12916 return ExprError(); 12917 12918 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12919 LookupQualifiedName(R, BaseRecord->getDecl()); 12920 R.suppressDiagnostics(); 12921 12922 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12923 Oper != OperEnd; ++Oper) { 12924 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12925 None, CandidateSet, /*SuppressUserConversions=*/false); 12926 } 12927 12928 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12929 12930 // Perform overload resolution. 12931 OverloadCandidateSet::iterator Best; 12932 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12933 case OR_Success: 12934 // Overload resolution succeeded; we'll build the call below. 12935 break; 12936 12937 case OR_No_Viable_Function: 12938 if (CandidateSet.empty()) { 12939 QualType BaseType = Base->getType(); 12940 if (NoArrowOperatorFound) { 12941 // Report this specific error to the caller instead of emitting a 12942 // diagnostic, as requested. 12943 *NoArrowOperatorFound = true; 12944 return ExprError(); 12945 } 12946 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12947 << BaseType << Base->getSourceRange(); 12948 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12949 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12950 << FixItHint::CreateReplacement(OpLoc, "."); 12951 } 12952 } else 12953 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12954 << "operator->" << Base->getSourceRange(); 12955 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12956 return ExprError(); 12957 12958 case OR_Ambiguous: 12959 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12960 << "->" << Base->getType() << Base->getSourceRange(); 12961 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12962 return ExprError(); 12963 12964 case OR_Deleted: 12965 Diag(OpLoc, diag::err_ovl_deleted_oper) 12966 << Best->Function->isDeleted() 12967 << "->" 12968 << getDeletedOrUnavailableSuffix(Best->Function) 12969 << Base->getSourceRange(); 12970 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12971 return ExprError(); 12972 } 12973 12974 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12975 12976 // Convert the object parameter. 12977 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12978 ExprResult BaseResult = 12979 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12980 Best->FoundDecl, Method); 12981 if (BaseResult.isInvalid()) 12982 return ExprError(); 12983 Base = BaseResult.get(); 12984 12985 // Build the operator call. 12986 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12987 HadMultipleCandidates, OpLoc); 12988 if (FnExpr.isInvalid()) 12989 return ExprError(); 12990 12991 QualType ResultTy = Method->getReturnType(); 12992 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12993 ResultTy = ResultTy.getNonLValueExprType(Context); 12994 CXXOperatorCallExpr *TheCall = 12995 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12996 Base, ResultTy, VK, OpLoc, false); 12997 12998 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12999 return ExprError(); 13000 13001 return MaybeBindToTemporary(TheCall); 13002 } 13003 13004 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13005 /// a literal operator described by the provided lookup results. 13006 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13007 DeclarationNameInfo &SuffixInfo, 13008 ArrayRef<Expr*> Args, 13009 SourceLocation LitEndLoc, 13010 TemplateArgumentListInfo *TemplateArgs) { 13011 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13012 13013 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13014 OverloadCandidateSet::CSK_Normal); 13015 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13016 /*SuppressUserConversions=*/true); 13017 13018 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13019 13020 // Perform overload resolution. This will usually be trivial, but might need 13021 // to perform substitutions for a literal operator template. 13022 OverloadCandidateSet::iterator Best; 13023 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13024 case OR_Success: 13025 case OR_Deleted: 13026 break; 13027 13028 case OR_No_Viable_Function: 13029 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13030 << R.getLookupName(); 13031 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13032 return ExprError(); 13033 13034 case OR_Ambiguous: 13035 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13036 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13037 return ExprError(); 13038 } 13039 13040 FunctionDecl *FD = Best->Function; 13041 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13042 HadMultipleCandidates, 13043 SuffixInfo.getLoc(), 13044 SuffixInfo.getInfo()); 13045 if (Fn.isInvalid()) 13046 return true; 13047 13048 // Check the argument types. This should almost always be a no-op, except 13049 // that array-to-pointer decay is applied to string literals. 13050 Expr *ConvArgs[2]; 13051 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13052 ExprResult InputInit = PerformCopyInitialization( 13053 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13054 SourceLocation(), Args[ArgIdx]); 13055 if (InputInit.isInvalid()) 13056 return true; 13057 ConvArgs[ArgIdx] = InputInit.get(); 13058 } 13059 13060 QualType ResultTy = FD->getReturnType(); 13061 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13062 ResultTy = ResultTy.getNonLValueExprType(Context); 13063 13064 UserDefinedLiteral *UDL = 13065 new (Context) UserDefinedLiteral(Context, Fn.get(), 13066 llvm::makeArrayRef(ConvArgs, Args.size()), 13067 ResultTy, VK, LitEndLoc, UDSuffixLoc); 13068 13069 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13070 return ExprError(); 13071 13072 if (CheckFunctionCall(FD, UDL, nullptr)) 13073 return ExprError(); 13074 13075 return MaybeBindToTemporary(UDL); 13076 } 13077 13078 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13079 /// given LookupResult is non-empty, it is assumed to describe a member which 13080 /// will be invoked. Otherwise, the function will be found via argument 13081 /// dependent lookup. 13082 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13083 /// otherwise CallExpr is set to ExprError() and some non-success value 13084 /// is returned. 13085 Sema::ForRangeStatus 13086 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13087 SourceLocation RangeLoc, 13088 const DeclarationNameInfo &NameInfo, 13089 LookupResult &MemberLookup, 13090 OverloadCandidateSet *CandidateSet, 13091 Expr *Range, ExprResult *CallExpr) { 13092 Scope *S = nullptr; 13093 13094 CandidateSet->clear(); 13095 if (!MemberLookup.empty()) { 13096 ExprResult MemberRef = 13097 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13098 /*IsPtr=*/false, CXXScopeSpec(), 13099 /*TemplateKWLoc=*/SourceLocation(), 13100 /*FirstQualifierInScope=*/nullptr, 13101 MemberLookup, 13102 /*TemplateArgs=*/nullptr, S); 13103 if (MemberRef.isInvalid()) { 13104 *CallExpr = ExprError(); 13105 return FRS_DiagnosticIssued; 13106 } 13107 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13108 if (CallExpr->isInvalid()) { 13109 *CallExpr = ExprError(); 13110 return FRS_DiagnosticIssued; 13111 } 13112 } else { 13113 UnresolvedSet<0> FoundNames; 13114 UnresolvedLookupExpr *Fn = 13115 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13116 NestedNameSpecifierLoc(), NameInfo, 13117 /*NeedsADL=*/true, /*Overloaded=*/false, 13118 FoundNames.begin(), FoundNames.end()); 13119 13120 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13121 CandidateSet, CallExpr); 13122 if (CandidateSet->empty() || CandidateSetError) { 13123 *CallExpr = ExprError(); 13124 return FRS_NoViableFunction; 13125 } 13126 OverloadCandidateSet::iterator Best; 13127 OverloadingResult OverloadResult = 13128 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 13129 13130 if (OverloadResult == OR_No_Viable_Function) { 13131 *CallExpr = ExprError(); 13132 return FRS_NoViableFunction; 13133 } 13134 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13135 Loc, nullptr, CandidateSet, &Best, 13136 OverloadResult, 13137 /*AllowTypoCorrection=*/false); 13138 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13139 *CallExpr = ExprError(); 13140 return FRS_DiagnosticIssued; 13141 } 13142 } 13143 return FRS_Success; 13144 } 13145 13146 13147 /// FixOverloadedFunctionReference - E is an expression that refers to 13148 /// a C++ overloaded function (possibly with some parentheses and 13149 /// perhaps a '&' around it). We have resolved the overloaded function 13150 /// to the function declaration Fn, so patch up the expression E to 13151 /// refer (possibly indirectly) to Fn. Returns the new expr. 13152 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13153 FunctionDecl *Fn) { 13154 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13155 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13156 Found, Fn); 13157 if (SubExpr == PE->getSubExpr()) 13158 return PE; 13159 13160 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13161 } 13162 13163 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13164 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13165 Found, Fn); 13166 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13167 SubExpr->getType()) && 13168 "Implicit cast type cannot be determined from overload"); 13169 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13170 if (SubExpr == ICE->getSubExpr()) 13171 return ICE; 13172 13173 return ImplicitCastExpr::Create(Context, ICE->getType(), 13174 ICE->getCastKind(), 13175 SubExpr, nullptr, 13176 ICE->getValueKind()); 13177 } 13178 13179 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13180 if (!GSE->isResultDependent()) { 13181 Expr *SubExpr = 13182 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13183 if (SubExpr == GSE->getResultExpr()) 13184 return GSE; 13185 13186 // Replace the resulting type information before rebuilding the generic 13187 // selection expression. 13188 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13189 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13190 unsigned ResultIdx = GSE->getResultIndex(); 13191 AssocExprs[ResultIdx] = SubExpr; 13192 13193 return new (Context) GenericSelectionExpr( 13194 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13195 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13196 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13197 ResultIdx); 13198 } 13199 // Rather than fall through to the unreachable, return the original generic 13200 // selection expression. 13201 return GSE; 13202 } 13203 13204 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13205 assert(UnOp->getOpcode() == UO_AddrOf && 13206 "Can only take the address of an overloaded function"); 13207 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13208 if (Method->isStatic()) { 13209 // Do nothing: static member functions aren't any different 13210 // from non-member functions. 13211 } else { 13212 // Fix the subexpression, which really has to be an 13213 // UnresolvedLookupExpr holding an overloaded member function 13214 // or template. 13215 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13216 Found, Fn); 13217 if (SubExpr == UnOp->getSubExpr()) 13218 return UnOp; 13219 13220 assert(isa<DeclRefExpr>(SubExpr) 13221 && "fixed to something other than a decl ref"); 13222 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13223 && "fixed to a member ref with no nested name qualifier"); 13224 13225 // We have taken the address of a pointer to member 13226 // function. Perform the computation here so that we get the 13227 // appropriate pointer to member type. 13228 QualType ClassType 13229 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13230 QualType MemPtrType 13231 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13232 // Under the MS ABI, lock down the inheritance model now. 13233 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13234 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13235 13236 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13237 VK_RValue, OK_Ordinary, 13238 UnOp->getOperatorLoc()); 13239 } 13240 } 13241 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13242 Found, Fn); 13243 if (SubExpr == UnOp->getSubExpr()) 13244 return UnOp; 13245 13246 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13247 Context.getPointerType(SubExpr->getType()), 13248 VK_RValue, OK_Ordinary, 13249 UnOp->getOperatorLoc()); 13250 } 13251 13252 // C++ [except.spec]p17: 13253 // An exception-specification is considered to be needed when: 13254 // - in an expression the function is the unique lookup result or the 13255 // selected member of a set of overloaded functions 13256 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13257 ResolveExceptionSpec(E->getExprLoc(), FPT); 13258 13259 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13260 // FIXME: avoid copy. 13261 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13262 if (ULE->hasExplicitTemplateArgs()) { 13263 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13264 TemplateArgs = &TemplateArgsBuffer; 13265 } 13266 13267 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13268 ULE->getQualifierLoc(), 13269 ULE->getTemplateKeywordLoc(), 13270 Fn, 13271 /*enclosing*/ false, // FIXME? 13272 ULE->getNameLoc(), 13273 Fn->getType(), 13274 VK_LValue, 13275 Found.getDecl(), 13276 TemplateArgs); 13277 MarkDeclRefReferenced(DRE); 13278 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13279 return DRE; 13280 } 13281 13282 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13283 // FIXME: avoid copy. 13284 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13285 if (MemExpr->hasExplicitTemplateArgs()) { 13286 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13287 TemplateArgs = &TemplateArgsBuffer; 13288 } 13289 13290 Expr *Base; 13291 13292 // If we're filling in a static method where we used to have an 13293 // implicit member access, rewrite to a simple decl ref. 13294 if (MemExpr->isImplicitAccess()) { 13295 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13296 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13297 MemExpr->getQualifierLoc(), 13298 MemExpr->getTemplateKeywordLoc(), 13299 Fn, 13300 /*enclosing*/ false, 13301 MemExpr->getMemberLoc(), 13302 Fn->getType(), 13303 VK_LValue, 13304 Found.getDecl(), 13305 TemplateArgs); 13306 MarkDeclRefReferenced(DRE); 13307 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13308 return DRE; 13309 } else { 13310 SourceLocation Loc = MemExpr->getMemberLoc(); 13311 if (MemExpr->getQualifier()) 13312 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13313 CheckCXXThisCapture(Loc); 13314 Base = new (Context) CXXThisExpr(Loc, 13315 MemExpr->getBaseType(), 13316 /*isImplicit=*/true); 13317 } 13318 } else 13319 Base = MemExpr->getBase(); 13320 13321 ExprValueKind valueKind; 13322 QualType type; 13323 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13324 valueKind = VK_LValue; 13325 type = Fn->getType(); 13326 } else { 13327 valueKind = VK_RValue; 13328 type = Context.BoundMemberTy; 13329 } 13330 13331 MemberExpr *ME = MemberExpr::Create( 13332 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13333 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13334 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13335 OK_Ordinary); 13336 ME->setHadMultipleCandidates(true); 13337 MarkMemberReferenced(ME); 13338 return ME; 13339 } 13340 13341 llvm_unreachable("Invalid reference to overloaded function"); 13342 } 13343 13344 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13345 DeclAccessPair Found, 13346 FunctionDecl *Fn) { 13347 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13348 } 13349