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 /// A convenience routine for creating a decayed reference to a function. 42 static ExprResult 43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 44 bool HadMultipleCandidates, 45 SourceLocation Loc = SourceLocation(), 46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 47 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 48 return ExprError(); 49 // If FoundDecl is different from Fn (such as if one is a template 50 // and the other a specialization), make sure DiagnoseUseOfDecl is 51 // called on both. 52 // FIXME: This would be more comprehensively addressed by modifying 53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 54 // being used. 55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 56 return ExprError(); 57 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 58 VK_LValue, Loc, LocInfo); 59 if (HadMultipleCandidates) 60 DRE->setHadMultipleCandidates(true); 61 62 S.MarkDeclRefReferenced(DRE); 63 64 ExprResult E = DRE; 65 E = S.DefaultFunctionArrayConversion(E.get()); 66 if (E.isInvalid()) 67 return ExprError(); 68 return E; 69 } 70 71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 72 bool InOverloadResolution, 73 StandardConversionSequence &SCS, 74 bool CStyle, 75 bool AllowObjCWritebackConversion); 76 77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 78 QualType &ToType, 79 bool InOverloadResolution, 80 StandardConversionSequence &SCS, 81 bool CStyle); 82 static OverloadingResult 83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 84 UserDefinedConversionSequence& User, 85 OverloadCandidateSet& Conversions, 86 bool AllowExplicit, 87 bool AllowObjCConversionOnExplicit); 88 89 90 static ImplicitConversionSequence::CompareKind 91 CompareStandardConversionSequences(Sema &S, 92 const StandardConversionSequence& SCS1, 93 const StandardConversionSequence& SCS2); 94 95 static ImplicitConversionSequence::CompareKind 96 CompareQualificationConversions(Sema &S, 97 const StandardConversionSequence& SCS1, 98 const StandardConversionSequence& SCS2); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareDerivedToBaseConversions(Sema &S, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 /// GetConversionRank - Retrieve the implicit conversion rank 106 /// corresponding to the given implicit conversion kind. 107 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 108 static const ImplicitConversionRank 109 Rank[(int)ICK_Num_Conversion_Kinds] = { 110 ICR_Exact_Match, 111 ICR_Exact_Match, 112 ICR_Exact_Match, 113 ICR_Exact_Match, 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Promotion, 117 ICR_Promotion, 118 ICR_Promotion, 119 ICR_Conversion, 120 ICR_Conversion, 121 ICR_Conversion, 122 ICR_Conversion, 123 ICR_Conversion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Complex_Real_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Writeback_Conversion, 134 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 135 // it was omitted by the patch that added 136 // ICK_Zero_Event_Conversion 137 ICR_C_Conversion 138 }; 139 return Rank[(int)Kind]; 140 } 141 142 /// GetImplicitConversionName - Return the name of this kind of 143 /// implicit conversion. 144 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 145 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 146 "No conversion", 147 "Lvalue-to-rvalue", 148 "Array-to-pointer", 149 "Function-to-pointer", 150 "Noreturn adjustment", 151 "Qualification", 152 "Integral promotion", 153 "Floating point promotion", 154 "Complex promotion", 155 "Integral conversion", 156 "Floating conversion", 157 "Complex conversion", 158 "Floating-integral conversion", 159 "Pointer conversion", 160 "Pointer-to-member conversion", 161 "Boolean conversion", 162 "Compatible-types conversion", 163 "Derived-to-base conversion", 164 "Vector conversion", 165 "Vector splat", 166 "Complex-real conversion", 167 "Block Pointer conversion", 168 "Transparent Union Conversion", 169 "Writeback conversion", 170 "OpenCL Zero Event Conversion", 171 "C specific type conversion" 172 }; 173 return Name[Kind]; 174 } 175 176 /// StandardConversionSequence - Set the standard conversion 177 /// sequence to the identity conversion. 178 void StandardConversionSequence::setAsIdentityConversion() { 179 First = ICK_Identity; 180 Second = ICK_Identity; 181 Third = ICK_Identity; 182 DeprecatedStringLiteralToCharPtr = false; 183 QualificationIncludesObjCLifetime = false; 184 ReferenceBinding = false; 185 DirectBinding = false; 186 IsLvalueReference = true; 187 BindsToFunctionLvalue = false; 188 BindsToRvalue = false; 189 BindsImplicitObjectArgumentWithoutRefQualifier = false; 190 ObjCLifetimeConversionBinding = false; 191 CopyConstructor = nullptr; 192 } 193 194 /// getRank - Retrieve the rank of this standard conversion sequence 195 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 196 /// implicit conversions. 197 ImplicitConversionRank StandardConversionSequence::getRank() const { 198 ImplicitConversionRank Rank = ICR_Exact_Match; 199 if (GetConversionRank(First) > Rank) 200 Rank = GetConversionRank(First); 201 if (GetConversionRank(Second) > Rank) 202 Rank = GetConversionRank(Second); 203 if (GetConversionRank(Third) > Rank) 204 Rank = GetConversionRank(Third); 205 return Rank; 206 } 207 208 /// isPointerConversionToBool - Determines whether this conversion is 209 /// a conversion of a pointer or pointer-to-member to bool. This is 210 /// used as part of the ranking of standard conversion sequences 211 /// (C++ 13.3.3.2p4). 212 bool StandardConversionSequence::isPointerConversionToBool() const { 213 // Note that FromType has not necessarily been transformed by the 214 // array-to-pointer or function-to-pointer implicit conversions, so 215 // check for their presence as well as checking whether FromType is 216 // a pointer. 217 if (getToType(1)->isBooleanType() && 218 (getFromType()->isPointerType() || 219 getFromType()->isObjCObjectPointerType() || 220 getFromType()->isBlockPointerType() || 221 getFromType()->isNullPtrType() || 222 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 223 return true; 224 225 return false; 226 } 227 228 /// isPointerConversionToVoidPointer - Determines whether this 229 /// conversion is a conversion of a pointer to a void pointer. This is 230 /// used as part of the ranking of standard conversion sequences (C++ 231 /// 13.3.3.2p4). 232 bool 233 StandardConversionSequence:: 234 isPointerConversionToVoidPointer(ASTContext& Context) const { 235 QualType FromType = getFromType(); 236 QualType ToType = getToType(1); 237 238 // Note that FromType has not necessarily been transformed by the 239 // array-to-pointer implicit conversion, so check for its presence 240 // and redo the conversion to get a pointer. 241 if (First == ICK_Array_To_Pointer) 242 FromType = Context.getArrayDecayedType(FromType); 243 244 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 245 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 246 return ToPtrType->getPointeeType()->isVoidType(); 247 248 return false; 249 } 250 251 /// Skip any implicit casts which could be either part of a narrowing conversion 252 /// or after one in an implicit conversion. 253 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 254 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 255 switch (ICE->getCastKind()) { 256 case CK_NoOp: 257 case CK_IntegralCast: 258 case CK_IntegralToBoolean: 259 case CK_IntegralToFloating: 260 case CK_FloatingToIntegral: 261 case CK_FloatingToBoolean: 262 case CK_FloatingCast: 263 Converted = ICE->getSubExpr(); 264 continue; 265 266 default: 267 return Converted; 268 } 269 } 270 271 return Converted; 272 } 273 274 /// Check if this standard conversion sequence represents a narrowing 275 /// conversion, according to C++11 [dcl.init.list]p7. 276 /// 277 /// \param Ctx The AST context. 278 /// \param Converted The result of applying this standard conversion sequence. 279 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 280 /// value of the expression prior to the narrowing conversion. 281 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 282 /// type of the expression prior to the narrowing conversion. 283 NarrowingKind 284 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 285 const Expr *Converted, 286 APValue &ConstantValue, 287 QualType &ConstantType) const { 288 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 289 290 // C++11 [dcl.init.list]p7: 291 // A narrowing conversion is an implicit conversion ... 292 QualType FromType = getToType(0); 293 QualType ToType = getToType(1); 294 switch (Second) { 295 // 'bool' is an integral type; dispatch to the right place to handle it. 296 case ICK_Boolean_Conversion: 297 if (FromType->isRealFloatingType()) 298 goto FloatingIntegralConversion; 299 if (FromType->isIntegralOrUnscopedEnumerationType()) 300 goto IntegralConversion; 301 // Boolean conversions can be from pointers and pointers to members 302 // [conv.bool], and those aren't considered narrowing conversions. 303 return NK_Not_Narrowing; 304 305 // -- from a floating-point type to an integer type, or 306 // 307 // -- from an integer type or unscoped enumeration type to a floating-point 308 // type, except where the source is a constant expression and the actual 309 // value after conversion will fit into the target type and will produce 310 // the original value when converted back to the original type, or 311 case ICK_Floating_Integral: 312 FloatingIntegralConversion: 313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 314 return NK_Type_Narrowing; 315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 316 llvm::APSInt IntConstantValue; 317 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 318 if (Initializer && 319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 320 // Convert the integer to the floating type. 321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 323 llvm::APFloat::rmNearestTiesToEven); 324 // And back. 325 llvm::APSInt ConvertedValue = IntConstantValue; 326 bool ignored; 327 Result.convertToInteger(ConvertedValue, 328 llvm::APFloat::rmTowardZero, &ignored); 329 // If the resulting value is different, this was a narrowing conversion. 330 if (IntConstantValue != ConvertedValue) { 331 ConstantValue = APValue(IntConstantValue); 332 ConstantType = Initializer->getType(); 333 return NK_Constant_Narrowing; 334 } 335 } else { 336 // Variables are always narrowings. 337 return NK_Variable_Narrowing; 338 } 339 } 340 return NK_Not_Narrowing; 341 342 // -- from long double to double or float, or from double to float, except 343 // where the source is a constant expression and the actual value after 344 // conversion is within the range of values that can be represented (even 345 // if it cannot be represented exactly), or 346 case ICK_Floating_Conversion: 347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 349 // FromType is larger than ToType. 350 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 352 // Constant! 353 assert(ConstantValue.isFloat()); 354 llvm::APFloat FloatVal = ConstantValue.getFloat(); 355 // Convert the source value into the target type. 356 bool ignored; 357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 358 Ctx.getFloatTypeSemantics(ToType), 359 llvm::APFloat::rmNearestTiesToEven, &ignored); 360 // If there was no overflow, the source value is within the range of 361 // values that can be represented. 362 if (ConvertStatus & llvm::APFloat::opOverflow) { 363 ConstantType = Initializer->getType(); 364 return NK_Constant_Narrowing; 365 } 366 } else { 367 return NK_Variable_Narrowing; 368 } 369 } 370 return NK_Not_Narrowing; 371 372 // -- from an integer type or unscoped enumeration type to an integer type 373 // that cannot represent all the values of the original type, except where 374 // the source is a constant expression and the actual value after 375 // conversion will fit into the target type and will produce the original 376 // value when converted back to the original type. 377 case ICK_Integral_Conversion: 378 IntegralConversion: { 379 assert(FromType->isIntegralOrUnscopedEnumerationType()); 380 assert(ToType->isIntegralOrUnscopedEnumerationType()); 381 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 382 const unsigned FromWidth = Ctx.getIntWidth(FromType); 383 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 384 const unsigned ToWidth = Ctx.getIntWidth(ToType); 385 386 if (FromWidth > ToWidth || 387 (FromWidth == ToWidth && FromSigned != ToSigned) || 388 (FromSigned && !ToSigned)) { 389 // Not all values of FromType can be represented in ToType. 390 llvm::APSInt InitializerValue; 391 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 392 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 393 // Such conversions on variables are always narrowing. 394 return NK_Variable_Narrowing; 395 } 396 bool Narrowing = false; 397 if (FromWidth < ToWidth) { 398 // Negative -> unsigned is narrowing. Otherwise, more bits is never 399 // narrowing. 400 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 401 Narrowing = true; 402 } else { 403 // Add a bit to the InitializerValue so we don't have to worry about 404 // signed vs. unsigned comparisons. 405 InitializerValue = InitializerValue.extend( 406 InitializerValue.getBitWidth() + 1); 407 // Convert the initializer to and from the target width and signed-ness. 408 llvm::APSInt ConvertedValue = InitializerValue; 409 ConvertedValue = ConvertedValue.trunc(ToWidth); 410 ConvertedValue.setIsSigned(ToSigned); 411 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 412 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 413 // If the result is different, this was a narrowing conversion. 414 if (ConvertedValue != InitializerValue) 415 Narrowing = true; 416 } 417 if (Narrowing) { 418 ConstantType = Initializer->getType(); 419 ConstantValue = APValue(InitializerValue); 420 return NK_Constant_Narrowing; 421 } 422 } 423 return NK_Not_Narrowing; 424 } 425 426 default: 427 // Other kinds of conversions are not narrowings. 428 return NK_Not_Narrowing; 429 } 430 } 431 432 /// dump - Print this standard conversion sequence to standard 433 /// error. Useful for debugging overloading issues. 434 void StandardConversionSequence::dump() const { 435 raw_ostream &OS = llvm::errs(); 436 bool PrintedSomething = false; 437 if (First != ICK_Identity) { 438 OS << GetImplicitConversionName(First); 439 PrintedSomething = true; 440 } 441 442 if (Second != ICK_Identity) { 443 if (PrintedSomething) { 444 OS << " -> "; 445 } 446 OS << GetImplicitConversionName(Second); 447 448 if (CopyConstructor) { 449 OS << " (by copy constructor)"; 450 } else if (DirectBinding) { 451 OS << " (direct reference binding)"; 452 } else if (ReferenceBinding) { 453 OS << " (reference binding)"; 454 } 455 PrintedSomething = true; 456 } 457 458 if (Third != ICK_Identity) { 459 if (PrintedSomething) { 460 OS << " -> "; 461 } 462 OS << GetImplicitConversionName(Third); 463 PrintedSomething = true; 464 } 465 466 if (!PrintedSomething) { 467 OS << "No conversions required"; 468 } 469 } 470 471 /// dump - Print this user-defined conversion sequence to standard 472 /// error. Useful for debugging overloading issues. 473 void UserDefinedConversionSequence::dump() const { 474 raw_ostream &OS = llvm::errs(); 475 if (Before.First || Before.Second || Before.Third) { 476 Before.dump(); 477 OS << " -> "; 478 } 479 if (ConversionFunction) 480 OS << '\'' << *ConversionFunction << '\''; 481 else 482 OS << "aggregate initialization"; 483 if (After.First || After.Second || After.Third) { 484 OS << " -> "; 485 After.dump(); 486 } 487 } 488 489 /// dump - Print this implicit conversion sequence to standard 490 /// error. Useful for debugging overloading issues. 491 void ImplicitConversionSequence::dump() const { 492 raw_ostream &OS = llvm::errs(); 493 if (isStdInitializerListElement()) 494 OS << "Worst std::initializer_list element conversion: "; 495 switch (ConversionKind) { 496 case StandardConversion: 497 OS << "Standard conversion: "; 498 Standard.dump(); 499 break; 500 case UserDefinedConversion: 501 OS << "User-defined conversion: "; 502 UserDefined.dump(); 503 break; 504 case EllipsisConversion: 505 OS << "Ellipsis conversion"; 506 break; 507 case AmbiguousConversion: 508 OS << "Ambiguous conversion"; 509 break; 510 case BadConversion: 511 OS << "Bad conversion"; 512 break; 513 } 514 515 OS << "\n"; 516 } 517 518 void AmbiguousConversionSequence::construct() { 519 new (&conversions()) ConversionSet(); 520 } 521 522 void AmbiguousConversionSequence::destruct() { 523 conversions().~ConversionSet(); 524 } 525 526 void 527 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 528 FromTypePtr = O.FromTypePtr; 529 ToTypePtr = O.ToTypePtr; 530 new (&conversions()) ConversionSet(O.conversions()); 531 } 532 533 namespace { 534 // Structure used by DeductionFailureInfo to store 535 // template argument information. 536 struct DFIArguments { 537 TemplateArgument FirstArg; 538 TemplateArgument SecondArg; 539 }; 540 // Structure used by DeductionFailureInfo to store 541 // template parameter and template argument information. 542 struct DFIParamWithArguments : DFIArguments { 543 TemplateParameter Param; 544 }; 545 } 546 547 /// \brief Convert from Sema's representation of template deduction information 548 /// to the form used in overload-candidate information. 549 DeductionFailureInfo 550 clang::MakeDeductionFailureInfo(ASTContext &Context, 551 Sema::TemplateDeductionResult TDK, 552 TemplateDeductionInfo &Info) { 553 DeductionFailureInfo Result; 554 Result.Result = static_cast<unsigned>(TDK); 555 Result.HasDiagnostic = false; 556 Result.Data = nullptr; 557 switch (TDK) { 558 case Sema::TDK_Success: 559 case Sema::TDK_Invalid: 560 case Sema::TDK_InstantiationDepth: 561 case Sema::TDK_TooManyArguments: 562 case Sema::TDK_TooFewArguments: 563 break; 564 565 case Sema::TDK_Incomplete: 566 case Sema::TDK_InvalidExplicitArguments: 567 Result.Data = Info.Param.getOpaqueValue(); 568 break; 569 570 case Sema::TDK_NonDeducedMismatch: { 571 // FIXME: Should allocate from normal heap so that we can free this later. 572 DFIArguments *Saved = new (Context) DFIArguments; 573 Saved->FirstArg = Info.FirstArg; 574 Saved->SecondArg = Info.SecondArg; 575 Result.Data = Saved; 576 break; 577 } 578 579 case Sema::TDK_Inconsistent: 580 case Sema::TDK_Underqualified: { 581 // FIXME: Should allocate from normal heap so that we can free this later. 582 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 583 Saved->Param = Info.Param; 584 Saved->FirstArg = Info.FirstArg; 585 Saved->SecondArg = Info.SecondArg; 586 Result.Data = Saved; 587 break; 588 } 589 590 case Sema::TDK_SubstitutionFailure: 591 Result.Data = Info.take(); 592 if (Info.hasSFINAEDiagnostic()) { 593 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 594 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 595 Info.takeSFINAEDiagnostic(*Diag); 596 Result.HasDiagnostic = true; 597 } 598 break; 599 600 case Sema::TDK_FailedOverloadResolution: 601 Result.Data = Info.Expression; 602 break; 603 604 case Sema::TDK_MiscellaneousDeductionFailure: 605 break; 606 } 607 608 return Result; 609 } 610 611 void DeductionFailureInfo::Destroy() { 612 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 613 case Sema::TDK_Success: 614 case Sema::TDK_Invalid: 615 case Sema::TDK_InstantiationDepth: 616 case Sema::TDK_Incomplete: 617 case Sema::TDK_TooManyArguments: 618 case Sema::TDK_TooFewArguments: 619 case Sema::TDK_InvalidExplicitArguments: 620 case Sema::TDK_FailedOverloadResolution: 621 break; 622 623 case Sema::TDK_Inconsistent: 624 case Sema::TDK_Underqualified: 625 case Sema::TDK_NonDeducedMismatch: 626 // FIXME: Destroy the data? 627 Data = nullptr; 628 break; 629 630 case Sema::TDK_SubstitutionFailure: 631 // FIXME: Destroy the template argument list? 632 Data = nullptr; 633 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 634 Diag->~PartialDiagnosticAt(); 635 HasDiagnostic = false; 636 } 637 break; 638 639 // Unhandled 640 case Sema::TDK_MiscellaneousDeductionFailure: 641 break; 642 } 643 } 644 645 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 646 if (HasDiagnostic) 647 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 648 return nullptr; 649 } 650 651 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 652 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 653 case Sema::TDK_Success: 654 case Sema::TDK_Invalid: 655 case Sema::TDK_InstantiationDepth: 656 case Sema::TDK_TooManyArguments: 657 case Sema::TDK_TooFewArguments: 658 case Sema::TDK_SubstitutionFailure: 659 case Sema::TDK_NonDeducedMismatch: 660 case Sema::TDK_FailedOverloadResolution: 661 return TemplateParameter(); 662 663 case Sema::TDK_Incomplete: 664 case Sema::TDK_InvalidExplicitArguments: 665 return TemplateParameter::getFromOpaqueValue(Data); 666 667 case Sema::TDK_Inconsistent: 668 case Sema::TDK_Underqualified: 669 return static_cast<DFIParamWithArguments*>(Data)->Param; 670 671 // Unhandled 672 case Sema::TDK_MiscellaneousDeductionFailure: 673 break; 674 } 675 676 return TemplateParameter(); 677 } 678 679 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 680 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 681 case Sema::TDK_Success: 682 case Sema::TDK_Invalid: 683 case Sema::TDK_InstantiationDepth: 684 case Sema::TDK_TooManyArguments: 685 case Sema::TDK_TooFewArguments: 686 case Sema::TDK_Incomplete: 687 case Sema::TDK_InvalidExplicitArguments: 688 case Sema::TDK_Inconsistent: 689 case Sema::TDK_Underqualified: 690 case Sema::TDK_NonDeducedMismatch: 691 case Sema::TDK_FailedOverloadResolution: 692 return nullptr; 693 694 case Sema::TDK_SubstitutionFailure: 695 return static_cast<TemplateArgumentList*>(Data); 696 697 // Unhandled 698 case Sema::TDK_MiscellaneousDeductionFailure: 699 break; 700 } 701 702 return nullptr; 703 } 704 705 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 706 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 707 case Sema::TDK_Success: 708 case Sema::TDK_Invalid: 709 case Sema::TDK_InstantiationDepth: 710 case Sema::TDK_Incomplete: 711 case Sema::TDK_TooManyArguments: 712 case Sema::TDK_TooFewArguments: 713 case Sema::TDK_InvalidExplicitArguments: 714 case Sema::TDK_SubstitutionFailure: 715 case Sema::TDK_FailedOverloadResolution: 716 return nullptr; 717 718 case Sema::TDK_Inconsistent: 719 case Sema::TDK_Underqualified: 720 case Sema::TDK_NonDeducedMismatch: 721 return &static_cast<DFIArguments*>(Data)->FirstArg; 722 723 // Unhandled 724 case Sema::TDK_MiscellaneousDeductionFailure: 725 break; 726 } 727 728 return nullptr; 729 } 730 731 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 733 case Sema::TDK_Success: 734 case Sema::TDK_Invalid: 735 case Sema::TDK_InstantiationDepth: 736 case Sema::TDK_Incomplete: 737 case Sema::TDK_TooManyArguments: 738 case Sema::TDK_TooFewArguments: 739 case Sema::TDK_InvalidExplicitArguments: 740 case Sema::TDK_SubstitutionFailure: 741 case Sema::TDK_FailedOverloadResolution: 742 return nullptr; 743 744 case Sema::TDK_Inconsistent: 745 case Sema::TDK_Underqualified: 746 case Sema::TDK_NonDeducedMismatch: 747 return &static_cast<DFIArguments*>(Data)->SecondArg; 748 749 // Unhandled 750 case Sema::TDK_MiscellaneousDeductionFailure: 751 break; 752 } 753 754 return nullptr; 755 } 756 757 Expr *DeductionFailureInfo::getExpr() { 758 if (static_cast<Sema::TemplateDeductionResult>(Result) == 759 Sema::TDK_FailedOverloadResolution) 760 return static_cast<Expr*>(Data); 761 762 return nullptr; 763 } 764 765 void OverloadCandidateSet::destroyCandidates() { 766 for (iterator i = begin(), e = end(); i != e; ++i) { 767 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 768 i->Conversions[ii].~ImplicitConversionSequence(); 769 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 770 i->DeductionFailure.Destroy(); 771 } 772 } 773 774 void OverloadCandidateSet::clear() { 775 destroyCandidates(); 776 NumInlineSequences = 0; 777 Candidates.clear(); 778 Functions.clear(); 779 } 780 781 namespace { 782 class UnbridgedCastsSet { 783 struct Entry { 784 Expr **Addr; 785 Expr *Saved; 786 }; 787 SmallVector<Entry, 2> Entries; 788 789 public: 790 void save(Sema &S, Expr *&E) { 791 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 792 Entry entry = { &E, E }; 793 Entries.push_back(entry); 794 E = S.stripARCUnbridgedCast(E); 795 } 796 797 void restore() { 798 for (SmallVectorImpl<Entry>::iterator 799 i = Entries.begin(), e = Entries.end(); i != e; ++i) 800 *i->Addr = i->Saved; 801 } 802 }; 803 } 804 805 /// checkPlaceholderForOverload - Do any interesting placeholder-like 806 /// preprocessing on the given expression. 807 /// 808 /// \param unbridgedCasts a collection to which to add unbridged casts; 809 /// without this, they will be immediately diagnosed as errors 810 /// 811 /// Return true on unrecoverable error. 812 static bool 813 checkPlaceholderForOverload(Sema &S, Expr *&E, 814 UnbridgedCastsSet *unbridgedCasts = nullptr) { 815 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 816 // We can't handle overloaded expressions here because overload 817 // resolution might reasonably tweak them. 818 if (placeholder->getKind() == BuiltinType::Overload) return false; 819 820 // If the context potentially accepts unbridged ARC casts, strip 821 // the unbridged cast and add it to the collection for later restoration. 822 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 823 unbridgedCasts) { 824 unbridgedCasts->save(S, E); 825 return false; 826 } 827 828 // Go ahead and check everything else. 829 ExprResult result = S.CheckPlaceholderExpr(E); 830 if (result.isInvalid()) 831 return true; 832 833 E = result.get(); 834 return false; 835 } 836 837 // Nothing to do. 838 return false; 839 } 840 841 /// checkArgPlaceholdersForOverload - Check a set of call operands for 842 /// placeholders. 843 static bool checkArgPlaceholdersForOverload(Sema &S, 844 MultiExprArg Args, 845 UnbridgedCastsSet &unbridged) { 846 for (unsigned i = 0, e = Args.size(); i != e; ++i) 847 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 848 return true; 849 850 return false; 851 } 852 853 // IsOverload - Determine whether the given New declaration is an 854 // overload of the declarations in Old. This routine returns false if 855 // New and Old cannot be overloaded, e.g., if New has the same 856 // signature as some function in Old (C++ 1.3.10) or if the Old 857 // declarations aren't functions (or function templates) at all. When 858 // it does return false, MatchedDecl will point to the decl that New 859 // cannot be overloaded with. This decl may be a UsingShadowDecl on 860 // top of the underlying declaration. 861 // 862 // Example: Given the following input: 863 // 864 // void f(int, float); // #1 865 // void f(int, int); // #2 866 // int f(int, int); // #3 867 // 868 // When we process #1, there is no previous declaration of "f", 869 // so IsOverload will not be used. 870 // 871 // When we process #2, Old contains only the FunctionDecl for #1. By 872 // comparing the parameter types, we see that #1 and #2 are overloaded 873 // (since they have different signatures), so this routine returns 874 // false; MatchedDecl is unchanged. 875 // 876 // When we process #3, Old is an overload set containing #1 and #2. We 877 // compare the signatures of #3 to #1 (they're overloaded, so we do 878 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 879 // identical (return types of functions are not part of the 880 // signature), IsOverload returns false and MatchedDecl will be set to 881 // point to the FunctionDecl for #2. 882 // 883 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 884 // into a class by a using declaration. The rules for whether to hide 885 // shadow declarations ignore some properties which otherwise figure 886 // into a function template's signature. 887 Sema::OverloadKind 888 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 889 NamedDecl *&Match, bool NewIsUsingDecl) { 890 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 891 I != E; ++I) { 892 NamedDecl *OldD = *I; 893 894 bool OldIsUsingDecl = false; 895 if (isa<UsingShadowDecl>(OldD)) { 896 OldIsUsingDecl = true; 897 898 // We can always introduce two using declarations into the same 899 // context, even if they have identical signatures. 900 if (NewIsUsingDecl) continue; 901 902 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 903 } 904 905 // A using-declaration does not conflict with another declaration 906 // if one of them is hidden. 907 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 908 continue; 909 910 // If either declaration was introduced by a using declaration, 911 // we'll need to use slightly different rules for matching. 912 // Essentially, these rules are the normal rules, except that 913 // function templates hide function templates with different 914 // return types or template parameter lists. 915 bool UseMemberUsingDeclRules = 916 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 917 !New->getFriendObjectKind(); 918 919 if (FunctionDecl *OldF = OldD->getAsFunction()) { 920 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 921 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 922 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 923 continue; 924 } 925 926 if (!isa<FunctionTemplateDecl>(OldD) && 927 !shouldLinkPossiblyHiddenDecl(*I, New)) 928 continue; 929 930 Match = *I; 931 return Ovl_Match; 932 } 933 } else if (isa<UsingDecl>(OldD)) { 934 // We can overload with these, which can show up when doing 935 // redeclaration checks for UsingDecls. 936 assert(Old.getLookupKind() == LookupUsingDeclName); 937 } else if (isa<TagDecl>(OldD)) { 938 // We can always overload with tags by hiding them. 939 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 940 // Optimistically assume that an unresolved using decl will 941 // overload; if it doesn't, we'll have to diagnose during 942 // template instantiation. 943 } else { 944 // (C++ 13p1): 945 // Only function declarations can be overloaded; object and type 946 // declarations cannot be overloaded. 947 Match = *I; 948 return Ovl_NonFunction; 949 } 950 } 951 952 return Ovl_Overload; 953 } 954 955 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 956 bool UseUsingDeclRules) { 957 // C++ [basic.start.main]p2: This function shall not be overloaded. 958 if (New->isMain()) 959 return false; 960 961 // MSVCRT user defined entry points cannot be overloaded. 962 if (New->isMSVCRTEntryPoint()) 963 return false; 964 965 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 966 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 967 968 // C++ [temp.fct]p2: 969 // A function template can be overloaded with other function templates 970 // and with normal (non-template) functions. 971 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 972 return true; 973 974 // Is the function New an overload of the function Old? 975 QualType OldQType = Context.getCanonicalType(Old->getType()); 976 QualType NewQType = Context.getCanonicalType(New->getType()); 977 978 // Compare the signatures (C++ 1.3.10) of the two functions to 979 // determine whether they are overloads. If we find any mismatch 980 // in the signature, they are overloads. 981 982 // If either of these functions is a K&R-style function (no 983 // prototype), then we consider them to have matching signatures. 984 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 985 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 986 return false; 987 988 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 989 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 990 991 // The signature of a function includes the types of its 992 // parameters (C++ 1.3.10), which includes the presence or absence 993 // of the ellipsis; see C++ DR 357). 994 if (OldQType != NewQType && 995 (OldType->getNumParams() != NewType->getNumParams() || 996 OldType->isVariadic() != NewType->isVariadic() || 997 !FunctionParamTypesAreEqual(OldType, NewType))) 998 return true; 999 1000 // C++ [temp.over.link]p4: 1001 // The signature of a function template consists of its function 1002 // signature, its return type and its template parameter list. The names 1003 // of the template parameters are significant only for establishing the 1004 // relationship between the template parameters and the rest of the 1005 // signature. 1006 // 1007 // We check the return type and template parameter lists for function 1008 // templates first; the remaining checks follow. 1009 // 1010 // However, we don't consider either of these when deciding whether 1011 // a member introduced by a shadow declaration is hidden. 1012 if (!UseUsingDeclRules && NewTemplate && 1013 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1014 OldTemplate->getTemplateParameters(), 1015 false, TPL_TemplateMatch) || 1016 OldType->getReturnType() != NewType->getReturnType())) 1017 return true; 1018 1019 // If the function is a class member, its signature includes the 1020 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1021 // 1022 // As part of this, also check whether one of the member functions 1023 // is static, in which case they are not overloads (C++ 1024 // 13.1p2). While not part of the definition of the signature, 1025 // this check is important to determine whether these functions 1026 // can be overloaded. 1027 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1028 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1029 if (OldMethod && NewMethod && 1030 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1031 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1032 if (!UseUsingDeclRules && 1033 (OldMethod->getRefQualifier() == RQ_None || 1034 NewMethod->getRefQualifier() == RQ_None)) { 1035 // C++0x [over.load]p2: 1036 // - Member function declarations with the same name and the same 1037 // parameter-type-list as well as member function template 1038 // declarations with the same name, the same parameter-type-list, and 1039 // the same template parameter lists cannot be overloaded if any of 1040 // them, but not all, have a ref-qualifier (8.3.5). 1041 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1042 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1043 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1044 } 1045 return true; 1046 } 1047 1048 // We may not have applied the implicit const for a constexpr member 1049 // function yet (because we haven't yet resolved whether this is a static 1050 // or non-static member function). Add it now, on the assumption that this 1051 // is a redeclaration of OldMethod. 1052 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1053 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1054 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1055 !isa<CXXConstructorDecl>(NewMethod)) 1056 NewQuals |= Qualifiers::Const; 1057 1058 // We do not allow overloading based off of '__restrict'. 1059 OldQuals &= ~Qualifiers::Restrict; 1060 NewQuals &= ~Qualifiers::Restrict; 1061 if (OldQuals != NewQuals) 1062 return true; 1063 } 1064 1065 // enable_if attributes are an order-sensitive part of the signature. 1066 for (specific_attr_iterator<EnableIfAttr> 1067 NewI = New->specific_attr_begin<EnableIfAttr>(), 1068 NewE = New->specific_attr_end<EnableIfAttr>(), 1069 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1070 OldE = Old->specific_attr_end<EnableIfAttr>(); 1071 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1072 if (NewI == NewE || OldI == OldE) 1073 return true; 1074 llvm::FoldingSetNodeID NewID, OldID; 1075 NewI->getCond()->Profile(NewID, Context, true); 1076 OldI->getCond()->Profile(OldID, Context, true); 1077 if (NewID != OldID) 1078 return true; 1079 } 1080 1081 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) { 1082 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1083 OldTarget = IdentifyCUDATarget(Old); 1084 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global) 1085 return false; 1086 1087 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1088 1089 // Don't allow mixing of HD with other kinds. This guarantees that 1090 // we have only one viable function with this signature on any 1091 // side of CUDA compilation . 1092 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice)) 1093 return false; 1094 1095 // Allow overloading of functions with same signature, but 1096 // different CUDA target attributes. 1097 return NewTarget != OldTarget; 1098 } 1099 1100 // The signatures match; this is not an overload. 1101 return false; 1102 } 1103 1104 /// \brief Checks availability of the function depending on the current 1105 /// function context. Inside an unavailable function, unavailability is ignored. 1106 /// 1107 /// \returns true if \arg FD is unavailable and current context is inside 1108 /// an available function, false otherwise. 1109 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1110 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1111 } 1112 1113 /// \brief Tries a user-defined conversion from From to ToType. 1114 /// 1115 /// Produces an implicit conversion sequence for when a standard conversion 1116 /// is not an option. See TryImplicitConversion for more information. 1117 static ImplicitConversionSequence 1118 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1119 bool SuppressUserConversions, 1120 bool AllowExplicit, 1121 bool InOverloadResolution, 1122 bool CStyle, 1123 bool AllowObjCWritebackConversion, 1124 bool AllowObjCConversionOnExplicit) { 1125 ImplicitConversionSequence ICS; 1126 1127 if (SuppressUserConversions) { 1128 // We're not in the case above, so there is no conversion that 1129 // we can perform. 1130 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1131 return ICS; 1132 } 1133 1134 // Attempt user-defined conversion. 1135 OverloadCandidateSet Conversions(From->getExprLoc(), 1136 OverloadCandidateSet::CSK_Normal); 1137 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1138 Conversions, AllowExplicit, 1139 AllowObjCConversionOnExplicit)) { 1140 case OR_Success: 1141 case OR_Deleted: 1142 ICS.setUserDefined(); 1143 ICS.UserDefined.Before.setAsIdentityConversion(); 1144 // C++ [over.ics.user]p4: 1145 // A conversion of an expression of class type to the same class 1146 // type is given Exact Match rank, and a conversion of an 1147 // expression of class type to a base class of that type is 1148 // given Conversion rank, in spite of the fact that a copy 1149 // constructor (i.e., a user-defined conversion function) is 1150 // called for those cases. 1151 if (CXXConstructorDecl *Constructor 1152 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1153 QualType FromCanon 1154 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1155 QualType ToCanon 1156 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1157 if (Constructor->isCopyConstructor() && 1158 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1159 // Turn this into a "standard" conversion sequence, so that it 1160 // gets ranked with standard conversion sequences. 1161 ICS.setStandard(); 1162 ICS.Standard.setAsIdentityConversion(); 1163 ICS.Standard.setFromType(From->getType()); 1164 ICS.Standard.setAllToTypes(ToType); 1165 ICS.Standard.CopyConstructor = Constructor; 1166 if (ToCanon != FromCanon) 1167 ICS.Standard.Second = ICK_Derived_To_Base; 1168 } 1169 } 1170 break; 1171 1172 case OR_Ambiguous: 1173 ICS.setAmbiguous(); 1174 ICS.Ambiguous.setFromType(From->getType()); 1175 ICS.Ambiguous.setToType(ToType); 1176 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1177 Cand != Conversions.end(); ++Cand) 1178 if (Cand->Viable) 1179 ICS.Ambiguous.addConversion(Cand->Function); 1180 break; 1181 1182 // Fall through. 1183 case OR_No_Viable_Function: 1184 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1185 break; 1186 } 1187 1188 return ICS; 1189 } 1190 1191 /// TryImplicitConversion - Attempt to perform an implicit conversion 1192 /// from the given expression (Expr) to the given type (ToType). This 1193 /// function returns an implicit conversion sequence that can be used 1194 /// to perform the initialization. Given 1195 /// 1196 /// void f(float f); 1197 /// void g(int i) { f(i); } 1198 /// 1199 /// this routine would produce an implicit conversion sequence to 1200 /// describe the initialization of f from i, which will be a standard 1201 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1202 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1203 // 1204 /// Note that this routine only determines how the conversion can be 1205 /// performed; it does not actually perform the conversion. As such, 1206 /// it will not produce any diagnostics if no conversion is available, 1207 /// but will instead return an implicit conversion sequence of kind 1208 /// "BadConversion". 1209 /// 1210 /// If @p SuppressUserConversions, then user-defined conversions are 1211 /// not permitted. 1212 /// If @p AllowExplicit, then explicit user-defined conversions are 1213 /// permitted. 1214 /// 1215 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1216 /// writeback conversion, which allows __autoreleasing id* parameters to 1217 /// be initialized with __strong id* or __weak id* arguments. 1218 static ImplicitConversionSequence 1219 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1220 bool SuppressUserConversions, 1221 bool AllowExplicit, 1222 bool InOverloadResolution, 1223 bool CStyle, 1224 bool AllowObjCWritebackConversion, 1225 bool AllowObjCConversionOnExplicit) { 1226 ImplicitConversionSequence ICS; 1227 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1228 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1229 ICS.setStandard(); 1230 return ICS; 1231 } 1232 1233 if (!S.getLangOpts().CPlusPlus) { 1234 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1235 return ICS; 1236 } 1237 1238 // C++ [over.ics.user]p4: 1239 // A conversion of an expression of class type to the same class 1240 // type is given Exact Match rank, and a conversion of an 1241 // expression of class type to a base class of that type is 1242 // given Conversion rank, in spite of the fact that a copy/move 1243 // constructor (i.e., a user-defined conversion function) is 1244 // called for those cases. 1245 QualType FromType = From->getType(); 1246 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1247 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1248 S.IsDerivedFrom(FromType, ToType))) { 1249 ICS.setStandard(); 1250 ICS.Standard.setAsIdentityConversion(); 1251 ICS.Standard.setFromType(FromType); 1252 ICS.Standard.setAllToTypes(ToType); 1253 1254 // We don't actually check at this point whether there is a valid 1255 // copy/move constructor, since overloading just assumes that it 1256 // exists. When we actually perform initialization, we'll find the 1257 // appropriate constructor to copy the returned object, if needed. 1258 ICS.Standard.CopyConstructor = nullptr; 1259 1260 // Determine whether this is considered a derived-to-base conversion. 1261 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1262 ICS.Standard.Second = ICK_Derived_To_Base; 1263 1264 return ICS; 1265 } 1266 1267 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1268 AllowExplicit, InOverloadResolution, CStyle, 1269 AllowObjCWritebackConversion, 1270 AllowObjCConversionOnExplicit); 1271 } 1272 1273 ImplicitConversionSequence 1274 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1275 bool SuppressUserConversions, 1276 bool AllowExplicit, 1277 bool InOverloadResolution, 1278 bool CStyle, 1279 bool AllowObjCWritebackConversion) { 1280 return ::TryImplicitConversion(*this, From, ToType, 1281 SuppressUserConversions, AllowExplicit, 1282 InOverloadResolution, CStyle, 1283 AllowObjCWritebackConversion, 1284 /*AllowObjCConversionOnExplicit=*/false); 1285 } 1286 1287 /// PerformImplicitConversion - Perform an implicit conversion of the 1288 /// expression From to the type ToType. Returns the 1289 /// converted expression. Flavor is the kind of conversion we're 1290 /// performing, used in the error message. If @p AllowExplicit, 1291 /// explicit user-defined conversions are permitted. 1292 ExprResult 1293 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1294 AssignmentAction Action, bool AllowExplicit) { 1295 ImplicitConversionSequence ICS; 1296 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1297 } 1298 1299 ExprResult 1300 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1301 AssignmentAction Action, bool AllowExplicit, 1302 ImplicitConversionSequence& ICS) { 1303 if (checkPlaceholderForOverload(*this, From)) 1304 return ExprError(); 1305 1306 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1307 bool AllowObjCWritebackConversion 1308 = getLangOpts().ObjCAutoRefCount && 1309 (Action == AA_Passing || Action == AA_Sending); 1310 if (getLangOpts().ObjC1) 1311 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1312 ToType, From->getType(), From); 1313 ICS = ::TryImplicitConversion(*this, From, ToType, 1314 /*SuppressUserConversions=*/false, 1315 AllowExplicit, 1316 /*InOverloadResolution=*/false, 1317 /*CStyle=*/false, 1318 AllowObjCWritebackConversion, 1319 /*AllowObjCConversionOnExplicit=*/false); 1320 return PerformImplicitConversion(From, ToType, ICS, Action); 1321 } 1322 1323 /// \brief Determine whether the conversion from FromType to ToType is a valid 1324 /// conversion that strips "noreturn" off the nested function type. 1325 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1326 QualType &ResultTy) { 1327 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1328 return false; 1329 1330 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1331 // where F adds one of the following at most once: 1332 // - a pointer 1333 // - a member pointer 1334 // - a block pointer 1335 CanQualType CanTo = Context.getCanonicalType(ToType); 1336 CanQualType CanFrom = Context.getCanonicalType(FromType); 1337 Type::TypeClass TyClass = CanTo->getTypeClass(); 1338 if (TyClass != CanFrom->getTypeClass()) return false; 1339 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1340 if (TyClass == Type::Pointer) { 1341 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1342 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1343 } else if (TyClass == Type::BlockPointer) { 1344 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1345 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1346 } else if (TyClass == Type::MemberPointer) { 1347 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1348 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1349 } else { 1350 return false; 1351 } 1352 1353 TyClass = CanTo->getTypeClass(); 1354 if (TyClass != CanFrom->getTypeClass()) return false; 1355 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1356 return false; 1357 } 1358 1359 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1360 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1361 if (!EInfo.getNoReturn()) return false; 1362 1363 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1364 assert(QualType(FromFn, 0).isCanonical()); 1365 if (QualType(FromFn, 0) != CanTo) return false; 1366 1367 ResultTy = ToType; 1368 return true; 1369 } 1370 1371 /// \brief Determine whether the conversion from FromType to ToType is a valid 1372 /// vector conversion. 1373 /// 1374 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1375 /// conversion. 1376 static bool IsVectorConversion(Sema &S, QualType FromType, 1377 QualType ToType, ImplicitConversionKind &ICK) { 1378 // We need at least one of these types to be a vector type to have a vector 1379 // conversion. 1380 if (!ToType->isVectorType() && !FromType->isVectorType()) 1381 return false; 1382 1383 // Identical types require no conversions. 1384 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1385 return false; 1386 1387 // There are no conversions between extended vector types, only identity. 1388 if (ToType->isExtVectorType()) { 1389 // There are no conversions between extended vector types other than the 1390 // identity conversion. 1391 if (FromType->isExtVectorType()) 1392 return false; 1393 1394 // Vector splat from any arithmetic type to a vector. 1395 if (FromType->isArithmeticType()) { 1396 ICK = ICK_Vector_Splat; 1397 return true; 1398 } 1399 } 1400 1401 // We can perform the conversion between vector types in the following cases: 1402 // 1)vector types are equivalent AltiVec and GCC vector types 1403 // 2)lax vector conversions are permitted and the vector types are of the 1404 // same size 1405 if (ToType->isVectorType() && FromType->isVectorType()) { 1406 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1407 S.isLaxVectorConversion(FromType, ToType)) { 1408 ICK = ICK_Vector_Conversion; 1409 return true; 1410 } 1411 } 1412 1413 return false; 1414 } 1415 1416 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1417 bool InOverloadResolution, 1418 StandardConversionSequence &SCS, 1419 bool CStyle); 1420 1421 /// IsStandardConversion - Determines whether there is a standard 1422 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1423 /// expression From to the type ToType. Standard conversion sequences 1424 /// only consider non-class types; for conversions that involve class 1425 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1426 /// contain the standard conversion sequence required to perform this 1427 /// conversion and this routine will return true. Otherwise, this 1428 /// routine will return false and the value of SCS is unspecified. 1429 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1430 bool InOverloadResolution, 1431 StandardConversionSequence &SCS, 1432 bool CStyle, 1433 bool AllowObjCWritebackConversion) { 1434 QualType FromType = From->getType(); 1435 1436 // Standard conversions (C++ [conv]) 1437 SCS.setAsIdentityConversion(); 1438 SCS.IncompatibleObjC = false; 1439 SCS.setFromType(FromType); 1440 SCS.CopyConstructor = nullptr; 1441 1442 // There are no standard conversions for class types in C++, so 1443 // abort early. When overloading in C, however, we do permit them. 1444 if (S.getLangOpts().CPlusPlus && 1445 (FromType->isRecordType() || ToType->isRecordType())) 1446 return false; 1447 1448 // The first conversion can be an lvalue-to-rvalue conversion, 1449 // array-to-pointer conversion, or function-to-pointer conversion 1450 // (C++ 4p1). 1451 1452 if (FromType == S.Context.OverloadTy) { 1453 DeclAccessPair AccessPair; 1454 if (FunctionDecl *Fn 1455 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1456 AccessPair)) { 1457 // We were able to resolve the address of the overloaded function, 1458 // so we can convert to the type of that function. 1459 FromType = Fn->getType(); 1460 SCS.setFromType(FromType); 1461 1462 // we can sometimes resolve &foo<int> regardless of ToType, so check 1463 // if the type matches (identity) or we are converting to bool 1464 if (!S.Context.hasSameUnqualifiedType( 1465 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1466 QualType resultTy; 1467 // if the function type matches except for [[noreturn]], it's ok 1468 if (!S.IsNoReturnConversion(FromType, 1469 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1470 // otherwise, only a boolean conversion is standard 1471 if (!ToType->isBooleanType()) 1472 return false; 1473 } 1474 1475 // Check if the "from" expression is taking the address of an overloaded 1476 // function and recompute the FromType accordingly. Take advantage of the 1477 // fact that non-static member functions *must* have such an address-of 1478 // expression. 1479 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1480 if (Method && !Method->isStatic()) { 1481 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1482 "Non-unary operator on non-static member address"); 1483 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1484 == UO_AddrOf && 1485 "Non-address-of operator on non-static member address"); 1486 const Type *ClassType 1487 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1488 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1489 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1490 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1491 UO_AddrOf && 1492 "Non-address-of operator for overloaded function expression"); 1493 FromType = S.Context.getPointerType(FromType); 1494 } 1495 1496 // Check that we've computed the proper type after overload resolution. 1497 assert(S.Context.hasSameType( 1498 FromType, 1499 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1500 } else { 1501 return false; 1502 } 1503 } 1504 // Lvalue-to-rvalue conversion (C++11 4.1): 1505 // A glvalue (3.10) of a non-function, non-array type T can 1506 // be converted to a prvalue. 1507 bool argIsLValue = From->isGLValue(); 1508 if (argIsLValue && 1509 !FromType->isFunctionType() && !FromType->isArrayType() && 1510 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1511 SCS.First = ICK_Lvalue_To_Rvalue; 1512 1513 // C11 6.3.2.1p2: 1514 // ... if the lvalue has atomic type, the value has the non-atomic version 1515 // of the type of the lvalue ... 1516 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1517 FromType = Atomic->getValueType(); 1518 1519 // If T is a non-class type, the type of the rvalue is the 1520 // cv-unqualified version of T. Otherwise, the type of the rvalue 1521 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1522 // just strip the qualifiers because they don't matter. 1523 FromType = FromType.getUnqualifiedType(); 1524 } else if (FromType->isArrayType()) { 1525 // Array-to-pointer conversion (C++ 4.2) 1526 SCS.First = ICK_Array_To_Pointer; 1527 1528 // An lvalue or rvalue of type "array of N T" or "array of unknown 1529 // bound of T" can be converted to an rvalue of type "pointer to 1530 // T" (C++ 4.2p1). 1531 FromType = S.Context.getArrayDecayedType(FromType); 1532 1533 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1534 // This conversion is deprecated in C++03 (D.4) 1535 SCS.DeprecatedStringLiteralToCharPtr = true; 1536 1537 // For the purpose of ranking in overload resolution 1538 // (13.3.3.1.1), this conversion is considered an 1539 // array-to-pointer conversion followed by a qualification 1540 // conversion (4.4). (C++ 4.2p2) 1541 SCS.Second = ICK_Identity; 1542 SCS.Third = ICK_Qualification; 1543 SCS.QualificationIncludesObjCLifetime = false; 1544 SCS.setAllToTypes(FromType); 1545 return true; 1546 } 1547 } else if (FromType->isFunctionType() && argIsLValue) { 1548 // Function-to-pointer conversion (C++ 4.3). 1549 SCS.First = ICK_Function_To_Pointer; 1550 1551 // An lvalue of function type T can be converted to an rvalue of 1552 // type "pointer to T." The result is a pointer to the 1553 // function. (C++ 4.3p1). 1554 FromType = S.Context.getPointerType(FromType); 1555 } else { 1556 // We don't require any conversions for the first step. 1557 SCS.First = ICK_Identity; 1558 } 1559 SCS.setToType(0, FromType); 1560 1561 // The second conversion can be an integral promotion, floating 1562 // point promotion, integral conversion, floating point conversion, 1563 // floating-integral conversion, pointer conversion, 1564 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1565 // For overloading in C, this can also be a "compatible-type" 1566 // conversion. 1567 bool IncompatibleObjC = false; 1568 ImplicitConversionKind SecondICK = ICK_Identity; 1569 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1570 // The unqualified versions of the types are the same: there's no 1571 // conversion to do. 1572 SCS.Second = ICK_Identity; 1573 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1574 // Integral promotion (C++ 4.5). 1575 SCS.Second = ICK_Integral_Promotion; 1576 FromType = ToType.getUnqualifiedType(); 1577 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1578 // Floating point promotion (C++ 4.6). 1579 SCS.Second = ICK_Floating_Promotion; 1580 FromType = ToType.getUnqualifiedType(); 1581 } else if (S.IsComplexPromotion(FromType, ToType)) { 1582 // Complex promotion (Clang extension) 1583 SCS.Second = ICK_Complex_Promotion; 1584 FromType = ToType.getUnqualifiedType(); 1585 } else if (ToType->isBooleanType() && 1586 (FromType->isArithmeticType() || 1587 FromType->isAnyPointerType() || 1588 FromType->isBlockPointerType() || 1589 FromType->isMemberPointerType() || 1590 FromType->isNullPtrType())) { 1591 // Boolean conversions (C++ 4.12). 1592 SCS.Second = ICK_Boolean_Conversion; 1593 FromType = S.Context.BoolTy; 1594 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1595 ToType->isIntegralType(S.Context)) { 1596 // Integral conversions (C++ 4.7). 1597 SCS.Second = ICK_Integral_Conversion; 1598 FromType = ToType.getUnqualifiedType(); 1599 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1600 // Complex conversions (C99 6.3.1.6) 1601 SCS.Second = ICK_Complex_Conversion; 1602 FromType = ToType.getUnqualifiedType(); 1603 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1604 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1605 // Complex-real conversions (C99 6.3.1.7) 1606 SCS.Second = ICK_Complex_Real; 1607 FromType = ToType.getUnqualifiedType(); 1608 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1609 // Floating point conversions (C++ 4.8). 1610 SCS.Second = ICK_Floating_Conversion; 1611 FromType = ToType.getUnqualifiedType(); 1612 } else if ((FromType->isRealFloatingType() && 1613 ToType->isIntegralType(S.Context)) || 1614 (FromType->isIntegralOrUnscopedEnumerationType() && 1615 ToType->isRealFloatingType())) { 1616 // Floating-integral conversions (C++ 4.9). 1617 SCS.Second = ICK_Floating_Integral; 1618 FromType = ToType.getUnqualifiedType(); 1619 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1620 SCS.Second = ICK_Block_Pointer_Conversion; 1621 } else if (AllowObjCWritebackConversion && 1622 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1623 SCS.Second = ICK_Writeback_Conversion; 1624 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1625 FromType, IncompatibleObjC)) { 1626 // Pointer conversions (C++ 4.10). 1627 SCS.Second = ICK_Pointer_Conversion; 1628 SCS.IncompatibleObjC = IncompatibleObjC; 1629 FromType = FromType.getUnqualifiedType(); 1630 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1631 InOverloadResolution, FromType)) { 1632 // Pointer to member conversions (4.11). 1633 SCS.Second = ICK_Pointer_Member; 1634 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1635 SCS.Second = SecondICK; 1636 FromType = ToType.getUnqualifiedType(); 1637 } else if (!S.getLangOpts().CPlusPlus && 1638 S.Context.typesAreCompatible(ToType, FromType)) { 1639 // Compatible conversions (Clang extension for C function overloading) 1640 SCS.Second = ICK_Compatible_Conversion; 1641 FromType = ToType.getUnqualifiedType(); 1642 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1643 // Treat a conversion that strips "noreturn" as an identity conversion. 1644 SCS.Second = ICK_NoReturn_Adjustment; 1645 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1646 InOverloadResolution, 1647 SCS, CStyle)) { 1648 SCS.Second = ICK_TransparentUnionConversion; 1649 FromType = ToType; 1650 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1651 CStyle)) { 1652 // tryAtomicConversion has updated the standard conversion sequence 1653 // appropriately. 1654 return true; 1655 } else if (ToType->isEventT() && 1656 From->isIntegerConstantExpr(S.getASTContext()) && 1657 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1658 SCS.Second = ICK_Zero_Event_Conversion; 1659 FromType = ToType; 1660 } else { 1661 // No second conversion required. 1662 SCS.Second = ICK_Identity; 1663 } 1664 SCS.setToType(1, FromType); 1665 1666 QualType CanonFrom; 1667 QualType CanonTo; 1668 // The third conversion can be a qualification conversion (C++ 4p1). 1669 bool ObjCLifetimeConversion; 1670 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1671 ObjCLifetimeConversion)) { 1672 SCS.Third = ICK_Qualification; 1673 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1674 FromType = ToType; 1675 CanonFrom = S.Context.getCanonicalType(FromType); 1676 CanonTo = S.Context.getCanonicalType(ToType); 1677 } else { 1678 // No conversion required 1679 SCS.Third = ICK_Identity; 1680 1681 // C++ [over.best.ics]p6: 1682 // [...] Any difference in top-level cv-qualification is 1683 // subsumed by the initialization itself and does not constitute 1684 // a conversion. [...] 1685 CanonFrom = S.Context.getCanonicalType(FromType); 1686 CanonTo = S.Context.getCanonicalType(ToType); 1687 if (CanonFrom.getLocalUnqualifiedType() 1688 == CanonTo.getLocalUnqualifiedType() && 1689 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1690 FromType = ToType; 1691 CanonFrom = CanonTo; 1692 } 1693 } 1694 SCS.setToType(2, FromType); 1695 1696 if (CanonFrom == CanonTo) 1697 return true; 1698 1699 // If we have not converted the argument type to the parameter type, 1700 // this is a bad conversion sequence, unless we're resolving an overload in C. 1701 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1702 return false; 1703 1704 ExprResult ER = ExprResult{From}; 1705 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER, 1706 /*Diagnose=*/false, 1707 /*DiagnoseCFAudited=*/false, 1708 /*ConvertRHS=*/false); 1709 if (Conv != Sema::Compatible) 1710 return false; 1711 1712 SCS.setAllToTypes(ToType); 1713 // We need to set all three because we want this conversion to rank terribly, 1714 // and we don't know what conversions it may overlap with. 1715 SCS.First = ICK_C_Only_Conversion; 1716 SCS.Second = ICK_C_Only_Conversion; 1717 SCS.Third = ICK_C_Only_Conversion; 1718 return true; 1719 } 1720 1721 static bool 1722 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1723 QualType &ToType, 1724 bool InOverloadResolution, 1725 StandardConversionSequence &SCS, 1726 bool CStyle) { 1727 1728 const RecordType *UT = ToType->getAsUnionType(); 1729 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1730 return false; 1731 // The field to initialize within the transparent union. 1732 RecordDecl *UD = UT->getDecl(); 1733 // It's compatible if the expression matches any of the fields. 1734 for (const auto *it : UD->fields()) { 1735 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1736 CStyle, /*ObjCWritebackConversion=*/false)) { 1737 ToType = it->getType(); 1738 return true; 1739 } 1740 } 1741 return false; 1742 } 1743 1744 /// IsIntegralPromotion - Determines whether the conversion from the 1745 /// expression From (whose potentially-adjusted type is FromType) to 1746 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1747 /// sets PromotedType to the promoted type. 1748 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1749 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1750 // All integers are built-in. 1751 if (!To) { 1752 return false; 1753 } 1754 1755 // An rvalue of type char, signed char, unsigned char, short int, or 1756 // unsigned short int can be converted to an rvalue of type int if 1757 // int can represent all the values of the source type; otherwise, 1758 // the source rvalue can be converted to an rvalue of type unsigned 1759 // int (C++ 4.5p1). 1760 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1761 !FromType->isEnumeralType()) { 1762 if (// We can promote any signed, promotable integer type to an int 1763 (FromType->isSignedIntegerType() || 1764 // We can promote any unsigned integer type whose size is 1765 // less than int to an int. 1766 (!FromType->isSignedIntegerType() && 1767 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1768 return To->getKind() == BuiltinType::Int; 1769 } 1770 1771 return To->getKind() == BuiltinType::UInt; 1772 } 1773 1774 // C++11 [conv.prom]p3: 1775 // A prvalue of an unscoped enumeration type whose underlying type is not 1776 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1777 // following types that can represent all the values of the enumeration 1778 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1779 // unsigned int, long int, unsigned long int, long long int, or unsigned 1780 // long long int. If none of the types in that list can represent all the 1781 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1782 // type can be converted to an rvalue a prvalue of the extended integer type 1783 // with lowest integer conversion rank (4.13) greater than the rank of long 1784 // long in which all the values of the enumeration can be represented. If 1785 // there are two such extended types, the signed one is chosen. 1786 // C++11 [conv.prom]p4: 1787 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1788 // can be converted to a prvalue of its underlying type. Moreover, if 1789 // integral promotion can be applied to its underlying type, a prvalue of an 1790 // unscoped enumeration type whose underlying type is fixed can also be 1791 // converted to a prvalue of the promoted underlying type. 1792 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1793 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1794 // provided for a scoped enumeration. 1795 if (FromEnumType->getDecl()->isScoped()) 1796 return false; 1797 1798 // We can perform an integral promotion to the underlying type of the enum, 1799 // even if that's not the promoted type. Note that the check for promoting 1800 // the underlying type is based on the type alone, and does not consider 1801 // the bitfield-ness of the actual source expression. 1802 if (FromEnumType->getDecl()->isFixed()) { 1803 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1804 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1805 IsIntegralPromotion(nullptr, Underlying, ToType); 1806 } 1807 1808 // We have already pre-calculated the promotion type, so this is trivial. 1809 if (ToType->isIntegerType() && 1810 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1811 return Context.hasSameUnqualifiedType( 1812 ToType, FromEnumType->getDecl()->getPromotionType()); 1813 } 1814 1815 // C++0x [conv.prom]p2: 1816 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1817 // to an rvalue a prvalue of the first of the following types that can 1818 // represent all the values of its underlying type: int, unsigned int, 1819 // long int, unsigned long int, long long int, or unsigned long long int. 1820 // If none of the types in that list can represent all the values of its 1821 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1822 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1823 // type. 1824 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1825 ToType->isIntegerType()) { 1826 // Determine whether the type we're converting from is signed or 1827 // unsigned. 1828 bool FromIsSigned = FromType->isSignedIntegerType(); 1829 uint64_t FromSize = Context.getTypeSize(FromType); 1830 1831 // The types we'll try to promote to, in the appropriate 1832 // order. Try each of these types. 1833 QualType PromoteTypes[6] = { 1834 Context.IntTy, Context.UnsignedIntTy, 1835 Context.LongTy, Context.UnsignedLongTy , 1836 Context.LongLongTy, Context.UnsignedLongLongTy 1837 }; 1838 for (int Idx = 0; Idx < 6; ++Idx) { 1839 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1840 if (FromSize < ToSize || 1841 (FromSize == ToSize && 1842 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1843 // We found the type that we can promote to. If this is the 1844 // type we wanted, we have a promotion. Otherwise, no 1845 // promotion. 1846 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1847 } 1848 } 1849 } 1850 1851 // An rvalue for an integral bit-field (9.6) can be converted to an 1852 // rvalue of type int if int can represent all the values of the 1853 // bit-field; otherwise, it can be converted to unsigned int if 1854 // unsigned int can represent all the values of the bit-field. If 1855 // the bit-field is larger yet, no integral promotion applies to 1856 // it. If the bit-field has an enumerated type, it is treated as any 1857 // other value of that type for promotion purposes (C++ 4.5p3). 1858 // FIXME: We should delay checking of bit-fields until we actually perform the 1859 // conversion. 1860 if (From) { 1861 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1862 llvm::APSInt BitWidth; 1863 if (FromType->isIntegralType(Context) && 1864 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1865 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1866 ToSize = Context.getTypeSize(ToType); 1867 1868 // Are we promoting to an int from a bitfield that fits in an int? 1869 if (BitWidth < ToSize || 1870 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1871 return To->getKind() == BuiltinType::Int; 1872 } 1873 1874 // Are we promoting to an unsigned int from an unsigned bitfield 1875 // that fits into an unsigned int? 1876 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1877 return To->getKind() == BuiltinType::UInt; 1878 } 1879 1880 return false; 1881 } 1882 } 1883 } 1884 1885 // An rvalue of type bool can be converted to an rvalue of type int, 1886 // with false becoming zero and true becoming one (C++ 4.5p4). 1887 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1888 return true; 1889 } 1890 1891 return false; 1892 } 1893 1894 /// IsFloatingPointPromotion - Determines whether the conversion from 1895 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1896 /// returns true and sets PromotedType to the promoted type. 1897 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1898 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1899 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1900 /// An rvalue of type float can be converted to an rvalue of type 1901 /// double. (C++ 4.6p1). 1902 if (FromBuiltin->getKind() == BuiltinType::Float && 1903 ToBuiltin->getKind() == BuiltinType::Double) 1904 return true; 1905 1906 // C99 6.3.1.5p1: 1907 // When a float is promoted to double or long double, or a 1908 // double is promoted to long double [...]. 1909 if (!getLangOpts().CPlusPlus && 1910 (FromBuiltin->getKind() == BuiltinType::Float || 1911 FromBuiltin->getKind() == BuiltinType::Double) && 1912 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1913 return true; 1914 1915 // Half can be promoted to float. 1916 if (!getLangOpts().NativeHalfType && 1917 FromBuiltin->getKind() == BuiltinType::Half && 1918 ToBuiltin->getKind() == BuiltinType::Float) 1919 return true; 1920 } 1921 1922 return false; 1923 } 1924 1925 /// \brief Determine if a conversion is a complex promotion. 1926 /// 1927 /// A complex promotion is defined as a complex -> complex conversion 1928 /// where the conversion between the underlying real types is a 1929 /// floating-point or integral promotion. 1930 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1931 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1932 if (!FromComplex) 1933 return false; 1934 1935 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1936 if (!ToComplex) 1937 return false; 1938 1939 return IsFloatingPointPromotion(FromComplex->getElementType(), 1940 ToComplex->getElementType()) || 1941 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 1942 ToComplex->getElementType()); 1943 } 1944 1945 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1946 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1947 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1948 /// if non-empty, will be a pointer to ToType that may or may not have 1949 /// the right set of qualifiers on its pointee. 1950 /// 1951 static QualType 1952 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1953 QualType ToPointee, QualType ToType, 1954 ASTContext &Context, 1955 bool StripObjCLifetime = false) { 1956 assert((FromPtr->getTypeClass() == Type::Pointer || 1957 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1958 "Invalid similarly-qualified pointer type"); 1959 1960 /// Conversions to 'id' subsume cv-qualifier conversions. 1961 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1962 return ToType.getUnqualifiedType(); 1963 1964 QualType CanonFromPointee 1965 = Context.getCanonicalType(FromPtr->getPointeeType()); 1966 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1967 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1968 1969 if (StripObjCLifetime) 1970 Quals.removeObjCLifetime(); 1971 1972 // Exact qualifier match -> return the pointer type we're converting to. 1973 if (CanonToPointee.getLocalQualifiers() == Quals) { 1974 // ToType is exactly what we need. Return it. 1975 if (!ToType.isNull()) 1976 return ToType.getUnqualifiedType(); 1977 1978 // Build a pointer to ToPointee. It has the right qualifiers 1979 // already. 1980 if (isa<ObjCObjectPointerType>(ToType)) 1981 return Context.getObjCObjectPointerType(ToPointee); 1982 return Context.getPointerType(ToPointee); 1983 } 1984 1985 // Just build a canonical type that has the right qualifiers. 1986 QualType QualifiedCanonToPointee 1987 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1988 1989 if (isa<ObjCObjectPointerType>(ToType)) 1990 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1991 return Context.getPointerType(QualifiedCanonToPointee); 1992 } 1993 1994 static bool isNullPointerConstantForConversion(Expr *Expr, 1995 bool InOverloadResolution, 1996 ASTContext &Context) { 1997 // Handle value-dependent integral null pointer constants correctly. 1998 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1999 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2000 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2001 return !InOverloadResolution; 2002 2003 return Expr->isNullPointerConstant(Context, 2004 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2005 : Expr::NPC_ValueDependentIsNull); 2006 } 2007 2008 /// IsPointerConversion - Determines whether the conversion of the 2009 /// expression From, which has the (possibly adjusted) type FromType, 2010 /// can be converted to the type ToType via a pointer conversion (C++ 2011 /// 4.10). If so, returns true and places the converted type (that 2012 /// might differ from ToType in its cv-qualifiers at some level) into 2013 /// ConvertedType. 2014 /// 2015 /// This routine also supports conversions to and from block pointers 2016 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2017 /// pointers to interfaces. FIXME: Once we've determined the 2018 /// appropriate overloading rules for Objective-C, we may want to 2019 /// split the Objective-C checks into a different routine; however, 2020 /// GCC seems to consider all of these conversions to be pointer 2021 /// conversions, so for now they live here. IncompatibleObjC will be 2022 /// set if the conversion is an allowed Objective-C conversion that 2023 /// should result in a warning. 2024 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2025 bool InOverloadResolution, 2026 QualType& ConvertedType, 2027 bool &IncompatibleObjC) { 2028 IncompatibleObjC = false; 2029 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2030 IncompatibleObjC)) 2031 return true; 2032 2033 // Conversion from a null pointer constant to any Objective-C pointer type. 2034 if (ToType->isObjCObjectPointerType() && 2035 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2036 ConvertedType = ToType; 2037 return true; 2038 } 2039 2040 // Blocks: Block pointers can be converted to void*. 2041 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2042 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2043 ConvertedType = ToType; 2044 return true; 2045 } 2046 // Blocks: A null pointer constant can be converted to a block 2047 // pointer type. 2048 if (ToType->isBlockPointerType() && 2049 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2050 ConvertedType = ToType; 2051 return true; 2052 } 2053 2054 // If the left-hand-side is nullptr_t, the right side can be a null 2055 // pointer constant. 2056 if (ToType->isNullPtrType() && 2057 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2058 ConvertedType = ToType; 2059 return true; 2060 } 2061 2062 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2063 if (!ToTypePtr) 2064 return false; 2065 2066 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2067 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2068 ConvertedType = ToType; 2069 return true; 2070 } 2071 2072 // Beyond this point, both types need to be pointers 2073 // , including objective-c pointers. 2074 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2075 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2076 !getLangOpts().ObjCAutoRefCount) { 2077 ConvertedType = BuildSimilarlyQualifiedPointerType( 2078 FromType->getAs<ObjCObjectPointerType>(), 2079 ToPointeeType, 2080 ToType, Context); 2081 return true; 2082 } 2083 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2084 if (!FromTypePtr) 2085 return false; 2086 2087 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2088 2089 // If the unqualified pointee types are the same, this can't be a 2090 // pointer conversion, so don't do all of the work below. 2091 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2092 return false; 2093 2094 // An rvalue of type "pointer to cv T," where T is an object type, 2095 // can be converted to an rvalue of type "pointer to cv void" (C++ 2096 // 4.10p2). 2097 if (FromPointeeType->isIncompleteOrObjectType() && 2098 ToPointeeType->isVoidType()) { 2099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2100 ToPointeeType, 2101 ToType, Context, 2102 /*StripObjCLifetime=*/true); 2103 return true; 2104 } 2105 2106 // MSVC allows implicit function to void* type conversion. 2107 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2108 ToPointeeType->isVoidType()) { 2109 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2110 ToPointeeType, 2111 ToType, Context); 2112 return true; 2113 } 2114 2115 // When we're overloading in C, we allow a special kind of pointer 2116 // conversion for compatible-but-not-identical pointee types. 2117 if (!getLangOpts().CPlusPlus && 2118 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2119 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2120 ToPointeeType, 2121 ToType, Context); 2122 return true; 2123 } 2124 2125 // C++ [conv.ptr]p3: 2126 // 2127 // An rvalue of type "pointer to cv D," where D is a class type, 2128 // can be converted to an rvalue of type "pointer to cv B," where 2129 // B is a base class (clause 10) of D. If B is an inaccessible 2130 // (clause 11) or ambiguous (10.2) base class of D, a program that 2131 // necessitates this conversion is ill-formed. The result of the 2132 // conversion is a pointer to the base class sub-object of the 2133 // derived class object. The null pointer value is converted to 2134 // the null pointer value of the destination type. 2135 // 2136 // Note that we do not check for ambiguity or inaccessibility 2137 // here. That is handled by CheckPointerConversion. 2138 if (getLangOpts().CPlusPlus && 2139 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2140 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2141 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2142 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2143 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2144 ToPointeeType, 2145 ToType, Context); 2146 return true; 2147 } 2148 2149 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2150 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2151 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2152 ToPointeeType, 2153 ToType, Context); 2154 return true; 2155 } 2156 2157 return false; 2158 } 2159 2160 /// \brief Adopt the given qualifiers for the given type. 2161 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2162 Qualifiers TQs = T.getQualifiers(); 2163 2164 // Check whether qualifiers already match. 2165 if (TQs == Qs) 2166 return T; 2167 2168 if (Qs.compatiblyIncludes(TQs)) 2169 return Context.getQualifiedType(T, Qs); 2170 2171 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2172 } 2173 2174 /// isObjCPointerConversion - Determines whether this is an 2175 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2176 /// with the same arguments and return values. 2177 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2178 QualType& ConvertedType, 2179 bool &IncompatibleObjC) { 2180 if (!getLangOpts().ObjC1) 2181 return false; 2182 2183 // The set of qualifiers on the type we're converting from. 2184 Qualifiers FromQualifiers = FromType.getQualifiers(); 2185 2186 // First, we handle all conversions on ObjC object pointer types. 2187 const ObjCObjectPointerType* ToObjCPtr = 2188 ToType->getAs<ObjCObjectPointerType>(); 2189 const ObjCObjectPointerType *FromObjCPtr = 2190 FromType->getAs<ObjCObjectPointerType>(); 2191 2192 if (ToObjCPtr && FromObjCPtr) { 2193 // If the pointee types are the same (ignoring qualifications), 2194 // then this is not a pointer conversion. 2195 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2196 FromObjCPtr->getPointeeType())) 2197 return false; 2198 2199 // Conversion between Objective-C pointers. 2200 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2201 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2202 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2203 if (getLangOpts().CPlusPlus && LHS && RHS && 2204 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2205 FromObjCPtr->getPointeeType())) 2206 return false; 2207 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2208 ToObjCPtr->getPointeeType(), 2209 ToType, Context); 2210 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2211 return true; 2212 } 2213 2214 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2215 // Okay: this is some kind of implicit downcast of Objective-C 2216 // interfaces, which is permitted. However, we're going to 2217 // complain about it. 2218 IncompatibleObjC = true; 2219 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2220 ToObjCPtr->getPointeeType(), 2221 ToType, Context); 2222 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2223 return true; 2224 } 2225 } 2226 // Beyond this point, both types need to be C pointers or block pointers. 2227 QualType ToPointeeType; 2228 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2229 ToPointeeType = ToCPtr->getPointeeType(); 2230 else if (const BlockPointerType *ToBlockPtr = 2231 ToType->getAs<BlockPointerType>()) { 2232 // Objective C++: We're able to convert from a pointer to any object 2233 // to a block pointer type. 2234 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2235 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2236 return true; 2237 } 2238 ToPointeeType = ToBlockPtr->getPointeeType(); 2239 } 2240 else if (FromType->getAs<BlockPointerType>() && 2241 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2242 // Objective C++: We're able to convert from a block pointer type to a 2243 // pointer to any object. 2244 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2245 return true; 2246 } 2247 else 2248 return false; 2249 2250 QualType FromPointeeType; 2251 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2252 FromPointeeType = FromCPtr->getPointeeType(); 2253 else if (const BlockPointerType *FromBlockPtr = 2254 FromType->getAs<BlockPointerType>()) 2255 FromPointeeType = FromBlockPtr->getPointeeType(); 2256 else 2257 return false; 2258 2259 // If we have pointers to pointers, recursively check whether this 2260 // is an Objective-C conversion. 2261 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2262 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2263 IncompatibleObjC)) { 2264 // We always complain about this conversion. 2265 IncompatibleObjC = true; 2266 ConvertedType = Context.getPointerType(ConvertedType); 2267 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2268 return true; 2269 } 2270 // Allow conversion of pointee being objective-c pointer to another one; 2271 // as in I* to id. 2272 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2273 ToPointeeType->getAs<ObjCObjectPointerType>() && 2274 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2275 IncompatibleObjC)) { 2276 2277 ConvertedType = Context.getPointerType(ConvertedType); 2278 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2279 return true; 2280 } 2281 2282 // If we have pointers to functions or blocks, check whether the only 2283 // differences in the argument and result types are in Objective-C 2284 // pointer conversions. If so, we permit the conversion (but 2285 // complain about it). 2286 const FunctionProtoType *FromFunctionType 2287 = FromPointeeType->getAs<FunctionProtoType>(); 2288 const FunctionProtoType *ToFunctionType 2289 = ToPointeeType->getAs<FunctionProtoType>(); 2290 if (FromFunctionType && ToFunctionType) { 2291 // If the function types are exactly the same, this isn't an 2292 // Objective-C pointer conversion. 2293 if (Context.getCanonicalType(FromPointeeType) 2294 == Context.getCanonicalType(ToPointeeType)) 2295 return false; 2296 2297 // Perform the quick checks that will tell us whether these 2298 // function types are obviously different. 2299 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2300 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2301 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2302 return false; 2303 2304 bool HasObjCConversion = false; 2305 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2306 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2307 // Okay, the types match exactly. Nothing to do. 2308 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2309 ToFunctionType->getReturnType(), 2310 ConvertedType, IncompatibleObjC)) { 2311 // Okay, we have an Objective-C pointer conversion. 2312 HasObjCConversion = true; 2313 } else { 2314 // Function types are too different. Abort. 2315 return false; 2316 } 2317 2318 // Check argument types. 2319 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2320 ArgIdx != NumArgs; ++ArgIdx) { 2321 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2322 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2323 if (Context.getCanonicalType(FromArgType) 2324 == Context.getCanonicalType(ToArgType)) { 2325 // Okay, the types match exactly. Nothing to do. 2326 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2327 ConvertedType, IncompatibleObjC)) { 2328 // Okay, we have an Objective-C pointer conversion. 2329 HasObjCConversion = true; 2330 } else { 2331 // Argument types are too different. Abort. 2332 return false; 2333 } 2334 } 2335 2336 if (HasObjCConversion) { 2337 // We had an Objective-C conversion. Allow this pointer 2338 // conversion, but complain about it. 2339 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2340 IncompatibleObjC = true; 2341 return true; 2342 } 2343 } 2344 2345 return false; 2346 } 2347 2348 /// \brief Determine whether this is an Objective-C writeback conversion, 2349 /// used for parameter passing when performing automatic reference counting. 2350 /// 2351 /// \param FromType The type we're converting form. 2352 /// 2353 /// \param ToType The type we're converting to. 2354 /// 2355 /// \param ConvertedType The type that will be produced after applying 2356 /// this conversion. 2357 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2358 QualType &ConvertedType) { 2359 if (!getLangOpts().ObjCAutoRefCount || 2360 Context.hasSameUnqualifiedType(FromType, ToType)) 2361 return false; 2362 2363 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2364 QualType ToPointee; 2365 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2366 ToPointee = ToPointer->getPointeeType(); 2367 else 2368 return false; 2369 2370 Qualifiers ToQuals = ToPointee.getQualifiers(); 2371 if (!ToPointee->isObjCLifetimeType() || 2372 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2373 !ToQuals.withoutObjCLifetime().empty()) 2374 return false; 2375 2376 // Argument must be a pointer to __strong to __weak. 2377 QualType FromPointee; 2378 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2379 FromPointee = FromPointer->getPointeeType(); 2380 else 2381 return false; 2382 2383 Qualifiers FromQuals = FromPointee.getQualifiers(); 2384 if (!FromPointee->isObjCLifetimeType() || 2385 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2386 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2387 return false; 2388 2389 // Make sure that we have compatible qualifiers. 2390 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2391 if (!ToQuals.compatiblyIncludes(FromQuals)) 2392 return false; 2393 2394 // Remove qualifiers from the pointee type we're converting from; they 2395 // aren't used in the compatibility check belong, and we'll be adding back 2396 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2397 FromPointee = FromPointee.getUnqualifiedType(); 2398 2399 // The unqualified form of the pointee types must be compatible. 2400 ToPointee = ToPointee.getUnqualifiedType(); 2401 bool IncompatibleObjC; 2402 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2403 FromPointee = ToPointee; 2404 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2405 IncompatibleObjC)) 2406 return false; 2407 2408 /// \brief Construct the type we're converting to, which is a pointer to 2409 /// __autoreleasing pointee. 2410 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2411 ConvertedType = Context.getPointerType(FromPointee); 2412 return true; 2413 } 2414 2415 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2416 QualType& ConvertedType) { 2417 QualType ToPointeeType; 2418 if (const BlockPointerType *ToBlockPtr = 2419 ToType->getAs<BlockPointerType>()) 2420 ToPointeeType = ToBlockPtr->getPointeeType(); 2421 else 2422 return false; 2423 2424 QualType FromPointeeType; 2425 if (const BlockPointerType *FromBlockPtr = 2426 FromType->getAs<BlockPointerType>()) 2427 FromPointeeType = FromBlockPtr->getPointeeType(); 2428 else 2429 return false; 2430 // We have pointer to blocks, check whether the only 2431 // differences in the argument and result types are in Objective-C 2432 // pointer conversions. If so, we permit the conversion. 2433 2434 const FunctionProtoType *FromFunctionType 2435 = FromPointeeType->getAs<FunctionProtoType>(); 2436 const FunctionProtoType *ToFunctionType 2437 = ToPointeeType->getAs<FunctionProtoType>(); 2438 2439 if (!FromFunctionType || !ToFunctionType) 2440 return false; 2441 2442 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2443 return true; 2444 2445 // Perform the quick checks that will tell us whether these 2446 // function types are obviously different. 2447 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2448 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2449 return false; 2450 2451 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2452 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2453 if (FromEInfo != ToEInfo) 2454 return false; 2455 2456 bool IncompatibleObjC = false; 2457 if (Context.hasSameType(FromFunctionType->getReturnType(), 2458 ToFunctionType->getReturnType())) { 2459 // Okay, the types match exactly. Nothing to do. 2460 } else { 2461 QualType RHS = FromFunctionType->getReturnType(); 2462 QualType LHS = ToFunctionType->getReturnType(); 2463 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2464 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2465 LHS = LHS.getUnqualifiedType(); 2466 2467 if (Context.hasSameType(RHS,LHS)) { 2468 // OK exact match. 2469 } else if (isObjCPointerConversion(RHS, LHS, 2470 ConvertedType, IncompatibleObjC)) { 2471 if (IncompatibleObjC) 2472 return false; 2473 // Okay, we have an Objective-C pointer conversion. 2474 } 2475 else 2476 return false; 2477 } 2478 2479 // Check argument types. 2480 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2481 ArgIdx != NumArgs; ++ArgIdx) { 2482 IncompatibleObjC = false; 2483 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2484 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2485 if (Context.hasSameType(FromArgType, ToArgType)) { 2486 // Okay, the types match exactly. Nothing to do. 2487 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2488 ConvertedType, IncompatibleObjC)) { 2489 if (IncompatibleObjC) 2490 return false; 2491 // Okay, we have an Objective-C pointer conversion. 2492 } else 2493 // Argument types are too different. Abort. 2494 return false; 2495 } 2496 if (LangOpts.ObjCAutoRefCount && 2497 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2498 ToFunctionType)) 2499 return false; 2500 2501 ConvertedType = ToType; 2502 return true; 2503 } 2504 2505 enum { 2506 ft_default, 2507 ft_different_class, 2508 ft_parameter_arity, 2509 ft_parameter_mismatch, 2510 ft_return_type, 2511 ft_qualifer_mismatch, 2512 ft_addr_enable_if 2513 }; 2514 2515 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2516 /// function types. Catches different number of parameter, mismatch in 2517 /// parameter types, and different return types. 2518 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2519 QualType FromType, QualType ToType) { 2520 // If either type is not valid, include no extra info. 2521 if (FromType.isNull() || ToType.isNull()) { 2522 PDiag << ft_default; 2523 return; 2524 } 2525 2526 // Get the function type from the pointers. 2527 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2528 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2529 *ToMember = ToType->getAs<MemberPointerType>(); 2530 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2531 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2532 << QualType(FromMember->getClass(), 0); 2533 return; 2534 } 2535 FromType = FromMember->getPointeeType(); 2536 ToType = ToMember->getPointeeType(); 2537 } 2538 2539 if (FromType->isPointerType()) 2540 FromType = FromType->getPointeeType(); 2541 if (ToType->isPointerType()) 2542 ToType = ToType->getPointeeType(); 2543 2544 // Remove references. 2545 FromType = FromType.getNonReferenceType(); 2546 ToType = ToType.getNonReferenceType(); 2547 2548 // Don't print extra info for non-specialized template functions. 2549 if (FromType->isInstantiationDependentType() && 2550 !FromType->getAs<TemplateSpecializationType>()) { 2551 PDiag << ft_default; 2552 return; 2553 } 2554 2555 // No extra info for same types. 2556 if (Context.hasSameType(FromType, ToType)) { 2557 PDiag << ft_default; 2558 return; 2559 } 2560 2561 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2562 *ToFunction = ToType->getAs<FunctionProtoType>(); 2563 2564 // Both types need to be function types. 2565 if (!FromFunction || !ToFunction) { 2566 PDiag << ft_default; 2567 return; 2568 } 2569 2570 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2571 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2572 << FromFunction->getNumParams(); 2573 return; 2574 } 2575 2576 // Handle different parameter types. 2577 unsigned ArgPos; 2578 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2579 PDiag << ft_parameter_mismatch << ArgPos + 1 2580 << ToFunction->getParamType(ArgPos) 2581 << FromFunction->getParamType(ArgPos); 2582 return; 2583 } 2584 2585 // Handle different return type. 2586 if (!Context.hasSameType(FromFunction->getReturnType(), 2587 ToFunction->getReturnType())) { 2588 PDiag << ft_return_type << ToFunction->getReturnType() 2589 << FromFunction->getReturnType(); 2590 return; 2591 } 2592 2593 unsigned FromQuals = FromFunction->getTypeQuals(), 2594 ToQuals = ToFunction->getTypeQuals(); 2595 if (FromQuals != ToQuals) { 2596 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2597 return; 2598 } 2599 2600 // Unable to find a difference, so add no extra info. 2601 PDiag << ft_default; 2602 } 2603 2604 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2605 /// for equality of their argument types. Caller has already checked that 2606 /// they have same number of arguments. If the parameters are different, 2607 /// ArgPos will have the parameter index of the first different parameter. 2608 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2609 const FunctionProtoType *NewType, 2610 unsigned *ArgPos) { 2611 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2612 N = NewType->param_type_begin(), 2613 E = OldType->param_type_end(); 2614 O && (O != E); ++O, ++N) { 2615 if (!Context.hasSameType(O->getUnqualifiedType(), 2616 N->getUnqualifiedType())) { 2617 if (ArgPos) 2618 *ArgPos = O - OldType->param_type_begin(); 2619 return false; 2620 } 2621 } 2622 return true; 2623 } 2624 2625 /// CheckPointerConversion - Check the pointer conversion from the 2626 /// expression From to the type ToType. This routine checks for 2627 /// ambiguous or inaccessible derived-to-base pointer 2628 /// conversions for which IsPointerConversion has already returned 2629 /// true. It returns true and produces a diagnostic if there was an 2630 /// error, or returns false otherwise. 2631 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2632 CastKind &Kind, 2633 CXXCastPath& BasePath, 2634 bool IgnoreBaseAccess) { 2635 QualType FromType = From->getType(); 2636 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2637 2638 Kind = CK_BitCast; 2639 2640 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2641 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2642 Expr::NPCK_ZeroExpression) { 2643 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2644 DiagRuntimeBehavior(From->getExprLoc(), From, 2645 PDiag(diag::warn_impcast_bool_to_null_pointer) 2646 << ToType << From->getSourceRange()); 2647 else if (!isUnevaluatedContext()) 2648 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2649 << ToType << From->getSourceRange(); 2650 } 2651 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2652 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2653 QualType FromPointeeType = FromPtrType->getPointeeType(), 2654 ToPointeeType = ToPtrType->getPointeeType(); 2655 2656 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2657 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2658 // We must have a derived-to-base conversion. Check an 2659 // ambiguous or inaccessible conversion. 2660 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2661 From->getExprLoc(), 2662 From->getSourceRange(), &BasePath, 2663 IgnoreBaseAccess)) 2664 return true; 2665 2666 // The conversion was successful. 2667 Kind = CK_DerivedToBase; 2668 } 2669 } 2670 } else if (const ObjCObjectPointerType *ToPtrType = 2671 ToType->getAs<ObjCObjectPointerType>()) { 2672 if (const ObjCObjectPointerType *FromPtrType = 2673 FromType->getAs<ObjCObjectPointerType>()) { 2674 // Objective-C++ conversions are always okay. 2675 // FIXME: We should have a different class of conversions for the 2676 // Objective-C++ implicit conversions. 2677 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2678 return false; 2679 } else if (FromType->isBlockPointerType()) { 2680 Kind = CK_BlockPointerToObjCPointerCast; 2681 } else { 2682 Kind = CK_CPointerToObjCPointerCast; 2683 } 2684 } else if (ToType->isBlockPointerType()) { 2685 if (!FromType->isBlockPointerType()) 2686 Kind = CK_AnyPointerToBlockPointerCast; 2687 } 2688 2689 // We shouldn't fall into this case unless it's valid for other 2690 // reasons. 2691 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2692 Kind = CK_NullToPointer; 2693 2694 return false; 2695 } 2696 2697 /// IsMemberPointerConversion - Determines whether the conversion of the 2698 /// expression From, which has the (possibly adjusted) type FromType, can be 2699 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2700 /// If so, returns true and places the converted type (that might differ from 2701 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2702 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2703 QualType ToType, 2704 bool InOverloadResolution, 2705 QualType &ConvertedType) { 2706 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2707 if (!ToTypePtr) 2708 return false; 2709 2710 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2711 if (From->isNullPointerConstant(Context, 2712 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2713 : Expr::NPC_ValueDependentIsNull)) { 2714 ConvertedType = ToType; 2715 return true; 2716 } 2717 2718 // Otherwise, both types have to be member pointers. 2719 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2720 if (!FromTypePtr) 2721 return false; 2722 2723 // A pointer to member of B can be converted to a pointer to member of D, 2724 // where D is derived from B (C++ 4.11p2). 2725 QualType FromClass(FromTypePtr->getClass(), 0); 2726 QualType ToClass(ToTypePtr->getClass(), 0); 2727 2728 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2729 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2730 IsDerivedFrom(ToClass, FromClass)) { 2731 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2732 ToClass.getTypePtr()); 2733 return true; 2734 } 2735 2736 return false; 2737 } 2738 2739 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2740 /// expression From to the type ToType. This routine checks for ambiguous or 2741 /// virtual or inaccessible base-to-derived member pointer conversions 2742 /// for which IsMemberPointerConversion has already returned true. It returns 2743 /// true and produces a diagnostic if there was an error, or returns false 2744 /// otherwise. 2745 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2746 CastKind &Kind, 2747 CXXCastPath &BasePath, 2748 bool IgnoreBaseAccess) { 2749 QualType FromType = From->getType(); 2750 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2751 if (!FromPtrType) { 2752 // This must be a null pointer to member pointer conversion 2753 assert(From->isNullPointerConstant(Context, 2754 Expr::NPC_ValueDependentIsNull) && 2755 "Expr must be null pointer constant!"); 2756 Kind = CK_NullToMemberPointer; 2757 return false; 2758 } 2759 2760 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2761 assert(ToPtrType && "No member pointer cast has a target type " 2762 "that is not a member pointer."); 2763 2764 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2765 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2766 2767 // FIXME: What about dependent types? 2768 assert(FromClass->isRecordType() && "Pointer into non-class."); 2769 assert(ToClass->isRecordType() && "Pointer into non-class."); 2770 2771 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2772 /*DetectVirtual=*/true); 2773 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2774 assert(DerivationOkay && 2775 "Should not have been called if derivation isn't OK."); 2776 (void)DerivationOkay; 2777 2778 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2779 getUnqualifiedType())) { 2780 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2781 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2782 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2783 return true; 2784 } 2785 2786 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2787 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2788 << FromClass << ToClass << QualType(VBase, 0) 2789 << From->getSourceRange(); 2790 return true; 2791 } 2792 2793 if (!IgnoreBaseAccess) 2794 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2795 Paths.front(), 2796 diag::err_downcast_from_inaccessible_base); 2797 2798 // Must be a base to derived member conversion. 2799 BuildBasePathArray(Paths, BasePath); 2800 Kind = CK_BaseToDerivedMemberPointer; 2801 return false; 2802 } 2803 2804 /// Determine whether the lifetime conversion between the two given 2805 /// qualifiers sets is nontrivial. 2806 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2807 Qualifiers ToQuals) { 2808 // Converting anything to const __unsafe_unretained is trivial. 2809 if (ToQuals.hasConst() && 2810 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2811 return false; 2812 2813 return true; 2814 } 2815 2816 /// IsQualificationConversion - Determines whether the conversion from 2817 /// an rvalue of type FromType to ToType is a qualification conversion 2818 /// (C++ 4.4). 2819 /// 2820 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2821 /// when the qualification conversion involves a change in the Objective-C 2822 /// object lifetime. 2823 bool 2824 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2825 bool CStyle, bool &ObjCLifetimeConversion) { 2826 FromType = Context.getCanonicalType(FromType); 2827 ToType = Context.getCanonicalType(ToType); 2828 ObjCLifetimeConversion = false; 2829 2830 // If FromType and ToType are the same type, this is not a 2831 // qualification conversion. 2832 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2833 return false; 2834 2835 // (C++ 4.4p4): 2836 // A conversion can add cv-qualifiers at levels other than the first 2837 // in multi-level pointers, subject to the following rules: [...] 2838 bool PreviousToQualsIncludeConst = true; 2839 bool UnwrappedAnyPointer = false; 2840 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2841 // Within each iteration of the loop, we check the qualifiers to 2842 // determine if this still looks like a qualification 2843 // conversion. Then, if all is well, we unwrap one more level of 2844 // pointers or pointers-to-members and do it all again 2845 // until there are no more pointers or pointers-to-members left to 2846 // unwrap. 2847 UnwrappedAnyPointer = true; 2848 2849 Qualifiers FromQuals = FromType.getQualifiers(); 2850 Qualifiers ToQuals = ToType.getQualifiers(); 2851 2852 // Objective-C ARC: 2853 // Check Objective-C lifetime conversions. 2854 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2855 UnwrappedAnyPointer) { 2856 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2857 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2858 ObjCLifetimeConversion = true; 2859 FromQuals.removeObjCLifetime(); 2860 ToQuals.removeObjCLifetime(); 2861 } else { 2862 // Qualification conversions cannot cast between different 2863 // Objective-C lifetime qualifiers. 2864 return false; 2865 } 2866 } 2867 2868 // Allow addition/removal of GC attributes but not changing GC attributes. 2869 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2870 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2871 FromQuals.removeObjCGCAttr(); 2872 ToQuals.removeObjCGCAttr(); 2873 } 2874 2875 // -- for every j > 0, if const is in cv 1,j then const is in cv 2876 // 2,j, and similarly for volatile. 2877 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2878 return false; 2879 2880 // -- if the cv 1,j and cv 2,j are different, then const is in 2881 // every cv for 0 < k < j. 2882 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2883 && !PreviousToQualsIncludeConst) 2884 return false; 2885 2886 // Keep track of whether all prior cv-qualifiers in the "to" type 2887 // include const. 2888 PreviousToQualsIncludeConst 2889 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2890 } 2891 2892 // We are left with FromType and ToType being the pointee types 2893 // after unwrapping the original FromType and ToType the same number 2894 // of types. If we unwrapped any pointers, and if FromType and 2895 // ToType have the same unqualified type (since we checked 2896 // qualifiers above), then this is a qualification conversion. 2897 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2898 } 2899 2900 /// \brief - Determine whether this is a conversion from a scalar type to an 2901 /// atomic type. 2902 /// 2903 /// If successful, updates \c SCS's second and third steps in the conversion 2904 /// sequence to finish the conversion. 2905 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2906 bool InOverloadResolution, 2907 StandardConversionSequence &SCS, 2908 bool CStyle) { 2909 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2910 if (!ToAtomic) 2911 return false; 2912 2913 StandardConversionSequence InnerSCS; 2914 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2915 InOverloadResolution, InnerSCS, 2916 CStyle, /*AllowObjCWritebackConversion=*/false)) 2917 return false; 2918 2919 SCS.Second = InnerSCS.Second; 2920 SCS.setToType(1, InnerSCS.getToType(1)); 2921 SCS.Third = InnerSCS.Third; 2922 SCS.QualificationIncludesObjCLifetime 2923 = InnerSCS.QualificationIncludesObjCLifetime; 2924 SCS.setToType(2, InnerSCS.getToType(2)); 2925 return true; 2926 } 2927 2928 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2929 CXXConstructorDecl *Constructor, 2930 QualType Type) { 2931 const FunctionProtoType *CtorType = 2932 Constructor->getType()->getAs<FunctionProtoType>(); 2933 if (CtorType->getNumParams() > 0) { 2934 QualType FirstArg = CtorType->getParamType(0); 2935 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2936 return true; 2937 } 2938 return false; 2939 } 2940 2941 static OverloadingResult 2942 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2943 CXXRecordDecl *To, 2944 UserDefinedConversionSequence &User, 2945 OverloadCandidateSet &CandidateSet, 2946 bool AllowExplicit) { 2947 DeclContext::lookup_result R = S.LookupConstructors(To); 2948 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2949 Con != ConEnd; ++Con) { 2950 NamedDecl *D = *Con; 2951 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2952 2953 // Find the constructor (which may be a template). 2954 CXXConstructorDecl *Constructor = nullptr; 2955 FunctionTemplateDecl *ConstructorTmpl 2956 = dyn_cast<FunctionTemplateDecl>(D); 2957 if (ConstructorTmpl) 2958 Constructor 2959 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2960 else 2961 Constructor = cast<CXXConstructorDecl>(D); 2962 2963 bool Usable = !Constructor->isInvalidDecl() && 2964 S.isInitListConstructor(Constructor) && 2965 (AllowExplicit || !Constructor->isExplicit()); 2966 if (Usable) { 2967 // If the first argument is (a reference to) the target type, 2968 // suppress conversions. 2969 bool SuppressUserConversions = 2970 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2971 if (ConstructorTmpl) 2972 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2973 /*ExplicitArgs*/ nullptr, 2974 From, CandidateSet, 2975 SuppressUserConversions); 2976 else 2977 S.AddOverloadCandidate(Constructor, FoundDecl, 2978 From, CandidateSet, 2979 SuppressUserConversions); 2980 } 2981 } 2982 2983 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2984 2985 OverloadCandidateSet::iterator Best; 2986 switch (auto Result = 2987 CandidateSet.BestViableFunction(S, From->getLocStart(), 2988 Best, true)) { 2989 case OR_Deleted: 2990 case OR_Success: { 2991 // Record the standard conversion we used and the conversion function. 2992 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2993 QualType ThisType = Constructor->getThisType(S.Context); 2994 // Initializer lists don't have conversions as such. 2995 User.Before.setAsIdentityConversion(); 2996 User.HadMultipleCandidates = HadMultipleCandidates; 2997 User.ConversionFunction = Constructor; 2998 User.FoundConversionFunction = Best->FoundDecl; 2999 User.After.setAsIdentityConversion(); 3000 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3001 User.After.setAllToTypes(ToType); 3002 return Result; 3003 } 3004 3005 case OR_No_Viable_Function: 3006 return OR_No_Viable_Function; 3007 case OR_Ambiguous: 3008 return OR_Ambiguous; 3009 } 3010 3011 llvm_unreachable("Invalid OverloadResult!"); 3012 } 3013 3014 /// Determines whether there is a user-defined conversion sequence 3015 /// (C++ [over.ics.user]) that converts expression From to the type 3016 /// ToType. If such a conversion exists, User will contain the 3017 /// user-defined conversion sequence that performs such a conversion 3018 /// and this routine will return true. Otherwise, this routine returns 3019 /// false and User is unspecified. 3020 /// 3021 /// \param AllowExplicit true if the conversion should consider C++0x 3022 /// "explicit" conversion functions as well as non-explicit conversion 3023 /// functions (C++0x [class.conv.fct]p2). 3024 /// 3025 /// \param AllowObjCConversionOnExplicit true if the conversion should 3026 /// allow an extra Objective-C pointer conversion on uses of explicit 3027 /// constructors. Requires \c AllowExplicit to also be set. 3028 static OverloadingResult 3029 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3030 UserDefinedConversionSequence &User, 3031 OverloadCandidateSet &CandidateSet, 3032 bool AllowExplicit, 3033 bool AllowObjCConversionOnExplicit) { 3034 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3035 3036 // Whether we will only visit constructors. 3037 bool ConstructorsOnly = false; 3038 3039 // If the type we are conversion to is a class type, enumerate its 3040 // constructors. 3041 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3042 // C++ [over.match.ctor]p1: 3043 // When objects of class type are direct-initialized (8.5), or 3044 // copy-initialized from an expression of the same or a 3045 // derived class type (8.5), overload resolution selects the 3046 // constructor. [...] For copy-initialization, the candidate 3047 // functions are all the converting constructors (12.3.1) of 3048 // that class. The argument list is the expression-list within 3049 // the parentheses of the initializer. 3050 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3051 (From->getType()->getAs<RecordType>() && 3052 S.IsDerivedFrom(From->getType(), ToType))) 3053 ConstructorsOnly = true; 3054 3055 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3056 // RequireCompleteType may have returned true due to some invalid decl 3057 // during template instantiation, but ToType may be complete enough now 3058 // to try to recover. 3059 if (ToType->isIncompleteType()) { 3060 // We're not going to find any constructors. 3061 } else if (CXXRecordDecl *ToRecordDecl 3062 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3063 3064 Expr **Args = &From; 3065 unsigned NumArgs = 1; 3066 bool ListInitializing = false; 3067 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3068 // But first, see if there is an init-list-constructor that will work. 3069 OverloadingResult Result = IsInitializerListConstructorConversion( 3070 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3071 if (Result != OR_No_Viable_Function) 3072 return Result; 3073 // Never mind. 3074 CandidateSet.clear(); 3075 3076 // If we're list-initializing, we pass the individual elements as 3077 // arguments, not the entire list. 3078 Args = InitList->getInits(); 3079 NumArgs = InitList->getNumInits(); 3080 ListInitializing = true; 3081 } 3082 3083 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3084 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3085 Con != ConEnd; ++Con) { 3086 NamedDecl *D = *Con; 3087 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3088 3089 // Find the constructor (which may be a template). 3090 CXXConstructorDecl *Constructor = nullptr; 3091 FunctionTemplateDecl *ConstructorTmpl 3092 = dyn_cast<FunctionTemplateDecl>(D); 3093 if (ConstructorTmpl) 3094 Constructor 3095 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3096 else 3097 Constructor = cast<CXXConstructorDecl>(D); 3098 3099 bool Usable = !Constructor->isInvalidDecl(); 3100 if (ListInitializing) 3101 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3102 else 3103 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3104 if (Usable) { 3105 bool SuppressUserConversions = !ConstructorsOnly; 3106 if (SuppressUserConversions && ListInitializing) { 3107 SuppressUserConversions = false; 3108 if (NumArgs == 1) { 3109 // If the first argument is (a reference to) the target type, 3110 // suppress conversions. 3111 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3112 S.Context, Constructor, ToType); 3113 } 3114 } 3115 if (ConstructorTmpl) 3116 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3117 /*ExplicitArgs*/ nullptr, 3118 llvm::makeArrayRef(Args, NumArgs), 3119 CandidateSet, SuppressUserConversions); 3120 else 3121 // Allow one user-defined conversion when user specifies a 3122 // From->ToType conversion via an static cast (c-style, etc). 3123 S.AddOverloadCandidate(Constructor, FoundDecl, 3124 llvm::makeArrayRef(Args, NumArgs), 3125 CandidateSet, SuppressUserConversions); 3126 } 3127 } 3128 } 3129 } 3130 3131 // Enumerate conversion functions, if we're allowed to. 3132 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3133 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3134 // No conversion functions from incomplete types. 3135 } else if (const RecordType *FromRecordType 3136 = From->getType()->getAs<RecordType>()) { 3137 if (CXXRecordDecl *FromRecordDecl 3138 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3139 // Add all of the conversion functions as candidates. 3140 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3141 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3142 DeclAccessPair FoundDecl = I.getPair(); 3143 NamedDecl *D = FoundDecl.getDecl(); 3144 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3145 if (isa<UsingShadowDecl>(D)) 3146 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3147 3148 CXXConversionDecl *Conv; 3149 FunctionTemplateDecl *ConvTemplate; 3150 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3151 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3152 else 3153 Conv = cast<CXXConversionDecl>(D); 3154 3155 if (AllowExplicit || !Conv->isExplicit()) { 3156 if (ConvTemplate) 3157 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3158 ActingContext, From, ToType, 3159 CandidateSet, 3160 AllowObjCConversionOnExplicit); 3161 else 3162 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3163 From, ToType, CandidateSet, 3164 AllowObjCConversionOnExplicit); 3165 } 3166 } 3167 } 3168 } 3169 3170 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3171 3172 OverloadCandidateSet::iterator Best; 3173 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3174 Best, true)) { 3175 case OR_Success: 3176 case OR_Deleted: 3177 // Record the standard conversion we used and the conversion function. 3178 if (CXXConstructorDecl *Constructor 3179 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3180 // C++ [over.ics.user]p1: 3181 // If the user-defined conversion is specified by a 3182 // constructor (12.3.1), the initial standard conversion 3183 // sequence converts the source type to the type required by 3184 // the argument of the constructor. 3185 // 3186 QualType ThisType = Constructor->getThisType(S.Context); 3187 if (isa<InitListExpr>(From)) { 3188 // Initializer lists don't have conversions as such. 3189 User.Before.setAsIdentityConversion(); 3190 } else { 3191 if (Best->Conversions[0].isEllipsis()) 3192 User.EllipsisConversion = true; 3193 else { 3194 User.Before = Best->Conversions[0].Standard; 3195 User.EllipsisConversion = false; 3196 } 3197 } 3198 User.HadMultipleCandidates = HadMultipleCandidates; 3199 User.ConversionFunction = Constructor; 3200 User.FoundConversionFunction = Best->FoundDecl; 3201 User.After.setAsIdentityConversion(); 3202 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3203 User.After.setAllToTypes(ToType); 3204 return Result; 3205 } 3206 if (CXXConversionDecl *Conversion 3207 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3208 // C++ [over.ics.user]p1: 3209 // 3210 // [...] If the user-defined conversion is specified by a 3211 // conversion function (12.3.2), the initial standard 3212 // conversion sequence converts the source type to the 3213 // implicit object parameter of the conversion function. 3214 User.Before = Best->Conversions[0].Standard; 3215 User.HadMultipleCandidates = HadMultipleCandidates; 3216 User.ConversionFunction = Conversion; 3217 User.FoundConversionFunction = Best->FoundDecl; 3218 User.EllipsisConversion = false; 3219 3220 // C++ [over.ics.user]p2: 3221 // The second standard conversion sequence converts the 3222 // result of the user-defined conversion to the target type 3223 // for the sequence. Since an implicit conversion sequence 3224 // is an initialization, the special rules for 3225 // initialization by user-defined conversion apply when 3226 // selecting the best user-defined conversion for a 3227 // user-defined conversion sequence (see 13.3.3 and 3228 // 13.3.3.1). 3229 User.After = Best->FinalConversion; 3230 return Result; 3231 } 3232 llvm_unreachable("Not a constructor or conversion function?"); 3233 3234 case OR_No_Viable_Function: 3235 return OR_No_Viable_Function; 3236 3237 case OR_Ambiguous: 3238 return OR_Ambiguous; 3239 } 3240 3241 llvm_unreachable("Invalid OverloadResult!"); 3242 } 3243 3244 bool 3245 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3246 ImplicitConversionSequence ICS; 3247 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3248 OverloadCandidateSet::CSK_Normal); 3249 OverloadingResult OvResult = 3250 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3251 CandidateSet, false, false); 3252 if (OvResult == OR_Ambiguous) 3253 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3254 << From->getType() << ToType << From->getSourceRange(); 3255 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3256 if (!RequireCompleteType(From->getLocStart(), ToType, 3257 diag::err_typecheck_nonviable_condition_incomplete, 3258 From->getType(), From->getSourceRange())) 3259 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3260 << false << From->getType() << From->getSourceRange() << ToType; 3261 } else 3262 return false; 3263 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3264 return true; 3265 } 3266 3267 /// \brief Compare the user-defined conversion functions or constructors 3268 /// of two user-defined conversion sequences to determine whether any ordering 3269 /// is possible. 3270 static ImplicitConversionSequence::CompareKind 3271 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3272 FunctionDecl *Function2) { 3273 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3274 return ImplicitConversionSequence::Indistinguishable; 3275 3276 // Objective-C++: 3277 // If both conversion functions are implicitly-declared conversions from 3278 // a lambda closure type to a function pointer and a block pointer, 3279 // respectively, always prefer the conversion to a function pointer, 3280 // because the function pointer is more lightweight and is more likely 3281 // to keep code working. 3282 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3283 if (!Conv1) 3284 return ImplicitConversionSequence::Indistinguishable; 3285 3286 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3287 if (!Conv2) 3288 return ImplicitConversionSequence::Indistinguishable; 3289 3290 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3291 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3292 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3293 if (Block1 != Block2) 3294 return Block1 ? ImplicitConversionSequence::Worse 3295 : ImplicitConversionSequence::Better; 3296 } 3297 3298 return ImplicitConversionSequence::Indistinguishable; 3299 } 3300 3301 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3302 const ImplicitConversionSequence &ICS) { 3303 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3304 (ICS.isUserDefined() && 3305 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3306 } 3307 3308 /// CompareImplicitConversionSequences - Compare two implicit 3309 /// conversion sequences to determine whether one is better than the 3310 /// other or if they are indistinguishable (C++ 13.3.3.2). 3311 static ImplicitConversionSequence::CompareKind 3312 CompareImplicitConversionSequences(Sema &S, 3313 const ImplicitConversionSequence& ICS1, 3314 const ImplicitConversionSequence& ICS2) 3315 { 3316 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3317 // conversion sequences (as defined in 13.3.3.1) 3318 // -- a standard conversion sequence (13.3.3.1.1) is a better 3319 // conversion sequence than a user-defined conversion sequence or 3320 // an ellipsis conversion sequence, and 3321 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3322 // conversion sequence than an ellipsis conversion sequence 3323 // (13.3.3.1.3). 3324 // 3325 // C++0x [over.best.ics]p10: 3326 // For the purpose of ranking implicit conversion sequences as 3327 // described in 13.3.3.2, the ambiguous conversion sequence is 3328 // treated as a user-defined sequence that is indistinguishable 3329 // from any other user-defined conversion sequence. 3330 3331 // String literal to 'char *' conversion has been deprecated in C++03. It has 3332 // been removed from C++11. We still accept this conversion, if it happens at 3333 // the best viable function. Otherwise, this conversion is considered worse 3334 // than ellipsis conversion. Consider this as an extension; this is not in the 3335 // standard. For example: 3336 // 3337 // int &f(...); // #1 3338 // void f(char*); // #2 3339 // void g() { int &r = f("foo"); } 3340 // 3341 // In C++03, we pick #2 as the best viable function. 3342 // In C++11, we pick #1 as the best viable function, because ellipsis 3343 // conversion is better than string-literal to char* conversion (since there 3344 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3345 // convert arguments, #2 would be the best viable function in C++11. 3346 // If the best viable function has this conversion, a warning will be issued 3347 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3348 3349 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3350 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3351 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3352 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3353 ? ImplicitConversionSequence::Worse 3354 : ImplicitConversionSequence::Better; 3355 3356 if (ICS1.getKindRank() < ICS2.getKindRank()) 3357 return ImplicitConversionSequence::Better; 3358 if (ICS2.getKindRank() < ICS1.getKindRank()) 3359 return ImplicitConversionSequence::Worse; 3360 3361 // The following checks require both conversion sequences to be of 3362 // the same kind. 3363 if (ICS1.getKind() != ICS2.getKind()) 3364 return ImplicitConversionSequence::Indistinguishable; 3365 3366 ImplicitConversionSequence::CompareKind Result = 3367 ImplicitConversionSequence::Indistinguishable; 3368 3369 // Two implicit conversion sequences of the same form are 3370 // indistinguishable conversion sequences unless one of the 3371 // following rules apply: (C++ 13.3.3.2p3): 3372 3373 // List-initialization sequence L1 is a better conversion sequence than 3374 // list-initialization sequence L2 if: 3375 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3376 // if not that, 3377 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3378 // and N1 is smaller than N2., 3379 // even if one of the other rules in this paragraph would otherwise apply. 3380 if (!ICS1.isBad()) { 3381 if (ICS1.isStdInitializerListElement() && 3382 !ICS2.isStdInitializerListElement()) 3383 return ImplicitConversionSequence::Better; 3384 if (!ICS1.isStdInitializerListElement() && 3385 ICS2.isStdInitializerListElement()) 3386 return ImplicitConversionSequence::Worse; 3387 } 3388 3389 if (ICS1.isStandard()) 3390 // Standard conversion sequence S1 is a better conversion sequence than 3391 // standard conversion sequence S2 if [...] 3392 Result = CompareStandardConversionSequences(S, 3393 ICS1.Standard, ICS2.Standard); 3394 else if (ICS1.isUserDefined()) { 3395 // User-defined conversion sequence U1 is a better conversion 3396 // sequence than another user-defined conversion sequence U2 if 3397 // they contain the same user-defined conversion function or 3398 // constructor and if the second standard conversion sequence of 3399 // U1 is better than the second standard conversion sequence of 3400 // U2 (C++ 13.3.3.2p3). 3401 if (ICS1.UserDefined.ConversionFunction == 3402 ICS2.UserDefined.ConversionFunction) 3403 Result = CompareStandardConversionSequences(S, 3404 ICS1.UserDefined.After, 3405 ICS2.UserDefined.After); 3406 else 3407 Result = compareConversionFunctions(S, 3408 ICS1.UserDefined.ConversionFunction, 3409 ICS2.UserDefined.ConversionFunction); 3410 } 3411 3412 return Result; 3413 } 3414 3415 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3416 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3417 Qualifiers Quals; 3418 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3419 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3420 } 3421 3422 return Context.hasSameUnqualifiedType(T1, T2); 3423 } 3424 3425 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3426 // determine if one is a proper subset of the other. 3427 static ImplicitConversionSequence::CompareKind 3428 compareStandardConversionSubsets(ASTContext &Context, 3429 const StandardConversionSequence& SCS1, 3430 const StandardConversionSequence& SCS2) { 3431 ImplicitConversionSequence::CompareKind Result 3432 = ImplicitConversionSequence::Indistinguishable; 3433 3434 // the identity conversion sequence is considered to be a subsequence of 3435 // any non-identity conversion sequence 3436 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3437 return ImplicitConversionSequence::Better; 3438 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3439 return ImplicitConversionSequence::Worse; 3440 3441 if (SCS1.Second != SCS2.Second) { 3442 if (SCS1.Second == ICK_Identity) 3443 Result = ImplicitConversionSequence::Better; 3444 else if (SCS2.Second == ICK_Identity) 3445 Result = ImplicitConversionSequence::Worse; 3446 else 3447 return ImplicitConversionSequence::Indistinguishable; 3448 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3449 return ImplicitConversionSequence::Indistinguishable; 3450 3451 if (SCS1.Third == SCS2.Third) { 3452 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3453 : ImplicitConversionSequence::Indistinguishable; 3454 } 3455 3456 if (SCS1.Third == ICK_Identity) 3457 return Result == ImplicitConversionSequence::Worse 3458 ? ImplicitConversionSequence::Indistinguishable 3459 : ImplicitConversionSequence::Better; 3460 3461 if (SCS2.Third == ICK_Identity) 3462 return Result == ImplicitConversionSequence::Better 3463 ? ImplicitConversionSequence::Indistinguishable 3464 : ImplicitConversionSequence::Worse; 3465 3466 return ImplicitConversionSequence::Indistinguishable; 3467 } 3468 3469 /// \brief Determine whether one of the given reference bindings is better 3470 /// than the other based on what kind of bindings they are. 3471 static bool 3472 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3473 const StandardConversionSequence &SCS2) { 3474 // C++0x [over.ics.rank]p3b4: 3475 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3476 // implicit object parameter of a non-static member function declared 3477 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3478 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3479 // lvalue reference to a function lvalue and S2 binds an rvalue 3480 // reference*. 3481 // 3482 // FIXME: Rvalue references. We're going rogue with the above edits, 3483 // because the semantics in the current C++0x working paper (N3225 at the 3484 // time of this writing) break the standard definition of std::forward 3485 // and std::reference_wrapper when dealing with references to functions. 3486 // Proposed wording changes submitted to CWG for consideration. 3487 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3488 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3489 return false; 3490 3491 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3492 SCS2.IsLvalueReference) || 3493 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3494 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3495 } 3496 3497 /// CompareStandardConversionSequences - Compare two standard 3498 /// conversion sequences to determine whether one is better than the 3499 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3500 static ImplicitConversionSequence::CompareKind 3501 CompareStandardConversionSequences(Sema &S, 3502 const StandardConversionSequence& SCS1, 3503 const StandardConversionSequence& SCS2) 3504 { 3505 // Standard conversion sequence S1 is a better conversion sequence 3506 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3507 3508 // -- S1 is a proper subsequence of S2 (comparing the conversion 3509 // sequences in the canonical form defined by 13.3.3.1.1, 3510 // excluding any Lvalue Transformation; the identity conversion 3511 // sequence is considered to be a subsequence of any 3512 // non-identity conversion sequence) or, if not that, 3513 if (ImplicitConversionSequence::CompareKind CK 3514 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3515 return CK; 3516 3517 // -- the rank of S1 is better than the rank of S2 (by the rules 3518 // defined below), or, if not that, 3519 ImplicitConversionRank Rank1 = SCS1.getRank(); 3520 ImplicitConversionRank Rank2 = SCS2.getRank(); 3521 if (Rank1 < Rank2) 3522 return ImplicitConversionSequence::Better; 3523 else if (Rank2 < Rank1) 3524 return ImplicitConversionSequence::Worse; 3525 3526 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3527 // are indistinguishable unless one of the following rules 3528 // applies: 3529 3530 // A conversion that is not a conversion of a pointer, or 3531 // pointer to member, to bool is better than another conversion 3532 // that is such a conversion. 3533 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3534 return SCS2.isPointerConversionToBool() 3535 ? ImplicitConversionSequence::Better 3536 : ImplicitConversionSequence::Worse; 3537 3538 // C++ [over.ics.rank]p4b2: 3539 // 3540 // If class B is derived directly or indirectly from class A, 3541 // conversion of B* to A* is better than conversion of B* to 3542 // void*, and conversion of A* to void* is better than conversion 3543 // of B* to void*. 3544 bool SCS1ConvertsToVoid 3545 = SCS1.isPointerConversionToVoidPointer(S.Context); 3546 bool SCS2ConvertsToVoid 3547 = SCS2.isPointerConversionToVoidPointer(S.Context); 3548 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3549 // Exactly one of the conversion sequences is a conversion to 3550 // a void pointer; it's the worse conversion. 3551 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3552 : ImplicitConversionSequence::Worse; 3553 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3554 // Neither conversion sequence converts to a void pointer; compare 3555 // their derived-to-base conversions. 3556 if (ImplicitConversionSequence::CompareKind DerivedCK 3557 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3558 return DerivedCK; 3559 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3560 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3561 // Both conversion sequences are conversions to void 3562 // pointers. Compare the source types to determine if there's an 3563 // inheritance relationship in their sources. 3564 QualType FromType1 = SCS1.getFromType(); 3565 QualType FromType2 = SCS2.getFromType(); 3566 3567 // Adjust the types we're converting from via the array-to-pointer 3568 // conversion, if we need to. 3569 if (SCS1.First == ICK_Array_To_Pointer) 3570 FromType1 = S.Context.getArrayDecayedType(FromType1); 3571 if (SCS2.First == ICK_Array_To_Pointer) 3572 FromType2 = S.Context.getArrayDecayedType(FromType2); 3573 3574 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3575 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3576 3577 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3578 return ImplicitConversionSequence::Better; 3579 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3580 return ImplicitConversionSequence::Worse; 3581 3582 // Objective-C++: If one interface is more specific than the 3583 // other, it is the better one. 3584 const ObjCObjectPointerType* FromObjCPtr1 3585 = FromType1->getAs<ObjCObjectPointerType>(); 3586 const ObjCObjectPointerType* FromObjCPtr2 3587 = FromType2->getAs<ObjCObjectPointerType>(); 3588 if (FromObjCPtr1 && FromObjCPtr2) { 3589 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3590 FromObjCPtr2); 3591 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3592 FromObjCPtr1); 3593 if (AssignLeft != AssignRight) { 3594 return AssignLeft? ImplicitConversionSequence::Better 3595 : ImplicitConversionSequence::Worse; 3596 } 3597 } 3598 } 3599 3600 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3601 // bullet 3). 3602 if (ImplicitConversionSequence::CompareKind QualCK 3603 = CompareQualificationConversions(S, SCS1, SCS2)) 3604 return QualCK; 3605 3606 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3607 // Check for a better reference binding based on the kind of bindings. 3608 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3609 return ImplicitConversionSequence::Better; 3610 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3611 return ImplicitConversionSequence::Worse; 3612 3613 // C++ [over.ics.rank]p3b4: 3614 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3615 // which the references refer are the same type except for 3616 // top-level cv-qualifiers, and the type to which the reference 3617 // initialized by S2 refers is more cv-qualified than the type 3618 // to which the reference initialized by S1 refers. 3619 QualType T1 = SCS1.getToType(2); 3620 QualType T2 = SCS2.getToType(2); 3621 T1 = S.Context.getCanonicalType(T1); 3622 T2 = S.Context.getCanonicalType(T2); 3623 Qualifiers T1Quals, T2Quals; 3624 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3625 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3626 if (UnqualT1 == UnqualT2) { 3627 // Objective-C++ ARC: If the references refer to objects with different 3628 // lifetimes, prefer bindings that don't change lifetime. 3629 if (SCS1.ObjCLifetimeConversionBinding != 3630 SCS2.ObjCLifetimeConversionBinding) { 3631 return SCS1.ObjCLifetimeConversionBinding 3632 ? ImplicitConversionSequence::Worse 3633 : ImplicitConversionSequence::Better; 3634 } 3635 3636 // If the type is an array type, promote the element qualifiers to the 3637 // type for comparison. 3638 if (isa<ArrayType>(T1) && T1Quals) 3639 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3640 if (isa<ArrayType>(T2) && T2Quals) 3641 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3642 if (T2.isMoreQualifiedThan(T1)) 3643 return ImplicitConversionSequence::Better; 3644 else if (T1.isMoreQualifiedThan(T2)) 3645 return ImplicitConversionSequence::Worse; 3646 } 3647 } 3648 3649 // In Microsoft mode, prefer an integral conversion to a 3650 // floating-to-integral conversion if the integral conversion 3651 // is between types of the same size. 3652 // For example: 3653 // void f(float); 3654 // void f(int); 3655 // int main { 3656 // long a; 3657 // f(a); 3658 // } 3659 // Here, MSVC will call f(int) instead of generating a compile error 3660 // as clang will do in standard mode. 3661 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3662 SCS2.Second == ICK_Floating_Integral && 3663 S.Context.getTypeSize(SCS1.getFromType()) == 3664 S.Context.getTypeSize(SCS1.getToType(2))) 3665 return ImplicitConversionSequence::Better; 3666 3667 return ImplicitConversionSequence::Indistinguishable; 3668 } 3669 3670 /// CompareQualificationConversions - Compares two standard conversion 3671 /// sequences to determine whether they can be ranked based on their 3672 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3673 static ImplicitConversionSequence::CompareKind 3674 CompareQualificationConversions(Sema &S, 3675 const StandardConversionSequence& SCS1, 3676 const StandardConversionSequence& SCS2) { 3677 // C++ 13.3.3.2p3: 3678 // -- S1 and S2 differ only in their qualification conversion and 3679 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3680 // cv-qualification signature of type T1 is a proper subset of 3681 // the cv-qualification signature of type T2, and S1 is not the 3682 // deprecated string literal array-to-pointer conversion (4.2). 3683 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3684 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3685 return ImplicitConversionSequence::Indistinguishable; 3686 3687 // FIXME: the example in the standard doesn't use a qualification 3688 // conversion (!) 3689 QualType T1 = SCS1.getToType(2); 3690 QualType T2 = SCS2.getToType(2); 3691 T1 = S.Context.getCanonicalType(T1); 3692 T2 = S.Context.getCanonicalType(T2); 3693 Qualifiers T1Quals, T2Quals; 3694 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3695 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3696 3697 // If the types are the same, we won't learn anything by unwrapped 3698 // them. 3699 if (UnqualT1 == UnqualT2) 3700 return ImplicitConversionSequence::Indistinguishable; 3701 3702 // If the type is an array type, promote the element qualifiers to the type 3703 // for comparison. 3704 if (isa<ArrayType>(T1) && T1Quals) 3705 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3706 if (isa<ArrayType>(T2) && T2Quals) 3707 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3708 3709 ImplicitConversionSequence::CompareKind Result 3710 = ImplicitConversionSequence::Indistinguishable; 3711 3712 // Objective-C++ ARC: 3713 // Prefer qualification conversions not involving a change in lifetime 3714 // to qualification conversions that do not change lifetime. 3715 if (SCS1.QualificationIncludesObjCLifetime != 3716 SCS2.QualificationIncludesObjCLifetime) { 3717 Result = SCS1.QualificationIncludesObjCLifetime 3718 ? ImplicitConversionSequence::Worse 3719 : ImplicitConversionSequence::Better; 3720 } 3721 3722 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3723 // Within each iteration of the loop, we check the qualifiers to 3724 // determine if this still looks like a qualification 3725 // conversion. Then, if all is well, we unwrap one more level of 3726 // pointers or pointers-to-members and do it all again 3727 // until there are no more pointers or pointers-to-members left 3728 // to unwrap. This essentially mimics what 3729 // IsQualificationConversion does, but here we're checking for a 3730 // strict subset of qualifiers. 3731 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3732 // The qualifiers are the same, so this doesn't tell us anything 3733 // about how the sequences rank. 3734 ; 3735 else if (T2.isMoreQualifiedThan(T1)) { 3736 // T1 has fewer qualifiers, so it could be the better sequence. 3737 if (Result == ImplicitConversionSequence::Worse) 3738 // Neither has qualifiers that are a subset of the other's 3739 // qualifiers. 3740 return ImplicitConversionSequence::Indistinguishable; 3741 3742 Result = ImplicitConversionSequence::Better; 3743 } else if (T1.isMoreQualifiedThan(T2)) { 3744 // T2 has fewer qualifiers, so it could be the better sequence. 3745 if (Result == ImplicitConversionSequence::Better) 3746 // Neither has qualifiers that are a subset of the other's 3747 // qualifiers. 3748 return ImplicitConversionSequence::Indistinguishable; 3749 3750 Result = ImplicitConversionSequence::Worse; 3751 } else { 3752 // Qualifiers are disjoint. 3753 return ImplicitConversionSequence::Indistinguishable; 3754 } 3755 3756 // If the types after this point are equivalent, we're done. 3757 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3758 break; 3759 } 3760 3761 // Check that the winning standard conversion sequence isn't using 3762 // the deprecated string literal array to pointer conversion. 3763 switch (Result) { 3764 case ImplicitConversionSequence::Better: 3765 if (SCS1.DeprecatedStringLiteralToCharPtr) 3766 Result = ImplicitConversionSequence::Indistinguishable; 3767 break; 3768 3769 case ImplicitConversionSequence::Indistinguishable: 3770 break; 3771 3772 case ImplicitConversionSequence::Worse: 3773 if (SCS2.DeprecatedStringLiteralToCharPtr) 3774 Result = ImplicitConversionSequence::Indistinguishable; 3775 break; 3776 } 3777 3778 return Result; 3779 } 3780 3781 /// CompareDerivedToBaseConversions - Compares two standard conversion 3782 /// sequences to determine whether they can be ranked based on their 3783 /// various kinds of derived-to-base conversions (C++ 3784 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3785 /// conversions between Objective-C interface types. 3786 static ImplicitConversionSequence::CompareKind 3787 CompareDerivedToBaseConversions(Sema &S, 3788 const StandardConversionSequence& SCS1, 3789 const StandardConversionSequence& SCS2) { 3790 QualType FromType1 = SCS1.getFromType(); 3791 QualType ToType1 = SCS1.getToType(1); 3792 QualType FromType2 = SCS2.getFromType(); 3793 QualType ToType2 = SCS2.getToType(1); 3794 3795 // Adjust the types we're converting from via the array-to-pointer 3796 // conversion, if we need to. 3797 if (SCS1.First == ICK_Array_To_Pointer) 3798 FromType1 = S.Context.getArrayDecayedType(FromType1); 3799 if (SCS2.First == ICK_Array_To_Pointer) 3800 FromType2 = S.Context.getArrayDecayedType(FromType2); 3801 3802 // Canonicalize all of the types. 3803 FromType1 = S.Context.getCanonicalType(FromType1); 3804 ToType1 = S.Context.getCanonicalType(ToType1); 3805 FromType2 = S.Context.getCanonicalType(FromType2); 3806 ToType2 = S.Context.getCanonicalType(ToType2); 3807 3808 // C++ [over.ics.rank]p4b3: 3809 // 3810 // If class B is derived directly or indirectly from class A and 3811 // class C is derived directly or indirectly from B, 3812 // 3813 // Compare based on pointer conversions. 3814 if (SCS1.Second == ICK_Pointer_Conversion && 3815 SCS2.Second == ICK_Pointer_Conversion && 3816 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3817 FromType1->isPointerType() && FromType2->isPointerType() && 3818 ToType1->isPointerType() && ToType2->isPointerType()) { 3819 QualType FromPointee1 3820 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3821 QualType ToPointee1 3822 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3823 QualType FromPointee2 3824 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3825 QualType ToPointee2 3826 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3827 3828 // -- conversion of C* to B* is better than conversion of C* to A*, 3829 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3830 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3831 return ImplicitConversionSequence::Better; 3832 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3833 return ImplicitConversionSequence::Worse; 3834 } 3835 3836 // -- conversion of B* to A* is better than conversion of C* to A*, 3837 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3838 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3839 return ImplicitConversionSequence::Better; 3840 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3841 return ImplicitConversionSequence::Worse; 3842 } 3843 } else if (SCS1.Second == ICK_Pointer_Conversion && 3844 SCS2.Second == ICK_Pointer_Conversion) { 3845 const ObjCObjectPointerType *FromPtr1 3846 = FromType1->getAs<ObjCObjectPointerType>(); 3847 const ObjCObjectPointerType *FromPtr2 3848 = FromType2->getAs<ObjCObjectPointerType>(); 3849 const ObjCObjectPointerType *ToPtr1 3850 = ToType1->getAs<ObjCObjectPointerType>(); 3851 const ObjCObjectPointerType *ToPtr2 3852 = ToType2->getAs<ObjCObjectPointerType>(); 3853 3854 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3855 // Apply the same conversion ranking rules for Objective-C pointer types 3856 // that we do for C++ pointers to class types. However, we employ the 3857 // Objective-C pseudo-subtyping relationship used for assignment of 3858 // Objective-C pointer types. 3859 bool FromAssignLeft 3860 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3861 bool FromAssignRight 3862 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3863 bool ToAssignLeft 3864 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3865 bool ToAssignRight 3866 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3867 3868 // A conversion to an a non-id object pointer type or qualified 'id' 3869 // type is better than a conversion to 'id'. 3870 if (ToPtr1->isObjCIdType() && 3871 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3872 return ImplicitConversionSequence::Worse; 3873 if (ToPtr2->isObjCIdType() && 3874 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3875 return ImplicitConversionSequence::Better; 3876 3877 // A conversion to a non-id object pointer type is better than a 3878 // conversion to a qualified 'id' type 3879 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3880 return ImplicitConversionSequence::Worse; 3881 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3882 return ImplicitConversionSequence::Better; 3883 3884 // A conversion to an a non-Class object pointer type or qualified 'Class' 3885 // type is better than a conversion to 'Class'. 3886 if (ToPtr1->isObjCClassType() && 3887 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3888 return ImplicitConversionSequence::Worse; 3889 if (ToPtr2->isObjCClassType() && 3890 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3891 return ImplicitConversionSequence::Better; 3892 3893 // A conversion to a non-Class object pointer type is better than a 3894 // conversion to a qualified 'Class' type. 3895 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3896 return ImplicitConversionSequence::Worse; 3897 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3898 return ImplicitConversionSequence::Better; 3899 3900 // -- "conversion of C* to B* is better than conversion of C* to A*," 3901 if (S.Context.hasSameType(FromType1, FromType2) && 3902 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3903 (ToAssignLeft != ToAssignRight)) 3904 return ToAssignLeft? ImplicitConversionSequence::Worse 3905 : ImplicitConversionSequence::Better; 3906 3907 // -- "conversion of B* to A* is better than conversion of C* to A*," 3908 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3909 (FromAssignLeft != FromAssignRight)) 3910 return FromAssignLeft? ImplicitConversionSequence::Better 3911 : ImplicitConversionSequence::Worse; 3912 } 3913 } 3914 3915 // Ranking of member-pointer types. 3916 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3917 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3918 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3919 const MemberPointerType * FromMemPointer1 = 3920 FromType1->getAs<MemberPointerType>(); 3921 const MemberPointerType * ToMemPointer1 = 3922 ToType1->getAs<MemberPointerType>(); 3923 const MemberPointerType * FromMemPointer2 = 3924 FromType2->getAs<MemberPointerType>(); 3925 const MemberPointerType * ToMemPointer2 = 3926 ToType2->getAs<MemberPointerType>(); 3927 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3928 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3929 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3930 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3931 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3932 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3933 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3934 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3935 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3936 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3937 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3938 return ImplicitConversionSequence::Worse; 3939 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3940 return ImplicitConversionSequence::Better; 3941 } 3942 // conversion of B::* to C::* is better than conversion of A::* to C::* 3943 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3944 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3945 return ImplicitConversionSequence::Better; 3946 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3947 return ImplicitConversionSequence::Worse; 3948 } 3949 } 3950 3951 if (SCS1.Second == ICK_Derived_To_Base) { 3952 // -- conversion of C to B is better than conversion of C to A, 3953 // -- binding of an expression of type C to a reference of type 3954 // B& is better than binding an expression of type C to a 3955 // reference of type A&, 3956 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3957 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3958 if (S.IsDerivedFrom(ToType1, ToType2)) 3959 return ImplicitConversionSequence::Better; 3960 else if (S.IsDerivedFrom(ToType2, ToType1)) 3961 return ImplicitConversionSequence::Worse; 3962 } 3963 3964 // -- conversion of B to A is better than conversion of C to A. 3965 // -- binding of an expression of type B to a reference of type 3966 // A& is better than binding an expression of type C to a 3967 // reference of type A&, 3968 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3969 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3970 if (S.IsDerivedFrom(FromType2, FromType1)) 3971 return ImplicitConversionSequence::Better; 3972 else if (S.IsDerivedFrom(FromType1, FromType2)) 3973 return ImplicitConversionSequence::Worse; 3974 } 3975 } 3976 3977 return ImplicitConversionSequence::Indistinguishable; 3978 } 3979 3980 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3981 /// C++ class. 3982 static bool isTypeValid(QualType T) { 3983 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3984 return !Record->isInvalidDecl(); 3985 3986 return true; 3987 } 3988 3989 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3990 /// determine whether they are reference-related, 3991 /// reference-compatible, reference-compatible with added 3992 /// qualification, or incompatible, for use in C++ initialization by 3993 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3994 /// type, and the first type (T1) is the pointee type of the reference 3995 /// type being initialized. 3996 Sema::ReferenceCompareResult 3997 Sema::CompareReferenceRelationship(SourceLocation Loc, 3998 QualType OrigT1, QualType OrigT2, 3999 bool &DerivedToBase, 4000 bool &ObjCConversion, 4001 bool &ObjCLifetimeConversion) { 4002 assert(!OrigT1->isReferenceType() && 4003 "T1 must be the pointee type of the reference type"); 4004 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4005 4006 QualType T1 = Context.getCanonicalType(OrigT1); 4007 QualType T2 = Context.getCanonicalType(OrigT2); 4008 Qualifiers T1Quals, T2Quals; 4009 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4010 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4011 4012 // C++ [dcl.init.ref]p4: 4013 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4014 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4015 // T1 is a base class of T2. 4016 DerivedToBase = false; 4017 ObjCConversion = false; 4018 ObjCLifetimeConversion = false; 4019 if (UnqualT1 == UnqualT2) { 4020 // Nothing to do. 4021 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 4022 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4023 IsDerivedFrom(UnqualT2, UnqualT1)) 4024 DerivedToBase = true; 4025 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4026 UnqualT2->isObjCObjectOrInterfaceType() && 4027 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4028 ObjCConversion = true; 4029 else 4030 return Ref_Incompatible; 4031 4032 // At this point, we know that T1 and T2 are reference-related (at 4033 // least). 4034 4035 // If the type is an array type, promote the element qualifiers to the type 4036 // for comparison. 4037 if (isa<ArrayType>(T1) && T1Quals) 4038 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4039 if (isa<ArrayType>(T2) && T2Quals) 4040 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4041 4042 // C++ [dcl.init.ref]p4: 4043 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4044 // reference-related to T2 and cv1 is the same cv-qualification 4045 // as, or greater cv-qualification than, cv2. For purposes of 4046 // overload resolution, cases for which cv1 is greater 4047 // cv-qualification than cv2 are identified as 4048 // reference-compatible with added qualification (see 13.3.3.2). 4049 // 4050 // Note that we also require equivalence of Objective-C GC and address-space 4051 // qualifiers when performing these computations, so that e.g., an int in 4052 // address space 1 is not reference-compatible with an int in address 4053 // space 2. 4054 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4055 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4056 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4057 ObjCLifetimeConversion = true; 4058 4059 T1Quals.removeObjCLifetime(); 4060 T2Quals.removeObjCLifetime(); 4061 } 4062 4063 if (T1Quals == T2Quals) 4064 return Ref_Compatible; 4065 else if (T1Quals.compatiblyIncludes(T2Quals)) 4066 return Ref_Compatible_With_Added_Qualification; 4067 else 4068 return Ref_Related; 4069 } 4070 4071 /// \brief Look for a user-defined conversion to an value reference-compatible 4072 /// with DeclType. Return true if something definite is found. 4073 static bool 4074 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4075 QualType DeclType, SourceLocation DeclLoc, 4076 Expr *Init, QualType T2, bool AllowRvalues, 4077 bool AllowExplicit) { 4078 assert(T2->isRecordType() && "Can only find conversions of record types."); 4079 CXXRecordDecl *T2RecordDecl 4080 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4081 4082 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4083 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4084 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4085 NamedDecl *D = *I; 4086 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4087 if (isa<UsingShadowDecl>(D)) 4088 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4089 4090 FunctionTemplateDecl *ConvTemplate 4091 = dyn_cast<FunctionTemplateDecl>(D); 4092 CXXConversionDecl *Conv; 4093 if (ConvTemplate) 4094 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4095 else 4096 Conv = cast<CXXConversionDecl>(D); 4097 4098 // If this is an explicit conversion, and we're not allowed to consider 4099 // explicit conversions, skip it. 4100 if (!AllowExplicit && Conv->isExplicit()) 4101 continue; 4102 4103 if (AllowRvalues) { 4104 bool DerivedToBase = false; 4105 bool ObjCConversion = false; 4106 bool ObjCLifetimeConversion = false; 4107 4108 // If we are initializing an rvalue reference, don't permit conversion 4109 // functions that return lvalues. 4110 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4111 const ReferenceType *RefType 4112 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4113 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4114 continue; 4115 } 4116 4117 if (!ConvTemplate && 4118 S.CompareReferenceRelationship( 4119 DeclLoc, 4120 Conv->getConversionType().getNonReferenceType() 4121 .getUnqualifiedType(), 4122 DeclType.getNonReferenceType().getUnqualifiedType(), 4123 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4124 Sema::Ref_Incompatible) 4125 continue; 4126 } else { 4127 // If the conversion function doesn't return a reference type, 4128 // it can't be considered for this conversion. An rvalue reference 4129 // is only acceptable if its referencee is a function type. 4130 4131 const ReferenceType *RefType = 4132 Conv->getConversionType()->getAs<ReferenceType>(); 4133 if (!RefType || 4134 (!RefType->isLValueReferenceType() && 4135 !RefType->getPointeeType()->isFunctionType())) 4136 continue; 4137 } 4138 4139 if (ConvTemplate) 4140 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4141 Init, DeclType, CandidateSet, 4142 /*AllowObjCConversionOnExplicit=*/false); 4143 else 4144 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4145 DeclType, CandidateSet, 4146 /*AllowObjCConversionOnExplicit=*/false); 4147 } 4148 4149 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4150 4151 OverloadCandidateSet::iterator Best; 4152 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4153 case OR_Success: 4154 // C++ [over.ics.ref]p1: 4155 // 4156 // [...] If the parameter binds directly to the result of 4157 // applying a conversion function to the argument 4158 // expression, the implicit conversion sequence is a 4159 // user-defined conversion sequence (13.3.3.1.2), with the 4160 // second standard conversion sequence either an identity 4161 // conversion or, if the conversion function returns an 4162 // entity of a type that is a derived class of the parameter 4163 // type, a derived-to-base Conversion. 4164 if (!Best->FinalConversion.DirectBinding) 4165 return false; 4166 4167 ICS.setUserDefined(); 4168 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4169 ICS.UserDefined.After = Best->FinalConversion; 4170 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4171 ICS.UserDefined.ConversionFunction = Best->Function; 4172 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4173 ICS.UserDefined.EllipsisConversion = false; 4174 assert(ICS.UserDefined.After.ReferenceBinding && 4175 ICS.UserDefined.After.DirectBinding && 4176 "Expected a direct reference binding!"); 4177 return true; 4178 4179 case OR_Ambiguous: 4180 ICS.setAmbiguous(); 4181 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4182 Cand != CandidateSet.end(); ++Cand) 4183 if (Cand->Viable) 4184 ICS.Ambiguous.addConversion(Cand->Function); 4185 return true; 4186 4187 case OR_No_Viable_Function: 4188 case OR_Deleted: 4189 // There was no suitable conversion, or we found a deleted 4190 // conversion; continue with other checks. 4191 return false; 4192 } 4193 4194 llvm_unreachable("Invalid OverloadResult!"); 4195 } 4196 4197 /// \brief Compute an implicit conversion sequence for reference 4198 /// initialization. 4199 static ImplicitConversionSequence 4200 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4201 SourceLocation DeclLoc, 4202 bool SuppressUserConversions, 4203 bool AllowExplicit) { 4204 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4205 4206 // Most paths end in a failed conversion. 4207 ImplicitConversionSequence ICS; 4208 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4209 4210 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4211 QualType T2 = Init->getType(); 4212 4213 // If the initializer is the address of an overloaded function, try 4214 // to resolve the overloaded function. If all goes well, T2 is the 4215 // type of the resulting function. 4216 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4217 DeclAccessPair Found; 4218 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4219 false, Found)) 4220 T2 = Fn->getType(); 4221 } 4222 4223 // Compute some basic properties of the types and the initializer. 4224 bool isRValRef = DeclType->isRValueReferenceType(); 4225 bool DerivedToBase = false; 4226 bool ObjCConversion = false; 4227 bool ObjCLifetimeConversion = false; 4228 Expr::Classification InitCategory = Init->Classify(S.Context); 4229 Sema::ReferenceCompareResult RefRelationship 4230 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4231 ObjCConversion, ObjCLifetimeConversion); 4232 4233 4234 // C++0x [dcl.init.ref]p5: 4235 // A reference to type "cv1 T1" is initialized by an expression 4236 // of type "cv2 T2" as follows: 4237 4238 // -- If reference is an lvalue reference and the initializer expression 4239 if (!isRValRef) { 4240 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4241 // reference-compatible with "cv2 T2," or 4242 // 4243 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4244 if (InitCategory.isLValue() && 4245 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4246 // C++ [over.ics.ref]p1: 4247 // When a parameter of reference type binds directly (8.5.3) 4248 // to an argument expression, the implicit conversion sequence 4249 // is the identity conversion, unless the argument expression 4250 // has a type that is a derived class of the parameter type, 4251 // in which case the implicit conversion sequence is a 4252 // derived-to-base Conversion (13.3.3.1). 4253 ICS.setStandard(); 4254 ICS.Standard.First = ICK_Identity; 4255 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4256 : ObjCConversion? ICK_Compatible_Conversion 4257 : ICK_Identity; 4258 ICS.Standard.Third = ICK_Identity; 4259 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4260 ICS.Standard.setToType(0, T2); 4261 ICS.Standard.setToType(1, T1); 4262 ICS.Standard.setToType(2, T1); 4263 ICS.Standard.ReferenceBinding = true; 4264 ICS.Standard.DirectBinding = true; 4265 ICS.Standard.IsLvalueReference = !isRValRef; 4266 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4267 ICS.Standard.BindsToRvalue = false; 4268 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4269 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4270 ICS.Standard.CopyConstructor = nullptr; 4271 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4272 4273 // Nothing more to do: the inaccessibility/ambiguity check for 4274 // derived-to-base conversions is suppressed when we're 4275 // computing the implicit conversion sequence (C++ 4276 // [over.best.ics]p2). 4277 return ICS; 4278 } 4279 4280 // -- has a class type (i.e., T2 is a class type), where T1 is 4281 // not reference-related to T2, and can be implicitly 4282 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4283 // is reference-compatible with "cv3 T3" 92) (this 4284 // conversion is selected by enumerating the applicable 4285 // conversion functions (13.3.1.6) and choosing the best 4286 // one through overload resolution (13.3)), 4287 if (!SuppressUserConversions && T2->isRecordType() && 4288 !S.RequireCompleteType(DeclLoc, T2, 0) && 4289 RefRelationship == Sema::Ref_Incompatible) { 4290 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4291 Init, T2, /*AllowRvalues=*/false, 4292 AllowExplicit)) 4293 return ICS; 4294 } 4295 } 4296 4297 // -- Otherwise, the reference shall be an lvalue reference to a 4298 // non-volatile const type (i.e., cv1 shall be const), or the reference 4299 // shall be an rvalue reference. 4300 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4301 return ICS; 4302 4303 // -- If the initializer expression 4304 // 4305 // -- is an xvalue, class prvalue, array prvalue or function 4306 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4307 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4308 (InitCategory.isXValue() || 4309 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4310 (InitCategory.isLValue() && T2->isFunctionType()))) { 4311 ICS.setStandard(); 4312 ICS.Standard.First = ICK_Identity; 4313 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4314 : ObjCConversion? ICK_Compatible_Conversion 4315 : ICK_Identity; 4316 ICS.Standard.Third = ICK_Identity; 4317 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4318 ICS.Standard.setToType(0, T2); 4319 ICS.Standard.setToType(1, T1); 4320 ICS.Standard.setToType(2, T1); 4321 ICS.Standard.ReferenceBinding = true; 4322 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4323 // binding unless we're binding to a class prvalue. 4324 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4325 // allow the use of rvalue references in C++98/03 for the benefit of 4326 // standard library implementors; therefore, we need the xvalue check here. 4327 ICS.Standard.DirectBinding = 4328 S.getLangOpts().CPlusPlus11 || 4329 !(InitCategory.isPRValue() || T2->isRecordType()); 4330 ICS.Standard.IsLvalueReference = !isRValRef; 4331 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4332 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4333 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4334 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4335 ICS.Standard.CopyConstructor = nullptr; 4336 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4337 return ICS; 4338 } 4339 4340 // -- has a class type (i.e., T2 is a class type), where T1 is not 4341 // reference-related to T2, and can be implicitly converted to 4342 // an xvalue, class prvalue, or function lvalue of type 4343 // "cv3 T3", where "cv1 T1" is reference-compatible with 4344 // "cv3 T3", 4345 // 4346 // then the reference is bound to the value of the initializer 4347 // expression in the first case and to the result of the conversion 4348 // in the second case (or, in either case, to an appropriate base 4349 // class subobject). 4350 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4351 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4352 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4353 Init, T2, /*AllowRvalues=*/true, 4354 AllowExplicit)) { 4355 // In the second case, if the reference is an rvalue reference 4356 // and the second standard conversion sequence of the 4357 // user-defined conversion sequence includes an lvalue-to-rvalue 4358 // conversion, the program is ill-formed. 4359 if (ICS.isUserDefined() && isRValRef && 4360 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4361 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4362 4363 return ICS; 4364 } 4365 4366 // A temporary of function type cannot be created; don't even try. 4367 if (T1->isFunctionType()) 4368 return ICS; 4369 4370 // -- Otherwise, a temporary of type "cv1 T1" is created and 4371 // initialized from the initializer expression using the 4372 // rules for a non-reference copy initialization (8.5). The 4373 // reference is then bound to the temporary. If T1 is 4374 // reference-related to T2, cv1 must be the same 4375 // cv-qualification as, or greater cv-qualification than, 4376 // cv2; otherwise, the program is ill-formed. 4377 if (RefRelationship == Sema::Ref_Related) { 4378 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4379 // we would be reference-compatible or reference-compatible with 4380 // added qualification. But that wasn't the case, so the reference 4381 // initialization fails. 4382 // 4383 // Note that we only want to check address spaces and cvr-qualifiers here. 4384 // ObjC GC and lifetime qualifiers aren't important. 4385 Qualifiers T1Quals = T1.getQualifiers(); 4386 Qualifiers T2Quals = T2.getQualifiers(); 4387 T1Quals.removeObjCGCAttr(); 4388 T1Quals.removeObjCLifetime(); 4389 T2Quals.removeObjCGCAttr(); 4390 T2Quals.removeObjCLifetime(); 4391 if (!T1Quals.compatiblyIncludes(T2Quals)) 4392 return ICS; 4393 } 4394 4395 // If at least one of the types is a class type, the types are not 4396 // related, and we aren't allowed any user conversions, the 4397 // reference binding fails. This case is important for breaking 4398 // recursion, since TryImplicitConversion below will attempt to 4399 // create a temporary through the use of a copy constructor. 4400 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4401 (T1->isRecordType() || T2->isRecordType())) 4402 return ICS; 4403 4404 // If T1 is reference-related to T2 and the reference is an rvalue 4405 // reference, the initializer expression shall not be an lvalue. 4406 if (RefRelationship >= Sema::Ref_Related && 4407 isRValRef && Init->Classify(S.Context).isLValue()) 4408 return ICS; 4409 4410 // C++ [over.ics.ref]p2: 4411 // When a parameter of reference type is not bound directly to 4412 // an argument expression, the conversion sequence is the one 4413 // required to convert the argument expression to the 4414 // underlying type of the reference according to 4415 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4416 // to copy-initializing a temporary of the underlying type with 4417 // the argument expression. Any difference in top-level 4418 // cv-qualification is subsumed by the initialization itself 4419 // and does not constitute a conversion. 4420 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4421 /*AllowExplicit=*/false, 4422 /*InOverloadResolution=*/false, 4423 /*CStyle=*/false, 4424 /*AllowObjCWritebackConversion=*/false, 4425 /*AllowObjCConversionOnExplicit=*/false); 4426 4427 // Of course, that's still a reference binding. 4428 if (ICS.isStandard()) { 4429 ICS.Standard.ReferenceBinding = true; 4430 ICS.Standard.IsLvalueReference = !isRValRef; 4431 ICS.Standard.BindsToFunctionLvalue = false; 4432 ICS.Standard.BindsToRvalue = true; 4433 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4434 ICS.Standard.ObjCLifetimeConversionBinding = false; 4435 } else if (ICS.isUserDefined()) { 4436 const ReferenceType *LValRefType = 4437 ICS.UserDefined.ConversionFunction->getReturnType() 4438 ->getAs<LValueReferenceType>(); 4439 4440 // C++ [over.ics.ref]p3: 4441 // Except for an implicit object parameter, for which see 13.3.1, a 4442 // standard conversion sequence cannot be formed if it requires [...] 4443 // binding an rvalue reference to an lvalue other than a function 4444 // lvalue. 4445 // Note that the function case is not possible here. 4446 if (DeclType->isRValueReferenceType() && LValRefType) { 4447 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4448 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4449 // reference to an rvalue! 4450 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4451 return ICS; 4452 } 4453 4454 ICS.UserDefined.Before.setAsIdentityConversion(); 4455 ICS.UserDefined.After.ReferenceBinding = true; 4456 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4457 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4458 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4459 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4460 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4461 } 4462 4463 return ICS; 4464 } 4465 4466 static ImplicitConversionSequence 4467 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4468 bool SuppressUserConversions, 4469 bool InOverloadResolution, 4470 bool AllowObjCWritebackConversion, 4471 bool AllowExplicit = false); 4472 4473 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4474 /// initializer list From. 4475 static ImplicitConversionSequence 4476 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4477 bool SuppressUserConversions, 4478 bool InOverloadResolution, 4479 bool AllowObjCWritebackConversion) { 4480 // C++11 [over.ics.list]p1: 4481 // When an argument is an initializer list, it is not an expression and 4482 // special rules apply for converting it to a parameter type. 4483 4484 ImplicitConversionSequence Result; 4485 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4486 4487 // We need a complete type for what follows. Incomplete types can never be 4488 // initialized from init lists. 4489 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4490 return Result; 4491 4492 // Per DR1467: 4493 // If the parameter type is a class X and the initializer list has a single 4494 // element of type cv U, where U is X or a class derived from X, the 4495 // implicit conversion sequence is the one required to convert the element 4496 // to the parameter type. 4497 // 4498 // Otherwise, if the parameter type is a character array [... ] 4499 // and the initializer list has a single element that is an 4500 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4501 // implicit conversion sequence is the identity conversion. 4502 if (From->getNumInits() == 1) { 4503 if (ToType->isRecordType()) { 4504 QualType InitType = From->getInit(0)->getType(); 4505 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4506 S.IsDerivedFrom(InitType, ToType)) 4507 return TryCopyInitialization(S, From->getInit(0), ToType, 4508 SuppressUserConversions, 4509 InOverloadResolution, 4510 AllowObjCWritebackConversion); 4511 } 4512 // FIXME: Check the other conditions here: array of character type, 4513 // initializer is a string literal. 4514 if (ToType->isArrayType()) { 4515 InitializedEntity Entity = 4516 InitializedEntity::InitializeParameter(S.Context, ToType, 4517 /*Consumed=*/false); 4518 if (S.CanPerformCopyInitialization(Entity, From)) { 4519 Result.setStandard(); 4520 Result.Standard.setAsIdentityConversion(); 4521 Result.Standard.setFromType(ToType); 4522 Result.Standard.setAllToTypes(ToType); 4523 return Result; 4524 } 4525 } 4526 } 4527 4528 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4529 // C++11 [over.ics.list]p2: 4530 // If the parameter type is std::initializer_list<X> or "array of X" and 4531 // all the elements can be implicitly converted to X, the implicit 4532 // conversion sequence is the worst conversion necessary to convert an 4533 // element of the list to X. 4534 // 4535 // C++14 [over.ics.list]p3: 4536 // Otherwise, if the parameter type is "array of N X", if the initializer 4537 // list has exactly N elements or if it has fewer than N elements and X is 4538 // default-constructible, and if all the elements of the initializer list 4539 // can be implicitly converted to X, the implicit conversion sequence is 4540 // the worst conversion necessary to convert an element of the list to X. 4541 // 4542 // FIXME: We're missing a lot of these checks. 4543 bool toStdInitializerList = false; 4544 QualType X; 4545 if (ToType->isArrayType()) 4546 X = S.Context.getAsArrayType(ToType)->getElementType(); 4547 else 4548 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4549 if (!X.isNull()) { 4550 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4551 Expr *Init = From->getInit(i); 4552 ImplicitConversionSequence ICS = 4553 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4554 InOverloadResolution, 4555 AllowObjCWritebackConversion); 4556 // If a single element isn't convertible, fail. 4557 if (ICS.isBad()) { 4558 Result = ICS; 4559 break; 4560 } 4561 // Otherwise, look for the worst conversion. 4562 if (Result.isBad() || 4563 CompareImplicitConversionSequences(S, ICS, Result) == 4564 ImplicitConversionSequence::Worse) 4565 Result = ICS; 4566 } 4567 4568 // For an empty list, we won't have computed any conversion sequence. 4569 // Introduce the identity conversion sequence. 4570 if (From->getNumInits() == 0) { 4571 Result.setStandard(); 4572 Result.Standard.setAsIdentityConversion(); 4573 Result.Standard.setFromType(ToType); 4574 Result.Standard.setAllToTypes(ToType); 4575 } 4576 4577 Result.setStdInitializerListElement(toStdInitializerList); 4578 return Result; 4579 } 4580 4581 // C++14 [over.ics.list]p4: 4582 // C++11 [over.ics.list]p3: 4583 // Otherwise, if the parameter is a non-aggregate class X and overload 4584 // resolution chooses a single best constructor [...] the implicit 4585 // conversion sequence is a user-defined conversion sequence. If multiple 4586 // constructors are viable but none is better than the others, the 4587 // implicit conversion sequence is a user-defined conversion sequence. 4588 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4589 // This function can deal with initializer lists. 4590 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4591 /*AllowExplicit=*/false, 4592 InOverloadResolution, /*CStyle=*/false, 4593 AllowObjCWritebackConversion, 4594 /*AllowObjCConversionOnExplicit=*/false); 4595 } 4596 4597 // C++14 [over.ics.list]p5: 4598 // C++11 [over.ics.list]p4: 4599 // Otherwise, if the parameter has an aggregate type which can be 4600 // initialized from the initializer list [...] the implicit conversion 4601 // sequence is a user-defined conversion sequence. 4602 if (ToType->isAggregateType()) { 4603 // Type is an aggregate, argument is an init list. At this point it comes 4604 // down to checking whether the initialization works. 4605 // FIXME: Find out whether this parameter is consumed or not. 4606 InitializedEntity Entity = 4607 InitializedEntity::InitializeParameter(S.Context, ToType, 4608 /*Consumed=*/false); 4609 if (S.CanPerformCopyInitialization(Entity, From)) { 4610 Result.setUserDefined(); 4611 Result.UserDefined.Before.setAsIdentityConversion(); 4612 // Initializer lists don't have a type. 4613 Result.UserDefined.Before.setFromType(QualType()); 4614 Result.UserDefined.Before.setAllToTypes(QualType()); 4615 4616 Result.UserDefined.After.setAsIdentityConversion(); 4617 Result.UserDefined.After.setFromType(ToType); 4618 Result.UserDefined.After.setAllToTypes(ToType); 4619 Result.UserDefined.ConversionFunction = nullptr; 4620 } 4621 return Result; 4622 } 4623 4624 // C++14 [over.ics.list]p6: 4625 // C++11 [over.ics.list]p5: 4626 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4627 if (ToType->isReferenceType()) { 4628 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4629 // mention initializer lists in any way. So we go by what list- 4630 // initialization would do and try to extrapolate from that. 4631 4632 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4633 4634 // If the initializer list has a single element that is reference-related 4635 // to the parameter type, we initialize the reference from that. 4636 if (From->getNumInits() == 1) { 4637 Expr *Init = From->getInit(0); 4638 4639 QualType T2 = Init->getType(); 4640 4641 // If the initializer is the address of an overloaded function, try 4642 // to resolve the overloaded function. If all goes well, T2 is the 4643 // type of the resulting function. 4644 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4645 DeclAccessPair Found; 4646 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4647 Init, ToType, false, Found)) 4648 T2 = Fn->getType(); 4649 } 4650 4651 // Compute some basic properties of the types and the initializer. 4652 bool dummy1 = false; 4653 bool dummy2 = false; 4654 bool dummy3 = false; 4655 Sema::ReferenceCompareResult RefRelationship 4656 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4657 dummy2, dummy3); 4658 4659 if (RefRelationship >= Sema::Ref_Related) { 4660 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4661 SuppressUserConversions, 4662 /*AllowExplicit=*/false); 4663 } 4664 } 4665 4666 // Otherwise, we bind the reference to a temporary created from the 4667 // initializer list. 4668 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4669 InOverloadResolution, 4670 AllowObjCWritebackConversion); 4671 if (Result.isFailure()) 4672 return Result; 4673 assert(!Result.isEllipsis() && 4674 "Sub-initialization cannot result in ellipsis conversion."); 4675 4676 // Can we even bind to a temporary? 4677 if (ToType->isRValueReferenceType() || 4678 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4679 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4680 Result.UserDefined.After; 4681 SCS.ReferenceBinding = true; 4682 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4683 SCS.BindsToRvalue = true; 4684 SCS.BindsToFunctionLvalue = false; 4685 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4686 SCS.ObjCLifetimeConversionBinding = false; 4687 } else 4688 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4689 From, ToType); 4690 return Result; 4691 } 4692 4693 // C++14 [over.ics.list]p7: 4694 // C++11 [over.ics.list]p6: 4695 // Otherwise, if the parameter type is not a class: 4696 if (!ToType->isRecordType()) { 4697 // - if the initializer list has one element that is not itself an 4698 // initializer list, the implicit conversion sequence is the one 4699 // required to convert the element to the parameter type. 4700 unsigned NumInits = From->getNumInits(); 4701 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4702 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4703 SuppressUserConversions, 4704 InOverloadResolution, 4705 AllowObjCWritebackConversion); 4706 // - if the initializer list has no elements, the implicit conversion 4707 // sequence is the identity conversion. 4708 else if (NumInits == 0) { 4709 Result.setStandard(); 4710 Result.Standard.setAsIdentityConversion(); 4711 Result.Standard.setFromType(ToType); 4712 Result.Standard.setAllToTypes(ToType); 4713 } 4714 return Result; 4715 } 4716 4717 // C++14 [over.ics.list]p8: 4718 // C++11 [over.ics.list]p7: 4719 // In all cases other than those enumerated above, no conversion is possible 4720 return Result; 4721 } 4722 4723 /// TryCopyInitialization - Try to copy-initialize a value of type 4724 /// ToType from the expression From. Return the implicit conversion 4725 /// sequence required to pass this argument, which may be a bad 4726 /// conversion sequence (meaning that the argument cannot be passed to 4727 /// a parameter of this type). If @p SuppressUserConversions, then we 4728 /// do not permit any user-defined conversion sequences. 4729 static ImplicitConversionSequence 4730 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4731 bool SuppressUserConversions, 4732 bool InOverloadResolution, 4733 bool AllowObjCWritebackConversion, 4734 bool AllowExplicit) { 4735 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4736 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4737 InOverloadResolution,AllowObjCWritebackConversion); 4738 4739 if (ToType->isReferenceType()) 4740 return TryReferenceInit(S, From, ToType, 4741 /*FIXME:*/From->getLocStart(), 4742 SuppressUserConversions, 4743 AllowExplicit); 4744 4745 return TryImplicitConversion(S, From, ToType, 4746 SuppressUserConversions, 4747 /*AllowExplicit=*/false, 4748 InOverloadResolution, 4749 /*CStyle=*/false, 4750 AllowObjCWritebackConversion, 4751 /*AllowObjCConversionOnExplicit=*/false); 4752 } 4753 4754 static bool TryCopyInitialization(const CanQualType FromQTy, 4755 const CanQualType ToQTy, 4756 Sema &S, 4757 SourceLocation Loc, 4758 ExprValueKind FromVK) { 4759 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4760 ImplicitConversionSequence ICS = 4761 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4762 4763 return !ICS.isBad(); 4764 } 4765 4766 /// TryObjectArgumentInitialization - Try to initialize the object 4767 /// parameter of the given member function (@c Method) from the 4768 /// expression @p From. 4769 static ImplicitConversionSequence 4770 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4771 Expr::Classification FromClassification, 4772 CXXMethodDecl *Method, 4773 CXXRecordDecl *ActingContext) { 4774 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4775 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4776 // const volatile object. 4777 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4778 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4779 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4780 4781 // Set up the conversion sequence as a "bad" conversion, to allow us 4782 // to exit early. 4783 ImplicitConversionSequence ICS; 4784 4785 // We need to have an object of class type. 4786 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4787 FromType = PT->getPointeeType(); 4788 4789 // When we had a pointer, it's implicitly dereferenced, so we 4790 // better have an lvalue. 4791 assert(FromClassification.isLValue()); 4792 } 4793 4794 assert(FromType->isRecordType()); 4795 4796 // C++0x [over.match.funcs]p4: 4797 // For non-static member functions, the type of the implicit object 4798 // parameter is 4799 // 4800 // - "lvalue reference to cv X" for functions declared without a 4801 // ref-qualifier or with the & ref-qualifier 4802 // - "rvalue reference to cv X" for functions declared with the && 4803 // ref-qualifier 4804 // 4805 // where X is the class of which the function is a member and cv is the 4806 // cv-qualification on the member function declaration. 4807 // 4808 // However, when finding an implicit conversion sequence for the argument, we 4809 // are not allowed to create temporaries or perform user-defined conversions 4810 // (C++ [over.match.funcs]p5). We perform a simplified version of 4811 // reference binding here, that allows class rvalues to bind to 4812 // non-constant references. 4813 4814 // First check the qualifiers. 4815 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4816 if (ImplicitParamType.getCVRQualifiers() 4817 != FromTypeCanon.getLocalCVRQualifiers() && 4818 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4819 ICS.setBad(BadConversionSequence::bad_qualifiers, 4820 FromType, ImplicitParamType); 4821 return ICS; 4822 } 4823 4824 // Check that we have either the same type or a derived type. It 4825 // affects the conversion rank. 4826 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4827 ImplicitConversionKind SecondKind; 4828 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4829 SecondKind = ICK_Identity; 4830 } else if (S.IsDerivedFrom(FromType, ClassType)) 4831 SecondKind = ICK_Derived_To_Base; 4832 else { 4833 ICS.setBad(BadConversionSequence::unrelated_class, 4834 FromType, ImplicitParamType); 4835 return ICS; 4836 } 4837 4838 // Check the ref-qualifier. 4839 switch (Method->getRefQualifier()) { 4840 case RQ_None: 4841 // Do nothing; we don't care about lvalueness or rvalueness. 4842 break; 4843 4844 case RQ_LValue: 4845 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4846 // non-const lvalue reference cannot bind to an rvalue 4847 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4848 ImplicitParamType); 4849 return ICS; 4850 } 4851 break; 4852 4853 case RQ_RValue: 4854 if (!FromClassification.isRValue()) { 4855 // rvalue reference cannot bind to an lvalue 4856 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4857 ImplicitParamType); 4858 return ICS; 4859 } 4860 break; 4861 } 4862 4863 // Success. Mark this as a reference binding. 4864 ICS.setStandard(); 4865 ICS.Standard.setAsIdentityConversion(); 4866 ICS.Standard.Second = SecondKind; 4867 ICS.Standard.setFromType(FromType); 4868 ICS.Standard.setAllToTypes(ImplicitParamType); 4869 ICS.Standard.ReferenceBinding = true; 4870 ICS.Standard.DirectBinding = true; 4871 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4872 ICS.Standard.BindsToFunctionLvalue = false; 4873 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4874 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4875 = (Method->getRefQualifier() == RQ_None); 4876 return ICS; 4877 } 4878 4879 /// PerformObjectArgumentInitialization - Perform initialization of 4880 /// the implicit object parameter for the given Method with the given 4881 /// expression. 4882 ExprResult 4883 Sema::PerformObjectArgumentInitialization(Expr *From, 4884 NestedNameSpecifier *Qualifier, 4885 NamedDecl *FoundDecl, 4886 CXXMethodDecl *Method) { 4887 QualType FromRecordType, DestType; 4888 QualType ImplicitParamRecordType = 4889 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4890 4891 Expr::Classification FromClassification; 4892 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4893 FromRecordType = PT->getPointeeType(); 4894 DestType = Method->getThisType(Context); 4895 FromClassification = Expr::Classification::makeSimpleLValue(); 4896 } else { 4897 FromRecordType = From->getType(); 4898 DestType = ImplicitParamRecordType; 4899 FromClassification = From->Classify(Context); 4900 } 4901 4902 // Note that we always use the true parent context when performing 4903 // the actual argument initialization. 4904 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4905 *this, From->getType(), FromClassification, Method, Method->getParent()); 4906 if (ICS.isBad()) { 4907 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4908 Qualifiers FromQs = FromRecordType.getQualifiers(); 4909 Qualifiers ToQs = DestType.getQualifiers(); 4910 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4911 if (CVR) { 4912 Diag(From->getLocStart(), 4913 diag::err_member_function_call_bad_cvr) 4914 << Method->getDeclName() << FromRecordType << (CVR - 1) 4915 << From->getSourceRange(); 4916 Diag(Method->getLocation(), diag::note_previous_decl) 4917 << Method->getDeclName(); 4918 return ExprError(); 4919 } 4920 } 4921 4922 return Diag(From->getLocStart(), 4923 diag::err_implicit_object_parameter_init) 4924 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4925 } 4926 4927 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4928 ExprResult FromRes = 4929 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4930 if (FromRes.isInvalid()) 4931 return ExprError(); 4932 From = FromRes.get(); 4933 } 4934 4935 if (!Context.hasSameType(From->getType(), DestType)) 4936 From = ImpCastExprToType(From, DestType, CK_NoOp, 4937 From->getValueKind()).get(); 4938 return From; 4939 } 4940 4941 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4942 /// expression From to bool (C++0x [conv]p3). 4943 static ImplicitConversionSequence 4944 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4945 return TryImplicitConversion(S, From, S.Context.BoolTy, 4946 /*SuppressUserConversions=*/false, 4947 /*AllowExplicit=*/true, 4948 /*InOverloadResolution=*/false, 4949 /*CStyle=*/false, 4950 /*AllowObjCWritebackConversion=*/false, 4951 /*AllowObjCConversionOnExplicit=*/false); 4952 } 4953 4954 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4955 /// of the expression From to bool (C++0x [conv]p3). 4956 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4957 if (checkPlaceholderForOverload(*this, From)) 4958 return ExprError(); 4959 4960 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4961 if (!ICS.isBad()) 4962 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4963 4964 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4965 return Diag(From->getLocStart(), 4966 diag::err_typecheck_bool_condition) 4967 << From->getType() << From->getSourceRange(); 4968 return ExprError(); 4969 } 4970 4971 /// Check that the specified conversion is permitted in a converted constant 4972 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4973 /// is acceptable. 4974 static bool CheckConvertedConstantConversions(Sema &S, 4975 StandardConversionSequence &SCS) { 4976 // Since we know that the target type is an integral or unscoped enumeration 4977 // type, most conversion kinds are impossible. All possible First and Third 4978 // conversions are fine. 4979 switch (SCS.Second) { 4980 case ICK_Identity: 4981 case ICK_NoReturn_Adjustment: 4982 case ICK_Integral_Promotion: 4983 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 4984 return true; 4985 4986 case ICK_Boolean_Conversion: 4987 // Conversion from an integral or unscoped enumeration type to bool is 4988 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 4989 // conversion, so we allow it in a converted constant expression. 4990 // 4991 // FIXME: Per core issue 1407, we should not allow this, but that breaks 4992 // a lot of popular code. We should at least add a warning for this 4993 // (non-conforming) extension. 4994 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4995 SCS.getToType(2)->isBooleanType(); 4996 4997 case ICK_Pointer_Conversion: 4998 case ICK_Pointer_Member: 4999 // C++1z: null pointer conversions and null member pointer conversions are 5000 // only permitted if the source type is std::nullptr_t. 5001 return SCS.getFromType()->isNullPtrType(); 5002 5003 case ICK_Floating_Promotion: 5004 case ICK_Complex_Promotion: 5005 case ICK_Floating_Conversion: 5006 case ICK_Complex_Conversion: 5007 case ICK_Floating_Integral: 5008 case ICK_Compatible_Conversion: 5009 case ICK_Derived_To_Base: 5010 case ICK_Vector_Conversion: 5011 case ICK_Vector_Splat: 5012 case ICK_Complex_Real: 5013 case ICK_Block_Pointer_Conversion: 5014 case ICK_TransparentUnionConversion: 5015 case ICK_Writeback_Conversion: 5016 case ICK_Zero_Event_Conversion: 5017 case ICK_C_Only_Conversion: 5018 return false; 5019 5020 case ICK_Lvalue_To_Rvalue: 5021 case ICK_Array_To_Pointer: 5022 case ICK_Function_To_Pointer: 5023 llvm_unreachable("found a first conversion kind in Second"); 5024 5025 case ICK_Qualification: 5026 llvm_unreachable("found a third conversion kind in Second"); 5027 5028 case ICK_Num_Conversion_Kinds: 5029 break; 5030 } 5031 5032 llvm_unreachable("unknown conversion kind"); 5033 } 5034 5035 /// CheckConvertedConstantExpression - Check that the expression From is a 5036 /// converted constant expression of type T, perform the conversion and produce 5037 /// the converted expression, per C++11 [expr.const]p3. 5038 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5039 QualType T, APValue &Value, 5040 Sema::CCEKind CCE, 5041 bool RequireInt) { 5042 assert(S.getLangOpts().CPlusPlus11 && 5043 "converted constant expression outside C++11"); 5044 5045 if (checkPlaceholderForOverload(S, From)) 5046 return ExprError(); 5047 5048 // C++1z [expr.const]p3: 5049 // A converted constant expression of type T is an expression, 5050 // implicitly converted to type T, where the converted 5051 // expression is a constant expression and the implicit conversion 5052 // sequence contains only [... list of conversions ...]. 5053 ImplicitConversionSequence ICS = 5054 TryCopyInitialization(S, From, T, 5055 /*SuppressUserConversions=*/false, 5056 /*InOverloadResolution=*/false, 5057 /*AllowObjcWritebackConversion=*/false, 5058 /*AllowExplicit=*/false); 5059 StandardConversionSequence *SCS = nullptr; 5060 switch (ICS.getKind()) { 5061 case ImplicitConversionSequence::StandardConversion: 5062 SCS = &ICS.Standard; 5063 break; 5064 case ImplicitConversionSequence::UserDefinedConversion: 5065 // We are converting to a non-class type, so the Before sequence 5066 // must be trivial. 5067 SCS = &ICS.UserDefined.After; 5068 break; 5069 case ImplicitConversionSequence::AmbiguousConversion: 5070 case ImplicitConversionSequence::BadConversion: 5071 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5072 return S.Diag(From->getLocStart(), 5073 diag::err_typecheck_converted_constant_expression) 5074 << From->getType() << From->getSourceRange() << T; 5075 return ExprError(); 5076 5077 case ImplicitConversionSequence::EllipsisConversion: 5078 llvm_unreachable("ellipsis conversion in converted constant expression"); 5079 } 5080 5081 // Check that we would only use permitted conversions. 5082 if (!CheckConvertedConstantConversions(S, *SCS)) { 5083 return S.Diag(From->getLocStart(), 5084 diag::err_typecheck_converted_constant_expression_disallowed) 5085 << From->getType() << From->getSourceRange() << T; 5086 } 5087 // [...] and where the reference binding (if any) binds directly. 5088 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5089 return S.Diag(From->getLocStart(), 5090 diag::err_typecheck_converted_constant_expression_indirect) 5091 << From->getType() << From->getSourceRange() << T; 5092 } 5093 5094 ExprResult Result = 5095 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5096 if (Result.isInvalid()) 5097 return Result; 5098 5099 // Check for a narrowing implicit conversion. 5100 APValue PreNarrowingValue; 5101 QualType PreNarrowingType; 5102 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5103 PreNarrowingType)) { 5104 case NK_Variable_Narrowing: 5105 // Implicit conversion to a narrower type, and the value is not a constant 5106 // expression. We'll diagnose this in a moment. 5107 case NK_Not_Narrowing: 5108 break; 5109 5110 case NK_Constant_Narrowing: 5111 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5112 << CCE << /*Constant*/1 5113 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5114 break; 5115 5116 case NK_Type_Narrowing: 5117 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5118 << CCE << /*Constant*/0 << From->getType() << T; 5119 break; 5120 } 5121 5122 // Check the expression is a constant expression. 5123 SmallVector<PartialDiagnosticAt, 8> Notes; 5124 Expr::EvalResult Eval; 5125 Eval.Diag = &Notes; 5126 5127 if ((T->isReferenceType() 5128 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5129 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5130 (RequireInt && !Eval.Val.isInt())) { 5131 // The expression can't be folded, so we can't keep it at this position in 5132 // the AST. 5133 Result = ExprError(); 5134 } else { 5135 Value = Eval.Val; 5136 5137 if (Notes.empty()) { 5138 // It's a constant expression. 5139 return Result; 5140 } 5141 } 5142 5143 // It's not a constant expression. Produce an appropriate diagnostic. 5144 if (Notes.size() == 1 && 5145 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5146 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5147 else { 5148 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5149 << CCE << From->getSourceRange(); 5150 for (unsigned I = 0; I < Notes.size(); ++I) 5151 S.Diag(Notes[I].first, Notes[I].second); 5152 } 5153 return ExprError(); 5154 } 5155 5156 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5157 APValue &Value, CCEKind CCE) { 5158 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5159 } 5160 5161 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5162 llvm::APSInt &Value, 5163 CCEKind CCE) { 5164 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5165 5166 APValue V; 5167 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5168 if (!R.isInvalid()) 5169 Value = V.getInt(); 5170 return R; 5171 } 5172 5173 5174 /// dropPointerConversions - If the given standard conversion sequence 5175 /// involves any pointer conversions, remove them. This may change 5176 /// the result type of the conversion sequence. 5177 static void dropPointerConversion(StandardConversionSequence &SCS) { 5178 if (SCS.Second == ICK_Pointer_Conversion) { 5179 SCS.Second = ICK_Identity; 5180 SCS.Third = ICK_Identity; 5181 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5182 } 5183 } 5184 5185 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5186 /// convert the expression From to an Objective-C pointer type. 5187 static ImplicitConversionSequence 5188 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5189 // Do an implicit conversion to 'id'. 5190 QualType Ty = S.Context.getObjCIdType(); 5191 ImplicitConversionSequence ICS 5192 = TryImplicitConversion(S, From, Ty, 5193 // FIXME: Are these flags correct? 5194 /*SuppressUserConversions=*/false, 5195 /*AllowExplicit=*/true, 5196 /*InOverloadResolution=*/false, 5197 /*CStyle=*/false, 5198 /*AllowObjCWritebackConversion=*/false, 5199 /*AllowObjCConversionOnExplicit=*/true); 5200 5201 // Strip off any final conversions to 'id'. 5202 switch (ICS.getKind()) { 5203 case ImplicitConversionSequence::BadConversion: 5204 case ImplicitConversionSequence::AmbiguousConversion: 5205 case ImplicitConversionSequence::EllipsisConversion: 5206 break; 5207 5208 case ImplicitConversionSequence::UserDefinedConversion: 5209 dropPointerConversion(ICS.UserDefined.After); 5210 break; 5211 5212 case ImplicitConversionSequence::StandardConversion: 5213 dropPointerConversion(ICS.Standard); 5214 break; 5215 } 5216 5217 return ICS; 5218 } 5219 5220 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5221 /// conversion of the expression From to an Objective-C pointer type. 5222 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5223 if (checkPlaceholderForOverload(*this, From)) 5224 return ExprError(); 5225 5226 QualType Ty = Context.getObjCIdType(); 5227 ImplicitConversionSequence ICS = 5228 TryContextuallyConvertToObjCPointer(*this, From); 5229 if (!ICS.isBad()) 5230 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5231 return ExprError(); 5232 } 5233 5234 /// Determine whether the provided type is an integral type, or an enumeration 5235 /// type of a permitted flavor. 5236 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5237 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5238 : T->isIntegralOrUnscopedEnumerationType(); 5239 } 5240 5241 static ExprResult 5242 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5243 Sema::ContextualImplicitConverter &Converter, 5244 QualType T, UnresolvedSetImpl &ViableConversions) { 5245 5246 if (Converter.Suppress) 5247 return ExprError(); 5248 5249 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5250 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5251 CXXConversionDecl *Conv = 5252 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5253 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5254 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5255 } 5256 return From; 5257 } 5258 5259 static bool 5260 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5261 Sema::ContextualImplicitConverter &Converter, 5262 QualType T, bool HadMultipleCandidates, 5263 UnresolvedSetImpl &ExplicitConversions) { 5264 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5265 DeclAccessPair Found = ExplicitConversions[0]; 5266 CXXConversionDecl *Conversion = 5267 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5268 5269 // The user probably meant to invoke the given explicit 5270 // conversion; use it. 5271 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5272 std::string TypeStr; 5273 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5274 5275 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5276 << FixItHint::CreateInsertion(From->getLocStart(), 5277 "static_cast<" + TypeStr + ">(") 5278 << FixItHint::CreateInsertion( 5279 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5280 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5281 5282 // If we aren't in a SFINAE context, build a call to the 5283 // explicit conversion function. 5284 if (SemaRef.isSFINAEContext()) 5285 return true; 5286 5287 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5288 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5289 HadMultipleCandidates); 5290 if (Result.isInvalid()) 5291 return true; 5292 // Record usage of conversion in an implicit cast. 5293 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5294 CK_UserDefinedConversion, Result.get(), 5295 nullptr, Result.get()->getValueKind()); 5296 } 5297 return false; 5298 } 5299 5300 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5301 Sema::ContextualImplicitConverter &Converter, 5302 QualType T, bool HadMultipleCandidates, 5303 DeclAccessPair &Found) { 5304 CXXConversionDecl *Conversion = 5305 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5306 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5307 5308 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5309 if (!Converter.SuppressConversion) { 5310 if (SemaRef.isSFINAEContext()) 5311 return true; 5312 5313 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5314 << From->getSourceRange(); 5315 } 5316 5317 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5318 HadMultipleCandidates); 5319 if (Result.isInvalid()) 5320 return true; 5321 // Record usage of conversion in an implicit cast. 5322 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5323 CK_UserDefinedConversion, Result.get(), 5324 nullptr, Result.get()->getValueKind()); 5325 return false; 5326 } 5327 5328 static ExprResult finishContextualImplicitConversion( 5329 Sema &SemaRef, SourceLocation Loc, Expr *From, 5330 Sema::ContextualImplicitConverter &Converter) { 5331 if (!Converter.match(From->getType()) && !Converter.Suppress) 5332 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5333 << From->getSourceRange(); 5334 5335 return SemaRef.DefaultLvalueConversion(From); 5336 } 5337 5338 static void 5339 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5340 UnresolvedSetImpl &ViableConversions, 5341 OverloadCandidateSet &CandidateSet) { 5342 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5343 DeclAccessPair FoundDecl = ViableConversions[I]; 5344 NamedDecl *D = FoundDecl.getDecl(); 5345 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5346 if (isa<UsingShadowDecl>(D)) 5347 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5348 5349 CXXConversionDecl *Conv; 5350 FunctionTemplateDecl *ConvTemplate; 5351 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5352 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5353 else 5354 Conv = cast<CXXConversionDecl>(D); 5355 5356 if (ConvTemplate) 5357 SemaRef.AddTemplateConversionCandidate( 5358 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5359 /*AllowObjCConversionOnExplicit=*/false); 5360 else 5361 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5362 ToType, CandidateSet, 5363 /*AllowObjCConversionOnExplicit=*/false); 5364 } 5365 } 5366 5367 /// \brief Attempt to convert the given expression to a type which is accepted 5368 /// by the given converter. 5369 /// 5370 /// This routine will attempt to convert an expression of class type to a 5371 /// type accepted by the specified converter. In C++11 and before, the class 5372 /// must have a single non-explicit conversion function converting to a matching 5373 /// type. In C++1y, there can be multiple such conversion functions, but only 5374 /// one target type. 5375 /// 5376 /// \param Loc The source location of the construct that requires the 5377 /// conversion. 5378 /// 5379 /// \param From The expression we're converting from. 5380 /// 5381 /// \param Converter Used to control and diagnose the conversion process. 5382 /// 5383 /// \returns The expression, converted to an integral or enumeration type if 5384 /// successful. 5385 ExprResult Sema::PerformContextualImplicitConversion( 5386 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5387 // We can't perform any more checking for type-dependent expressions. 5388 if (From->isTypeDependent()) 5389 return From; 5390 5391 // Process placeholders immediately. 5392 if (From->hasPlaceholderType()) { 5393 ExprResult result = CheckPlaceholderExpr(From); 5394 if (result.isInvalid()) 5395 return result; 5396 From = result.get(); 5397 } 5398 5399 // If the expression already has a matching type, we're golden. 5400 QualType T = From->getType(); 5401 if (Converter.match(T)) 5402 return DefaultLvalueConversion(From); 5403 5404 // FIXME: Check for missing '()' if T is a function type? 5405 5406 // We can only perform contextual implicit conversions on objects of class 5407 // type. 5408 const RecordType *RecordTy = T->getAs<RecordType>(); 5409 if (!RecordTy || !getLangOpts().CPlusPlus) { 5410 if (!Converter.Suppress) 5411 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5412 return From; 5413 } 5414 5415 // We must have a complete class type. 5416 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5417 ContextualImplicitConverter &Converter; 5418 Expr *From; 5419 5420 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5421 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5422 5423 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5424 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5425 } 5426 } IncompleteDiagnoser(Converter, From); 5427 5428 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5429 return From; 5430 5431 // Look for a conversion to an integral or enumeration type. 5432 UnresolvedSet<4> 5433 ViableConversions; // These are *potentially* viable in C++1y. 5434 UnresolvedSet<4> ExplicitConversions; 5435 const auto &Conversions = 5436 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5437 5438 bool HadMultipleCandidates = 5439 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5440 5441 // To check that there is only one target type, in C++1y: 5442 QualType ToType; 5443 bool HasUniqueTargetType = true; 5444 5445 // Collect explicit or viable (potentially in C++1y) conversions. 5446 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5447 NamedDecl *D = (*I)->getUnderlyingDecl(); 5448 CXXConversionDecl *Conversion; 5449 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5450 if (ConvTemplate) { 5451 if (getLangOpts().CPlusPlus14) 5452 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5453 else 5454 continue; // C++11 does not consider conversion operator templates(?). 5455 } else 5456 Conversion = cast<CXXConversionDecl>(D); 5457 5458 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5459 "Conversion operator templates are considered potentially " 5460 "viable in C++1y"); 5461 5462 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5463 if (Converter.match(CurToType) || ConvTemplate) { 5464 5465 if (Conversion->isExplicit()) { 5466 // FIXME: For C++1y, do we need this restriction? 5467 // cf. diagnoseNoViableConversion() 5468 if (!ConvTemplate) 5469 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5470 } else { 5471 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5472 if (ToType.isNull()) 5473 ToType = CurToType.getUnqualifiedType(); 5474 else if (HasUniqueTargetType && 5475 (CurToType.getUnqualifiedType() != ToType)) 5476 HasUniqueTargetType = false; 5477 } 5478 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5479 } 5480 } 5481 } 5482 5483 if (getLangOpts().CPlusPlus14) { 5484 // C++1y [conv]p6: 5485 // ... An expression e of class type E appearing in such a context 5486 // is said to be contextually implicitly converted to a specified 5487 // type T and is well-formed if and only if e can be implicitly 5488 // converted to a type T that is determined as follows: E is searched 5489 // for conversion functions whose return type is cv T or reference to 5490 // cv T such that T is allowed by the context. There shall be 5491 // exactly one such T. 5492 5493 // If no unique T is found: 5494 if (ToType.isNull()) { 5495 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5496 HadMultipleCandidates, 5497 ExplicitConversions)) 5498 return ExprError(); 5499 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5500 } 5501 5502 // If more than one unique Ts are found: 5503 if (!HasUniqueTargetType) 5504 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5505 ViableConversions); 5506 5507 // If one unique T is found: 5508 // First, build a candidate set from the previously recorded 5509 // potentially viable conversions. 5510 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5511 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5512 CandidateSet); 5513 5514 // Then, perform overload resolution over the candidate set. 5515 OverloadCandidateSet::iterator Best; 5516 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5517 case OR_Success: { 5518 // Apply this conversion. 5519 DeclAccessPair Found = 5520 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5521 if (recordConversion(*this, Loc, From, Converter, T, 5522 HadMultipleCandidates, Found)) 5523 return ExprError(); 5524 break; 5525 } 5526 case OR_Ambiguous: 5527 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5528 ViableConversions); 5529 case OR_No_Viable_Function: 5530 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5531 HadMultipleCandidates, 5532 ExplicitConversions)) 5533 return ExprError(); 5534 // fall through 'OR_Deleted' case. 5535 case OR_Deleted: 5536 // We'll complain below about a non-integral condition type. 5537 break; 5538 } 5539 } else { 5540 switch (ViableConversions.size()) { 5541 case 0: { 5542 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5543 HadMultipleCandidates, 5544 ExplicitConversions)) 5545 return ExprError(); 5546 5547 // We'll complain below about a non-integral condition type. 5548 break; 5549 } 5550 case 1: { 5551 // Apply this conversion. 5552 DeclAccessPair Found = ViableConversions[0]; 5553 if (recordConversion(*this, Loc, From, Converter, T, 5554 HadMultipleCandidates, Found)) 5555 return ExprError(); 5556 break; 5557 } 5558 default: 5559 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5560 ViableConversions); 5561 } 5562 } 5563 5564 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5565 } 5566 5567 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5568 /// an acceptable non-member overloaded operator for a call whose 5569 /// arguments have types T1 (and, if non-empty, T2). This routine 5570 /// implements the check in C++ [over.match.oper]p3b2 concerning 5571 /// enumeration types. 5572 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5573 FunctionDecl *Fn, 5574 ArrayRef<Expr *> Args) { 5575 QualType T1 = Args[0]->getType(); 5576 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5577 5578 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5579 return true; 5580 5581 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5582 return true; 5583 5584 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5585 if (Proto->getNumParams() < 1) 5586 return false; 5587 5588 if (T1->isEnumeralType()) { 5589 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5590 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5591 return true; 5592 } 5593 5594 if (Proto->getNumParams() < 2) 5595 return false; 5596 5597 if (!T2.isNull() && T2->isEnumeralType()) { 5598 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5599 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5600 return true; 5601 } 5602 5603 return false; 5604 } 5605 5606 /// AddOverloadCandidate - Adds the given function to the set of 5607 /// candidate functions, using the given function call arguments. If 5608 /// @p SuppressUserConversions, then don't allow user-defined 5609 /// conversions via constructors or conversion operators. 5610 /// 5611 /// \param PartialOverloading true if we are performing "partial" overloading 5612 /// based on an incomplete set of function arguments. This feature is used by 5613 /// code completion. 5614 void 5615 Sema::AddOverloadCandidate(FunctionDecl *Function, 5616 DeclAccessPair FoundDecl, 5617 ArrayRef<Expr *> Args, 5618 OverloadCandidateSet &CandidateSet, 5619 bool SuppressUserConversions, 5620 bool PartialOverloading, 5621 bool AllowExplicit) { 5622 const FunctionProtoType *Proto 5623 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5624 assert(Proto && "Functions without a prototype cannot be overloaded"); 5625 assert(!Function->getDescribedFunctionTemplate() && 5626 "Use AddTemplateOverloadCandidate for function templates"); 5627 5628 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5629 if (!isa<CXXConstructorDecl>(Method)) { 5630 // If we get here, it's because we're calling a member function 5631 // that is named without a member access expression (e.g., 5632 // "this->f") that was either written explicitly or created 5633 // implicitly. This can happen with a qualified call to a member 5634 // function, e.g., X::f(). We use an empty type for the implied 5635 // object argument (C++ [over.call.func]p3), and the acting context 5636 // is irrelevant. 5637 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5638 QualType(), Expr::Classification::makeSimpleLValue(), 5639 Args, CandidateSet, SuppressUserConversions, 5640 PartialOverloading); 5641 return; 5642 } 5643 // We treat a constructor like a non-member function, since its object 5644 // argument doesn't participate in overload resolution. 5645 } 5646 5647 if (!CandidateSet.isNewCandidate(Function)) 5648 return; 5649 5650 // C++ [over.match.oper]p3: 5651 // if no operand has a class type, only those non-member functions in the 5652 // lookup set that have a first parameter of type T1 or "reference to 5653 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5654 // is a right operand) a second parameter of type T2 or "reference to 5655 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5656 // candidate functions. 5657 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5658 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5659 return; 5660 5661 // C++11 [class.copy]p11: [DR1402] 5662 // A defaulted move constructor that is defined as deleted is ignored by 5663 // overload resolution. 5664 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5665 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5666 Constructor->isMoveConstructor()) 5667 return; 5668 5669 // Overload resolution is always an unevaluated context. 5670 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5671 5672 // Add this candidate 5673 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5674 Candidate.FoundDecl = FoundDecl; 5675 Candidate.Function = Function; 5676 Candidate.Viable = true; 5677 Candidate.IsSurrogate = false; 5678 Candidate.IgnoreObjectArgument = false; 5679 Candidate.ExplicitCallArguments = Args.size(); 5680 5681 if (Constructor) { 5682 // C++ [class.copy]p3: 5683 // A member function template is never instantiated to perform the copy 5684 // of a class object to an object of its class type. 5685 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5686 if (Args.size() == 1 && 5687 Constructor->isSpecializationCopyingObject() && 5688 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5689 IsDerivedFrom(Args[0]->getType(), ClassType))) { 5690 Candidate.Viable = false; 5691 Candidate.FailureKind = ovl_fail_illegal_constructor; 5692 return; 5693 } 5694 } 5695 5696 unsigned NumParams = Proto->getNumParams(); 5697 5698 // (C++ 13.3.2p2): A candidate function having fewer than m 5699 // parameters is viable only if it has an ellipsis in its parameter 5700 // list (8.3.5). 5701 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5702 !Proto->isVariadic()) { 5703 Candidate.Viable = false; 5704 Candidate.FailureKind = ovl_fail_too_many_arguments; 5705 return; 5706 } 5707 5708 // (C++ 13.3.2p2): A candidate function having more than m parameters 5709 // is viable only if the (m+1)st parameter has a default argument 5710 // (8.3.6). For the purposes of overload resolution, the 5711 // parameter list is truncated on the right, so that there are 5712 // exactly m parameters. 5713 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5714 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5715 // Not enough arguments. 5716 Candidate.Viable = false; 5717 Candidate.FailureKind = ovl_fail_too_few_arguments; 5718 return; 5719 } 5720 5721 // (CUDA B.1): Check for invalid calls between targets. 5722 if (getLangOpts().CUDA) 5723 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5724 // Skip the check for callers that are implicit members, because in this 5725 // case we may not yet know what the member's target is; the target is 5726 // inferred for the member automatically, based on the bases and fields of 5727 // the class. 5728 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5729 Candidate.Viable = false; 5730 Candidate.FailureKind = ovl_fail_bad_target; 5731 return; 5732 } 5733 5734 // Determine the implicit conversion sequences for each of the 5735 // arguments. 5736 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5737 if (ArgIdx < NumParams) { 5738 // (C++ 13.3.2p3): for F to be a viable function, there shall 5739 // exist for each argument an implicit conversion sequence 5740 // (13.3.3.1) that converts that argument to the corresponding 5741 // parameter of F. 5742 QualType ParamType = Proto->getParamType(ArgIdx); 5743 Candidate.Conversions[ArgIdx] 5744 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5745 SuppressUserConversions, 5746 /*InOverloadResolution=*/true, 5747 /*AllowObjCWritebackConversion=*/ 5748 getLangOpts().ObjCAutoRefCount, 5749 AllowExplicit); 5750 if (Candidate.Conversions[ArgIdx].isBad()) { 5751 Candidate.Viable = false; 5752 Candidate.FailureKind = ovl_fail_bad_conversion; 5753 return; 5754 } 5755 } else { 5756 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5757 // argument for which there is no corresponding parameter is 5758 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5759 Candidate.Conversions[ArgIdx].setEllipsis(); 5760 } 5761 } 5762 5763 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5764 Candidate.Viable = false; 5765 Candidate.FailureKind = ovl_fail_enable_if; 5766 Candidate.DeductionFailure.Data = FailedAttr; 5767 return; 5768 } 5769 } 5770 5771 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5772 bool IsInstance) { 5773 SmallVector<ObjCMethodDecl*, 4> Methods; 5774 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5775 return nullptr; 5776 5777 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5778 bool Match = true; 5779 ObjCMethodDecl *Method = Methods[b]; 5780 unsigned NumNamedArgs = Sel.getNumArgs(); 5781 // Method might have more arguments than selector indicates. This is due 5782 // to addition of c-style arguments in method. 5783 if (Method->param_size() > NumNamedArgs) 5784 NumNamedArgs = Method->param_size(); 5785 if (Args.size() < NumNamedArgs) 5786 continue; 5787 5788 for (unsigned i = 0; i < NumNamedArgs; i++) { 5789 // We can't do any type-checking on a type-dependent argument. 5790 if (Args[i]->isTypeDependent()) { 5791 Match = false; 5792 break; 5793 } 5794 5795 ParmVarDecl *param = Method->parameters()[i]; 5796 Expr *argExpr = Args[i]; 5797 assert(argExpr && "SelectBestMethod(): missing expression"); 5798 5799 // Strip the unbridged-cast placeholder expression off unless it's 5800 // a consumed argument. 5801 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5802 !param->hasAttr<CFConsumedAttr>()) 5803 argExpr = stripARCUnbridgedCast(argExpr); 5804 5805 // If the parameter is __unknown_anytype, move on to the next method. 5806 if (param->getType() == Context.UnknownAnyTy) { 5807 Match = false; 5808 break; 5809 } 5810 5811 ImplicitConversionSequence ConversionState 5812 = TryCopyInitialization(*this, argExpr, param->getType(), 5813 /*SuppressUserConversions*/false, 5814 /*InOverloadResolution=*/true, 5815 /*AllowObjCWritebackConversion=*/ 5816 getLangOpts().ObjCAutoRefCount, 5817 /*AllowExplicit*/false); 5818 if (ConversionState.isBad()) { 5819 Match = false; 5820 break; 5821 } 5822 } 5823 // Promote additional arguments to variadic methods. 5824 if (Match && Method->isVariadic()) { 5825 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5826 if (Args[i]->isTypeDependent()) { 5827 Match = false; 5828 break; 5829 } 5830 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5831 nullptr); 5832 if (Arg.isInvalid()) { 5833 Match = false; 5834 break; 5835 } 5836 } 5837 } else { 5838 // Check for extra arguments to non-variadic methods. 5839 if (Args.size() != NumNamedArgs) 5840 Match = false; 5841 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5842 // Special case when selectors have no argument. In this case, select 5843 // one with the most general result type of 'id'. 5844 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5845 QualType ReturnT = Methods[b]->getReturnType(); 5846 if (ReturnT->isObjCIdType()) 5847 return Methods[b]; 5848 } 5849 } 5850 } 5851 5852 if (Match) 5853 return Method; 5854 } 5855 return nullptr; 5856 } 5857 5858 // specific_attr_iterator iterates over enable_if attributes in reverse, and 5859 // enable_if is order-sensitive. As a result, we need to reverse things 5860 // sometimes. Size of 4 elements is arbitrary. 5861 static SmallVector<EnableIfAttr *, 4> 5862 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 5863 SmallVector<EnableIfAttr *, 4> Result; 5864 if (!Function->hasAttrs()) 5865 return Result; 5866 5867 const auto &FuncAttrs = Function->getAttrs(); 5868 for (Attr *Attr : FuncAttrs) 5869 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 5870 Result.push_back(EnableIf); 5871 5872 std::reverse(Result.begin(), Result.end()); 5873 return Result; 5874 } 5875 5876 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5877 bool MissingImplicitThis) { 5878 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 5879 if (EnableIfAttrs.empty()) 5880 return nullptr; 5881 5882 SFINAETrap Trap(*this); 5883 SmallVector<Expr *, 16> ConvertedArgs; 5884 bool InitializationFailed = false; 5885 bool ContainsValueDependentExpr = false; 5886 5887 // Convert the arguments. 5888 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5889 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5890 !cast<CXXMethodDecl>(Function)->isStatic() && 5891 !isa<CXXConstructorDecl>(Function)) { 5892 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5893 ExprResult R = 5894 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5895 Method, Method); 5896 if (R.isInvalid()) { 5897 InitializationFailed = true; 5898 break; 5899 } 5900 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5901 ConvertedArgs.push_back(R.get()); 5902 } else { 5903 ExprResult R = 5904 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5905 Context, 5906 Function->getParamDecl(i)), 5907 SourceLocation(), 5908 Args[i]); 5909 if (R.isInvalid()) { 5910 InitializationFailed = true; 5911 break; 5912 } 5913 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5914 ConvertedArgs.push_back(R.get()); 5915 } 5916 } 5917 5918 if (InitializationFailed || Trap.hasErrorOccurred()) 5919 return EnableIfAttrs[0]; 5920 5921 // Push default arguments if needed. 5922 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 5923 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 5924 ParmVarDecl *P = Function->getParamDecl(i); 5925 ExprResult R = PerformCopyInitialization( 5926 InitializedEntity::InitializeParameter(Context, 5927 Function->getParamDecl(i)), 5928 SourceLocation(), 5929 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 5930 : P->getDefaultArg()); 5931 if (R.isInvalid()) { 5932 InitializationFailed = true; 5933 break; 5934 } 5935 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5936 ConvertedArgs.push_back(R.get()); 5937 } 5938 5939 if (InitializationFailed || Trap.hasErrorOccurred()) 5940 return EnableIfAttrs[0]; 5941 } 5942 5943 for (auto *EIA : EnableIfAttrs) { 5944 APValue Result; 5945 if (EIA->getCond()->isValueDependent()) { 5946 // Don't even try now, we'll examine it after instantiation. 5947 continue; 5948 } 5949 5950 if (!EIA->getCond()->EvaluateWithSubstitution( 5951 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) { 5952 if (!ContainsValueDependentExpr) 5953 return EIA; 5954 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) { 5955 return EIA; 5956 } 5957 } 5958 return nullptr; 5959 } 5960 5961 /// \brief Add all of the function declarations in the given function set to 5962 /// the overload candidate set. 5963 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5964 ArrayRef<Expr *> Args, 5965 OverloadCandidateSet& CandidateSet, 5966 TemplateArgumentListInfo *ExplicitTemplateArgs, 5967 bool SuppressUserConversions, 5968 bool PartialOverloading) { 5969 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5970 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5971 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5972 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5973 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5974 cast<CXXMethodDecl>(FD)->getParent(), 5975 Args[0]->getType(), Args[0]->Classify(Context), 5976 Args.slice(1), CandidateSet, 5977 SuppressUserConversions, PartialOverloading); 5978 else 5979 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5980 SuppressUserConversions, PartialOverloading); 5981 } else { 5982 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5983 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5984 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5985 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5986 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5987 ExplicitTemplateArgs, 5988 Args[0]->getType(), 5989 Args[0]->Classify(Context), Args.slice(1), 5990 CandidateSet, SuppressUserConversions, 5991 PartialOverloading); 5992 else 5993 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5994 ExplicitTemplateArgs, Args, 5995 CandidateSet, SuppressUserConversions, 5996 PartialOverloading); 5997 } 5998 } 5999 } 6000 6001 /// AddMethodCandidate - Adds a named decl (which is some kind of 6002 /// method) as a method candidate to the given overload set. 6003 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6004 QualType ObjectType, 6005 Expr::Classification ObjectClassification, 6006 ArrayRef<Expr *> Args, 6007 OverloadCandidateSet& CandidateSet, 6008 bool SuppressUserConversions) { 6009 NamedDecl *Decl = FoundDecl.getDecl(); 6010 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6011 6012 if (isa<UsingShadowDecl>(Decl)) 6013 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6014 6015 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6016 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6017 "Expected a member function template"); 6018 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6019 /*ExplicitArgs*/ nullptr, 6020 ObjectType, ObjectClassification, 6021 Args, CandidateSet, 6022 SuppressUserConversions); 6023 } else { 6024 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6025 ObjectType, ObjectClassification, 6026 Args, 6027 CandidateSet, SuppressUserConversions); 6028 } 6029 } 6030 6031 /// AddMethodCandidate - Adds the given C++ member function to the set 6032 /// of candidate functions, using the given function call arguments 6033 /// and the object argument (@c Object). For example, in a call 6034 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6035 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6036 /// allow user-defined conversions via constructors or conversion 6037 /// operators. 6038 void 6039 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6040 CXXRecordDecl *ActingContext, QualType ObjectType, 6041 Expr::Classification ObjectClassification, 6042 ArrayRef<Expr *> Args, 6043 OverloadCandidateSet &CandidateSet, 6044 bool SuppressUserConversions, 6045 bool PartialOverloading) { 6046 const FunctionProtoType *Proto 6047 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6048 assert(Proto && "Methods without a prototype cannot be overloaded"); 6049 assert(!isa<CXXConstructorDecl>(Method) && 6050 "Use AddOverloadCandidate for constructors"); 6051 6052 if (!CandidateSet.isNewCandidate(Method)) 6053 return; 6054 6055 // C++11 [class.copy]p23: [DR1402] 6056 // A defaulted move assignment operator that is defined as deleted is 6057 // ignored by overload resolution. 6058 if (Method->isDefaulted() && Method->isDeleted() && 6059 Method->isMoveAssignmentOperator()) 6060 return; 6061 6062 // Overload resolution is always an unevaluated context. 6063 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6064 6065 // Add this candidate 6066 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6067 Candidate.FoundDecl = FoundDecl; 6068 Candidate.Function = Method; 6069 Candidate.IsSurrogate = false; 6070 Candidate.IgnoreObjectArgument = false; 6071 Candidate.ExplicitCallArguments = Args.size(); 6072 6073 unsigned NumParams = Proto->getNumParams(); 6074 6075 // (C++ 13.3.2p2): A candidate function having fewer than m 6076 // parameters is viable only if it has an ellipsis in its parameter 6077 // list (8.3.5). 6078 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6079 !Proto->isVariadic()) { 6080 Candidate.Viable = false; 6081 Candidate.FailureKind = ovl_fail_too_many_arguments; 6082 return; 6083 } 6084 6085 // (C++ 13.3.2p2): A candidate function having more than m parameters 6086 // is viable only if the (m+1)st parameter has a default argument 6087 // (8.3.6). For the purposes of overload resolution, the 6088 // parameter list is truncated on the right, so that there are 6089 // exactly m parameters. 6090 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6091 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6092 // Not enough arguments. 6093 Candidate.Viable = false; 6094 Candidate.FailureKind = ovl_fail_too_few_arguments; 6095 return; 6096 } 6097 6098 Candidate.Viable = true; 6099 6100 if (Method->isStatic() || ObjectType.isNull()) 6101 // The implicit object argument is ignored. 6102 Candidate.IgnoreObjectArgument = true; 6103 else { 6104 // Determine the implicit conversion sequence for the object 6105 // parameter. 6106 Candidate.Conversions[0] 6107 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 6108 Method, ActingContext); 6109 if (Candidate.Conversions[0].isBad()) { 6110 Candidate.Viable = false; 6111 Candidate.FailureKind = ovl_fail_bad_conversion; 6112 return; 6113 } 6114 } 6115 6116 // (CUDA B.1): Check for invalid calls between targets. 6117 if (getLangOpts().CUDA) 6118 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6119 if (CheckCUDATarget(Caller, Method)) { 6120 Candidate.Viable = false; 6121 Candidate.FailureKind = ovl_fail_bad_target; 6122 return; 6123 } 6124 6125 // Determine the implicit conversion sequences for each of the 6126 // arguments. 6127 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6128 if (ArgIdx < NumParams) { 6129 // (C++ 13.3.2p3): for F to be a viable function, there shall 6130 // exist for each argument an implicit conversion sequence 6131 // (13.3.3.1) that converts that argument to the corresponding 6132 // parameter of F. 6133 QualType ParamType = Proto->getParamType(ArgIdx); 6134 Candidate.Conversions[ArgIdx + 1] 6135 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6136 SuppressUserConversions, 6137 /*InOverloadResolution=*/true, 6138 /*AllowObjCWritebackConversion=*/ 6139 getLangOpts().ObjCAutoRefCount); 6140 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6141 Candidate.Viable = false; 6142 Candidate.FailureKind = ovl_fail_bad_conversion; 6143 return; 6144 } 6145 } else { 6146 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6147 // argument for which there is no corresponding parameter is 6148 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6149 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6150 } 6151 } 6152 6153 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6154 Candidate.Viable = false; 6155 Candidate.FailureKind = ovl_fail_enable_if; 6156 Candidate.DeductionFailure.Data = FailedAttr; 6157 return; 6158 } 6159 } 6160 6161 /// \brief Add a C++ member function template as a candidate to the candidate 6162 /// set, using template argument deduction to produce an appropriate member 6163 /// function template specialization. 6164 void 6165 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6166 DeclAccessPair FoundDecl, 6167 CXXRecordDecl *ActingContext, 6168 TemplateArgumentListInfo *ExplicitTemplateArgs, 6169 QualType ObjectType, 6170 Expr::Classification ObjectClassification, 6171 ArrayRef<Expr *> Args, 6172 OverloadCandidateSet& CandidateSet, 6173 bool SuppressUserConversions, 6174 bool PartialOverloading) { 6175 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6176 return; 6177 6178 // C++ [over.match.funcs]p7: 6179 // In each case where a candidate is a function template, candidate 6180 // function template specializations are generated using template argument 6181 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6182 // candidate functions in the usual way.113) A given name can refer to one 6183 // or more function templates and also to a set of overloaded non-template 6184 // functions. In such a case, the candidate functions generated from each 6185 // function template are combined with the set of non-template candidate 6186 // functions. 6187 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6188 FunctionDecl *Specialization = nullptr; 6189 if (TemplateDeductionResult Result 6190 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6191 Specialization, Info, PartialOverloading)) { 6192 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6193 Candidate.FoundDecl = FoundDecl; 6194 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6195 Candidate.Viable = false; 6196 Candidate.FailureKind = ovl_fail_bad_deduction; 6197 Candidate.IsSurrogate = false; 6198 Candidate.IgnoreObjectArgument = false; 6199 Candidate.ExplicitCallArguments = Args.size(); 6200 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6201 Info); 6202 return; 6203 } 6204 6205 // Add the function template specialization produced by template argument 6206 // deduction as a candidate. 6207 assert(Specialization && "Missing member function template specialization?"); 6208 assert(isa<CXXMethodDecl>(Specialization) && 6209 "Specialization is not a member function?"); 6210 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6211 ActingContext, ObjectType, ObjectClassification, Args, 6212 CandidateSet, SuppressUserConversions, PartialOverloading); 6213 } 6214 6215 /// \brief Add a C++ function template specialization as a candidate 6216 /// in the candidate set, using template argument deduction to produce 6217 /// an appropriate function template specialization. 6218 void 6219 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6220 DeclAccessPair FoundDecl, 6221 TemplateArgumentListInfo *ExplicitTemplateArgs, 6222 ArrayRef<Expr *> Args, 6223 OverloadCandidateSet& CandidateSet, 6224 bool SuppressUserConversions, 6225 bool PartialOverloading) { 6226 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6227 return; 6228 6229 // C++ [over.match.funcs]p7: 6230 // In each case where a candidate is a function template, candidate 6231 // function template specializations are generated using template argument 6232 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6233 // candidate functions in the usual way.113) A given name can refer to one 6234 // or more function templates and also to a set of overloaded non-template 6235 // functions. In such a case, the candidate functions generated from each 6236 // function template are combined with the set of non-template candidate 6237 // functions. 6238 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6239 FunctionDecl *Specialization = nullptr; 6240 if (TemplateDeductionResult Result 6241 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6242 Specialization, Info, PartialOverloading)) { 6243 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6244 Candidate.FoundDecl = FoundDecl; 6245 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6246 Candidate.Viable = false; 6247 Candidate.FailureKind = ovl_fail_bad_deduction; 6248 Candidate.IsSurrogate = false; 6249 Candidate.IgnoreObjectArgument = false; 6250 Candidate.ExplicitCallArguments = Args.size(); 6251 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6252 Info); 6253 return; 6254 } 6255 6256 // Add the function template specialization produced by template argument 6257 // deduction as a candidate. 6258 assert(Specialization && "Missing function template specialization?"); 6259 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6260 SuppressUserConversions, PartialOverloading); 6261 } 6262 6263 /// Determine whether this is an allowable conversion from the result 6264 /// of an explicit conversion operator to the expected type, per C++ 6265 /// [over.match.conv]p1 and [over.match.ref]p1. 6266 /// 6267 /// \param ConvType The return type of the conversion function. 6268 /// 6269 /// \param ToType The type we are converting to. 6270 /// 6271 /// \param AllowObjCPointerConversion Allow a conversion from one 6272 /// Objective-C pointer to another. 6273 /// 6274 /// \returns true if the conversion is allowable, false otherwise. 6275 static bool isAllowableExplicitConversion(Sema &S, 6276 QualType ConvType, QualType ToType, 6277 bool AllowObjCPointerConversion) { 6278 QualType ToNonRefType = ToType.getNonReferenceType(); 6279 6280 // Easy case: the types are the same. 6281 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6282 return true; 6283 6284 // Allow qualification conversions. 6285 bool ObjCLifetimeConversion; 6286 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6287 ObjCLifetimeConversion)) 6288 return true; 6289 6290 // If we're not allowed to consider Objective-C pointer conversions, 6291 // we're done. 6292 if (!AllowObjCPointerConversion) 6293 return false; 6294 6295 // Is this an Objective-C pointer conversion? 6296 bool IncompatibleObjC = false; 6297 QualType ConvertedType; 6298 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6299 IncompatibleObjC); 6300 } 6301 6302 /// AddConversionCandidate - Add a C++ conversion function as a 6303 /// candidate in the candidate set (C++ [over.match.conv], 6304 /// C++ [over.match.copy]). From is the expression we're converting from, 6305 /// and ToType is the type that we're eventually trying to convert to 6306 /// (which may or may not be the same type as the type that the 6307 /// conversion function produces). 6308 void 6309 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6310 DeclAccessPair FoundDecl, 6311 CXXRecordDecl *ActingContext, 6312 Expr *From, QualType ToType, 6313 OverloadCandidateSet& CandidateSet, 6314 bool AllowObjCConversionOnExplicit) { 6315 assert(!Conversion->getDescribedFunctionTemplate() && 6316 "Conversion function templates use AddTemplateConversionCandidate"); 6317 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6318 if (!CandidateSet.isNewCandidate(Conversion)) 6319 return; 6320 6321 // If the conversion function has an undeduced return type, trigger its 6322 // deduction now. 6323 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6324 if (DeduceReturnType(Conversion, From->getExprLoc())) 6325 return; 6326 ConvType = Conversion->getConversionType().getNonReferenceType(); 6327 } 6328 6329 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6330 // operator is only a candidate if its return type is the target type or 6331 // can be converted to the target type with a qualification conversion. 6332 if (Conversion->isExplicit() && 6333 !isAllowableExplicitConversion(*this, ConvType, ToType, 6334 AllowObjCConversionOnExplicit)) 6335 return; 6336 6337 // Overload resolution is always an unevaluated context. 6338 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6339 6340 // Add this candidate 6341 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6342 Candidate.FoundDecl = FoundDecl; 6343 Candidate.Function = Conversion; 6344 Candidate.IsSurrogate = false; 6345 Candidate.IgnoreObjectArgument = false; 6346 Candidate.FinalConversion.setAsIdentityConversion(); 6347 Candidate.FinalConversion.setFromType(ConvType); 6348 Candidate.FinalConversion.setAllToTypes(ToType); 6349 Candidate.Viable = true; 6350 Candidate.ExplicitCallArguments = 1; 6351 6352 // C++ [over.match.funcs]p4: 6353 // For conversion functions, the function is considered to be a member of 6354 // the class of the implicit implied object argument for the purpose of 6355 // defining the type of the implicit object parameter. 6356 // 6357 // Determine the implicit conversion sequence for the implicit 6358 // object parameter. 6359 QualType ImplicitParamType = From->getType(); 6360 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6361 ImplicitParamType = FromPtrType->getPointeeType(); 6362 CXXRecordDecl *ConversionContext 6363 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6364 6365 Candidate.Conversions[0] 6366 = TryObjectArgumentInitialization(*this, From->getType(), 6367 From->Classify(Context), 6368 Conversion, ConversionContext); 6369 6370 if (Candidate.Conversions[0].isBad()) { 6371 Candidate.Viable = false; 6372 Candidate.FailureKind = ovl_fail_bad_conversion; 6373 return; 6374 } 6375 6376 // We won't go through a user-defined type conversion function to convert a 6377 // derived to base as such conversions are given Conversion Rank. They only 6378 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6379 QualType FromCanon 6380 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6381 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6382 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6383 Candidate.Viable = false; 6384 Candidate.FailureKind = ovl_fail_trivial_conversion; 6385 return; 6386 } 6387 6388 // To determine what the conversion from the result of calling the 6389 // conversion function to the type we're eventually trying to 6390 // convert to (ToType), we need to synthesize a call to the 6391 // conversion function and attempt copy initialization from it. This 6392 // makes sure that we get the right semantics with respect to 6393 // lvalues/rvalues and the type. Fortunately, we can allocate this 6394 // call on the stack and we don't need its arguments to be 6395 // well-formed. 6396 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6397 VK_LValue, From->getLocStart()); 6398 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6399 Context.getPointerType(Conversion->getType()), 6400 CK_FunctionToPointerDecay, 6401 &ConversionRef, VK_RValue); 6402 6403 QualType ConversionType = Conversion->getConversionType(); 6404 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6405 Candidate.Viable = false; 6406 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6407 return; 6408 } 6409 6410 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6411 6412 // Note that it is safe to allocate CallExpr on the stack here because 6413 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6414 // allocator). 6415 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6416 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6417 From->getLocStart()); 6418 ImplicitConversionSequence ICS = 6419 TryCopyInitialization(*this, &Call, ToType, 6420 /*SuppressUserConversions=*/true, 6421 /*InOverloadResolution=*/false, 6422 /*AllowObjCWritebackConversion=*/false); 6423 6424 switch (ICS.getKind()) { 6425 case ImplicitConversionSequence::StandardConversion: 6426 Candidate.FinalConversion = ICS.Standard; 6427 6428 // C++ [over.ics.user]p3: 6429 // If the user-defined conversion is specified by a specialization of a 6430 // conversion function template, the second standard conversion sequence 6431 // shall have exact match rank. 6432 if (Conversion->getPrimaryTemplate() && 6433 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6434 Candidate.Viable = false; 6435 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6436 return; 6437 } 6438 6439 // C++0x [dcl.init.ref]p5: 6440 // In the second case, if the reference is an rvalue reference and 6441 // the second standard conversion sequence of the user-defined 6442 // conversion sequence includes an lvalue-to-rvalue conversion, the 6443 // program is ill-formed. 6444 if (ToType->isRValueReferenceType() && 6445 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6446 Candidate.Viable = false; 6447 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6448 return; 6449 } 6450 break; 6451 6452 case ImplicitConversionSequence::BadConversion: 6453 Candidate.Viable = false; 6454 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6455 return; 6456 6457 default: 6458 llvm_unreachable( 6459 "Can only end up with a standard conversion sequence or failure"); 6460 } 6461 6462 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6463 Candidate.Viable = false; 6464 Candidate.FailureKind = ovl_fail_enable_if; 6465 Candidate.DeductionFailure.Data = FailedAttr; 6466 return; 6467 } 6468 } 6469 6470 /// \brief Adds a conversion function template specialization 6471 /// candidate to the overload set, using template argument deduction 6472 /// to deduce the template arguments of the conversion function 6473 /// template from the type that we are converting to (C++ 6474 /// [temp.deduct.conv]). 6475 void 6476 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6477 DeclAccessPair FoundDecl, 6478 CXXRecordDecl *ActingDC, 6479 Expr *From, QualType ToType, 6480 OverloadCandidateSet &CandidateSet, 6481 bool AllowObjCConversionOnExplicit) { 6482 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6483 "Only conversion function templates permitted here"); 6484 6485 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6486 return; 6487 6488 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6489 CXXConversionDecl *Specialization = nullptr; 6490 if (TemplateDeductionResult Result 6491 = DeduceTemplateArguments(FunctionTemplate, ToType, 6492 Specialization, Info)) { 6493 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6494 Candidate.FoundDecl = FoundDecl; 6495 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6496 Candidate.Viable = false; 6497 Candidate.FailureKind = ovl_fail_bad_deduction; 6498 Candidate.IsSurrogate = false; 6499 Candidate.IgnoreObjectArgument = false; 6500 Candidate.ExplicitCallArguments = 1; 6501 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6502 Info); 6503 return; 6504 } 6505 6506 // Add the conversion function template specialization produced by 6507 // template argument deduction as a candidate. 6508 assert(Specialization && "Missing function template specialization?"); 6509 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6510 CandidateSet, AllowObjCConversionOnExplicit); 6511 } 6512 6513 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6514 /// converts the given @c Object to a function pointer via the 6515 /// conversion function @c Conversion, and then attempts to call it 6516 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6517 /// the type of function that we'll eventually be calling. 6518 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6519 DeclAccessPair FoundDecl, 6520 CXXRecordDecl *ActingContext, 6521 const FunctionProtoType *Proto, 6522 Expr *Object, 6523 ArrayRef<Expr *> Args, 6524 OverloadCandidateSet& CandidateSet) { 6525 if (!CandidateSet.isNewCandidate(Conversion)) 6526 return; 6527 6528 // Overload resolution is always an unevaluated context. 6529 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6530 6531 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6532 Candidate.FoundDecl = FoundDecl; 6533 Candidate.Function = nullptr; 6534 Candidate.Surrogate = Conversion; 6535 Candidate.Viable = true; 6536 Candidate.IsSurrogate = true; 6537 Candidate.IgnoreObjectArgument = false; 6538 Candidate.ExplicitCallArguments = Args.size(); 6539 6540 // Determine the implicit conversion sequence for the implicit 6541 // object parameter. 6542 ImplicitConversionSequence ObjectInit 6543 = TryObjectArgumentInitialization(*this, Object->getType(), 6544 Object->Classify(Context), 6545 Conversion, ActingContext); 6546 if (ObjectInit.isBad()) { 6547 Candidate.Viable = false; 6548 Candidate.FailureKind = ovl_fail_bad_conversion; 6549 Candidate.Conversions[0] = ObjectInit; 6550 return; 6551 } 6552 6553 // The first conversion is actually a user-defined conversion whose 6554 // first conversion is ObjectInit's standard conversion (which is 6555 // effectively a reference binding). Record it as such. 6556 Candidate.Conversions[0].setUserDefined(); 6557 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6558 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6559 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6560 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6561 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6562 Candidate.Conversions[0].UserDefined.After 6563 = Candidate.Conversions[0].UserDefined.Before; 6564 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6565 6566 // Find the 6567 unsigned NumParams = Proto->getNumParams(); 6568 6569 // (C++ 13.3.2p2): A candidate function having fewer than m 6570 // parameters is viable only if it has an ellipsis in its parameter 6571 // list (8.3.5). 6572 if (Args.size() > NumParams && !Proto->isVariadic()) { 6573 Candidate.Viable = false; 6574 Candidate.FailureKind = ovl_fail_too_many_arguments; 6575 return; 6576 } 6577 6578 // Function types don't have any default arguments, so just check if 6579 // we have enough arguments. 6580 if (Args.size() < NumParams) { 6581 // Not enough arguments. 6582 Candidate.Viable = false; 6583 Candidate.FailureKind = ovl_fail_too_few_arguments; 6584 return; 6585 } 6586 6587 // Determine the implicit conversion sequences for each of the 6588 // arguments. 6589 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6590 if (ArgIdx < NumParams) { 6591 // (C++ 13.3.2p3): for F to be a viable function, there shall 6592 // exist for each argument an implicit conversion sequence 6593 // (13.3.3.1) that converts that argument to the corresponding 6594 // parameter of F. 6595 QualType ParamType = Proto->getParamType(ArgIdx); 6596 Candidate.Conversions[ArgIdx + 1] 6597 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6598 /*SuppressUserConversions=*/false, 6599 /*InOverloadResolution=*/false, 6600 /*AllowObjCWritebackConversion=*/ 6601 getLangOpts().ObjCAutoRefCount); 6602 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6603 Candidate.Viable = false; 6604 Candidate.FailureKind = ovl_fail_bad_conversion; 6605 return; 6606 } 6607 } else { 6608 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6609 // argument for which there is no corresponding parameter is 6610 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6611 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6612 } 6613 } 6614 6615 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6616 Candidate.Viable = false; 6617 Candidate.FailureKind = ovl_fail_enable_if; 6618 Candidate.DeductionFailure.Data = FailedAttr; 6619 return; 6620 } 6621 } 6622 6623 /// \brief Add overload candidates for overloaded operators that are 6624 /// member functions. 6625 /// 6626 /// Add the overloaded operator candidates that are member functions 6627 /// for the operator Op that was used in an operator expression such 6628 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6629 /// CandidateSet will store the added overload candidates. (C++ 6630 /// [over.match.oper]). 6631 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6632 SourceLocation OpLoc, 6633 ArrayRef<Expr *> Args, 6634 OverloadCandidateSet& CandidateSet, 6635 SourceRange OpRange) { 6636 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6637 6638 // C++ [over.match.oper]p3: 6639 // For a unary operator @ with an operand of a type whose 6640 // cv-unqualified version is T1, and for a binary operator @ with 6641 // a left operand of a type whose cv-unqualified version is T1 and 6642 // a right operand of a type whose cv-unqualified version is T2, 6643 // three sets of candidate functions, designated member 6644 // candidates, non-member candidates and built-in candidates, are 6645 // constructed as follows: 6646 QualType T1 = Args[0]->getType(); 6647 6648 // -- If T1 is a complete class type or a class currently being 6649 // defined, the set of member candidates is the result of the 6650 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6651 // the set of member candidates is empty. 6652 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6653 // Complete the type if it can be completed. 6654 RequireCompleteType(OpLoc, T1, 0); 6655 // If the type is neither complete nor being defined, bail out now. 6656 if (!T1Rec->getDecl()->getDefinition()) 6657 return; 6658 6659 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6660 LookupQualifiedName(Operators, T1Rec->getDecl()); 6661 Operators.suppressDiagnostics(); 6662 6663 for (LookupResult::iterator Oper = Operators.begin(), 6664 OperEnd = Operators.end(); 6665 Oper != OperEnd; 6666 ++Oper) 6667 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6668 Args[0]->Classify(Context), 6669 Args.slice(1), 6670 CandidateSet, 6671 /* SuppressUserConversions = */ false); 6672 } 6673 } 6674 6675 /// AddBuiltinCandidate - Add a candidate for a built-in 6676 /// operator. ResultTy and ParamTys are the result and parameter types 6677 /// of the built-in candidate, respectively. Args and NumArgs are the 6678 /// arguments being passed to the candidate. IsAssignmentOperator 6679 /// should be true when this built-in candidate is an assignment 6680 /// operator. NumContextualBoolArguments is the number of arguments 6681 /// (at the beginning of the argument list) that will be contextually 6682 /// converted to bool. 6683 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6684 ArrayRef<Expr *> Args, 6685 OverloadCandidateSet& CandidateSet, 6686 bool IsAssignmentOperator, 6687 unsigned NumContextualBoolArguments) { 6688 // Overload resolution is always an unevaluated context. 6689 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6690 6691 // Add this candidate 6692 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6693 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6694 Candidate.Function = nullptr; 6695 Candidate.IsSurrogate = false; 6696 Candidate.IgnoreObjectArgument = false; 6697 Candidate.BuiltinTypes.ResultTy = ResultTy; 6698 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6699 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6700 6701 // Determine the implicit conversion sequences for each of the 6702 // arguments. 6703 Candidate.Viable = true; 6704 Candidate.ExplicitCallArguments = Args.size(); 6705 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6706 // C++ [over.match.oper]p4: 6707 // For the built-in assignment operators, conversions of the 6708 // left operand are restricted as follows: 6709 // -- no temporaries are introduced to hold the left operand, and 6710 // -- no user-defined conversions are applied to the left 6711 // operand to achieve a type match with the left-most 6712 // parameter of a built-in candidate. 6713 // 6714 // We block these conversions by turning off user-defined 6715 // conversions, since that is the only way that initialization of 6716 // a reference to a non-class type can occur from something that 6717 // is not of the same type. 6718 if (ArgIdx < NumContextualBoolArguments) { 6719 assert(ParamTys[ArgIdx] == Context.BoolTy && 6720 "Contextual conversion to bool requires bool type"); 6721 Candidate.Conversions[ArgIdx] 6722 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6723 } else { 6724 Candidate.Conversions[ArgIdx] 6725 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6726 ArgIdx == 0 && IsAssignmentOperator, 6727 /*InOverloadResolution=*/false, 6728 /*AllowObjCWritebackConversion=*/ 6729 getLangOpts().ObjCAutoRefCount); 6730 } 6731 if (Candidate.Conversions[ArgIdx].isBad()) { 6732 Candidate.Viable = false; 6733 Candidate.FailureKind = ovl_fail_bad_conversion; 6734 break; 6735 } 6736 } 6737 } 6738 6739 namespace { 6740 6741 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6742 /// candidate operator functions for built-in operators (C++ 6743 /// [over.built]). The types are separated into pointer types and 6744 /// enumeration types. 6745 class BuiltinCandidateTypeSet { 6746 /// TypeSet - A set of types. 6747 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6748 6749 /// PointerTypes - The set of pointer types that will be used in the 6750 /// built-in candidates. 6751 TypeSet PointerTypes; 6752 6753 /// MemberPointerTypes - The set of member pointer types that will be 6754 /// used in the built-in candidates. 6755 TypeSet MemberPointerTypes; 6756 6757 /// EnumerationTypes - The set of enumeration types that will be 6758 /// used in the built-in candidates. 6759 TypeSet EnumerationTypes; 6760 6761 /// \brief The set of vector types that will be used in the built-in 6762 /// candidates. 6763 TypeSet VectorTypes; 6764 6765 /// \brief A flag indicating non-record types are viable candidates 6766 bool HasNonRecordTypes; 6767 6768 /// \brief A flag indicating whether either arithmetic or enumeration types 6769 /// were present in the candidate set. 6770 bool HasArithmeticOrEnumeralTypes; 6771 6772 /// \brief A flag indicating whether the nullptr type was present in the 6773 /// candidate set. 6774 bool HasNullPtrType; 6775 6776 /// Sema - The semantic analysis instance where we are building the 6777 /// candidate type set. 6778 Sema &SemaRef; 6779 6780 /// Context - The AST context in which we will build the type sets. 6781 ASTContext &Context; 6782 6783 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6784 const Qualifiers &VisibleQuals); 6785 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6786 6787 public: 6788 /// iterator - Iterates through the types that are part of the set. 6789 typedef TypeSet::iterator iterator; 6790 6791 BuiltinCandidateTypeSet(Sema &SemaRef) 6792 : HasNonRecordTypes(false), 6793 HasArithmeticOrEnumeralTypes(false), 6794 HasNullPtrType(false), 6795 SemaRef(SemaRef), 6796 Context(SemaRef.Context) { } 6797 6798 void AddTypesConvertedFrom(QualType Ty, 6799 SourceLocation Loc, 6800 bool AllowUserConversions, 6801 bool AllowExplicitConversions, 6802 const Qualifiers &VisibleTypeConversionsQuals); 6803 6804 /// pointer_begin - First pointer type found; 6805 iterator pointer_begin() { return PointerTypes.begin(); } 6806 6807 /// pointer_end - Past the last pointer type found; 6808 iterator pointer_end() { return PointerTypes.end(); } 6809 6810 /// member_pointer_begin - First member pointer type found; 6811 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6812 6813 /// member_pointer_end - Past the last member pointer type found; 6814 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6815 6816 /// enumeration_begin - First enumeration type found; 6817 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6818 6819 /// enumeration_end - Past the last enumeration type found; 6820 iterator enumeration_end() { return EnumerationTypes.end(); } 6821 6822 iterator vector_begin() { return VectorTypes.begin(); } 6823 iterator vector_end() { return VectorTypes.end(); } 6824 6825 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6826 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6827 bool hasNullPtrType() const { return HasNullPtrType; } 6828 }; 6829 6830 } // end anonymous namespace 6831 6832 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6833 /// the set of pointer types along with any more-qualified variants of 6834 /// that type. For example, if @p Ty is "int const *", this routine 6835 /// will add "int const *", "int const volatile *", "int const 6836 /// restrict *", and "int const volatile restrict *" to the set of 6837 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6838 /// false otherwise. 6839 /// 6840 /// FIXME: what to do about extended qualifiers? 6841 bool 6842 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6843 const Qualifiers &VisibleQuals) { 6844 6845 // Insert this type. 6846 if (!PointerTypes.insert(Ty).second) 6847 return false; 6848 6849 QualType PointeeTy; 6850 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6851 bool buildObjCPtr = false; 6852 if (!PointerTy) { 6853 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6854 PointeeTy = PTy->getPointeeType(); 6855 buildObjCPtr = true; 6856 } else { 6857 PointeeTy = PointerTy->getPointeeType(); 6858 } 6859 6860 // Don't add qualified variants of arrays. For one, they're not allowed 6861 // (the qualifier would sink to the element type), and for another, the 6862 // only overload situation where it matters is subscript or pointer +- int, 6863 // and those shouldn't have qualifier variants anyway. 6864 if (PointeeTy->isArrayType()) 6865 return true; 6866 6867 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6868 bool hasVolatile = VisibleQuals.hasVolatile(); 6869 bool hasRestrict = VisibleQuals.hasRestrict(); 6870 6871 // Iterate through all strict supersets of BaseCVR. 6872 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6873 if ((CVR | BaseCVR) != CVR) continue; 6874 // Skip over volatile if no volatile found anywhere in the types. 6875 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6876 6877 // Skip over restrict if no restrict found anywhere in the types, or if 6878 // the type cannot be restrict-qualified. 6879 if ((CVR & Qualifiers::Restrict) && 6880 (!hasRestrict || 6881 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6882 continue; 6883 6884 // Build qualified pointee type. 6885 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6886 6887 // Build qualified pointer type. 6888 QualType QPointerTy; 6889 if (!buildObjCPtr) 6890 QPointerTy = Context.getPointerType(QPointeeTy); 6891 else 6892 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6893 6894 // Insert qualified pointer type. 6895 PointerTypes.insert(QPointerTy); 6896 } 6897 6898 return true; 6899 } 6900 6901 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6902 /// to the set of pointer types along with any more-qualified variants of 6903 /// that type. For example, if @p Ty is "int const *", this routine 6904 /// will add "int const *", "int const volatile *", "int const 6905 /// restrict *", and "int const volatile restrict *" to the set of 6906 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6907 /// false otherwise. 6908 /// 6909 /// FIXME: what to do about extended qualifiers? 6910 bool 6911 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6912 QualType Ty) { 6913 // Insert this type. 6914 if (!MemberPointerTypes.insert(Ty).second) 6915 return false; 6916 6917 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6918 assert(PointerTy && "type was not a member pointer type!"); 6919 6920 QualType PointeeTy = PointerTy->getPointeeType(); 6921 // Don't add qualified variants of arrays. For one, they're not allowed 6922 // (the qualifier would sink to the element type), and for another, the 6923 // only overload situation where it matters is subscript or pointer +- int, 6924 // and those shouldn't have qualifier variants anyway. 6925 if (PointeeTy->isArrayType()) 6926 return true; 6927 const Type *ClassTy = PointerTy->getClass(); 6928 6929 // Iterate through all strict supersets of the pointee type's CVR 6930 // qualifiers. 6931 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6932 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6933 if ((CVR | BaseCVR) != CVR) continue; 6934 6935 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6936 MemberPointerTypes.insert( 6937 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6938 } 6939 6940 return true; 6941 } 6942 6943 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6944 /// Ty can be implicit converted to the given set of @p Types. We're 6945 /// primarily interested in pointer types and enumeration types. We also 6946 /// take member pointer types, for the conditional operator. 6947 /// AllowUserConversions is true if we should look at the conversion 6948 /// functions of a class type, and AllowExplicitConversions if we 6949 /// should also include the explicit conversion functions of a class 6950 /// type. 6951 void 6952 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6953 SourceLocation Loc, 6954 bool AllowUserConversions, 6955 bool AllowExplicitConversions, 6956 const Qualifiers &VisibleQuals) { 6957 // Only deal with canonical types. 6958 Ty = Context.getCanonicalType(Ty); 6959 6960 // Look through reference types; they aren't part of the type of an 6961 // expression for the purposes of conversions. 6962 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6963 Ty = RefTy->getPointeeType(); 6964 6965 // If we're dealing with an array type, decay to the pointer. 6966 if (Ty->isArrayType()) 6967 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6968 6969 // Otherwise, we don't care about qualifiers on the type. 6970 Ty = Ty.getLocalUnqualifiedType(); 6971 6972 // Flag if we ever add a non-record type. 6973 const RecordType *TyRec = Ty->getAs<RecordType>(); 6974 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6975 6976 // Flag if we encounter an arithmetic type. 6977 HasArithmeticOrEnumeralTypes = 6978 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6979 6980 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6981 PointerTypes.insert(Ty); 6982 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6983 // Insert our type, and its more-qualified variants, into the set 6984 // of types. 6985 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6986 return; 6987 } else if (Ty->isMemberPointerType()) { 6988 // Member pointers are far easier, since the pointee can't be converted. 6989 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6990 return; 6991 } else if (Ty->isEnumeralType()) { 6992 HasArithmeticOrEnumeralTypes = true; 6993 EnumerationTypes.insert(Ty); 6994 } else if (Ty->isVectorType()) { 6995 // We treat vector types as arithmetic types in many contexts as an 6996 // extension. 6997 HasArithmeticOrEnumeralTypes = true; 6998 VectorTypes.insert(Ty); 6999 } else if (Ty->isNullPtrType()) { 7000 HasNullPtrType = true; 7001 } else if (AllowUserConversions && TyRec) { 7002 // No conversion functions in incomplete types. 7003 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 7004 return; 7005 7006 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7007 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7008 if (isa<UsingShadowDecl>(D)) 7009 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7010 7011 // Skip conversion function templates; they don't tell us anything 7012 // about which builtin types we can convert to. 7013 if (isa<FunctionTemplateDecl>(D)) 7014 continue; 7015 7016 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7017 if (AllowExplicitConversions || !Conv->isExplicit()) { 7018 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7019 VisibleQuals); 7020 } 7021 } 7022 } 7023 } 7024 7025 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7026 /// the volatile- and non-volatile-qualified assignment operators for the 7027 /// given type to the candidate set. 7028 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7029 QualType T, 7030 ArrayRef<Expr *> Args, 7031 OverloadCandidateSet &CandidateSet) { 7032 QualType ParamTypes[2]; 7033 7034 // T& operator=(T&, T) 7035 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7036 ParamTypes[1] = T; 7037 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7038 /*IsAssignmentOperator=*/true); 7039 7040 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7041 // volatile T& operator=(volatile T&, T) 7042 ParamTypes[0] 7043 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7044 ParamTypes[1] = T; 7045 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7046 /*IsAssignmentOperator=*/true); 7047 } 7048 } 7049 7050 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7051 /// if any, found in visible type conversion functions found in ArgExpr's type. 7052 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7053 Qualifiers VRQuals; 7054 const RecordType *TyRec; 7055 if (const MemberPointerType *RHSMPType = 7056 ArgExpr->getType()->getAs<MemberPointerType>()) 7057 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7058 else 7059 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7060 if (!TyRec) { 7061 // Just to be safe, assume the worst case. 7062 VRQuals.addVolatile(); 7063 VRQuals.addRestrict(); 7064 return VRQuals; 7065 } 7066 7067 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7068 if (!ClassDecl->hasDefinition()) 7069 return VRQuals; 7070 7071 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7072 if (isa<UsingShadowDecl>(D)) 7073 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7074 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7075 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7076 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7077 CanTy = ResTypeRef->getPointeeType(); 7078 // Need to go down the pointer/mempointer chain and add qualifiers 7079 // as see them. 7080 bool done = false; 7081 while (!done) { 7082 if (CanTy.isRestrictQualified()) 7083 VRQuals.addRestrict(); 7084 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7085 CanTy = ResTypePtr->getPointeeType(); 7086 else if (const MemberPointerType *ResTypeMPtr = 7087 CanTy->getAs<MemberPointerType>()) 7088 CanTy = ResTypeMPtr->getPointeeType(); 7089 else 7090 done = true; 7091 if (CanTy.isVolatileQualified()) 7092 VRQuals.addVolatile(); 7093 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7094 return VRQuals; 7095 } 7096 } 7097 } 7098 return VRQuals; 7099 } 7100 7101 namespace { 7102 7103 /// \brief Helper class to manage the addition of builtin operator overload 7104 /// candidates. It provides shared state and utility methods used throughout 7105 /// the process, as well as a helper method to add each group of builtin 7106 /// operator overloads from the standard to a candidate set. 7107 class BuiltinOperatorOverloadBuilder { 7108 // Common instance state available to all overload candidate addition methods. 7109 Sema &S; 7110 ArrayRef<Expr *> Args; 7111 Qualifiers VisibleTypeConversionsQuals; 7112 bool HasArithmeticOrEnumeralCandidateType; 7113 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7114 OverloadCandidateSet &CandidateSet; 7115 7116 // Define some constants used to index and iterate over the arithemetic types 7117 // provided via the getArithmeticType() method below. 7118 // The "promoted arithmetic types" are the arithmetic 7119 // types are that preserved by promotion (C++ [over.built]p2). 7120 static const unsigned FirstIntegralType = 3; 7121 static const unsigned LastIntegralType = 20; 7122 static const unsigned FirstPromotedIntegralType = 3, 7123 LastPromotedIntegralType = 11; 7124 static const unsigned FirstPromotedArithmeticType = 0, 7125 LastPromotedArithmeticType = 11; 7126 static const unsigned NumArithmeticTypes = 20; 7127 7128 /// \brief Get the canonical type for a given arithmetic type index. 7129 CanQualType getArithmeticType(unsigned index) { 7130 assert(index < NumArithmeticTypes); 7131 static CanQualType ASTContext::* const 7132 ArithmeticTypes[NumArithmeticTypes] = { 7133 // Start of promoted types. 7134 &ASTContext::FloatTy, 7135 &ASTContext::DoubleTy, 7136 &ASTContext::LongDoubleTy, 7137 7138 // Start of integral types. 7139 &ASTContext::IntTy, 7140 &ASTContext::LongTy, 7141 &ASTContext::LongLongTy, 7142 &ASTContext::Int128Ty, 7143 &ASTContext::UnsignedIntTy, 7144 &ASTContext::UnsignedLongTy, 7145 &ASTContext::UnsignedLongLongTy, 7146 &ASTContext::UnsignedInt128Ty, 7147 // End of promoted types. 7148 7149 &ASTContext::BoolTy, 7150 &ASTContext::CharTy, 7151 &ASTContext::WCharTy, 7152 &ASTContext::Char16Ty, 7153 &ASTContext::Char32Ty, 7154 &ASTContext::SignedCharTy, 7155 &ASTContext::ShortTy, 7156 &ASTContext::UnsignedCharTy, 7157 &ASTContext::UnsignedShortTy, 7158 // End of integral types. 7159 // FIXME: What about complex? What about half? 7160 }; 7161 return S.Context.*ArithmeticTypes[index]; 7162 } 7163 7164 /// \brief Gets the canonical type resulting from the usual arithemetic 7165 /// converions for the given arithmetic types. 7166 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7167 // Accelerator table for performing the usual arithmetic conversions. 7168 // The rules are basically: 7169 // - if either is floating-point, use the wider floating-point 7170 // - if same signedness, use the higher rank 7171 // - if same size, use unsigned of the higher rank 7172 // - use the larger type 7173 // These rules, together with the axiom that higher ranks are 7174 // never smaller, are sufficient to precompute all of these results 7175 // *except* when dealing with signed types of higher rank. 7176 // (we could precompute SLL x UI for all known platforms, but it's 7177 // better not to make any assumptions). 7178 // We assume that int128 has a higher rank than long long on all platforms. 7179 enum PromotedType { 7180 Dep=-1, 7181 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7182 }; 7183 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7184 [LastPromotedArithmeticType] = { 7185 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7186 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7187 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7188 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7189 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7190 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7191 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7192 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7193 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7194 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7195 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7196 }; 7197 7198 assert(L < LastPromotedArithmeticType); 7199 assert(R < LastPromotedArithmeticType); 7200 int Idx = ConversionsTable[L][R]; 7201 7202 // Fast path: the table gives us a concrete answer. 7203 if (Idx != Dep) return getArithmeticType(Idx); 7204 7205 // Slow path: we need to compare widths. 7206 // An invariant is that the signed type has higher rank. 7207 CanQualType LT = getArithmeticType(L), 7208 RT = getArithmeticType(R); 7209 unsigned LW = S.Context.getIntWidth(LT), 7210 RW = S.Context.getIntWidth(RT); 7211 7212 // If they're different widths, use the signed type. 7213 if (LW > RW) return LT; 7214 else if (LW < RW) return RT; 7215 7216 // Otherwise, use the unsigned type of the signed type's rank. 7217 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7218 assert(L == SLL || R == SLL); 7219 return S.Context.UnsignedLongLongTy; 7220 } 7221 7222 /// \brief Helper method to factor out the common pattern of adding overloads 7223 /// for '++' and '--' builtin operators. 7224 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7225 bool HasVolatile, 7226 bool HasRestrict) { 7227 QualType ParamTypes[2] = { 7228 S.Context.getLValueReferenceType(CandidateTy), 7229 S.Context.IntTy 7230 }; 7231 7232 // Non-volatile version. 7233 if (Args.size() == 1) 7234 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7235 else 7236 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7237 7238 // Use a heuristic to reduce number of builtin candidates in the set: 7239 // add volatile version only if there are conversions to a volatile type. 7240 if (HasVolatile) { 7241 ParamTypes[0] = 7242 S.Context.getLValueReferenceType( 7243 S.Context.getVolatileType(CandidateTy)); 7244 if (Args.size() == 1) 7245 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7246 else 7247 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7248 } 7249 7250 // Add restrict version only if there are conversions to a restrict type 7251 // and our candidate type is a non-restrict-qualified pointer. 7252 if (HasRestrict && CandidateTy->isAnyPointerType() && 7253 !CandidateTy.isRestrictQualified()) { 7254 ParamTypes[0] 7255 = S.Context.getLValueReferenceType( 7256 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7257 if (Args.size() == 1) 7258 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7259 else 7260 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7261 7262 if (HasVolatile) { 7263 ParamTypes[0] 7264 = S.Context.getLValueReferenceType( 7265 S.Context.getCVRQualifiedType(CandidateTy, 7266 (Qualifiers::Volatile | 7267 Qualifiers::Restrict))); 7268 if (Args.size() == 1) 7269 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7270 else 7271 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7272 } 7273 } 7274 7275 } 7276 7277 public: 7278 BuiltinOperatorOverloadBuilder( 7279 Sema &S, ArrayRef<Expr *> Args, 7280 Qualifiers VisibleTypeConversionsQuals, 7281 bool HasArithmeticOrEnumeralCandidateType, 7282 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7283 OverloadCandidateSet &CandidateSet) 7284 : S(S), Args(Args), 7285 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7286 HasArithmeticOrEnumeralCandidateType( 7287 HasArithmeticOrEnumeralCandidateType), 7288 CandidateTypes(CandidateTypes), 7289 CandidateSet(CandidateSet) { 7290 // Validate some of our static helper constants in debug builds. 7291 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7292 "Invalid first promoted integral type"); 7293 assert(getArithmeticType(LastPromotedIntegralType - 1) 7294 == S.Context.UnsignedInt128Ty && 7295 "Invalid last promoted integral type"); 7296 assert(getArithmeticType(FirstPromotedArithmeticType) 7297 == S.Context.FloatTy && 7298 "Invalid first promoted arithmetic type"); 7299 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7300 == S.Context.UnsignedInt128Ty && 7301 "Invalid last promoted arithmetic type"); 7302 } 7303 7304 // C++ [over.built]p3: 7305 // 7306 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7307 // is either volatile or empty, there exist candidate operator 7308 // functions of the form 7309 // 7310 // VQ T& operator++(VQ T&); 7311 // T operator++(VQ T&, int); 7312 // 7313 // C++ [over.built]p4: 7314 // 7315 // For every pair (T, VQ), where T is an arithmetic type other 7316 // than bool, and VQ is either volatile or empty, there exist 7317 // candidate operator functions of the form 7318 // 7319 // VQ T& operator--(VQ T&); 7320 // T operator--(VQ T&, int); 7321 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7322 if (!HasArithmeticOrEnumeralCandidateType) 7323 return; 7324 7325 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7326 Arith < NumArithmeticTypes; ++Arith) { 7327 addPlusPlusMinusMinusStyleOverloads( 7328 getArithmeticType(Arith), 7329 VisibleTypeConversionsQuals.hasVolatile(), 7330 VisibleTypeConversionsQuals.hasRestrict()); 7331 } 7332 } 7333 7334 // C++ [over.built]p5: 7335 // 7336 // For every pair (T, VQ), where T is a cv-qualified or 7337 // cv-unqualified object type, and VQ is either volatile or 7338 // empty, there exist candidate operator functions of the form 7339 // 7340 // T*VQ& operator++(T*VQ&); 7341 // T*VQ& operator--(T*VQ&); 7342 // T* operator++(T*VQ&, int); 7343 // T* operator--(T*VQ&, int); 7344 void addPlusPlusMinusMinusPointerOverloads() { 7345 for (BuiltinCandidateTypeSet::iterator 7346 Ptr = CandidateTypes[0].pointer_begin(), 7347 PtrEnd = CandidateTypes[0].pointer_end(); 7348 Ptr != PtrEnd; ++Ptr) { 7349 // Skip pointer types that aren't pointers to object types. 7350 if (!(*Ptr)->getPointeeType()->isObjectType()) 7351 continue; 7352 7353 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7354 (!(*Ptr).isVolatileQualified() && 7355 VisibleTypeConversionsQuals.hasVolatile()), 7356 (!(*Ptr).isRestrictQualified() && 7357 VisibleTypeConversionsQuals.hasRestrict())); 7358 } 7359 } 7360 7361 // C++ [over.built]p6: 7362 // For every cv-qualified or cv-unqualified object type T, there 7363 // exist candidate operator functions of the form 7364 // 7365 // T& operator*(T*); 7366 // 7367 // C++ [over.built]p7: 7368 // For every function type T that does not have cv-qualifiers or a 7369 // ref-qualifier, there exist candidate operator functions of the form 7370 // T& operator*(T*); 7371 void addUnaryStarPointerOverloads() { 7372 for (BuiltinCandidateTypeSet::iterator 7373 Ptr = CandidateTypes[0].pointer_begin(), 7374 PtrEnd = CandidateTypes[0].pointer_end(); 7375 Ptr != PtrEnd; ++Ptr) { 7376 QualType ParamTy = *Ptr; 7377 QualType PointeeTy = ParamTy->getPointeeType(); 7378 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7379 continue; 7380 7381 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7382 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7383 continue; 7384 7385 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7386 &ParamTy, Args, CandidateSet); 7387 } 7388 } 7389 7390 // C++ [over.built]p9: 7391 // For every promoted arithmetic type T, there exist candidate 7392 // operator functions of the form 7393 // 7394 // T operator+(T); 7395 // T operator-(T); 7396 void addUnaryPlusOrMinusArithmeticOverloads() { 7397 if (!HasArithmeticOrEnumeralCandidateType) 7398 return; 7399 7400 for (unsigned Arith = FirstPromotedArithmeticType; 7401 Arith < LastPromotedArithmeticType; ++Arith) { 7402 QualType ArithTy = getArithmeticType(Arith); 7403 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7404 } 7405 7406 // Extension: We also add these operators for vector types. 7407 for (BuiltinCandidateTypeSet::iterator 7408 Vec = CandidateTypes[0].vector_begin(), 7409 VecEnd = CandidateTypes[0].vector_end(); 7410 Vec != VecEnd; ++Vec) { 7411 QualType VecTy = *Vec; 7412 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7413 } 7414 } 7415 7416 // C++ [over.built]p8: 7417 // For every type T, there exist candidate operator functions of 7418 // the form 7419 // 7420 // T* operator+(T*); 7421 void addUnaryPlusPointerOverloads() { 7422 for (BuiltinCandidateTypeSet::iterator 7423 Ptr = CandidateTypes[0].pointer_begin(), 7424 PtrEnd = CandidateTypes[0].pointer_end(); 7425 Ptr != PtrEnd; ++Ptr) { 7426 QualType ParamTy = *Ptr; 7427 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7428 } 7429 } 7430 7431 // C++ [over.built]p10: 7432 // For every promoted integral type T, there exist candidate 7433 // operator functions of the form 7434 // 7435 // T operator~(T); 7436 void addUnaryTildePromotedIntegralOverloads() { 7437 if (!HasArithmeticOrEnumeralCandidateType) 7438 return; 7439 7440 for (unsigned Int = FirstPromotedIntegralType; 7441 Int < LastPromotedIntegralType; ++Int) { 7442 QualType IntTy = getArithmeticType(Int); 7443 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7444 } 7445 7446 // Extension: We also add this operator for vector types. 7447 for (BuiltinCandidateTypeSet::iterator 7448 Vec = CandidateTypes[0].vector_begin(), 7449 VecEnd = CandidateTypes[0].vector_end(); 7450 Vec != VecEnd; ++Vec) { 7451 QualType VecTy = *Vec; 7452 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7453 } 7454 } 7455 7456 // C++ [over.match.oper]p16: 7457 // For every pointer to member type T, there exist candidate operator 7458 // functions of the form 7459 // 7460 // bool operator==(T,T); 7461 // bool operator!=(T,T); 7462 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7463 /// Set of (canonical) types that we've already handled. 7464 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7465 7466 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7467 for (BuiltinCandidateTypeSet::iterator 7468 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7469 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7470 MemPtr != MemPtrEnd; 7471 ++MemPtr) { 7472 // Don't add the same builtin candidate twice. 7473 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7474 continue; 7475 7476 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7477 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7478 } 7479 } 7480 } 7481 7482 // C++ [over.built]p15: 7483 // 7484 // For every T, where T is an enumeration type, a pointer type, or 7485 // std::nullptr_t, there exist candidate operator functions of the form 7486 // 7487 // bool operator<(T, T); 7488 // bool operator>(T, T); 7489 // bool operator<=(T, T); 7490 // bool operator>=(T, T); 7491 // bool operator==(T, T); 7492 // bool operator!=(T, T); 7493 void addRelationalPointerOrEnumeralOverloads() { 7494 // C++ [over.match.oper]p3: 7495 // [...]the built-in candidates include all of the candidate operator 7496 // functions defined in 13.6 that, compared to the given operator, [...] 7497 // do not have the same parameter-type-list as any non-template non-member 7498 // candidate. 7499 // 7500 // Note that in practice, this only affects enumeration types because there 7501 // aren't any built-in candidates of record type, and a user-defined operator 7502 // must have an operand of record or enumeration type. Also, the only other 7503 // overloaded operator with enumeration arguments, operator=, 7504 // cannot be overloaded for enumeration types, so this is the only place 7505 // where we must suppress candidates like this. 7506 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7507 UserDefinedBinaryOperators; 7508 7509 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7510 if (CandidateTypes[ArgIdx].enumeration_begin() != 7511 CandidateTypes[ArgIdx].enumeration_end()) { 7512 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7513 CEnd = CandidateSet.end(); 7514 C != CEnd; ++C) { 7515 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7516 continue; 7517 7518 if (C->Function->isFunctionTemplateSpecialization()) 7519 continue; 7520 7521 QualType FirstParamType = 7522 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7523 QualType SecondParamType = 7524 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7525 7526 // Skip if either parameter isn't of enumeral type. 7527 if (!FirstParamType->isEnumeralType() || 7528 !SecondParamType->isEnumeralType()) 7529 continue; 7530 7531 // Add this operator to the set of known user-defined operators. 7532 UserDefinedBinaryOperators.insert( 7533 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7534 S.Context.getCanonicalType(SecondParamType))); 7535 } 7536 } 7537 } 7538 7539 /// Set of (canonical) types that we've already handled. 7540 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7541 7542 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7543 for (BuiltinCandidateTypeSet::iterator 7544 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7545 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7546 Ptr != PtrEnd; ++Ptr) { 7547 // Don't add the same builtin candidate twice. 7548 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7549 continue; 7550 7551 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7552 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7553 } 7554 for (BuiltinCandidateTypeSet::iterator 7555 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7556 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7557 Enum != EnumEnd; ++Enum) { 7558 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7559 7560 // Don't add the same builtin candidate twice, or if a user defined 7561 // candidate exists. 7562 if (!AddedTypes.insert(CanonType).second || 7563 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7564 CanonType))) 7565 continue; 7566 7567 QualType ParamTypes[2] = { *Enum, *Enum }; 7568 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7569 } 7570 7571 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7572 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7573 if (AddedTypes.insert(NullPtrTy).second && 7574 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7575 NullPtrTy))) { 7576 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7577 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7578 CandidateSet); 7579 } 7580 } 7581 } 7582 } 7583 7584 // C++ [over.built]p13: 7585 // 7586 // For every cv-qualified or cv-unqualified object type T 7587 // there exist candidate operator functions of the form 7588 // 7589 // T* operator+(T*, ptrdiff_t); 7590 // T& operator[](T*, ptrdiff_t); [BELOW] 7591 // T* operator-(T*, ptrdiff_t); 7592 // T* operator+(ptrdiff_t, T*); 7593 // T& operator[](ptrdiff_t, T*); [BELOW] 7594 // 7595 // C++ [over.built]p14: 7596 // 7597 // For every T, where T is a pointer to object type, there 7598 // exist candidate operator functions of the form 7599 // 7600 // ptrdiff_t operator-(T, T); 7601 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7602 /// Set of (canonical) types that we've already handled. 7603 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7604 7605 for (int Arg = 0; Arg < 2; ++Arg) { 7606 QualType AsymmetricParamTypes[2] = { 7607 S.Context.getPointerDiffType(), 7608 S.Context.getPointerDiffType(), 7609 }; 7610 for (BuiltinCandidateTypeSet::iterator 7611 Ptr = CandidateTypes[Arg].pointer_begin(), 7612 PtrEnd = CandidateTypes[Arg].pointer_end(); 7613 Ptr != PtrEnd; ++Ptr) { 7614 QualType PointeeTy = (*Ptr)->getPointeeType(); 7615 if (!PointeeTy->isObjectType()) 7616 continue; 7617 7618 AsymmetricParamTypes[Arg] = *Ptr; 7619 if (Arg == 0 || Op == OO_Plus) { 7620 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7621 // T* operator+(ptrdiff_t, T*); 7622 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7623 } 7624 if (Op == OO_Minus) { 7625 // ptrdiff_t operator-(T, T); 7626 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7627 continue; 7628 7629 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7630 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7631 Args, CandidateSet); 7632 } 7633 } 7634 } 7635 } 7636 7637 // C++ [over.built]p12: 7638 // 7639 // For every pair of promoted arithmetic types L and R, there 7640 // exist candidate operator functions of the form 7641 // 7642 // LR operator*(L, R); 7643 // LR operator/(L, R); 7644 // LR operator+(L, R); 7645 // LR operator-(L, R); 7646 // bool operator<(L, R); 7647 // bool operator>(L, R); 7648 // bool operator<=(L, R); 7649 // bool operator>=(L, R); 7650 // bool operator==(L, R); 7651 // bool operator!=(L, R); 7652 // 7653 // where LR is the result of the usual arithmetic conversions 7654 // between types L and R. 7655 // 7656 // C++ [over.built]p24: 7657 // 7658 // For every pair of promoted arithmetic types L and R, there exist 7659 // candidate operator functions of the form 7660 // 7661 // LR operator?(bool, L, R); 7662 // 7663 // where LR is the result of the usual arithmetic conversions 7664 // between types L and R. 7665 // Our candidates ignore the first parameter. 7666 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7667 if (!HasArithmeticOrEnumeralCandidateType) 7668 return; 7669 7670 for (unsigned Left = FirstPromotedArithmeticType; 7671 Left < LastPromotedArithmeticType; ++Left) { 7672 for (unsigned Right = FirstPromotedArithmeticType; 7673 Right < LastPromotedArithmeticType; ++Right) { 7674 QualType LandR[2] = { getArithmeticType(Left), 7675 getArithmeticType(Right) }; 7676 QualType Result = 7677 isComparison ? S.Context.BoolTy 7678 : getUsualArithmeticConversions(Left, Right); 7679 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7680 } 7681 } 7682 7683 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7684 // conditional operator for vector types. 7685 for (BuiltinCandidateTypeSet::iterator 7686 Vec1 = CandidateTypes[0].vector_begin(), 7687 Vec1End = CandidateTypes[0].vector_end(); 7688 Vec1 != Vec1End; ++Vec1) { 7689 for (BuiltinCandidateTypeSet::iterator 7690 Vec2 = CandidateTypes[1].vector_begin(), 7691 Vec2End = CandidateTypes[1].vector_end(); 7692 Vec2 != Vec2End; ++Vec2) { 7693 QualType LandR[2] = { *Vec1, *Vec2 }; 7694 QualType Result = S.Context.BoolTy; 7695 if (!isComparison) { 7696 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7697 Result = *Vec1; 7698 else 7699 Result = *Vec2; 7700 } 7701 7702 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7703 } 7704 } 7705 } 7706 7707 // C++ [over.built]p17: 7708 // 7709 // For every pair of promoted integral types L and R, there 7710 // exist candidate operator functions of the form 7711 // 7712 // LR operator%(L, R); 7713 // LR operator&(L, R); 7714 // LR operator^(L, R); 7715 // LR operator|(L, R); 7716 // L operator<<(L, R); 7717 // L operator>>(L, R); 7718 // 7719 // where LR is the result of the usual arithmetic conversions 7720 // between types L and R. 7721 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7722 if (!HasArithmeticOrEnumeralCandidateType) 7723 return; 7724 7725 for (unsigned Left = FirstPromotedIntegralType; 7726 Left < LastPromotedIntegralType; ++Left) { 7727 for (unsigned Right = FirstPromotedIntegralType; 7728 Right < LastPromotedIntegralType; ++Right) { 7729 QualType LandR[2] = { getArithmeticType(Left), 7730 getArithmeticType(Right) }; 7731 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7732 ? LandR[0] 7733 : getUsualArithmeticConversions(Left, Right); 7734 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7735 } 7736 } 7737 } 7738 7739 // C++ [over.built]p20: 7740 // 7741 // For every pair (T, VQ), where T is an enumeration or 7742 // pointer to member type and VQ is either volatile or 7743 // empty, there exist candidate operator functions of the form 7744 // 7745 // VQ T& operator=(VQ T&, T); 7746 void addAssignmentMemberPointerOrEnumeralOverloads() { 7747 /// Set of (canonical) types that we've already handled. 7748 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7749 7750 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7751 for (BuiltinCandidateTypeSet::iterator 7752 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7753 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7754 Enum != EnumEnd; ++Enum) { 7755 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7756 continue; 7757 7758 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7759 } 7760 7761 for (BuiltinCandidateTypeSet::iterator 7762 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7763 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7764 MemPtr != MemPtrEnd; ++MemPtr) { 7765 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7766 continue; 7767 7768 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7769 } 7770 } 7771 } 7772 7773 // C++ [over.built]p19: 7774 // 7775 // For every pair (T, VQ), where T is any type and VQ is either 7776 // volatile or empty, there exist candidate operator functions 7777 // of the form 7778 // 7779 // T*VQ& operator=(T*VQ&, T*); 7780 // 7781 // C++ [over.built]p21: 7782 // 7783 // For every pair (T, VQ), where T is a cv-qualified or 7784 // cv-unqualified object type and VQ is either volatile or 7785 // empty, there exist candidate operator functions of the form 7786 // 7787 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7788 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7789 void addAssignmentPointerOverloads(bool isEqualOp) { 7790 /// Set of (canonical) types that we've already handled. 7791 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7792 7793 for (BuiltinCandidateTypeSet::iterator 7794 Ptr = CandidateTypes[0].pointer_begin(), 7795 PtrEnd = CandidateTypes[0].pointer_end(); 7796 Ptr != PtrEnd; ++Ptr) { 7797 // If this is operator=, keep track of the builtin candidates we added. 7798 if (isEqualOp) 7799 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7800 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7801 continue; 7802 7803 // non-volatile version 7804 QualType ParamTypes[2] = { 7805 S.Context.getLValueReferenceType(*Ptr), 7806 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7807 }; 7808 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7809 /*IsAssigmentOperator=*/ isEqualOp); 7810 7811 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7812 VisibleTypeConversionsQuals.hasVolatile(); 7813 if (NeedVolatile) { 7814 // volatile version 7815 ParamTypes[0] = 7816 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7817 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7818 /*IsAssigmentOperator=*/isEqualOp); 7819 } 7820 7821 if (!(*Ptr).isRestrictQualified() && 7822 VisibleTypeConversionsQuals.hasRestrict()) { 7823 // restrict version 7824 ParamTypes[0] 7825 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7826 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7827 /*IsAssigmentOperator=*/isEqualOp); 7828 7829 if (NeedVolatile) { 7830 // volatile restrict version 7831 ParamTypes[0] 7832 = S.Context.getLValueReferenceType( 7833 S.Context.getCVRQualifiedType(*Ptr, 7834 (Qualifiers::Volatile | 7835 Qualifiers::Restrict))); 7836 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7837 /*IsAssigmentOperator=*/isEqualOp); 7838 } 7839 } 7840 } 7841 7842 if (isEqualOp) { 7843 for (BuiltinCandidateTypeSet::iterator 7844 Ptr = CandidateTypes[1].pointer_begin(), 7845 PtrEnd = CandidateTypes[1].pointer_end(); 7846 Ptr != PtrEnd; ++Ptr) { 7847 // Make sure we don't add the same candidate twice. 7848 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7849 continue; 7850 7851 QualType ParamTypes[2] = { 7852 S.Context.getLValueReferenceType(*Ptr), 7853 *Ptr, 7854 }; 7855 7856 // non-volatile version 7857 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7858 /*IsAssigmentOperator=*/true); 7859 7860 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7861 VisibleTypeConversionsQuals.hasVolatile(); 7862 if (NeedVolatile) { 7863 // volatile version 7864 ParamTypes[0] = 7865 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7866 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7867 /*IsAssigmentOperator=*/true); 7868 } 7869 7870 if (!(*Ptr).isRestrictQualified() && 7871 VisibleTypeConversionsQuals.hasRestrict()) { 7872 // restrict version 7873 ParamTypes[0] 7874 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7875 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7876 /*IsAssigmentOperator=*/true); 7877 7878 if (NeedVolatile) { 7879 // volatile restrict version 7880 ParamTypes[0] 7881 = S.Context.getLValueReferenceType( 7882 S.Context.getCVRQualifiedType(*Ptr, 7883 (Qualifiers::Volatile | 7884 Qualifiers::Restrict))); 7885 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7886 /*IsAssigmentOperator=*/true); 7887 } 7888 } 7889 } 7890 } 7891 } 7892 7893 // C++ [over.built]p18: 7894 // 7895 // For every triple (L, VQ, R), where L is an arithmetic type, 7896 // VQ is either volatile or empty, and R is a promoted 7897 // arithmetic type, there exist candidate operator functions of 7898 // the form 7899 // 7900 // VQ L& operator=(VQ L&, R); 7901 // VQ L& operator*=(VQ L&, R); 7902 // VQ L& operator/=(VQ L&, R); 7903 // VQ L& operator+=(VQ L&, R); 7904 // VQ L& operator-=(VQ L&, R); 7905 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7906 if (!HasArithmeticOrEnumeralCandidateType) 7907 return; 7908 7909 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7910 for (unsigned Right = FirstPromotedArithmeticType; 7911 Right < LastPromotedArithmeticType; ++Right) { 7912 QualType ParamTypes[2]; 7913 ParamTypes[1] = getArithmeticType(Right); 7914 7915 // Add this built-in operator as a candidate (VQ is empty). 7916 ParamTypes[0] = 7917 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7918 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7919 /*IsAssigmentOperator=*/isEqualOp); 7920 7921 // Add this built-in operator as a candidate (VQ is 'volatile'). 7922 if (VisibleTypeConversionsQuals.hasVolatile()) { 7923 ParamTypes[0] = 7924 S.Context.getVolatileType(getArithmeticType(Left)); 7925 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7926 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7927 /*IsAssigmentOperator=*/isEqualOp); 7928 } 7929 } 7930 } 7931 7932 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7933 for (BuiltinCandidateTypeSet::iterator 7934 Vec1 = CandidateTypes[0].vector_begin(), 7935 Vec1End = CandidateTypes[0].vector_end(); 7936 Vec1 != Vec1End; ++Vec1) { 7937 for (BuiltinCandidateTypeSet::iterator 7938 Vec2 = CandidateTypes[1].vector_begin(), 7939 Vec2End = CandidateTypes[1].vector_end(); 7940 Vec2 != Vec2End; ++Vec2) { 7941 QualType ParamTypes[2]; 7942 ParamTypes[1] = *Vec2; 7943 // Add this built-in operator as a candidate (VQ is empty). 7944 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7945 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7946 /*IsAssigmentOperator=*/isEqualOp); 7947 7948 // Add this built-in operator as a candidate (VQ is 'volatile'). 7949 if (VisibleTypeConversionsQuals.hasVolatile()) { 7950 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7951 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7952 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7953 /*IsAssigmentOperator=*/isEqualOp); 7954 } 7955 } 7956 } 7957 } 7958 7959 // C++ [over.built]p22: 7960 // 7961 // For every triple (L, VQ, R), where L is an integral type, VQ 7962 // is either volatile or empty, and R is a promoted integral 7963 // type, there exist candidate operator functions of the form 7964 // 7965 // VQ L& operator%=(VQ L&, R); 7966 // VQ L& operator<<=(VQ L&, R); 7967 // VQ L& operator>>=(VQ L&, R); 7968 // VQ L& operator&=(VQ L&, R); 7969 // VQ L& operator^=(VQ L&, R); 7970 // VQ L& operator|=(VQ L&, R); 7971 void addAssignmentIntegralOverloads() { 7972 if (!HasArithmeticOrEnumeralCandidateType) 7973 return; 7974 7975 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7976 for (unsigned Right = FirstPromotedIntegralType; 7977 Right < LastPromotedIntegralType; ++Right) { 7978 QualType ParamTypes[2]; 7979 ParamTypes[1] = getArithmeticType(Right); 7980 7981 // Add this built-in operator as a candidate (VQ is empty). 7982 ParamTypes[0] = 7983 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7984 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7985 if (VisibleTypeConversionsQuals.hasVolatile()) { 7986 // Add this built-in operator as a candidate (VQ is 'volatile'). 7987 ParamTypes[0] = getArithmeticType(Left); 7988 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7989 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7990 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7991 } 7992 } 7993 } 7994 } 7995 7996 // C++ [over.operator]p23: 7997 // 7998 // There also exist candidate operator functions of the form 7999 // 8000 // bool operator!(bool); 8001 // bool operator&&(bool, bool); 8002 // bool operator||(bool, bool); 8003 void addExclaimOverload() { 8004 QualType ParamTy = S.Context.BoolTy; 8005 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8006 /*IsAssignmentOperator=*/false, 8007 /*NumContextualBoolArguments=*/1); 8008 } 8009 void addAmpAmpOrPipePipeOverload() { 8010 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8011 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8012 /*IsAssignmentOperator=*/false, 8013 /*NumContextualBoolArguments=*/2); 8014 } 8015 8016 // C++ [over.built]p13: 8017 // 8018 // For every cv-qualified or cv-unqualified object type T there 8019 // exist candidate operator functions of the form 8020 // 8021 // T* operator+(T*, ptrdiff_t); [ABOVE] 8022 // T& operator[](T*, ptrdiff_t); 8023 // T* operator-(T*, ptrdiff_t); [ABOVE] 8024 // T* operator+(ptrdiff_t, T*); [ABOVE] 8025 // T& operator[](ptrdiff_t, T*); 8026 void addSubscriptOverloads() { 8027 for (BuiltinCandidateTypeSet::iterator 8028 Ptr = CandidateTypes[0].pointer_begin(), 8029 PtrEnd = CandidateTypes[0].pointer_end(); 8030 Ptr != PtrEnd; ++Ptr) { 8031 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8032 QualType PointeeType = (*Ptr)->getPointeeType(); 8033 if (!PointeeType->isObjectType()) 8034 continue; 8035 8036 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8037 8038 // T& operator[](T*, ptrdiff_t) 8039 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8040 } 8041 8042 for (BuiltinCandidateTypeSet::iterator 8043 Ptr = CandidateTypes[1].pointer_begin(), 8044 PtrEnd = CandidateTypes[1].pointer_end(); 8045 Ptr != PtrEnd; ++Ptr) { 8046 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8047 QualType PointeeType = (*Ptr)->getPointeeType(); 8048 if (!PointeeType->isObjectType()) 8049 continue; 8050 8051 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8052 8053 // T& operator[](ptrdiff_t, T*) 8054 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8055 } 8056 } 8057 8058 // C++ [over.built]p11: 8059 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8060 // C1 is the same type as C2 or is a derived class of C2, T is an object 8061 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8062 // there exist candidate operator functions of the form 8063 // 8064 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8065 // 8066 // where CV12 is the union of CV1 and CV2. 8067 void addArrowStarOverloads() { 8068 for (BuiltinCandidateTypeSet::iterator 8069 Ptr = CandidateTypes[0].pointer_begin(), 8070 PtrEnd = CandidateTypes[0].pointer_end(); 8071 Ptr != PtrEnd; ++Ptr) { 8072 QualType C1Ty = (*Ptr); 8073 QualType C1; 8074 QualifierCollector Q1; 8075 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8076 if (!isa<RecordType>(C1)) 8077 continue; 8078 // heuristic to reduce number of builtin candidates in the set. 8079 // Add volatile/restrict version only if there are conversions to a 8080 // volatile/restrict type. 8081 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8082 continue; 8083 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8084 continue; 8085 for (BuiltinCandidateTypeSet::iterator 8086 MemPtr = CandidateTypes[1].member_pointer_begin(), 8087 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8088 MemPtr != MemPtrEnd; ++MemPtr) { 8089 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8090 QualType C2 = QualType(mptr->getClass(), 0); 8091 C2 = C2.getUnqualifiedType(); 8092 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 8093 break; 8094 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8095 // build CV12 T& 8096 QualType T = mptr->getPointeeType(); 8097 if (!VisibleTypeConversionsQuals.hasVolatile() && 8098 T.isVolatileQualified()) 8099 continue; 8100 if (!VisibleTypeConversionsQuals.hasRestrict() && 8101 T.isRestrictQualified()) 8102 continue; 8103 T = Q1.apply(S.Context, T); 8104 QualType ResultTy = S.Context.getLValueReferenceType(T); 8105 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8106 } 8107 } 8108 } 8109 8110 // Note that we don't consider the first argument, since it has been 8111 // contextually converted to bool long ago. The candidates below are 8112 // therefore added as binary. 8113 // 8114 // C++ [over.built]p25: 8115 // For every type T, where T is a pointer, pointer-to-member, or scoped 8116 // enumeration type, there exist candidate operator functions of the form 8117 // 8118 // T operator?(bool, T, T); 8119 // 8120 void addConditionalOperatorOverloads() { 8121 /// Set of (canonical) types that we've already handled. 8122 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8123 8124 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8125 for (BuiltinCandidateTypeSet::iterator 8126 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8127 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8128 Ptr != PtrEnd; ++Ptr) { 8129 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8130 continue; 8131 8132 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8133 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8134 } 8135 8136 for (BuiltinCandidateTypeSet::iterator 8137 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8138 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8139 MemPtr != MemPtrEnd; ++MemPtr) { 8140 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8141 continue; 8142 8143 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8144 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8145 } 8146 8147 if (S.getLangOpts().CPlusPlus11) { 8148 for (BuiltinCandidateTypeSet::iterator 8149 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8150 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8151 Enum != EnumEnd; ++Enum) { 8152 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8153 continue; 8154 8155 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8156 continue; 8157 8158 QualType ParamTypes[2] = { *Enum, *Enum }; 8159 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8160 } 8161 } 8162 } 8163 } 8164 }; 8165 8166 } // end anonymous namespace 8167 8168 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8169 /// operator overloads to the candidate set (C++ [over.built]), based 8170 /// on the operator @p Op and the arguments given. For example, if the 8171 /// operator is a binary '+', this routine might add "int 8172 /// operator+(int, int)" to cover integer addition. 8173 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8174 SourceLocation OpLoc, 8175 ArrayRef<Expr *> Args, 8176 OverloadCandidateSet &CandidateSet) { 8177 // Find all of the types that the arguments can convert to, but only 8178 // if the operator we're looking at has built-in operator candidates 8179 // that make use of these types. Also record whether we encounter non-record 8180 // candidate types or either arithmetic or enumeral candidate types. 8181 Qualifiers VisibleTypeConversionsQuals; 8182 VisibleTypeConversionsQuals.addConst(); 8183 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8184 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8185 8186 bool HasNonRecordCandidateType = false; 8187 bool HasArithmeticOrEnumeralCandidateType = false; 8188 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8189 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8190 CandidateTypes.emplace_back(*this); 8191 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8192 OpLoc, 8193 true, 8194 (Op == OO_Exclaim || 8195 Op == OO_AmpAmp || 8196 Op == OO_PipePipe), 8197 VisibleTypeConversionsQuals); 8198 HasNonRecordCandidateType = HasNonRecordCandidateType || 8199 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8200 HasArithmeticOrEnumeralCandidateType = 8201 HasArithmeticOrEnumeralCandidateType || 8202 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8203 } 8204 8205 // Exit early when no non-record types have been added to the candidate set 8206 // for any of the arguments to the operator. 8207 // 8208 // We can't exit early for !, ||, or &&, since there we have always have 8209 // 'bool' overloads. 8210 if (!HasNonRecordCandidateType && 8211 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8212 return; 8213 8214 // Setup an object to manage the common state for building overloads. 8215 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8216 VisibleTypeConversionsQuals, 8217 HasArithmeticOrEnumeralCandidateType, 8218 CandidateTypes, CandidateSet); 8219 8220 // Dispatch over the operation to add in only those overloads which apply. 8221 switch (Op) { 8222 case OO_None: 8223 case NUM_OVERLOADED_OPERATORS: 8224 llvm_unreachable("Expected an overloaded operator"); 8225 8226 case OO_New: 8227 case OO_Delete: 8228 case OO_Array_New: 8229 case OO_Array_Delete: 8230 case OO_Call: 8231 case OO_Coawait: 8232 llvm_unreachable( 8233 "Special operators don't use AddBuiltinOperatorCandidates"); 8234 8235 case OO_Comma: 8236 case OO_Arrow: 8237 // C++ [over.match.oper]p3: 8238 // -- For the operator ',', the unary operator '&', or the 8239 // operator '->', the built-in candidates set is empty. 8240 break; 8241 8242 case OO_Plus: // '+' is either unary or binary 8243 if (Args.size() == 1) 8244 OpBuilder.addUnaryPlusPointerOverloads(); 8245 // Fall through. 8246 8247 case OO_Minus: // '-' is either unary or binary 8248 if (Args.size() == 1) { 8249 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8250 } else { 8251 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8252 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8253 } 8254 break; 8255 8256 case OO_Star: // '*' is either unary or binary 8257 if (Args.size() == 1) 8258 OpBuilder.addUnaryStarPointerOverloads(); 8259 else 8260 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8261 break; 8262 8263 case OO_Slash: 8264 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8265 break; 8266 8267 case OO_PlusPlus: 8268 case OO_MinusMinus: 8269 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8270 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8271 break; 8272 8273 case OO_EqualEqual: 8274 case OO_ExclaimEqual: 8275 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8276 // Fall through. 8277 8278 case OO_Less: 8279 case OO_Greater: 8280 case OO_LessEqual: 8281 case OO_GreaterEqual: 8282 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8283 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8284 break; 8285 8286 case OO_Percent: 8287 case OO_Caret: 8288 case OO_Pipe: 8289 case OO_LessLess: 8290 case OO_GreaterGreater: 8291 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8292 break; 8293 8294 case OO_Amp: // '&' is either unary or binary 8295 if (Args.size() == 1) 8296 // C++ [over.match.oper]p3: 8297 // -- For the operator ',', the unary operator '&', or the 8298 // operator '->', the built-in candidates set is empty. 8299 break; 8300 8301 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8302 break; 8303 8304 case OO_Tilde: 8305 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8306 break; 8307 8308 case OO_Equal: 8309 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8310 // Fall through. 8311 8312 case OO_PlusEqual: 8313 case OO_MinusEqual: 8314 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8315 // Fall through. 8316 8317 case OO_StarEqual: 8318 case OO_SlashEqual: 8319 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8320 break; 8321 8322 case OO_PercentEqual: 8323 case OO_LessLessEqual: 8324 case OO_GreaterGreaterEqual: 8325 case OO_AmpEqual: 8326 case OO_CaretEqual: 8327 case OO_PipeEqual: 8328 OpBuilder.addAssignmentIntegralOverloads(); 8329 break; 8330 8331 case OO_Exclaim: 8332 OpBuilder.addExclaimOverload(); 8333 break; 8334 8335 case OO_AmpAmp: 8336 case OO_PipePipe: 8337 OpBuilder.addAmpAmpOrPipePipeOverload(); 8338 break; 8339 8340 case OO_Subscript: 8341 OpBuilder.addSubscriptOverloads(); 8342 break; 8343 8344 case OO_ArrowStar: 8345 OpBuilder.addArrowStarOverloads(); 8346 break; 8347 8348 case OO_Conditional: 8349 OpBuilder.addConditionalOperatorOverloads(); 8350 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8351 break; 8352 } 8353 } 8354 8355 /// \brief Add function candidates found via argument-dependent lookup 8356 /// to the set of overloading candidates. 8357 /// 8358 /// This routine performs argument-dependent name lookup based on the 8359 /// given function name (which may also be an operator name) and adds 8360 /// all of the overload candidates found by ADL to the overload 8361 /// candidate set (C++ [basic.lookup.argdep]). 8362 void 8363 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8364 SourceLocation Loc, 8365 ArrayRef<Expr *> Args, 8366 TemplateArgumentListInfo *ExplicitTemplateArgs, 8367 OverloadCandidateSet& CandidateSet, 8368 bool PartialOverloading) { 8369 ADLResult Fns; 8370 8371 // FIXME: This approach for uniquing ADL results (and removing 8372 // redundant candidates from the set) relies on pointer-equality, 8373 // which means we need to key off the canonical decl. However, 8374 // always going back to the canonical decl might not get us the 8375 // right set of default arguments. What default arguments are 8376 // we supposed to consider on ADL candidates, anyway? 8377 8378 // FIXME: Pass in the explicit template arguments? 8379 ArgumentDependentLookup(Name, Loc, Args, Fns); 8380 8381 // Erase all of the candidates we already knew about. 8382 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8383 CandEnd = CandidateSet.end(); 8384 Cand != CandEnd; ++Cand) 8385 if (Cand->Function) { 8386 Fns.erase(Cand->Function); 8387 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8388 Fns.erase(FunTmpl); 8389 } 8390 8391 // For each of the ADL candidates we found, add it to the overload 8392 // set. 8393 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8394 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8395 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8396 if (ExplicitTemplateArgs) 8397 continue; 8398 8399 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8400 PartialOverloading); 8401 } else 8402 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8403 FoundDecl, ExplicitTemplateArgs, 8404 Args, CandidateSet, PartialOverloading); 8405 } 8406 } 8407 8408 // Determines whether Cand1 is "better" in terms of its enable_if attrs than 8409 // Cand2 for overloading. This function assumes that all of the enable_if attrs 8410 // on Cand1 and Cand2 have conditions that evaluate to true. 8411 // 8412 // Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8413 // Cand1's first N enable_if attributes have precisely the same conditions as 8414 // Cand2's first N enable_if attributes (where N = the number of enable_if 8415 // attributes on Cand2), and Cand1 has more than N enable_if attributes. 8416 static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1, 8417 const FunctionDecl *Cand2) { 8418 8419 // FIXME: The next several lines are just 8420 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8421 // instead of reverse order which is how they're stored in the AST. 8422 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8423 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8424 8425 // Candidate 1 is better if it has strictly more attributes and 8426 // the common sequence is identical. 8427 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8428 return false; 8429 8430 auto Cand1I = Cand1Attrs.begin(); 8431 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8432 for (auto &Cand2A : Cand2Attrs) { 8433 Cand1ID.clear(); 8434 Cand2ID.clear(); 8435 8436 auto &Cand1A = *Cand1I++; 8437 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8438 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8439 if (Cand1ID != Cand2ID) 8440 return false; 8441 } 8442 8443 return true; 8444 } 8445 8446 /// isBetterOverloadCandidate - Determines whether the first overload 8447 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8448 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8449 const OverloadCandidate &Cand2, 8450 SourceLocation Loc, 8451 bool UserDefinedConversion) { 8452 // Define viable functions to be better candidates than non-viable 8453 // functions. 8454 if (!Cand2.Viable) 8455 return Cand1.Viable; 8456 else if (!Cand1.Viable) 8457 return false; 8458 8459 // C++ [over.match.best]p1: 8460 // 8461 // -- if F is a static member function, ICS1(F) is defined such 8462 // that ICS1(F) is neither better nor worse than ICS1(G) for 8463 // any function G, and, symmetrically, ICS1(G) is neither 8464 // better nor worse than ICS1(F). 8465 unsigned StartArg = 0; 8466 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8467 StartArg = 1; 8468 8469 // C++ [over.match.best]p1: 8470 // A viable function F1 is defined to be a better function than another 8471 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8472 // conversion sequence than ICSi(F2), and then... 8473 unsigned NumArgs = Cand1.NumConversions; 8474 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8475 bool HasBetterConversion = false; 8476 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8477 switch (CompareImplicitConversionSequences(S, 8478 Cand1.Conversions[ArgIdx], 8479 Cand2.Conversions[ArgIdx])) { 8480 case ImplicitConversionSequence::Better: 8481 // Cand1 has a better conversion sequence. 8482 HasBetterConversion = true; 8483 break; 8484 8485 case ImplicitConversionSequence::Worse: 8486 // Cand1 can't be better than Cand2. 8487 return false; 8488 8489 case ImplicitConversionSequence::Indistinguishable: 8490 // Do nothing. 8491 break; 8492 } 8493 } 8494 8495 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8496 // ICSj(F2), or, if not that, 8497 if (HasBetterConversion) 8498 return true; 8499 8500 // -- the context is an initialization by user-defined conversion 8501 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8502 // from the return type of F1 to the destination type (i.e., 8503 // the type of the entity being initialized) is a better 8504 // conversion sequence than the standard conversion sequence 8505 // from the return type of F2 to the destination type. 8506 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8507 isa<CXXConversionDecl>(Cand1.Function) && 8508 isa<CXXConversionDecl>(Cand2.Function)) { 8509 // First check whether we prefer one of the conversion functions over the 8510 // other. This only distinguishes the results in non-standard, extension 8511 // cases such as the conversion from a lambda closure type to a function 8512 // pointer or block. 8513 ImplicitConversionSequence::CompareKind Result = 8514 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8515 if (Result == ImplicitConversionSequence::Indistinguishable) 8516 Result = CompareStandardConversionSequences(S, 8517 Cand1.FinalConversion, 8518 Cand2.FinalConversion); 8519 8520 if (Result != ImplicitConversionSequence::Indistinguishable) 8521 return Result == ImplicitConversionSequence::Better; 8522 8523 // FIXME: Compare kind of reference binding if conversion functions 8524 // convert to a reference type used in direct reference binding, per 8525 // C++14 [over.match.best]p1 section 2 bullet 3. 8526 } 8527 8528 // -- F1 is a non-template function and F2 is a function template 8529 // specialization, or, if not that, 8530 bool Cand1IsSpecialization = Cand1.Function && 8531 Cand1.Function->getPrimaryTemplate(); 8532 bool Cand2IsSpecialization = Cand2.Function && 8533 Cand2.Function->getPrimaryTemplate(); 8534 if (Cand1IsSpecialization != Cand2IsSpecialization) 8535 return Cand2IsSpecialization; 8536 8537 // -- F1 and F2 are function template specializations, and the function 8538 // template for F1 is more specialized than the template for F2 8539 // according to the partial ordering rules described in 14.5.5.2, or, 8540 // if not that, 8541 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8542 if (FunctionTemplateDecl *BetterTemplate 8543 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8544 Cand2.Function->getPrimaryTemplate(), 8545 Loc, 8546 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8547 : TPOC_Call, 8548 Cand1.ExplicitCallArguments, 8549 Cand2.ExplicitCallArguments)) 8550 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8551 } 8552 8553 // Check for enable_if value-based overload resolution. 8554 if (Cand1.Function && Cand2.Function && 8555 (Cand1.Function->hasAttr<EnableIfAttr>() || 8556 Cand2.Function->hasAttr<EnableIfAttr>())) 8557 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8558 8559 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 8560 Cand1.Function && Cand2.Function) { 8561 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8562 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8563 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8564 } 8565 8566 return false; 8567 } 8568 8569 /// Determine whether two function declarations are "equivalent" for overload 8570 /// resolution purposes. This applies when the same internal linkage function 8571 /// is defined by two modules (textually including the same header). In such 8572 /// a case, we don't consider the declarations to declare the same entity, but 8573 /// we also don't want lookups with both declarations visible to be ambiguous 8574 /// in some cases (this happens when using a modularized libstdc++). 8575 static bool isEquivalentCompatibleOverload(Sema &S, 8576 const OverloadCandidate &Best, 8577 const OverloadCandidate &Cand) { 8578 return Best.Function && Cand.Function && 8579 Best.Function->getDeclContext()->getRedeclContext()->Equals( 8580 Cand.Function->getDeclContext()->getRedeclContext()) && 8581 S.getOwningModule(Best.Function) != S.getOwningModule(Cand.Function) && 8582 !Best.Function->isExternallyVisible() && 8583 !Cand.Function->isExternallyVisible() && 8584 !S.IsOverload(Best.Function, Cand.Function, /*UsingDecl*/false); 8585 } 8586 8587 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8588 unsigned NumArgs); 8589 8590 /// \brief Computes the best viable function (C++ 13.3.3) 8591 /// within an overload candidate set. 8592 /// 8593 /// \param Loc The location of the function name (or operator symbol) for 8594 /// which overload resolution occurs. 8595 /// 8596 /// \param Best If overload resolution was successful or found a deleted 8597 /// function, \p Best points to the candidate function found. 8598 /// 8599 /// \returns The result of overload resolution. 8600 OverloadingResult 8601 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8602 iterator &Best, 8603 bool UserDefinedConversion) { 8604 // Find the best viable function. 8605 Best = end(); 8606 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8607 if (Cand->Viable) 8608 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8609 UserDefinedConversion)) 8610 Best = Cand; 8611 } 8612 8613 // If we didn't find any viable functions, abort. 8614 if (Best == end()) 8615 return OR_No_Viable_Function; 8616 8617 llvm::SmallVector<const OverloadCandidate *, 4> EquivalentCands; 8618 8619 // Make sure that this function is better than every other viable 8620 // function. If not, we have an ambiguity. 8621 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8622 if (Cand->Viable && 8623 Cand != Best && 8624 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8625 UserDefinedConversion)) { 8626 if (isEquivalentCompatibleOverload(S, *Best, *Cand)) { 8627 EquivalentCands.push_back(Cand); 8628 continue; 8629 } 8630 8631 Best = end(); 8632 return OR_Ambiguous; 8633 } 8634 } 8635 8636 // Best is the best viable function. 8637 if (Best->Function && 8638 (Best->Function->isDeleted() || 8639 S.isFunctionConsideredUnavailable(Best->Function))) 8640 return OR_Deleted; 8641 8642 if (!EquivalentCands.empty()) { 8643 S.Diag(Loc, diag::ext_ovl_equivalent_internal_linkage_functions_in_modules) 8644 << Best->Function; 8645 S.NoteOverloadCandidate(Best->Function); 8646 for (auto *Cand : EquivalentCands) 8647 S.NoteOverloadCandidate(Cand->Function); 8648 } 8649 8650 return OR_Success; 8651 } 8652 8653 namespace { 8654 8655 enum OverloadCandidateKind { 8656 oc_function, 8657 oc_method, 8658 oc_constructor, 8659 oc_function_template, 8660 oc_method_template, 8661 oc_constructor_template, 8662 oc_implicit_default_constructor, 8663 oc_implicit_copy_constructor, 8664 oc_implicit_move_constructor, 8665 oc_implicit_copy_assignment, 8666 oc_implicit_move_assignment, 8667 oc_implicit_inherited_constructor 8668 }; 8669 8670 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8671 FunctionDecl *Fn, 8672 std::string &Description) { 8673 bool isTemplate = false; 8674 8675 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8676 isTemplate = true; 8677 Description = S.getTemplateArgumentBindingsText( 8678 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8679 } 8680 8681 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8682 if (!Ctor->isImplicit()) 8683 return isTemplate ? oc_constructor_template : oc_constructor; 8684 8685 if (Ctor->getInheritedConstructor()) 8686 return oc_implicit_inherited_constructor; 8687 8688 if (Ctor->isDefaultConstructor()) 8689 return oc_implicit_default_constructor; 8690 8691 if (Ctor->isMoveConstructor()) 8692 return oc_implicit_move_constructor; 8693 8694 assert(Ctor->isCopyConstructor() && 8695 "unexpected sort of implicit constructor"); 8696 return oc_implicit_copy_constructor; 8697 } 8698 8699 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8700 // This actually gets spelled 'candidate function' for now, but 8701 // it doesn't hurt to split it out. 8702 if (!Meth->isImplicit()) 8703 return isTemplate ? oc_method_template : oc_method; 8704 8705 if (Meth->isMoveAssignmentOperator()) 8706 return oc_implicit_move_assignment; 8707 8708 if (Meth->isCopyAssignmentOperator()) 8709 return oc_implicit_copy_assignment; 8710 8711 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8712 return oc_method; 8713 } 8714 8715 return isTemplate ? oc_function_template : oc_function; 8716 } 8717 8718 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8719 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8720 if (!Ctor) return; 8721 8722 Ctor = Ctor->getInheritedConstructor(); 8723 if (!Ctor) return; 8724 8725 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8726 } 8727 8728 } // end anonymous namespace 8729 8730 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 8731 const FunctionDecl *FD) { 8732 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 8733 bool AlwaysTrue; 8734 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 8735 return false; 8736 if (!AlwaysTrue) 8737 return false; 8738 } 8739 return true; 8740 } 8741 8742 // Notes the location of an overload candidate. 8743 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType, 8744 bool TakingAddress) { 8745 std::string FnDesc; 8746 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8747 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8748 << (unsigned) K << FnDesc; 8749 if (TakingAddress && !isFunctionAlwaysEnabled(Context, Fn)) 8750 PD << ft_addr_enable_if; 8751 else 8752 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8753 Diag(Fn->getLocation(), PD); 8754 MaybeEmitInheritedConstructorNote(*this, Fn); 8755 } 8756 8757 // Notes the location of all overload candidates designated through 8758 // OverloadedExpr 8759 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 8760 bool TakingAddress) { 8761 assert(OverloadedExpr->getType() == Context.OverloadTy); 8762 8763 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8764 OverloadExpr *OvlExpr = Ovl.Expression; 8765 8766 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8767 IEnd = OvlExpr->decls_end(); 8768 I != IEnd; ++I) { 8769 if (FunctionTemplateDecl *FunTmpl = 8770 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8771 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType, 8772 TakingAddress); 8773 } else if (FunctionDecl *Fun 8774 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8775 NoteOverloadCandidate(Fun, DestType, TakingAddress); 8776 } 8777 } 8778 } 8779 8780 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8781 /// "lead" diagnostic; it will be given two arguments, the source and 8782 /// target types of the conversion. 8783 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8784 Sema &S, 8785 SourceLocation CaretLoc, 8786 const PartialDiagnostic &PDiag) const { 8787 S.Diag(CaretLoc, PDiag) 8788 << Ambiguous.getFromType() << Ambiguous.getToType(); 8789 // FIXME: The note limiting machinery is borrowed from 8790 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8791 // refactoring here. 8792 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8793 unsigned CandsShown = 0; 8794 AmbiguousConversionSequence::const_iterator I, E; 8795 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8796 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8797 break; 8798 ++CandsShown; 8799 S.NoteOverloadCandidate(*I); 8800 } 8801 if (I != E) 8802 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8803 } 8804 8805 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 8806 unsigned I) { 8807 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8808 assert(Conv.isBad()); 8809 assert(Cand->Function && "for now, candidate must be a function"); 8810 FunctionDecl *Fn = Cand->Function; 8811 8812 // There's a conversion slot for the object argument if this is a 8813 // non-constructor method. Note that 'I' corresponds the 8814 // conversion-slot index. 8815 bool isObjectArgument = false; 8816 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8817 if (I == 0) 8818 isObjectArgument = true; 8819 else 8820 I--; 8821 } 8822 8823 std::string FnDesc; 8824 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8825 8826 Expr *FromExpr = Conv.Bad.FromExpr; 8827 QualType FromTy = Conv.Bad.getFromType(); 8828 QualType ToTy = Conv.Bad.getToType(); 8829 8830 if (FromTy == S.Context.OverloadTy) { 8831 assert(FromExpr && "overload set argument came from implicit argument?"); 8832 Expr *E = FromExpr->IgnoreParens(); 8833 if (isa<UnaryOperator>(E)) 8834 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8835 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8836 8837 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8838 << (unsigned) FnKind << FnDesc 8839 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8840 << ToTy << Name << I+1; 8841 MaybeEmitInheritedConstructorNote(S, Fn); 8842 return; 8843 } 8844 8845 // Do some hand-waving analysis to see if the non-viability is due 8846 // to a qualifier mismatch. 8847 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8848 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8849 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8850 CToTy = RT->getPointeeType(); 8851 else { 8852 // TODO: detect and diagnose the full richness of const mismatches. 8853 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8854 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8855 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8856 } 8857 8858 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8859 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8860 Qualifiers FromQs = CFromTy.getQualifiers(); 8861 Qualifiers ToQs = CToTy.getQualifiers(); 8862 8863 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8864 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8865 << (unsigned) FnKind << FnDesc 8866 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8867 << FromTy 8868 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8869 << (unsigned) isObjectArgument << I+1; 8870 MaybeEmitInheritedConstructorNote(S, Fn); 8871 return; 8872 } 8873 8874 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8875 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8876 << (unsigned) FnKind << FnDesc 8877 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8878 << FromTy 8879 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8880 << (unsigned) isObjectArgument << I+1; 8881 MaybeEmitInheritedConstructorNote(S, Fn); 8882 return; 8883 } 8884 8885 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8886 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8887 << (unsigned) FnKind << FnDesc 8888 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8889 << FromTy 8890 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8891 << (unsigned) isObjectArgument << I+1; 8892 MaybeEmitInheritedConstructorNote(S, Fn); 8893 return; 8894 } 8895 8896 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8897 assert(CVR && "unexpected qualifiers mismatch"); 8898 8899 if (isObjectArgument) { 8900 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8901 << (unsigned) FnKind << FnDesc 8902 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8903 << FromTy << (CVR - 1); 8904 } else { 8905 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8906 << (unsigned) FnKind << FnDesc 8907 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8908 << FromTy << (CVR - 1) << I+1; 8909 } 8910 MaybeEmitInheritedConstructorNote(S, Fn); 8911 return; 8912 } 8913 8914 // Special diagnostic for failure to convert an initializer list, since 8915 // telling the user that it has type void is not useful. 8916 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8917 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8918 << (unsigned) FnKind << FnDesc 8919 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8920 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8921 MaybeEmitInheritedConstructorNote(S, Fn); 8922 return; 8923 } 8924 8925 // Diagnose references or pointers to incomplete types differently, 8926 // since it's far from impossible that the incompleteness triggered 8927 // the failure. 8928 QualType TempFromTy = FromTy.getNonReferenceType(); 8929 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8930 TempFromTy = PTy->getPointeeType(); 8931 if (TempFromTy->isIncompleteType()) { 8932 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8933 << (unsigned) FnKind << FnDesc 8934 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8935 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8936 MaybeEmitInheritedConstructorNote(S, Fn); 8937 return; 8938 } 8939 8940 // Diagnose base -> derived pointer conversions. 8941 unsigned BaseToDerivedConversion = 0; 8942 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8943 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8944 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8945 FromPtrTy->getPointeeType()) && 8946 !FromPtrTy->getPointeeType()->isIncompleteType() && 8947 !ToPtrTy->getPointeeType()->isIncompleteType() && 8948 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8949 FromPtrTy->getPointeeType())) 8950 BaseToDerivedConversion = 1; 8951 } 8952 } else if (const ObjCObjectPointerType *FromPtrTy 8953 = FromTy->getAs<ObjCObjectPointerType>()) { 8954 if (const ObjCObjectPointerType *ToPtrTy 8955 = ToTy->getAs<ObjCObjectPointerType>()) 8956 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8957 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8958 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8959 FromPtrTy->getPointeeType()) && 8960 FromIface->isSuperClassOf(ToIface)) 8961 BaseToDerivedConversion = 2; 8962 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8963 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8964 !FromTy->isIncompleteType() && 8965 !ToRefTy->getPointeeType()->isIncompleteType() && 8966 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8967 BaseToDerivedConversion = 3; 8968 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8969 ToTy.getNonReferenceType().getCanonicalType() == 8970 FromTy.getNonReferenceType().getCanonicalType()) { 8971 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8972 << (unsigned) FnKind << FnDesc 8973 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8974 << (unsigned) isObjectArgument << I + 1; 8975 MaybeEmitInheritedConstructorNote(S, Fn); 8976 return; 8977 } 8978 } 8979 8980 if (BaseToDerivedConversion) { 8981 S.Diag(Fn->getLocation(), 8982 diag::note_ovl_candidate_bad_base_to_derived_conv) 8983 << (unsigned) FnKind << FnDesc 8984 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8985 << (BaseToDerivedConversion - 1) 8986 << FromTy << ToTy << I+1; 8987 MaybeEmitInheritedConstructorNote(S, Fn); 8988 return; 8989 } 8990 8991 if (isa<ObjCObjectPointerType>(CFromTy) && 8992 isa<PointerType>(CToTy)) { 8993 Qualifiers FromQs = CFromTy.getQualifiers(); 8994 Qualifiers ToQs = CToTy.getQualifiers(); 8995 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8996 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8997 << (unsigned) FnKind << FnDesc 8998 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8999 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9000 MaybeEmitInheritedConstructorNote(S, Fn); 9001 return; 9002 } 9003 } 9004 9005 // Emit the generic diagnostic and, optionally, add the hints to it. 9006 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9007 FDiag << (unsigned) FnKind << FnDesc 9008 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9009 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9010 << (unsigned) (Cand->Fix.Kind); 9011 9012 // If we can fix the conversion, suggest the FixIts. 9013 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9014 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9015 FDiag << *HI; 9016 S.Diag(Fn->getLocation(), FDiag); 9017 9018 MaybeEmitInheritedConstructorNote(S, Fn); 9019 } 9020 9021 /// Additional arity mismatch diagnosis specific to a function overload 9022 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9023 /// over a candidate in any candidate set. 9024 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9025 unsigned NumArgs) { 9026 FunctionDecl *Fn = Cand->Function; 9027 unsigned MinParams = Fn->getMinRequiredArguments(); 9028 9029 // With invalid overloaded operators, it's possible that we think we 9030 // have an arity mismatch when in fact it looks like we have the 9031 // right number of arguments, because only overloaded operators have 9032 // the weird behavior of overloading member and non-member functions. 9033 // Just don't report anything. 9034 if (Fn->isInvalidDecl() && 9035 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9036 return true; 9037 9038 if (NumArgs < MinParams) { 9039 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9040 (Cand->FailureKind == ovl_fail_bad_deduction && 9041 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9042 } else { 9043 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9044 (Cand->FailureKind == ovl_fail_bad_deduction && 9045 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9046 } 9047 9048 return false; 9049 } 9050 9051 /// General arity mismatch diagnosis over a candidate in a candidate set. 9052 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 9053 assert(isa<FunctionDecl>(D) && 9054 "The templated declaration should at least be a function" 9055 " when diagnosing bad template argument deduction due to too many" 9056 " or too few arguments"); 9057 9058 FunctionDecl *Fn = cast<FunctionDecl>(D); 9059 9060 // TODO: treat calls to a missing default constructor as a special case 9061 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9062 unsigned MinParams = Fn->getMinRequiredArguments(); 9063 9064 // at least / at most / exactly 9065 unsigned mode, modeCount; 9066 if (NumFormalArgs < MinParams) { 9067 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9068 FnTy->isTemplateVariadic()) 9069 mode = 0; // "at least" 9070 else 9071 mode = 2; // "exactly" 9072 modeCount = MinParams; 9073 } else { 9074 if (MinParams != FnTy->getNumParams()) 9075 mode = 1; // "at most" 9076 else 9077 mode = 2; // "exactly" 9078 modeCount = FnTy->getNumParams(); 9079 } 9080 9081 std::string Description; 9082 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 9083 9084 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9085 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9086 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9087 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9088 else 9089 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9090 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9091 << mode << modeCount << NumFormalArgs; 9092 MaybeEmitInheritedConstructorNote(S, Fn); 9093 } 9094 9095 /// Arity mismatch diagnosis specific to a function overload candidate. 9096 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9097 unsigned NumFormalArgs) { 9098 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9099 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 9100 } 9101 9102 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9103 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 9104 return FD->getDescribedFunctionTemplate(); 9105 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 9106 return RD->getDescribedClassTemplate(); 9107 9108 llvm_unreachable("Unsupported: Getting the described template declaration" 9109 " for bad deduction diagnosis"); 9110 } 9111 9112 /// Diagnose a failed template-argument deduction. 9113 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 9114 DeductionFailureInfo &DeductionFailure, 9115 unsigned NumArgs) { 9116 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9117 NamedDecl *ParamD; 9118 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9119 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9120 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9121 switch (DeductionFailure.Result) { 9122 case Sema::TDK_Success: 9123 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9124 9125 case Sema::TDK_Incomplete: { 9126 assert(ParamD && "no parameter found for incomplete deduction result"); 9127 S.Diag(Templated->getLocation(), 9128 diag::note_ovl_candidate_incomplete_deduction) 9129 << ParamD->getDeclName(); 9130 MaybeEmitInheritedConstructorNote(S, Templated); 9131 return; 9132 } 9133 9134 case Sema::TDK_Underqualified: { 9135 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9136 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9137 9138 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9139 9140 // Param will have been canonicalized, but it should just be a 9141 // qualified version of ParamD, so move the qualifiers to that. 9142 QualifierCollector Qs; 9143 Qs.strip(Param); 9144 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9145 assert(S.Context.hasSameType(Param, NonCanonParam)); 9146 9147 // Arg has also been canonicalized, but there's nothing we can do 9148 // about that. It also doesn't matter as much, because it won't 9149 // have any template parameters in it (because deduction isn't 9150 // done on dependent types). 9151 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9152 9153 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9154 << ParamD->getDeclName() << Arg << NonCanonParam; 9155 MaybeEmitInheritedConstructorNote(S, Templated); 9156 return; 9157 } 9158 9159 case Sema::TDK_Inconsistent: { 9160 assert(ParamD && "no parameter found for inconsistent deduction result"); 9161 int which = 0; 9162 if (isa<TemplateTypeParmDecl>(ParamD)) 9163 which = 0; 9164 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9165 which = 1; 9166 else { 9167 which = 2; 9168 } 9169 9170 S.Diag(Templated->getLocation(), 9171 diag::note_ovl_candidate_inconsistent_deduction) 9172 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9173 << *DeductionFailure.getSecondArg(); 9174 MaybeEmitInheritedConstructorNote(S, Templated); 9175 return; 9176 } 9177 9178 case Sema::TDK_InvalidExplicitArguments: 9179 assert(ParamD && "no parameter found for invalid explicit arguments"); 9180 if (ParamD->getDeclName()) 9181 S.Diag(Templated->getLocation(), 9182 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9183 << ParamD->getDeclName(); 9184 else { 9185 int index = 0; 9186 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9187 index = TTP->getIndex(); 9188 else if (NonTypeTemplateParmDecl *NTTP 9189 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9190 index = NTTP->getIndex(); 9191 else 9192 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9193 S.Diag(Templated->getLocation(), 9194 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9195 << (index + 1); 9196 } 9197 MaybeEmitInheritedConstructorNote(S, Templated); 9198 return; 9199 9200 case Sema::TDK_TooManyArguments: 9201 case Sema::TDK_TooFewArguments: 9202 DiagnoseArityMismatch(S, Templated, NumArgs); 9203 return; 9204 9205 case Sema::TDK_InstantiationDepth: 9206 S.Diag(Templated->getLocation(), 9207 diag::note_ovl_candidate_instantiation_depth); 9208 MaybeEmitInheritedConstructorNote(S, Templated); 9209 return; 9210 9211 case Sema::TDK_SubstitutionFailure: { 9212 // Format the template argument list into the argument string. 9213 SmallString<128> TemplateArgString; 9214 if (TemplateArgumentList *Args = 9215 DeductionFailure.getTemplateArgumentList()) { 9216 TemplateArgString = " "; 9217 TemplateArgString += S.getTemplateArgumentBindingsText( 9218 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9219 } 9220 9221 // If this candidate was disabled by enable_if, say so. 9222 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9223 if (PDiag && PDiag->second.getDiagID() == 9224 diag::err_typename_nested_not_found_enable_if) { 9225 // FIXME: Use the source range of the condition, and the fully-qualified 9226 // name of the enable_if template. These are both present in PDiag. 9227 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9228 << "'enable_if'" << TemplateArgString; 9229 return; 9230 } 9231 9232 // Format the SFINAE diagnostic into the argument string. 9233 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9234 // formatted message in another diagnostic. 9235 SmallString<128> SFINAEArgString; 9236 SourceRange R; 9237 if (PDiag) { 9238 SFINAEArgString = ": "; 9239 R = SourceRange(PDiag->first, PDiag->first); 9240 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9241 } 9242 9243 S.Diag(Templated->getLocation(), 9244 diag::note_ovl_candidate_substitution_failure) 9245 << TemplateArgString << SFINAEArgString << R; 9246 MaybeEmitInheritedConstructorNote(S, Templated); 9247 return; 9248 } 9249 9250 case Sema::TDK_FailedOverloadResolution: { 9251 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9252 S.Diag(Templated->getLocation(), 9253 diag::note_ovl_candidate_failed_overload_resolution) 9254 << R.Expression->getName(); 9255 return; 9256 } 9257 9258 case Sema::TDK_NonDeducedMismatch: { 9259 // FIXME: Provide a source location to indicate what we couldn't match. 9260 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9261 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9262 if (FirstTA.getKind() == TemplateArgument::Template && 9263 SecondTA.getKind() == TemplateArgument::Template) { 9264 TemplateName FirstTN = FirstTA.getAsTemplate(); 9265 TemplateName SecondTN = SecondTA.getAsTemplate(); 9266 if (FirstTN.getKind() == TemplateName::Template && 9267 SecondTN.getKind() == TemplateName::Template) { 9268 if (FirstTN.getAsTemplateDecl()->getName() == 9269 SecondTN.getAsTemplateDecl()->getName()) { 9270 // FIXME: This fixes a bad diagnostic where both templates are named 9271 // the same. This particular case is a bit difficult since: 9272 // 1) It is passed as a string to the diagnostic printer. 9273 // 2) The diagnostic printer only attempts to find a better 9274 // name for types, not decls. 9275 // Ideally, this should folded into the diagnostic printer. 9276 S.Diag(Templated->getLocation(), 9277 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9278 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9279 return; 9280 } 9281 } 9282 } 9283 // FIXME: For generic lambda parameters, check if the function is a lambda 9284 // call operator, and if so, emit a prettier and more informative 9285 // diagnostic that mentions 'auto' and lambda in addition to 9286 // (or instead of?) the canonical template type parameters. 9287 S.Diag(Templated->getLocation(), 9288 diag::note_ovl_candidate_non_deduced_mismatch) 9289 << FirstTA << SecondTA; 9290 return; 9291 } 9292 // TODO: diagnose these individually, then kill off 9293 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9294 case Sema::TDK_MiscellaneousDeductionFailure: 9295 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9296 MaybeEmitInheritedConstructorNote(S, Templated); 9297 return; 9298 } 9299 } 9300 9301 /// Diagnose a failed template-argument deduction, for function calls. 9302 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9303 unsigned NumArgs) { 9304 unsigned TDK = Cand->DeductionFailure.Result; 9305 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9306 if (CheckArityMismatch(S, Cand, NumArgs)) 9307 return; 9308 } 9309 DiagnoseBadDeduction(S, Cand->Function, // pattern 9310 Cand->DeductionFailure, NumArgs); 9311 } 9312 9313 /// CUDA: diagnose an invalid call across targets. 9314 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9315 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9316 FunctionDecl *Callee = Cand->Function; 9317 9318 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9319 CalleeTarget = S.IdentifyCUDATarget(Callee); 9320 9321 std::string FnDesc; 9322 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9323 9324 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9325 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9326 9327 // This could be an implicit constructor for which we could not infer the 9328 // target due to a collsion. Diagnose that case. 9329 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9330 if (Meth != nullptr && Meth->isImplicit()) { 9331 CXXRecordDecl *ParentClass = Meth->getParent(); 9332 Sema::CXXSpecialMember CSM; 9333 9334 switch (FnKind) { 9335 default: 9336 return; 9337 case oc_implicit_default_constructor: 9338 CSM = Sema::CXXDefaultConstructor; 9339 break; 9340 case oc_implicit_copy_constructor: 9341 CSM = Sema::CXXCopyConstructor; 9342 break; 9343 case oc_implicit_move_constructor: 9344 CSM = Sema::CXXMoveConstructor; 9345 break; 9346 case oc_implicit_copy_assignment: 9347 CSM = Sema::CXXCopyAssignment; 9348 break; 9349 case oc_implicit_move_assignment: 9350 CSM = Sema::CXXMoveAssignment; 9351 break; 9352 }; 9353 9354 bool ConstRHS = false; 9355 if (Meth->getNumParams()) { 9356 if (const ReferenceType *RT = 9357 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9358 ConstRHS = RT->getPointeeType().isConstQualified(); 9359 } 9360 } 9361 9362 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9363 /* ConstRHS */ ConstRHS, 9364 /* Diagnose */ true); 9365 } 9366 } 9367 9368 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9369 FunctionDecl *Callee = Cand->Function; 9370 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9371 9372 S.Diag(Callee->getLocation(), 9373 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9374 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9375 } 9376 9377 /// Generates a 'note' diagnostic for an overload candidate. We've 9378 /// already generated a primary error at the call site. 9379 /// 9380 /// It really does need to be a single diagnostic with its caret 9381 /// pointed at the candidate declaration. Yes, this creates some 9382 /// major challenges of technical writing. Yes, this makes pointing 9383 /// out problems with specific arguments quite awkward. It's still 9384 /// better than generating twenty screens of text for every failed 9385 /// overload. 9386 /// 9387 /// It would be great to be able to express per-candidate problems 9388 /// more richly for those diagnostic clients that cared, but we'd 9389 /// still have to be just as careful with the default diagnostics. 9390 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9391 unsigned NumArgs) { 9392 FunctionDecl *Fn = Cand->Function; 9393 9394 // Note deleted candidates, but only if they're viable. 9395 if (Cand->Viable && (Fn->isDeleted() || 9396 S.isFunctionConsideredUnavailable(Fn))) { 9397 std::string FnDesc; 9398 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9399 9400 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9401 << FnKind << FnDesc 9402 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9403 MaybeEmitInheritedConstructorNote(S, Fn); 9404 return; 9405 } 9406 9407 // We don't really have anything else to say about viable candidates. 9408 if (Cand->Viable) { 9409 S.NoteOverloadCandidate(Fn); 9410 return; 9411 } 9412 9413 switch (Cand->FailureKind) { 9414 case ovl_fail_too_many_arguments: 9415 case ovl_fail_too_few_arguments: 9416 return DiagnoseArityMismatch(S, Cand, NumArgs); 9417 9418 case ovl_fail_bad_deduction: 9419 return DiagnoseBadDeduction(S, Cand, NumArgs); 9420 9421 case ovl_fail_illegal_constructor: { 9422 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9423 << (Fn->getPrimaryTemplate() ? 1 : 0); 9424 MaybeEmitInheritedConstructorNote(S, Fn); 9425 return; 9426 } 9427 9428 case ovl_fail_trivial_conversion: 9429 case ovl_fail_bad_final_conversion: 9430 case ovl_fail_final_conversion_not_exact: 9431 return S.NoteOverloadCandidate(Fn); 9432 9433 case ovl_fail_bad_conversion: { 9434 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9435 for (unsigned N = Cand->NumConversions; I != N; ++I) 9436 if (Cand->Conversions[I].isBad()) 9437 return DiagnoseBadConversion(S, Cand, I); 9438 9439 // FIXME: this currently happens when we're called from SemaInit 9440 // when user-conversion overload fails. Figure out how to handle 9441 // those conditions and diagnose them well. 9442 return S.NoteOverloadCandidate(Fn); 9443 } 9444 9445 case ovl_fail_bad_target: 9446 return DiagnoseBadTarget(S, Cand); 9447 9448 case ovl_fail_enable_if: 9449 return DiagnoseFailedEnableIfAttr(S, Cand); 9450 } 9451 } 9452 9453 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9454 // Desugar the type of the surrogate down to a function type, 9455 // retaining as many typedefs as possible while still showing 9456 // the function type (and, therefore, its parameter types). 9457 QualType FnType = Cand->Surrogate->getConversionType(); 9458 bool isLValueReference = false; 9459 bool isRValueReference = false; 9460 bool isPointer = false; 9461 if (const LValueReferenceType *FnTypeRef = 9462 FnType->getAs<LValueReferenceType>()) { 9463 FnType = FnTypeRef->getPointeeType(); 9464 isLValueReference = true; 9465 } else if (const RValueReferenceType *FnTypeRef = 9466 FnType->getAs<RValueReferenceType>()) { 9467 FnType = FnTypeRef->getPointeeType(); 9468 isRValueReference = true; 9469 } 9470 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9471 FnType = FnTypePtr->getPointeeType(); 9472 isPointer = true; 9473 } 9474 // Desugar down to a function type. 9475 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9476 // Reconstruct the pointer/reference as appropriate. 9477 if (isPointer) FnType = S.Context.getPointerType(FnType); 9478 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9479 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9480 9481 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9482 << FnType; 9483 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9484 } 9485 9486 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9487 SourceLocation OpLoc, 9488 OverloadCandidate *Cand) { 9489 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9490 std::string TypeStr("operator"); 9491 TypeStr += Opc; 9492 TypeStr += "("; 9493 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9494 if (Cand->NumConversions == 1) { 9495 TypeStr += ")"; 9496 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9497 } else { 9498 TypeStr += ", "; 9499 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9500 TypeStr += ")"; 9501 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9502 } 9503 } 9504 9505 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9506 OverloadCandidate *Cand) { 9507 unsigned NoOperands = Cand->NumConversions; 9508 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9509 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9510 if (ICS.isBad()) break; // all meaningless after first invalid 9511 if (!ICS.isAmbiguous()) continue; 9512 9513 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9514 S.PDiag(diag::note_ambiguous_type_conversion)); 9515 } 9516 } 9517 9518 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9519 if (Cand->Function) 9520 return Cand->Function->getLocation(); 9521 if (Cand->IsSurrogate) 9522 return Cand->Surrogate->getLocation(); 9523 return SourceLocation(); 9524 } 9525 9526 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9527 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9528 case Sema::TDK_Success: 9529 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9530 9531 case Sema::TDK_Invalid: 9532 case Sema::TDK_Incomplete: 9533 return 1; 9534 9535 case Sema::TDK_Underqualified: 9536 case Sema::TDK_Inconsistent: 9537 return 2; 9538 9539 case Sema::TDK_SubstitutionFailure: 9540 case Sema::TDK_NonDeducedMismatch: 9541 case Sema::TDK_MiscellaneousDeductionFailure: 9542 return 3; 9543 9544 case Sema::TDK_InstantiationDepth: 9545 case Sema::TDK_FailedOverloadResolution: 9546 return 4; 9547 9548 case Sema::TDK_InvalidExplicitArguments: 9549 return 5; 9550 9551 case Sema::TDK_TooManyArguments: 9552 case Sema::TDK_TooFewArguments: 9553 return 6; 9554 } 9555 llvm_unreachable("Unhandled deduction result"); 9556 } 9557 9558 namespace { 9559 struct CompareOverloadCandidatesForDisplay { 9560 Sema &S; 9561 size_t NumArgs; 9562 9563 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs) 9564 : S(S), NumArgs(nArgs) {} 9565 9566 bool operator()(const OverloadCandidate *L, 9567 const OverloadCandidate *R) { 9568 // Fast-path this check. 9569 if (L == R) return false; 9570 9571 // Order first by viability. 9572 if (L->Viable) { 9573 if (!R->Viable) return true; 9574 9575 // TODO: introduce a tri-valued comparison for overload 9576 // candidates. Would be more worthwhile if we had a sort 9577 // that could exploit it. 9578 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9579 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9580 } else if (R->Viable) 9581 return false; 9582 9583 assert(L->Viable == R->Viable); 9584 9585 // Criteria by which we can sort non-viable candidates: 9586 if (!L->Viable) { 9587 // 1. Arity mismatches come after other candidates. 9588 if (L->FailureKind == ovl_fail_too_many_arguments || 9589 L->FailureKind == ovl_fail_too_few_arguments) { 9590 if (R->FailureKind == ovl_fail_too_many_arguments || 9591 R->FailureKind == ovl_fail_too_few_arguments) { 9592 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9593 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9594 if (LDist == RDist) { 9595 if (L->FailureKind == R->FailureKind) 9596 // Sort non-surrogates before surrogates. 9597 return !L->IsSurrogate && R->IsSurrogate; 9598 // Sort candidates requiring fewer parameters than there were 9599 // arguments given after candidates requiring more parameters 9600 // than there were arguments given. 9601 return L->FailureKind == ovl_fail_too_many_arguments; 9602 } 9603 return LDist < RDist; 9604 } 9605 return false; 9606 } 9607 if (R->FailureKind == ovl_fail_too_many_arguments || 9608 R->FailureKind == ovl_fail_too_few_arguments) 9609 return true; 9610 9611 // 2. Bad conversions come first and are ordered by the number 9612 // of bad conversions and quality of good conversions. 9613 if (L->FailureKind == ovl_fail_bad_conversion) { 9614 if (R->FailureKind != ovl_fail_bad_conversion) 9615 return true; 9616 9617 // The conversion that can be fixed with a smaller number of changes, 9618 // comes first. 9619 unsigned numLFixes = L->Fix.NumConversionsFixed; 9620 unsigned numRFixes = R->Fix.NumConversionsFixed; 9621 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9622 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9623 if (numLFixes != numRFixes) { 9624 return numLFixes < numRFixes; 9625 } 9626 9627 // If there's any ordering between the defined conversions... 9628 // FIXME: this might not be transitive. 9629 assert(L->NumConversions == R->NumConversions); 9630 9631 int leftBetter = 0; 9632 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9633 for (unsigned E = L->NumConversions; I != E; ++I) { 9634 switch (CompareImplicitConversionSequences(S, 9635 L->Conversions[I], 9636 R->Conversions[I])) { 9637 case ImplicitConversionSequence::Better: 9638 leftBetter++; 9639 break; 9640 9641 case ImplicitConversionSequence::Worse: 9642 leftBetter--; 9643 break; 9644 9645 case ImplicitConversionSequence::Indistinguishable: 9646 break; 9647 } 9648 } 9649 if (leftBetter > 0) return true; 9650 if (leftBetter < 0) return false; 9651 9652 } else if (R->FailureKind == ovl_fail_bad_conversion) 9653 return false; 9654 9655 if (L->FailureKind == ovl_fail_bad_deduction) { 9656 if (R->FailureKind != ovl_fail_bad_deduction) 9657 return true; 9658 9659 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9660 return RankDeductionFailure(L->DeductionFailure) 9661 < RankDeductionFailure(R->DeductionFailure); 9662 } else if (R->FailureKind == ovl_fail_bad_deduction) 9663 return false; 9664 9665 // TODO: others? 9666 } 9667 9668 // Sort everything else by location. 9669 SourceLocation LLoc = GetLocationForCandidate(L); 9670 SourceLocation RLoc = GetLocationForCandidate(R); 9671 9672 // Put candidates without locations (e.g. builtins) at the end. 9673 if (LLoc.isInvalid()) return false; 9674 if (RLoc.isInvalid()) return true; 9675 9676 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9677 } 9678 }; 9679 } 9680 9681 /// CompleteNonViableCandidate - Normally, overload resolution only 9682 /// computes up to the first. Produces the FixIt set if possible. 9683 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9684 ArrayRef<Expr *> Args) { 9685 assert(!Cand->Viable); 9686 9687 // Don't do anything on failures other than bad conversion. 9688 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9689 9690 // We only want the FixIts if all the arguments can be corrected. 9691 bool Unfixable = false; 9692 // Use a implicit copy initialization to check conversion fixes. 9693 Cand->Fix.setConversionChecker(TryCopyInitialization); 9694 9695 // Skip forward to the first bad conversion. 9696 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9697 unsigned ConvCount = Cand->NumConversions; 9698 while (true) { 9699 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9700 ConvIdx++; 9701 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9702 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9703 break; 9704 } 9705 } 9706 9707 if (ConvIdx == ConvCount) 9708 return; 9709 9710 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9711 "remaining conversion is initialized?"); 9712 9713 // FIXME: this should probably be preserved from the overload 9714 // operation somehow. 9715 bool SuppressUserConversions = false; 9716 9717 const FunctionProtoType* Proto; 9718 unsigned ArgIdx = ConvIdx; 9719 9720 if (Cand->IsSurrogate) { 9721 QualType ConvType 9722 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9723 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9724 ConvType = ConvPtrType->getPointeeType(); 9725 Proto = ConvType->getAs<FunctionProtoType>(); 9726 ArgIdx--; 9727 } else if (Cand->Function) { 9728 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9729 if (isa<CXXMethodDecl>(Cand->Function) && 9730 !isa<CXXConstructorDecl>(Cand->Function)) 9731 ArgIdx--; 9732 } else { 9733 // Builtin binary operator with a bad first conversion. 9734 assert(ConvCount <= 3); 9735 for (; ConvIdx != ConvCount; ++ConvIdx) 9736 Cand->Conversions[ConvIdx] 9737 = TryCopyInitialization(S, Args[ConvIdx], 9738 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9739 SuppressUserConversions, 9740 /*InOverloadResolution*/ true, 9741 /*AllowObjCWritebackConversion=*/ 9742 S.getLangOpts().ObjCAutoRefCount); 9743 return; 9744 } 9745 9746 // Fill in the rest of the conversions. 9747 unsigned NumParams = Proto->getNumParams(); 9748 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9749 if (ArgIdx < NumParams) { 9750 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9751 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9752 /*InOverloadResolution=*/true, 9753 /*AllowObjCWritebackConversion=*/ 9754 S.getLangOpts().ObjCAutoRefCount); 9755 // Store the FixIt in the candidate if it exists. 9756 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9757 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9758 } 9759 else 9760 Cand->Conversions[ConvIdx].setEllipsis(); 9761 } 9762 } 9763 9764 /// PrintOverloadCandidates - When overload resolution fails, prints 9765 /// diagnostic messages containing the candidates in the candidate 9766 /// set. 9767 void OverloadCandidateSet::NoteCandidates(Sema &S, 9768 OverloadCandidateDisplayKind OCD, 9769 ArrayRef<Expr *> Args, 9770 StringRef Opc, 9771 SourceLocation OpLoc) { 9772 // Sort the candidates by viability and position. Sorting directly would 9773 // be prohibitive, so we make a set of pointers and sort those. 9774 SmallVector<OverloadCandidate*, 32> Cands; 9775 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9776 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9777 if (Cand->Viable) 9778 Cands.push_back(Cand); 9779 else if (OCD == OCD_AllCandidates) { 9780 CompleteNonViableCandidate(S, Cand, Args); 9781 if (Cand->Function || Cand->IsSurrogate) 9782 Cands.push_back(Cand); 9783 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9784 // want to list every possible builtin candidate. 9785 } 9786 } 9787 9788 std::sort(Cands.begin(), Cands.end(), 9789 CompareOverloadCandidatesForDisplay(S, Args.size())); 9790 9791 bool ReportedAmbiguousConversions = false; 9792 9793 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9794 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9795 unsigned CandsShown = 0; 9796 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9797 OverloadCandidate *Cand = *I; 9798 9799 // Set an arbitrary limit on the number of candidate functions we'll spam 9800 // the user with. FIXME: This limit should depend on details of the 9801 // candidate list. 9802 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9803 break; 9804 } 9805 ++CandsShown; 9806 9807 if (Cand->Function) 9808 NoteFunctionCandidate(S, Cand, Args.size()); 9809 else if (Cand->IsSurrogate) 9810 NoteSurrogateCandidate(S, Cand); 9811 else { 9812 assert(Cand->Viable && 9813 "Non-viable built-in candidates are not added to Cands."); 9814 // Generally we only see ambiguities including viable builtin 9815 // operators if overload resolution got screwed up by an 9816 // ambiguous user-defined conversion. 9817 // 9818 // FIXME: It's quite possible for different conversions to see 9819 // different ambiguities, though. 9820 if (!ReportedAmbiguousConversions) { 9821 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9822 ReportedAmbiguousConversions = true; 9823 } 9824 9825 // If this is a viable builtin, print it. 9826 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9827 } 9828 } 9829 9830 if (I != E) 9831 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9832 } 9833 9834 static SourceLocation 9835 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9836 return Cand->Specialization ? Cand->Specialization->getLocation() 9837 : SourceLocation(); 9838 } 9839 9840 namespace { 9841 struct CompareTemplateSpecCandidatesForDisplay { 9842 Sema &S; 9843 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9844 9845 bool operator()(const TemplateSpecCandidate *L, 9846 const TemplateSpecCandidate *R) { 9847 // Fast-path this check. 9848 if (L == R) 9849 return false; 9850 9851 // Assuming that both candidates are not matches... 9852 9853 // Sort by the ranking of deduction failures. 9854 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9855 return RankDeductionFailure(L->DeductionFailure) < 9856 RankDeductionFailure(R->DeductionFailure); 9857 9858 // Sort everything else by location. 9859 SourceLocation LLoc = GetLocationForCandidate(L); 9860 SourceLocation RLoc = GetLocationForCandidate(R); 9861 9862 // Put candidates without locations (e.g. builtins) at the end. 9863 if (LLoc.isInvalid()) 9864 return false; 9865 if (RLoc.isInvalid()) 9866 return true; 9867 9868 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9869 } 9870 }; 9871 } 9872 9873 /// Diagnose a template argument deduction failure. 9874 /// We are treating these failures as overload failures due to bad 9875 /// deductions. 9876 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9877 DiagnoseBadDeduction(S, Specialization, // pattern 9878 DeductionFailure, /*NumArgs=*/0); 9879 } 9880 9881 void TemplateSpecCandidateSet::destroyCandidates() { 9882 for (iterator i = begin(), e = end(); i != e; ++i) { 9883 i->DeductionFailure.Destroy(); 9884 } 9885 } 9886 9887 void TemplateSpecCandidateSet::clear() { 9888 destroyCandidates(); 9889 Candidates.clear(); 9890 } 9891 9892 /// NoteCandidates - When no template specialization match is found, prints 9893 /// diagnostic messages containing the non-matching specializations that form 9894 /// the candidate set. 9895 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9896 /// OCD == OCD_AllCandidates and Cand->Viable == false. 9897 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9898 // Sort the candidates by position (assuming no candidate is a match). 9899 // Sorting directly would be prohibitive, so we make a set of pointers 9900 // and sort those. 9901 SmallVector<TemplateSpecCandidate *, 32> Cands; 9902 Cands.reserve(size()); 9903 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9904 if (Cand->Specialization) 9905 Cands.push_back(Cand); 9906 // Otherwise, this is a non-matching builtin candidate. We do not, 9907 // in general, want to list every possible builtin candidate. 9908 } 9909 9910 std::sort(Cands.begin(), Cands.end(), 9911 CompareTemplateSpecCandidatesForDisplay(S)); 9912 9913 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9914 // for generalization purposes (?). 9915 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9916 9917 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9918 unsigned CandsShown = 0; 9919 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9920 TemplateSpecCandidate *Cand = *I; 9921 9922 // Set an arbitrary limit on the number of candidates we'll spam 9923 // the user with. FIXME: This limit should depend on details of the 9924 // candidate list. 9925 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9926 break; 9927 ++CandsShown; 9928 9929 assert(Cand->Specialization && 9930 "Non-matching built-in candidates are not added to Cands."); 9931 Cand->NoteDeductionFailure(S); 9932 } 9933 9934 if (I != E) 9935 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9936 } 9937 9938 // [PossiblyAFunctionType] --> [Return] 9939 // NonFunctionType --> NonFunctionType 9940 // R (A) --> R(A) 9941 // R (*)(A) --> R (A) 9942 // R (&)(A) --> R (A) 9943 // R (S::*)(A) --> R (A) 9944 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9945 QualType Ret = PossiblyAFunctionType; 9946 if (const PointerType *ToTypePtr = 9947 PossiblyAFunctionType->getAs<PointerType>()) 9948 Ret = ToTypePtr->getPointeeType(); 9949 else if (const ReferenceType *ToTypeRef = 9950 PossiblyAFunctionType->getAs<ReferenceType>()) 9951 Ret = ToTypeRef->getPointeeType(); 9952 else if (const MemberPointerType *MemTypePtr = 9953 PossiblyAFunctionType->getAs<MemberPointerType>()) 9954 Ret = MemTypePtr->getPointeeType(); 9955 Ret = 9956 Context.getCanonicalType(Ret).getUnqualifiedType(); 9957 return Ret; 9958 } 9959 9960 namespace { 9961 // A helper class to help with address of function resolution 9962 // - allows us to avoid passing around all those ugly parameters 9963 class AddressOfFunctionResolver { 9964 Sema& S; 9965 Expr* SourceExpr; 9966 const QualType& TargetType; 9967 QualType TargetFunctionType; // Extracted function type from target type 9968 9969 bool Complain; 9970 //DeclAccessPair& ResultFunctionAccessPair; 9971 ASTContext& Context; 9972 9973 bool TargetTypeIsNonStaticMemberFunction; 9974 bool FoundNonTemplateFunction; 9975 bool StaticMemberFunctionFromBoundPointer; 9976 bool HasComplained; 9977 9978 OverloadExpr::FindResult OvlExprInfo; 9979 OverloadExpr *OvlExpr; 9980 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9981 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9982 TemplateSpecCandidateSet FailedCandidates; 9983 9984 public: 9985 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9986 const QualType &TargetType, bool Complain) 9987 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9988 Complain(Complain), Context(S.getASTContext()), 9989 TargetTypeIsNonStaticMemberFunction( 9990 !!TargetType->getAs<MemberPointerType>()), 9991 FoundNonTemplateFunction(false), 9992 StaticMemberFunctionFromBoundPointer(false), 9993 HasComplained(false), 9994 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9995 OvlExpr(OvlExprInfo.Expression), 9996 FailedCandidates(OvlExpr->getNameLoc()) { 9997 ExtractUnqualifiedFunctionTypeFromTargetType(); 9998 9999 if (TargetFunctionType->isFunctionType()) { 10000 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10001 if (!UME->isImplicitAccess() && 10002 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10003 StaticMemberFunctionFromBoundPointer = true; 10004 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10005 DeclAccessPair dap; 10006 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10007 OvlExpr, false, &dap)) { 10008 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10009 if (!Method->isStatic()) { 10010 // If the target type is a non-function type and the function found 10011 // is a non-static member function, pretend as if that was the 10012 // target, it's the only possible type to end up with. 10013 TargetTypeIsNonStaticMemberFunction = true; 10014 10015 // And skip adding the function if its not in the proper form. 10016 // We'll diagnose this due to an empty set of functions. 10017 if (!OvlExprInfo.HasFormOfMemberPointer) 10018 return; 10019 } 10020 10021 Matches.push_back(std::make_pair(dap, Fn)); 10022 } 10023 return; 10024 } 10025 10026 if (OvlExpr->hasExplicitTemplateArgs()) 10027 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 10028 10029 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10030 // C++ [over.over]p4: 10031 // If more than one function is selected, [...] 10032 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10033 if (FoundNonTemplateFunction) 10034 EliminateAllTemplateMatches(); 10035 else 10036 EliminateAllExceptMostSpecializedTemplate(); 10037 } 10038 } 10039 10040 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 10041 Matches.size() > 1) 10042 EliminateSuboptimalCudaMatches(); 10043 } 10044 10045 bool hasComplained() const { return HasComplained; } 10046 10047 private: 10048 // Is A considered a better overload candidate for the desired type than B? 10049 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10050 return hasBetterEnableIfAttrs(S, A, B); 10051 } 10052 10053 // Returns true if we've eliminated any (read: all but one) candidates, false 10054 // otherwise. 10055 bool eliminiateSuboptimalOverloadCandidates() { 10056 // Same algorithm as overload resolution -- one pass to pick the "best", 10057 // another pass to be sure that nothing is better than the best. 10058 auto Best = Matches.begin(); 10059 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10060 if (isBetterCandidate(I->second, Best->second)) 10061 Best = I; 10062 10063 const FunctionDecl *BestFn = Best->second; 10064 auto IsBestOrInferiorToBest = [this, BestFn]( 10065 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10066 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10067 }; 10068 10069 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10070 // option, so we can potentially give the user a better error 10071 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10072 return false; 10073 Matches[0] = *Best; 10074 Matches.resize(1); 10075 return true; 10076 } 10077 10078 bool isTargetTypeAFunction() const { 10079 return TargetFunctionType->isFunctionType(); 10080 } 10081 10082 // [ToType] [Return] 10083 10084 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10085 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10086 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10087 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10088 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10089 } 10090 10091 // return true if any matching specializations were found 10092 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10093 const DeclAccessPair& CurAccessFunPair) { 10094 if (CXXMethodDecl *Method 10095 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10096 // Skip non-static function templates when converting to pointer, and 10097 // static when converting to member pointer. 10098 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10099 return false; 10100 } 10101 else if (TargetTypeIsNonStaticMemberFunction) 10102 return false; 10103 10104 // C++ [over.over]p2: 10105 // If the name is a function template, template argument deduction is 10106 // done (14.8.2.2), and if the argument deduction succeeds, the 10107 // resulting template argument list is used to generate a single 10108 // function template specialization, which is added to the set of 10109 // overloaded functions considered. 10110 FunctionDecl *Specialization = nullptr; 10111 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10112 if (Sema::TemplateDeductionResult Result 10113 = S.DeduceTemplateArguments(FunctionTemplate, 10114 &OvlExplicitTemplateArgs, 10115 TargetFunctionType, Specialization, 10116 Info, /*InOverloadResolution=*/true)) { 10117 // Make a note of the failed deduction for diagnostics. 10118 FailedCandidates.addCandidate() 10119 .set(FunctionTemplate->getTemplatedDecl(), 10120 MakeDeductionFailureInfo(Context, Result, Info)); 10121 return false; 10122 } 10123 10124 // Template argument deduction ensures that we have an exact match or 10125 // compatible pointer-to-function arguments that would be adjusted by ICS. 10126 // This function template specicalization works. 10127 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 10128 assert(S.isSameOrCompatibleFunctionType( 10129 Context.getCanonicalType(Specialization->getType()), 10130 Context.getCanonicalType(TargetFunctionType)) || 10131 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())); 10132 10133 if (!isFunctionAlwaysEnabled(S.Context, Specialization)) 10134 return false; 10135 10136 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10137 return true; 10138 } 10139 10140 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10141 const DeclAccessPair& CurAccessFunPair) { 10142 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10143 // Skip non-static functions when converting to pointer, and static 10144 // when converting to member pointer. 10145 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10146 return false; 10147 } 10148 else if (TargetTypeIsNonStaticMemberFunction) 10149 return false; 10150 10151 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10152 if (S.getLangOpts().CUDA) 10153 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10154 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 10155 return false; 10156 10157 // If any candidate has a placeholder return type, trigger its deduction 10158 // now. 10159 if (S.getLangOpts().CPlusPlus14 && 10160 FunDecl->getReturnType()->isUndeducedType() && 10161 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10162 HasComplained |= Complain; 10163 return false; 10164 } 10165 10166 if (!isFunctionAlwaysEnabled(S.Context, FunDecl)) 10167 return false; 10168 10169 QualType ResultTy; 10170 if (Context.hasSameUnqualifiedType(TargetFunctionType, 10171 FunDecl->getType()) || 10172 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 10173 ResultTy) || 10174 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) { 10175 Matches.push_back(std::make_pair( 10176 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10177 FoundNonTemplateFunction = true; 10178 return true; 10179 } 10180 } 10181 10182 return false; 10183 } 10184 10185 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10186 bool Ret = false; 10187 10188 // If the overload expression doesn't have the form of a pointer to 10189 // member, don't try to convert it to a pointer-to-member type. 10190 if (IsInvalidFormOfPointerToMemberFunction()) 10191 return false; 10192 10193 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10194 E = OvlExpr->decls_end(); 10195 I != E; ++I) { 10196 // Look through any using declarations to find the underlying function. 10197 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10198 10199 // C++ [over.over]p3: 10200 // Non-member functions and static member functions match 10201 // targets of type "pointer-to-function" or "reference-to-function." 10202 // Nonstatic member functions match targets of 10203 // type "pointer-to-member-function." 10204 // Note that according to DR 247, the containing class does not matter. 10205 if (FunctionTemplateDecl *FunctionTemplate 10206 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10207 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10208 Ret = true; 10209 } 10210 // If we have explicit template arguments supplied, skip non-templates. 10211 else if (!OvlExpr->hasExplicitTemplateArgs() && 10212 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10213 Ret = true; 10214 } 10215 assert(Ret || Matches.empty()); 10216 return Ret; 10217 } 10218 10219 void EliminateAllExceptMostSpecializedTemplate() { 10220 // [...] and any given function template specialization F1 is 10221 // eliminated if the set contains a second function template 10222 // specialization whose function template is more specialized 10223 // than the function template of F1 according to the partial 10224 // ordering rules of 14.5.5.2. 10225 10226 // The algorithm specified above is quadratic. We instead use a 10227 // two-pass algorithm (similar to the one used to identify the 10228 // best viable function in an overload set) that identifies the 10229 // best function template (if it exists). 10230 10231 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10232 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10233 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10234 10235 // TODO: It looks like FailedCandidates does not serve much purpose 10236 // here, since the no_viable diagnostic has index 0. 10237 UnresolvedSetIterator Result = S.getMostSpecialized( 10238 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10239 SourceExpr->getLocStart(), S.PDiag(), 10240 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10241 .second->getDeclName(), 10242 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10243 Complain, TargetFunctionType); 10244 10245 if (Result != MatchesCopy.end()) { 10246 // Make it the first and only element 10247 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10248 Matches[0].second = cast<FunctionDecl>(*Result); 10249 Matches.resize(1); 10250 } else 10251 HasComplained |= Complain; 10252 } 10253 10254 void EliminateAllTemplateMatches() { 10255 // [...] any function template specializations in the set are 10256 // eliminated if the set also contains a non-template function, [...] 10257 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10258 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10259 ++I; 10260 else { 10261 Matches[I] = Matches[--N]; 10262 Matches.resize(N); 10263 } 10264 } 10265 } 10266 10267 void EliminateSuboptimalCudaMatches() { 10268 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10269 } 10270 10271 public: 10272 void ComplainNoMatchesFound() const { 10273 assert(Matches.empty()); 10274 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10275 << OvlExpr->getName() << TargetFunctionType 10276 << OvlExpr->getSourceRange(); 10277 if (FailedCandidates.empty()) 10278 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10279 /*TakingAddress=*/true); 10280 else { 10281 // We have some deduction failure messages. Use them to diagnose 10282 // the function templates, and diagnose the non-template candidates 10283 // normally. 10284 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10285 IEnd = OvlExpr->decls_end(); 10286 I != IEnd; ++I) 10287 if (FunctionDecl *Fun = 10288 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10289 S.NoteOverloadCandidate(Fun, TargetFunctionType, 10290 /*TakingAddress=*/true); 10291 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10292 } 10293 } 10294 10295 bool IsInvalidFormOfPointerToMemberFunction() const { 10296 return TargetTypeIsNonStaticMemberFunction && 10297 !OvlExprInfo.HasFormOfMemberPointer; 10298 } 10299 10300 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10301 // TODO: Should we condition this on whether any functions might 10302 // have matched, or is it more appropriate to do that in callers? 10303 // TODO: a fixit wouldn't hurt. 10304 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10305 << TargetType << OvlExpr->getSourceRange(); 10306 } 10307 10308 bool IsStaticMemberFunctionFromBoundPointer() const { 10309 return StaticMemberFunctionFromBoundPointer; 10310 } 10311 10312 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10313 S.Diag(OvlExpr->getLocStart(), 10314 diag::err_invalid_form_pointer_member_function) 10315 << OvlExpr->getSourceRange(); 10316 } 10317 10318 void ComplainOfInvalidConversion() const { 10319 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10320 << OvlExpr->getName() << TargetType; 10321 } 10322 10323 void ComplainMultipleMatchesFound() const { 10324 assert(Matches.size() > 1); 10325 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10326 << OvlExpr->getName() 10327 << OvlExpr->getSourceRange(); 10328 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10329 /*TakingAddress=*/true); 10330 } 10331 10332 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10333 10334 int getNumMatches() const { return Matches.size(); } 10335 10336 FunctionDecl* getMatchingFunctionDecl() const { 10337 if (Matches.size() != 1) return nullptr; 10338 return Matches[0].second; 10339 } 10340 10341 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10342 if (Matches.size() != 1) return nullptr; 10343 return &Matches[0].first; 10344 } 10345 }; 10346 } 10347 10348 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10349 /// an overloaded function (C++ [over.over]), where @p From is an 10350 /// expression with overloaded function type and @p ToType is the type 10351 /// we're trying to resolve to. For example: 10352 /// 10353 /// @code 10354 /// int f(double); 10355 /// int f(int); 10356 /// 10357 /// int (*pfd)(double) = f; // selects f(double) 10358 /// @endcode 10359 /// 10360 /// This routine returns the resulting FunctionDecl if it could be 10361 /// resolved, and NULL otherwise. When @p Complain is true, this 10362 /// routine will emit diagnostics if there is an error. 10363 FunctionDecl * 10364 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10365 QualType TargetType, 10366 bool Complain, 10367 DeclAccessPair &FoundResult, 10368 bool *pHadMultipleCandidates) { 10369 assert(AddressOfExpr->getType() == Context.OverloadTy); 10370 10371 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10372 Complain); 10373 int NumMatches = Resolver.getNumMatches(); 10374 FunctionDecl *Fn = nullptr; 10375 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10376 if (NumMatches == 0 && ShouldComplain) { 10377 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10378 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10379 else 10380 Resolver.ComplainNoMatchesFound(); 10381 } 10382 else if (NumMatches > 1 && ShouldComplain) 10383 Resolver.ComplainMultipleMatchesFound(); 10384 else if (NumMatches == 1) { 10385 Fn = Resolver.getMatchingFunctionDecl(); 10386 assert(Fn); 10387 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10388 if (Complain) { 10389 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10390 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10391 else 10392 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10393 } 10394 } 10395 10396 if (pHadMultipleCandidates) 10397 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10398 return Fn; 10399 } 10400 10401 /// \brief Given an expression that refers to an overloaded function, try to 10402 /// resolve that overloaded function expression down to a single function. 10403 /// 10404 /// This routine can only resolve template-ids that refer to a single function 10405 /// template, where that template-id refers to a single template whose template 10406 /// arguments are either provided by the template-id or have defaults, 10407 /// as described in C++0x [temp.arg.explicit]p3. 10408 /// 10409 /// If no template-ids are found, no diagnostics are emitted and NULL is 10410 /// returned. 10411 FunctionDecl * 10412 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10413 bool Complain, 10414 DeclAccessPair *FoundResult) { 10415 // C++ [over.over]p1: 10416 // [...] [Note: any redundant set of parentheses surrounding the 10417 // overloaded function name is ignored (5.1). ] 10418 // C++ [over.over]p1: 10419 // [...] The overloaded function name can be preceded by the & 10420 // operator. 10421 10422 // If we didn't actually find any template-ids, we're done. 10423 if (!ovl->hasExplicitTemplateArgs()) 10424 return nullptr; 10425 10426 TemplateArgumentListInfo ExplicitTemplateArgs; 10427 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 10428 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10429 10430 // Look through all of the overloaded functions, searching for one 10431 // whose type matches exactly. 10432 FunctionDecl *Matched = nullptr; 10433 for (UnresolvedSetIterator I = ovl->decls_begin(), 10434 E = ovl->decls_end(); I != E; ++I) { 10435 // C++0x [temp.arg.explicit]p3: 10436 // [...] In contexts where deduction is done and fails, or in contexts 10437 // where deduction is not done, if a template argument list is 10438 // specified and it, along with any default template arguments, 10439 // identifies a single function template specialization, then the 10440 // template-id is an lvalue for the function template specialization. 10441 FunctionTemplateDecl *FunctionTemplate 10442 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10443 10444 // C++ [over.over]p2: 10445 // If the name is a function template, template argument deduction is 10446 // done (14.8.2.2), and if the argument deduction succeeds, the 10447 // resulting template argument list is used to generate a single 10448 // function template specialization, which is added to the set of 10449 // overloaded functions considered. 10450 FunctionDecl *Specialization = nullptr; 10451 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10452 if (TemplateDeductionResult Result 10453 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10454 Specialization, Info, 10455 /*InOverloadResolution=*/true)) { 10456 // Make a note of the failed deduction for diagnostics. 10457 // TODO: Actually use the failed-deduction info? 10458 FailedCandidates.addCandidate() 10459 .set(FunctionTemplate->getTemplatedDecl(), 10460 MakeDeductionFailureInfo(Context, Result, Info)); 10461 continue; 10462 } 10463 10464 assert(Specialization && "no specialization and no error?"); 10465 10466 // Multiple matches; we can't resolve to a single declaration. 10467 if (Matched) { 10468 if (Complain) { 10469 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10470 << ovl->getName(); 10471 NoteAllOverloadCandidates(ovl); 10472 } 10473 return nullptr; 10474 } 10475 10476 Matched = Specialization; 10477 if (FoundResult) *FoundResult = I.getPair(); 10478 } 10479 10480 if (Matched && getLangOpts().CPlusPlus14 && 10481 Matched->getReturnType()->isUndeducedType() && 10482 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10483 return nullptr; 10484 10485 return Matched; 10486 } 10487 10488 10489 10490 10491 // Resolve and fix an overloaded expression that can be resolved 10492 // because it identifies a single function template specialization. 10493 // 10494 // Last three arguments should only be supplied if Complain = true 10495 // 10496 // Return true if it was logically possible to so resolve the 10497 // expression, regardless of whether or not it succeeded. Always 10498 // returns true if 'complain' is set. 10499 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10500 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10501 bool complain, SourceRange OpRangeForComplaining, 10502 QualType DestTypeForComplaining, 10503 unsigned DiagIDForComplaining) { 10504 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10505 10506 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10507 10508 DeclAccessPair found; 10509 ExprResult SingleFunctionExpression; 10510 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10511 ovl.Expression, /*complain*/ false, &found)) { 10512 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10513 SrcExpr = ExprError(); 10514 return true; 10515 } 10516 10517 // It is only correct to resolve to an instance method if we're 10518 // resolving a form that's permitted to be a pointer to member. 10519 // Otherwise we'll end up making a bound member expression, which 10520 // is illegal in all the contexts we resolve like this. 10521 if (!ovl.HasFormOfMemberPointer && 10522 isa<CXXMethodDecl>(fn) && 10523 cast<CXXMethodDecl>(fn)->isInstance()) { 10524 if (!complain) return false; 10525 10526 Diag(ovl.Expression->getExprLoc(), 10527 diag::err_bound_member_function) 10528 << 0 << ovl.Expression->getSourceRange(); 10529 10530 // TODO: I believe we only end up here if there's a mix of 10531 // static and non-static candidates (otherwise the expression 10532 // would have 'bound member' type, not 'overload' type). 10533 // Ideally we would note which candidate was chosen and why 10534 // the static candidates were rejected. 10535 SrcExpr = ExprError(); 10536 return true; 10537 } 10538 10539 // Fix the expression to refer to 'fn'. 10540 SingleFunctionExpression = 10541 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10542 10543 // If desired, do function-to-pointer decay. 10544 if (doFunctionPointerConverion) { 10545 SingleFunctionExpression = 10546 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10547 if (SingleFunctionExpression.isInvalid()) { 10548 SrcExpr = ExprError(); 10549 return true; 10550 } 10551 } 10552 } 10553 10554 if (!SingleFunctionExpression.isUsable()) { 10555 if (complain) { 10556 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10557 << ovl.Expression->getName() 10558 << DestTypeForComplaining 10559 << OpRangeForComplaining 10560 << ovl.Expression->getQualifierLoc().getSourceRange(); 10561 NoteAllOverloadCandidates(SrcExpr.get()); 10562 10563 SrcExpr = ExprError(); 10564 return true; 10565 } 10566 10567 return false; 10568 } 10569 10570 SrcExpr = SingleFunctionExpression; 10571 return true; 10572 } 10573 10574 /// \brief Add a single candidate to the overload set. 10575 static void AddOverloadedCallCandidate(Sema &S, 10576 DeclAccessPair FoundDecl, 10577 TemplateArgumentListInfo *ExplicitTemplateArgs, 10578 ArrayRef<Expr *> Args, 10579 OverloadCandidateSet &CandidateSet, 10580 bool PartialOverloading, 10581 bool KnownValid) { 10582 NamedDecl *Callee = FoundDecl.getDecl(); 10583 if (isa<UsingShadowDecl>(Callee)) 10584 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10585 10586 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10587 if (ExplicitTemplateArgs) { 10588 assert(!KnownValid && "Explicit template arguments?"); 10589 return; 10590 } 10591 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10592 /*SuppressUsedConversions=*/false, 10593 PartialOverloading); 10594 return; 10595 } 10596 10597 if (FunctionTemplateDecl *FuncTemplate 10598 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10599 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10600 ExplicitTemplateArgs, Args, CandidateSet, 10601 /*SuppressUsedConversions=*/false, 10602 PartialOverloading); 10603 return; 10604 } 10605 10606 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10607 } 10608 10609 /// \brief Add the overload candidates named by callee and/or found by argument 10610 /// dependent lookup to the given overload set. 10611 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10612 ArrayRef<Expr *> Args, 10613 OverloadCandidateSet &CandidateSet, 10614 bool PartialOverloading) { 10615 10616 #ifndef NDEBUG 10617 // Verify that ArgumentDependentLookup is consistent with the rules 10618 // in C++0x [basic.lookup.argdep]p3: 10619 // 10620 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10621 // and let Y be the lookup set produced by argument dependent 10622 // lookup (defined as follows). If X contains 10623 // 10624 // -- a declaration of a class member, or 10625 // 10626 // -- a block-scope function declaration that is not a 10627 // using-declaration, or 10628 // 10629 // -- a declaration that is neither a function or a function 10630 // template 10631 // 10632 // then Y is empty. 10633 10634 if (ULE->requiresADL()) { 10635 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10636 E = ULE->decls_end(); I != E; ++I) { 10637 assert(!(*I)->getDeclContext()->isRecord()); 10638 assert(isa<UsingShadowDecl>(*I) || 10639 !(*I)->getDeclContext()->isFunctionOrMethod()); 10640 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10641 } 10642 } 10643 #endif 10644 10645 // It would be nice to avoid this copy. 10646 TemplateArgumentListInfo TABuffer; 10647 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10648 if (ULE->hasExplicitTemplateArgs()) { 10649 ULE->copyTemplateArgumentsInto(TABuffer); 10650 ExplicitTemplateArgs = &TABuffer; 10651 } 10652 10653 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10654 E = ULE->decls_end(); I != E; ++I) 10655 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10656 CandidateSet, PartialOverloading, 10657 /*KnownValid*/ true); 10658 10659 if (ULE->requiresADL()) 10660 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10661 Args, ExplicitTemplateArgs, 10662 CandidateSet, PartialOverloading); 10663 } 10664 10665 /// Determine whether a declaration with the specified name could be moved into 10666 /// a different namespace. 10667 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10668 switch (Name.getCXXOverloadedOperator()) { 10669 case OO_New: case OO_Array_New: 10670 case OO_Delete: case OO_Array_Delete: 10671 return false; 10672 10673 default: 10674 return true; 10675 } 10676 } 10677 10678 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10679 /// template, where the non-dependent name was declared after the template 10680 /// was defined. This is common in code written for a compilers which do not 10681 /// correctly implement two-stage name lookup. 10682 /// 10683 /// Returns true if a viable candidate was found and a diagnostic was issued. 10684 static bool 10685 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10686 const CXXScopeSpec &SS, LookupResult &R, 10687 OverloadCandidateSet::CandidateSetKind CSK, 10688 TemplateArgumentListInfo *ExplicitTemplateArgs, 10689 ArrayRef<Expr *> Args, 10690 bool *DoDiagnoseEmptyLookup = nullptr) { 10691 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10692 return false; 10693 10694 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10695 if (DC->isTransparentContext()) 10696 continue; 10697 10698 SemaRef.LookupQualifiedName(R, DC); 10699 10700 if (!R.empty()) { 10701 R.suppressDiagnostics(); 10702 10703 if (isa<CXXRecordDecl>(DC)) { 10704 // Don't diagnose names we find in classes; we get much better 10705 // diagnostics for these from DiagnoseEmptyLookup. 10706 R.clear(); 10707 if (DoDiagnoseEmptyLookup) 10708 *DoDiagnoseEmptyLookup = true; 10709 return false; 10710 } 10711 10712 OverloadCandidateSet Candidates(FnLoc, CSK); 10713 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10714 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10715 ExplicitTemplateArgs, Args, 10716 Candidates, false, /*KnownValid*/ false); 10717 10718 OverloadCandidateSet::iterator Best; 10719 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10720 // No viable functions. Don't bother the user with notes for functions 10721 // which don't work and shouldn't be found anyway. 10722 R.clear(); 10723 return false; 10724 } 10725 10726 // Find the namespaces where ADL would have looked, and suggest 10727 // declaring the function there instead. 10728 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10729 Sema::AssociatedClassSet AssociatedClasses; 10730 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10731 AssociatedNamespaces, 10732 AssociatedClasses); 10733 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10734 if (canBeDeclaredInNamespace(R.getLookupName())) { 10735 DeclContext *Std = SemaRef.getStdNamespace(); 10736 for (Sema::AssociatedNamespaceSet::iterator 10737 it = AssociatedNamespaces.begin(), 10738 end = AssociatedNamespaces.end(); it != end; ++it) { 10739 // Never suggest declaring a function within namespace 'std'. 10740 if (Std && Std->Encloses(*it)) 10741 continue; 10742 10743 // Never suggest declaring a function within a namespace with a 10744 // reserved name, like __gnu_cxx. 10745 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10746 if (NS && 10747 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10748 continue; 10749 10750 SuggestedNamespaces.insert(*it); 10751 } 10752 } 10753 10754 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10755 << R.getLookupName(); 10756 if (SuggestedNamespaces.empty()) { 10757 SemaRef.Diag(Best->Function->getLocation(), 10758 diag::note_not_found_by_two_phase_lookup) 10759 << R.getLookupName() << 0; 10760 } else if (SuggestedNamespaces.size() == 1) { 10761 SemaRef.Diag(Best->Function->getLocation(), 10762 diag::note_not_found_by_two_phase_lookup) 10763 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10764 } else { 10765 // FIXME: It would be useful to list the associated namespaces here, 10766 // but the diagnostics infrastructure doesn't provide a way to produce 10767 // a localized representation of a list of items. 10768 SemaRef.Diag(Best->Function->getLocation(), 10769 diag::note_not_found_by_two_phase_lookup) 10770 << R.getLookupName() << 2; 10771 } 10772 10773 // Try to recover by calling this function. 10774 return true; 10775 } 10776 10777 R.clear(); 10778 } 10779 10780 return false; 10781 } 10782 10783 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10784 /// template, where the non-dependent operator was declared after the template 10785 /// was defined. 10786 /// 10787 /// Returns true if a viable candidate was found and a diagnostic was issued. 10788 static bool 10789 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10790 SourceLocation OpLoc, 10791 ArrayRef<Expr *> Args) { 10792 DeclarationName OpName = 10793 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10794 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10795 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10796 OverloadCandidateSet::CSK_Operator, 10797 /*ExplicitTemplateArgs=*/nullptr, Args); 10798 } 10799 10800 namespace { 10801 class BuildRecoveryCallExprRAII { 10802 Sema &SemaRef; 10803 public: 10804 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10805 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10806 SemaRef.IsBuildingRecoveryCallExpr = true; 10807 } 10808 10809 ~BuildRecoveryCallExprRAII() { 10810 SemaRef.IsBuildingRecoveryCallExpr = false; 10811 } 10812 }; 10813 10814 } 10815 10816 static std::unique_ptr<CorrectionCandidateCallback> 10817 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 10818 bool HasTemplateArgs, bool AllowTypoCorrection) { 10819 if (!AllowTypoCorrection) 10820 return llvm::make_unique<NoTypoCorrectionCCC>(); 10821 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 10822 HasTemplateArgs, ME); 10823 } 10824 10825 /// Attempts to recover from a call where no functions were found. 10826 /// 10827 /// Returns true if new candidates were found. 10828 static ExprResult 10829 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10830 UnresolvedLookupExpr *ULE, 10831 SourceLocation LParenLoc, 10832 MutableArrayRef<Expr *> Args, 10833 SourceLocation RParenLoc, 10834 bool EmptyLookup, bool AllowTypoCorrection) { 10835 // Do not try to recover if it is already building a recovery call. 10836 // This stops infinite loops for template instantiations like 10837 // 10838 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10839 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10840 // 10841 if (SemaRef.IsBuildingRecoveryCallExpr) 10842 return ExprError(); 10843 BuildRecoveryCallExprRAII RCE(SemaRef); 10844 10845 CXXScopeSpec SS; 10846 SS.Adopt(ULE->getQualifierLoc()); 10847 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10848 10849 TemplateArgumentListInfo TABuffer; 10850 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10851 if (ULE->hasExplicitTemplateArgs()) { 10852 ULE->copyTemplateArgumentsInto(TABuffer); 10853 ExplicitTemplateArgs = &TABuffer; 10854 } 10855 10856 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10857 Sema::LookupOrdinaryName); 10858 bool DoDiagnoseEmptyLookup = EmptyLookup; 10859 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10860 OverloadCandidateSet::CSK_Normal, 10861 ExplicitTemplateArgs, Args, 10862 &DoDiagnoseEmptyLookup) && 10863 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 10864 S, SS, R, 10865 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 10866 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 10867 ExplicitTemplateArgs, Args))) 10868 return ExprError(); 10869 10870 assert(!R.empty() && "lookup results empty despite recovery"); 10871 10872 // Build an implicit member call if appropriate. Just drop the 10873 // casts and such from the call, we don't really care. 10874 ExprResult NewFn = ExprError(); 10875 if ((*R.begin())->isCXXClassMember()) 10876 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 10877 ExplicitTemplateArgs, S); 10878 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10879 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10880 ExplicitTemplateArgs); 10881 else 10882 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10883 10884 if (NewFn.isInvalid()) 10885 return ExprError(); 10886 10887 // This shouldn't cause an infinite loop because we're giving it 10888 // an expression with viable lookup results, which should never 10889 // end up here. 10890 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 10891 MultiExprArg(Args.data(), Args.size()), 10892 RParenLoc); 10893 } 10894 10895 /// \brief Constructs and populates an OverloadedCandidateSet from 10896 /// the given function. 10897 /// \returns true when an the ExprResult output parameter has been set. 10898 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10899 UnresolvedLookupExpr *ULE, 10900 MultiExprArg Args, 10901 SourceLocation RParenLoc, 10902 OverloadCandidateSet *CandidateSet, 10903 ExprResult *Result) { 10904 #ifndef NDEBUG 10905 if (ULE->requiresADL()) { 10906 // To do ADL, we must have found an unqualified name. 10907 assert(!ULE->getQualifier() && "qualified name with ADL"); 10908 10909 // We don't perform ADL for implicit declarations of builtins. 10910 // Verify that this was correctly set up. 10911 FunctionDecl *F; 10912 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10913 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10914 F->getBuiltinID() && F->isImplicit()) 10915 llvm_unreachable("performing ADL for builtin"); 10916 10917 // We don't perform ADL in C. 10918 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10919 } 10920 #endif 10921 10922 UnbridgedCastsSet UnbridgedCasts; 10923 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10924 *Result = ExprError(); 10925 return true; 10926 } 10927 10928 // Add the functions denoted by the callee to the set of candidate 10929 // functions, including those from argument-dependent lookup. 10930 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10931 10932 if (getLangOpts().MSVCCompat && 10933 CurContext->isDependentContext() && !isSFINAEContext() && 10934 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10935 10936 OverloadCandidateSet::iterator Best; 10937 if (CandidateSet->empty() || 10938 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 10939 OR_No_Viable_Function) { 10940 // In Microsoft mode, if we are inside a template class member function then 10941 // create a type dependent CallExpr. The goal is to postpone name lookup 10942 // to instantiation time to be able to search into type dependent base 10943 // classes. 10944 CallExpr *CE = new (Context) CallExpr( 10945 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 10946 CE->setTypeDependent(true); 10947 CE->setValueDependent(true); 10948 CE->setInstantiationDependent(true); 10949 *Result = CE; 10950 return true; 10951 } 10952 } 10953 10954 if (CandidateSet->empty()) 10955 return false; 10956 10957 UnbridgedCasts.restore(); 10958 return false; 10959 } 10960 10961 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10962 /// the completed call expression. If overload resolution fails, emits 10963 /// diagnostics and returns ExprError() 10964 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10965 UnresolvedLookupExpr *ULE, 10966 SourceLocation LParenLoc, 10967 MultiExprArg Args, 10968 SourceLocation RParenLoc, 10969 Expr *ExecConfig, 10970 OverloadCandidateSet *CandidateSet, 10971 OverloadCandidateSet::iterator *Best, 10972 OverloadingResult OverloadResult, 10973 bool AllowTypoCorrection) { 10974 if (CandidateSet->empty()) 10975 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10976 RParenLoc, /*EmptyLookup=*/true, 10977 AllowTypoCorrection); 10978 10979 switch (OverloadResult) { 10980 case OR_Success: { 10981 FunctionDecl *FDecl = (*Best)->Function; 10982 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10983 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10984 return ExprError(); 10985 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10986 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10987 ExecConfig); 10988 } 10989 10990 case OR_No_Viable_Function: { 10991 // Try to recover by looking for viable functions which the user might 10992 // have meant to call. 10993 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10994 Args, RParenLoc, 10995 /*EmptyLookup=*/false, 10996 AllowTypoCorrection); 10997 if (!Recovery.isInvalid()) 10998 return Recovery; 10999 11000 SemaRef.Diag(Fn->getLocStart(), 11001 diag::err_ovl_no_viable_function_in_call) 11002 << ULE->getName() << Fn->getSourceRange(); 11003 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11004 break; 11005 } 11006 11007 case OR_Ambiguous: 11008 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11009 << ULE->getName() << Fn->getSourceRange(); 11010 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11011 break; 11012 11013 case OR_Deleted: { 11014 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11015 << (*Best)->Function->isDeleted() 11016 << ULE->getName() 11017 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11018 << Fn->getSourceRange(); 11019 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11020 11021 // We emitted an error for the unvailable/deleted function call but keep 11022 // the call in the AST. 11023 FunctionDecl *FDecl = (*Best)->Function; 11024 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11025 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11026 ExecConfig); 11027 } 11028 } 11029 11030 // Overload resolution failed. 11031 return ExprError(); 11032 } 11033 11034 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11035 /// (which eventually refers to the declaration Func) and the call 11036 /// arguments Args/NumArgs, attempt to resolve the function call down 11037 /// to a specific function. If overload resolution succeeds, returns 11038 /// the call expression produced by overload resolution. 11039 /// Otherwise, emits diagnostics and returns ExprError. 11040 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11041 UnresolvedLookupExpr *ULE, 11042 SourceLocation LParenLoc, 11043 MultiExprArg Args, 11044 SourceLocation RParenLoc, 11045 Expr *ExecConfig, 11046 bool AllowTypoCorrection) { 11047 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11048 OverloadCandidateSet::CSK_Normal); 11049 ExprResult result; 11050 11051 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11052 &result)) 11053 return result; 11054 11055 OverloadCandidateSet::iterator Best; 11056 OverloadingResult OverloadResult = 11057 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11058 11059 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11060 RParenLoc, ExecConfig, &CandidateSet, 11061 &Best, OverloadResult, 11062 AllowTypoCorrection); 11063 } 11064 11065 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11066 return Functions.size() > 1 || 11067 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11068 } 11069 11070 /// \brief Create a unary operation that may resolve to an overloaded 11071 /// operator. 11072 /// 11073 /// \param OpLoc The location of the operator itself (e.g., '*'). 11074 /// 11075 /// \param OpcIn The UnaryOperator::Opcode that describes this 11076 /// operator. 11077 /// 11078 /// \param Fns The set of non-member functions that will be 11079 /// considered by overload resolution. The caller needs to build this 11080 /// set based on the context using, e.g., 11081 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11082 /// set should not contain any member functions; those will be added 11083 /// by CreateOverloadedUnaryOp(). 11084 /// 11085 /// \param Input The input argument. 11086 ExprResult 11087 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 11088 const UnresolvedSetImpl &Fns, 11089 Expr *Input) { 11090 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 11091 11092 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11093 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11094 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11095 // TODO: provide better source location info. 11096 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11097 11098 if (checkPlaceholderForOverload(*this, Input)) 11099 return ExprError(); 11100 11101 Expr *Args[2] = { Input, nullptr }; 11102 unsigned NumArgs = 1; 11103 11104 // For post-increment and post-decrement, add the implicit '0' as 11105 // the second argument, so that we know this is a post-increment or 11106 // post-decrement. 11107 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11108 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11109 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11110 SourceLocation()); 11111 NumArgs = 2; 11112 } 11113 11114 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11115 11116 if (Input->isTypeDependent()) { 11117 if (Fns.empty()) 11118 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11119 VK_RValue, OK_Ordinary, OpLoc); 11120 11121 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11122 UnresolvedLookupExpr *Fn 11123 = UnresolvedLookupExpr::Create(Context, NamingClass, 11124 NestedNameSpecifierLoc(), OpNameInfo, 11125 /*ADL*/ true, IsOverloaded(Fns), 11126 Fns.begin(), Fns.end()); 11127 return new (Context) 11128 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11129 VK_RValue, OpLoc, false); 11130 } 11131 11132 // Build an empty overload set. 11133 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11134 11135 // Add the candidates from the given function set. 11136 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11137 11138 // Add operator candidates that are member functions. 11139 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11140 11141 // Add candidates from ADL. 11142 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11143 /*ExplicitTemplateArgs*/nullptr, 11144 CandidateSet); 11145 11146 // Add builtin operator candidates. 11147 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11148 11149 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11150 11151 // Perform overload resolution. 11152 OverloadCandidateSet::iterator Best; 11153 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11154 case OR_Success: { 11155 // We found a built-in operator or an overloaded operator. 11156 FunctionDecl *FnDecl = Best->Function; 11157 11158 if (FnDecl) { 11159 // We matched an overloaded operator. Build a call to that 11160 // operator. 11161 11162 // Convert the arguments. 11163 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11164 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11165 11166 ExprResult InputRes = 11167 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11168 Best->FoundDecl, Method); 11169 if (InputRes.isInvalid()) 11170 return ExprError(); 11171 Input = InputRes.get(); 11172 } else { 11173 // Convert the arguments. 11174 ExprResult InputInit 11175 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11176 Context, 11177 FnDecl->getParamDecl(0)), 11178 SourceLocation(), 11179 Input); 11180 if (InputInit.isInvalid()) 11181 return ExprError(); 11182 Input = InputInit.get(); 11183 } 11184 11185 // Build the actual expression node. 11186 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11187 HadMultipleCandidates, OpLoc); 11188 if (FnExpr.isInvalid()) 11189 return ExprError(); 11190 11191 // Determine the result type. 11192 QualType ResultTy = FnDecl->getReturnType(); 11193 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11194 ResultTy = ResultTy.getNonLValueExprType(Context); 11195 11196 Args[0] = Input; 11197 CallExpr *TheCall = 11198 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11199 ResultTy, VK, OpLoc, false); 11200 11201 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11202 return ExprError(); 11203 11204 return MaybeBindToTemporary(TheCall); 11205 } else { 11206 // We matched a built-in operator. Convert the arguments, then 11207 // break out so that we will build the appropriate built-in 11208 // operator node. 11209 ExprResult InputRes = 11210 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11211 Best->Conversions[0], AA_Passing); 11212 if (InputRes.isInvalid()) 11213 return ExprError(); 11214 Input = InputRes.get(); 11215 break; 11216 } 11217 } 11218 11219 case OR_No_Viable_Function: 11220 // This is an erroneous use of an operator which can be overloaded by 11221 // a non-member function. Check for non-member operators which were 11222 // defined too late to be candidates. 11223 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11224 // FIXME: Recover by calling the found function. 11225 return ExprError(); 11226 11227 // No viable function; fall through to handling this as a 11228 // built-in operator, which will produce an error message for us. 11229 break; 11230 11231 case OR_Ambiguous: 11232 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11233 << UnaryOperator::getOpcodeStr(Opc) 11234 << Input->getType() 11235 << Input->getSourceRange(); 11236 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11237 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11238 return ExprError(); 11239 11240 case OR_Deleted: 11241 Diag(OpLoc, diag::err_ovl_deleted_oper) 11242 << Best->Function->isDeleted() 11243 << UnaryOperator::getOpcodeStr(Opc) 11244 << getDeletedOrUnavailableSuffix(Best->Function) 11245 << Input->getSourceRange(); 11246 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11247 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11248 return ExprError(); 11249 } 11250 11251 // Either we found no viable overloaded operator or we matched a 11252 // built-in operator. In either case, fall through to trying to 11253 // build a built-in operation. 11254 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11255 } 11256 11257 /// \brief Create a binary operation that may resolve to an overloaded 11258 /// operator. 11259 /// 11260 /// \param OpLoc The location of the operator itself (e.g., '+'). 11261 /// 11262 /// \param OpcIn The BinaryOperator::Opcode that describes this 11263 /// operator. 11264 /// 11265 /// \param Fns The set of non-member functions that will be 11266 /// considered by overload resolution. The caller needs to build this 11267 /// set based on the context using, e.g., 11268 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11269 /// set should not contain any member functions; those will be added 11270 /// by CreateOverloadedBinOp(). 11271 /// 11272 /// \param LHS Left-hand argument. 11273 /// \param RHS Right-hand argument. 11274 ExprResult 11275 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11276 unsigned OpcIn, 11277 const UnresolvedSetImpl &Fns, 11278 Expr *LHS, Expr *RHS) { 11279 Expr *Args[2] = { LHS, RHS }; 11280 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11281 11282 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 11283 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11284 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11285 11286 // If either side is type-dependent, create an appropriate dependent 11287 // expression. 11288 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11289 if (Fns.empty()) { 11290 // If there are no functions to store, just build a dependent 11291 // BinaryOperator or CompoundAssignment. 11292 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11293 return new (Context) BinaryOperator( 11294 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11295 OpLoc, FPFeatures.fp_contract); 11296 11297 return new (Context) CompoundAssignOperator( 11298 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11299 Context.DependentTy, Context.DependentTy, OpLoc, 11300 FPFeatures.fp_contract); 11301 } 11302 11303 // FIXME: save results of ADL from here? 11304 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11305 // TODO: provide better source location info in DNLoc component. 11306 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11307 UnresolvedLookupExpr *Fn 11308 = UnresolvedLookupExpr::Create(Context, NamingClass, 11309 NestedNameSpecifierLoc(), OpNameInfo, 11310 /*ADL*/ true, IsOverloaded(Fns), 11311 Fns.begin(), Fns.end()); 11312 return new (Context) 11313 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11314 VK_RValue, OpLoc, FPFeatures.fp_contract); 11315 } 11316 11317 // Always do placeholder-like conversions on the RHS. 11318 if (checkPlaceholderForOverload(*this, Args[1])) 11319 return ExprError(); 11320 11321 // Do placeholder-like conversion on the LHS; note that we should 11322 // not get here with a PseudoObject LHS. 11323 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11324 if (checkPlaceholderForOverload(*this, Args[0])) 11325 return ExprError(); 11326 11327 // If this is the assignment operator, we only perform overload resolution 11328 // if the left-hand side is a class or enumeration type. This is actually 11329 // a hack. The standard requires that we do overload resolution between the 11330 // various built-in candidates, but as DR507 points out, this can lead to 11331 // problems. So we do it this way, which pretty much follows what GCC does. 11332 // Note that we go the traditional code path for compound assignment forms. 11333 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11334 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11335 11336 // If this is the .* operator, which is not overloadable, just 11337 // create a built-in binary operator. 11338 if (Opc == BO_PtrMemD) 11339 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11340 11341 // Build an empty overload set. 11342 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11343 11344 // Add the candidates from the given function set. 11345 AddFunctionCandidates(Fns, Args, CandidateSet); 11346 11347 // Add operator candidates that are member functions. 11348 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11349 11350 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11351 // performed for an assignment operator (nor for operator[] nor operator->, 11352 // which don't get here). 11353 if (Opc != BO_Assign) 11354 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11355 /*ExplicitTemplateArgs*/ nullptr, 11356 CandidateSet); 11357 11358 // Add builtin operator candidates. 11359 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11360 11361 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11362 11363 // Perform overload resolution. 11364 OverloadCandidateSet::iterator Best; 11365 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11366 case OR_Success: { 11367 // We found a built-in operator or an overloaded operator. 11368 FunctionDecl *FnDecl = Best->Function; 11369 11370 if (FnDecl) { 11371 // We matched an overloaded operator. Build a call to that 11372 // operator. 11373 11374 // Convert the arguments. 11375 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11376 // Best->Access is only meaningful for class members. 11377 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11378 11379 ExprResult Arg1 = 11380 PerformCopyInitialization( 11381 InitializedEntity::InitializeParameter(Context, 11382 FnDecl->getParamDecl(0)), 11383 SourceLocation(), Args[1]); 11384 if (Arg1.isInvalid()) 11385 return ExprError(); 11386 11387 ExprResult Arg0 = 11388 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11389 Best->FoundDecl, Method); 11390 if (Arg0.isInvalid()) 11391 return ExprError(); 11392 Args[0] = Arg0.getAs<Expr>(); 11393 Args[1] = RHS = Arg1.getAs<Expr>(); 11394 } else { 11395 // Convert the arguments. 11396 ExprResult Arg0 = PerformCopyInitialization( 11397 InitializedEntity::InitializeParameter(Context, 11398 FnDecl->getParamDecl(0)), 11399 SourceLocation(), Args[0]); 11400 if (Arg0.isInvalid()) 11401 return ExprError(); 11402 11403 ExprResult Arg1 = 11404 PerformCopyInitialization( 11405 InitializedEntity::InitializeParameter(Context, 11406 FnDecl->getParamDecl(1)), 11407 SourceLocation(), Args[1]); 11408 if (Arg1.isInvalid()) 11409 return ExprError(); 11410 Args[0] = LHS = Arg0.getAs<Expr>(); 11411 Args[1] = RHS = Arg1.getAs<Expr>(); 11412 } 11413 11414 // Build the actual expression node. 11415 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11416 Best->FoundDecl, 11417 HadMultipleCandidates, OpLoc); 11418 if (FnExpr.isInvalid()) 11419 return ExprError(); 11420 11421 // Determine the result type. 11422 QualType ResultTy = FnDecl->getReturnType(); 11423 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11424 ResultTy = ResultTy.getNonLValueExprType(Context); 11425 11426 CXXOperatorCallExpr *TheCall = 11427 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11428 Args, ResultTy, VK, OpLoc, 11429 FPFeatures.fp_contract); 11430 11431 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11432 FnDecl)) 11433 return ExprError(); 11434 11435 ArrayRef<const Expr *> ArgsArray(Args, 2); 11436 // Cut off the implicit 'this'. 11437 if (isa<CXXMethodDecl>(FnDecl)) 11438 ArgsArray = ArgsArray.slice(1); 11439 11440 // Check for a self move. 11441 if (Op == OO_Equal) 11442 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11443 11444 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11445 TheCall->getSourceRange(), VariadicDoesNotApply); 11446 11447 return MaybeBindToTemporary(TheCall); 11448 } else { 11449 // We matched a built-in operator. Convert the arguments, then 11450 // break out so that we will build the appropriate built-in 11451 // operator node. 11452 ExprResult ArgsRes0 = 11453 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11454 Best->Conversions[0], AA_Passing); 11455 if (ArgsRes0.isInvalid()) 11456 return ExprError(); 11457 Args[0] = ArgsRes0.get(); 11458 11459 ExprResult ArgsRes1 = 11460 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11461 Best->Conversions[1], AA_Passing); 11462 if (ArgsRes1.isInvalid()) 11463 return ExprError(); 11464 Args[1] = ArgsRes1.get(); 11465 break; 11466 } 11467 } 11468 11469 case OR_No_Viable_Function: { 11470 // C++ [over.match.oper]p9: 11471 // If the operator is the operator , [...] and there are no 11472 // viable functions, then the operator is assumed to be the 11473 // built-in operator and interpreted according to clause 5. 11474 if (Opc == BO_Comma) 11475 break; 11476 11477 // For class as left operand for assignment or compound assigment 11478 // operator do not fall through to handling in built-in, but report that 11479 // no overloaded assignment operator found 11480 ExprResult Result = ExprError(); 11481 if (Args[0]->getType()->isRecordType() && 11482 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11483 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11484 << BinaryOperator::getOpcodeStr(Opc) 11485 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11486 if (Args[0]->getType()->isIncompleteType()) { 11487 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11488 << Args[0]->getType() 11489 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11490 } 11491 } else { 11492 // This is an erroneous use of an operator which can be overloaded by 11493 // a non-member function. Check for non-member operators which were 11494 // defined too late to be candidates. 11495 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11496 // FIXME: Recover by calling the found function. 11497 return ExprError(); 11498 11499 // No viable function; try to create a built-in operation, which will 11500 // produce an error. Then, show the non-viable candidates. 11501 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11502 } 11503 assert(Result.isInvalid() && 11504 "C++ binary operator overloading is missing candidates!"); 11505 if (Result.isInvalid()) 11506 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11507 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11508 return Result; 11509 } 11510 11511 case OR_Ambiguous: 11512 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11513 << BinaryOperator::getOpcodeStr(Opc) 11514 << Args[0]->getType() << Args[1]->getType() 11515 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11516 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11517 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11518 return ExprError(); 11519 11520 case OR_Deleted: 11521 if (isImplicitlyDeleted(Best->Function)) { 11522 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11523 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11524 << Context.getRecordType(Method->getParent()) 11525 << getSpecialMember(Method); 11526 11527 // The user probably meant to call this special member. Just 11528 // explain why it's deleted. 11529 NoteDeletedFunction(Method); 11530 return ExprError(); 11531 } else { 11532 Diag(OpLoc, diag::err_ovl_deleted_oper) 11533 << Best->Function->isDeleted() 11534 << BinaryOperator::getOpcodeStr(Opc) 11535 << getDeletedOrUnavailableSuffix(Best->Function) 11536 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11537 } 11538 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11539 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11540 return ExprError(); 11541 } 11542 11543 // We matched a built-in operator; build it. 11544 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11545 } 11546 11547 ExprResult 11548 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11549 SourceLocation RLoc, 11550 Expr *Base, Expr *Idx) { 11551 Expr *Args[2] = { Base, Idx }; 11552 DeclarationName OpName = 11553 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11554 11555 // If either side is type-dependent, create an appropriate dependent 11556 // expression. 11557 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11558 11559 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11560 // CHECKME: no 'operator' keyword? 11561 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11562 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11563 UnresolvedLookupExpr *Fn 11564 = UnresolvedLookupExpr::Create(Context, NamingClass, 11565 NestedNameSpecifierLoc(), OpNameInfo, 11566 /*ADL*/ true, /*Overloaded*/ false, 11567 UnresolvedSetIterator(), 11568 UnresolvedSetIterator()); 11569 // Can't add any actual overloads yet 11570 11571 return new (Context) 11572 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11573 Context.DependentTy, VK_RValue, RLoc, false); 11574 } 11575 11576 // Handle placeholders on both operands. 11577 if (checkPlaceholderForOverload(*this, Args[0])) 11578 return ExprError(); 11579 if (checkPlaceholderForOverload(*this, Args[1])) 11580 return ExprError(); 11581 11582 // Build an empty overload set. 11583 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11584 11585 // Subscript can only be overloaded as a member function. 11586 11587 // Add operator candidates that are member functions. 11588 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11589 11590 // Add builtin operator candidates. 11591 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11592 11593 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11594 11595 // Perform overload resolution. 11596 OverloadCandidateSet::iterator Best; 11597 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11598 case OR_Success: { 11599 // We found a built-in operator or an overloaded operator. 11600 FunctionDecl *FnDecl = Best->Function; 11601 11602 if (FnDecl) { 11603 // We matched an overloaded operator. Build a call to that 11604 // operator. 11605 11606 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11607 11608 // Convert the arguments. 11609 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11610 ExprResult Arg0 = 11611 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11612 Best->FoundDecl, Method); 11613 if (Arg0.isInvalid()) 11614 return ExprError(); 11615 Args[0] = Arg0.get(); 11616 11617 // Convert the arguments. 11618 ExprResult InputInit 11619 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11620 Context, 11621 FnDecl->getParamDecl(0)), 11622 SourceLocation(), 11623 Args[1]); 11624 if (InputInit.isInvalid()) 11625 return ExprError(); 11626 11627 Args[1] = InputInit.getAs<Expr>(); 11628 11629 // Build the actual expression node. 11630 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11631 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11632 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11633 Best->FoundDecl, 11634 HadMultipleCandidates, 11635 OpLocInfo.getLoc(), 11636 OpLocInfo.getInfo()); 11637 if (FnExpr.isInvalid()) 11638 return ExprError(); 11639 11640 // Determine the result type 11641 QualType ResultTy = FnDecl->getReturnType(); 11642 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11643 ResultTy = ResultTy.getNonLValueExprType(Context); 11644 11645 CXXOperatorCallExpr *TheCall = 11646 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11647 FnExpr.get(), Args, 11648 ResultTy, VK, RLoc, 11649 false); 11650 11651 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11652 return ExprError(); 11653 11654 return MaybeBindToTemporary(TheCall); 11655 } else { 11656 // We matched a built-in operator. Convert the arguments, then 11657 // break out so that we will build the appropriate built-in 11658 // operator node. 11659 ExprResult ArgsRes0 = 11660 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11661 Best->Conversions[0], AA_Passing); 11662 if (ArgsRes0.isInvalid()) 11663 return ExprError(); 11664 Args[0] = ArgsRes0.get(); 11665 11666 ExprResult ArgsRes1 = 11667 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11668 Best->Conversions[1], AA_Passing); 11669 if (ArgsRes1.isInvalid()) 11670 return ExprError(); 11671 Args[1] = ArgsRes1.get(); 11672 11673 break; 11674 } 11675 } 11676 11677 case OR_No_Viable_Function: { 11678 if (CandidateSet.empty()) 11679 Diag(LLoc, diag::err_ovl_no_oper) 11680 << Args[0]->getType() << /*subscript*/ 0 11681 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11682 else 11683 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11684 << Args[0]->getType() 11685 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11686 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11687 "[]", LLoc); 11688 return ExprError(); 11689 } 11690 11691 case OR_Ambiguous: 11692 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11693 << "[]" 11694 << Args[0]->getType() << Args[1]->getType() 11695 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11696 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11697 "[]", LLoc); 11698 return ExprError(); 11699 11700 case OR_Deleted: 11701 Diag(LLoc, diag::err_ovl_deleted_oper) 11702 << Best->Function->isDeleted() << "[]" 11703 << getDeletedOrUnavailableSuffix(Best->Function) 11704 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11705 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11706 "[]", LLoc); 11707 return ExprError(); 11708 } 11709 11710 // We matched a built-in operator; build it. 11711 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11712 } 11713 11714 /// BuildCallToMemberFunction - Build a call to a member 11715 /// function. MemExpr is the expression that refers to the member 11716 /// function (and includes the object parameter), Args/NumArgs are the 11717 /// arguments to the function call (not including the object 11718 /// parameter). The caller needs to validate that the member 11719 /// expression refers to a non-static member function or an overloaded 11720 /// member function. 11721 ExprResult 11722 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11723 SourceLocation LParenLoc, 11724 MultiExprArg Args, 11725 SourceLocation RParenLoc) { 11726 assert(MemExprE->getType() == Context.BoundMemberTy || 11727 MemExprE->getType() == Context.OverloadTy); 11728 11729 // Dig out the member expression. This holds both the object 11730 // argument and the member function we're referring to. 11731 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11732 11733 // Determine whether this is a call to a pointer-to-member function. 11734 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11735 assert(op->getType() == Context.BoundMemberTy); 11736 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11737 11738 QualType fnType = 11739 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11740 11741 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11742 QualType resultType = proto->getCallResultType(Context); 11743 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11744 11745 // Check that the object type isn't more qualified than the 11746 // member function we're calling. 11747 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11748 11749 QualType objectType = op->getLHS()->getType(); 11750 if (op->getOpcode() == BO_PtrMemI) 11751 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11752 Qualifiers objectQuals = objectType.getQualifiers(); 11753 11754 Qualifiers difference = objectQuals - funcQuals; 11755 difference.removeObjCGCAttr(); 11756 difference.removeAddressSpace(); 11757 if (difference) { 11758 std::string qualsString = difference.getAsString(); 11759 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11760 << fnType.getUnqualifiedType() 11761 << qualsString 11762 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11763 } 11764 11765 CXXMemberCallExpr *call 11766 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11767 resultType, valueKind, RParenLoc); 11768 11769 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11770 call, nullptr)) 11771 return ExprError(); 11772 11773 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 11774 return ExprError(); 11775 11776 if (CheckOtherCall(call, proto)) 11777 return ExprError(); 11778 11779 return MaybeBindToTemporary(call); 11780 } 11781 11782 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 11783 return new (Context) 11784 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 11785 11786 UnbridgedCastsSet UnbridgedCasts; 11787 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11788 return ExprError(); 11789 11790 MemberExpr *MemExpr; 11791 CXXMethodDecl *Method = nullptr; 11792 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 11793 NestedNameSpecifier *Qualifier = nullptr; 11794 if (isa<MemberExpr>(NakedMemExpr)) { 11795 MemExpr = cast<MemberExpr>(NakedMemExpr); 11796 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11797 FoundDecl = MemExpr->getFoundDecl(); 11798 Qualifier = MemExpr->getQualifier(); 11799 UnbridgedCasts.restore(); 11800 } else { 11801 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11802 Qualifier = UnresExpr->getQualifier(); 11803 11804 QualType ObjectType = UnresExpr->getBaseType(); 11805 Expr::Classification ObjectClassification 11806 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11807 : UnresExpr->getBase()->Classify(Context); 11808 11809 // Add overload candidates 11810 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 11811 OverloadCandidateSet::CSK_Normal); 11812 11813 // FIXME: avoid copy. 11814 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 11815 if (UnresExpr->hasExplicitTemplateArgs()) { 11816 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11817 TemplateArgs = &TemplateArgsBuffer; 11818 } 11819 11820 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11821 E = UnresExpr->decls_end(); I != E; ++I) { 11822 11823 NamedDecl *Func = *I; 11824 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11825 if (isa<UsingShadowDecl>(Func)) 11826 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11827 11828 11829 // Microsoft supports direct constructor calls. 11830 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11831 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11832 Args, CandidateSet); 11833 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11834 // If explicit template arguments were provided, we can't call a 11835 // non-template member function. 11836 if (TemplateArgs) 11837 continue; 11838 11839 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11840 ObjectClassification, Args, CandidateSet, 11841 /*SuppressUserConversions=*/false); 11842 } else { 11843 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11844 I.getPair(), ActingDC, TemplateArgs, 11845 ObjectType, ObjectClassification, 11846 Args, CandidateSet, 11847 /*SuppressUsedConversions=*/false); 11848 } 11849 } 11850 11851 DeclarationName DeclName = UnresExpr->getMemberName(); 11852 11853 UnbridgedCasts.restore(); 11854 11855 OverloadCandidateSet::iterator Best; 11856 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11857 Best)) { 11858 case OR_Success: 11859 Method = cast<CXXMethodDecl>(Best->Function); 11860 FoundDecl = Best->FoundDecl; 11861 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11862 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11863 return ExprError(); 11864 // If FoundDecl is different from Method (such as if one is a template 11865 // and the other a specialization), make sure DiagnoseUseOfDecl is 11866 // called on both. 11867 // FIXME: This would be more comprehensively addressed by modifying 11868 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11869 // being used. 11870 if (Method != FoundDecl.getDecl() && 11871 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11872 return ExprError(); 11873 break; 11874 11875 case OR_No_Viable_Function: 11876 Diag(UnresExpr->getMemberLoc(), 11877 diag::err_ovl_no_viable_member_function_in_call) 11878 << DeclName << MemExprE->getSourceRange(); 11879 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11880 // FIXME: Leaking incoming expressions! 11881 return ExprError(); 11882 11883 case OR_Ambiguous: 11884 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11885 << DeclName << MemExprE->getSourceRange(); 11886 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11887 // FIXME: Leaking incoming expressions! 11888 return ExprError(); 11889 11890 case OR_Deleted: 11891 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11892 << Best->Function->isDeleted() 11893 << DeclName 11894 << getDeletedOrUnavailableSuffix(Best->Function) 11895 << MemExprE->getSourceRange(); 11896 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11897 // FIXME: Leaking incoming expressions! 11898 return ExprError(); 11899 } 11900 11901 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11902 11903 // If overload resolution picked a static member, build a 11904 // non-member call based on that function. 11905 if (Method->isStatic()) { 11906 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11907 RParenLoc); 11908 } 11909 11910 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11911 } 11912 11913 QualType ResultType = Method->getReturnType(); 11914 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11915 ResultType = ResultType.getNonLValueExprType(Context); 11916 11917 assert(Method && "Member call to something that isn't a method?"); 11918 CXXMemberCallExpr *TheCall = 11919 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11920 ResultType, VK, RParenLoc); 11921 11922 // (CUDA B.1): Check for invalid calls between targets. 11923 if (getLangOpts().CUDA) { 11924 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 11925 if (CheckCUDATarget(Caller, Method)) { 11926 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 11927 << IdentifyCUDATarget(Method) << Method->getIdentifier() 11928 << IdentifyCUDATarget(Caller); 11929 return ExprError(); 11930 } 11931 } 11932 } 11933 11934 // Check for a valid return type. 11935 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 11936 TheCall, Method)) 11937 return ExprError(); 11938 11939 // Convert the object argument (for a non-static member function call). 11940 // We only need to do this if there was actually an overload; otherwise 11941 // it was done at lookup. 11942 if (!Method->isStatic()) { 11943 ExprResult ObjectArg = 11944 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11945 FoundDecl, Method); 11946 if (ObjectArg.isInvalid()) 11947 return ExprError(); 11948 MemExpr->setBase(ObjectArg.get()); 11949 } 11950 11951 // Convert the rest of the arguments 11952 const FunctionProtoType *Proto = 11953 Method->getType()->getAs<FunctionProtoType>(); 11954 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11955 RParenLoc)) 11956 return ExprError(); 11957 11958 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11959 11960 if (CheckFunctionCall(Method, TheCall, Proto)) 11961 return ExprError(); 11962 11963 // In the case the method to call was not selected by the overloading 11964 // resolution process, we still need to handle the enable_if attribute. Do 11965 // that here, so it will not hide previous -- and more relevant -- errors 11966 if (isa<MemberExpr>(NakedMemExpr)) { 11967 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 11968 Diag(MemExprE->getLocStart(), 11969 diag::err_ovl_no_viable_member_function_in_call) 11970 << Method << Method->getSourceRange(); 11971 Diag(Method->getLocation(), 11972 diag::note_ovl_candidate_disabled_by_enable_if_attr) 11973 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11974 return ExprError(); 11975 } 11976 } 11977 11978 if ((isa<CXXConstructorDecl>(CurContext) || 11979 isa<CXXDestructorDecl>(CurContext)) && 11980 TheCall->getMethodDecl()->isPure()) { 11981 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11982 11983 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 11984 MemExpr->performsVirtualDispatch(getLangOpts())) { 11985 Diag(MemExpr->getLocStart(), 11986 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11987 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11988 << MD->getParent()->getDeclName(); 11989 11990 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11991 if (getLangOpts().AppleKext) 11992 Diag(MemExpr->getLocStart(), 11993 diag::note_pure_qualified_call_kext) 11994 << MD->getParent()->getDeclName() 11995 << MD->getDeclName(); 11996 } 11997 } 11998 return MaybeBindToTemporary(TheCall); 11999 } 12000 12001 /// BuildCallToObjectOfClassType - Build a call to an object of class 12002 /// type (C++ [over.call.object]), which can end up invoking an 12003 /// overloaded function call operator (@c operator()) or performing a 12004 /// user-defined conversion on the object argument. 12005 ExprResult 12006 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12007 SourceLocation LParenLoc, 12008 MultiExprArg Args, 12009 SourceLocation RParenLoc) { 12010 if (checkPlaceholderForOverload(*this, Obj)) 12011 return ExprError(); 12012 ExprResult Object = Obj; 12013 12014 UnbridgedCastsSet UnbridgedCasts; 12015 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12016 return ExprError(); 12017 12018 assert(Object.get()->getType()->isRecordType() && 12019 "Requires object type argument"); 12020 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12021 12022 // C++ [over.call.object]p1: 12023 // If the primary-expression E in the function call syntax 12024 // evaluates to a class object of type "cv T", then the set of 12025 // candidate functions includes at least the function call 12026 // operators of T. The function call operators of T are obtained by 12027 // ordinary lookup of the name operator() in the context of 12028 // (E).operator(). 12029 OverloadCandidateSet CandidateSet(LParenLoc, 12030 OverloadCandidateSet::CSK_Operator); 12031 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12032 12033 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12034 diag::err_incomplete_object_call, Object.get())) 12035 return true; 12036 12037 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12038 LookupQualifiedName(R, Record->getDecl()); 12039 R.suppressDiagnostics(); 12040 12041 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12042 Oper != OperEnd; ++Oper) { 12043 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12044 Object.get()->Classify(Context), 12045 Args, CandidateSet, 12046 /*SuppressUserConversions=*/ false); 12047 } 12048 12049 // C++ [over.call.object]p2: 12050 // In addition, for each (non-explicit in C++0x) conversion function 12051 // declared in T of the form 12052 // 12053 // operator conversion-type-id () cv-qualifier; 12054 // 12055 // where cv-qualifier is the same cv-qualification as, or a 12056 // greater cv-qualification than, cv, and where conversion-type-id 12057 // denotes the type "pointer to function of (P1,...,Pn) returning 12058 // R", or the type "reference to pointer to function of 12059 // (P1,...,Pn) returning R", or the type "reference to function 12060 // of (P1,...,Pn) returning R", a surrogate call function [...] 12061 // is also considered as a candidate function. Similarly, 12062 // surrogate call functions are added to the set of candidate 12063 // functions for each conversion function declared in an 12064 // accessible base class provided the function is not hidden 12065 // within T by another intervening declaration. 12066 const auto &Conversions = 12067 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12068 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12069 NamedDecl *D = *I; 12070 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12071 if (isa<UsingShadowDecl>(D)) 12072 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12073 12074 // Skip over templated conversion functions; they aren't 12075 // surrogates. 12076 if (isa<FunctionTemplateDecl>(D)) 12077 continue; 12078 12079 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12080 if (!Conv->isExplicit()) { 12081 // Strip the reference type (if any) and then the pointer type (if 12082 // any) to get down to what might be a function type. 12083 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12084 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12085 ConvType = ConvPtrType->getPointeeType(); 12086 12087 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12088 { 12089 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12090 Object.get(), Args, CandidateSet); 12091 } 12092 } 12093 } 12094 12095 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12096 12097 // Perform overload resolution. 12098 OverloadCandidateSet::iterator Best; 12099 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12100 Best)) { 12101 case OR_Success: 12102 // Overload resolution succeeded; we'll build the appropriate call 12103 // below. 12104 break; 12105 12106 case OR_No_Viable_Function: 12107 if (CandidateSet.empty()) 12108 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12109 << Object.get()->getType() << /*call*/ 1 12110 << Object.get()->getSourceRange(); 12111 else 12112 Diag(Object.get()->getLocStart(), 12113 diag::err_ovl_no_viable_object_call) 12114 << Object.get()->getType() << Object.get()->getSourceRange(); 12115 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12116 break; 12117 12118 case OR_Ambiguous: 12119 Diag(Object.get()->getLocStart(), 12120 diag::err_ovl_ambiguous_object_call) 12121 << Object.get()->getType() << Object.get()->getSourceRange(); 12122 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12123 break; 12124 12125 case OR_Deleted: 12126 Diag(Object.get()->getLocStart(), 12127 diag::err_ovl_deleted_object_call) 12128 << Best->Function->isDeleted() 12129 << Object.get()->getType() 12130 << getDeletedOrUnavailableSuffix(Best->Function) 12131 << Object.get()->getSourceRange(); 12132 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12133 break; 12134 } 12135 12136 if (Best == CandidateSet.end()) 12137 return true; 12138 12139 UnbridgedCasts.restore(); 12140 12141 if (Best->Function == nullptr) { 12142 // Since there is no function declaration, this is one of the 12143 // surrogate candidates. Dig out the conversion function. 12144 CXXConversionDecl *Conv 12145 = cast<CXXConversionDecl>( 12146 Best->Conversions[0].UserDefined.ConversionFunction); 12147 12148 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12149 Best->FoundDecl); 12150 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12151 return ExprError(); 12152 assert(Conv == Best->FoundDecl.getDecl() && 12153 "Found Decl & conversion-to-functionptr should be same, right?!"); 12154 // We selected one of the surrogate functions that converts the 12155 // object parameter to a function pointer. Perform the conversion 12156 // on the object argument, then let ActOnCallExpr finish the job. 12157 12158 // Create an implicit member expr to refer to the conversion operator. 12159 // and then call it. 12160 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12161 Conv, HadMultipleCandidates); 12162 if (Call.isInvalid()) 12163 return ExprError(); 12164 // Record usage of conversion in an implicit cast. 12165 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12166 CK_UserDefinedConversion, Call.get(), 12167 nullptr, VK_RValue); 12168 12169 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12170 } 12171 12172 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12173 12174 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12175 // that calls this method, using Object for the implicit object 12176 // parameter and passing along the remaining arguments. 12177 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12178 12179 // An error diagnostic has already been printed when parsing the declaration. 12180 if (Method->isInvalidDecl()) 12181 return ExprError(); 12182 12183 const FunctionProtoType *Proto = 12184 Method->getType()->getAs<FunctionProtoType>(); 12185 12186 unsigned NumParams = Proto->getNumParams(); 12187 12188 DeclarationNameInfo OpLocInfo( 12189 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12190 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12191 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12192 HadMultipleCandidates, 12193 OpLocInfo.getLoc(), 12194 OpLocInfo.getInfo()); 12195 if (NewFn.isInvalid()) 12196 return true; 12197 12198 // Build the full argument list for the method call (the implicit object 12199 // parameter is placed at the beginning of the list). 12200 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12201 MethodArgs[0] = Object.get(); 12202 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12203 12204 // Once we've built TheCall, all of the expressions are properly 12205 // owned. 12206 QualType ResultTy = Method->getReturnType(); 12207 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12208 ResultTy = ResultTy.getNonLValueExprType(Context); 12209 12210 CXXOperatorCallExpr *TheCall = new (Context) 12211 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12212 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12213 ResultTy, VK, RParenLoc, false); 12214 MethodArgs.reset(); 12215 12216 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12217 return true; 12218 12219 // We may have default arguments. If so, we need to allocate more 12220 // slots in the call for them. 12221 if (Args.size() < NumParams) 12222 TheCall->setNumArgs(Context, NumParams + 1); 12223 12224 bool IsError = false; 12225 12226 // Initialize the implicit object parameter. 12227 ExprResult ObjRes = 12228 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12229 Best->FoundDecl, Method); 12230 if (ObjRes.isInvalid()) 12231 IsError = true; 12232 else 12233 Object = ObjRes; 12234 TheCall->setArg(0, Object.get()); 12235 12236 // Check the argument types. 12237 for (unsigned i = 0; i != NumParams; i++) { 12238 Expr *Arg; 12239 if (i < Args.size()) { 12240 Arg = Args[i]; 12241 12242 // Pass the argument. 12243 12244 ExprResult InputInit 12245 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12246 Context, 12247 Method->getParamDecl(i)), 12248 SourceLocation(), Arg); 12249 12250 IsError |= InputInit.isInvalid(); 12251 Arg = InputInit.getAs<Expr>(); 12252 } else { 12253 ExprResult DefArg 12254 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12255 if (DefArg.isInvalid()) { 12256 IsError = true; 12257 break; 12258 } 12259 12260 Arg = DefArg.getAs<Expr>(); 12261 } 12262 12263 TheCall->setArg(i + 1, Arg); 12264 } 12265 12266 // If this is a variadic call, handle args passed through "...". 12267 if (Proto->isVariadic()) { 12268 // Promote the arguments (C99 6.5.2.2p7). 12269 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12270 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12271 nullptr); 12272 IsError |= Arg.isInvalid(); 12273 TheCall->setArg(i + 1, Arg.get()); 12274 } 12275 } 12276 12277 if (IsError) return true; 12278 12279 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12280 12281 if (CheckFunctionCall(Method, TheCall, Proto)) 12282 return true; 12283 12284 return MaybeBindToTemporary(TheCall); 12285 } 12286 12287 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12288 /// (if one exists), where @c Base is an expression of class type and 12289 /// @c Member is the name of the member we're trying to find. 12290 ExprResult 12291 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12292 bool *NoArrowOperatorFound) { 12293 assert(Base->getType()->isRecordType() && 12294 "left-hand side must have class type"); 12295 12296 if (checkPlaceholderForOverload(*this, Base)) 12297 return ExprError(); 12298 12299 SourceLocation Loc = Base->getExprLoc(); 12300 12301 // C++ [over.ref]p1: 12302 // 12303 // [...] An expression x->m is interpreted as (x.operator->())->m 12304 // for a class object x of type T if T::operator->() exists and if 12305 // the operator is selected as the best match function by the 12306 // overload resolution mechanism (13.3). 12307 DeclarationName OpName = 12308 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12309 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12310 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12311 12312 if (RequireCompleteType(Loc, Base->getType(), 12313 diag::err_typecheck_incomplete_tag, Base)) 12314 return ExprError(); 12315 12316 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12317 LookupQualifiedName(R, BaseRecord->getDecl()); 12318 R.suppressDiagnostics(); 12319 12320 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12321 Oper != OperEnd; ++Oper) { 12322 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12323 None, CandidateSet, /*SuppressUserConversions=*/false); 12324 } 12325 12326 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12327 12328 // Perform overload resolution. 12329 OverloadCandidateSet::iterator Best; 12330 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12331 case OR_Success: 12332 // Overload resolution succeeded; we'll build the call below. 12333 break; 12334 12335 case OR_No_Viable_Function: 12336 if (CandidateSet.empty()) { 12337 QualType BaseType = Base->getType(); 12338 if (NoArrowOperatorFound) { 12339 // Report this specific error to the caller instead of emitting a 12340 // diagnostic, as requested. 12341 *NoArrowOperatorFound = true; 12342 return ExprError(); 12343 } 12344 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12345 << BaseType << Base->getSourceRange(); 12346 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12347 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12348 << FixItHint::CreateReplacement(OpLoc, "."); 12349 } 12350 } else 12351 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12352 << "operator->" << Base->getSourceRange(); 12353 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12354 return ExprError(); 12355 12356 case OR_Ambiguous: 12357 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12358 << "->" << Base->getType() << Base->getSourceRange(); 12359 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12360 return ExprError(); 12361 12362 case OR_Deleted: 12363 Diag(OpLoc, diag::err_ovl_deleted_oper) 12364 << Best->Function->isDeleted() 12365 << "->" 12366 << getDeletedOrUnavailableSuffix(Best->Function) 12367 << Base->getSourceRange(); 12368 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12369 return ExprError(); 12370 } 12371 12372 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12373 12374 // Convert the object parameter. 12375 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12376 ExprResult BaseResult = 12377 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12378 Best->FoundDecl, Method); 12379 if (BaseResult.isInvalid()) 12380 return ExprError(); 12381 Base = BaseResult.get(); 12382 12383 // Build the operator call. 12384 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12385 HadMultipleCandidates, OpLoc); 12386 if (FnExpr.isInvalid()) 12387 return ExprError(); 12388 12389 QualType ResultTy = Method->getReturnType(); 12390 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12391 ResultTy = ResultTy.getNonLValueExprType(Context); 12392 CXXOperatorCallExpr *TheCall = 12393 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12394 Base, ResultTy, VK, OpLoc, false); 12395 12396 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12397 return ExprError(); 12398 12399 return MaybeBindToTemporary(TheCall); 12400 } 12401 12402 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12403 /// a literal operator described by the provided lookup results. 12404 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12405 DeclarationNameInfo &SuffixInfo, 12406 ArrayRef<Expr*> Args, 12407 SourceLocation LitEndLoc, 12408 TemplateArgumentListInfo *TemplateArgs) { 12409 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12410 12411 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12412 OverloadCandidateSet::CSK_Normal); 12413 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12414 /*SuppressUserConversions=*/true); 12415 12416 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12417 12418 // Perform overload resolution. This will usually be trivial, but might need 12419 // to perform substitutions for a literal operator template. 12420 OverloadCandidateSet::iterator Best; 12421 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12422 case OR_Success: 12423 case OR_Deleted: 12424 break; 12425 12426 case OR_No_Viable_Function: 12427 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12428 << R.getLookupName(); 12429 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12430 return ExprError(); 12431 12432 case OR_Ambiguous: 12433 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12434 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12435 return ExprError(); 12436 } 12437 12438 FunctionDecl *FD = Best->Function; 12439 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12440 HadMultipleCandidates, 12441 SuffixInfo.getLoc(), 12442 SuffixInfo.getInfo()); 12443 if (Fn.isInvalid()) 12444 return true; 12445 12446 // Check the argument types. This should almost always be a no-op, except 12447 // that array-to-pointer decay is applied to string literals. 12448 Expr *ConvArgs[2]; 12449 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12450 ExprResult InputInit = PerformCopyInitialization( 12451 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12452 SourceLocation(), Args[ArgIdx]); 12453 if (InputInit.isInvalid()) 12454 return true; 12455 ConvArgs[ArgIdx] = InputInit.get(); 12456 } 12457 12458 QualType ResultTy = FD->getReturnType(); 12459 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12460 ResultTy = ResultTy.getNonLValueExprType(Context); 12461 12462 UserDefinedLiteral *UDL = 12463 new (Context) UserDefinedLiteral(Context, Fn.get(), 12464 llvm::makeArrayRef(ConvArgs, Args.size()), 12465 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12466 12467 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12468 return ExprError(); 12469 12470 if (CheckFunctionCall(FD, UDL, nullptr)) 12471 return ExprError(); 12472 12473 return MaybeBindToTemporary(UDL); 12474 } 12475 12476 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12477 /// given LookupResult is non-empty, it is assumed to describe a member which 12478 /// will be invoked. Otherwise, the function will be found via argument 12479 /// dependent lookup. 12480 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12481 /// otherwise CallExpr is set to ExprError() and some non-success value 12482 /// is returned. 12483 Sema::ForRangeStatus 12484 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 12485 SourceLocation RangeLoc, VarDecl *Decl, 12486 BeginEndFunction BEF, 12487 const DeclarationNameInfo &NameInfo, 12488 LookupResult &MemberLookup, 12489 OverloadCandidateSet *CandidateSet, 12490 Expr *Range, ExprResult *CallExpr) { 12491 CandidateSet->clear(); 12492 if (!MemberLookup.empty()) { 12493 ExprResult MemberRef = 12494 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12495 /*IsPtr=*/false, CXXScopeSpec(), 12496 /*TemplateKWLoc=*/SourceLocation(), 12497 /*FirstQualifierInScope=*/nullptr, 12498 MemberLookup, 12499 /*TemplateArgs=*/nullptr, S); 12500 if (MemberRef.isInvalid()) { 12501 *CallExpr = ExprError(); 12502 Diag(Range->getLocStart(), diag::note_in_for_range) 12503 << RangeLoc << BEF << Range->getType(); 12504 return FRS_DiagnosticIssued; 12505 } 12506 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12507 if (CallExpr->isInvalid()) { 12508 *CallExpr = ExprError(); 12509 Diag(Range->getLocStart(), diag::note_in_for_range) 12510 << RangeLoc << BEF << Range->getType(); 12511 return FRS_DiagnosticIssued; 12512 } 12513 } else { 12514 UnresolvedSet<0> FoundNames; 12515 UnresolvedLookupExpr *Fn = 12516 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12517 NestedNameSpecifierLoc(), NameInfo, 12518 /*NeedsADL=*/true, /*Overloaded=*/false, 12519 FoundNames.begin(), FoundNames.end()); 12520 12521 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12522 CandidateSet, CallExpr); 12523 if (CandidateSet->empty() || CandidateSetError) { 12524 *CallExpr = ExprError(); 12525 return FRS_NoViableFunction; 12526 } 12527 OverloadCandidateSet::iterator Best; 12528 OverloadingResult OverloadResult = 12529 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12530 12531 if (OverloadResult == OR_No_Viable_Function) { 12532 *CallExpr = ExprError(); 12533 return FRS_NoViableFunction; 12534 } 12535 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12536 Loc, nullptr, CandidateSet, &Best, 12537 OverloadResult, 12538 /*AllowTypoCorrection=*/false); 12539 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12540 *CallExpr = ExprError(); 12541 Diag(Range->getLocStart(), diag::note_in_for_range) 12542 << RangeLoc << BEF << Range->getType(); 12543 return FRS_DiagnosticIssued; 12544 } 12545 } 12546 return FRS_Success; 12547 } 12548 12549 12550 /// FixOverloadedFunctionReference - E is an expression that refers to 12551 /// a C++ overloaded function (possibly with some parentheses and 12552 /// perhaps a '&' around it). We have resolved the overloaded function 12553 /// to the function declaration Fn, so patch up the expression E to 12554 /// refer (possibly indirectly) to Fn. Returns the new expr. 12555 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12556 FunctionDecl *Fn) { 12557 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12558 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12559 Found, Fn); 12560 if (SubExpr == PE->getSubExpr()) 12561 return PE; 12562 12563 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12564 } 12565 12566 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12567 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12568 Found, Fn); 12569 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12570 SubExpr->getType()) && 12571 "Implicit cast type cannot be determined from overload"); 12572 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12573 if (SubExpr == ICE->getSubExpr()) 12574 return ICE; 12575 12576 return ImplicitCastExpr::Create(Context, ICE->getType(), 12577 ICE->getCastKind(), 12578 SubExpr, nullptr, 12579 ICE->getValueKind()); 12580 } 12581 12582 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12583 assert(UnOp->getOpcode() == UO_AddrOf && 12584 "Can only take the address of an overloaded function"); 12585 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12586 if (Method->isStatic()) { 12587 // Do nothing: static member functions aren't any different 12588 // from non-member functions. 12589 } else { 12590 // Fix the subexpression, which really has to be an 12591 // UnresolvedLookupExpr holding an overloaded member function 12592 // or template. 12593 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12594 Found, Fn); 12595 if (SubExpr == UnOp->getSubExpr()) 12596 return UnOp; 12597 12598 assert(isa<DeclRefExpr>(SubExpr) 12599 && "fixed to something other than a decl ref"); 12600 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12601 && "fixed to a member ref with no nested name qualifier"); 12602 12603 // We have taken the address of a pointer to member 12604 // function. Perform the computation here so that we get the 12605 // appropriate pointer to member type. 12606 QualType ClassType 12607 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12608 QualType MemPtrType 12609 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12610 12611 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12612 VK_RValue, OK_Ordinary, 12613 UnOp->getOperatorLoc()); 12614 } 12615 } 12616 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12617 Found, Fn); 12618 if (SubExpr == UnOp->getSubExpr()) 12619 return UnOp; 12620 12621 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12622 Context.getPointerType(SubExpr->getType()), 12623 VK_RValue, OK_Ordinary, 12624 UnOp->getOperatorLoc()); 12625 } 12626 12627 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12628 // FIXME: avoid copy. 12629 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12630 if (ULE->hasExplicitTemplateArgs()) { 12631 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12632 TemplateArgs = &TemplateArgsBuffer; 12633 } 12634 12635 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12636 ULE->getQualifierLoc(), 12637 ULE->getTemplateKeywordLoc(), 12638 Fn, 12639 /*enclosing*/ false, // FIXME? 12640 ULE->getNameLoc(), 12641 Fn->getType(), 12642 VK_LValue, 12643 Found.getDecl(), 12644 TemplateArgs); 12645 MarkDeclRefReferenced(DRE); 12646 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12647 return DRE; 12648 } 12649 12650 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12651 // FIXME: avoid copy. 12652 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12653 if (MemExpr->hasExplicitTemplateArgs()) { 12654 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12655 TemplateArgs = &TemplateArgsBuffer; 12656 } 12657 12658 Expr *Base; 12659 12660 // If we're filling in a static method where we used to have an 12661 // implicit member access, rewrite to a simple decl ref. 12662 if (MemExpr->isImplicitAccess()) { 12663 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12664 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12665 MemExpr->getQualifierLoc(), 12666 MemExpr->getTemplateKeywordLoc(), 12667 Fn, 12668 /*enclosing*/ false, 12669 MemExpr->getMemberLoc(), 12670 Fn->getType(), 12671 VK_LValue, 12672 Found.getDecl(), 12673 TemplateArgs); 12674 MarkDeclRefReferenced(DRE); 12675 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12676 return DRE; 12677 } else { 12678 SourceLocation Loc = MemExpr->getMemberLoc(); 12679 if (MemExpr->getQualifier()) 12680 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12681 CheckCXXThisCapture(Loc); 12682 Base = new (Context) CXXThisExpr(Loc, 12683 MemExpr->getBaseType(), 12684 /*isImplicit=*/true); 12685 } 12686 } else 12687 Base = MemExpr->getBase(); 12688 12689 ExprValueKind valueKind; 12690 QualType type; 12691 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12692 valueKind = VK_LValue; 12693 type = Fn->getType(); 12694 } else { 12695 valueKind = VK_RValue; 12696 type = Context.BoundMemberTy; 12697 } 12698 12699 MemberExpr *ME = MemberExpr::Create( 12700 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 12701 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 12702 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 12703 OK_Ordinary); 12704 ME->setHadMultipleCandidates(true); 12705 MarkMemberReferenced(ME); 12706 return ME; 12707 } 12708 12709 llvm_unreachable("Invalid reference to overloaded function"); 12710 } 12711 12712 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12713 DeclAccessPair Found, 12714 FunctionDecl *Fn) { 12715 return FixOverloadedFunctionReference(E.get(), Found, Fn); 12716 } 12717