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 }; 135 return Rank[(int)Kind]; 136 } 137 138 /// GetImplicitConversionName - Return the name of this kind of 139 /// implicit conversion. 140 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 141 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 142 "No conversion", 143 "Lvalue-to-rvalue", 144 "Array-to-pointer", 145 "Function-to-pointer", 146 "Noreturn adjustment", 147 "Qualification", 148 "Integral promotion", 149 "Floating point promotion", 150 "Complex promotion", 151 "Integral conversion", 152 "Floating conversion", 153 "Complex conversion", 154 "Floating-integral conversion", 155 "Pointer conversion", 156 "Pointer-to-member conversion", 157 "Boolean conversion", 158 "Compatible-types conversion", 159 "Derived-to-base conversion", 160 "Vector conversion", 161 "Vector splat", 162 "Complex-real conversion", 163 "Block Pointer conversion", 164 "Transparent Union Conversion", 165 "Writeback conversion" 166 }; 167 return Name[Kind]; 168 } 169 170 /// StandardConversionSequence - Set the standard conversion 171 /// sequence to the identity conversion. 172 void StandardConversionSequence::setAsIdentityConversion() { 173 First = ICK_Identity; 174 Second = ICK_Identity; 175 Third = ICK_Identity; 176 DeprecatedStringLiteralToCharPtr = false; 177 QualificationIncludesObjCLifetime = false; 178 ReferenceBinding = false; 179 DirectBinding = false; 180 IsLvalueReference = true; 181 BindsToFunctionLvalue = false; 182 BindsToRvalue = false; 183 BindsImplicitObjectArgumentWithoutRefQualifier = false; 184 ObjCLifetimeConversionBinding = false; 185 CopyConstructor = nullptr; 186 } 187 188 /// getRank - Retrieve the rank of this standard conversion sequence 189 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 190 /// implicit conversions. 191 ImplicitConversionRank StandardConversionSequence::getRank() const { 192 ImplicitConversionRank Rank = ICR_Exact_Match; 193 if (GetConversionRank(First) > Rank) 194 Rank = GetConversionRank(First); 195 if (GetConversionRank(Second) > Rank) 196 Rank = GetConversionRank(Second); 197 if (GetConversionRank(Third) > Rank) 198 Rank = GetConversionRank(Third); 199 return Rank; 200 } 201 202 /// isPointerConversionToBool - Determines whether this conversion is 203 /// a conversion of a pointer or pointer-to-member to bool. This is 204 /// used as part of the ranking of standard conversion sequences 205 /// (C++ 13.3.3.2p4). 206 bool StandardConversionSequence::isPointerConversionToBool() const { 207 // Note that FromType has not necessarily been transformed by the 208 // array-to-pointer or function-to-pointer implicit conversions, so 209 // check for their presence as well as checking whether FromType is 210 // a pointer. 211 if (getToType(1)->isBooleanType() && 212 (getFromType()->isPointerType() || 213 getFromType()->isObjCObjectPointerType() || 214 getFromType()->isBlockPointerType() || 215 getFromType()->isNullPtrType() || 216 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 217 return true; 218 219 return false; 220 } 221 222 /// isPointerConversionToVoidPointer - Determines whether this 223 /// conversion is a conversion of a pointer to a void pointer. This is 224 /// used as part of the ranking of standard conversion sequences (C++ 225 /// 13.3.3.2p4). 226 bool 227 StandardConversionSequence:: 228 isPointerConversionToVoidPointer(ASTContext& Context) const { 229 QualType FromType = getFromType(); 230 QualType ToType = getToType(1); 231 232 // Note that FromType has not necessarily been transformed by the 233 // array-to-pointer implicit conversion, so check for its presence 234 // and redo the conversion to get a pointer. 235 if (First == ICK_Array_To_Pointer) 236 FromType = Context.getArrayDecayedType(FromType); 237 238 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 239 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 240 return ToPtrType->getPointeeType()->isVoidType(); 241 242 return false; 243 } 244 245 /// Skip any implicit casts which could be either part of a narrowing conversion 246 /// or after one in an implicit conversion. 247 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 248 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 249 switch (ICE->getCastKind()) { 250 case CK_NoOp: 251 case CK_IntegralCast: 252 case CK_IntegralToBoolean: 253 case CK_IntegralToFloating: 254 case CK_FloatingToIntegral: 255 case CK_FloatingToBoolean: 256 case CK_FloatingCast: 257 Converted = ICE->getSubExpr(); 258 continue; 259 260 default: 261 return Converted; 262 } 263 } 264 265 return Converted; 266 } 267 268 /// Check if this standard conversion sequence represents a narrowing 269 /// conversion, according to C++11 [dcl.init.list]p7. 270 /// 271 /// \param Ctx The AST context. 272 /// \param Converted The result of applying this standard conversion sequence. 273 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 274 /// value of the expression prior to the narrowing conversion. 275 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 276 /// type of the expression prior to the narrowing conversion. 277 NarrowingKind 278 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 279 const Expr *Converted, 280 APValue &ConstantValue, 281 QualType &ConstantType) const { 282 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 283 284 // C++11 [dcl.init.list]p7: 285 // A narrowing conversion is an implicit conversion ... 286 QualType FromType = getToType(0); 287 QualType ToType = getToType(1); 288 switch (Second) { 289 // 'bool' is an integral type; dispatch to the right place to handle it. 290 case ICK_Boolean_Conversion: 291 if (FromType->isRealFloatingType()) 292 goto FloatingIntegralConversion; 293 if (FromType->isIntegralOrUnscopedEnumerationType()) 294 goto IntegralConversion; 295 // Boolean conversions can be from pointers and pointers to members 296 // [conv.bool], and those aren't considered narrowing conversions. 297 return NK_Not_Narrowing; 298 299 // -- from a floating-point type to an integer type, or 300 // 301 // -- from an integer type or unscoped enumeration type to a floating-point 302 // type, except where the source is a constant expression and the actual 303 // value after conversion will fit into the target type and will produce 304 // the original value when converted back to the original type, or 305 case ICK_Floating_Integral: 306 FloatingIntegralConversion: 307 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 308 return NK_Type_Narrowing; 309 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 310 llvm::APSInt IntConstantValue; 311 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 312 if (Initializer && 313 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 314 // Convert the integer to the floating type. 315 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 316 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 317 llvm::APFloat::rmNearestTiesToEven); 318 // And back. 319 llvm::APSInt ConvertedValue = IntConstantValue; 320 bool ignored; 321 Result.convertToInteger(ConvertedValue, 322 llvm::APFloat::rmTowardZero, &ignored); 323 // If the resulting value is different, this was a narrowing conversion. 324 if (IntConstantValue != ConvertedValue) { 325 ConstantValue = APValue(IntConstantValue); 326 ConstantType = Initializer->getType(); 327 return NK_Constant_Narrowing; 328 } 329 } else { 330 // Variables are always narrowings. 331 return NK_Variable_Narrowing; 332 } 333 } 334 return NK_Not_Narrowing; 335 336 // -- from long double to double or float, or from double to float, except 337 // where the source is a constant expression and the actual value after 338 // conversion is within the range of values that can be represented (even 339 // if it cannot be represented exactly), or 340 case ICK_Floating_Conversion: 341 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 342 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 343 // FromType is larger than ToType. 344 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 345 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 346 // Constant! 347 assert(ConstantValue.isFloat()); 348 llvm::APFloat FloatVal = ConstantValue.getFloat(); 349 // Convert the source value into the target type. 350 bool ignored; 351 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 352 Ctx.getFloatTypeSemantics(ToType), 353 llvm::APFloat::rmNearestTiesToEven, &ignored); 354 // If there was no overflow, the source value is within the range of 355 // values that can be represented. 356 if (ConvertStatus & llvm::APFloat::opOverflow) { 357 ConstantType = Initializer->getType(); 358 return NK_Constant_Narrowing; 359 } 360 } else { 361 return NK_Variable_Narrowing; 362 } 363 } 364 return NK_Not_Narrowing; 365 366 // -- from an integer type or unscoped enumeration type to an integer type 367 // that cannot represent all the values of the original type, except where 368 // the source is a constant expression and the actual value after 369 // conversion will fit into the target type and will produce the original 370 // value when converted back to the original type. 371 case ICK_Integral_Conversion: 372 IntegralConversion: { 373 assert(FromType->isIntegralOrUnscopedEnumerationType()); 374 assert(ToType->isIntegralOrUnscopedEnumerationType()); 375 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 376 const unsigned FromWidth = Ctx.getIntWidth(FromType); 377 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 378 const unsigned ToWidth = Ctx.getIntWidth(ToType); 379 380 if (FromWidth > ToWidth || 381 (FromWidth == ToWidth && FromSigned != ToSigned) || 382 (FromSigned && !ToSigned)) { 383 // Not all values of FromType can be represented in ToType. 384 llvm::APSInt InitializerValue; 385 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 386 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 387 // Such conversions on variables are always narrowing. 388 return NK_Variable_Narrowing; 389 } 390 bool Narrowing = false; 391 if (FromWidth < ToWidth) { 392 // Negative -> unsigned is narrowing. Otherwise, more bits is never 393 // narrowing. 394 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 395 Narrowing = true; 396 } else { 397 // Add a bit to the InitializerValue so we don't have to worry about 398 // signed vs. unsigned comparisons. 399 InitializerValue = InitializerValue.extend( 400 InitializerValue.getBitWidth() + 1); 401 // Convert the initializer to and from the target width and signed-ness. 402 llvm::APSInt ConvertedValue = InitializerValue; 403 ConvertedValue = ConvertedValue.trunc(ToWidth); 404 ConvertedValue.setIsSigned(ToSigned); 405 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 406 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 407 // If the result is different, this was a narrowing conversion. 408 if (ConvertedValue != InitializerValue) 409 Narrowing = true; 410 } 411 if (Narrowing) { 412 ConstantType = Initializer->getType(); 413 ConstantValue = APValue(InitializerValue); 414 return NK_Constant_Narrowing; 415 } 416 } 417 return NK_Not_Narrowing; 418 } 419 420 default: 421 // Other kinds of conversions are not narrowings. 422 return NK_Not_Narrowing; 423 } 424 } 425 426 /// dump - Print this standard conversion sequence to standard 427 /// error. Useful for debugging overloading issues. 428 void StandardConversionSequence::dump() const { 429 raw_ostream &OS = llvm::errs(); 430 bool PrintedSomething = false; 431 if (First != ICK_Identity) { 432 OS << GetImplicitConversionName(First); 433 PrintedSomething = true; 434 } 435 436 if (Second != ICK_Identity) { 437 if (PrintedSomething) { 438 OS << " -> "; 439 } 440 OS << GetImplicitConversionName(Second); 441 442 if (CopyConstructor) { 443 OS << " (by copy constructor)"; 444 } else if (DirectBinding) { 445 OS << " (direct reference binding)"; 446 } else if (ReferenceBinding) { 447 OS << " (reference binding)"; 448 } 449 PrintedSomething = true; 450 } 451 452 if (Third != ICK_Identity) { 453 if (PrintedSomething) { 454 OS << " -> "; 455 } 456 OS << GetImplicitConversionName(Third); 457 PrintedSomething = true; 458 } 459 460 if (!PrintedSomething) { 461 OS << "No conversions required"; 462 } 463 } 464 465 /// dump - Print this user-defined conversion sequence to standard 466 /// error. Useful for debugging overloading issues. 467 void UserDefinedConversionSequence::dump() const { 468 raw_ostream &OS = llvm::errs(); 469 if (Before.First || Before.Second || Before.Third) { 470 Before.dump(); 471 OS << " -> "; 472 } 473 if (ConversionFunction) 474 OS << '\'' << *ConversionFunction << '\''; 475 else 476 OS << "aggregate initialization"; 477 if (After.First || After.Second || After.Third) { 478 OS << " -> "; 479 After.dump(); 480 } 481 } 482 483 /// dump - Print this implicit conversion sequence to standard 484 /// error. Useful for debugging overloading issues. 485 void ImplicitConversionSequence::dump() const { 486 raw_ostream &OS = llvm::errs(); 487 if (isStdInitializerListElement()) 488 OS << "Worst std::initializer_list element conversion: "; 489 switch (ConversionKind) { 490 case StandardConversion: 491 OS << "Standard conversion: "; 492 Standard.dump(); 493 break; 494 case UserDefinedConversion: 495 OS << "User-defined conversion: "; 496 UserDefined.dump(); 497 break; 498 case EllipsisConversion: 499 OS << "Ellipsis conversion"; 500 break; 501 case AmbiguousConversion: 502 OS << "Ambiguous conversion"; 503 break; 504 case BadConversion: 505 OS << "Bad conversion"; 506 break; 507 } 508 509 OS << "\n"; 510 } 511 512 void AmbiguousConversionSequence::construct() { 513 new (&conversions()) ConversionSet(); 514 } 515 516 void AmbiguousConversionSequence::destruct() { 517 conversions().~ConversionSet(); 518 } 519 520 void 521 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 522 FromTypePtr = O.FromTypePtr; 523 ToTypePtr = O.ToTypePtr; 524 new (&conversions()) ConversionSet(O.conversions()); 525 } 526 527 namespace { 528 // Structure used by DeductionFailureInfo to store 529 // template argument information. 530 struct DFIArguments { 531 TemplateArgument FirstArg; 532 TemplateArgument SecondArg; 533 }; 534 // Structure used by DeductionFailureInfo to store 535 // template parameter and template argument information. 536 struct DFIParamWithArguments : DFIArguments { 537 TemplateParameter Param; 538 }; 539 } 540 541 /// \brief Convert from Sema's representation of template deduction information 542 /// to the form used in overload-candidate information. 543 DeductionFailureInfo 544 clang::MakeDeductionFailureInfo(ASTContext &Context, 545 Sema::TemplateDeductionResult TDK, 546 TemplateDeductionInfo &Info) { 547 DeductionFailureInfo Result; 548 Result.Result = static_cast<unsigned>(TDK); 549 Result.HasDiagnostic = false; 550 Result.Data = nullptr; 551 switch (TDK) { 552 case Sema::TDK_Success: 553 case Sema::TDK_Invalid: 554 case Sema::TDK_InstantiationDepth: 555 case Sema::TDK_TooManyArguments: 556 case Sema::TDK_TooFewArguments: 557 break; 558 559 case Sema::TDK_Incomplete: 560 case Sema::TDK_InvalidExplicitArguments: 561 Result.Data = Info.Param.getOpaqueValue(); 562 break; 563 564 case Sema::TDK_NonDeducedMismatch: { 565 // FIXME: Should allocate from normal heap so that we can free this later. 566 DFIArguments *Saved = new (Context) DFIArguments; 567 Saved->FirstArg = Info.FirstArg; 568 Saved->SecondArg = Info.SecondArg; 569 Result.Data = Saved; 570 break; 571 } 572 573 case Sema::TDK_Inconsistent: 574 case Sema::TDK_Underqualified: { 575 // FIXME: Should allocate from normal heap so that we can free this later. 576 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 577 Saved->Param = Info.Param; 578 Saved->FirstArg = Info.FirstArg; 579 Saved->SecondArg = Info.SecondArg; 580 Result.Data = Saved; 581 break; 582 } 583 584 case Sema::TDK_SubstitutionFailure: 585 Result.Data = Info.take(); 586 if (Info.hasSFINAEDiagnostic()) { 587 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 588 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 589 Info.takeSFINAEDiagnostic(*Diag); 590 Result.HasDiagnostic = true; 591 } 592 break; 593 594 case Sema::TDK_FailedOverloadResolution: 595 Result.Data = Info.Expression; 596 break; 597 598 case Sema::TDK_MiscellaneousDeductionFailure: 599 break; 600 } 601 602 return Result; 603 } 604 605 void DeductionFailureInfo::Destroy() { 606 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 607 case Sema::TDK_Success: 608 case Sema::TDK_Invalid: 609 case Sema::TDK_InstantiationDepth: 610 case Sema::TDK_Incomplete: 611 case Sema::TDK_TooManyArguments: 612 case Sema::TDK_TooFewArguments: 613 case Sema::TDK_InvalidExplicitArguments: 614 case Sema::TDK_FailedOverloadResolution: 615 break; 616 617 case Sema::TDK_Inconsistent: 618 case Sema::TDK_Underqualified: 619 case Sema::TDK_NonDeducedMismatch: 620 // FIXME: Destroy the data? 621 Data = nullptr; 622 break; 623 624 case Sema::TDK_SubstitutionFailure: 625 // FIXME: Destroy the template argument list? 626 Data = nullptr; 627 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 628 Diag->~PartialDiagnosticAt(); 629 HasDiagnostic = false; 630 } 631 break; 632 633 // Unhandled 634 case Sema::TDK_MiscellaneousDeductionFailure: 635 break; 636 } 637 } 638 639 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 640 if (HasDiagnostic) 641 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 642 return nullptr; 643 } 644 645 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 646 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 647 case Sema::TDK_Success: 648 case Sema::TDK_Invalid: 649 case Sema::TDK_InstantiationDepth: 650 case Sema::TDK_TooManyArguments: 651 case Sema::TDK_TooFewArguments: 652 case Sema::TDK_SubstitutionFailure: 653 case Sema::TDK_NonDeducedMismatch: 654 case Sema::TDK_FailedOverloadResolution: 655 return TemplateParameter(); 656 657 case Sema::TDK_Incomplete: 658 case Sema::TDK_InvalidExplicitArguments: 659 return TemplateParameter::getFromOpaqueValue(Data); 660 661 case Sema::TDK_Inconsistent: 662 case Sema::TDK_Underqualified: 663 return static_cast<DFIParamWithArguments*>(Data)->Param; 664 665 // Unhandled 666 case Sema::TDK_MiscellaneousDeductionFailure: 667 break; 668 } 669 670 return TemplateParameter(); 671 } 672 673 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 674 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 675 case Sema::TDK_Success: 676 case Sema::TDK_Invalid: 677 case Sema::TDK_InstantiationDepth: 678 case Sema::TDK_TooManyArguments: 679 case Sema::TDK_TooFewArguments: 680 case Sema::TDK_Incomplete: 681 case Sema::TDK_InvalidExplicitArguments: 682 case Sema::TDK_Inconsistent: 683 case Sema::TDK_Underqualified: 684 case Sema::TDK_NonDeducedMismatch: 685 case Sema::TDK_FailedOverloadResolution: 686 return nullptr; 687 688 case Sema::TDK_SubstitutionFailure: 689 return static_cast<TemplateArgumentList*>(Data); 690 691 // Unhandled 692 case Sema::TDK_MiscellaneousDeductionFailure: 693 break; 694 } 695 696 return nullptr; 697 } 698 699 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 701 case Sema::TDK_Success: 702 case Sema::TDK_Invalid: 703 case Sema::TDK_InstantiationDepth: 704 case Sema::TDK_Incomplete: 705 case Sema::TDK_TooManyArguments: 706 case Sema::TDK_TooFewArguments: 707 case Sema::TDK_InvalidExplicitArguments: 708 case Sema::TDK_SubstitutionFailure: 709 case Sema::TDK_FailedOverloadResolution: 710 return nullptr; 711 712 case Sema::TDK_Inconsistent: 713 case Sema::TDK_Underqualified: 714 case Sema::TDK_NonDeducedMismatch: 715 return &static_cast<DFIArguments*>(Data)->FirstArg; 716 717 // Unhandled 718 case Sema::TDK_MiscellaneousDeductionFailure: 719 break; 720 } 721 722 return nullptr; 723 } 724 725 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 727 case Sema::TDK_Success: 728 case Sema::TDK_Invalid: 729 case Sema::TDK_InstantiationDepth: 730 case Sema::TDK_Incomplete: 731 case Sema::TDK_TooManyArguments: 732 case Sema::TDK_TooFewArguments: 733 case Sema::TDK_InvalidExplicitArguments: 734 case Sema::TDK_SubstitutionFailure: 735 case Sema::TDK_FailedOverloadResolution: 736 return nullptr; 737 738 case Sema::TDK_Inconsistent: 739 case Sema::TDK_Underqualified: 740 case Sema::TDK_NonDeducedMismatch: 741 return &static_cast<DFIArguments*>(Data)->SecondArg; 742 743 // Unhandled 744 case Sema::TDK_MiscellaneousDeductionFailure: 745 break; 746 } 747 748 return nullptr; 749 } 750 751 Expr *DeductionFailureInfo::getExpr() { 752 if (static_cast<Sema::TemplateDeductionResult>(Result) == 753 Sema::TDK_FailedOverloadResolution) 754 return static_cast<Expr*>(Data); 755 756 return nullptr; 757 } 758 759 void OverloadCandidateSet::destroyCandidates() { 760 for (iterator i = begin(), e = end(); i != e; ++i) { 761 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 762 i->Conversions[ii].~ImplicitConversionSequence(); 763 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 764 i->DeductionFailure.Destroy(); 765 } 766 } 767 768 void OverloadCandidateSet::clear() { 769 destroyCandidates(); 770 NumInlineSequences = 0; 771 Candidates.clear(); 772 Functions.clear(); 773 } 774 775 namespace { 776 class UnbridgedCastsSet { 777 struct Entry { 778 Expr **Addr; 779 Expr *Saved; 780 }; 781 SmallVector<Entry, 2> Entries; 782 783 public: 784 void save(Sema &S, Expr *&E) { 785 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 786 Entry entry = { &E, E }; 787 Entries.push_back(entry); 788 E = S.stripARCUnbridgedCast(E); 789 } 790 791 void restore() { 792 for (SmallVectorImpl<Entry>::iterator 793 i = Entries.begin(), e = Entries.end(); i != e; ++i) 794 *i->Addr = i->Saved; 795 } 796 }; 797 } 798 799 /// checkPlaceholderForOverload - Do any interesting placeholder-like 800 /// preprocessing on the given expression. 801 /// 802 /// \param unbridgedCasts a collection to which to add unbridged casts; 803 /// without this, they will be immediately diagnosed as errors 804 /// 805 /// Return true on unrecoverable error. 806 static bool 807 checkPlaceholderForOverload(Sema &S, Expr *&E, 808 UnbridgedCastsSet *unbridgedCasts = nullptr) { 809 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 810 // We can't handle overloaded expressions here because overload 811 // resolution might reasonably tweak them. 812 if (placeholder->getKind() == BuiltinType::Overload) return false; 813 814 // If the context potentially accepts unbridged ARC casts, strip 815 // the unbridged cast and add it to the collection for later restoration. 816 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 817 unbridgedCasts) { 818 unbridgedCasts->save(S, E); 819 return false; 820 } 821 822 // Go ahead and check everything else. 823 ExprResult result = S.CheckPlaceholderExpr(E); 824 if (result.isInvalid()) 825 return true; 826 827 E = result.get(); 828 return false; 829 } 830 831 // Nothing to do. 832 return false; 833 } 834 835 /// checkArgPlaceholdersForOverload - Check a set of call operands for 836 /// placeholders. 837 static bool checkArgPlaceholdersForOverload(Sema &S, 838 MultiExprArg Args, 839 UnbridgedCastsSet &unbridged) { 840 for (unsigned i = 0, e = Args.size(); i != e; ++i) 841 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 842 return true; 843 844 return false; 845 } 846 847 // IsOverload - Determine whether the given New declaration is an 848 // overload of the declarations in Old. This routine returns false if 849 // New and Old cannot be overloaded, e.g., if New has the same 850 // signature as some function in Old (C++ 1.3.10) or if the Old 851 // declarations aren't functions (or function templates) at all. When 852 // it does return false, MatchedDecl will point to the decl that New 853 // cannot be overloaded with. This decl may be a UsingShadowDecl on 854 // top of the underlying declaration. 855 // 856 // Example: Given the following input: 857 // 858 // void f(int, float); // #1 859 // void f(int, int); // #2 860 // int f(int, int); // #3 861 // 862 // When we process #1, there is no previous declaration of "f", 863 // so IsOverload will not be used. 864 // 865 // When we process #2, Old contains only the FunctionDecl for #1. By 866 // comparing the parameter types, we see that #1 and #2 are overloaded 867 // (since they have different signatures), so this routine returns 868 // false; MatchedDecl is unchanged. 869 // 870 // When we process #3, Old is an overload set containing #1 and #2. We 871 // compare the signatures of #3 to #1 (they're overloaded, so we do 872 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 873 // identical (return types of functions are not part of the 874 // signature), IsOverload returns false and MatchedDecl will be set to 875 // point to the FunctionDecl for #2. 876 // 877 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 878 // into a class by a using declaration. The rules for whether to hide 879 // shadow declarations ignore some properties which otherwise figure 880 // into a function template's signature. 881 Sema::OverloadKind 882 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 883 NamedDecl *&Match, bool NewIsUsingDecl) { 884 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 885 I != E; ++I) { 886 NamedDecl *OldD = *I; 887 888 bool OldIsUsingDecl = false; 889 if (isa<UsingShadowDecl>(OldD)) { 890 OldIsUsingDecl = true; 891 892 // We can always introduce two using declarations into the same 893 // context, even if they have identical signatures. 894 if (NewIsUsingDecl) continue; 895 896 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 897 } 898 899 // If either declaration was introduced by a using declaration, 900 // we'll need to use slightly different rules for matching. 901 // Essentially, these rules are the normal rules, except that 902 // function templates hide function templates with different 903 // return types or template parameter lists. 904 bool UseMemberUsingDeclRules = 905 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 906 !New->getFriendObjectKind(); 907 908 if (FunctionDecl *OldF = OldD->getAsFunction()) { 909 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 910 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 911 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 912 continue; 913 } 914 915 if (!isa<FunctionTemplateDecl>(OldD) && 916 !shouldLinkPossiblyHiddenDecl(*I, New)) 917 continue; 918 919 Match = *I; 920 return Ovl_Match; 921 } 922 } else if (isa<UsingDecl>(OldD)) { 923 // We can overload with these, which can show up when doing 924 // redeclaration checks for UsingDecls. 925 assert(Old.getLookupKind() == LookupUsingDeclName); 926 } else if (isa<TagDecl>(OldD)) { 927 // We can always overload with tags by hiding them. 928 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 929 // Optimistically assume that an unresolved using decl will 930 // overload; if it doesn't, we'll have to diagnose during 931 // template instantiation. 932 } else { 933 // (C++ 13p1): 934 // Only function declarations can be overloaded; object and type 935 // declarations cannot be overloaded. 936 Match = *I; 937 return Ovl_NonFunction; 938 } 939 } 940 941 return Ovl_Overload; 942 } 943 944 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 945 bool UseUsingDeclRules) { 946 // C++ [basic.start.main]p2: This function shall not be overloaded. 947 if (New->isMain()) 948 return false; 949 950 // MSVCRT user defined entry points cannot be overloaded. 951 if (New->isMSVCRTEntryPoint()) 952 return false; 953 954 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 955 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 956 957 // C++ [temp.fct]p2: 958 // A function template can be overloaded with other function templates 959 // and with normal (non-template) functions. 960 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 961 return true; 962 963 // Is the function New an overload of the function Old? 964 QualType OldQType = Context.getCanonicalType(Old->getType()); 965 QualType NewQType = Context.getCanonicalType(New->getType()); 966 967 // Compare the signatures (C++ 1.3.10) of the two functions to 968 // determine whether they are overloads. If we find any mismatch 969 // in the signature, they are overloads. 970 971 // If either of these functions is a K&R-style function (no 972 // prototype), then we consider them to have matching signatures. 973 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 974 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 975 return false; 976 977 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 978 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 979 980 // The signature of a function includes the types of its 981 // parameters (C++ 1.3.10), which includes the presence or absence 982 // of the ellipsis; see C++ DR 357). 983 if (OldQType != NewQType && 984 (OldType->getNumParams() != NewType->getNumParams() || 985 OldType->isVariadic() != NewType->isVariadic() || 986 !FunctionParamTypesAreEqual(OldType, NewType))) 987 return true; 988 989 // C++ [temp.over.link]p4: 990 // The signature of a function template consists of its function 991 // signature, its return type and its template parameter list. The names 992 // of the template parameters are significant only for establishing the 993 // relationship between the template parameters and the rest of the 994 // signature. 995 // 996 // We check the return type and template parameter lists for function 997 // templates first; the remaining checks follow. 998 // 999 // However, we don't consider either of these when deciding whether 1000 // a member introduced by a shadow declaration is hidden. 1001 if (!UseUsingDeclRules && NewTemplate && 1002 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1003 OldTemplate->getTemplateParameters(), 1004 false, TPL_TemplateMatch) || 1005 OldType->getReturnType() != NewType->getReturnType())) 1006 return true; 1007 1008 // If the function is a class member, its signature includes the 1009 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1010 // 1011 // As part of this, also check whether one of the member functions 1012 // is static, in which case they are not overloads (C++ 1013 // 13.1p2). While not part of the definition of the signature, 1014 // this check is important to determine whether these functions 1015 // can be overloaded. 1016 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1017 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1018 if (OldMethod && NewMethod && 1019 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1020 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1021 if (!UseUsingDeclRules && 1022 (OldMethod->getRefQualifier() == RQ_None || 1023 NewMethod->getRefQualifier() == RQ_None)) { 1024 // C++0x [over.load]p2: 1025 // - Member function declarations with the same name and the same 1026 // parameter-type-list as well as member function template 1027 // declarations with the same name, the same parameter-type-list, and 1028 // the same template parameter lists cannot be overloaded if any of 1029 // them, but not all, have a ref-qualifier (8.3.5). 1030 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1031 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1032 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1033 } 1034 return true; 1035 } 1036 1037 // We may not have applied the implicit const for a constexpr member 1038 // function yet (because we haven't yet resolved whether this is a static 1039 // or non-static member function). Add it now, on the assumption that this 1040 // is a redeclaration of OldMethod. 1041 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1042 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1043 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1044 !isa<CXXConstructorDecl>(NewMethod)) 1045 NewQuals |= Qualifiers::Const; 1046 1047 // We do not allow overloading based off of '__restrict'. 1048 OldQuals &= ~Qualifiers::Restrict; 1049 NewQuals &= ~Qualifiers::Restrict; 1050 if (OldQuals != NewQuals) 1051 return true; 1052 } 1053 1054 // enable_if attributes are an order-sensitive part of the signature. 1055 for (specific_attr_iterator<EnableIfAttr> 1056 NewI = New->specific_attr_begin<EnableIfAttr>(), 1057 NewE = New->specific_attr_end<EnableIfAttr>(), 1058 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1059 OldE = Old->specific_attr_end<EnableIfAttr>(); 1060 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1061 if (NewI == NewE || OldI == OldE) 1062 return true; 1063 llvm::FoldingSetNodeID NewID, OldID; 1064 NewI->getCond()->Profile(NewID, Context, true); 1065 OldI->getCond()->Profile(OldID, Context, true); 1066 if (NewID != OldID) 1067 return true; 1068 } 1069 1070 // The signatures match; this is not an overload. 1071 return false; 1072 } 1073 1074 /// \brief Checks availability of the function depending on the current 1075 /// function context. Inside an unavailable function, unavailability is ignored. 1076 /// 1077 /// \returns true if \arg FD is unavailable and current context is inside 1078 /// an available function, false otherwise. 1079 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1080 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1081 } 1082 1083 /// \brief Tries a user-defined conversion from From to ToType. 1084 /// 1085 /// Produces an implicit conversion sequence for when a standard conversion 1086 /// is not an option. See TryImplicitConversion for more information. 1087 static ImplicitConversionSequence 1088 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1089 bool SuppressUserConversions, 1090 bool AllowExplicit, 1091 bool InOverloadResolution, 1092 bool CStyle, 1093 bool AllowObjCWritebackConversion, 1094 bool AllowObjCConversionOnExplicit) { 1095 ImplicitConversionSequence ICS; 1096 1097 if (SuppressUserConversions) { 1098 // We're not in the case above, so there is no conversion that 1099 // we can perform. 1100 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1101 return ICS; 1102 } 1103 1104 // Attempt user-defined conversion. 1105 OverloadCandidateSet Conversions(From->getExprLoc(), 1106 OverloadCandidateSet::CSK_Normal); 1107 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1108 Conversions, AllowExplicit, 1109 AllowObjCConversionOnExplicit)) { 1110 case OR_Success: 1111 case OR_Deleted: 1112 ICS.setUserDefined(); 1113 ICS.UserDefined.Before.setAsIdentityConversion(); 1114 // C++ [over.ics.user]p4: 1115 // A conversion of an expression of class type to the same class 1116 // type is given Exact Match rank, and a conversion of an 1117 // expression of class type to a base class of that type is 1118 // given Conversion rank, in spite of the fact that a copy 1119 // constructor (i.e., a user-defined conversion function) is 1120 // called for those cases. 1121 if (CXXConstructorDecl *Constructor 1122 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1123 QualType FromCanon 1124 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1125 QualType ToCanon 1126 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1127 if (Constructor->isCopyConstructor() && 1128 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1129 // Turn this into a "standard" conversion sequence, so that it 1130 // gets ranked with standard conversion sequences. 1131 ICS.setStandard(); 1132 ICS.Standard.setAsIdentityConversion(); 1133 ICS.Standard.setFromType(From->getType()); 1134 ICS.Standard.setAllToTypes(ToType); 1135 ICS.Standard.CopyConstructor = Constructor; 1136 if (ToCanon != FromCanon) 1137 ICS.Standard.Second = ICK_Derived_To_Base; 1138 } 1139 } 1140 break; 1141 1142 case OR_Ambiguous: 1143 ICS.setAmbiguous(); 1144 ICS.Ambiguous.setFromType(From->getType()); 1145 ICS.Ambiguous.setToType(ToType); 1146 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1147 Cand != Conversions.end(); ++Cand) 1148 if (Cand->Viable) 1149 ICS.Ambiguous.addConversion(Cand->Function); 1150 break; 1151 1152 // Fall through. 1153 case OR_No_Viable_Function: 1154 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1155 break; 1156 } 1157 1158 return ICS; 1159 } 1160 1161 /// TryImplicitConversion - Attempt to perform an implicit conversion 1162 /// from the given expression (Expr) to the given type (ToType). This 1163 /// function returns an implicit conversion sequence that can be used 1164 /// to perform the initialization. Given 1165 /// 1166 /// void f(float f); 1167 /// void g(int i) { f(i); } 1168 /// 1169 /// this routine would produce an implicit conversion sequence to 1170 /// describe the initialization of f from i, which will be a standard 1171 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1172 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1173 // 1174 /// Note that this routine only determines how the conversion can be 1175 /// performed; it does not actually perform the conversion. As such, 1176 /// it will not produce any diagnostics if no conversion is available, 1177 /// but will instead return an implicit conversion sequence of kind 1178 /// "BadConversion". 1179 /// 1180 /// If @p SuppressUserConversions, then user-defined conversions are 1181 /// not permitted. 1182 /// If @p AllowExplicit, then explicit user-defined conversions are 1183 /// permitted. 1184 /// 1185 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1186 /// writeback conversion, which allows __autoreleasing id* parameters to 1187 /// be initialized with __strong id* or __weak id* arguments. 1188 static ImplicitConversionSequence 1189 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1190 bool SuppressUserConversions, 1191 bool AllowExplicit, 1192 bool InOverloadResolution, 1193 bool CStyle, 1194 bool AllowObjCWritebackConversion, 1195 bool AllowObjCConversionOnExplicit) { 1196 ImplicitConversionSequence ICS; 1197 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1198 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1199 ICS.setStandard(); 1200 return ICS; 1201 } 1202 1203 if (!S.getLangOpts().CPlusPlus) { 1204 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1205 return ICS; 1206 } 1207 1208 // C++ [over.ics.user]p4: 1209 // A conversion of an expression of class type to the same class 1210 // type is given Exact Match rank, and a conversion of an 1211 // expression of class type to a base class of that type is 1212 // given Conversion rank, in spite of the fact that a copy/move 1213 // constructor (i.e., a user-defined conversion function) is 1214 // called for those cases. 1215 QualType FromType = From->getType(); 1216 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1217 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1218 S.IsDerivedFrom(FromType, ToType))) { 1219 ICS.setStandard(); 1220 ICS.Standard.setAsIdentityConversion(); 1221 ICS.Standard.setFromType(FromType); 1222 ICS.Standard.setAllToTypes(ToType); 1223 1224 // We don't actually check at this point whether there is a valid 1225 // copy/move constructor, since overloading just assumes that it 1226 // exists. When we actually perform initialization, we'll find the 1227 // appropriate constructor to copy the returned object, if needed. 1228 ICS.Standard.CopyConstructor = nullptr; 1229 1230 // Determine whether this is considered a derived-to-base conversion. 1231 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1232 ICS.Standard.Second = ICK_Derived_To_Base; 1233 1234 return ICS; 1235 } 1236 1237 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1238 AllowExplicit, InOverloadResolution, CStyle, 1239 AllowObjCWritebackConversion, 1240 AllowObjCConversionOnExplicit); 1241 } 1242 1243 ImplicitConversionSequence 1244 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1245 bool SuppressUserConversions, 1246 bool AllowExplicit, 1247 bool InOverloadResolution, 1248 bool CStyle, 1249 bool AllowObjCWritebackConversion) { 1250 return ::TryImplicitConversion(*this, From, ToType, 1251 SuppressUserConversions, AllowExplicit, 1252 InOverloadResolution, CStyle, 1253 AllowObjCWritebackConversion, 1254 /*AllowObjCConversionOnExplicit=*/false); 1255 } 1256 1257 /// PerformImplicitConversion - Perform an implicit conversion of the 1258 /// expression From to the type ToType. Returns the 1259 /// converted expression. Flavor is the kind of conversion we're 1260 /// performing, used in the error message. If @p AllowExplicit, 1261 /// explicit user-defined conversions are permitted. 1262 ExprResult 1263 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1264 AssignmentAction Action, bool AllowExplicit) { 1265 ImplicitConversionSequence ICS; 1266 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1267 } 1268 1269 ExprResult 1270 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1271 AssignmentAction Action, bool AllowExplicit, 1272 ImplicitConversionSequence& ICS) { 1273 if (checkPlaceholderForOverload(*this, From)) 1274 return ExprError(); 1275 1276 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1277 bool AllowObjCWritebackConversion 1278 = getLangOpts().ObjCAutoRefCount && 1279 (Action == AA_Passing || Action == AA_Sending); 1280 if (getLangOpts().ObjC1) 1281 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1282 ToType, From->getType(), From); 1283 ICS = ::TryImplicitConversion(*this, From, ToType, 1284 /*SuppressUserConversions=*/false, 1285 AllowExplicit, 1286 /*InOverloadResolution=*/false, 1287 /*CStyle=*/false, 1288 AllowObjCWritebackConversion, 1289 /*AllowObjCConversionOnExplicit=*/false); 1290 return PerformImplicitConversion(From, ToType, ICS, Action); 1291 } 1292 1293 /// \brief Determine whether the conversion from FromType to ToType is a valid 1294 /// conversion that strips "noreturn" off the nested function type. 1295 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1296 QualType &ResultTy) { 1297 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1298 return false; 1299 1300 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1301 // where F adds one of the following at most once: 1302 // - a pointer 1303 // - a member pointer 1304 // - a block pointer 1305 CanQualType CanTo = Context.getCanonicalType(ToType); 1306 CanQualType CanFrom = Context.getCanonicalType(FromType); 1307 Type::TypeClass TyClass = CanTo->getTypeClass(); 1308 if (TyClass != CanFrom->getTypeClass()) return false; 1309 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1310 if (TyClass == Type::Pointer) { 1311 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1312 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1313 } else if (TyClass == Type::BlockPointer) { 1314 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1315 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1316 } else if (TyClass == Type::MemberPointer) { 1317 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1318 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1319 } else { 1320 return false; 1321 } 1322 1323 TyClass = CanTo->getTypeClass(); 1324 if (TyClass != CanFrom->getTypeClass()) return false; 1325 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1326 return false; 1327 } 1328 1329 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1330 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1331 if (!EInfo.getNoReturn()) return false; 1332 1333 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1334 assert(QualType(FromFn, 0).isCanonical()); 1335 if (QualType(FromFn, 0) != CanTo) return false; 1336 1337 ResultTy = ToType; 1338 return true; 1339 } 1340 1341 /// \brief Determine whether the conversion from FromType to ToType is a valid 1342 /// vector conversion. 1343 /// 1344 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1345 /// conversion. 1346 static bool IsVectorConversion(Sema &S, QualType FromType, 1347 QualType ToType, ImplicitConversionKind &ICK) { 1348 // We need at least one of these types to be a vector type to have a vector 1349 // conversion. 1350 if (!ToType->isVectorType() && !FromType->isVectorType()) 1351 return false; 1352 1353 // Identical types require no conversions. 1354 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1355 return false; 1356 1357 // There are no conversions between extended vector types, only identity. 1358 if (ToType->isExtVectorType()) { 1359 // There are no conversions between extended vector types other than the 1360 // identity conversion. 1361 if (FromType->isExtVectorType()) 1362 return false; 1363 1364 // Vector splat from any arithmetic type to a vector. 1365 if (FromType->isArithmeticType()) { 1366 ICK = ICK_Vector_Splat; 1367 return true; 1368 } 1369 } 1370 1371 // We can perform the conversion between vector types in the following cases: 1372 // 1)vector types are equivalent AltiVec and GCC vector types 1373 // 2)lax vector conversions are permitted and the vector types are of the 1374 // same size 1375 if (ToType->isVectorType() && FromType->isVectorType()) { 1376 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1377 S.isLaxVectorConversion(FromType, ToType)) { 1378 ICK = ICK_Vector_Conversion; 1379 return true; 1380 } 1381 } 1382 1383 return false; 1384 } 1385 1386 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1387 bool InOverloadResolution, 1388 StandardConversionSequence &SCS, 1389 bool CStyle); 1390 1391 /// IsStandardConversion - Determines whether there is a standard 1392 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1393 /// expression From to the type ToType. Standard conversion sequences 1394 /// only consider non-class types; for conversions that involve class 1395 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1396 /// contain the standard conversion sequence required to perform this 1397 /// conversion and this routine will return true. Otherwise, this 1398 /// routine will return false and the value of SCS is unspecified. 1399 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1400 bool InOverloadResolution, 1401 StandardConversionSequence &SCS, 1402 bool CStyle, 1403 bool AllowObjCWritebackConversion) { 1404 QualType FromType = From->getType(); 1405 1406 // Standard conversions (C++ [conv]) 1407 SCS.setAsIdentityConversion(); 1408 SCS.IncompatibleObjC = false; 1409 SCS.setFromType(FromType); 1410 SCS.CopyConstructor = nullptr; 1411 1412 // There are no standard conversions for class types in C++, so 1413 // abort early. When overloading in C, however, we do permit 1414 if (FromType->isRecordType() || ToType->isRecordType()) { 1415 if (S.getLangOpts().CPlusPlus) 1416 return false; 1417 1418 // When we're overloading in C, we allow, as standard conversions, 1419 } 1420 1421 // The first conversion can be an lvalue-to-rvalue conversion, 1422 // array-to-pointer conversion, or function-to-pointer conversion 1423 // (C++ 4p1). 1424 1425 if (FromType == S.Context.OverloadTy) { 1426 DeclAccessPair AccessPair; 1427 if (FunctionDecl *Fn 1428 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1429 AccessPair)) { 1430 // We were able to resolve the address of the overloaded function, 1431 // so we can convert to the type of that function. 1432 FromType = Fn->getType(); 1433 SCS.setFromType(FromType); 1434 1435 // we can sometimes resolve &foo<int> regardless of ToType, so check 1436 // if the type matches (identity) or we are converting to bool 1437 if (!S.Context.hasSameUnqualifiedType( 1438 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1439 QualType resultTy; 1440 // if the function type matches except for [[noreturn]], it's ok 1441 if (!S.IsNoReturnConversion(FromType, 1442 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1443 // otherwise, only a boolean conversion is standard 1444 if (!ToType->isBooleanType()) 1445 return false; 1446 } 1447 1448 // Check if the "from" expression is taking the address of an overloaded 1449 // function and recompute the FromType accordingly. Take advantage of the 1450 // fact that non-static member functions *must* have such an address-of 1451 // expression. 1452 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1453 if (Method && !Method->isStatic()) { 1454 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1455 "Non-unary operator on non-static member address"); 1456 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1457 == UO_AddrOf && 1458 "Non-address-of operator on non-static member address"); 1459 const Type *ClassType 1460 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1461 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1462 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1463 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1464 UO_AddrOf && 1465 "Non-address-of operator for overloaded function expression"); 1466 FromType = S.Context.getPointerType(FromType); 1467 } 1468 1469 // Check that we've computed the proper type after overload resolution. 1470 assert(S.Context.hasSameType( 1471 FromType, 1472 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1473 } else { 1474 return false; 1475 } 1476 } 1477 // Lvalue-to-rvalue conversion (C++11 4.1): 1478 // A glvalue (3.10) of a non-function, non-array type T can 1479 // be converted to a prvalue. 1480 bool argIsLValue = From->isGLValue(); 1481 if (argIsLValue && 1482 !FromType->isFunctionType() && !FromType->isArrayType() && 1483 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1484 SCS.First = ICK_Lvalue_To_Rvalue; 1485 1486 // C11 6.3.2.1p2: 1487 // ... if the lvalue has atomic type, the value has the non-atomic version 1488 // of the type of the lvalue ... 1489 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1490 FromType = Atomic->getValueType(); 1491 1492 // If T is a non-class type, the type of the rvalue is the 1493 // cv-unqualified version of T. Otherwise, the type of the rvalue 1494 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1495 // just strip the qualifiers because they don't matter. 1496 FromType = FromType.getUnqualifiedType(); 1497 } else if (FromType->isArrayType()) { 1498 // Array-to-pointer conversion (C++ 4.2) 1499 SCS.First = ICK_Array_To_Pointer; 1500 1501 // An lvalue or rvalue of type "array of N T" or "array of unknown 1502 // bound of T" can be converted to an rvalue of type "pointer to 1503 // T" (C++ 4.2p1). 1504 FromType = S.Context.getArrayDecayedType(FromType); 1505 1506 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1507 // This conversion is deprecated in C++03 (D.4) 1508 SCS.DeprecatedStringLiteralToCharPtr = true; 1509 1510 // For the purpose of ranking in overload resolution 1511 // (13.3.3.1.1), this conversion is considered an 1512 // array-to-pointer conversion followed by a qualification 1513 // conversion (4.4). (C++ 4.2p2) 1514 SCS.Second = ICK_Identity; 1515 SCS.Third = ICK_Qualification; 1516 SCS.QualificationIncludesObjCLifetime = false; 1517 SCS.setAllToTypes(FromType); 1518 return true; 1519 } 1520 } else if (FromType->isFunctionType() && argIsLValue) { 1521 // Function-to-pointer conversion (C++ 4.3). 1522 SCS.First = ICK_Function_To_Pointer; 1523 1524 // An lvalue of function type T can be converted to an rvalue of 1525 // type "pointer to T." The result is a pointer to the 1526 // function. (C++ 4.3p1). 1527 FromType = S.Context.getPointerType(FromType); 1528 } else { 1529 // We don't require any conversions for the first step. 1530 SCS.First = ICK_Identity; 1531 } 1532 SCS.setToType(0, FromType); 1533 1534 // The second conversion can be an integral promotion, floating 1535 // point promotion, integral conversion, floating point conversion, 1536 // floating-integral conversion, pointer conversion, 1537 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1538 // For overloading in C, this can also be a "compatible-type" 1539 // conversion. 1540 bool IncompatibleObjC = false; 1541 ImplicitConversionKind SecondICK = ICK_Identity; 1542 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1543 // The unqualified versions of the types are the same: there's no 1544 // conversion to do. 1545 SCS.Second = ICK_Identity; 1546 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1547 // Integral promotion (C++ 4.5). 1548 SCS.Second = ICK_Integral_Promotion; 1549 FromType = ToType.getUnqualifiedType(); 1550 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1551 // Floating point promotion (C++ 4.6). 1552 SCS.Second = ICK_Floating_Promotion; 1553 FromType = ToType.getUnqualifiedType(); 1554 } else if (S.IsComplexPromotion(FromType, ToType)) { 1555 // Complex promotion (Clang extension) 1556 SCS.Second = ICK_Complex_Promotion; 1557 FromType = ToType.getUnqualifiedType(); 1558 } else if (ToType->isBooleanType() && 1559 (FromType->isArithmeticType() || 1560 FromType->isAnyPointerType() || 1561 FromType->isBlockPointerType() || 1562 FromType->isMemberPointerType() || 1563 FromType->isNullPtrType())) { 1564 // Boolean conversions (C++ 4.12). 1565 SCS.Second = ICK_Boolean_Conversion; 1566 FromType = S.Context.BoolTy; 1567 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1568 ToType->isIntegralType(S.Context)) { 1569 // Integral conversions (C++ 4.7). 1570 SCS.Second = ICK_Integral_Conversion; 1571 FromType = ToType.getUnqualifiedType(); 1572 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1573 // Complex conversions (C99 6.3.1.6) 1574 SCS.Second = ICK_Complex_Conversion; 1575 FromType = ToType.getUnqualifiedType(); 1576 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1577 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1578 // Complex-real conversions (C99 6.3.1.7) 1579 SCS.Second = ICK_Complex_Real; 1580 FromType = ToType.getUnqualifiedType(); 1581 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1582 // Floating point conversions (C++ 4.8). 1583 SCS.Second = ICK_Floating_Conversion; 1584 FromType = ToType.getUnqualifiedType(); 1585 } else if ((FromType->isRealFloatingType() && 1586 ToType->isIntegralType(S.Context)) || 1587 (FromType->isIntegralOrUnscopedEnumerationType() && 1588 ToType->isRealFloatingType())) { 1589 // Floating-integral conversions (C++ 4.9). 1590 SCS.Second = ICK_Floating_Integral; 1591 FromType = ToType.getUnqualifiedType(); 1592 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1593 SCS.Second = ICK_Block_Pointer_Conversion; 1594 } else if (AllowObjCWritebackConversion && 1595 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1596 SCS.Second = ICK_Writeback_Conversion; 1597 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1598 FromType, IncompatibleObjC)) { 1599 // Pointer conversions (C++ 4.10). 1600 SCS.Second = ICK_Pointer_Conversion; 1601 SCS.IncompatibleObjC = IncompatibleObjC; 1602 FromType = FromType.getUnqualifiedType(); 1603 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1604 InOverloadResolution, FromType)) { 1605 // Pointer to member conversions (4.11). 1606 SCS.Second = ICK_Pointer_Member; 1607 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1608 SCS.Second = SecondICK; 1609 FromType = ToType.getUnqualifiedType(); 1610 } else if (!S.getLangOpts().CPlusPlus && 1611 S.Context.typesAreCompatible(ToType, FromType)) { 1612 // Compatible conversions (Clang extension for C function overloading) 1613 SCS.Second = ICK_Compatible_Conversion; 1614 FromType = ToType.getUnqualifiedType(); 1615 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1616 // Treat a conversion that strips "noreturn" as an identity conversion. 1617 SCS.Second = ICK_NoReturn_Adjustment; 1618 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1619 InOverloadResolution, 1620 SCS, CStyle)) { 1621 SCS.Second = ICK_TransparentUnionConversion; 1622 FromType = ToType; 1623 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1624 CStyle)) { 1625 // tryAtomicConversion has updated the standard conversion sequence 1626 // appropriately. 1627 return true; 1628 } else if (ToType->isEventT() && 1629 From->isIntegerConstantExpr(S.getASTContext()) && 1630 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1631 SCS.Second = ICK_Zero_Event_Conversion; 1632 FromType = ToType; 1633 } else { 1634 // No second conversion required. 1635 SCS.Second = ICK_Identity; 1636 } 1637 SCS.setToType(1, FromType); 1638 1639 QualType CanonFrom; 1640 QualType CanonTo; 1641 // The third conversion can be a qualification conversion (C++ 4p1). 1642 bool ObjCLifetimeConversion; 1643 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1644 ObjCLifetimeConversion)) { 1645 SCS.Third = ICK_Qualification; 1646 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1647 FromType = ToType; 1648 CanonFrom = S.Context.getCanonicalType(FromType); 1649 CanonTo = S.Context.getCanonicalType(ToType); 1650 } else { 1651 // No conversion required 1652 SCS.Third = ICK_Identity; 1653 1654 // C++ [over.best.ics]p6: 1655 // [...] Any difference in top-level cv-qualification is 1656 // subsumed by the initialization itself and does not constitute 1657 // a conversion. [...] 1658 CanonFrom = S.Context.getCanonicalType(FromType); 1659 CanonTo = S.Context.getCanonicalType(ToType); 1660 if (CanonFrom.getLocalUnqualifiedType() 1661 == CanonTo.getLocalUnqualifiedType() && 1662 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1663 FromType = ToType; 1664 CanonFrom = CanonTo; 1665 } 1666 } 1667 SCS.setToType(2, FromType); 1668 1669 // If we have not converted the argument type to the parameter type, 1670 // this is a bad conversion sequence. 1671 if (CanonFrom != CanonTo) 1672 return false; 1673 1674 return true; 1675 } 1676 1677 static bool 1678 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1679 QualType &ToType, 1680 bool InOverloadResolution, 1681 StandardConversionSequence &SCS, 1682 bool CStyle) { 1683 1684 const RecordType *UT = ToType->getAsUnionType(); 1685 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1686 return false; 1687 // The field to initialize within the transparent union. 1688 RecordDecl *UD = UT->getDecl(); 1689 // It's compatible if the expression matches any of the fields. 1690 for (const auto *it : UD->fields()) { 1691 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1692 CStyle, /*ObjCWritebackConversion=*/false)) { 1693 ToType = it->getType(); 1694 return true; 1695 } 1696 } 1697 return false; 1698 } 1699 1700 /// IsIntegralPromotion - Determines whether the conversion from the 1701 /// expression From (whose potentially-adjusted type is FromType) to 1702 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1703 /// sets PromotedType to the promoted type. 1704 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1705 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1706 // All integers are built-in. 1707 if (!To) { 1708 return false; 1709 } 1710 1711 // An rvalue of type char, signed char, unsigned char, short int, or 1712 // unsigned short int can be converted to an rvalue of type int if 1713 // int can represent all the values of the source type; otherwise, 1714 // the source rvalue can be converted to an rvalue of type unsigned 1715 // int (C++ 4.5p1). 1716 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1717 !FromType->isEnumeralType()) { 1718 if (// We can promote any signed, promotable integer type to an int 1719 (FromType->isSignedIntegerType() || 1720 // We can promote any unsigned integer type whose size is 1721 // less than int to an int. 1722 (!FromType->isSignedIntegerType() && 1723 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1724 return To->getKind() == BuiltinType::Int; 1725 } 1726 1727 return To->getKind() == BuiltinType::UInt; 1728 } 1729 1730 // C++11 [conv.prom]p3: 1731 // A prvalue of an unscoped enumeration type whose underlying type is not 1732 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1733 // following types that can represent all the values of the enumeration 1734 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1735 // unsigned int, long int, unsigned long int, long long int, or unsigned 1736 // long long int. If none of the types in that list can represent all the 1737 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1738 // type can be converted to an rvalue a prvalue of the extended integer type 1739 // with lowest integer conversion rank (4.13) greater than the rank of long 1740 // long in which all the values of the enumeration can be represented. If 1741 // there are two such extended types, the signed one is chosen. 1742 // C++11 [conv.prom]p4: 1743 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1744 // can be converted to a prvalue of its underlying type. Moreover, if 1745 // integral promotion can be applied to its underlying type, a prvalue of an 1746 // unscoped enumeration type whose underlying type is fixed can also be 1747 // converted to a prvalue of the promoted underlying type. 1748 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1749 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1750 // provided for a scoped enumeration. 1751 if (FromEnumType->getDecl()->isScoped()) 1752 return false; 1753 1754 // We can perform an integral promotion to the underlying type of the enum, 1755 // even if that's not the promoted type. Note that the check for promoting 1756 // the underlying type is based on the type alone, and does not consider 1757 // the bitfield-ness of the actual source expression. 1758 if (FromEnumType->getDecl()->isFixed()) { 1759 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1760 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1761 IsIntegralPromotion(nullptr, Underlying, ToType); 1762 } 1763 1764 // We have already pre-calculated the promotion type, so this is trivial. 1765 if (ToType->isIntegerType() && 1766 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1767 return Context.hasSameUnqualifiedType( 1768 ToType, FromEnumType->getDecl()->getPromotionType()); 1769 } 1770 1771 // C++0x [conv.prom]p2: 1772 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1773 // to an rvalue a prvalue of the first of the following types that can 1774 // represent all the values of its underlying type: int, unsigned int, 1775 // long int, unsigned long int, long long int, or unsigned long long int. 1776 // If none of the types in that list can represent all the values of its 1777 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1778 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1779 // type. 1780 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1781 ToType->isIntegerType()) { 1782 // Determine whether the type we're converting from is signed or 1783 // unsigned. 1784 bool FromIsSigned = FromType->isSignedIntegerType(); 1785 uint64_t FromSize = Context.getTypeSize(FromType); 1786 1787 // The types we'll try to promote to, in the appropriate 1788 // order. Try each of these types. 1789 QualType PromoteTypes[6] = { 1790 Context.IntTy, Context.UnsignedIntTy, 1791 Context.LongTy, Context.UnsignedLongTy , 1792 Context.LongLongTy, Context.UnsignedLongLongTy 1793 }; 1794 for (int Idx = 0; Idx < 6; ++Idx) { 1795 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1796 if (FromSize < ToSize || 1797 (FromSize == ToSize && 1798 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1799 // We found the type that we can promote to. If this is the 1800 // type we wanted, we have a promotion. Otherwise, no 1801 // promotion. 1802 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1803 } 1804 } 1805 } 1806 1807 // An rvalue for an integral bit-field (9.6) can be converted to an 1808 // rvalue of type int if int can represent all the values of the 1809 // bit-field; otherwise, it can be converted to unsigned int if 1810 // unsigned int can represent all the values of the bit-field. If 1811 // the bit-field is larger yet, no integral promotion applies to 1812 // it. If the bit-field has an enumerated type, it is treated as any 1813 // other value of that type for promotion purposes (C++ 4.5p3). 1814 // FIXME: We should delay checking of bit-fields until we actually perform the 1815 // conversion. 1816 if (From) { 1817 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1818 llvm::APSInt BitWidth; 1819 if (FromType->isIntegralType(Context) && 1820 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1821 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1822 ToSize = Context.getTypeSize(ToType); 1823 1824 // Are we promoting to an int from a bitfield that fits in an int? 1825 if (BitWidth < ToSize || 1826 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1827 return To->getKind() == BuiltinType::Int; 1828 } 1829 1830 // Are we promoting to an unsigned int from an unsigned bitfield 1831 // that fits into an unsigned int? 1832 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1833 return To->getKind() == BuiltinType::UInt; 1834 } 1835 1836 return false; 1837 } 1838 } 1839 } 1840 1841 // An rvalue of type bool can be converted to an rvalue of type int, 1842 // with false becoming zero and true becoming one (C++ 4.5p4). 1843 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1844 return true; 1845 } 1846 1847 return false; 1848 } 1849 1850 /// IsFloatingPointPromotion - Determines whether the conversion from 1851 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1852 /// returns true and sets PromotedType to the promoted type. 1853 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1854 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1855 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1856 /// An rvalue of type float can be converted to an rvalue of type 1857 /// double. (C++ 4.6p1). 1858 if (FromBuiltin->getKind() == BuiltinType::Float && 1859 ToBuiltin->getKind() == BuiltinType::Double) 1860 return true; 1861 1862 // C99 6.3.1.5p1: 1863 // When a float is promoted to double or long double, or a 1864 // double is promoted to long double [...]. 1865 if (!getLangOpts().CPlusPlus && 1866 (FromBuiltin->getKind() == BuiltinType::Float || 1867 FromBuiltin->getKind() == BuiltinType::Double) && 1868 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1869 return true; 1870 1871 // Half can be promoted to float. 1872 if (!getLangOpts().NativeHalfType && 1873 FromBuiltin->getKind() == BuiltinType::Half && 1874 ToBuiltin->getKind() == BuiltinType::Float) 1875 return true; 1876 } 1877 1878 return false; 1879 } 1880 1881 /// \brief Determine if a conversion is a complex promotion. 1882 /// 1883 /// A complex promotion is defined as a complex -> complex conversion 1884 /// where the conversion between the underlying real types is a 1885 /// floating-point or integral promotion. 1886 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1887 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1888 if (!FromComplex) 1889 return false; 1890 1891 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1892 if (!ToComplex) 1893 return false; 1894 1895 return IsFloatingPointPromotion(FromComplex->getElementType(), 1896 ToComplex->getElementType()) || 1897 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 1898 ToComplex->getElementType()); 1899 } 1900 1901 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1902 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1903 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1904 /// if non-empty, will be a pointer to ToType that may or may not have 1905 /// the right set of qualifiers on its pointee. 1906 /// 1907 static QualType 1908 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1909 QualType ToPointee, QualType ToType, 1910 ASTContext &Context, 1911 bool StripObjCLifetime = false) { 1912 assert((FromPtr->getTypeClass() == Type::Pointer || 1913 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1914 "Invalid similarly-qualified pointer type"); 1915 1916 /// Conversions to 'id' subsume cv-qualifier conversions. 1917 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1918 return ToType.getUnqualifiedType(); 1919 1920 QualType CanonFromPointee 1921 = Context.getCanonicalType(FromPtr->getPointeeType()); 1922 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1923 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1924 1925 if (StripObjCLifetime) 1926 Quals.removeObjCLifetime(); 1927 1928 // Exact qualifier match -> return the pointer type we're converting to. 1929 if (CanonToPointee.getLocalQualifiers() == Quals) { 1930 // ToType is exactly what we need. Return it. 1931 if (!ToType.isNull()) 1932 return ToType.getUnqualifiedType(); 1933 1934 // Build a pointer to ToPointee. It has the right qualifiers 1935 // already. 1936 if (isa<ObjCObjectPointerType>(ToType)) 1937 return Context.getObjCObjectPointerType(ToPointee); 1938 return Context.getPointerType(ToPointee); 1939 } 1940 1941 // Just build a canonical type that has the right qualifiers. 1942 QualType QualifiedCanonToPointee 1943 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1944 1945 if (isa<ObjCObjectPointerType>(ToType)) 1946 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1947 return Context.getPointerType(QualifiedCanonToPointee); 1948 } 1949 1950 static bool isNullPointerConstantForConversion(Expr *Expr, 1951 bool InOverloadResolution, 1952 ASTContext &Context) { 1953 // Handle value-dependent integral null pointer constants correctly. 1954 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1955 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1956 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1957 return !InOverloadResolution; 1958 1959 return Expr->isNullPointerConstant(Context, 1960 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1961 : Expr::NPC_ValueDependentIsNull); 1962 } 1963 1964 /// IsPointerConversion - Determines whether the conversion of the 1965 /// expression From, which has the (possibly adjusted) type FromType, 1966 /// can be converted to the type ToType via a pointer conversion (C++ 1967 /// 4.10). If so, returns true and places the converted type (that 1968 /// might differ from ToType in its cv-qualifiers at some level) into 1969 /// ConvertedType. 1970 /// 1971 /// This routine also supports conversions to and from block pointers 1972 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 1973 /// pointers to interfaces. FIXME: Once we've determined the 1974 /// appropriate overloading rules for Objective-C, we may want to 1975 /// split the Objective-C checks into a different routine; however, 1976 /// GCC seems to consider all of these conversions to be pointer 1977 /// conversions, so for now they live here. IncompatibleObjC will be 1978 /// set if the conversion is an allowed Objective-C conversion that 1979 /// should result in a warning. 1980 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1981 bool InOverloadResolution, 1982 QualType& ConvertedType, 1983 bool &IncompatibleObjC) { 1984 IncompatibleObjC = false; 1985 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1986 IncompatibleObjC)) 1987 return true; 1988 1989 // Conversion from a null pointer constant to any Objective-C pointer type. 1990 if (ToType->isObjCObjectPointerType() && 1991 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1992 ConvertedType = ToType; 1993 return true; 1994 } 1995 1996 // Blocks: Block pointers can be converted to void*. 1997 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1998 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1999 ConvertedType = ToType; 2000 return true; 2001 } 2002 // Blocks: A null pointer constant can be converted to a block 2003 // pointer type. 2004 if (ToType->isBlockPointerType() && 2005 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2006 ConvertedType = ToType; 2007 return true; 2008 } 2009 2010 // If the left-hand-side is nullptr_t, the right side can be a null 2011 // pointer constant. 2012 if (ToType->isNullPtrType() && 2013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2014 ConvertedType = ToType; 2015 return true; 2016 } 2017 2018 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2019 if (!ToTypePtr) 2020 return false; 2021 2022 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2023 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2024 ConvertedType = ToType; 2025 return true; 2026 } 2027 2028 // Beyond this point, both types need to be pointers 2029 // , including objective-c pointers. 2030 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2031 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2032 !getLangOpts().ObjCAutoRefCount) { 2033 ConvertedType = BuildSimilarlyQualifiedPointerType( 2034 FromType->getAs<ObjCObjectPointerType>(), 2035 ToPointeeType, 2036 ToType, Context); 2037 return true; 2038 } 2039 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2040 if (!FromTypePtr) 2041 return false; 2042 2043 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2044 2045 // If the unqualified pointee types are the same, this can't be a 2046 // pointer conversion, so don't do all of the work below. 2047 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2048 return false; 2049 2050 // An rvalue of type "pointer to cv T," where T is an object type, 2051 // can be converted to an rvalue of type "pointer to cv void" (C++ 2052 // 4.10p2). 2053 if (FromPointeeType->isIncompleteOrObjectType() && 2054 ToPointeeType->isVoidType()) { 2055 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2056 ToPointeeType, 2057 ToType, Context, 2058 /*StripObjCLifetime=*/true); 2059 return true; 2060 } 2061 2062 // MSVC allows implicit function to void* type conversion. 2063 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2064 ToPointeeType->isVoidType()) { 2065 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2066 ToPointeeType, 2067 ToType, Context); 2068 return true; 2069 } 2070 2071 // When we're overloading in C, we allow a special kind of pointer 2072 // conversion for compatible-but-not-identical pointee types. 2073 if (!getLangOpts().CPlusPlus && 2074 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2075 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2076 ToPointeeType, 2077 ToType, Context); 2078 return true; 2079 } 2080 2081 // C++ [conv.ptr]p3: 2082 // 2083 // An rvalue of type "pointer to cv D," where D is a class type, 2084 // can be converted to an rvalue of type "pointer to cv B," where 2085 // B is a base class (clause 10) of D. If B is an inaccessible 2086 // (clause 11) or ambiguous (10.2) base class of D, a program that 2087 // necessitates this conversion is ill-formed. The result of the 2088 // conversion is a pointer to the base class sub-object of the 2089 // derived class object. The null pointer value is converted to 2090 // the null pointer value of the destination type. 2091 // 2092 // Note that we do not check for ambiguity or inaccessibility 2093 // here. That is handled by CheckPointerConversion. 2094 if (getLangOpts().CPlusPlus && 2095 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2096 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2097 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2098 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2100 ToPointeeType, 2101 ToType, Context); 2102 return true; 2103 } 2104 2105 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2106 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2107 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2108 ToPointeeType, 2109 ToType, Context); 2110 return true; 2111 } 2112 2113 return false; 2114 } 2115 2116 /// \brief Adopt the given qualifiers for the given type. 2117 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2118 Qualifiers TQs = T.getQualifiers(); 2119 2120 // Check whether qualifiers already match. 2121 if (TQs == Qs) 2122 return T; 2123 2124 if (Qs.compatiblyIncludes(TQs)) 2125 return Context.getQualifiedType(T, Qs); 2126 2127 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2128 } 2129 2130 /// isObjCPointerConversion - Determines whether this is an 2131 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2132 /// with the same arguments and return values. 2133 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2134 QualType& ConvertedType, 2135 bool &IncompatibleObjC) { 2136 if (!getLangOpts().ObjC1) 2137 return false; 2138 2139 // The set of qualifiers on the type we're converting from. 2140 Qualifiers FromQualifiers = FromType.getQualifiers(); 2141 2142 // First, we handle all conversions on ObjC object pointer types. 2143 const ObjCObjectPointerType* ToObjCPtr = 2144 ToType->getAs<ObjCObjectPointerType>(); 2145 const ObjCObjectPointerType *FromObjCPtr = 2146 FromType->getAs<ObjCObjectPointerType>(); 2147 2148 if (ToObjCPtr && FromObjCPtr) { 2149 // If the pointee types are the same (ignoring qualifications), 2150 // then this is not a pointer conversion. 2151 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2152 FromObjCPtr->getPointeeType())) 2153 return false; 2154 2155 // Conversion between Objective-C pointers. 2156 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2157 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2158 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2159 if (getLangOpts().CPlusPlus && LHS && RHS && 2160 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2161 FromObjCPtr->getPointeeType())) 2162 return false; 2163 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2164 ToObjCPtr->getPointeeType(), 2165 ToType, Context); 2166 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2167 return true; 2168 } 2169 2170 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2171 // Okay: this is some kind of implicit downcast of Objective-C 2172 // interfaces, which is permitted. However, we're going to 2173 // complain about it. 2174 IncompatibleObjC = true; 2175 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2176 ToObjCPtr->getPointeeType(), 2177 ToType, Context); 2178 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2179 return true; 2180 } 2181 } 2182 // Beyond this point, both types need to be C pointers or block pointers. 2183 QualType ToPointeeType; 2184 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2185 ToPointeeType = ToCPtr->getPointeeType(); 2186 else if (const BlockPointerType *ToBlockPtr = 2187 ToType->getAs<BlockPointerType>()) { 2188 // Objective C++: We're able to convert from a pointer to any object 2189 // to a block pointer type. 2190 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2191 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2192 return true; 2193 } 2194 ToPointeeType = ToBlockPtr->getPointeeType(); 2195 } 2196 else if (FromType->getAs<BlockPointerType>() && 2197 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2198 // Objective C++: We're able to convert from a block pointer type to a 2199 // pointer to any object. 2200 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2201 return true; 2202 } 2203 else 2204 return false; 2205 2206 QualType FromPointeeType; 2207 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2208 FromPointeeType = FromCPtr->getPointeeType(); 2209 else if (const BlockPointerType *FromBlockPtr = 2210 FromType->getAs<BlockPointerType>()) 2211 FromPointeeType = FromBlockPtr->getPointeeType(); 2212 else 2213 return false; 2214 2215 // If we have pointers to pointers, recursively check whether this 2216 // is an Objective-C conversion. 2217 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2218 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2219 IncompatibleObjC)) { 2220 // We always complain about this conversion. 2221 IncompatibleObjC = true; 2222 ConvertedType = Context.getPointerType(ConvertedType); 2223 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2224 return true; 2225 } 2226 // Allow conversion of pointee being objective-c pointer to another one; 2227 // as in I* to id. 2228 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2229 ToPointeeType->getAs<ObjCObjectPointerType>() && 2230 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2231 IncompatibleObjC)) { 2232 2233 ConvertedType = Context.getPointerType(ConvertedType); 2234 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2235 return true; 2236 } 2237 2238 // If we have pointers to functions or blocks, check whether the only 2239 // differences in the argument and result types are in Objective-C 2240 // pointer conversions. If so, we permit the conversion (but 2241 // complain about it). 2242 const FunctionProtoType *FromFunctionType 2243 = FromPointeeType->getAs<FunctionProtoType>(); 2244 const FunctionProtoType *ToFunctionType 2245 = ToPointeeType->getAs<FunctionProtoType>(); 2246 if (FromFunctionType && ToFunctionType) { 2247 // If the function types are exactly the same, this isn't an 2248 // Objective-C pointer conversion. 2249 if (Context.getCanonicalType(FromPointeeType) 2250 == Context.getCanonicalType(ToPointeeType)) 2251 return false; 2252 2253 // Perform the quick checks that will tell us whether these 2254 // function types are obviously different. 2255 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2256 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2257 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2258 return false; 2259 2260 bool HasObjCConversion = false; 2261 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2262 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2263 // Okay, the types match exactly. Nothing to do. 2264 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2265 ToFunctionType->getReturnType(), 2266 ConvertedType, IncompatibleObjC)) { 2267 // Okay, we have an Objective-C pointer conversion. 2268 HasObjCConversion = true; 2269 } else { 2270 // Function types are too different. Abort. 2271 return false; 2272 } 2273 2274 // Check argument types. 2275 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2276 ArgIdx != NumArgs; ++ArgIdx) { 2277 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2278 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2279 if (Context.getCanonicalType(FromArgType) 2280 == Context.getCanonicalType(ToArgType)) { 2281 // Okay, the types match exactly. Nothing to do. 2282 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2283 ConvertedType, IncompatibleObjC)) { 2284 // Okay, we have an Objective-C pointer conversion. 2285 HasObjCConversion = true; 2286 } else { 2287 // Argument types are too different. Abort. 2288 return false; 2289 } 2290 } 2291 2292 if (HasObjCConversion) { 2293 // We had an Objective-C conversion. Allow this pointer 2294 // conversion, but complain about it. 2295 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2296 IncompatibleObjC = true; 2297 return true; 2298 } 2299 } 2300 2301 return false; 2302 } 2303 2304 /// \brief Determine whether this is an Objective-C writeback conversion, 2305 /// used for parameter passing when performing automatic reference counting. 2306 /// 2307 /// \param FromType The type we're converting form. 2308 /// 2309 /// \param ToType The type we're converting to. 2310 /// 2311 /// \param ConvertedType The type that will be produced after applying 2312 /// this conversion. 2313 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2314 QualType &ConvertedType) { 2315 if (!getLangOpts().ObjCAutoRefCount || 2316 Context.hasSameUnqualifiedType(FromType, ToType)) 2317 return false; 2318 2319 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2320 QualType ToPointee; 2321 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2322 ToPointee = ToPointer->getPointeeType(); 2323 else 2324 return false; 2325 2326 Qualifiers ToQuals = ToPointee.getQualifiers(); 2327 if (!ToPointee->isObjCLifetimeType() || 2328 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2329 !ToQuals.withoutObjCLifetime().empty()) 2330 return false; 2331 2332 // Argument must be a pointer to __strong to __weak. 2333 QualType FromPointee; 2334 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2335 FromPointee = FromPointer->getPointeeType(); 2336 else 2337 return false; 2338 2339 Qualifiers FromQuals = FromPointee.getQualifiers(); 2340 if (!FromPointee->isObjCLifetimeType() || 2341 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2342 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2343 return false; 2344 2345 // Make sure that we have compatible qualifiers. 2346 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2347 if (!ToQuals.compatiblyIncludes(FromQuals)) 2348 return false; 2349 2350 // Remove qualifiers from the pointee type we're converting from; they 2351 // aren't used in the compatibility check belong, and we'll be adding back 2352 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2353 FromPointee = FromPointee.getUnqualifiedType(); 2354 2355 // The unqualified form of the pointee types must be compatible. 2356 ToPointee = ToPointee.getUnqualifiedType(); 2357 bool IncompatibleObjC; 2358 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2359 FromPointee = ToPointee; 2360 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2361 IncompatibleObjC)) 2362 return false; 2363 2364 /// \brief Construct the type we're converting to, which is a pointer to 2365 /// __autoreleasing pointee. 2366 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2367 ConvertedType = Context.getPointerType(FromPointee); 2368 return true; 2369 } 2370 2371 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2372 QualType& ConvertedType) { 2373 QualType ToPointeeType; 2374 if (const BlockPointerType *ToBlockPtr = 2375 ToType->getAs<BlockPointerType>()) 2376 ToPointeeType = ToBlockPtr->getPointeeType(); 2377 else 2378 return false; 2379 2380 QualType FromPointeeType; 2381 if (const BlockPointerType *FromBlockPtr = 2382 FromType->getAs<BlockPointerType>()) 2383 FromPointeeType = FromBlockPtr->getPointeeType(); 2384 else 2385 return false; 2386 // We have pointer to blocks, check whether the only 2387 // differences in the argument and result types are in Objective-C 2388 // pointer conversions. If so, we permit the conversion. 2389 2390 const FunctionProtoType *FromFunctionType 2391 = FromPointeeType->getAs<FunctionProtoType>(); 2392 const FunctionProtoType *ToFunctionType 2393 = ToPointeeType->getAs<FunctionProtoType>(); 2394 2395 if (!FromFunctionType || !ToFunctionType) 2396 return false; 2397 2398 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2399 return true; 2400 2401 // Perform the quick checks that will tell us whether these 2402 // function types are obviously different. 2403 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2404 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2405 return false; 2406 2407 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2408 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2409 if (FromEInfo != ToEInfo) 2410 return false; 2411 2412 bool IncompatibleObjC = false; 2413 if (Context.hasSameType(FromFunctionType->getReturnType(), 2414 ToFunctionType->getReturnType())) { 2415 // Okay, the types match exactly. Nothing to do. 2416 } else { 2417 QualType RHS = FromFunctionType->getReturnType(); 2418 QualType LHS = ToFunctionType->getReturnType(); 2419 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2420 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2421 LHS = LHS.getUnqualifiedType(); 2422 2423 if (Context.hasSameType(RHS,LHS)) { 2424 // OK exact match. 2425 } else if (isObjCPointerConversion(RHS, LHS, 2426 ConvertedType, IncompatibleObjC)) { 2427 if (IncompatibleObjC) 2428 return false; 2429 // Okay, we have an Objective-C pointer conversion. 2430 } 2431 else 2432 return false; 2433 } 2434 2435 // Check argument types. 2436 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2437 ArgIdx != NumArgs; ++ArgIdx) { 2438 IncompatibleObjC = false; 2439 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2440 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2441 if (Context.hasSameType(FromArgType, ToArgType)) { 2442 // Okay, the types match exactly. Nothing to do. 2443 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2444 ConvertedType, IncompatibleObjC)) { 2445 if (IncompatibleObjC) 2446 return false; 2447 // Okay, we have an Objective-C pointer conversion. 2448 } else 2449 // Argument types are too different. Abort. 2450 return false; 2451 } 2452 if (LangOpts.ObjCAutoRefCount && 2453 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2454 ToFunctionType)) 2455 return false; 2456 2457 ConvertedType = ToType; 2458 return true; 2459 } 2460 2461 enum { 2462 ft_default, 2463 ft_different_class, 2464 ft_parameter_arity, 2465 ft_parameter_mismatch, 2466 ft_return_type, 2467 ft_qualifer_mismatch 2468 }; 2469 2470 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2471 /// function types. Catches different number of parameter, mismatch in 2472 /// parameter types, and different return types. 2473 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2474 QualType FromType, QualType ToType) { 2475 // If either type is not valid, include no extra info. 2476 if (FromType.isNull() || ToType.isNull()) { 2477 PDiag << ft_default; 2478 return; 2479 } 2480 2481 // Get the function type from the pointers. 2482 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2483 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2484 *ToMember = ToType->getAs<MemberPointerType>(); 2485 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2486 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2487 << QualType(FromMember->getClass(), 0); 2488 return; 2489 } 2490 FromType = FromMember->getPointeeType(); 2491 ToType = ToMember->getPointeeType(); 2492 } 2493 2494 if (FromType->isPointerType()) 2495 FromType = FromType->getPointeeType(); 2496 if (ToType->isPointerType()) 2497 ToType = ToType->getPointeeType(); 2498 2499 // Remove references. 2500 FromType = FromType.getNonReferenceType(); 2501 ToType = ToType.getNonReferenceType(); 2502 2503 // Don't print extra info for non-specialized template functions. 2504 if (FromType->isInstantiationDependentType() && 2505 !FromType->getAs<TemplateSpecializationType>()) { 2506 PDiag << ft_default; 2507 return; 2508 } 2509 2510 // No extra info for same types. 2511 if (Context.hasSameType(FromType, ToType)) { 2512 PDiag << ft_default; 2513 return; 2514 } 2515 2516 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2517 *ToFunction = ToType->getAs<FunctionProtoType>(); 2518 2519 // Both types need to be function types. 2520 if (!FromFunction || !ToFunction) { 2521 PDiag << ft_default; 2522 return; 2523 } 2524 2525 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2526 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2527 << FromFunction->getNumParams(); 2528 return; 2529 } 2530 2531 // Handle different parameter types. 2532 unsigned ArgPos; 2533 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2534 PDiag << ft_parameter_mismatch << ArgPos + 1 2535 << ToFunction->getParamType(ArgPos) 2536 << FromFunction->getParamType(ArgPos); 2537 return; 2538 } 2539 2540 // Handle different return type. 2541 if (!Context.hasSameType(FromFunction->getReturnType(), 2542 ToFunction->getReturnType())) { 2543 PDiag << ft_return_type << ToFunction->getReturnType() 2544 << FromFunction->getReturnType(); 2545 return; 2546 } 2547 2548 unsigned FromQuals = FromFunction->getTypeQuals(), 2549 ToQuals = ToFunction->getTypeQuals(); 2550 if (FromQuals != ToQuals) { 2551 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2552 return; 2553 } 2554 2555 // Unable to find a difference, so add no extra info. 2556 PDiag << ft_default; 2557 } 2558 2559 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2560 /// for equality of their argument types. Caller has already checked that 2561 /// they have same number of arguments. If the parameters are different, 2562 /// ArgPos will have the parameter index of the first different parameter. 2563 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2564 const FunctionProtoType *NewType, 2565 unsigned *ArgPos) { 2566 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2567 N = NewType->param_type_begin(), 2568 E = OldType->param_type_end(); 2569 O && (O != E); ++O, ++N) { 2570 if (!Context.hasSameType(O->getUnqualifiedType(), 2571 N->getUnqualifiedType())) { 2572 if (ArgPos) 2573 *ArgPos = O - OldType->param_type_begin(); 2574 return false; 2575 } 2576 } 2577 return true; 2578 } 2579 2580 /// CheckPointerConversion - Check the pointer conversion from the 2581 /// expression From to the type ToType. This routine checks for 2582 /// ambiguous or inaccessible derived-to-base pointer 2583 /// conversions for which IsPointerConversion has already returned 2584 /// true. It returns true and produces a diagnostic if there was an 2585 /// error, or returns false otherwise. 2586 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2587 CastKind &Kind, 2588 CXXCastPath& BasePath, 2589 bool IgnoreBaseAccess) { 2590 QualType FromType = From->getType(); 2591 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2592 2593 Kind = CK_BitCast; 2594 2595 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2596 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2597 Expr::NPCK_ZeroExpression) { 2598 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2599 DiagRuntimeBehavior(From->getExprLoc(), From, 2600 PDiag(diag::warn_impcast_bool_to_null_pointer) 2601 << ToType << From->getSourceRange()); 2602 else if (!isUnevaluatedContext()) 2603 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2604 << ToType << From->getSourceRange(); 2605 } 2606 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2607 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2608 QualType FromPointeeType = FromPtrType->getPointeeType(), 2609 ToPointeeType = ToPtrType->getPointeeType(); 2610 2611 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2612 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2613 // We must have a derived-to-base conversion. Check an 2614 // ambiguous or inaccessible conversion. 2615 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2616 From->getExprLoc(), 2617 From->getSourceRange(), &BasePath, 2618 IgnoreBaseAccess)) 2619 return true; 2620 2621 // The conversion was successful. 2622 Kind = CK_DerivedToBase; 2623 } 2624 } 2625 } else if (const ObjCObjectPointerType *ToPtrType = 2626 ToType->getAs<ObjCObjectPointerType>()) { 2627 if (const ObjCObjectPointerType *FromPtrType = 2628 FromType->getAs<ObjCObjectPointerType>()) { 2629 // Objective-C++ conversions are always okay. 2630 // FIXME: We should have a different class of conversions for the 2631 // Objective-C++ implicit conversions. 2632 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2633 return false; 2634 } else if (FromType->isBlockPointerType()) { 2635 Kind = CK_BlockPointerToObjCPointerCast; 2636 } else { 2637 Kind = CK_CPointerToObjCPointerCast; 2638 } 2639 } else if (ToType->isBlockPointerType()) { 2640 if (!FromType->isBlockPointerType()) 2641 Kind = CK_AnyPointerToBlockPointerCast; 2642 } 2643 2644 // We shouldn't fall into this case unless it's valid for other 2645 // reasons. 2646 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2647 Kind = CK_NullToPointer; 2648 2649 return false; 2650 } 2651 2652 /// IsMemberPointerConversion - Determines whether the conversion of the 2653 /// expression From, which has the (possibly adjusted) type FromType, can be 2654 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2655 /// If so, returns true and places the converted type (that might differ from 2656 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2657 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2658 QualType ToType, 2659 bool InOverloadResolution, 2660 QualType &ConvertedType) { 2661 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2662 if (!ToTypePtr) 2663 return false; 2664 2665 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2666 if (From->isNullPointerConstant(Context, 2667 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2668 : Expr::NPC_ValueDependentIsNull)) { 2669 ConvertedType = ToType; 2670 return true; 2671 } 2672 2673 // Otherwise, both types have to be member pointers. 2674 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2675 if (!FromTypePtr) 2676 return false; 2677 2678 // A pointer to member of B can be converted to a pointer to member of D, 2679 // where D is derived from B (C++ 4.11p2). 2680 QualType FromClass(FromTypePtr->getClass(), 0); 2681 QualType ToClass(ToTypePtr->getClass(), 0); 2682 2683 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2684 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2685 IsDerivedFrom(ToClass, FromClass)) { 2686 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2687 ToClass.getTypePtr()); 2688 return true; 2689 } 2690 2691 return false; 2692 } 2693 2694 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2695 /// expression From to the type ToType. This routine checks for ambiguous or 2696 /// virtual or inaccessible base-to-derived member pointer conversions 2697 /// for which IsMemberPointerConversion has already returned true. It returns 2698 /// true and produces a diagnostic if there was an error, or returns false 2699 /// otherwise. 2700 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2701 CastKind &Kind, 2702 CXXCastPath &BasePath, 2703 bool IgnoreBaseAccess) { 2704 QualType FromType = From->getType(); 2705 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2706 if (!FromPtrType) { 2707 // This must be a null pointer to member pointer conversion 2708 assert(From->isNullPointerConstant(Context, 2709 Expr::NPC_ValueDependentIsNull) && 2710 "Expr must be null pointer constant!"); 2711 Kind = CK_NullToMemberPointer; 2712 return false; 2713 } 2714 2715 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2716 assert(ToPtrType && "No member pointer cast has a target type " 2717 "that is not a member pointer."); 2718 2719 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2720 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2721 2722 // FIXME: What about dependent types? 2723 assert(FromClass->isRecordType() && "Pointer into non-class."); 2724 assert(ToClass->isRecordType() && "Pointer into non-class."); 2725 2726 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2727 /*DetectVirtual=*/true); 2728 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2729 assert(DerivationOkay && 2730 "Should not have been called if derivation isn't OK."); 2731 (void)DerivationOkay; 2732 2733 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2734 getUnqualifiedType())) { 2735 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2736 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2737 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2738 return true; 2739 } 2740 2741 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2742 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2743 << FromClass << ToClass << QualType(VBase, 0) 2744 << From->getSourceRange(); 2745 return true; 2746 } 2747 2748 if (!IgnoreBaseAccess) 2749 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2750 Paths.front(), 2751 diag::err_downcast_from_inaccessible_base); 2752 2753 // Must be a base to derived member conversion. 2754 BuildBasePathArray(Paths, BasePath); 2755 Kind = CK_BaseToDerivedMemberPointer; 2756 return false; 2757 } 2758 2759 /// Determine whether the lifetime conversion between the two given 2760 /// qualifiers sets is nontrivial. 2761 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2762 Qualifiers ToQuals) { 2763 // Converting anything to const __unsafe_unretained is trivial. 2764 if (ToQuals.hasConst() && 2765 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2766 return false; 2767 2768 return true; 2769 } 2770 2771 /// IsQualificationConversion - Determines whether the conversion from 2772 /// an rvalue of type FromType to ToType is a qualification conversion 2773 /// (C++ 4.4). 2774 /// 2775 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2776 /// when the qualification conversion involves a change in the Objective-C 2777 /// object lifetime. 2778 bool 2779 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2780 bool CStyle, bool &ObjCLifetimeConversion) { 2781 FromType = Context.getCanonicalType(FromType); 2782 ToType = Context.getCanonicalType(ToType); 2783 ObjCLifetimeConversion = false; 2784 2785 // If FromType and ToType are the same type, this is not a 2786 // qualification conversion. 2787 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2788 return false; 2789 2790 // (C++ 4.4p4): 2791 // A conversion can add cv-qualifiers at levels other than the first 2792 // in multi-level pointers, subject to the following rules: [...] 2793 bool PreviousToQualsIncludeConst = true; 2794 bool UnwrappedAnyPointer = false; 2795 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2796 // Within each iteration of the loop, we check the qualifiers to 2797 // determine if this still looks like a qualification 2798 // conversion. Then, if all is well, we unwrap one more level of 2799 // pointers or pointers-to-members and do it all again 2800 // until there are no more pointers or pointers-to-members left to 2801 // unwrap. 2802 UnwrappedAnyPointer = true; 2803 2804 Qualifiers FromQuals = FromType.getQualifiers(); 2805 Qualifiers ToQuals = ToType.getQualifiers(); 2806 2807 // Objective-C ARC: 2808 // Check Objective-C lifetime conversions. 2809 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2810 UnwrappedAnyPointer) { 2811 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2812 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2813 ObjCLifetimeConversion = true; 2814 FromQuals.removeObjCLifetime(); 2815 ToQuals.removeObjCLifetime(); 2816 } else { 2817 // Qualification conversions cannot cast between different 2818 // Objective-C lifetime qualifiers. 2819 return false; 2820 } 2821 } 2822 2823 // Allow addition/removal of GC attributes but not changing GC attributes. 2824 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2825 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2826 FromQuals.removeObjCGCAttr(); 2827 ToQuals.removeObjCGCAttr(); 2828 } 2829 2830 // -- for every j > 0, if const is in cv 1,j then const is in cv 2831 // 2,j, and similarly for volatile. 2832 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2833 return false; 2834 2835 // -- if the cv 1,j and cv 2,j are different, then const is in 2836 // every cv for 0 < k < j. 2837 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2838 && !PreviousToQualsIncludeConst) 2839 return false; 2840 2841 // Keep track of whether all prior cv-qualifiers in the "to" type 2842 // include const. 2843 PreviousToQualsIncludeConst 2844 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2845 } 2846 2847 // We are left with FromType and ToType being the pointee types 2848 // after unwrapping the original FromType and ToType the same number 2849 // of types. If we unwrapped any pointers, and if FromType and 2850 // ToType have the same unqualified type (since we checked 2851 // qualifiers above), then this is a qualification conversion. 2852 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2853 } 2854 2855 /// \brief - Determine whether this is a conversion from a scalar type to an 2856 /// atomic type. 2857 /// 2858 /// If successful, updates \c SCS's second and third steps in the conversion 2859 /// sequence to finish the conversion. 2860 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2861 bool InOverloadResolution, 2862 StandardConversionSequence &SCS, 2863 bool CStyle) { 2864 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2865 if (!ToAtomic) 2866 return false; 2867 2868 StandardConversionSequence InnerSCS; 2869 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2870 InOverloadResolution, InnerSCS, 2871 CStyle, /*AllowObjCWritebackConversion=*/false)) 2872 return false; 2873 2874 SCS.Second = InnerSCS.Second; 2875 SCS.setToType(1, InnerSCS.getToType(1)); 2876 SCS.Third = InnerSCS.Third; 2877 SCS.QualificationIncludesObjCLifetime 2878 = InnerSCS.QualificationIncludesObjCLifetime; 2879 SCS.setToType(2, InnerSCS.getToType(2)); 2880 return true; 2881 } 2882 2883 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2884 CXXConstructorDecl *Constructor, 2885 QualType Type) { 2886 const FunctionProtoType *CtorType = 2887 Constructor->getType()->getAs<FunctionProtoType>(); 2888 if (CtorType->getNumParams() > 0) { 2889 QualType FirstArg = CtorType->getParamType(0); 2890 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2891 return true; 2892 } 2893 return false; 2894 } 2895 2896 static OverloadingResult 2897 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2898 CXXRecordDecl *To, 2899 UserDefinedConversionSequence &User, 2900 OverloadCandidateSet &CandidateSet, 2901 bool AllowExplicit) { 2902 DeclContext::lookup_result R = S.LookupConstructors(To); 2903 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2904 Con != ConEnd; ++Con) { 2905 NamedDecl *D = *Con; 2906 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2907 2908 // Find the constructor (which may be a template). 2909 CXXConstructorDecl *Constructor = nullptr; 2910 FunctionTemplateDecl *ConstructorTmpl 2911 = dyn_cast<FunctionTemplateDecl>(D); 2912 if (ConstructorTmpl) 2913 Constructor 2914 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2915 else 2916 Constructor = cast<CXXConstructorDecl>(D); 2917 2918 bool Usable = !Constructor->isInvalidDecl() && 2919 S.isInitListConstructor(Constructor) && 2920 (AllowExplicit || !Constructor->isExplicit()); 2921 if (Usable) { 2922 // If the first argument is (a reference to) the target type, 2923 // suppress conversions. 2924 bool SuppressUserConversions = 2925 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2926 if (ConstructorTmpl) 2927 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2928 /*ExplicitArgs*/ nullptr, 2929 From, CandidateSet, 2930 SuppressUserConversions); 2931 else 2932 S.AddOverloadCandidate(Constructor, FoundDecl, 2933 From, CandidateSet, 2934 SuppressUserConversions); 2935 } 2936 } 2937 2938 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2939 2940 OverloadCandidateSet::iterator Best; 2941 switch (auto Result = 2942 CandidateSet.BestViableFunction(S, From->getLocStart(), 2943 Best, true)) { 2944 case OR_Deleted: 2945 case OR_Success: { 2946 // Record the standard conversion we used and the conversion function. 2947 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2948 QualType ThisType = Constructor->getThisType(S.Context); 2949 // Initializer lists don't have conversions as such. 2950 User.Before.setAsIdentityConversion(); 2951 User.HadMultipleCandidates = HadMultipleCandidates; 2952 User.ConversionFunction = Constructor; 2953 User.FoundConversionFunction = Best->FoundDecl; 2954 User.After.setAsIdentityConversion(); 2955 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2956 User.After.setAllToTypes(ToType); 2957 return Result; 2958 } 2959 2960 case OR_No_Viable_Function: 2961 return OR_No_Viable_Function; 2962 case OR_Ambiguous: 2963 return OR_Ambiguous; 2964 } 2965 2966 llvm_unreachable("Invalid OverloadResult!"); 2967 } 2968 2969 /// Determines whether there is a user-defined conversion sequence 2970 /// (C++ [over.ics.user]) that converts expression From to the type 2971 /// ToType. If such a conversion exists, User will contain the 2972 /// user-defined conversion sequence that performs such a conversion 2973 /// and this routine will return true. Otherwise, this routine returns 2974 /// false and User is unspecified. 2975 /// 2976 /// \param AllowExplicit true if the conversion should consider C++0x 2977 /// "explicit" conversion functions as well as non-explicit conversion 2978 /// functions (C++0x [class.conv.fct]p2). 2979 /// 2980 /// \param AllowObjCConversionOnExplicit true if the conversion should 2981 /// allow an extra Objective-C pointer conversion on uses of explicit 2982 /// constructors. Requires \c AllowExplicit to also be set. 2983 static OverloadingResult 2984 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2985 UserDefinedConversionSequence &User, 2986 OverloadCandidateSet &CandidateSet, 2987 bool AllowExplicit, 2988 bool AllowObjCConversionOnExplicit) { 2989 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 2990 2991 // Whether we will only visit constructors. 2992 bool ConstructorsOnly = false; 2993 2994 // If the type we are conversion to is a class type, enumerate its 2995 // constructors. 2996 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2997 // C++ [over.match.ctor]p1: 2998 // When objects of class type are direct-initialized (8.5), or 2999 // copy-initialized from an expression of the same or a 3000 // derived class type (8.5), overload resolution selects the 3001 // constructor. [...] For copy-initialization, the candidate 3002 // functions are all the converting constructors (12.3.1) of 3003 // that class. The argument list is the expression-list within 3004 // the parentheses of the initializer. 3005 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3006 (From->getType()->getAs<RecordType>() && 3007 S.IsDerivedFrom(From->getType(), ToType))) 3008 ConstructorsOnly = true; 3009 3010 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3011 // RequireCompleteType may have returned true due to some invalid decl 3012 // during template instantiation, but ToType may be complete enough now 3013 // to try to recover. 3014 if (ToType->isIncompleteType()) { 3015 // We're not going to find any constructors. 3016 } else if (CXXRecordDecl *ToRecordDecl 3017 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3018 3019 Expr **Args = &From; 3020 unsigned NumArgs = 1; 3021 bool ListInitializing = false; 3022 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3023 // But first, see if there is an init-list-constructor that will work. 3024 OverloadingResult Result = IsInitializerListConstructorConversion( 3025 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3026 if (Result != OR_No_Viable_Function) 3027 return Result; 3028 // Never mind. 3029 CandidateSet.clear(); 3030 3031 // If we're list-initializing, we pass the individual elements as 3032 // arguments, not the entire list. 3033 Args = InitList->getInits(); 3034 NumArgs = InitList->getNumInits(); 3035 ListInitializing = true; 3036 } 3037 3038 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3039 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3040 Con != ConEnd; ++Con) { 3041 NamedDecl *D = *Con; 3042 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3043 3044 // Find the constructor (which may be a template). 3045 CXXConstructorDecl *Constructor = nullptr; 3046 FunctionTemplateDecl *ConstructorTmpl 3047 = dyn_cast<FunctionTemplateDecl>(D); 3048 if (ConstructorTmpl) 3049 Constructor 3050 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3051 else 3052 Constructor = cast<CXXConstructorDecl>(D); 3053 3054 bool Usable = !Constructor->isInvalidDecl(); 3055 if (ListInitializing) 3056 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3057 else 3058 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3059 if (Usable) { 3060 bool SuppressUserConversions = !ConstructorsOnly; 3061 if (SuppressUserConversions && ListInitializing) { 3062 SuppressUserConversions = false; 3063 if (NumArgs == 1) { 3064 // If the first argument is (a reference to) the target type, 3065 // suppress conversions. 3066 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3067 S.Context, Constructor, ToType); 3068 } 3069 } 3070 if (ConstructorTmpl) 3071 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3072 /*ExplicitArgs*/ nullptr, 3073 llvm::makeArrayRef(Args, NumArgs), 3074 CandidateSet, SuppressUserConversions); 3075 else 3076 // Allow one user-defined conversion when user specifies a 3077 // From->ToType conversion via an static cast (c-style, etc). 3078 S.AddOverloadCandidate(Constructor, FoundDecl, 3079 llvm::makeArrayRef(Args, NumArgs), 3080 CandidateSet, SuppressUserConversions); 3081 } 3082 } 3083 } 3084 } 3085 3086 // Enumerate conversion functions, if we're allowed to. 3087 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3088 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3089 // No conversion functions from incomplete types. 3090 } else if (const RecordType *FromRecordType 3091 = From->getType()->getAs<RecordType>()) { 3092 if (CXXRecordDecl *FromRecordDecl 3093 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3094 // Add all of the conversion functions as candidates. 3095 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3096 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3097 DeclAccessPair FoundDecl = I.getPair(); 3098 NamedDecl *D = FoundDecl.getDecl(); 3099 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3100 if (isa<UsingShadowDecl>(D)) 3101 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3102 3103 CXXConversionDecl *Conv; 3104 FunctionTemplateDecl *ConvTemplate; 3105 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3106 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3107 else 3108 Conv = cast<CXXConversionDecl>(D); 3109 3110 if (AllowExplicit || !Conv->isExplicit()) { 3111 if (ConvTemplate) 3112 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3113 ActingContext, From, ToType, 3114 CandidateSet, 3115 AllowObjCConversionOnExplicit); 3116 else 3117 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3118 From, ToType, CandidateSet, 3119 AllowObjCConversionOnExplicit); 3120 } 3121 } 3122 } 3123 } 3124 3125 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3126 3127 OverloadCandidateSet::iterator Best; 3128 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3129 Best, true)) { 3130 case OR_Success: 3131 case OR_Deleted: 3132 // Record the standard conversion we used and the conversion function. 3133 if (CXXConstructorDecl *Constructor 3134 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3135 // C++ [over.ics.user]p1: 3136 // If the user-defined conversion is specified by a 3137 // constructor (12.3.1), the initial standard conversion 3138 // sequence converts the source type to the type required by 3139 // the argument of the constructor. 3140 // 3141 QualType ThisType = Constructor->getThisType(S.Context); 3142 if (isa<InitListExpr>(From)) { 3143 // Initializer lists don't have conversions as such. 3144 User.Before.setAsIdentityConversion(); 3145 } else { 3146 if (Best->Conversions[0].isEllipsis()) 3147 User.EllipsisConversion = true; 3148 else { 3149 User.Before = Best->Conversions[0].Standard; 3150 User.EllipsisConversion = false; 3151 } 3152 } 3153 User.HadMultipleCandidates = HadMultipleCandidates; 3154 User.ConversionFunction = Constructor; 3155 User.FoundConversionFunction = Best->FoundDecl; 3156 User.After.setAsIdentityConversion(); 3157 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3158 User.After.setAllToTypes(ToType); 3159 return Result; 3160 } 3161 if (CXXConversionDecl *Conversion 3162 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3163 // C++ [over.ics.user]p1: 3164 // 3165 // [...] If the user-defined conversion is specified by a 3166 // conversion function (12.3.2), the initial standard 3167 // conversion sequence converts the source type to the 3168 // implicit object parameter of the conversion function. 3169 User.Before = Best->Conversions[0].Standard; 3170 User.HadMultipleCandidates = HadMultipleCandidates; 3171 User.ConversionFunction = Conversion; 3172 User.FoundConversionFunction = Best->FoundDecl; 3173 User.EllipsisConversion = false; 3174 3175 // C++ [over.ics.user]p2: 3176 // The second standard conversion sequence converts the 3177 // result of the user-defined conversion to the target type 3178 // for the sequence. Since an implicit conversion sequence 3179 // is an initialization, the special rules for 3180 // initialization by user-defined conversion apply when 3181 // selecting the best user-defined conversion for a 3182 // user-defined conversion sequence (see 13.3.3 and 3183 // 13.3.3.1). 3184 User.After = Best->FinalConversion; 3185 return Result; 3186 } 3187 llvm_unreachable("Not a constructor or conversion function?"); 3188 3189 case OR_No_Viable_Function: 3190 return OR_No_Viable_Function; 3191 3192 case OR_Ambiguous: 3193 return OR_Ambiguous; 3194 } 3195 3196 llvm_unreachable("Invalid OverloadResult!"); 3197 } 3198 3199 bool 3200 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3201 ImplicitConversionSequence ICS; 3202 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3203 OverloadCandidateSet::CSK_Normal); 3204 OverloadingResult OvResult = 3205 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3206 CandidateSet, false, false); 3207 if (OvResult == OR_Ambiguous) 3208 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3209 << From->getType() << ToType << From->getSourceRange(); 3210 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3211 if (!RequireCompleteType(From->getLocStart(), ToType, 3212 diag::err_typecheck_nonviable_condition_incomplete, 3213 From->getType(), From->getSourceRange())) 3214 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3215 << From->getType() << From->getSourceRange() << ToType; 3216 } else 3217 return false; 3218 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3219 return true; 3220 } 3221 3222 /// \brief Compare the user-defined conversion functions or constructors 3223 /// of two user-defined conversion sequences to determine whether any ordering 3224 /// is possible. 3225 static ImplicitConversionSequence::CompareKind 3226 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3227 FunctionDecl *Function2) { 3228 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3229 return ImplicitConversionSequence::Indistinguishable; 3230 3231 // Objective-C++: 3232 // If both conversion functions are implicitly-declared conversions from 3233 // a lambda closure type to a function pointer and a block pointer, 3234 // respectively, always prefer the conversion to a function pointer, 3235 // because the function pointer is more lightweight and is more likely 3236 // to keep code working. 3237 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3238 if (!Conv1) 3239 return ImplicitConversionSequence::Indistinguishable; 3240 3241 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3242 if (!Conv2) 3243 return ImplicitConversionSequence::Indistinguishable; 3244 3245 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3246 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3247 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3248 if (Block1 != Block2) 3249 return Block1 ? ImplicitConversionSequence::Worse 3250 : ImplicitConversionSequence::Better; 3251 } 3252 3253 return ImplicitConversionSequence::Indistinguishable; 3254 } 3255 3256 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3257 const ImplicitConversionSequence &ICS) { 3258 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3259 (ICS.isUserDefined() && 3260 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3261 } 3262 3263 /// CompareImplicitConversionSequences - Compare two implicit 3264 /// conversion sequences to determine whether one is better than the 3265 /// other or if they are indistinguishable (C++ 13.3.3.2). 3266 static ImplicitConversionSequence::CompareKind 3267 CompareImplicitConversionSequences(Sema &S, 3268 const ImplicitConversionSequence& ICS1, 3269 const ImplicitConversionSequence& ICS2) 3270 { 3271 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3272 // conversion sequences (as defined in 13.3.3.1) 3273 // -- a standard conversion sequence (13.3.3.1.1) is a better 3274 // conversion sequence than a user-defined conversion sequence or 3275 // an ellipsis conversion sequence, and 3276 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3277 // conversion sequence than an ellipsis conversion sequence 3278 // (13.3.3.1.3). 3279 // 3280 // C++0x [over.best.ics]p10: 3281 // For the purpose of ranking implicit conversion sequences as 3282 // described in 13.3.3.2, the ambiguous conversion sequence is 3283 // treated as a user-defined sequence that is indistinguishable 3284 // from any other user-defined conversion sequence. 3285 3286 // String literal to 'char *' conversion has been deprecated in C++03. It has 3287 // been removed from C++11. We still accept this conversion, if it happens at 3288 // the best viable function. Otherwise, this conversion is considered worse 3289 // than ellipsis conversion. Consider this as an extension; this is not in the 3290 // standard. For example: 3291 // 3292 // int &f(...); // #1 3293 // void f(char*); // #2 3294 // void g() { int &r = f("foo"); } 3295 // 3296 // In C++03, we pick #2 as the best viable function. 3297 // In C++11, we pick #1 as the best viable function, because ellipsis 3298 // conversion is better than string-literal to char* conversion (since there 3299 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3300 // convert arguments, #2 would be the best viable function in C++11. 3301 // If the best viable function has this conversion, a warning will be issued 3302 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3303 3304 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3305 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3306 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3307 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3308 ? ImplicitConversionSequence::Worse 3309 : ImplicitConversionSequence::Better; 3310 3311 if (ICS1.getKindRank() < ICS2.getKindRank()) 3312 return ImplicitConversionSequence::Better; 3313 if (ICS2.getKindRank() < ICS1.getKindRank()) 3314 return ImplicitConversionSequence::Worse; 3315 3316 // The following checks require both conversion sequences to be of 3317 // the same kind. 3318 if (ICS1.getKind() != ICS2.getKind()) 3319 return ImplicitConversionSequence::Indistinguishable; 3320 3321 ImplicitConversionSequence::CompareKind Result = 3322 ImplicitConversionSequence::Indistinguishable; 3323 3324 // Two implicit conversion sequences of the same form are 3325 // indistinguishable conversion sequences unless one of the 3326 // following rules apply: (C++ 13.3.3.2p3): 3327 3328 // List-initialization sequence L1 is a better conversion sequence than 3329 // list-initialization sequence L2 if: 3330 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3331 // if not that, 3332 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3333 // and N1 is smaller than N2., 3334 // even if one of the other rules in this paragraph would otherwise apply. 3335 if (!ICS1.isBad()) { 3336 if (ICS1.isStdInitializerListElement() && 3337 !ICS2.isStdInitializerListElement()) 3338 return ImplicitConversionSequence::Better; 3339 if (!ICS1.isStdInitializerListElement() && 3340 ICS2.isStdInitializerListElement()) 3341 return ImplicitConversionSequence::Worse; 3342 } 3343 3344 if (ICS1.isStandard()) 3345 // Standard conversion sequence S1 is a better conversion sequence than 3346 // standard conversion sequence S2 if [...] 3347 Result = CompareStandardConversionSequences(S, 3348 ICS1.Standard, ICS2.Standard); 3349 else if (ICS1.isUserDefined()) { 3350 // User-defined conversion sequence U1 is a better conversion 3351 // sequence than another user-defined conversion sequence U2 if 3352 // they contain the same user-defined conversion function or 3353 // constructor and if the second standard conversion sequence of 3354 // U1 is better than the second standard conversion sequence of 3355 // U2 (C++ 13.3.3.2p3). 3356 if (ICS1.UserDefined.ConversionFunction == 3357 ICS2.UserDefined.ConversionFunction) 3358 Result = CompareStandardConversionSequences(S, 3359 ICS1.UserDefined.After, 3360 ICS2.UserDefined.After); 3361 else 3362 Result = compareConversionFunctions(S, 3363 ICS1.UserDefined.ConversionFunction, 3364 ICS2.UserDefined.ConversionFunction); 3365 } 3366 3367 return Result; 3368 } 3369 3370 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3371 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3372 Qualifiers Quals; 3373 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3374 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3375 } 3376 3377 return Context.hasSameUnqualifiedType(T1, T2); 3378 } 3379 3380 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3381 // determine if one is a proper subset of the other. 3382 static ImplicitConversionSequence::CompareKind 3383 compareStandardConversionSubsets(ASTContext &Context, 3384 const StandardConversionSequence& SCS1, 3385 const StandardConversionSequence& SCS2) { 3386 ImplicitConversionSequence::CompareKind Result 3387 = ImplicitConversionSequence::Indistinguishable; 3388 3389 // the identity conversion sequence is considered to be a subsequence of 3390 // any non-identity conversion sequence 3391 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3392 return ImplicitConversionSequence::Better; 3393 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3394 return ImplicitConversionSequence::Worse; 3395 3396 if (SCS1.Second != SCS2.Second) { 3397 if (SCS1.Second == ICK_Identity) 3398 Result = ImplicitConversionSequence::Better; 3399 else if (SCS2.Second == ICK_Identity) 3400 Result = ImplicitConversionSequence::Worse; 3401 else 3402 return ImplicitConversionSequence::Indistinguishable; 3403 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3404 return ImplicitConversionSequence::Indistinguishable; 3405 3406 if (SCS1.Third == SCS2.Third) { 3407 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3408 : ImplicitConversionSequence::Indistinguishable; 3409 } 3410 3411 if (SCS1.Third == ICK_Identity) 3412 return Result == ImplicitConversionSequence::Worse 3413 ? ImplicitConversionSequence::Indistinguishable 3414 : ImplicitConversionSequence::Better; 3415 3416 if (SCS2.Third == ICK_Identity) 3417 return Result == ImplicitConversionSequence::Better 3418 ? ImplicitConversionSequence::Indistinguishable 3419 : ImplicitConversionSequence::Worse; 3420 3421 return ImplicitConversionSequence::Indistinguishable; 3422 } 3423 3424 /// \brief Determine whether one of the given reference bindings is better 3425 /// than the other based on what kind of bindings they are. 3426 static bool 3427 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3428 const StandardConversionSequence &SCS2) { 3429 // C++0x [over.ics.rank]p3b4: 3430 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3431 // implicit object parameter of a non-static member function declared 3432 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3433 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3434 // lvalue reference to a function lvalue and S2 binds an rvalue 3435 // reference*. 3436 // 3437 // FIXME: Rvalue references. We're going rogue with the above edits, 3438 // because the semantics in the current C++0x working paper (N3225 at the 3439 // time of this writing) break the standard definition of std::forward 3440 // and std::reference_wrapper when dealing with references to functions. 3441 // Proposed wording changes submitted to CWG for consideration. 3442 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3443 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3444 return false; 3445 3446 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3447 SCS2.IsLvalueReference) || 3448 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3449 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3450 } 3451 3452 /// CompareStandardConversionSequences - Compare two standard 3453 /// conversion sequences to determine whether one is better than the 3454 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3455 static ImplicitConversionSequence::CompareKind 3456 CompareStandardConversionSequences(Sema &S, 3457 const StandardConversionSequence& SCS1, 3458 const StandardConversionSequence& SCS2) 3459 { 3460 // Standard conversion sequence S1 is a better conversion sequence 3461 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3462 3463 // -- S1 is a proper subsequence of S2 (comparing the conversion 3464 // sequences in the canonical form defined by 13.3.3.1.1, 3465 // excluding any Lvalue Transformation; the identity conversion 3466 // sequence is considered to be a subsequence of any 3467 // non-identity conversion sequence) or, if not that, 3468 if (ImplicitConversionSequence::CompareKind CK 3469 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3470 return CK; 3471 3472 // -- the rank of S1 is better than the rank of S2 (by the rules 3473 // defined below), or, if not that, 3474 ImplicitConversionRank Rank1 = SCS1.getRank(); 3475 ImplicitConversionRank Rank2 = SCS2.getRank(); 3476 if (Rank1 < Rank2) 3477 return ImplicitConversionSequence::Better; 3478 else if (Rank2 < Rank1) 3479 return ImplicitConversionSequence::Worse; 3480 3481 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3482 // are indistinguishable unless one of the following rules 3483 // applies: 3484 3485 // A conversion that is not a conversion of a pointer, or 3486 // pointer to member, to bool is better than another conversion 3487 // that is such a conversion. 3488 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3489 return SCS2.isPointerConversionToBool() 3490 ? ImplicitConversionSequence::Better 3491 : ImplicitConversionSequence::Worse; 3492 3493 // C++ [over.ics.rank]p4b2: 3494 // 3495 // If class B is derived directly or indirectly from class A, 3496 // conversion of B* to A* is better than conversion of B* to 3497 // void*, and conversion of A* to void* is better than conversion 3498 // of B* to void*. 3499 bool SCS1ConvertsToVoid 3500 = SCS1.isPointerConversionToVoidPointer(S.Context); 3501 bool SCS2ConvertsToVoid 3502 = SCS2.isPointerConversionToVoidPointer(S.Context); 3503 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3504 // Exactly one of the conversion sequences is a conversion to 3505 // a void pointer; it's the worse conversion. 3506 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3507 : ImplicitConversionSequence::Worse; 3508 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3509 // Neither conversion sequence converts to a void pointer; compare 3510 // their derived-to-base conversions. 3511 if (ImplicitConversionSequence::CompareKind DerivedCK 3512 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3513 return DerivedCK; 3514 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3515 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3516 // Both conversion sequences are conversions to void 3517 // pointers. Compare the source types to determine if there's an 3518 // inheritance relationship in their sources. 3519 QualType FromType1 = SCS1.getFromType(); 3520 QualType FromType2 = SCS2.getFromType(); 3521 3522 // Adjust the types we're converting from via the array-to-pointer 3523 // conversion, if we need to. 3524 if (SCS1.First == ICK_Array_To_Pointer) 3525 FromType1 = S.Context.getArrayDecayedType(FromType1); 3526 if (SCS2.First == ICK_Array_To_Pointer) 3527 FromType2 = S.Context.getArrayDecayedType(FromType2); 3528 3529 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3530 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3531 3532 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3533 return ImplicitConversionSequence::Better; 3534 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3535 return ImplicitConversionSequence::Worse; 3536 3537 // Objective-C++: If one interface is more specific than the 3538 // other, it is the better one. 3539 const ObjCObjectPointerType* FromObjCPtr1 3540 = FromType1->getAs<ObjCObjectPointerType>(); 3541 const ObjCObjectPointerType* FromObjCPtr2 3542 = FromType2->getAs<ObjCObjectPointerType>(); 3543 if (FromObjCPtr1 && FromObjCPtr2) { 3544 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3545 FromObjCPtr2); 3546 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3547 FromObjCPtr1); 3548 if (AssignLeft != AssignRight) { 3549 return AssignLeft? ImplicitConversionSequence::Better 3550 : ImplicitConversionSequence::Worse; 3551 } 3552 } 3553 } 3554 3555 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3556 // bullet 3). 3557 if (ImplicitConversionSequence::CompareKind QualCK 3558 = CompareQualificationConversions(S, SCS1, SCS2)) 3559 return QualCK; 3560 3561 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3562 // Check for a better reference binding based on the kind of bindings. 3563 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3564 return ImplicitConversionSequence::Better; 3565 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3566 return ImplicitConversionSequence::Worse; 3567 3568 // C++ [over.ics.rank]p3b4: 3569 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3570 // which the references refer are the same type except for 3571 // top-level cv-qualifiers, and the type to which the reference 3572 // initialized by S2 refers is more cv-qualified than the type 3573 // to which the reference initialized by S1 refers. 3574 QualType T1 = SCS1.getToType(2); 3575 QualType T2 = SCS2.getToType(2); 3576 T1 = S.Context.getCanonicalType(T1); 3577 T2 = S.Context.getCanonicalType(T2); 3578 Qualifiers T1Quals, T2Quals; 3579 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3580 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3581 if (UnqualT1 == UnqualT2) { 3582 // Objective-C++ ARC: If the references refer to objects with different 3583 // lifetimes, prefer bindings that don't change lifetime. 3584 if (SCS1.ObjCLifetimeConversionBinding != 3585 SCS2.ObjCLifetimeConversionBinding) { 3586 return SCS1.ObjCLifetimeConversionBinding 3587 ? ImplicitConversionSequence::Worse 3588 : ImplicitConversionSequence::Better; 3589 } 3590 3591 // If the type is an array type, promote the element qualifiers to the 3592 // type for comparison. 3593 if (isa<ArrayType>(T1) && T1Quals) 3594 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3595 if (isa<ArrayType>(T2) && T2Quals) 3596 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3597 if (T2.isMoreQualifiedThan(T1)) 3598 return ImplicitConversionSequence::Better; 3599 else if (T1.isMoreQualifiedThan(T2)) 3600 return ImplicitConversionSequence::Worse; 3601 } 3602 } 3603 3604 // In Microsoft mode, prefer an integral conversion to a 3605 // floating-to-integral conversion if the integral conversion 3606 // is between types of the same size. 3607 // For example: 3608 // void f(float); 3609 // void f(int); 3610 // int main { 3611 // long a; 3612 // f(a); 3613 // } 3614 // Here, MSVC will call f(int) instead of generating a compile error 3615 // as clang will do in standard mode. 3616 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3617 SCS2.Second == ICK_Floating_Integral && 3618 S.Context.getTypeSize(SCS1.getFromType()) == 3619 S.Context.getTypeSize(SCS1.getToType(2))) 3620 return ImplicitConversionSequence::Better; 3621 3622 return ImplicitConversionSequence::Indistinguishable; 3623 } 3624 3625 /// CompareQualificationConversions - Compares two standard conversion 3626 /// sequences to determine whether they can be ranked based on their 3627 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3628 static ImplicitConversionSequence::CompareKind 3629 CompareQualificationConversions(Sema &S, 3630 const StandardConversionSequence& SCS1, 3631 const StandardConversionSequence& SCS2) { 3632 // C++ 13.3.3.2p3: 3633 // -- S1 and S2 differ only in their qualification conversion and 3634 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3635 // cv-qualification signature of type T1 is a proper subset of 3636 // the cv-qualification signature of type T2, and S1 is not the 3637 // deprecated string literal array-to-pointer conversion (4.2). 3638 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3639 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3640 return ImplicitConversionSequence::Indistinguishable; 3641 3642 // FIXME: the example in the standard doesn't use a qualification 3643 // conversion (!) 3644 QualType T1 = SCS1.getToType(2); 3645 QualType T2 = SCS2.getToType(2); 3646 T1 = S.Context.getCanonicalType(T1); 3647 T2 = S.Context.getCanonicalType(T2); 3648 Qualifiers T1Quals, T2Quals; 3649 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3650 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3651 3652 // If the types are the same, we won't learn anything by unwrapped 3653 // them. 3654 if (UnqualT1 == UnqualT2) 3655 return ImplicitConversionSequence::Indistinguishable; 3656 3657 // If the type is an array type, promote the element qualifiers to the type 3658 // for comparison. 3659 if (isa<ArrayType>(T1) && T1Quals) 3660 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3661 if (isa<ArrayType>(T2) && T2Quals) 3662 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3663 3664 ImplicitConversionSequence::CompareKind Result 3665 = ImplicitConversionSequence::Indistinguishable; 3666 3667 // Objective-C++ ARC: 3668 // Prefer qualification conversions not involving a change in lifetime 3669 // to qualification conversions that do not change lifetime. 3670 if (SCS1.QualificationIncludesObjCLifetime != 3671 SCS2.QualificationIncludesObjCLifetime) { 3672 Result = SCS1.QualificationIncludesObjCLifetime 3673 ? ImplicitConversionSequence::Worse 3674 : ImplicitConversionSequence::Better; 3675 } 3676 3677 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3678 // Within each iteration of the loop, we check the qualifiers to 3679 // determine if this still looks like a qualification 3680 // conversion. Then, if all is well, we unwrap one more level of 3681 // pointers or pointers-to-members and do it all again 3682 // until there are no more pointers or pointers-to-members left 3683 // to unwrap. This essentially mimics what 3684 // IsQualificationConversion does, but here we're checking for a 3685 // strict subset of qualifiers. 3686 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3687 // The qualifiers are the same, so this doesn't tell us anything 3688 // about how the sequences rank. 3689 ; 3690 else if (T2.isMoreQualifiedThan(T1)) { 3691 // T1 has fewer qualifiers, so it could be the better sequence. 3692 if (Result == ImplicitConversionSequence::Worse) 3693 // Neither has qualifiers that are a subset of the other's 3694 // qualifiers. 3695 return ImplicitConversionSequence::Indistinguishable; 3696 3697 Result = ImplicitConversionSequence::Better; 3698 } else if (T1.isMoreQualifiedThan(T2)) { 3699 // T2 has fewer qualifiers, so it could be the better sequence. 3700 if (Result == ImplicitConversionSequence::Better) 3701 // Neither has qualifiers that are a subset of the other's 3702 // qualifiers. 3703 return ImplicitConversionSequence::Indistinguishable; 3704 3705 Result = ImplicitConversionSequence::Worse; 3706 } else { 3707 // Qualifiers are disjoint. 3708 return ImplicitConversionSequence::Indistinguishable; 3709 } 3710 3711 // If the types after this point are equivalent, we're done. 3712 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3713 break; 3714 } 3715 3716 // Check that the winning standard conversion sequence isn't using 3717 // the deprecated string literal array to pointer conversion. 3718 switch (Result) { 3719 case ImplicitConversionSequence::Better: 3720 if (SCS1.DeprecatedStringLiteralToCharPtr) 3721 Result = ImplicitConversionSequence::Indistinguishable; 3722 break; 3723 3724 case ImplicitConversionSequence::Indistinguishable: 3725 break; 3726 3727 case ImplicitConversionSequence::Worse: 3728 if (SCS2.DeprecatedStringLiteralToCharPtr) 3729 Result = ImplicitConversionSequence::Indistinguishable; 3730 break; 3731 } 3732 3733 return Result; 3734 } 3735 3736 /// CompareDerivedToBaseConversions - Compares two standard conversion 3737 /// sequences to determine whether they can be ranked based on their 3738 /// various kinds of derived-to-base conversions (C++ 3739 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3740 /// conversions between Objective-C interface types. 3741 static ImplicitConversionSequence::CompareKind 3742 CompareDerivedToBaseConversions(Sema &S, 3743 const StandardConversionSequence& SCS1, 3744 const StandardConversionSequence& SCS2) { 3745 QualType FromType1 = SCS1.getFromType(); 3746 QualType ToType1 = SCS1.getToType(1); 3747 QualType FromType2 = SCS2.getFromType(); 3748 QualType ToType2 = SCS2.getToType(1); 3749 3750 // Adjust the types we're converting from via the array-to-pointer 3751 // conversion, if we need to. 3752 if (SCS1.First == ICK_Array_To_Pointer) 3753 FromType1 = S.Context.getArrayDecayedType(FromType1); 3754 if (SCS2.First == ICK_Array_To_Pointer) 3755 FromType2 = S.Context.getArrayDecayedType(FromType2); 3756 3757 // Canonicalize all of the types. 3758 FromType1 = S.Context.getCanonicalType(FromType1); 3759 ToType1 = S.Context.getCanonicalType(ToType1); 3760 FromType2 = S.Context.getCanonicalType(FromType2); 3761 ToType2 = S.Context.getCanonicalType(ToType2); 3762 3763 // C++ [over.ics.rank]p4b3: 3764 // 3765 // If class B is derived directly or indirectly from class A and 3766 // class C is derived directly or indirectly from B, 3767 // 3768 // Compare based on pointer conversions. 3769 if (SCS1.Second == ICK_Pointer_Conversion && 3770 SCS2.Second == ICK_Pointer_Conversion && 3771 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3772 FromType1->isPointerType() && FromType2->isPointerType() && 3773 ToType1->isPointerType() && ToType2->isPointerType()) { 3774 QualType FromPointee1 3775 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3776 QualType ToPointee1 3777 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3778 QualType FromPointee2 3779 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3780 QualType ToPointee2 3781 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3782 3783 // -- conversion of C* to B* is better than conversion of C* to A*, 3784 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3785 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3786 return ImplicitConversionSequence::Better; 3787 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3788 return ImplicitConversionSequence::Worse; 3789 } 3790 3791 // -- conversion of B* to A* is better than conversion of C* to A*, 3792 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3793 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3794 return ImplicitConversionSequence::Better; 3795 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3796 return ImplicitConversionSequence::Worse; 3797 } 3798 } else if (SCS1.Second == ICK_Pointer_Conversion && 3799 SCS2.Second == ICK_Pointer_Conversion) { 3800 const ObjCObjectPointerType *FromPtr1 3801 = FromType1->getAs<ObjCObjectPointerType>(); 3802 const ObjCObjectPointerType *FromPtr2 3803 = FromType2->getAs<ObjCObjectPointerType>(); 3804 const ObjCObjectPointerType *ToPtr1 3805 = ToType1->getAs<ObjCObjectPointerType>(); 3806 const ObjCObjectPointerType *ToPtr2 3807 = ToType2->getAs<ObjCObjectPointerType>(); 3808 3809 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3810 // Apply the same conversion ranking rules for Objective-C pointer types 3811 // that we do for C++ pointers to class types. However, we employ the 3812 // Objective-C pseudo-subtyping relationship used for assignment of 3813 // Objective-C pointer types. 3814 bool FromAssignLeft 3815 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3816 bool FromAssignRight 3817 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3818 bool ToAssignLeft 3819 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3820 bool ToAssignRight 3821 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3822 3823 // A conversion to an a non-id object pointer type or qualified 'id' 3824 // type is better than a conversion to 'id'. 3825 if (ToPtr1->isObjCIdType() && 3826 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3827 return ImplicitConversionSequence::Worse; 3828 if (ToPtr2->isObjCIdType() && 3829 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3830 return ImplicitConversionSequence::Better; 3831 3832 // A conversion to a non-id object pointer type is better than a 3833 // conversion to a qualified 'id' type 3834 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3835 return ImplicitConversionSequence::Worse; 3836 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3837 return ImplicitConversionSequence::Better; 3838 3839 // A conversion to an a non-Class object pointer type or qualified 'Class' 3840 // type is better than a conversion to 'Class'. 3841 if (ToPtr1->isObjCClassType() && 3842 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3843 return ImplicitConversionSequence::Worse; 3844 if (ToPtr2->isObjCClassType() && 3845 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3846 return ImplicitConversionSequence::Better; 3847 3848 // A conversion to a non-Class object pointer type is better than a 3849 // conversion to a qualified 'Class' type. 3850 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3851 return ImplicitConversionSequence::Worse; 3852 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3853 return ImplicitConversionSequence::Better; 3854 3855 // -- "conversion of C* to B* is better than conversion of C* to A*," 3856 if (S.Context.hasSameType(FromType1, FromType2) && 3857 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3858 (ToAssignLeft != ToAssignRight)) 3859 return ToAssignLeft? ImplicitConversionSequence::Worse 3860 : ImplicitConversionSequence::Better; 3861 3862 // -- "conversion of B* to A* is better than conversion of C* to A*," 3863 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3864 (FromAssignLeft != FromAssignRight)) 3865 return FromAssignLeft? ImplicitConversionSequence::Better 3866 : ImplicitConversionSequence::Worse; 3867 } 3868 } 3869 3870 // Ranking of member-pointer types. 3871 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3872 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3873 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3874 const MemberPointerType * FromMemPointer1 = 3875 FromType1->getAs<MemberPointerType>(); 3876 const MemberPointerType * ToMemPointer1 = 3877 ToType1->getAs<MemberPointerType>(); 3878 const MemberPointerType * FromMemPointer2 = 3879 FromType2->getAs<MemberPointerType>(); 3880 const MemberPointerType * ToMemPointer2 = 3881 ToType2->getAs<MemberPointerType>(); 3882 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3883 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3884 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3885 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3886 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3887 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3888 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3889 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3890 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3891 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3892 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3893 return ImplicitConversionSequence::Worse; 3894 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3895 return ImplicitConversionSequence::Better; 3896 } 3897 // conversion of B::* to C::* is better than conversion of A::* to C::* 3898 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3899 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3900 return ImplicitConversionSequence::Better; 3901 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3902 return ImplicitConversionSequence::Worse; 3903 } 3904 } 3905 3906 if (SCS1.Second == ICK_Derived_To_Base) { 3907 // -- conversion of C to B is better than conversion of C to A, 3908 // -- binding of an expression of type C to a reference of type 3909 // B& is better than binding an expression of type C to a 3910 // reference of type A&, 3911 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3912 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3913 if (S.IsDerivedFrom(ToType1, ToType2)) 3914 return ImplicitConversionSequence::Better; 3915 else if (S.IsDerivedFrom(ToType2, ToType1)) 3916 return ImplicitConversionSequence::Worse; 3917 } 3918 3919 // -- conversion of B to A is better than conversion of C to A. 3920 // -- binding of an expression of type B to a reference of type 3921 // A& is better than binding an expression of type C to a 3922 // reference of type A&, 3923 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3924 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3925 if (S.IsDerivedFrom(FromType2, FromType1)) 3926 return ImplicitConversionSequence::Better; 3927 else if (S.IsDerivedFrom(FromType1, FromType2)) 3928 return ImplicitConversionSequence::Worse; 3929 } 3930 } 3931 3932 return ImplicitConversionSequence::Indistinguishable; 3933 } 3934 3935 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3936 /// C++ class. 3937 static bool isTypeValid(QualType T) { 3938 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3939 return !Record->isInvalidDecl(); 3940 3941 return true; 3942 } 3943 3944 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3945 /// determine whether they are reference-related, 3946 /// reference-compatible, reference-compatible with added 3947 /// qualification, or incompatible, for use in C++ initialization by 3948 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3949 /// type, and the first type (T1) is the pointee type of the reference 3950 /// type being initialized. 3951 Sema::ReferenceCompareResult 3952 Sema::CompareReferenceRelationship(SourceLocation Loc, 3953 QualType OrigT1, QualType OrigT2, 3954 bool &DerivedToBase, 3955 bool &ObjCConversion, 3956 bool &ObjCLifetimeConversion) { 3957 assert(!OrigT1->isReferenceType() && 3958 "T1 must be the pointee type of the reference type"); 3959 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3960 3961 QualType T1 = Context.getCanonicalType(OrigT1); 3962 QualType T2 = Context.getCanonicalType(OrigT2); 3963 Qualifiers T1Quals, T2Quals; 3964 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3965 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3966 3967 // C++ [dcl.init.ref]p4: 3968 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3969 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3970 // T1 is a base class of T2. 3971 DerivedToBase = false; 3972 ObjCConversion = false; 3973 ObjCLifetimeConversion = false; 3974 if (UnqualT1 == UnqualT2) { 3975 // Nothing to do. 3976 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3977 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3978 IsDerivedFrom(UnqualT2, UnqualT1)) 3979 DerivedToBase = true; 3980 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3981 UnqualT2->isObjCObjectOrInterfaceType() && 3982 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3983 ObjCConversion = true; 3984 else 3985 return Ref_Incompatible; 3986 3987 // At this point, we know that T1 and T2 are reference-related (at 3988 // least). 3989 3990 // If the type is an array type, promote the element qualifiers to the type 3991 // for comparison. 3992 if (isa<ArrayType>(T1) && T1Quals) 3993 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3994 if (isa<ArrayType>(T2) && T2Quals) 3995 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3996 3997 // C++ [dcl.init.ref]p4: 3998 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3999 // reference-related to T2 and cv1 is the same cv-qualification 4000 // as, or greater cv-qualification than, cv2. For purposes of 4001 // overload resolution, cases for which cv1 is greater 4002 // cv-qualification than cv2 are identified as 4003 // reference-compatible with added qualification (see 13.3.3.2). 4004 // 4005 // Note that we also require equivalence of Objective-C GC and address-space 4006 // qualifiers when performing these computations, so that e.g., an int in 4007 // address space 1 is not reference-compatible with an int in address 4008 // space 2. 4009 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4010 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4011 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4012 ObjCLifetimeConversion = true; 4013 4014 T1Quals.removeObjCLifetime(); 4015 T2Quals.removeObjCLifetime(); 4016 } 4017 4018 if (T1Quals == T2Quals) 4019 return Ref_Compatible; 4020 else if (T1Quals.compatiblyIncludes(T2Quals)) 4021 return Ref_Compatible_With_Added_Qualification; 4022 else 4023 return Ref_Related; 4024 } 4025 4026 /// \brief Look for a user-defined conversion to an value reference-compatible 4027 /// with DeclType. Return true if something definite is found. 4028 static bool 4029 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4030 QualType DeclType, SourceLocation DeclLoc, 4031 Expr *Init, QualType T2, bool AllowRvalues, 4032 bool AllowExplicit) { 4033 assert(T2->isRecordType() && "Can only find conversions of record types."); 4034 CXXRecordDecl *T2RecordDecl 4035 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4036 4037 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4038 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4039 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4040 NamedDecl *D = *I; 4041 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4042 if (isa<UsingShadowDecl>(D)) 4043 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4044 4045 FunctionTemplateDecl *ConvTemplate 4046 = dyn_cast<FunctionTemplateDecl>(D); 4047 CXXConversionDecl *Conv; 4048 if (ConvTemplate) 4049 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4050 else 4051 Conv = cast<CXXConversionDecl>(D); 4052 4053 // If this is an explicit conversion, and we're not allowed to consider 4054 // explicit conversions, skip it. 4055 if (!AllowExplicit && Conv->isExplicit()) 4056 continue; 4057 4058 if (AllowRvalues) { 4059 bool DerivedToBase = false; 4060 bool ObjCConversion = false; 4061 bool ObjCLifetimeConversion = false; 4062 4063 // If we are initializing an rvalue reference, don't permit conversion 4064 // functions that return lvalues. 4065 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4066 const ReferenceType *RefType 4067 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4068 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4069 continue; 4070 } 4071 4072 if (!ConvTemplate && 4073 S.CompareReferenceRelationship( 4074 DeclLoc, 4075 Conv->getConversionType().getNonReferenceType() 4076 .getUnqualifiedType(), 4077 DeclType.getNonReferenceType().getUnqualifiedType(), 4078 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4079 Sema::Ref_Incompatible) 4080 continue; 4081 } else { 4082 // If the conversion function doesn't return a reference type, 4083 // it can't be considered for this conversion. An rvalue reference 4084 // is only acceptable if its referencee is a function type. 4085 4086 const ReferenceType *RefType = 4087 Conv->getConversionType()->getAs<ReferenceType>(); 4088 if (!RefType || 4089 (!RefType->isLValueReferenceType() && 4090 !RefType->getPointeeType()->isFunctionType())) 4091 continue; 4092 } 4093 4094 if (ConvTemplate) 4095 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4096 Init, DeclType, CandidateSet, 4097 /*AllowObjCConversionOnExplicit=*/false); 4098 else 4099 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4100 DeclType, CandidateSet, 4101 /*AllowObjCConversionOnExplicit=*/false); 4102 } 4103 4104 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4105 4106 OverloadCandidateSet::iterator Best; 4107 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4108 case OR_Success: 4109 // C++ [over.ics.ref]p1: 4110 // 4111 // [...] If the parameter binds directly to the result of 4112 // applying a conversion function to the argument 4113 // expression, the implicit conversion sequence is a 4114 // user-defined conversion sequence (13.3.3.1.2), with the 4115 // second standard conversion sequence either an identity 4116 // conversion or, if the conversion function returns an 4117 // entity of a type that is a derived class of the parameter 4118 // type, a derived-to-base Conversion. 4119 if (!Best->FinalConversion.DirectBinding) 4120 return false; 4121 4122 ICS.setUserDefined(); 4123 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4124 ICS.UserDefined.After = Best->FinalConversion; 4125 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4126 ICS.UserDefined.ConversionFunction = Best->Function; 4127 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4128 ICS.UserDefined.EllipsisConversion = false; 4129 assert(ICS.UserDefined.After.ReferenceBinding && 4130 ICS.UserDefined.After.DirectBinding && 4131 "Expected a direct reference binding!"); 4132 return true; 4133 4134 case OR_Ambiguous: 4135 ICS.setAmbiguous(); 4136 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4137 Cand != CandidateSet.end(); ++Cand) 4138 if (Cand->Viable) 4139 ICS.Ambiguous.addConversion(Cand->Function); 4140 return true; 4141 4142 case OR_No_Viable_Function: 4143 case OR_Deleted: 4144 // There was no suitable conversion, or we found a deleted 4145 // conversion; continue with other checks. 4146 return false; 4147 } 4148 4149 llvm_unreachable("Invalid OverloadResult!"); 4150 } 4151 4152 /// \brief Compute an implicit conversion sequence for reference 4153 /// initialization. 4154 static ImplicitConversionSequence 4155 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4156 SourceLocation DeclLoc, 4157 bool SuppressUserConversions, 4158 bool AllowExplicit) { 4159 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4160 4161 // Most paths end in a failed conversion. 4162 ImplicitConversionSequence ICS; 4163 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4164 4165 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4166 QualType T2 = Init->getType(); 4167 4168 // If the initializer is the address of an overloaded function, try 4169 // to resolve the overloaded function. If all goes well, T2 is the 4170 // type of the resulting function. 4171 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4172 DeclAccessPair Found; 4173 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4174 false, Found)) 4175 T2 = Fn->getType(); 4176 } 4177 4178 // Compute some basic properties of the types and the initializer. 4179 bool isRValRef = DeclType->isRValueReferenceType(); 4180 bool DerivedToBase = false; 4181 bool ObjCConversion = false; 4182 bool ObjCLifetimeConversion = false; 4183 Expr::Classification InitCategory = Init->Classify(S.Context); 4184 Sema::ReferenceCompareResult RefRelationship 4185 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4186 ObjCConversion, ObjCLifetimeConversion); 4187 4188 4189 // C++0x [dcl.init.ref]p5: 4190 // A reference to type "cv1 T1" is initialized by an expression 4191 // of type "cv2 T2" as follows: 4192 4193 // -- If reference is an lvalue reference and the initializer expression 4194 if (!isRValRef) { 4195 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4196 // reference-compatible with "cv2 T2," or 4197 // 4198 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4199 if (InitCategory.isLValue() && 4200 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4201 // C++ [over.ics.ref]p1: 4202 // When a parameter of reference type binds directly (8.5.3) 4203 // to an argument expression, the implicit conversion sequence 4204 // is the identity conversion, unless the argument expression 4205 // has a type that is a derived class of the parameter type, 4206 // in which case the implicit conversion sequence is a 4207 // derived-to-base Conversion (13.3.3.1). 4208 ICS.setStandard(); 4209 ICS.Standard.First = ICK_Identity; 4210 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4211 : ObjCConversion? ICK_Compatible_Conversion 4212 : ICK_Identity; 4213 ICS.Standard.Third = ICK_Identity; 4214 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4215 ICS.Standard.setToType(0, T2); 4216 ICS.Standard.setToType(1, T1); 4217 ICS.Standard.setToType(2, T1); 4218 ICS.Standard.ReferenceBinding = true; 4219 ICS.Standard.DirectBinding = true; 4220 ICS.Standard.IsLvalueReference = !isRValRef; 4221 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4222 ICS.Standard.BindsToRvalue = false; 4223 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4224 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4225 ICS.Standard.CopyConstructor = nullptr; 4226 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4227 4228 // Nothing more to do: the inaccessibility/ambiguity check for 4229 // derived-to-base conversions is suppressed when we're 4230 // computing the implicit conversion sequence (C++ 4231 // [over.best.ics]p2). 4232 return ICS; 4233 } 4234 4235 // -- has a class type (i.e., T2 is a class type), where T1 is 4236 // not reference-related to T2, and can be implicitly 4237 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4238 // is reference-compatible with "cv3 T3" 92) (this 4239 // conversion is selected by enumerating the applicable 4240 // conversion functions (13.3.1.6) and choosing the best 4241 // one through overload resolution (13.3)), 4242 if (!SuppressUserConversions && T2->isRecordType() && 4243 !S.RequireCompleteType(DeclLoc, T2, 0) && 4244 RefRelationship == Sema::Ref_Incompatible) { 4245 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4246 Init, T2, /*AllowRvalues=*/false, 4247 AllowExplicit)) 4248 return ICS; 4249 } 4250 } 4251 4252 // -- Otherwise, the reference shall be an lvalue reference to a 4253 // non-volatile const type (i.e., cv1 shall be const), or the reference 4254 // shall be an rvalue reference. 4255 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4256 return ICS; 4257 4258 // -- If the initializer expression 4259 // 4260 // -- is an xvalue, class prvalue, array prvalue or function 4261 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4262 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4263 (InitCategory.isXValue() || 4264 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4265 (InitCategory.isLValue() && T2->isFunctionType()))) { 4266 ICS.setStandard(); 4267 ICS.Standard.First = ICK_Identity; 4268 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4269 : ObjCConversion? ICK_Compatible_Conversion 4270 : ICK_Identity; 4271 ICS.Standard.Third = ICK_Identity; 4272 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4273 ICS.Standard.setToType(0, T2); 4274 ICS.Standard.setToType(1, T1); 4275 ICS.Standard.setToType(2, T1); 4276 ICS.Standard.ReferenceBinding = true; 4277 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4278 // binding unless we're binding to a class prvalue. 4279 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4280 // allow the use of rvalue references in C++98/03 for the benefit of 4281 // standard library implementors; therefore, we need the xvalue check here. 4282 ICS.Standard.DirectBinding = 4283 S.getLangOpts().CPlusPlus11 || 4284 !(InitCategory.isPRValue() || T2->isRecordType()); 4285 ICS.Standard.IsLvalueReference = !isRValRef; 4286 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4287 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4288 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4289 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4290 ICS.Standard.CopyConstructor = nullptr; 4291 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4292 return ICS; 4293 } 4294 4295 // -- has a class type (i.e., T2 is a class type), where T1 is not 4296 // reference-related to T2, and can be implicitly converted to 4297 // an xvalue, class prvalue, or function lvalue of type 4298 // "cv3 T3", where "cv1 T1" is reference-compatible with 4299 // "cv3 T3", 4300 // 4301 // then the reference is bound to the value of the initializer 4302 // expression in the first case and to the result of the conversion 4303 // in the second case (or, in either case, to an appropriate base 4304 // class subobject). 4305 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4306 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4307 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4308 Init, T2, /*AllowRvalues=*/true, 4309 AllowExplicit)) { 4310 // In the second case, if the reference is an rvalue reference 4311 // and the second standard conversion sequence of the 4312 // user-defined conversion sequence includes an lvalue-to-rvalue 4313 // conversion, the program is ill-formed. 4314 if (ICS.isUserDefined() && isRValRef && 4315 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4316 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4317 4318 return ICS; 4319 } 4320 4321 // A temporary of function type cannot be created; don't even try. 4322 if (T1->isFunctionType()) 4323 return ICS; 4324 4325 // -- Otherwise, a temporary of type "cv1 T1" is created and 4326 // initialized from the initializer expression using the 4327 // rules for a non-reference copy initialization (8.5). The 4328 // reference is then bound to the temporary. If T1 is 4329 // reference-related to T2, cv1 must be the same 4330 // cv-qualification as, or greater cv-qualification than, 4331 // cv2; otherwise, the program is ill-formed. 4332 if (RefRelationship == Sema::Ref_Related) { 4333 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4334 // we would be reference-compatible or reference-compatible with 4335 // added qualification. But that wasn't the case, so the reference 4336 // initialization fails. 4337 // 4338 // Note that we only want to check address spaces and cvr-qualifiers here. 4339 // ObjC GC and lifetime qualifiers aren't important. 4340 Qualifiers T1Quals = T1.getQualifiers(); 4341 Qualifiers T2Quals = T2.getQualifiers(); 4342 T1Quals.removeObjCGCAttr(); 4343 T1Quals.removeObjCLifetime(); 4344 T2Quals.removeObjCGCAttr(); 4345 T2Quals.removeObjCLifetime(); 4346 if (!T1Quals.compatiblyIncludes(T2Quals)) 4347 return ICS; 4348 } 4349 4350 // If at least one of the types is a class type, the types are not 4351 // related, and we aren't allowed any user conversions, the 4352 // reference binding fails. This case is important for breaking 4353 // recursion, since TryImplicitConversion below will attempt to 4354 // create a temporary through the use of a copy constructor. 4355 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4356 (T1->isRecordType() || T2->isRecordType())) 4357 return ICS; 4358 4359 // If T1 is reference-related to T2 and the reference is an rvalue 4360 // reference, the initializer expression shall not be an lvalue. 4361 if (RefRelationship >= Sema::Ref_Related && 4362 isRValRef && Init->Classify(S.Context).isLValue()) 4363 return ICS; 4364 4365 // C++ [over.ics.ref]p2: 4366 // When a parameter of reference type is not bound directly to 4367 // an argument expression, the conversion sequence is the one 4368 // required to convert the argument expression to the 4369 // underlying type of the reference according to 4370 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4371 // to copy-initializing a temporary of the underlying type with 4372 // the argument expression. Any difference in top-level 4373 // cv-qualification is subsumed by the initialization itself 4374 // and does not constitute a conversion. 4375 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4376 /*AllowExplicit=*/false, 4377 /*InOverloadResolution=*/false, 4378 /*CStyle=*/false, 4379 /*AllowObjCWritebackConversion=*/false, 4380 /*AllowObjCConversionOnExplicit=*/false); 4381 4382 // Of course, that's still a reference binding. 4383 if (ICS.isStandard()) { 4384 ICS.Standard.ReferenceBinding = true; 4385 ICS.Standard.IsLvalueReference = !isRValRef; 4386 ICS.Standard.BindsToFunctionLvalue = false; 4387 ICS.Standard.BindsToRvalue = true; 4388 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4389 ICS.Standard.ObjCLifetimeConversionBinding = false; 4390 } else if (ICS.isUserDefined()) { 4391 const ReferenceType *LValRefType = 4392 ICS.UserDefined.ConversionFunction->getReturnType() 4393 ->getAs<LValueReferenceType>(); 4394 4395 // C++ [over.ics.ref]p3: 4396 // Except for an implicit object parameter, for which see 13.3.1, a 4397 // standard conversion sequence cannot be formed if it requires [...] 4398 // binding an rvalue reference to an lvalue other than a function 4399 // lvalue. 4400 // Note that the function case is not possible here. 4401 if (DeclType->isRValueReferenceType() && LValRefType) { 4402 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4403 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4404 // reference to an rvalue! 4405 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4406 return ICS; 4407 } 4408 4409 ICS.UserDefined.Before.setAsIdentityConversion(); 4410 ICS.UserDefined.After.ReferenceBinding = true; 4411 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4412 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4413 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4414 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4415 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4416 } 4417 4418 return ICS; 4419 } 4420 4421 static ImplicitConversionSequence 4422 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4423 bool SuppressUserConversions, 4424 bool InOverloadResolution, 4425 bool AllowObjCWritebackConversion, 4426 bool AllowExplicit = false); 4427 4428 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4429 /// initializer list From. 4430 static ImplicitConversionSequence 4431 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4432 bool SuppressUserConversions, 4433 bool InOverloadResolution, 4434 bool AllowObjCWritebackConversion) { 4435 // C++11 [over.ics.list]p1: 4436 // When an argument is an initializer list, it is not an expression and 4437 // special rules apply for converting it to a parameter type. 4438 4439 ImplicitConversionSequence Result; 4440 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4441 4442 // We need a complete type for what follows. Incomplete types can never be 4443 // initialized from init lists. 4444 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4445 return Result; 4446 4447 // Per DR1467: 4448 // If the parameter type is a class X and the initializer list has a single 4449 // element of type cv U, where U is X or a class derived from X, the 4450 // implicit conversion sequence is the one required to convert the element 4451 // to the parameter type. 4452 // 4453 // Otherwise, if the parameter type is a character array [... ] 4454 // and the initializer list has a single element that is an 4455 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4456 // implicit conversion sequence is the identity conversion. 4457 if (From->getNumInits() == 1) { 4458 if (ToType->isRecordType()) { 4459 QualType InitType = From->getInit(0)->getType(); 4460 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4461 S.IsDerivedFrom(InitType, ToType)) 4462 return TryCopyInitialization(S, From->getInit(0), ToType, 4463 SuppressUserConversions, 4464 InOverloadResolution, 4465 AllowObjCWritebackConversion); 4466 } 4467 // FIXME: Check the other conditions here: array of character type, 4468 // initializer is a string literal. 4469 if (ToType->isArrayType()) { 4470 InitializedEntity Entity = 4471 InitializedEntity::InitializeParameter(S.Context, ToType, 4472 /*Consumed=*/false); 4473 if (S.CanPerformCopyInitialization(Entity, From)) { 4474 Result.setStandard(); 4475 Result.Standard.setAsIdentityConversion(); 4476 Result.Standard.setFromType(ToType); 4477 Result.Standard.setAllToTypes(ToType); 4478 return Result; 4479 } 4480 } 4481 } 4482 4483 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4484 // C++11 [over.ics.list]p2: 4485 // If the parameter type is std::initializer_list<X> or "array of X" and 4486 // all the elements can be implicitly converted to X, the implicit 4487 // conversion sequence is the worst conversion necessary to convert an 4488 // element of the list to X. 4489 // 4490 // C++14 [over.ics.list]p3: 4491 // Otherwise, if the parameter type is "array of N X", if the initializer 4492 // list has exactly N elements or if it has fewer than N elements and X is 4493 // default-constructible, and if all the elements of the initializer list 4494 // can be implicitly converted to X, the implicit conversion sequence is 4495 // the worst conversion necessary to convert an element of the list to X. 4496 // 4497 // FIXME: We're missing a lot of these checks. 4498 bool toStdInitializerList = false; 4499 QualType X; 4500 if (ToType->isArrayType()) 4501 X = S.Context.getAsArrayType(ToType)->getElementType(); 4502 else 4503 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4504 if (!X.isNull()) { 4505 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4506 Expr *Init = From->getInit(i); 4507 ImplicitConversionSequence ICS = 4508 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4509 InOverloadResolution, 4510 AllowObjCWritebackConversion); 4511 // If a single element isn't convertible, fail. 4512 if (ICS.isBad()) { 4513 Result = ICS; 4514 break; 4515 } 4516 // Otherwise, look for the worst conversion. 4517 if (Result.isBad() || 4518 CompareImplicitConversionSequences(S, ICS, Result) == 4519 ImplicitConversionSequence::Worse) 4520 Result = ICS; 4521 } 4522 4523 // For an empty list, we won't have computed any conversion sequence. 4524 // Introduce the identity conversion sequence. 4525 if (From->getNumInits() == 0) { 4526 Result.setStandard(); 4527 Result.Standard.setAsIdentityConversion(); 4528 Result.Standard.setFromType(ToType); 4529 Result.Standard.setAllToTypes(ToType); 4530 } 4531 4532 Result.setStdInitializerListElement(toStdInitializerList); 4533 return Result; 4534 } 4535 4536 // C++14 [over.ics.list]p4: 4537 // C++11 [over.ics.list]p3: 4538 // Otherwise, if the parameter is a non-aggregate class X and overload 4539 // resolution chooses a single best constructor [...] the implicit 4540 // conversion sequence is a user-defined conversion sequence. If multiple 4541 // constructors are viable but none is better than the others, the 4542 // implicit conversion sequence is a user-defined conversion sequence. 4543 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4544 // This function can deal with initializer lists. 4545 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4546 /*AllowExplicit=*/false, 4547 InOverloadResolution, /*CStyle=*/false, 4548 AllowObjCWritebackConversion, 4549 /*AllowObjCConversionOnExplicit=*/false); 4550 } 4551 4552 // C++14 [over.ics.list]p5: 4553 // C++11 [over.ics.list]p4: 4554 // Otherwise, if the parameter has an aggregate type which can be 4555 // initialized from the initializer list [...] the implicit conversion 4556 // sequence is a user-defined conversion sequence. 4557 if (ToType->isAggregateType()) { 4558 // Type is an aggregate, argument is an init list. At this point it comes 4559 // down to checking whether the initialization works. 4560 // FIXME: Find out whether this parameter is consumed or not. 4561 InitializedEntity Entity = 4562 InitializedEntity::InitializeParameter(S.Context, ToType, 4563 /*Consumed=*/false); 4564 if (S.CanPerformCopyInitialization(Entity, From)) { 4565 Result.setUserDefined(); 4566 Result.UserDefined.Before.setAsIdentityConversion(); 4567 // Initializer lists don't have a type. 4568 Result.UserDefined.Before.setFromType(QualType()); 4569 Result.UserDefined.Before.setAllToTypes(QualType()); 4570 4571 Result.UserDefined.After.setAsIdentityConversion(); 4572 Result.UserDefined.After.setFromType(ToType); 4573 Result.UserDefined.After.setAllToTypes(ToType); 4574 Result.UserDefined.ConversionFunction = nullptr; 4575 } 4576 return Result; 4577 } 4578 4579 // C++14 [over.ics.list]p6: 4580 // C++11 [over.ics.list]p5: 4581 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4582 if (ToType->isReferenceType()) { 4583 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4584 // mention initializer lists in any way. So we go by what list- 4585 // initialization would do and try to extrapolate from that. 4586 4587 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4588 4589 // If the initializer list has a single element that is reference-related 4590 // to the parameter type, we initialize the reference from that. 4591 if (From->getNumInits() == 1) { 4592 Expr *Init = From->getInit(0); 4593 4594 QualType T2 = Init->getType(); 4595 4596 // If the initializer is the address of an overloaded function, try 4597 // to resolve the overloaded function. If all goes well, T2 is the 4598 // type of the resulting function. 4599 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4600 DeclAccessPair Found; 4601 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4602 Init, ToType, false, Found)) 4603 T2 = Fn->getType(); 4604 } 4605 4606 // Compute some basic properties of the types and the initializer. 4607 bool dummy1 = false; 4608 bool dummy2 = false; 4609 bool dummy3 = false; 4610 Sema::ReferenceCompareResult RefRelationship 4611 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4612 dummy2, dummy3); 4613 4614 if (RefRelationship >= Sema::Ref_Related) { 4615 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4616 SuppressUserConversions, 4617 /*AllowExplicit=*/false); 4618 } 4619 } 4620 4621 // Otherwise, we bind the reference to a temporary created from the 4622 // initializer list. 4623 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4624 InOverloadResolution, 4625 AllowObjCWritebackConversion); 4626 if (Result.isFailure()) 4627 return Result; 4628 assert(!Result.isEllipsis() && 4629 "Sub-initialization cannot result in ellipsis conversion."); 4630 4631 // Can we even bind to a temporary? 4632 if (ToType->isRValueReferenceType() || 4633 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4634 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4635 Result.UserDefined.After; 4636 SCS.ReferenceBinding = true; 4637 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4638 SCS.BindsToRvalue = true; 4639 SCS.BindsToFunctionLvalue = false; 4640 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4641 SCS.ObjCLifetimeConversionBinding = false; 4642 } else 4643 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4644 From, ToType); 4645 return Result; 4646 } 4647 4648 // C++14 [over.ics.list]p7: 4649 // C++11 [over.ics.list]p6: 4650 // Otherwise, if the parameter type is not a class: 4651 if (!ToType->isRecordType()) { 4652 // - if the initializer list has one element that is not itself an 4653 // initializer list, the implicit conversion sequence is the one 4654 // required to convert the element to the parameter type. 4655 unsigned NumInits = From->getNumInits(); 4656 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4657 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4658 SuppressUserConversions, 4659 InOverloadResolution, 4660 AllowObjCWritebackConversion); 4661 // - if the initializer list has no elements, the implicit conversion 4662 // sequence is the identity conversion. 4663 else if (NumInits == 0) { 4664 Result.setStandard(); 4665 Result.Standard.setAsIdentityConversion(); 4666 Result.Standard.setFromType(ToType); 4667 Result.Standard.setAllToTypes(ToType); 4668 } 4669 return Result; 4670 } 4671 4672 // C++14 [over.ics.list]p8: 4673 // C++11 [over.ics.list]p7: 4674 // In all cases other than those enumerated above, no conversion is possible 4675 return Result; 4676 } 4677 4678 /// TryCopyInitialization - Try to copy-initialize a value of type 4679 /// ToType from the expression From. Return the implicit conversion 4680 /// sequence required to pass this argument, which may be a bad 4681 /// conversion sequence (meaning that the argument cannot be passed to 4682 /// a parameter of this type). If @p SuppressUserConversions, then we 4683 /// do not permit any user-defined conversion sequences. 4684 static ImplicitConversionSequence 4685 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4686 bool SuppressUserConversions, 4687 bool InOverloadResolution, 4688 bool AllowObjCWritebackConversion, 4689 bool AllowExplicit) { 4690 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4691 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4692 InOverloadResolution,AllowObjCWritebackConversion); 4693 4694 if (ToType->isReferenceType()) 4695 return TryReferenceInit(S, From, ToType, 4696 /*FIXME:*/From->getLocStart(), 4697 SuppressUserConversions, 4698 AllowExplicit); 4699 4700 return TryImplicitConversion(S, From, ToType, 4701 SuppressUserConversions, 4702 /*AllowExplicit=*/false, 4703 InOverloadResolution, 4704 /*CStyle=*/false, 4705 AllowObjCWritebackConversion, 4706 /*AllowObjCConversionOnExplicit=*/false); 4707 } 4708 4709 static bool TryCopyInitialization(const CanQualType FromQTy, 4710 const CanQualType ToQTy, 4711 Sema &S, 4712 SourceLocation Loc, 4713 ExprValueKind FromVK) { 4714 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4715 ImplicitConversionSequence ICS = 4716 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4717 4718 return !ICS.isBad(); 4719 } 4720 4721 /// TryObjectArgumentInitialization - Try to initialize the object 4722 /// parameter of the given member function (@c Method) from the 4723 /// expression @p From. 4724 static ImplicitConversionSequence 4725 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4726 Expr::Classification FromClassification, 4727 CXXMethodDecl *Method, 4728 CXXRecordDecl *ActingContext) { 4729 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4730 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4731 // const volatile object. 4732 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4733 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4734 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4735 4736 // Set up the conversion sequence as a "bad" conversion, to allow us 4737 // to exit early. 4738 ImplicitConversionSequence ICS; 4739 4740 // We need to have an object of class type. 4741 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4742 FromType = PT->getPointeeType(); 4743 4744 // When we had a pointer, it's implicitly dereferenced, so we 4745 // better have an lvalue. 4746 assert(FromClassification.isLValue()); 4747 } 4748 4749 assert(FromType->isRecordType()); 4750 4751 // C++0x [over.match.funcs]p4: 4752 // For non-static member functions, the type of the implicit object 4753 // parameter is 4754 // 4755 // - "lvalue reference to cv X" for functions declared without a 4756 // ref-qualifier or with the & ref-qualifier 4757 // - "rvalue reference to cv X" for functions declared with the && 4758 // ref-qualifier 4759 // 4760 // where X is the class of which the function is a member and cv is the 4761 // cv-qualification on the member function declaration. 4762 // 4763 // However, when finding an implicit conversion sequence for the argument, we 4764 // are not allowed to create temporaries or perform user-defined conversions 4765 // (C++ [over.match.funcs]p5). We perform a simplified version of 4766 // reference binding here, that allows class rvalues to bind to 4767 // non-constant references. 4768 4769 // First check the qualifiers. 4770 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4771 if (ImplicitParamType.getCVRQualifiers() 4772 != FromTypeCanon.getLocalCVRQualifiers() && 4773 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4774 ICS.setBad(BadConversionSequence::bad_qualifiers, 4775 FromType, ImplicitParamType); 4776 return ICS; 4777 } 4778 4779 // Check that we have either the same type or a derived type. It 4780 // affects the conversion rank. 4781 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4782 ImplicitConversionKind SecondKind; 4783 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4784 SecondKind = ICK_Identity; 4785 } else if (S.IsDerivedFrom(FromType, ClassType)) 4786 SecondKind = ICK_Derived_To_Base; 4787 else { 4788 ICS.setBad(BadConversionSequence::unrelated_class, 4789 FromType, ImplicitParamType); 4790 return ICS; 4791 } 4792 4793 // Check the ref-qualifier. 4794 switch (Method->getRefQualifier()) { 4795 case RQ_None: 4796 // Do nothing; we don't care about lvalueness or rvalueness. 4797 break; 4798 4799 case RQ_LValue: 4800 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4801 // non-const lvalue reference cannot bind to an rvalue 4802 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4803 ImplicitParamType); 4804 return ICS; 4805 } 4806 break; 4807 4808 case RQ_RValue: 4809 if (!FromClassification.isRValue()) { 4810 // rvalue reference cannot bind to an lvalue 4811 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4812 ImplicitParamType); 4813 return ICS; 4814 } 4815 break; 4816 } 4817 4818 // Success. Mark this as a reference binding. 4819 ICS.setStandard(); 4820 ICS.Standard.setAsIdentityConversion(); 4821 ICS.Standard.Second = SecondKind; 4822 ICS.Standard.setFromType(FromType); 4823 ICS.Standard.setAllToTypes(ImplicitParamType); 4824 ICS.Standard.ReferenceBinding = true; 4825 ICS.Standard.DirectBinding = true; 4826 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4827 ICS.Standard.BindsToFunctionLvalue = false; 4828 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4829 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4830 = (Method->getRefQualifier() == RQ_None); 4831 return ICS; 4832 } 4833 4834 /// PerformObjectArgumentInitialization - Perform initialization of 4835 /// the implicit object parameter for the given Method with the given 4836 /// expression. 4837 ExprResult 4838 Sema::PerformObjectArgumentInitialization(Expr *From, 4839 NestedNameSpecifier *Qualifier, 4840 NamedDecl *FoundDecl, 4841 CXXMethodDecl *Method) { 4842 QualType FromRecordType, DestType; 4843 QualType ImplicitParamRecordType = 4844 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4845 4846 Expr::Classification FromClassification; 4847 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4848 FromRecordType = PT->getPointeeType(); 4849 DestType = Method->getThisType(Context); 4850 FromClassification = Expr::Classification::makeSimpleLValue(); 4851 } else { 4852 FromRecordType = From->getType(); 4853 DestType = ImplicitParamRecordType; 4854 FromClassification = From->Classify(Context); 4855 } 4856 4857 // Note that we always use the true parent context when performing 4858 // the actual argument initialization. 4859 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4860 *this, From->getType(), FromClassification, Method, Method->getParent()); 4861 if (ICS.isBad()) { 4862 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4863 Qualifiers FromQs = FromRecordType.getQualifiers(); 4864 Qualifiers ToQs = DestType.getQualifiers(); 4865 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4866 if (CVR) { 4867 Diag(From->getLocStart(), 4868 diag::err_member_function_call_bad_cvr) 4869 << Method->getDeclName() << FromRecordType << (CVR - 1) 4870 << From->getSourceRange(); 4871 Diag(Method->getLocation(), diag::note_previous_decl) 4872 << Method->getDeclName(); 4873 return ExprError(); 4874 } 4875 } 4876 4877 return Diag(From->getLocStart(), 4878 diag::err_implicit_object_parameter_init) 4879 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4880 } 4881 4882 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4883 ExprResult FromRes = 4884 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4885 if (FromRes.isInvalid()) 4886 return ExprError(); 4887 From = FromRes.get(); 4888 } 4889 4890 if (!Context.hasSameType(From->getType(), DestType)) 4891 From = ImpCastExprToType(From, DestType, CK_NoOp, 4892 From->getValueKind()).get(); 4893 return From; 4894 } 4895 4896 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4897 /// expression From to bool (C++0x [conv]p3). 4898 static ImplicitConversionSequence 4899 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4900 return TryImplicitConversion(S, From, S.Context.BoolTy, 4901 /*SuppressUserConversions=*/false, 4902 /*AllowExplicit=*/true, 4903 /*InOverloadResolution=*/false, 4904 /*CStyle=*/false, 4905 /*AllowObjCWritebackConversion=*/false, 4906 /*AllowObjCConversionOnExplicit=*/false); 4907 } 4908 4909 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4910 /// of the expression From to bool (C++0x [conv]p3). 4911 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4912 if (checkPlaceholderForOverload(*this, From)) 4913 return ExprError(); 4914 4915 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4916 if (!ICS.isBad()) 4917 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4918 4919 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4920 return Diag(From->getLocStart(), 4921 diag::err_typecheck_bool_condition) 4922 << From->getType() << From->getSourceRange(); 4923 return ExprError(); 4924 } 4925 4926 /// Check that the specified conversion is permitted in a converted constant 4927 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4928 /// is acceptable. 4929 static bool CheckConvertedConstantConversions(Sema &S, 4930 StandardConversionSequence &SCS) { 4931 // Since we know that the target type is an integral or unscoped enumeration 4932 // type, most conversion kinds are impossible. All possible First and Third 4933 // conversions are fine. 4934 switch (SCS.Second) { 4935 case ICK_Identity: 4936 case ICK_NoReturn_Adjustment: 4937 case ICK_Integral_Promotion: 4938 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 4939 return true; 4940 4941 case ICK_Boolean_Conversion: 4942 // Conversion from an integral or unscoped enumeration type to bool is 4943 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 4944 // conversion, so we allow it in a converted constant expression. 4945 // 4946 // FIXME: Per core issue 1407, we should not allow this, but that breaks 4947 // a lot of popular code. We should at least add a warning for this 4948 // (non-conforming) extension. 4949 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4950 SCS.getToType(2)->isBooleanType(); 4951 4952 case ICK_Pointer_Conversion: 4953 case ICK_Pointer_Member: 4954 // C++1z: null pointer conversions and null member pointer conversions are 4955 // only permitted if the source type is std::nullptr_t. 4956 return SCS.getFromType()->isNullPtrType(); 4957 4958 case ICK_Floating_Promotion: 4959 case ICK_Complex_Promotion: 4960 case ICK_Floating_Conversion: 4961 case ICK_Complex_Conversion: 4962 case ICK_Floating_Integral: 4963 case ICK_Compatible_Conversion: 4964 case ICK_Derived_To_Base: 4965 case ICK_Vector_Conversion: 4966 case ICK_Vector_Splat: 4967 case ICK_Complex_Real: 4968 case ICK_Block_Pointer_Conversion: 4969 case ICK_TransparentUnionConversion: 4970 case ICK_Writeback_Conversion: 4971 case ICK_Zero_Event_Conversion: 4972 return false; 4973 4974 case ICK_Lvalue_To_Rvalue: 4975 case ICK_Array_To_Pointer: 4976 case ICK_Function_To_Pointer: 4977 llvm_unreachable("found a first conversion kind in Second"); 4978 4979 case ICK_Qualification: 4980 llvm_unreachable("found a third conversion kind in Second"); 4981 4982 case ICK_Num_Conversion_Kinds: 4983 break; 4984 } 4985 4986 llvm_unreachable("unknown conversion kind"); 4987 } 4988 4989 /// CheckConvertedConstantExpression - Check that the expression From is a 4990 /// converted constant expression of type T, perform the conversion and produce 4991 /// the converted expression, per C++11 [expr.const]p3. 4992 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 4993 QualType T, APValue &Value, 4994 Sema::CCEKind CCE, 4995 bool RequireInt) { 4996 assert(S.getLangOpts().CPlusPlus11 && 4997 "converted constant expression outside C++11"); 4998 4999 if (checkPlaceholderForOverload(S, From)) 5000 return ExprError(); 5001 5002 // C++1z [expr.const]p3: 5003 // A converted constant expression of type T is an expression, 5004 // implicitly converted to type T, where the converted 5005 // expression is a constant expression and the implicit conversion 5006 // sequence contains only [... list of conversions ...]. 5007 ImplicitConversionSequence ICS = 5008 TryCopyInitialization(S, From, T, 5009 /*SuppressUserConversions=*/false, 5010 /*InOverloadResolution=*/false, 5011 /*AllowObjcWritebackConversion=*/false, 5012 /*AllowExplicit=*/false); 5013 StandardConversionSequence *SCS = nullptr; 5014 switch (ICS.getKind()) { 5015 case ImplicitConversionSequence::StandardConversion: 5016 SCS = &ICS.Standard; 5017 break; 5018 case ImplicitConversionSequence::UserDefinedConversion: 5019 // We are converting to a non-class type, so the Before sequence 5020 // must be trivial. 5021 SCS = &ICS.UserDefined.After; 5022 break; 5023 case ImplicitConversionSequence::AmbiguousConversion: 5024 case ImplicitConversionSequence::BadConversion: 5025 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5026 return S.Diag(From->getLocStart(), 5027 diag::err_typecheck_converted_constant_expression) 5028 << From->getType() << From->getSourceRange() << T; 5029 return ExprError(); 5030 5031 case ImplicitConversionSequence::EllipsisConversion: 5032 llvm_unreachable("ellipsis conversion in converted constant expression"); 5033 } 5034 5035 // Check that we would only use permitted conversions. 5036 if (!CheckConvertedConstantConversions(S, *SCS)) { 5037 return S.Diag(From->getLocStart(), 5038 diag::err_typecheck_converted_constant_expression_disallowed) 5039 << From->getType() << From->getSourceRange() << T; 5040 } 5041 // [...] and where the reference binding (if any) binds directly. 5042 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5043 return S.Diag(From->getLocStart(), 5044 diag::err_typecheck_converted_constant_expression_indirect) 5045 << From->getType() << From->getSourceRange() << T; 5046 } 5047 5048 ExprResult Result = 5049 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5050 if (Result.isInvalid()) 5051 return Result; 5052 5053 // Check for a narrowing implicit conversion. 5054 APValue PreNarrowingValue; 5055 QualType PreNarrowingType; 5056 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5057 PreNarrowingType)) { 5058 case NK_Variable_Narrowing: 5059 // Implicit conversion to a narrower type, and the value is not a constant 5060 // expression. We'll diagnose this in a moment. 5061 case NK_Not_Narrowing: 5062 break; 5063 5064 case NK_Constant_Narrowing: 5065 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5066 << CCE << /*Constant*/1 5067 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5068 break; 5069 5070 case NK_Type_Narrowing: 5071 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5072 << CCE << /*Constant*/0 << From->getType() << T; 5073 break; 5074 } 5075 5076 // Check the expression is a constant expression. 5077 SmallVector<PartialDiagnosticAt, 8> Notes; 5078 Expr::EvalResult Eval; 5079 Eval.Diag = &Notes; 5080 5081 if ((T->isReferenceType() 5082 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5083 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5084 (RequireInt && !Eval.Val.isInt())) { 5085 // The expression can't be folded, so we can't keep it at this position in 5086 // the AST. 5087 Result = ExprError(); 5088 } else { 5089 Value = Eval.Val; 5090 5091 if (Notes.empty()) { 5092 // It's a constant expression. 5093 return Result; 5094 } 5095 } 5096 5097 // It's not a constant expression. Produce an appropriate diagnostic. 5098 if (Notes.size() == 1 && 5099 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5100 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5101 else { 5102 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5103 << CCE << From->getSourceRange(); 5104 for (unsigned I = 0; I < Notes.size(); ++I) 5105 S.Diag(Notes[I].first, Notes[I].second); 5106 } 5107 return ExprError(); 5108 } 5109 5110 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5111 APValue &Value, CCEKind CCE) { 5112 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5113 } 5114 5115 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5116 llvm::APSInt &Value, 5117 CCEKind CCE) { 5118 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5119 5120 APValue V; 5121 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5122 if (!R.isInvalid()) 5123 Value = V.getInt(); 5124 return R; 5125 } 5126 5127 5128 /// dropPointerConversions - If the given standard conversion sequence 5129 /// involves any pointer conversions, remove them. This may change 5130 /// the result type of the conversion sequence. 5131 static void dropPointerConversion(StandardConversionSequence &SCS) { 5132 if (SCS.Second == ICK_Pointer_Conversion) { 5133 SCS.Second = ICK_Identity; 5134 SCS.Third = ICK_Identity; 5135 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5136 } 5137 } 5138 5139 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5140 /// convert the expression From to an Objective-C pointer type. 5141 static ImplicitConversionSequence 5142 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5143 // Do an implicit conversion to 'id'. 5144 QualType Ty = S.Context.getObjCIdType(); 5145 ImplicitConversionSequence ICS 5146 = TryImplicitConversion(S, From, Ty, 5147 // FIXME: Are these flags correct? 5148 /*SuppressUserConversions=*/false, 5149 /*AllowExplicit=*/true, 5150 /*InOverloadResolution=*/false, 5151 /*CStyle=*/false, 5152 /*AllowObjCWritebackConversion=*/false, 5153 /*AllowObjCConversionOnExplicit=*/true); 5154 5155 // Strip off any final conversions to 'id'. 5156 switch (ICS.getKind()) { 5157 case ImplicitConversionSequence::BadConversion: 5158 case ImplicitConversionSequence::AmbiguousConversion: 5159 case ImplicitConversionSequence::EllipsisConversion: 5160 break; 5161 5162 case ImplicitConversionSequence::UserDefinedConversion: 5163 dropPointerConversion(ICS.UserDefined.After); 5164 break; 5165 5166 case ImplicitConversionSequence::StandardConversion: 5167 dropPointerConversion(ICS.Standard); 5168 break; 5169 } 5170 5171 return ICS; 5172 } 5173 5174 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5175 /// conversion of the expression From to an Objective-C pointer type. 5176 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5177 if (checkPlaceholderForOverload(*this, From)) 5178 return ExprError(); 5179 5180 QualType Ty = Context.getObjCIdType(); 5181 ImplicitConversionSequence ICS = 5182 TryContextuallyConvertToObjCPointer(*this, From); 5183 if (!ICS.isBad()) 5184 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5185 return ExprError(); 5186 } 5187 5188 /// Determine whether the provided type is an integral type, or an enumeration 5189 /// type of a permitted flavor. 5190 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5191 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5192 : T->isIntegralOrUnscopedEnumerationType(); 5193 } 5194 5195 static ExprResult 5196 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5197 Sema::ContextualImplicitConverter &Converter, 5198 QualType T, UnresolvedSetImpl &ViableConversions) { 5199 5200 if (Converter.Suppress) 5201 return ExprError(); 5202 5203 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5204 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5205 CXXConversionDecl *Conv = 5206 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5207 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5208 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5209 } 5210 return From; 5211 } 5212 5213 static bool 5214 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5215 Sema::ContextualImplicitConverter &Converter, 5216 QualType T, bool HadMultipleCandidates, 5217 UnresolvedSetImpl &ExplicitConversions) { 5218 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5219 DeclAccessPair Found = ExplicitConversions[0]; 5220 CXXConversionDecl *Conversion = 5221 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5222 5223 // The user probably meant to invoke the given explicit 5224 // conversion; use it. 5225 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5226 std::string TypeStr; 5227 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5228 5229 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5230 << FixItHint::CreateInsertion(From->getLocStart(), 5231 "static_cast<" + TypeStr + ">(") 5232 << FixItHint::CreateInsertion( 5233 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5234 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5235 5236 // If we aren't in a SFINAE context, build a call to the 5237 // explicit conversion function. 5238 if (SemaRef.isSFINAEContext()) 5239 return true; 5240 5241 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5242 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5243 HadMultipleCandidates); 5244 if (Result.isInvalid()) 5245 return true; 5246 // Record usage of conversion in an implicit cast. 5247 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5248 CK_UserDefinedConversion, Result.get(), 5249 nullptr, Result.get()->getValueKind()); 5250 } 5251 return false; 5252 } 5253 5254 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5255 Sema::ContextualImplicitConverter &Converter, 5256 QualType T, bool HadMultipleCandidates, 5257 DeclAccessPair &Found) { 5258 CXXConversionDecl *Conversion = 5259 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5260 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5261 5262 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5263 if (!Converter.SuppressConversion) { 5264 if (SemaRef.isSFINAEContext()) 5265 return true; 5266 5267 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5268 << From->getSourceRange(); 5269 } 5270 5271 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5272 HadMultipleCandidates); 5273 if (Result.isInvalid()) 5274 return true; 5275 // Record usage of conversion in an implicit cast. 5276 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5277 CK_UserDefinedConversion, Result.get(), 5278 nullptr, Result.get()->getValueKind()); 5279 return false; 5280 } 5281 5282 static ExprResult finishContextualImplicitConversion( 5283 Sema &SemaRef, SourceLocation Loc, Expr *From, 5284 Sema::ContextualImplicitConverter &Converter) { 5285 if (!Converter.match(From->getType()) && !Converter.Suppress) 5286 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5287 << From->getSourceRange(); 5288 5289 return SemaRef.DefaultLvalueConversion(From); 5290 } 5291 5292 static void 5293 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5294 UnresolvedSetImpl &ViableConversions, 5295 OverloadCandidateSet &CandidateSet) { 5296 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5297 DeclAccessPair FoundDecl = ViableConversions[I]; 5298 NamedDecl *D = FoundDecl.getDecl(); 5299 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5300 if (isa<UsingShadowDecl>(D)) 5301 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5302 5303 CXXConversionDecl *Conv; 5304 FunctionTemplateDecl *ConvTemplate; 5305 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5306 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5307 else 5308 Conv = cast<CXXConversionDecl>(D); 5309 5310 if (ConvTemplate) 5311 SemaRef.AddTemplateConversionCandidate( 5312 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5313 /*AllowObjCConversionOnExplicit=*/false); 5314 else 5315 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5316 ToType, CandidateSet, 5317 /*AllowObjCConversionOnExplicit=*/false); 5318 } 5319 } 5320 5321 /// \brief Attempt to convert the given expression to a type which is accepted 5322 /// by the given converter. 5323 /// 5324 /// This routine will attempt to convert an expression of class type to a 5325 /// type accepted by the specified converter. In C++11 and before, the class 5326 /// must have a single non-explicit conversion function converting to a matching 5327 /// type. In C++1y, there can be multiple such conversion functions, but only 5328 /// one target type. 5329 /// 5330 /// \param Loc The source location of the construct that requires the 5331 /// conversion. 5332 /// 5333 /// \param From The expression we're converting from. 5334 /// 5335 /// \param Converter Used to control and diagnose the conversion process. 5336 /// 5337 /// \returns The expression, converted to an integral or enumeration type if 5338 /// successful. 5339 ExprResult Sema::PerformContextualImplicitConversion( 5340 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5341 // We can't perform any more checking for type-dependent expressions. 5342 if (From->isTypeDependent()) 5343 return From; 5344 5345 // Process placeholders immediately. 5346 if (From->hasPlaceholderType()) { 5347 ExprResult result = CheckPlaceholderExpr(From); 5348 if (result.isInvalid()) 5349 return result; 5350 From = result.get(); 5351 } 5352 5353 // If the expression already has a matching type, we're golden. 5354 QualType T = From->getType(); 5355 if (Converter.match(T)) 5356 return DefaultLvalueConversion(From); 5357 5358 // FIXME: Check for missing '()' if T is a function type? 5359 5360 // We can only perform contextual implicit conversions on objects of class 5361 // type. 5362 const RecordType *RecordTy = T->getAs<RecordType>(); 5363 if (!RecordTy || !getLangOpts().CPlusPlus) { 5364 if (!Converter.Suppress) 5365 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5366 return From; 5367 } 5368 5369 // We must have a complete class type. 5370 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5371 ContextualImplicitConverter &Converter; 5372 Expr *From; 5373 5374 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5375 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5376 5377 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5378 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5379 } 5380 } IncompleteDiagnoser(Converter, From); 5381 5382 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5383 return From; 5384 5385 // Look for a conversion to an integral or enumeration type. 5386 UnresolvedSet<4> 5387 ViableConversions; // These are *potentially* viable in C++1y. 5388 UnresolvedSet<4> ExplicitConversions; 5389 const auto &Conversions = 5390 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5391 5392 bool HadMultipleCandidates = 5393 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5394 5395 // To check that there is only one target type, in C++1y: 5396 QualType ToType; 5397 bool HasUniqueTargetType = true; 5398 5399 // Collect explicit or viable (potentially in C++1y) conversions. 5400 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5401 NamedDecl *D = (*I)->getUnderlyingDecl(); 5402 CXXConversionDecl *Conversion; 5403 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5404 if (ConvTemplate) { 5405 if (getLangOpts().CPlusPlus14) 5406 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5407 else 5408 continue; // C++11 does not consider conversion operator templates(?). 5409 } else 5410 Conversion = cast<CXXConversionDecl>(D); 5411 5412 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5413 "Conversion operator templates are considered potentially " 5414 "viable in C++1y"); 5415 5416 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5417 if (Converter.match(CurToType) || ConvTemplate) { 5418 5419 if (Conversion->isExplicit()) { 5420 // FIXME: For C++1y, do we need this restriction? 5421 // cf. diagnoseNoViableConversion() 5422 if (!ConvTemplate) 5423 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5424 } else { 5425 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5426 if (ToType.isNull()) 5427 ToType = CurToType.getUnqualifiedType(); 5428 else if (HasUniqueTargetType && 5429 (CurToType.getUnqualifiedType() != ToType)) 5430 HasUniqueTargetType = false; 5431 } 5432 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5433 } 5434 } 5435 } 5436 5437 if (getLangOpts().CPlusPlus14) { 5438 // C++1y [conv]p6: 5439 // ... An expression e of class type E appearing in such a context 5440 // is said to be contextually implicitly converted to a specified 5441 // type T and is well-formed if and only if e can be implicitly 5442 // converted to a type T that is determined as follows: E is searched 5443 // for conversion functions whose return type is cv T or reference to 5444 // cv T such that T is allowed by the context. There shall be 5445 // exactly one such T. 5446 5447 // If no unique T is found: 5448 if (ToType.isNull()) { 5449 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5450 HadMultipleCandidates, 5451 ExplicitConversions)) 5452 return ExprError(); 5453 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5454 } 5455 5456 // If more than one unique Ts are found: 5457 if (!HasUniqueTargetType) 5458 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5459 ViableConversions); 5460 5461 // If one unique T is found: 5462 // First, build a candidate set from the previously recorded 5463 // potentially viable conversions. 5464 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5465 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5466 CandidateSet); 5467 5468 // Then, perform overload resolution over the candidate set. 5469 OverloadCandidateSet::iterator Best; 5470 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5471 case OR_Success: { 5472 // Apply this conversion. 5473 DeclAccessPair Found = 5474 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5475 if (recordConversion(*this, Loc, From, Converter, T, 5476 HadMultipleCandidates, Found)) 5477 return ExprError(); 5478 break; 5479 } 5480 case OR_Ambiguous: 5481 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5482 ViableConversions); 5483 case OR_No_Viable_Function: 5484 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5485 HadMultipleCandidates, 5486 ExplicitConversions)) 5487 return ExprError(); 5488 // fall through 'OR_Deleted' case. 5489 case OR_Deleted: 5490 // We'll complain below about a non-integral condition type. 5491 break; 5492 } 5493 } else { 5494 switch (ViableConversions.size()) { 5495 case 0: { 5496 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5497 HadMultipleCandidates, 5498 ExplicitConversions)) 5499 return ExprError(); 5500 5501 // We'll complain below about a non-integral condition type. 5502 break; 5503 } 5504 case 1: { 5505 // Apply this conversion. 5506 DeclAccessPair Found = ViableConversions[0]; 5507 if (recordConversion(*this, Loc, From, Converter, T, 5508 HadMultipleCandidates, Found)) 5509 return ExprError(); 5510 break; 5511 } 5512 default: 5513 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5514 ViableConversions); 5515 } 5516 } 5517 5518 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5519 } 5520 5521 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5522 /// an acceptable non-member overloaded operator for a call whose 5523 /// arguments have types T1 (and, if non-empty, T2). This routine 5524 /// implements the check in C++ [over.match.oper]p3b2 concerning 5525 /// enumeration types. 5526 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5527 FunctionDecl *Fn, 5528 ArrayRef<Expr *> Args) { 5529 QualType T1 = Args[0]->getType(); 5530 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5531 5532 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5533 return true; 5534 5535 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5536 return true; 5537 5538 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5539 if (Proto->getNumParams() < 1) 5540 return false; 5541 5542 if (T1->isEnumeralType()) { 5543 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5544 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5545 return true; 5546 } 5547 5548 if (Proto->getNumParams() < 2) 5549 return false; 5550 5551 if (!T2.isNull() && T2->isEnumeralType()) { 5552 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5553 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5554 return true; 5555 } 5556 5557 return false; 5558 } 5559 5560 /// AddOverloadCandidate - Adds the given function to the set of 5561 /// candidate functions, using the given function call arguments. If 5562 /// @p SuppressUserConversions, then don't allow user-defined 5563 /// conversions via constructors or conversion operators. 5564 /// 5565 /// \param PartialOverloading true if we are performing "partial" overloading 5566 /// based on an incomplete set of function arguments. This feature is used by 5567 /// code completion. 5568 void 5569 Sema::AddOverloadCandidate(FunctionDecl *Function, 5570 DeclAccessPair FoundDecl, 5571 ArrayRef<Expr *> Args, 5572 OverloadCandidateSet &CandidateSet, 5573 bool SuppressUserConversions, 5574 bool PartialOverloading, 5575 bool AllowExplicit) { 5576 const FunctionProtoType *Proto 5577 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5578 assert(Proto && "Functions without a prototype cannot be overloaded"); 5579 assert(!Function->getDescribedFunctionTemplate() && 5580 "Use AddTemplateOverloadCandidate for function templates"); 5581 5582 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5583 if (!isa<CXXConstructorDecl>(Method)) { 5584 // If we get here, it's because we're calling a member function 5585 // that is named without a member access expression (e.g., 5586 // "this->f") that was either written explicitly or created 5587 // implicitly. This can happen with a qualified call to a member 5588 // function, e.g., X::f(). We use an empty type for the implied 5589 // object argument (C++ [over.call.func]p3), and the acting context 5590 // is irrelevant. 5591 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5592 QualType(), Expr::Classification::makeSimpleLValue(), 5593 Args, CandidateSet, SuppressUserConversions, 5594 PartialOverloading); 5595 return; 5596 } 5597 // We treat a constructor like a non-member function, since its object 5598 // argument doesn't participate in overload resolution. 5599 } 5600 5601 if (!CandidateSet.isNewCandidate(Function)) 5602 return; 5603 5604 // C++ [over.match.oper]p3: 5605 // if no operand has a class type, only those non-member functions in the 5606 // lookup set that have a first parameter of type T1 or "reference to 5607 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5608 // is a right operand) a second parameter of type T2 or "reference to 5609 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5610 // candidate functions. 5611 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5612 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5613 return; 5614 5615 // C++11 [class.copy]p11: [DR1402] 5616 // A defaulted move constructor that is defined as deleted is ignored by 5617 // overload resolution. 5618 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5619 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5620 Constructor->isMoveConstructor()) 5621 return; 5622 5623 // Overload resolution is always an unevaluated context. 5624 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5625 5626 // Add this candidate 5627 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5628 Candidate.FoundDecl = FoundDecl; 5629 Candidate.Function = Function; 5630 Candidate.Viable = true; 5631 Candidate.IsSurrogate = false; 5632 Candidate.IgnoreObjectArgument = false; 5633 Candidate.ExplicitCallArguments = Args.size(); 5634 5635 if (Constructor) { 5636 // C++ [class.copy]p3: 5637 // A member function template is never instantiated to perform the copy 5638 // of a class object to an object of its class type. 5639 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5640 if (Args.size() == 1 && 5641 Constructor->isSpecializationCopyingObject() && 5642 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5643 IsDerivedFrom(Args[0]->getType(), ClassType))) { 5644 Candidate.Viable = false; 5645 Candidate.FailureKind = ovl_fail_illegal_constructor; 5646 return; 5647 } 5648 } 5649 5650 unsigned NumParams = Proto->getNumParams(); 5651 5652 // (C++ 13.3.2p2): A candidate function having fewer than m 5653 // parameters is viable only if it has an ellipsis in its parameter 5654 // list (8.3.5). 5655 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5656 !Proto->isVariadic()) { 5657 Candidate.Viable = false; 5658 Candidate.FailureKind = ovl_fail_too_many_arguments; 5659 return; 5660 } 5661 5662 // (C++ 13.3.2p2): A candidate function having more than m parameters 5663 // is viable only if the (m+1)st parameter has a default argument 5664 // (8.3.6). For the purposes of overload resolution, the 5665 // parameter list is truncated on the right, so that there are 5666 // exactly m parameters. 5667 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5668 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5669 // Not enough arguments. 5670 Candidate.Viable = false; 5671 Candidate.FailureKind = ovl_fail_too_few_arguments; 5672 return; 5673 } 5674 5675 // (CUDA B.1): Check for invalid calls between targets. 5676 if (getLangOpts().CUDA) 5677 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5678 // Skip the check for callers that are implicit members, because in this 5679 // case we may not yet know what the member's target is; the target is 5680 // inferred for the member automatically, based on the bases and fields of 5681 // the class. 5682 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5683 Candidate.Viable = false; 5684 Candidate.FailureKind = ovl_fail_bad_target; 5685 return; 5686 } 5687 5688 // Determine the implicit conversion sequences for each of the 5689 // arguments. 5690 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5691 if (ArgIdx < NumParams) { 5692 // (C++ 13.3.2p3): for F to be a viable function, there shall 5693 // exist for each argument an implicit conversion sequence 5694 // (13.3.3.1) that converts that argument to the corresponding 5695 // parameter of F. 5696 QualType ParamType = Proto->getParamType(ArgIdx); 5697 Candidate.Conversions[ArgIdx] 5698 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5699 SuppressUserConversions, 5700 /*InOverloadResolution=*/true, 5701 /*AllowObjCWritebackConversion=*/ 5702 getLangOpts().ObjCAutoRefCount, 5703 AllowExplicit); 5704 if (Candidate.Conversions[ArgIdx].isBad()) { 5705 Candidate.Viable = false; 5706 Candidate.FailureKind = ovl_fail_bad_conversion; 5707 return; 5708 } 5709 } else { 5710 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5711 // argument for which there is no corresponding parameter is 5712 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5713 Candidate.Conversions[ArgIdx].setEllipsis(); 5714 } 5715 } 5716 5717 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5718 Candidate.Viable = false; 5719 Candidate.FailureKind = ovl_fail_enable_if; 5720 Candidate.DeductionFailure.Data = FailedAttr; 5721 return; 5722 } 5723 } 5724 5725 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5726 bool IsInstance) { 5727 SmallVector<ObjCMethodDecl*, 4> Methods; 5728 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5729 return nullptr; 5730 5731 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5732 bool Match = true; 5733 ObjCMethodDecl *Method = Methods[b]; 5734 unsigned NumNamedArgs = Sel.getNumArgs(); 5735 // Method might have more arguments than selector indicates. This is due 5736 // to addition of c-style arguments in method. 5737 if (Method->param_size() > NumNamedArgs) 5738 NumNamedArgs = Method->param_size(); 5739 if (Args.size() < NumNamedArgs) 5740 continue; 5741 5742 for (unsigned i = 0; i < NumNamedArgs; i++) { 5743 // We can't do any type-checking on a type-dependent argument. 5744 if (Args[i]->isTypeDependent()) { 5745 Match = false; 5746 break; 5747 } 5748 5749 ParmVarDecl *param = Method->parameters()[i]; 5750 Expr *argExpr = Args[i]; 5751 assert(argExpr && "SelectBestMethod(): missing expression"); 5752 5753 // Strip the unbridged-cast placeholder expression off unless it's 5754 // a consumed argument. 5755 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5756 !param->hasAttr<CFConsumedAttr>()) 5757 argExpr = stripARCUnbridgedCast(argExpr); 5758 5759 // If the parameter is __unknown_anytype, move on to the next method. 5760 if (param->getType() == Context.UnknownAnyTy) { 5761 Match = false; 5762 break; 5763 } 5764 5765 ImplicitConversionSequence ConversionState 5766 = TryCopyInitialization(*this, argExpr, param->getType(), 5767 /*SuppressUserConversions*/false, 5768 /*InOverloadResolution=*/true, 5769 /*AllowObjCWritebackConversion=*/ 5770 getLangOpts().ObjCAutoRefCount, 5771 /*AllowExplicit*/false); 5772 if (ConversionState.isBad()) { 5773 Match = false; 5774 break; 5775 } 5776 } 5777 // Promote additional arguments to variadic methods. 5778 if (Match && Method->isVariadic()) { 5779 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5780 if (Args[i]->isTypeDependent()) { 5781 Match = false; 5782 break; 5783 } 5784 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5785 nullptr); 5786 if (Arg.isInvalid()) { 5787 Match = false; 5788 break; 5789 } 5790 } 5791 } else { 5792 // Check for extra arguments to non-variadic methods. 5793 if (Args.size() != NumNamedArgs) 5794 Match = false; 5795 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5796 // Special case when selectors have no argument. In this case, select 5797 // one with the most general result type of 'id'. 5798 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5799 QualType ReturnT = Methods[b]->getReturnType(); 5800 if (ReturnT->isObjCIdType()) 5801 return Methods[b]; 5802 } 5803 } 5804 } 5805 5806 if (Match) 5807 return Method; 5808 } 5809 return nullptr; 5810 } 5811 5812 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); } 5813 5814 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5815 bool MissingImplicitThis) { 5816 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but 5817 // we need to find the first failing one. 5818 if (!Function->hasAttrs()) 5819 return nullptr; 5820 AttrVec Attrs = Function->getAttrs(); 5821 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(), 5822 IsNotEnableIfAttr); 5823 if (Attrs.begin() == E) 5824 return nullptr; 5825 std::reverse(Attrs.begin(), E); 5826 5827 SFINAETrap Trap(*this); 5828 5829 // Convert the arguments. 5830 SmallVector<Expr *, 16> ConvertedArgs; 5831 bool InitializationFailed = false; 5832 bool ContainsValueDependentExpr = false; 5833 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5834 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5835 !cast<CXXMethodDecl>(Function)->isStatic() && 5836 !isa<CXXConstructorDecl>(Function)) { 5837 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5838 ExprResult R = 5839 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5840 Method, Method); 5841 if (R.isInvalid()) { 5842 InitializationFailed = true; 5843 break; 5844 } 5845 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5846 ConvertedArgs.push_back(R.get()); 5847 } else { 5848 ExprResult R = 5849 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5850 Context, 5851 Function->getParamDecl(i)), 5852 SourceLocation(), 5853 Args[i]); 5854 if (R.isInvalid()) { 5855 InitializationFailed = true; 5856 break; 5857 } 5858 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5859 ConvertedArgs.push_back(R.get()); 5860 } 5861 } 5862 5863 if (InitializationFailed || Trap.hasErrorOccurred()) 5864 return cast<EnableIfAttr>(Attrs[0]); 5865 5866 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) { 5867 APValue Result; 5868 EnableIfAttr *EIA = cast<EnableIfAttr>(*I); 5869 if (EIA->getCond()->isValueDependent()) { 5870 // Don't even try now, we'll examine it after instantiation. 5871 continue; 5872 } 5873 5874 if (!EIA->getCond()->EvaluateWithSubstitution( 5875 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) { 5876 if (!ContainsValueDependentExpr) 5877 return EIA; 5878 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) { 5879 return EIA; 5880 } 5881 } 5882 return nullptr; 5883 } 5884 5885 /// \brief Add all of the function declarations in the given function set to 5886 /// the overload candidate set. 5887 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5888 ArrayRef<Expr *> Args, 5889 OverloadCandidateSet& CandidateSet, 5890 TemplateArgumentListInfo *ExplicitTemplateArgs, 5891 bool SuppressUserConversions, 5892 bool PartialOverloading) { 5893 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5894 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5895 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5896 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5897 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5898 cast<CXXMethodDecl>(FD)->getParent(), 5899 Args[0]->getType(), Args[0]->Classify(Context), 5900 Args.slice(1), CandidateSet, 5901 SuppressUserConversions, PartialOverloading); 5902 else 5903 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5904 SuppressUserConversions, PartialOverloading); 5905 } else { 5906 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5907 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5908 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5909 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5910 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5911 ExplicitTemplateArgs, 5912 Args[0]->getType(), 5913 Args[0]->Classify(Context), Args.slice(1), 5914 CandidateSet, SuppressUserConversions, 5915 PartialOverloading); 5916 else 5917 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5918 ExplicitTemplateArgs, Args, 5919 CandidateSet, SuppressUserConversions, 5920 PartialOverloading); 5921 } 5922 } 5923 } 5924 5925 /// AddMethodCandidate - Adds a named decl (which is some kind of 5926 /// method) as a method candidate to the given overload set. 5927 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5928 QualType ObjectType, 5929 Expr::Classification ObjectClassification, 5930 ArrayRef<Expr *> Args, 5931 OverloadCandidateSet& CandidateSet, 5932 bool SuppressUserConversions) { 5933 NamedDecl *Decl = FoundDecl.getDecl(); 5934 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5935 5936 if (isa<UsingShadowDecl>(Decl)) 5937 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5938 5939 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5940 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5941 "Expected a member function template"); 5942 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5943 /*ExplicitArgs*/ nullptr, 5944 ObjectType, ObjectClassification, 5945 Args, CandidateSet, 5946 SuppressUserConversions); 5947 } else { 5948 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5949 ObjectType, ObjectClassification, 5950 Args, 5951 CandidateSet, SuppressUserConversions); 5952 } 5953 } 5954 5955 /// AddMethodCandidate - Adds the given C++ member function to the set 5956 /// of candidate functions, using the given function call arguments 5957 /// and the object argument (@c Object). For example, in a call 5958 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5959 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5960 /// allow user-defined conversions via constructors or conversion 5961 /// operators. 5962 void 5963 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5964 CXXRecordDecl *ActingContext, QualType ObjectType, 5965 Expr::Classification ObjectClassification, 5966 ArrayRef<Expr *> Args, 5967 OverloadCandidateSet &CandidateSet, 5968 bool SuppressUserConversions, 5969 bool PartialOverloading) { 5970 const FunctionProtoType *Proto 5971 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5972 assert(Proto && "Methods without a prototype cannot be overloaded"); 5973 assert(!isa<CXXConstructorDecl>(Method) && 5974 "Use AddOverloadCandidate for constructors"); 5975 5976 if (!CandidateSet.isNewCandidate(Method)) 5977 return; 5978 5979 // C++11 [class.copy]p23: [DR1402] 5980 // A defaulted move assignment operator that is defined as deleted is 5981 // ignored by overload resolution. 5982 if (Method->isDefaulted() && Method->isDeleted() && 5983 Method->isMoveAssignmentOperator()) 5984 return; 5985 5986 // Overload resolution is always an unevaluated context. 5987 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5988 5989 // Add this candidate 5990 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5991 Candidate.FoundDecl = FoundDecl; 5992 Candidate.Function = Method; 5993 Candidate.IsSurrogate = false; 5994 Candidate.IgnoreObjectArgument = false; 5995 Candidate.ExplicitCallArguments = Args.size(); 5996 5997 unsigned NumParams = Proto->getNumParams(); 5998 5999 // (C++ 13.3.2p2): A candidate function having fewer than m 6000 // parameters is viable only if it has an ellipsis in its parameter 6001 // list (8.3.5). 6002 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6003 !Proto->isVariadic()) { 6004 Candidate.Viable = false; 6005 Candidate.FailureKind = ovl_fail_too_many_arguments; 6006 return; 6007 } 6008 6009 // (C++ 13.3.2p2): A candidate function having more than m parameters 6010 // is viable only if the (m+1)st parameter has a default argument 6011 // (8.3.6). For the purposes of overload resolution, the 6012 // parameter list is truncated on the right, so that there are 6013 // exactly m parameters. 6014 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6015 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6016 // Not enough arguments. 6017 Candidate.Viable = false; 6018 Candidate.FailureKind = ovl_fail_too_few_arguments; 6019 return; 6020 } 6021 6022 Candidate.Viable = true; 6023 6024 if (Method->isStatic() || ObjectType.isNull()) 6025 // The implicit object argument is ignored. 6026 Candidate.IgnoreObjectArgument = true; 6027 else { 6028 // Determine the implicit conversion sequence for the object 6029 // parameter. 6030 Candidate.Conversions[0] 6031 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 6032 Method, ActingContext); 6033 if (Candidate.Conversions[0].isBad()) { 6034 Candidate.Viable = false; 6035 Candidate.FailureKind = ovl_fail_bad_conversion; 6036 return; 6037 } 6038 } 6039 6040 // (CUDA B.1): Check for invalid calls between targets. 6041 if (getLangOpts().CUDA) 6042 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6043 if (CheckCUDATarget(Caller, Method)) { 6044 Candidate.Viable = false; 6045 Candidate.FailureKind = ovl_fail_bad_target; 6046 return; 6047 } 6048 6049 // Determine the implicit conversion sequences for each of the 6050 // arguments. 6051 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6052 if (ArgIdx < NumParams) { 6053 // (C++ 13.3.2p3): for F to be a viable function, there shall 6054 // exist for each argument an implicit conversion sequence 6055 // (13.3.3.1) that converts that argument to the corresponding 6056 // parameter of F. 6057 QualType ParamType = Proto->getParamType(ArgIdx); 6058 Candidate.Conversions[ArgIdx + 1] 6059 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6060 SuppressUserConversions, 6061 /*InOverloadResolution=*/true, 6062 /*AllowObjCWritebackConversion=*/ 6063 getLangOpts().ObjCAutoRefCount); 6064 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6065 Candidate.Viable = false; 6066 Candidate.FailureKind = ovl_fail_bad_conversion; 6067 return; 6068 } 6069 } else { 6070 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6071 // argument for which there is no corresponding parameter is 6072 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6073 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6074 } 6075 } 6076 6077 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6078 Candidate.Viable = false; 6079 Candidate.FailureKind = ovl_fail_enable_if; 6080 Candidate.DeductionFailure.Data = FailedAttr; 6081 return; 6082 } 6083 } 6084 6085 /// \brief Add a C++ member function template as a candidate to the candidate 6086 /// set, using template argument deduction to produce an appropriate member 6087 /// function template specialization. 6088 void 6089 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6090 DeclAccessPair FoundDecl, 6091 CXXRecordDecl *ActingContext, 6092 TemplateArgumentListInfo *ExplicitTemplateArgs, 6093 QualType ObjectType, 6094 Expr::Classification ObjectClassification, 6095 ArrayRef<Expr *> Args, 6096 OverloadCandidateSet& CandidateSet, 6097 bool SuppressUserConversions, 6098 bool PartialOverloading) { 6099 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6100 return; 6101 6102 // C++ [over.match.funcs]p7: 6103 // In each case where a candidate is a function template, candidate 6104 // function template specializations are generated using template argument 6105 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6106 // candidate functions in the usual way.113) A given name can refer to one 6107 // or more function templates and also to a set of overloaded non-template 6108 // functions. In such a case, the candidate functions generated from each 6109 // function template are combined with the set of non-template candidate 6110 // functions. 6111 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6112 FunctionDecl *Specialization = nullptr; 6113 if (TemplateDeductionResult Result 6114 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6115 Specialization, Info, PartialOverloading)) { 6116 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6117 Candidate.FoundDecl = FoundDecl; 6118 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6119 Candidate.Viable = false; 6120 Candidate.FailureKind = ovl_fail_bad_deduction; 6121 Candidate.IsSurrogate = false; 6122 Candidate.IgnoreObjectArgument = false; 6123 Candidate.ExplicitCallArguments = Args.size(); 6124 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6125 Info); 6126 return; 6127 } 6128 6129 // Add the function template specialization produced by template argument 6130 // deduction as a candidate. 6131 assert(Specialization && "Missing member function template specialization?"); 6132 assert(isa<CXXMethodDecl>(Specialization) && 6133 "Specialization is not a member function?"); 6134 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6135 ActingContext, ObjectType, ObjectClassification, Args, 6136 CandidateSet, SuppressUserConversions, PartialOverloading); 6137 } 6138 6139 /// \brief Add a C++ function template specialization as a candidate 6140 /// in the candidate set, using template argument deduction to produce 6141 /// an appropriate function template specialization. 6142 void 6143 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6144 DeclAccessPair FoundDecl, 6145 TemplateArgumentListInfo *ExplicitTemplateArgs, 6146 ArrayRef<Expr *> Args, 6147 OverloadCandidateSet& CandidateSet, 6148 bool SuppressUserConversions, 6149 bool PartialOverloading) { 6150 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6151 return; 6152 6153 // C++ [over.match.funcs]p7: 6154 // In each case where a candidate is a function template, candidate 6155 // function template specializations are generated using template argument 6156 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6157 // candidate functions in the usual way.113) A given name can refer to one 6158 // or more function templates and also to a set of overloaded non-template 6159 // functions. In such a case, the candidate functions generated from each 6160 // function template are combined with the set of non-template candidate 6161 // functions. 6162 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6163 FunctionDecl *Specialization = nullptr; 6164 if (TemplateDeductionResult Result 6165 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6166 Specialization, Info, PartialOverloading)) { 6167 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6168 Candidate.FoundDecl = FoundDecl; 6169 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6170 Candidate.Viable = false; 6171 Candidate.FailureKind = ovl_fail_bad_deduction; 6172 Candidate.IsSurrogate = false; 6173 Candidate.IgnoreObjectArgument = false; 6174 Candidate.ExplicitCallArguments = Args.size(); 6175 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6176 Info); 6177 return; 6178 } 6179 6180 // Add the function template specialization produced by template argument 6181 // deduction as a candidate. 6182 assert(Specialization && "Missing function template specialization?"); 6183 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6184 SuppressUserConversions, PartialOverloading); 6185 } 6186 6187 /// Determine whether this is an allowable conversion from the result 6188 /// of an explicit conversion operator to the expected type, per C++ 6189 /// [over.match.conv]p1 and [over.match.ref]p1. 6190 /// 6191 /// \param ConvType The return type of the conversion function. 6192 /// 6193 /// \param ToType The type we are converting to. 6194 /// 6195 /// \param AllowObjCPointerConversion Allow a conversion from one 6196 /// Objective-C pointer to another. 6197 /// 6198 /// \returns true if the conversion is allowable, false otherwise. 6199 static bool isAllowableExplicitConversion(Sema &S, 6200 QualType ConvType, QualType ToType, 6201 bool AllowObjCPointerConversion) { 6202 QualType ToNonRefType = ToType.getNonReferenceType(); 6203 6204 // Easy case: the types are the same. 6205 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6206 return true; 6207 6208 // Allow qualification conversions. 6209 bool ObjCLifetimeConversion; 6210 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6211 ObjCLifetimeConversion)) 6212 return true; 6213 6214 // If we're not allowed to consider Objective-C pointer conversions, 6215 // we're done. 6216 if (!AllowObjCPointerConversion) 6217 return false; 6218 6219 // Is this an Objective-C pointer conversion? 6220 bool IncompatibleObjC = false; 6221 QualType ConvertedType; 6222 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6223 IncompatibleObjC); 6224 } 6225 6226 /// AddConversionCandidate - Add a C++ conversion function as a 6227 /// candidate in the candidate set (C++ [over.match.conv], 6228 /// C++ [over.match.copy]). From is the expression we're converting from, 6229 /// and ToType is the type that we're eventually trying to convert to 6230 /// (which may or may not be the same type as the type that the 6231 /// conversion function produces). 6232 void 6233 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6234 DeclAccessPair FoundDecl, 6235 CXXRecordDecl *ActingContext, 6236 Expr *From, QualType ToType, 6237 OverloadCandidateSet& CandidateSet, 6238 bool AllowObjCConversionOnExplicit) { 6239 assert(!Conversion->getDescribedFunctionTemplate() && 6240 "Conversion function templates use AddTemplateConversionCandidate"); 6241 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6242 if (!CandidateSet.isNewCandidate(Conversion)) 6243 return; 6244 6245 // If the conversion function has an undeduced return type, trigger its 6246 // deduction now. 6247 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6248 if (DeduceReturnType(Conversion, From->getExprLoc())) 6249 return; 6250 ConvType = Conversion->getConversionType().getNonReferenceType(); 6251 } 6252 6253 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6254 // operator is only a candidate if its return type is the target type or 6255 // can be converted to the target type with a qualification conversion. 6256 if (Conversion->isExplicit() && 6257 !isAllowableExplicitConversion(*this, ConvType, ToType, 6258 AllowObjCConversionOnExplicit)) 6259 return; 6260 6261 // Overload resolution is always an unevaluated context. 6262 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6263 6264 // Add this candidate 6265 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6266 Candidate.FoundDecl = FoundDecl; 6267 Candidate.Function = Conversion; 6268 Candidate.IsSurrogate = false; 6269 Candidate.IgnoreObjectArgument = false; 6270 Candidate.FinalConversion.setAsIdentityConversion(); 6271 Candidate.FinalConversion.setFromType(ConvType); 6272 Candidate.FinalConversion.setAllToTypes(ToType); 6273 Candidate.Viable = true; 6274 Candidate.ExplicitCallArguments = 1; 6275 6276 // C++ [over.match.funcs]p4: 6277 // For conversion functions, the function is considered to be a member of 6278 // the class of the implicit implied object argument for the purpose of 6279 // defining the type of the implicit object parameter. 6280 // 6281 // Determine the implicit conversion sequence for the implicit 6282 // object parameter. 6283 QualType ImplicitParamType = From->getType(); 6284 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6285 ImplicitParamType = FromPtrType->getPointeeType(); 6286 CXXRecordDecl *ConversionContext 6287 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6288 6289 Candidate.Conversions[0] 6290 = TryObjectArgumentInitialization(*this, From->getType(), 6291 From->Classify(Context), 6292 Conversion, ConversionContext); 6293 6294 if (Candidate.Conversions[0].isBad()) { 6295 Candidate.Viable = false; 6296 Candidate.FailureKind = ovl_fail_bad_conversion; 6297 return; 6298 } 6299 6300 // We won't go through a user-defined type conversion function to convert a 6301 // derived to base as such conversions are given Conversion Rank. They only 6302 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6303 QualType FromCanon 6304 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6305 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6306 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6307 Candidate.Viable = false; 6308 Candidate.FailureKind = ovl_fail_trivial_conversion; 6309 return; 6310 } 6311 6312 // To determine what the conversion from the result of calling the 6313 // conversion function to the type we're eventually trying to 6314 // convert to (ToType), we need to synthesize a call to the 6315 // conversion function and attempt copy initialization from it. This 6316 // makes sure that we get the right semantics with respect to 6317 // lvalues/rvalues and the type. Fortunately, we can allocate this 6318 // call on the stack and we don't need its arguments to be 6319 // well-formed. 6320 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6321 VK_LValue, From->getLocStart()); 6322 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6323 Context.getPointerType(Conversion->getType()), 6324 CK_FunctionToPointerDecay, 6325 &ConversionRef, VK_RValue); 6326 6327 QualType ConversionType = Conversion->getConversionType(); 6328 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6329 Candidate.Viable = false; 6330 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6331 return; 6332 } 6333 6334 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6335 6336 // Note that it is safe to allocate CallExpr on the stack here because 6337 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6338 // allocator). 6339 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6340 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6341 From->getLocStart()); 6342 ImplicitConversionSequence ICS = 6343 TryCopyInitialization(*this, &Call, ToType, 6344 /*SuppressUserConversions=*/true, 6345 /*InOverloadResolution=*/false, 6346 /*AllowObjCWritebackConversion=*/false); 6347 6348 switch (ICS.getKind()) { 6349 case ImplicitConversionSequence::StandardConversion: 6350 Candidate.FinalConversion = ICS.Standard; 6351 6352 // C++ [over.ics.user]p3: 6353 // If the user-defined conversion is specified by a specialization of a 6354 // conversion function template, the second standard conversion sequence 6355 // shall have exact match rank. 6356 if (Conversion->getPrimaryTemplate() && 6357 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6358 Candidate.Viable = false; 6359 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6360 return; 6361 } 6362 6363 // C++0x [dcl.init.ref]p5: 6364 // In the second case, if the reference is an rvalue reference and 6365 // the second standard conversion sequence of the user-defined 6366 // conversion sequence includes an lvalue-to-rvalue conversion, the 6367 // program is ill-formed. 6368 if (ToType->isRValueReferenceType() && 6369 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6370 Candidate.Viable = false; 6371 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6372 return; 6373 } 6374 break; 6375 6376 case ImplicitConversionSequence::BadConversion: 6377 Candidate.Viable = false; 6378 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6379 return; 6380 6381 default: 6382 llvm_unreachable( 6383 "Can only end up with a standard conversion sequence or failure"); 6384 } 6385 6386 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6387 Candidate.Viable = false; 6388 Candidate.FailureKind = ovl_fail_enable_if; 6389 Candidate.DeductionFailure.Data = FailedAttr; 6390 return; 6391 } 6392 } 6393 6394 /// \brief Adds a conversion function template specialization 6395 /// candidate to the overload set, using template argument deduction 6396 /// to deduce the template arguments of the conversion function 6397 /// template from the type that we are converting to (C++ 6398 /// [temp.deduct.conv]). 6399 void 6400 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6401 DeclAccessPair FoundDecl, 6402 CXXRecordDecl *ActingDC, 6403 Expr *From, QualType ToType, 6404 OverloadCandidateSet &CandidateSet, 6405 bool AllowObjCConversionOnExplicit) { 6406 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6407 "Only conversion function templates permitted here"); 6408 6409 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6410 return; 6411 6412 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6413 CXXConversionDecl *Specialization = nullptr; 6414 if (TemplateDeductionResult Result 6415 = DeduceTemplateArguments(FunctionTemplate, ToType, 6416 Specialization, Info)) { 6417 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6418 Candidate.FoundDecl = FoundDecl; 6419 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6420 Candidate.Viable = false; 6421 Candidate.FailureKind = ovl_fail_bad_deduction; 6422 Candidate.IsSurrogate = false; 6423 Candidate.IgnoreObjectArgument = false; 6424 Candidate.ExplicitCallArguments = 1; 6425 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6426 Info); 6427 return; 6428 } 6429 6430 // Add the conversion function template specialization produced by 6431 // template argument deduction as a candidate. 6432 assert(Specialization && "Missing function template specialization?"); 6433 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6434 CandidateSet, AllowObjCConversionOnExplicit); 6435 } 6436 6437 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6438 /// converts the given @c Object to a function pointer via the 6439 /// conversion function @c Conversion, and then attempts to call it 6440 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6441 /// the type of function that we'll eventually be calling. 6442 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6443 DeclAccessPair FoundDecl, 6444 CXXRecordDecl *ActingContext, 6445 const FunctionProtoType *Proto, 6446 Expr *Object, 6447 ArrayRef<Expr *> Args, 6448 OverloadCandidateSet& CandidateSet) { 6449 if (!CandidateSet.isNewCandidate(Conversion)) 6450 return; 6451 6452 // Overload resolution is always an unevaluated context. 6453 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6454 6455 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6456 Candidate.FoundDecl = FoundDecl; 6457 Candidate.Function = nullptr; 6458 Candidate.Surrogate = Conversion; 6459 Candidate.Viable = true; 6460 Candidate.IsSurrogate = true; 6461 Candidate.IgnoreObjectArgument = false; 6462 Candidate.ExplicitCallArguments = Args.size(); 6463 6464 // Determine the implicit conversion sequence for the implicit 6465 // object parameter. 6466 ImplicitConversionSequence ObjectInit 6467 = TryObjectArgumentInitialization(*this, Object->getType(), 6468 Object->Classify(Context), 6469 Conversion, ActingContext); 6470 if (ObjectInit.isBad()) { 6471 Candidate.Viable = false; 6472 Candidate.FailureKind = ovl_fail_bad_conversion; 6473 Candidate.Conversions[0] = ObjectInit; 6474 return; 6475 } 6476 6477 // The first conversion is actually a user-defined conversion whose 6478 // first conversion is ObjectInit's standard conversion (which is 6479 // effectively a reference binding). Record it as such. 6480 Candidate.Conversions[0].setUserDefined(); 6481 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6482 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6483 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6484 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6485 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6486 Candidate.Conversions[0].UserDefined.After 6487 = Candidate.Conversions[0].UserDefined.Before; 6488 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6489 6490 // Find the 6491 unsigned NumParams = Proto->getNumParams(); 6492 6493 // (C++ 13.3.2p2): A candidate function having fewer than m 6494 // parameters is viable only if it has an ellipsis in its parameter 6495 // list (8.3.5). 6496 if (Args.size() > NumParams && !Proto->isVariadic()) { 6497 Candidate.Viable = false; 6498 Candidate.FailureKind = ovl_fail_too_many_arguments; 6499 return; 6500 } 6501 6502 // Function types don't have any default arguments, so just check if 6503 // we have enough arguments. 6504 if (Args.size() < NumParams) { 6505 // Not enough arguments. 6506 Candidate.Viable = false; 6507 Candidate.FailureKind = ovl_fail_too_few_arguments; 6508 return; 6509 } 6510 6511 // Determine the implicit conversion sequences for each of the 6512 // arguments. 6513 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6514 if (ArgIdx < NumParams) { 6515 // (C++ 13.3.2p3): for F to be a viable function, there shall 6516 // exist for each argument an implicit conversion sequence 6517 // (13.3.3.1) that converts that argument to the corresponding 6518 // parameter of F. 6519 QualType ParamType = Proto->getParamType(ArgIdx); 6520 Candidate.Conversions[ArgIdx + 1] 6521 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6522 /*SuppressUserConversions=*/false, 6523 /*InOverloadResolution=*/false, 6524 /*AllowObjCWritebackConversion=*/ 6525 getLangOpts().ObjCAutoRefCount); 6526 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6527 Candidate.Viable = false; 6528 Candidate.FailureKind = ovl_fail_bad_conversion; 6529 return; 6530 } 6531 } else { 6532 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6533 // argument for which there is no corresponding parameter is 6534 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6535 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6536 } 6537 } 6538 6539 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6540 Candidate.Viable = false; 6541 Candidate.FailureKind = ovl_fail_enable_if; 6542 Candidate.DeductionFailure.Data = FailedAttr; 6543 return; 6544 } 6545 } 6546 6547 /// \brief Add overload candidates for overloaded operators that are 6548 /// member functions. 6549 /// 6550 /// Add the overloaded operator candidates that are member functions 6551 /// for the operator Op that was used in an operator expression such 6552 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6553 /// CandidateSet will store the added overload candidates. (C++ 6554 /// [over.match.oper]). 6555 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6556 SourceLocation OpLoc, 6557 ArrayRef<Expr *> Args, 6558 OverloadCandidateSet& CandidateSet, 6559 SourceRange OpRange) { 6560 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6561 6562 // C++ [over.match.oper]p3: 6563 // For a unary operator @ with an operand of a type whose 6564 // cv-unqualified version is T1, and for a binary operator @ with 6565 // a left operand of a type whose cv-unqualified version is T1 and 6566 // a right operand of a type whose cv-unqualified version is T2, 6567 // three sets of candidate functions, designated member 6568 // candidates, non-member candidates and built-in candidates, are 6569 // constructed as follows: 6570 QualType T1 = Args[0]->getType(); 6571 6572 // -- If T1 is a complete class type or a class currently being 6573 // defined, the set of member candidates is the result of the 6574 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6575 // the set of member candidates is empty. 6576 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6577 // Complete the type if it can be completed. 6578 RequireCompleteType(OpLoc, T1, 0); 6579 // If the type is neither complete nor being defined, bail out now. 6580 if (!T1Rec->getDecl()->getDefinition()) 6581 return; 6582 6583 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6584 LookupQualifiedName(Operators, T1Rec->getDecl()); 6585 Operators.suppressDiagnostics(); 6586 6587 for (LookupResult::iterator Oper = Operators.begin(), 6588 OperEnd = Operators.end(); 6589 Oper != OperEnd; 6590 ++Oper) 6591 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6592 Args[0]->Classify(Context), 6593 Args.slice(1), 6594 CandidateSet, 6595 /* SuppressUserConversions = */ false); 6596 } 6597 } 6598 6599 /// AddBuiltinCandidate - Add a candidate for a built-in 6600 /// operator. ResultTy and ParamTys are the result and parameter types 6601 /// of the built-in candidate, respectively. Args and NumArgs are the 6602 /// arguments being passed to the candidate. IsAssignmentOperator 6603 /// should be true when this built-in candidate is an assignment 6604 /// operator. NumContextualBoolArguments is the number of arguments 6605 /// (at the beginning of the argument list) that will be contextually 6606 /// converted to bool. 6607 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6608 ArrayRef<Expr *> Args, 6609 OverloadCandidateSet& CandidateSet, 6610 bool IsAssignmentOperator, 6611 unsigned NumContextualBoolArguments) { 6612 // Overload resolution is always an unevaluated context. 6613 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6614 6615 // Add this candidate 6616 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6617 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6618 Candidate.Function = nullptr; 6619 Candidate.IsSurrogate = false; 6620 Candidate.IgnoreObjectArgument = false; 6621 Candidate.BuiltinTypes.ResultTy = ResultTy; 6622 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6623 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6624 6625 // Determine the implicit conversion sequences for each of the 6626 // arguments. 6627 Candidate.Viable = true; 6628 Candidate.ExplicitCallArguments = Args.size(); 6629 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6630 // C++ [over.match.oper]p4: 6631 // For the built-in assignment operators, conversions of the 6632 // left operand are restricted as follows: 6633 // -- no temporaries are introduced to hold the left operand, and 6634 // -- no user-defined conversions are applied to the left 6635 // operand to achieve a type match with the left-most 6636 // parameter of a built-in candidate. 6637 // 6638 // We block these conversions by turning off user-defined 6639 // conversions, since that is the only way that initialization of 6640 // a reference to a non-class type can occur from something that 6641 // is not of the same type. 6642 if (ArgIdx < NumContextualBoolArguments) { 6643 assert(ParamTys[ArgIdx] == Context.BoolTy && 6644 "Contextual conversion to bool requires bool type"); 6645 Candidate.Conversions[ArgIdx] 6646 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6647 } else { 6648 Candidate.Conversions[ArgIdx] 6649 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6650 ArgIdx == 0 && IsAssignmentOperator, 6651 /*InOverloadResolution=*/false, 6652 /*AllowObjCWritebackConversion=*/ 6653 getLangOpts().ObjCAutoRefCount); 6654 } 6655 if (Candidate.Conversions[ArgIdx].isBad()) { 6656 Candidate.Viable = false; 6657 Candidate.FailureKind = ovl_fail_bad_conversion; 6658 break; 6659 } 6660 } 6661 } 6662 6663 namespace { 6664 6665 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6666 /// candidate operator functions for built-in operators (C++ 6667 /// [over.built]). The types are separated into pointer types and 6668 /// enumeration types. 6669 class BuiltinCandidateTypeSet { 6670 /// TypeSet - A set of types. 6671 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6672 6673 /// PointerTypes - The set of pointer types that will be used in the 6674 /// built-in candidates. 6675 TypeSet PointerTypes; 6676 6677 /// MemberPointerTypes - The set of member pointer types that will be 6678 /// used in the built-in candidates. 6679 TypeSet MemberPointerTypes; 6680 6681 /// EnumerationTypes - The set of enumeration types that will be 6682 /// used in the built-in candidates. 6683 TypeSet EnumerationTypes; 6684 6685 /// \brief The set of vector types that will be used in the built-in 6686 /// candidates. 6687 TypeSet VectorTypes; 6688 6689 /// \brief A flag indicating non-record types are viable candidates 6690 bool HasNonRecordTypes; 6691 6692 /// \brief A flag indicating whether either arithmetic or enumeration types 6693 /// were present in the candidate set. 6694 bool HasArithmeticOrEnumeralTypes; 6695 6696 /// \brief A flag indicating whether the nullptr type was present in the 6697 /// candidate set. 6698 bool HasNullPtrType; 6699 6700 /// Sema - The semantic analysis instance where we are building the 6701 /// candidate type set. 6702 Sema &SemaRef; 6703 6704 /// Context - The AST context in which we will build the type sets. 6705 ASTContext &Context; 6706 6707 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6708 const Qualifiers &VisibleQuals); 6709 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6710 6711 public: 6712 /// iterator - Iterates through the types that are part of the set. 6713 typedef TypeSet::iterator iterator; 6714 6715 BuiltinCandidateTypeSet(Sema &SemaRef) 6716 : HasNonRecordTypes(false), 6717 HasArithmeticOrEnumeralTypes(false), 6718 HasNullPtrType(false), 6719 SemaRef(SemaRef), 6720 Context(SemaRef.Context) { } 6721 6722 void AddTypesConvertedFrom(QualType Ty, 6723 SourceLocation Loc, 6724 bool AllowUserConversions, 6725 bool AllowExplicitConversions, 6726 const Qualifiers &VisibleTypeConversionsQuals); 6727 6728 /// pointer_begin - First pointer type found; 6729 iterator pointer_begin() { return PointerTypes.begin(); } 6730 6731 /// pointer_end - Past the last pointer type found; 6732 iterator pointer_end() { return PointerTypes.end(); } 6733 6734 /// member_pointer_begin - First member pointer type found; 6735 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6736 6737 /// member_pointer_end - Past the last member pointer type found; 6738 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6739 6740 /// enumeration_begin - First enumeration type found; 6741 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6742 6743 /// enumeration_end - Past the last enumeration type found; 6744 iterator enumeration_end() { return EnumerationTypes.end(); } 6745 6746 iterator vector_begin() { return VectorTypes.begin(); } 6747 iterator vector_end() { return VectorTypes.end(); } 6748 6749 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6750 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6751 bool hasNullPtrType() const { return HasNullPtrType; } 6752 }; 6753 6754 } // end anonymous namespace 6755 6756 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6757 /// the set of pointer types along with any more-qualified variants of 6758 /// that type. For example, if @p Ty is "int const *", this routine 6759 /// will add "int const *", "int const volatile *", "int const 6760 /// restrict *", and "int const volatile restrict *" to the set of 6761 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6762 /// false otherwise. 6763 /// 6764 /// FIXME: what to do about extended qualifiers? 6765 bool 6766 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6767 const Qualifiers &VisibleQuals) { 6768 6769 // Insert this type. 6770 if (!PointerTypes.insert(Ty).second) 6771 return false; 6772 6773 QualType PointeeTy; 6774 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6775 bool buildObjCPtr = false; 6776 if (!PointerTy) { 6777 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6778 PointeeTy = PTy->getPointeeType(); 6779 buildObjCPtr = true; 6780 } else { 6781 PointeeTy = PointerTy->getPointeeType(); 6782 } 6783 6784 // Don't add qualified variants of arrays. For one, they're not allowed 6785 // (the qualifier would sink to the element type), and for another, the 6786 // only overload situation where it matters is subscript or pointer +- int, 6787 // and those shouldn't have qualifier variants anyway. 6788 if (PointeeTy->isArrayType()) 6789 return true; 6790 6791 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6792 bool hasVolatile = VisibleQuals.hasVolatile(); 6793 bool hasRestrict = VisibleQuals.hasRestrict(); 6794 6795 // Iterate through all strict supersets of BaseCVR. 6796 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6797 if ((CVR | BaseCVR) != CVR) continue; 6798 // Skip over volatile if no volatile found anywhere in the types. 6799 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6800 6801 // Skip over restrict if no restrict found anywhere in the types, or if 6802 // the type cannot be restrict-qualified. 6803 if ((CVR & Qualifiers::Restrict) && 6804 (!hasRestrict || 6805 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6806 continue; 6807 6808 // Build qualified pointee type. 6809 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6810 6811 // Build qualified pointer type. 6812 QualType QPointerTy; 6813 if (!buildObjCPtr) 6814 QPointerTy = Context.getPointerType(QPointeeTy); 6815 else 6816 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6817 6818 // Insert qualified pointer type. 6819 PointerTypes.insert(QPointerTy); 6820 } 6821 6822 return true; 6823 } 6824 6825 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6826 /// to the set of pointer types along with any more-qualified variants of 6827 /// that type. For example, if @p Ty is "int const *", this routine 6828 /// will add "int const *", "int const volatile *", "int const 6829 /// restrict *", and "int const volatile restrict *" to the set of 6830 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6831 /// false otherwise. 6832 /// 6833 /// FIXME: what to do about extended qualifiers? 6834 bool 6835 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6836 QualType Ty) { 6837 // Insert this type. 6838 if (!MemberPointerTypes.insert(Ty).second) 6839 return false; 6840 6841 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6842 assert(PointerTy && "type was not a member pointer type!"); 6843 6844 QualType PointeeTy = PointerTy->getPointeeType(); 6845 // Don't add qualified variants of arrays. For one, they're not allowed 6846 // (the qualifier would sink to the element type), and for another, the 6847 // only overload situation where it matters is subscript or pointer +- int, 6848 // and those shouldn't have qualifier variants anyway. 6849 if (PointeeTy->isArrayType()) 6850 return true; 6851 const Type *ClassTy = PointerTy->getClass(); 6852 6853 // Iterate through all strict supersets of the pointee type's CVR 6854 // qualifiers. 6855 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6856 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6857 if ((CVR | BaseCVR) != CVR) continue; 6858 6859 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6860 MemberPointerTypes.insert( 6861 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6862 } 6863 6864 return true; 6865 } 6866 6867 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6868 /// Ty can be implicit converted to the given set of @p Types. We're 6869 /// primarily interested in pointer types and enumeration types. We also 6870 /// take member pointer types, for the conditional operator. 6871 /// AllowUserConversions is true if we should look at the conversion 6872 /// functions of a class type, and AllowExplicitConversions if we 6873 /// should also include the explicit conversion functions of a class 6874 /// type. 6875 void 6876 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6877 SourceLocation Loc, 6878 bool AllowUserConversions, 6879 bool AllowExplicitConversions, 6880 const Qualifiers &VisibleQuals) { 6881 // Only deal with canonical types. 6882 Ty = Context.getCanonicalType(Ty); 6883 6884 // Look through reference types; they aren't part of the type of an 6885 // expression for the purposes of conversions. 6886 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6887 Ty = RefTy->getPointeeType(); 6888 6889 // If we're dealing with an array type, decay to the pointer. 6890 if (Ty->isArrayType()) 6891 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6892 6893 // Otherwise, we don't care about qualifiers on the type. 6894 Ty = Ty.getLocalUnqualifiedType(); 6895 6896 // Flag if we ever add a non-record type. 6897 const RecordType *TyRec = Ty->getAs<RecordType>(); 6898 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6899 6900 // Flag if we encounter an arithmetic type. 6901 HasArithmeticOrEnumeralTypes = 6902 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6903 6904 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6905 PointerTypes.insert(Ty); 6906 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6907 // Insert our type, and its more-qualified variants, into the set 6908 // of types. 6909 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6910 return; 6911 } else if (Ty->isMemberPointerType()) { 6912 // Member pointers are far easier, since the pointee can't be converted. 6913 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6914 return; 6915 } else if (Ty->isEnumeralType()) { 6916 HasArithmeticOrEnumeralTypes = true; 6917 EnumerationTypes.insert(Ty); 6918 } else if (Ty->isVectorType()) { 6919 // We treat vector types as arithmetic types in many contexts as an 6920 // extension. 6921 HasArithmeticOrEnumeralTypes = true; 6922 VectorTypes.insert(Ty); 6923 } else if (Ty->isNullPtrType()) { 6924 HasNullPtrType = true; 6925 } else if (AllowUserConversions && TyRec) { 6926 // No conversion functions in incomplete types. 6927 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6928 return; 6929 6930 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6931 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 6932 if (isa<UsingShadowDecl>(D)) 6933 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6934 6935 // Skip conversion function templates; they don't tell us anything 6936 // about which builtin types we can convert to. 6937 if (isa<FunctionTemplateDecl>(D)) 6938 continue; 6939 6940 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6941 if (AllowExplicitConversions || !Conv->isExplicit()) { 6942 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6943 VisibleQuals); 6944 } 6945 } 6946 } 6947 } 6948 6949 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6950 /// the volatile- and non-volatile-qualified assignment operators for the 6951 /// given type to the candidate set. 6952 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6953 QualType T, 6954 ArrayRef<Expr *> Args, 6955 OverloadCandidateSet &CandidateSet) { 6956 QualType ParamTypes[2]; 6957 6958 // T& operator=(T&, T) 6959 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6960 ParamTypes[1] = T; 6961 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6962 /*IsAssignmentOperator=*/true); 6963 6964 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6965 // volatile T& operator=(volatile T&, T) 6966 ParamTypes[0] 6967 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6968 ParamTypes[1] = T; 6969 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6970 /*IsAssignmentOperator=*/true); 6971 } 6972 } 6973 6974 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6975 /// if any, found in visible type conversion functions found in ArgExpr's type. 6976 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6977 Qualifiers VRQuals; 6978 const RecordType *TyRec; 6979 if (const MemberPointerType *RHSMPType = 6980 ArgExpr->getType()->getAs<MemberPointerType>()) 6981 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6982 else 6983 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6984 if (!TyRec) { 6985 // Just to be safe, assume the worst case. 6986 VRQuals.addVolatile(); 6987 VRQuals.addRestrict(); 6988 return VRQuals; 6989 } 6990 6991 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6992 if (!ClassDecl->hasDefinition()) 6993 return VRQuals; 6994 6995 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 6996 if (isa<UsingShadowDecl>(D)) 6997 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6998 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6999 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7000 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7001 CanTy = ResTypeRef->getPointeeType(); 7002 // Need to go down the pointer/mempointer chain and add qualifiers 7003 // as see them. 7004 bool done = false; 7005 while (!done) { 7006 if (CanTy.isRestrictQualified()) 7007 VRQuals.addRestrict(); 7008 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7009 CanTy = ResTypePtr->getPointeeType(); 7010 else if (const MemberPointerType *ResTypeMPtr = 7011 CanTy->getAs<MemberPointerType>()) 7012 CanTy = ResTypeMPtr->getPointeeType(); 7013 else 7014 done = true; 7015 if (CanTy.isVolatileQualified()) 7016 VRQuals.addVolatile(); 7017 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7018 return VRQuals; 7019 } 7020 } 7021 } 7022 return VRQuals; 7023 } 7024 7025 namespace { 7026 7027 /// \brief Helper class to manage the addition of builtin operator overload 7028 /// candidates. It provides shared state and utility methods used throughout 7029 /// the process, as well as a helper method to add each group of builtin 7030 /// operator overloads from the standard to a candidate set. 7031 class BuiltinOperatorOverloadBuilder { 7032 // Common instance state available to all overload candidate addition methods. 7033 Sema &S; 7034 ArrayRef<Expr *> Args; 7035 Qualifiers VisibleTypeConversionsQuals; 7036 bool HasArithmeticOrEnumeralCandidateType; 7037 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7038 OverloadCandidateSet &CandidateSet; 7039 7040 // Define some constants used to index and iterate over the arithemetic types 7041 // provided via the getArithmeticType() method below. 7042 // The "promoted arithmetic types" are the arithmetic 7043 // types are that preserved by promotion (C++ [over.built]p2). 7044 static const unsigned FirstIntegralType = 3; 7045 static const unsigned LastIntegralType = 20; 7046 static const unsigned FirstPromotedIntegralType = 3, 7047 LastPromotedIntegralType = 11; 7048 static const unsigned FirstPromotedArithmeticType = 0, 7049 LastPromotedArithmeticType = 11; 7050 static const unsigned NumArithmeticTypes = 20; 7051 7052 /// \brief Get the canonical type for a given arithmetic type index. 7053 CanQualType getArithmeticType(unsigned index) { 7054 assert(index < NumArithmeticTypes); 7055 static CanQualType ASTContext::* const 7056 ArithmeticTypes[NumArithmeticTypes] = { 7057 // Start of promoted types. 7058 &ASTContext::FloatTy, 7059 &ASTContext::DoubleTy, 7060 &ASTContext::LongDoubleTy, 7061 7062 // Start of integral types. 7063 &ASTContext::IntTy, 7064 &ASTContext::LongTy, 7065 &ASTContext::LongLongTy, 7066 &ASTContext::Int128Ty, 7067 &ASTContext::UnsignedIntTy, 7068 &ASTContext::UnsignedLongTy, 7069 &ASTContext::UnsignedLongLongTy, 7070 &ASTContext::UnsignedInt128Ty, 7071 // End of promoted types. 7072 7073 &ASTContext::BoolTy, 7074 &ASTContext::CharTy, 7075 &ASTContext::WCharTy, 7076 &ASTContext::Char16Ty, 7077 &ASTContext::Char32Ty, 7078 &ASTContext::SignedCharTy, 7079 &ASTContext::ShortTy, 7080 &ASTContext::UnsignedCharTy, 7081 &ASTContext::UnsignedShortTy, 7082 // End of integral types. 7083 // FIXME: What about complex? What about half? 7084 }; 7085 return S.Context.*ArithmeticTypes[index]; 7086 } 7087 7088 /// \brief Gets the canonical type resulting from the usual arithemetic 7089 /// converions for the given arithmetic types. 7090 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7091 // Accelerator table for performing the usual arithmetic conversions. 7092 // The rules are basically: 7093 // - if either is floating-point, use the wider floating-point 7094 // - if same signedness, use the higher rank 7095 // - if same size, use unsigned of the higher rank 7096 // - use the larger type 7097 // These rules, together with the axiom that higher ranks are 7098 // never smaller, are sufficient to precompute all of these results 7099 // *except* when dealing with signed types of higher rank. 7100 // (we could precompute SLL x UI for all known platforms, but it's 7101 // better not to make any assumptions). 7102 // We assume that int128 has a higher rank than long long on all platforms. 7103 enum PromotedType { 7104 Dep=-1, 7105 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7106 }; 7107 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7108 [LastPromotedArithmeticType] = { 7109 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7110 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7111 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7112 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7113 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7114 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7115 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7116 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7117 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7118 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7119 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7120 }; 7121 7122 assert(L < LastPromotedArithmeticType); 7123 assert(R < LastPromotedArithmeticType); 7124 int Idx = ConversionsTable[L][R]; 7125 7126 // Fast path: the table gives us a concrete answer. 7127 if (Idx != Dep) return getArithmeticType(Idx); 7128 7129 // Slow path: we need to compare widths. 7130 // An invariant is that the signed type has higher rank. 7131 CanQualType LT = getArithmeticType(L), 7132 RT = getArithmeticType(R); 7133 unsigned LW = S.Context.getIntWidth(LT), 7134 RW = S.Context.getIntWidth(RT); 7135 7136 // If they're different widths, use the signed type. 7137 if (LW > RW) return LT; 7138 else if (LW < RW) return RT; 7139 7140 // Otherwise, use the unsigned type of the signed type's rank. 7141 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7142 assert(L == SLL || R == SLL); 7143 return S.Context.UnsignedLongLongTy; 7144 } 7145 7146 /// \brief Helper method to factor out the common pattern of adding overloads 7147 /// for '++' and '--' builtin operators. 7148 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7149 bool HasVolatile, 7150 bool HasRestrict) { 7151 QualType ParamTypes[2] = { 7152 S.Context.getLValueReferenceType(CandidateTy), 7153 S.Context.IntTy 7154 }; 7155 7156 // Non-volatile version. 7157 if (Args.size() == 1) 7158 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7159 else 7160 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7161 7162 // Use a heuristic to reduce number of builtin candidates in the set: 7163 // add volatile version only if there are conversions to a volatile type. 7164 if (HasVolatile) { 7165 ParamTypes[0] = 7166 S.Context.getLValueReferenceType( 7167 S.Context.getVolatileType(CandidateTy)); 7168 if (Args.size() == 1) 7169 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7170 else 7171 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7172 } 7173 7174 // Add restrict version only if there are conversions to a restrict type 7175 // and our candidate type is a non-restrict-qualified pointer. 7176 if (HasRestrict && CandidateTy->isAnyPointerType() && 7177 !CandidateTy.isRestrictQualified()) { 7178 ParamTypes[0] 7179 = S.Context.getLValueReferenceType( 7180 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7181 if (Args.size() == 1) 7182 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7183 else 7184 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7185 7186 if (HasVolatile) { 7187 ParamTypes[0] 7188 = S.Context.getLValueReferenceType( 7189 S.Context.getCVRQualifiedType(CandidateTy, 7190 (Qualifiers::Volatile | 7191 Qualifiers::Restrict))); 7192 if (Args.size() == 1) 7193 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7194 else 7195 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7196 } 7197 } 7198 7199 } 7200 7201 public: 7202 BuiltinOperatorOverloadBuilder( 7203 Sema &S, ArrayRef<Expr *> Args, 7204 Qualifiers VisibleTypeConversionsQuals, 7205 bool HasArithmeticOrEnumeralCandidateType, 7206 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7207 OverloadCandidateSet &CandidateSet) 7208 : S(S), Args(Args), 7209 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7210 HasArithmeticOrEnumeralCandidateType( 7211 HasArithmeticOrEnumeralCandidateType), 7212 CandidateTypes(CandidateTypes), 7213 CandidateSet(CandidateSet) { 7214 // Validate some of our static helper constants in debug builds. 7215 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7216 "Invalid first promoted integral type"); 7217 assert(getArithmeticType(LastPromotedIntegralType - 1) 7218 == S.Context.UnsignedInt128Ty && 7219 "Invalid last promoted integral type"); 7220 assert(getArithmeticType(FirstPromotedArithmeticType) 7221 == S.Context.FloatTy && 7222 "Invalid first promoted arithmetic type"); 7223 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7224 == S.Context.UnsignedInt128Ty && 7225 "Invalid last promoted arithmetic type"); 7226 } 7227 7228 // C++ [over.built]p3: 7229 // 7230 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7231 // is either volatile or empty, there exist candidate operator 7232 // functions of the form 7233 // 7234 // VQ T& operator++(VQ T&); 7235 // T operator++(VQ T&, int); 7236 // 7237 // C++ [over.built]p4: 7238 // 7239 // For every pair (T, VQ), where T is an arithmetic type other 7240 // than bool, and VQ is either volatile or empty, there exist 7241 // candidate operator functions of the form 7242 // 7243 // VQ T& operator--(VQ T&); 7244 // T operator--(VQ T&, int); 7245 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7246 if (!HasArithmeticOrEnumeralCandidateType) 7247 return; 7248 7249 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7250 Arith < NumArithmeticTypes; ++Arith) { 7251 addPlusPlusMinusMinusStyleOverloads( 7252 getArithmeticType(Arith), 7253 VisibleTypeConversionsQuals.hasVolatile(), 7254 VisibleTypeConversionsQuals.hasRestrict()); 7255 } 7256 } 7257 7258 // C++ [over.built]p5: 7259 // 7260 // For every pair (T, VQ), where T is a cv-qualified or 7261 // cv-unqualified object type, and VQ is either volatile or 7262 // empty, there exist candidate operator functions of the form 7263 // 7264 // T*VQ& operator++(T*VQ&); 7265 // T*VQ& operator--(T*VQ&); 7266 // T* operator++(T*VQ&, int); 7267 // T* operator--(T*VQ&, int); 7268 void addPlusPlusMinusMinusPointerOverloads() { 7269 for (BuiltinCandidateTypeSet::iterator 7270 Ptr = CandidateTypes[0].pointer_begin(), 7271 PtrEnd = CandidateTypes[0].pointer_end(); 7272 Ptr != PtrEnd; ++Ptr) { 7273 // Skip pointer types that aren't pointers to object types. 7274 if (!(*Ptr)->getPointeeType()->isObjectType()) 7275 continue; 7276 7277 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7278 (!(*Ptr).isVolatileQualified() && 7279 VisibleTypeConversionsQuals.hasVolatile()), 7280 (!(*Ptr).isRestrictQualified() && 7281 VisibleTypeConversionsQuals.hasRestrict())); 7282 } 7283 } 7284 7285 // C++ [over.built]p6: 7286 // For every cv-qualified or cv-unqualified object type T, there 7287 // exist candidate operator functions of the form 7288 // 7289 // T& operator*(T*); 7290 // 7291 // C++ [over.built]p7: 7292 // For every function type T that does not have cv-qualifiers or a 7293 // ref-qualifier, there exist candidate operator functions of the form 7294 // T& operator*(T*); 7295 void addUnaryStarPointerOverloads() { 7296 for (BuiltinCandidateTypeSet::iterator 7297 Ptr = CandidateTypes[0].pointer_begin(), 7298 PtrEnd = CandidateTypes[0].pointer_end(); 7299 Ptr != PtrEnd; ++Ptr) { 7300 QualType ParamTy = *Ptr; 7301 QualType PointeeTy = ParamTy->getPointeeType(); 7302 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7303 continue; 7304 7305 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7306 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7307 continue; 7308 7309 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7310 &ParamTy, Args, CandidateSet); 7311 } 7312 } 7313 7314 // C++ [over.built]p9: 7315 // For every promoted arithmetic type T, there exist candidate 7316 // operator functions of the form 7317 // 7318 // T operator+(T); 7319 // T operator-(T); 7320 void addUnaryPlusOrMinusArithmeticOverloads() { 7321 if (!HasArithmeticOrEnumeralCandidateType) 7322 return; 7323 7324 for (unsigned Arith = FirstPromotedArithmeticType; 7325 Arith < LastPromotedArithmeticType; ++Arith) { 7326 QualType ArithTy = getArithmeticType(Arith); 7327 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7328 } 7329 7330 // Extension: We also add these operators for vector types. 7331 for (BuiltinCandidateTypeSet::iterator 7332 Vec = CandidateTypes[0].vector_begin(), 7333 VecEnd = CandidateTypes[0].vector_end(); 7334 Vec != VecEnd; ++Vec) { 7335 QualType VecTy = *Vec; 7336 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7337 } 7338 } 7339 7340 // C++ [over.built]p8: 7341 // For every type T, there exist candidate operator functions of 7342 // the form 7343 // 7344 // T* operator+(T*); 7345 void addUnaryPlusPointerOverloads() { 7346 for (BuiltinCandidateTypeSet::iterator 7347 Ptr = CandidateTypes[0].pointer_begin(), 7348 PtrEnd = CandidateTypes[0].pointer_end(); 7349 Ptr != PtrEnd; ++Ptr) { 7350 QualType ParamTy = *Ptr; 7351 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7352 } 7353 } 7354 7355 // C++ [over.built]p10: 7356 // For every promoted integral type T, there exist candidate 7357 // operator functions of the form 7358 // 7359 // T operator~(T); 7360 void addUnaryTildePromotedIntegralOverloads() { 7361 if (!HasArithmeticOrEnumeralCandidateType) 7362 return; 7363 7364 for (unsigned Int = FirstPromotedIntegralType; 7365 Int < LastPromotedIntegralType; ++Int) { 7366 QualType IntTy = getArithmeticType(Int); 7367 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7368 } 7369 7370 // Extension: We also add this operator for vector types. 7371 for (BuiltinCandidateTypeSet::iterator 7372 Vec = CandidateTypes[0].vector_begin(), 7373 VecEnd = CandidateTypes[0].vector_end(); 7374 Vec != VecEnd; ++Vec) { 7375 QualType VecTy = *Vec; 7376 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7377 } 7378 } 7379 7380 // C++ [over.match.oper]p16: 7381 // For every pointer to member type T, there exist candidate operator 7382 // functions of the form 7383 // 7384 // bool operator==(T,T); 7385 // bool operator!=(T,T); 7386 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7387 /// Set of (canonical) types that we've already handled. 7388 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7389 7390 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7391 for (BuiltinCandidateTypeSet::iterator 7392 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7393 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7394 MemPtr != MemPtrEnd; 7395 ++MemPtr) { 7396 // Don't add the same builtin candidate twice. 7397 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7398 continue; 7399 7400 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7401 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7402 } 7403 } 7404 } 7405 7406 // C++ [over.built]p15: 7407 // 7408 // For every T, where T is an enumeration type, a pointer type, or 7409 // std::nullptr_t, there exist candidate operator functions of the form 7410 // 7411 // bool operator<(T, T); 7412 // bool operator>(T, T); 7413 // bool operator<=(T, T); 7414 // bool operator>=(T, T); 7415 // bool operator==(T, T); 7416 // bool operator!=(T, T); 7417 void addRelationalPointerOrEnumeralOverloads() { 7418 // C++ [over.match.oper]p3: 7419 // [...]the built-in candidates include all of the candidate operator 7420 // functions defined in 13.6 that, compared to the given operator, [...] 7421 // do not have the same parameter-type-list as any non-template non-member 7422 // candidate. 7423 // 7424 // Note that in practice, this only affects enumeration types because there 7425 // aren't any built-in candidates of record type, and a user-defined operator 7426 // must have an operand of record or enumeration type. Also, the only other 7427 // overloaded operator with enumeration arguments, operator=, 7428 // cannot be overloaded for enumeration types, so this is the only place 7429 // where we must suppress candidates like this. 7430 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7431 UserDefinedBinaryOperators; 7432 7433 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7434 if (CandidateTypes[ArgIdx].enumeration_begin() != 7435 CandidateTypes[ArgIdx].enumeration_end()) { 7436 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7437 CEnd = CandidateSet.end(); 7438 C != CEnd; ++C) { 7439 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7440 continue; 7441 7442 if (C->Function->isFunctionTemplateSpecialization()) 7443 continue; 7444 7445 QualType FirstParamType = 7446 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7447 QualType SecondParamType = 7448 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7449 7450 // Skip if either parameter isn't of enumeral type. 7451 if (!FirstParamType->isEnumeralType() || 7452 !SecondParamType->isEnumeralType()) 7453 continue; 7454 7455 // Add this operator to the set of known user-defined operators. 7456 UserDefinedBinaryOperators.insert( 7457 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7458 S.Context.getCanonicalType(SecondParamType))); 7459 } 7460 } 7461 } 7462 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 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7469 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7470 Ptr != PtrEnd; ++Ptr) { 7471 // Don't add the same builtin candidate twice. 7472 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7473 continue; 7474 7475 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7476 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7477 } 7478 for (BuiltinCandidateTypeSet::iterator 7479 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7480 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7481 Enum != EnumEnd; ++Enum) { 7482 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7483 7484 // Don't add the same builtin candidate twice, or if a user defined 7485 // candidate exists. 7486 if (!AddedTypes.insert(CanonType).second || 7487 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7488 CanonType))) 7489 continue; 7490 7491 QualType ParamTypes[2] = { *Enum, *Enum }; 7492 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7493 } 7494 7495 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7496 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7497 if (AddedTypes.insert(NullPtrTy).second && 7498 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7499 NullPtrTy))) { 7500 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7501 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7502 CandidateSet); 7503 } 7504 } 7505 } 7506 } 7507 7508 // C++ [over.built]p13: 7509 // 7510 // For every cv-qualified or cv-unqualified object type T 7511 // there exist candidate operator functions of the form 7512 // 7513 // T* operator+(T*, ptrdiff_t); 7514 // T& operator[](T*, ptrdiff_t); [BELOW] 7515 // T* operator-(T*, ptrdiff_t); 7516 // T* operator+(ptrdiff_t, T*); 7517 // T& operator[](ptrdiff_t, T*); [BELOW] 7518 // 7519 // C++ [over.built]p14: 7520 // 7521 // For every T, where T is a pointer to object type, there 7522 // exist candidate operator functions of the form 7523 // 7524 // ptrdiff_t operator-(T, T); 7525 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7526 /// Set of (canonical) types that we've already handled. 7527 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7528 7529 for (int Arg = 0; Arg < 2; ++Arg) { 7530 QualType AsymetricParamTypes[2] = { 7531 S.Context.getPointerDiffType(), 7532 S.Context.getPointerDiffType(), 7533 }; 7534 for (BuiltinCandidateTypeSet::iterator 7535 Ptr = CandidateTypes[Arg].pointer_begin(), 7536 PtrEnd = CandidateTypes[Arg].pointer_end(); 7537 Ptr != PtrEnd; ++Ptr) { 7538 QualType PointeeTy = (*Ptr)->getPointeeType(); 7539 if (!PointeeTy->isObjectType()) 7540 continue; 7541 7542 AsymetricParamTypes[Arg] = *Ptr; 7543 if (Arg == 0 || Op == OO_Plus) { 7544 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7545 // T* operator+(ptrdiff_t, T*); 7546 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7547 } 7548 if (Op == OO_Minus) { 7549 // ptrdiff_t operator-(T, T); 7550 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7551 continue; 7552 7553 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7554 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7555 Args, CandidateSet); 7556 } 7557 } 7558 } 7559 } 7560 7561 // C++ [over.built]p12: 7562 // 7563 // For every pair of promoted arithmetic types L and R, there 7564 // exist candidate operator functions of the form 7565 // 7566 // LR operator*(L, R); 7567 // LR operator/(L, R); 7568 // LR operator+(L, R); 7569 // LR operator-(L, R); 7570 // bool operator<(L, R); 7571 // bool operator>(L, R); 7572 // bool operator<=(L, R); 7573 // bool operator>=(L, R); 7574 // bool operator==(L, R); 7575 // bool operator!=(L, R); 7576 // 7577 // where LR is the result of the usual arithmetic conversions 7578 // between types L and R. 7579 // 7580 // C++ [over.built]p24: 7581 // 7582 // For every pair of promoted arithmetic types L and R, there exist 7583 // candidate operator functions of the form 7584 // 7585 // LR operator?(bool, L, R); 7586 // 7587 // where LR is the result of the usual arithmetic conversions 7588 // between types L and R. 7589 // Our candidates ignore the first parameter. 7590 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7591 if (!HasArithmeticOrEnumeralCandidateType) 7592 return; 7593 7594 for (unsigned Left = FirstPromotedArithmeticType; 7595 Left < LastPromotedArithmeticType; ++Left) { 7596 for (unsigned Right = FirstPromotedArithmeticType; 7597 Right < LastPromotedArithmeticType; ++Right) { 7598 QualType LandR[2] = { getArithmeticType(Left), 7599 getArithmeticType(Right) }; 7600 QualType Result = 7601 isComparison ? S.Context.BoolTy 7602 : getUsualArithmeticConversions(Left, Right); 7603 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7604 } 7605 } 7606 7607 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7608 // conditional operator for vector types. 7609 for (BuiltinCandidateTypeSet::iterator 7610 Vec1 = CandidateTypes[0].vector_begin(), 7611 Vec1End = CandidateTypes[0].vector_end(); 7612 Vec1 != Vec1End; ++Vec1) { 7613 for (BuiltinCandidateTypeSet::iterator 7614 Vec2 = CandidateTypes[1].vector_begin(), 7615 Vec2End = CandidateTypes[1].vector_end(); 7616 Vec2 != Vec2End; ++Vec2) { 7617 QualType LandR[2] = { *Vec1, *Vec2 }; 7618 QualType Result = S.Context.BoolTy; 7619 if (!isComparison) { 7620 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7621 Result = *Vec1; 7622 else 7623 Result = *Vec2; 7624 } 7625 7626 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7627 } 7628 } 7629 } 7630 7631 // C++ [over.built]p17: 7632 // 7633 // For every pair of promoted integral types L and R, there 7634 // exist candidate operator functions of the form 7635 // 7636 // LR operator%(L, R); 7637 // LR operator&(L, R); 7638 // LR operator^(L, R); 7639 // LR operator|(L, R); 7640 // L operator<<(L, R); 7641 // L operator>>(L, R); 7642 // 7643 // where LR is the result of the usual arithmetic conversions 7644 // between types L and R. 7645 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7646 if (!HasArithmeticOrEnumeralCandidateType) 7647 return; 7648 7649 for (unsigned Left = FirstPromotedIntegralType; 7650 Left < LastPromotedIntegralType; ++Left) { 7651 for (unsigned Right = FirstPromotedIntegralType; 7652 Right < LastPromotedIntegralType; ++Right) { 7653 QualType LandR[2] = { getArithmeticType(Left), 7654 getArithmeticType(Right) }; 7655 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7656 ? LandR[0] 7657 : getUsualArithmeticConversions(Left, Right); 7658 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7659 } 7660 } 7661 } 7662 7663 // C++ [over.built]p20: 7664 // 7665 // For every pair (T, VQ), where T is an enumeration or 7666 // pointer to member type and VQ is either volatile or 7667 // empty, there exist candidate operator functions of the form 7668 // 7669 // VQ T& operator=(VQ T&, T); 7670 void addAssignmentMemberPointerOrEnumeralOverloads() { 7671 /// Set of (canonical) types that we've already handled. 7672 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7673 7674 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7675 for (BuiltinCandidateTypeSet::iterator 7676 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7677 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7678 Enum != EnumEnd; ++Enum) { 7679 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7680 continue; 7681 7682 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7683 } 7684 7685 for (BuiltinCandidateTypeSet::iterator 7686 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7687 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7688 MemPtr != MemPtrEnd; ++MemPtr) { 7689 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7690 continue; 7691 7692 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7693 } 7694 } 7695 } 7696 7697 // C++ [over.built]p19: 7698 // 7699 // For every pair (T, VQ), where T is any type and VQ is either 7700 // volatile or empty, there exist candidate operator functions 7701 // of the form 7702 // 7703 // T*VQ& operator=(T*VQ&, T*); 7704 // 7705 // C++ [over.built]p21: 7706 // 7707 // For every pair (T, VQ), where T is a cv-qualified or 7708 // cv-unqualified object type and VQ is either volatile or 7709 // empty, there exist candidate operator functions of the form 7710 // 7711 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7712 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7713 void addAssignmentPointerOverloads(bool isEqualOp) { 7714 /// Set of (canonical) types that we've already handled. 7715 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7716 7717 for (BuiltinCandidateTypeSet::iterator 7718 Ptr = CandidateTypes[0].pointer_begin(), 7719 PtrEnd = CandidateTypes[0].pointer_end(); 7720 Ptr != PtrEnd; ++Ptr) { 7721 // If this is operator=, keep track of the builtin candidates we added. 7722 if (isEqualOp) 7723 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7724 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7725 continue; 7726 7727 // non-volatile version 7728 QualType ParamTypes[2] = { 7729 S.Context.getLValueReferenceType(*Ptr), 7730 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7731 }; 7732 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7733 /*IsAssigmentOperator=*/ isEqualOp); 7734 7735 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7736 VisibleTypeConversionsQuals.hasVolatile(); 7737 if (NeedVolatile) { 7738 // volatile version 7739 ParamTypes[0] = 7740 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7741 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7742 /*IsAssigmentOperator=*/isEqualOp); 7743 } 7744 7745 if (!(*Ptr).isRestrictQualified() && 7746 VisibleTypeConversionsQuals.hasRestrict()) { 7747 // restrict version 7748 ParamTypes[0] 7749 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7750 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7751 /*IsAssigmentOperator=*/isEqualOp); 7752 7753 if (NeedVolatile) { 7754 // volatile restrict version 7755 ParamTypes[0] 7756 = S.Context.getLValueReferenceType( 7757 S.Context.getCVRQualifiedType(*Ptr, 7758 (Qualifiers::Volatile | 7759 Qualifiers::Restrict))); 7760 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7761 /*IsAssigmentOperator=*/isEqualOp); 7762 } 7763 } 7764 } 7765 7766 if (isEqualOp) { 7767 for (BuiltinCandidateTypeSet::iterator 7768 Ptr = CandidateTypes[1].pointer_begin(), 7769 PtrEnd = CandidateTypes[1].pointer_end(); 7770 Ptr != PtrEnd; ++Ptr) { 7771 // Make sure we don't add the same candidate twice. 7772 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7773 continue; 7774 7775 QualType ParamTypes[2] = { 7776 S.Context.getLValueReferenceType(*Ptr), 7777 *Ptr, 7778 }; 7779 7780 // non-volatile version 7781 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7782 /*IsAssigmentOperator=*/true); 7783 7784 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7785 VisibleTypeConversionsQuals.hasVolatile(); 7786 if (NeedVolatile) { 7787 // volatile version 7788 ParamTypes[0] = 7789 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7790 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7791 /*IsAssigmentOperator=*/true); 7792 } 7793 7794 if (!(*Ptr).isRestrictQualified() && 7795 VisibleTypeConversionsQuals.hasRestrict()) { 7796 // restrict version 7797 ParamTypes[0] 7798 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7799 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7800 /*IsAssigmentOperator=*/true); 7801 7802 if (NeedVolatile) { 7803 // volatile restrict version 7804 ParamTypes[0] 7805 = S.Context.getLValueReferenceType( 7806 S.Context.getCVRQualifiedType(*Ptr, 7807 (Qualifiers::Volatile | 7808 Qualifiers::Restrict))); 7809 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7810 /*IsAssigmentOperator=*/true); 7811 } 7812 } 7813 } 7814 } 7815 } 7816 7817 // C++ [over.built]p18: 7818 // 7819 // For every triple (L, VQ, R), where L is an arithmetic type, 7820 // VQ is either volatile or empty, and R is a promoted 7821 // arithmetic type, there exist candidate operator functions of 7822 // the form 7823 // 7824 // VQ L& operator=(VQ L&, R); 7825 // VQ L& operator*=(VQ L&, R); 7826 // VQ L& operator/=(VQ L&, R); 7827 // VQ L& operator+=(VQ L&, R); 7828 // VQ L& operator-=(VQ L&, R); 7829 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7830 if (!HasArithmeticOrEnumeralCandidateType) 7831 return; 7832 7833 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7834 for (unsigned Right = FirstPromotedArithmeticType; 7835 Right < LastPromotedArithmeticType; ++Right) { 7836 QualType ParamTypes[2]; 7837 ParamTypes[1] = getArithmeticType(Right); 7838 7839 // Add this built-in operator as a candidate (VQ is empty). 7840 ParamTypes[0] = 7841 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7842 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7843 /*IsAssigmentOperator=*/isEqualOp); 7844 7845 // Add this built-in operator as a candidate (VQ is 'volatile'). 7846 if (VisibleTypeConversionsQuals.hasVolatile()) { 7847 ParamTypes[0] = 7848 S.Context.getVolatileType(getArithmeticType(Left)); 7849 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7850 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7851 /*IsAssigmentOperator=*/isEqualOp); 7852 } 7853 } 7854 } 7855 7856 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7857 for (BuiltinCandidateTypeSet::iterator 7858 Vec1 = CandidateTypes[0].vector_begin(), 7859 Vec1End = CandidateTypes[0].vector_end(); 7860 Vec1 != Vec1End; ++Vec1) { 7861 for (BuiltinCandidateTypeSet::iterator 7862 Vec2 = CandidateTypes[1].vector_begin(), 7863 Vec2End = CandidateTypes[1].vector_end(); 7864 Vec2 != Vec2End; ++Vec2) { 7865 QualType ParamTypes[2]; 7866 ParamTypes[1] = *Vec2; 7867 // Add this built-in operator as a candidate (VQ is empty). 7868 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7869 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7870 /*IsAssigmentOperator=*/isEqualOp); 7871 7872 // Add this built-in operator as a candidate (VQ is 'volatile'). 7873 if (VisibleTypeConversionsQuals.hasVolatile()) { 7874 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7875 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7876 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7877 /*IsAssigmentOperator=*/isEqualOp); 7878 } 7879 } 7880 } 7881 } 7882 7883 // C++ [over.built]p22: 7884 // 7885 // For every triple (L, VQ, R), where L is an integral type, VQ 7886 // is either volatile or empty, and R is a promoted integral 7887 // type, there exist candidate operator functions of the form 7888 // 7889 // VQ L& operator%=(VQ L&, R); 7890 // VQ L& operator<<=(VQ L&, R); 7891 // VQ L& operator>>=(VQ L&, R); 7892 // VQ L& operator&=(VQ L&, R); 7893 // VQ L& operator^=(VQ L&, R); 7894 // VQ L& operator|=(VQ L&, R); 7895 void addAssignmentIntegralOverloads() { 7896 if (!HasArithmeticOrEnumeralCandidateType) 7897 return; 7898 7899 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7900 for (unsigned Right = FirstPromotedIntegralType; 7901 Right < LastPromotedIntegralType; ++Right) { 7902 QualType ParamTypes[2]; 7903 ParamTypes[1] = getArithmeticType(Right); 7904 7905 // Add this built-in operator as a candidate (VQ is empty). 7906 ParamTypes[0] = 7907 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7908 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7909 if (VisibleTypeConversionsQuals.hasVolatile()) { 7910 // Add this built-in operator as a candidate (VQ is 'volatile'). 7911 ParamTypes[0] = getArithmeticType(Left); 7912 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7913 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7914 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7915 } 7916 } 7917 } 7918 } 7919 7920 // C++ [over.operator]p23: 7921 // 7922 // There also exist candidate operator functions of the form 7923 // 7924 // bool operator!(bool); 7925 // bool operator&&(bool, bool); 7926 // bool operator||(bool, bool); 7927 void addExclaimOverload() { 7928 QualType ParamTy = S.Context.BoolTy; 7929 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7930 /*IsAssignmentOperator=*/false, 7931 /*NumContextualBoolArguments=*/1); 7932 } 7933 void addAmpAmpOrPipePipeOverload() { 7934 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7935 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7936 /*IsAssignmentOperator=*/false, 7937 /*NumContextualBoolArguments=*/2); 7938 } 7939 7940 // C++ [over.built]p13: 7941 // 7942 // For every cv-qualified or cv-unqualified object type T there 7943 // exist candidate operator functions of the form 7944 // 7945 // T* operator+(T*, ptrdiff_t); [ABOVE] 7946 // T& operator[](T*, ptrdiff_t); 7947 // T* operator-(T*, ptrdiff_t); [ABOVE] 7948 // T* operator+(ptrdiff_t, T*); [ABOVE] 7949 // T& operator[](ptrdiff_t, T*); 7950 void addSubscriptOverloads() { 7951 for (BuiltinCandidateTypeSet::iterator 7952 Ptr = CandidateTypes[0].pointer_begin(), 7953 PtrEnd = CandidateTypes[0].pointer_end(); 7954 Ptr != PtrEnd; ++Ptr) { 7955 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7956 QualType PointeeType = (*Ptr)->getPointeeType(); 7957 if (!PointeeType->isObjectType()) 7958 continue; 7959 7960 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7961 7962 // T& operator[](T*, ptrdiff_t) 7963 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7964 } 7965 7966 for (BuiltinCandidateTypeSet::iterator 7967 Ptr = CandidateTypes[1].pointer_begin(), 7968 PtrEnd = CandidateTypes[1].pointer_end(); 7969 Ptr != PtrEnd; ++Ptr) { 7970 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7971 QualType PointeeType = (*Ptr)->getPointeeType(); 7972 if (!PointeeType->isObjectType()) 7973 continue; 7974 7975 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7976 7977 // T& operator[](ptrdiff_t, T*) 7978 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7979 } 7980 } 7981 7982 // C++ [over.built]p11: 7983 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7984 // C1 is the same type as C2 or is a derived class of C2, T is an object 7985 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7986 // there exist candidate operator functions of the form 7987 // 7988 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7989 // 7990 // where CV12 is the union of CV1 and CV2. 7991 void addArrowStarOverloads() { 7992 for (BuiltinCandidateTypeSet::iterator 7993 Ptr = CandidateTypes[0].pointer_begin(), 7994 PtrEnd = CandidateTypes[0].pointer_end(); 7995 Ptr != PtrEnd; ++Ptr) { 7996 QualType C1Ty = (*Ptr); 7997 QualType C1; 7998 QualifierCollector Q1; 7999 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8000 if (!isa<RecordType>(C1)) 8001 continue; 8002 // heuristic to reduce number of builtin candidates in the set. 8003 // Add volatile/restrict version only if there are conversions to a 8004 // volatile/restrict type. 8005 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8006 continue; 8007 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8008 continue; 8009 for (BuiltinCandidateTypeSet::iterator 8010 MemPtr = CandidateTypes[1].member_pointer_begin(), 8011 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8012 MemPtr != MemPtrEnd; ++MemPtr) { 8013 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8014 QualType C2 = QualType(mptr->getClass(), 0); 8015 C2 = C2.getUnqualifiedType(); 8016 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 8017 break; 8018 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8019 // build CV12 T& 8020 QualType T = mptr->getPointeeType(); 8021 if (!VisibleTypeConversionsQuals.hasVolatile() && 8022 T.isVolatileQualified()) 8023 continue; 8024 if (!VisibleTypeConversionsQuals.hasRestrict() && 8025 T.isRestrictQualified()) 8026 continue; 8027 T = Q1.apply(S.Context, T); 8028 QualType ResultTy = S.Context.getLValueReferenceType(T); 8029 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8030 } 8031 } 8032 } 8033 8034 // Note that we don't consider the first argument, since it has been 8035 // contextually converted to bool long ago. The candidates below are 8036 // therefore added as binary. 8037 // 8038 // C++ [over.built]p25: 8039 // For every type T, where T is a pointer, pointer-to-member, or scoped 8040 // enumeration type, there exist candidate operator functions of the form 8041 // 8042 // T operator?(bool, T, T); 8043 // 8044 void addConditionalOperatorOverloads() { 8045 /// Set of (canonical) types that we've already handled. 8046 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8047 8048 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8049 for (BuiltinCandidateTypeSet::iterator 8050 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8051 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8052 Ptr != PtrEnd; ++Ptr) { 8053 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8054 continue; 8055 8056 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8057 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8058 } 8059 8060 for (BuiltinCandidateTypeSet::iterator 8061 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8062 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8063 MemPtr != MemPtrEnd; ++MemPtr) { 8064 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8065 continue; 8066 8067 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8068 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8069 } 8070 8071 if (S.getLangOpts().CPlusPlus11) { 8072 for (BuiltinCandidateTypeSet::iterator 8073 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8074 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8075 Enum != EnumEnd; ++Enum) { 8076 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8077 continue; 8078 8079 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8080 continue; 8081 8082 QualType ParamTypes[2] = { *Enum, *Enum }; 8083 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8084 } 8085 } 8086 } 8087 } 8088 }; 8089 8090 } // end anonymous namespace 8091 8092 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8093 /// operator overloads to the candidate set (C++ [over.built]), based 8094 /// on the operator @p Op and the arguments given. For example, if the 8095 /// operator is a binary '+', this routine might add "int 8096 /// operator+(int, int)" to cover integer addition. 8097 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8098 SourceLocation OpLoc, 8099 ArrayRef<Expr *> Args, 8100 OverloadCandidateSet &CandidateSet) { 8101 // Find all of the types that the arguments can convert to, but only 8102 // if the operator we're looking at has built-in operator candidates 8103 // that make use of these types. Also record whether we encounter non-record 8104 // candidate types or either arithmetic or enumeral candidate types. 8105 Qualifiers VisibleTypeConversionsQuals; 8106 VisibleTypeConversionsQuals.addConst(); 8107 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8108 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8109 8110 bool HasNonRecordCandidateType = false; 8111 bool HasArithmeticOrEnumeralCandidateType = false; 8112 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8113 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8114 CandidateTypes.emplace_back(*this); 8115 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8116 OpLoc, 8117 true, 8118 (Op == OO_Exclaim || 8119 Op == OO_AmpAmp || 8120 Op == OO_PipePipe), 8121 VisibleTypeConversionsQuals); 8122 HasNonRecordCandidateType = HasNonRecordCandidateType || 8123 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8124 HasArithmeticOrEnumeralCandidateType = 8125 HasArithmeticOrEnumeralCandidateType || 8126 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8127 } 8128 8129 // Exit early when no non-record types have been added to the candidate set 8130 // for any of the arguments to the operator. 8131 // 8132 // We can't exit early for !, ||, or &&, since there we have always have 8133 // 'bool' overloads. 8134 if (!HasNonRecordCandidateType && 8135 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8136 return; 8137 8138 // Setup an object to manage the common state for building overloads. 8139 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8140 VisibleTypeConversionsQuals, 8141 HasArithmeticOrEnumeralCandidateType, 8142 CandidateTypes, CandidateSet); 8143 8144 // Dispatch over the operation to add in only those overloads which apply. 8145 switch (Op) { 8146 case OO_None: 8147 case NUM_OVERLOADED_OPERATORS: 8148 llvm_unreachable("Expected an overloaded operator"); 8149 8150 case OO_New: 8151 case OO_Delete: 8152 case OO_Array_New: 8153 case OO_Array_Delete: 8154 case OO_Call: 8155 llvm_unreachable( 8156 "Special operators don't use AddBuiltinOperatorCandidates"); 8157 8158 case OO_Comma: 8159 case OO_Arrow: 8160 // C++ [over.match.oper]p3: 8161 // -- For the operator ',', the unary operator '&', or the 8162 // operator '->', the built-in candidates set is empty. 8163 break; 8164 8165 case OO_Plus: // '+' is either unary or binary 8166 if (Args.size() == 1) 8167 OpBuilder.addUnaryPlusPointerOverloads(); 8168 // Fall through. 8169 8170 case OO_Minus: // '-' is either unary or binary 8171 if (Args.size() == 1) { 8172 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8173 } else { 8174 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8175 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8176 } 8177 break; 8178 8179 case OO_Star: // '*' is either unary or binary 8180 if (Args.size() == 1) 8181 OpBuilder.addUnaryStarPointerOverloads(); 8182 else 8183 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8184 break; 8185 8186 case OO_Slash: 8187 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8188 break; 8189 8190 case OO_PlusPlus: 8191 case OO_MinusMinus: 8192 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8193 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8194 break; 8195 8196 case OO_EqualEqual: 8197 case OO_ExclaimEqual: 8198 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8199 // Fall through. 8200 8201 case OO_Less: 8202 case OO_Greater: 8203 case OO_LessEqual: 8204 case OO_GreaterEqual: 8205 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8206 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8207 break; 8208 8209 case OO_Percent: 8210 case OO_Caret: 8211 case OO_Pipe: 8212 case OO_LessLess: 8213 case OO_GreaterGreater: 8214 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8215 break; 8216 8217 case OO_Amp: // '&' is either unary or binary 8218 if (Args.size() == 1) 8219 // C++ [over.match.oper]p3: 8220 // -- For the operator ',', the unary operator '&', or the 8221 // operator '->', the built-in candidates set is empty. 8222 break; 8223 8224 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8225 break; 8226 8227 case OO_Tilde: 8228 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8229 break; 8230 8231 case OO_Equal: 8232 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8233 // Fall through. 8234 8235 case OO_PlusEqual: 8236 case OO_MinusEqual: 8237 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8238 // Fall through. 8239 8240 case OO_StarEqual: 8241 case OO_SlashEqual: 8242 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8243 break; 8244 8245 case OO_PercentEqual: 8246 case OO_LessLessEqual: 8247 case OO_GreaterGreaterEqual: 8248 case OO_AmpEqual: 8249 case OO_CaretEqual: 8250 case OO_PipeEqual: 8251 OpBuilder.addAssignmentIntegralOverloads(); 8252 break; 8253 8254 case OO_Exclaim: 8255 OpBuilder.addExclaimOverload(); 8256 break; 8257 8258 case OO_AmpAmp: 8259 case OO_PipePipe: 8260 OpBuilder.addAmpAmpOrPipePipeOverload(); 8261 break; 8262 8263 case OO_Subscript: 8264 OpBuilder.addSubscriptOverloads(); 8265 break; 8266 8267 case OO_ArrowStar: 8268 OpBuilder.addArrowStarOverloads(); 8269 break; 8270 8271 case OO_Conditional: 8272 OpBuilder.addConditionalOperatorOverloads(); 8273 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8274 break; 8275 } 8276 } 8277 8278 /// \brief Add function candidates found via argument-dependent lookup 8279 /// to the set of overloading candidates. 8280 /// 8281 /// This routine performs argument-dependent name lookup based on the 8282 /// given function name (which may also be an operator name) and adds 8283 /// all of the overload candidates found by ADL to the overload 8284 /// candidate set (C++ [basic.lookup.argdep]). 8285 void 8286 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8287 SourceLocation Loc, 8288 ArrayRef<Expr *> Args, 8289 TemplateArgumentListInfo *ExplicitTemplateArgs, 8290 OverloadCandidateSet& CandidateSet, 8291 bool PartialOverloading) { 8292 ADLResult Fns; 8293 8294 // FIXME: This approach for uniquing ADL results (and removing 8295 // redundant candidates from the set) relies on pointer-equality, 8296 // which means we need to key off the canonical decl. However, 8297 // always going back to the canonical decl might not get us the 8298 // right set of default arguments. What default arguments are 8299 // we supposed to consider on ADL candidates, anyway? 8300 8301 // FIXME: Pass in the explicit template arguments? 8302 ArgumentDependentLookup(Name, Loc, Args, Fns); 8303 8304 // Erase all of the candidates we already knew about. 8305 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8306 CandEnd = CandidateSet.end(); 8307 Cand != CandEnd; ++Cand) 8308 if (Cand->Function) { 8309 Fns.erase(Cand->Function); 8310 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8311 Fns.erase(FunTmpl); 8312 } 8313 8314 // For each of the ADL candidates we found, add it to the overload 8315 // set. 8316 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8317 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8318 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8319 if (ExplicitTemplateArgs) 8320 continue; 8321 8322 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8323 PartialOverloading); 8324 } else 8325 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8326 FoundDecl, ExplicitTemplateArgs, 8327 Args, CandidateSet, PartialOverloading); 8328 } 8329 } 8330 8331 /// isBetterOverloadCandidate - Determines whether the first overload 8332 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8333 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8334 const OverloadCandidate &Cand2, 8335 SourceLocation Loc, 8336 bool UserDefinedConversion) { 8337 // Define viable functions to be better candidates than non-viable 8338 // functions. 8339 if (!Cand2.Viable) 8340 return Cand1.Viable; 8341 else if (!Cand1.Viable) 8342 return false; 8343 8344 // C++ [over.match.best]p1: 8345 // 8346 // -- if F is a static member function, ICS1(F) is defined such 8347 // that ICS1(F) is neither better nor worse than ICS1(G) for 8348 // any function G, and, symmetrically, ICS1(G) is neither 8349 // better nor worse than ICS1(F). 8350 unsigned StartArg = 0; 8351 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8352 StartArg = 1; 8353 8354 // C++ [over.match.best]p1: 8355 // A viable function F1 is defined to be a better function than another 8356 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8357 // conversion sequence than ICSi(F2), and then... 8358 unsigned NumArgs = Cand1.NumConversions; 8359 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8360 bool HasBetterConversion = false; 8361 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8362 switch (CompareImplicitConversionSequences(S, 8363 Cand1.Conversions[ArgIdx], 8364 Cand2.Conversions[ArgIdx])) { 8365 case ImplicitConversionSequence::Better: 8366 // Cand1 has a better conversion sequence. 8367 HasBetterConversion = true; 8368 break; 8369 8370 case ImplicitConversionSequence::Worse: 8371 // Cand1 can't be better than Cand2. 8372 return false; 8373 8374 case ImplicitConversionSequence::Indistinguishable: 8375 // Do nothing. 8376 break; 8377 } 8378 } 8379 8380 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8381 // ICSj(F2), or, if not that, 8382 if (HasBetterConversion) 8383 return true; 8384 8385 // -- the context is an initialization by user-defined conversion 8386 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8387 // from the return type of F1 to the destination type (i.e., 8388 // the type of the entity being initialized) is a better 8389 // conversion sequence than the standard conversion sequence 8390 // from the return type of F2 to the destination type. 8391 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8392 isa<CXXConversionDecl>(Cand1.Function) && 8393 isa<CXXConversionDecl>(Cand2.Function)) { 8394 // First check whether we prefer one of the conversion functions over the 8395 // other. This only distinguishes the results in non-standard, extension 8396 // cases such as the conversion from a lambda closure type to a function 8397 // pointer or block. 8398 ImplicitConversionSequence::CompareKind Result = 8399 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8400 if (Result == ImplicitConversionSequence::Indistinguishable) 8401 Result = CompareStandardConversionSequences(S, 8402 Cand1.FinalConversion, 8403 Cand2.FinalConversion); 8404 8405 if (Result != ImplicitConversionSequence::Indistinguishable) 8406 return Result == ImplicitConversionSequence::Better; 8407 8408 // FIXME: Compare kind of reference binding if conversion functions 8409 // convert to a reference type used in direct reference binding, per 8410 // C++14 [over.match.best]p1 section 2 bullet 3. 8411 } 8412 8413 // -- F1 is a non-template function and F2 is a function template 8414 // specialization, or, if not that, 8415 bool Cand1IsSpecialization = Cand1.Function && 8416 Cand1.Function->getPrimaryTemplate(); 8417 bool Cand2IsSpecialization = Cand2.Function && 8418 Cand2.Function->getPrimaryTemplate(); 8419 if (Cand1IsSpecialization != Cand2IsSpecialization) 8420 return Cand2IsSpecialization; 8421 8422 // -- F1 and F2 are function template specializations, and the function 8423 // template for F1 is more specialized than the template for F2 8424 // according to the partial ordering rules described in 14.5.5.2, or, 8425 // if not that, 8426 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8427 if (FunctionTemplateDecl *BetterTemplate 8428 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8429 Cand2.Function->getPrimaryTemplate(), 8430 Loc, 8431 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8432 : TPOC_Call, 8433 Cand1.ExplicitCallArguments, 8434 Cand2.ExplicitCallArguments)) 8435 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8436 } 8437 8438 // Check for enable_if value-based overload resolution. 8439 if (Cand1.Function && Cand2.Function && 8440 (Cand1.Function->hasAttr<EnableIfAttr>() || 8441 Cand2.Function->hasAttr<EnableIfAttr>())) { 8442 // FIXME: The next several lines are just 8443 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8444 // instead of reverse order which is how they're stored in the AST. 8445 AttrVec Cand1Attrs; 8446 if (Cand1.Function->hasAttrs()) { 8447 Cand1Attrs = Cand1.Function->getAttrs(); 8448 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(), 8449 IsNotEnableIfAttr), 8450 Cand1Attrs.end()); 8451 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end()); 8452 } 8453 8454 AttrVec Cand2Attrs; 8455 if (Cand2.Function->hasAttrs()) { 8456 Cand2Attrs = Cand2.Function->getAttrs(); 8457 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(), 8458 IsNotEnableIfAttr), 8459 Cand2Attrs.end()); 8460 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end()); 8461 } 8462 8463 // Candidate 1 is better if it has strictly more attributes and 8464 // the common sequence is identical. 8465 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8466 return false; 8467 8468 auto Cand1I = Cand1Attrs.begin(); 8469 for (auto &Cand2A : Cand2Attrs) { 8470 auto &Cand1A = *Cand1I++; 8471 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8472 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID, 8473 S.getASTContext(), true); 8474 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID, 8475 S.getASTContext(), true); 8476 if (Cand1ID != Cand2ID) 8477 return false; 8478 } 8479 8480 return true; 8481 } 8482 8483 return false; 8484 } 8485 8486 /// \brief Computes the best viable function (C++ 13.3.3) 8487 /// within an overload candidate set. 8488 /// 8489 /// \param Loc The location of the function name (or operator symbol) for 8490 /// which overload resolution occurs. 8491 /// 8492 /// \param Best If overload resolution was successful or found a deleted 8493 /// function, \p Best points to the candidate function found. 8494 /// 8495 /// \returns The result of overload resolution. 8496 OverloadingResult 8497 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8498 iterator &Best, 8499 bool UserDefinedConversion) { 8500 // Find the best viable function. 8501 Best = end(); 8502 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8503 if (Cand->Viable) 8504 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8505 UserDefinedConversion)) 8506 Best = Cand; 8507 } 8508 8509 // If we didn't find any viable functions, abort. 8510 if (Best == end()) 8511 return OR_No_Viable_Function; 8512 8513 // Make sure that this function is better than every other viable 8514 // function. If not, we have an ambiguity. 8515 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8516 if (Cand->Viable && 8517 Cand != Best && 8518 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8519 UserDefinedConversion)) { 8520 Best = end(); 8521 return OR_Ambiguous; 8522 } 8523 } 8524 8525 // Best is the best viable function. 8526 if (Best->Function && 8527 (Best->Function->isDeleted() || 8528 S.isFunctionConsideredUnavailable(Best->Function))) 8529 return OR_Deleted; 8530 8531 return OR_Success; 8532 } 8533 8534 namespace { 8535 8536 enum OverloadCandidateKind { 8537 oc_function, 8538 oc_method, 8539 oc_constructor, 8540 oc_function_template, 8541 oc_method_template, 8542 oc_constructor_template, 8543 oc_implicit_default_constructor, 8544 oc_implicit_copy_constructor, 8545 oc_implicit_move_constructor, 8546 oc_implicit_copy_assignment, 8547 oc_implicit_move_assignment, 8548 oc_implicit_inherited_constructor 8549 }; 8550 8551 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8552 FunctionDecl *Fn, 8553 std::string &Description) { 8554 bool isTemplate = false; 8555 8556 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8557 isTemplate = true; 8558 Description = S.getTemplateArgumentBindingsText( 8559 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8560 } 8561 8562 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8563 if (!Ctor->isImplicit()) 8564 return isTemplate ? oc_constructor_template : oc_constructor; 8565 8566 if (Ctor->getInheritedConstructor()) 8567 return oc_implicit_inherited_constructor; 8568 8569 if (Ctor->isDefaultConstructor()) 8570 return oc_implicit_default_constructor; 8571 8572 if (Ctor->isMoveConstructor()) 8573 return oc_implicit_move_constructor; 8574 8575 assert(Ctor->isCopyConstructor() && 8576 "unexpected sort of implicit constructor"); 8577 return oc_implicit_copy_constructor; 8578 } 8579 8580 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8581 // This actually gets spelled 'candidate function' for now, but 8582 // it doesn't hurt to split it out. 8583 if (!Meth->isImplicit()) 8584 return isTemplate ? oc_method_template : oc_method; 8585 8586 if (Meth->isMoveAssignmentOperator()) 8587 return oc_implicit_move_assignment; 8588 8589 if (Meth->isCopyAssignmentOperator()) 8590 return oc_implicit_copy_assignment; 8591 8592 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8593 return oc_method; 8594 } 8595 8596 return isTemplate ? oc_function_template : oc_function; 8597 } 8598 8599 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8600 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8601 if (!Ctor) return; 8602 8603 Ctor = Ctor->getInheritedConstructor(); 8604 if (!Ctor) return; 8605 8606 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8607 } 8608 8609 } // end anonymous namespace 8610 8611 // Notes the location of an overload candidate. 8612 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8613 std::string FnDesc; 8614 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8615 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8616 << (unsigned) K << FnDesc; 8617 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8618 Diag(Fn->getLocation(), PD); 8619 MaybeEmitInheritedConstructorNote(*this, Fn); 8620 } 8621 8622 // Notes the location of all overload candidates designated through 8623 // OverloadedExpr 8624 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8625 assert(OverloadedExpr->getType() == Context.OverloadTy); 8626 8627 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8628 OverloadExpr *OvlExpr = Ovl.Expression; 8629 8630 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8631 IEnd = OvlExpr->decls_end(); 8632 I != IEnd; ++I) { 8633 if (FunctionTemplateDecl *FunTmpl = 8634 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8635 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8636 } else if (FunctionDecl *Fun 8637 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8638 NoteOverloadCandidate(Fun, DestType); 8639 } 8640 } 8641 } 8642 8643 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8644 /// "lead" diagnostic; it will be given two arguments, the source and 8645 /// target types of the conversion. 8646 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8647 Sema &S, 8648 SourceLocation CaretLoc, 8649 const PartialDiagnostic &PDiag) const { 8650 S.Diag(CaretLoc, PDiag) 8651 << Ambiguous.getFromType() << Ambiguous.getToType(); 8652 // FIXME: The note limiting machinery is borrowed from 8653 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8654 // refactoring here. 8655 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8656 unsigned CandsShown = 0; 8657 AmbiguousConversionSequence::const_iterator I, E; 8658 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8659 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8660 break; 8661 ++CandsShown; 8662 S.NoteOverloadCandidate(*I); 8663 } 8664 if (I != E) 8665 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8666 } 8667 8668 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 8669 unsigned I) { 8670 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8671 assert(Conv.isBad()); 8672 assert(Cand->Function && "for now, candidate must be a function"); 8673 FunctionDecl *Fn = Cand->Function; 8674 8675 // There's a conversion slot for the object argument if this is a 8676 // non-constructor method. Note that 'I' corresponds the 8677 // conversion-slot index. 8678 bool isObjectArgument = false; 8679 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8680 if (I == 0) 8681 isObjectArgument = true; 8682 else 8683 I--; 8684 } 8685 8686 std::string FnDesc; 8687 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8688 8689 Expr *FromExpr = Conv.Bad.FromExpr; 8690 QualType FromTy = Conv.Bad.getFromType(); 8691 QualType ToTy = Conv.Bad.getToType(); 8692 8693 if (FromTy == S.Context.OverloadTy) { 8694 assert(FromExpr && "overload set argument came from implicit argument?"); 8695 Expr *E = FromExpr->IgnoreParens(); 8696 if (isa<UnaryOperator>(E)) 8697 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8698 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8699 8700 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8701 << (unsigned) FnKind << FnDesc 8702 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8703 << ToTy << Name << I+1; 8704 MaybeEmitInheritedConstructorNote(S, Fn); 8705 return; 8706 } 8707 8708 // Do some hand-waving analysis to see if the non-viability is due 8709 // to a qualifier mismatch. 8710 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8711 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8712 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8713 CToTy = RT->getPointeeType(); 8714 else { 8715 // TODO: detect and diagnose the full richness of const mismatches. 8716 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8717 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8718 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8719 } 8720 8721 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8722 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8723 Qualifiers FromQs = CFromTy.getQualifiers(); 8724 Qualifiers ToQs = CToTy.getQualifiers(); 8725 8726 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8727 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8728 << (unsigned) FnKind << FnDesc 8729 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8730 << FromTy 8731 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8732 << (unsigned) isObjectArgument << I+1; 8733 MaybeEmitInheritedConstructorNote(S, Fn); 8734 return; 8735 } 8736 8737 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8738 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8739 << (unsigned) FnKind << FnDesc 8740 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8741 << FromTy 8742 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8743 << (unsigned) isObjectArgument << I+1; 8744 MaybeEmitInheritedConstructorNote(S, Fn); 8745 return; 8746 } 8747 8748 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8749 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8750 << (unsigned) FnKind << FnDesc 8751 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8752 << FromTy 8753 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8754 << (unsigned) isObjectArgument << I+1; 8755 MaybeEmitInheritedConstructorNote(S, Fn); 8756 return; 8757 } 8758 8759 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8760 assert(CVR && "unexpected qualifiers mismatch"); 8761 8762 if (isObjectArgument) { 8763 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8764 << (unsigned) FnKind << FnDesc 8765 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8766 << FromTy << (CVR - 1); 8767 } else { 8768 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8769 << (unsigned) FnKind << FnDesc 8770 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8771 << FromTy << (CVR - 1) << I+1; 8772 } 8773 MaybeEmitInheritedConstructorNote(S, Fn); 8774 return; 8775 } 8776 8777 // Special diagnostic for failure to convert an initializer list, since 8778 // telling the user that it has type void is not useful. 8779 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8780 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8781 << (unsigned) FnKind << FnDesc 8782 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8783 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8784 MaybeEmitInheritedConstructorNote(S, Fn); 8785 return; 8786 } 8787 8788 // Diagnose references or pointers to incomplete types differently, 8789 // since it's far from impossible that the incompleteness triggered 8790 // the failure. 8791 QualType TempFromTy = FromTy.getNonReferenceType(); 8792 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8793 TempFromTy = PTy->getPointeeType(); 8794 if (TempFromTy->isIncompleteType()) { 8795 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8796 << (unsigned) FnKind << FnDesc 8797 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8798 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8799 MaybeEmitInheritedConstructorNote(S, Fn); 8800 return; 8801 } 8802 8803 // Diagnose base -> derived pointer conversions. 8804 unsigned BaseToDerivedConversion = 0; 8805 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8806 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8807 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8808 FromPtrTy->getPointeeType()) && 8809 !FromPtrTy->getPointeeType()->isIncompleteType() && 8810 !ToPtrTy->getPointeeType()->isIncompleteType() && 8811 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8812 FromPtrTy->getPointeeType())) 8813 BaseToDerivedConversion = 1; 8814 } 8815 } else if (const ObjCObjectPointerType *FromPtrTy 8816 = FromTy->getAs<ObjCObjectPointerType>()) { 8817 if (const ObjCObjectPointerType *ToPtrTy 8818 = ToTy->getAs<ObjCObjectPointerType>()) 8819 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8820 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8821 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8822 FromPtrTy->getPointeeType()) && 8823 FromIface->isSuperClassOf(ToIface)) 8824 BaseToDerivedConversion = 2; 8825 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8826 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8827 !FromTy->isIncompleteType() && 8828 !ToRefTy->getPointeeType()->isIncompleteType() && 8829 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8830 BaseToDerivedConversion = 3; 8831 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8832 ToTy.getNonReferenceType().getCanonicalType() == 8833 FromTy.getNonReferenceType().getCanonicalType()) { 8834 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8835 << (unsigned) FnKind << FnDesc 8836 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8837 << (unsigned) isObjectArgument << I + 1; 8838 MaybeEmitInheritedConstructorNote(S, Fn); 8839 return; 8840 } 8841 } 8842 8843 if (BaseToDerivedConversion) { 8844 S.Diag(Fn->getLocation(), 8845 diag::note_ovl_candidate_bad_base_to_derived_conv) 8846 << (unsigned) FnKind << FnDesc 8847 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8848 << (BaseToDerivedConversion - 1) 8849 << FromTy << ToTy << I+1; 8850 MaybeEmitInheritedConstructorNote(S, Fn); 8851 return; 8852 } 8853 8854 if (isa<ObjCObjectPointerType>(CFromTy) && 8855 isa<PointerType>(CToTy)) { 8856 Qualifiers FromQs = CFromTy.getQualifiers(); 8857 Qualifiers ToQs = CToTy.getQualifiers(); 8858 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8859 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8860 << (unsigned) FnKind << FnDesc 8861 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8862 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8863 MaybeEmitInheritedConstructorNote(S, Fn); 8864 return; 8865 } 8866 } 8867 8868 // Emit the generic diagnostic and, optionally, add the hints to it. 8869 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8870 FDiag << (unsigned) FnKind << FnDesc 8871 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8872 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8873 << (unsigned) (Cand->Fix.Kind); 8874 8875 // If we can fix the conversion, suggest the FixIts. 8876 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8877 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8878 FDiag << *HI; 8879 S.Diag(Fn->getLocation(), FDiag); 8880 8881 MaybeEmitInheritedConstructorNote(S, Fn); 8882 } 8883 8884 /// Additional arity mismatch diagnosis specific to a function overload 8885 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 8886 /// over a candidate in any candidate set. 8887 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 8888 unsigned NumArgs) { 8889 FunctionDecl *Fn = Cand->Function; 8890 unsigned MinParams = Fn->getMinRequiredArguments(); 8891 8892 // With invalid overloaded operators, it's possible that we think we 8893 // have an arity mismatch when in fact it looks like we have the 8894 // right number of arguments, because only overloaded operators have 8895 // the weird behavior of overloading member and non-member functions. 8896 // Just don't report anything. 8897 if (Fn->isInvalidDecl() && 8898 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8899 return true; 8900 8901 if (NumArgs < MinParams) { 8902 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8903 (Cand->FailureKind == ovl_fail_bad_deduction && 8904 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8905 } else { 8906 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8907 (Cand->FailureKind == ovl_fail_bad_deduction && 8908 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8909 } 8910 8911 return false; 8912 } 8913 8914 /// General arity mismatch diagnosis over a candidate in a candidate set. 8915 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 8916 assert(isa<FunctionDecl>(D) && 8917 "The templated declaration should at least be a function" 8918 " when diagnosing bad template argument deduction due to too many" 8919 " or too few arguments"); 8920 8921 FunctionDecl *Fn = cast<FunctionDecl>(D); 8922 8923 // TODO: treat calls to a missing default constructor as a special case 8924 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8925 unsigned MinParams = Fn->getMinRequiredArguments(); 8926 8927 // at least / at most / exactly 8928 unsigned mode, modeCount; 8929 if (NumFormalArgs < MinParams) { 8930 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 8931 FnTy->isTemplateVariadic()) 8932 mode = 0; // "at least" 8933 else 8934 mode = 2; // "exactly" 8935 modeCount = MinParams; 8936 } else { 8937 if (MinParams != FnTy->getNumParams()) 8938 mode = 1; // "at most" 8939 else 8940 mode = 2; // "exactly" 8941 modeCount = FnTy->getNumParams(); 8942 } 8943 8944 std::string Description; 8945 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8946 8947 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8948 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8949 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 8950 << mode << Fn->getParamDecl(0) << NumFormalArgs; 8951 else 8952 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8953 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 8954 << mode << modeCount << NumFormalArgs; 8955 MaybeEmitInheritedConstructorNote(S, Fn); 8956 } 8957 8958 /// Arity mismatch diagnosis specific to a function overload candidate. 8959 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8960 unsigned NumFormalArgs) { 8961 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 8962 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 8963 } 8964 8965 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 8966 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 8967 return FD->getDescribedFunctionTemplate(); 8968 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 8969 return RD->getDescribedClassTemplate(); 8970 8971 llvm_unreachable("Unsupported: Getting the described template declaration" 8972 " for bad deduction diagnosis"); 8973 } 8974 8975 /// Diagnose a failed template-argument deduction. 8976 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 8977 DeductionFailureInfo &DeductionFailure, 8978 unsigned NumArgs) { 8979 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 8980 NamedDecl *ParamD; 8981 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8982 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8983 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8984 switch (DeductionFailure.Result) { 8985 case Sema::TDK_Success: 8986 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8987 8988 case Sema::TDK_Incomplete: { 8989 assert(ParamD && "no parameter found for incomplete deduction result"); 8990 S.Diag(Templated->getLocation(), 8991 diag::note_ovl_candidate_incomplete_deduction) 8992 << ParamD->getDeclName(); 8993 MaybeEmitInheritedConstructorNote(S, Templated); 8994 return; 8995 } 8996 8997 case Sema::TDK_Underqualified: { 8998 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8999 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9000 9001 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9002 9003 // Param will have been canonicalized, but it should just be a 9004 // qualified version of ParamD, so move the qualifiers to that. 9005 QualifierCollector Qs; 9006 Qs.strip(Param); 9007 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9008 assert(S.Context.hasSameType(Param, NonCanonParam)); 9009 9010 // Arg has also been canonicalized, but there's nothing we can do 9011 // about that. It also doesn't matter as much, because it won't 9012 // have any template parameters in it (because deduction isn't 9013 // done on dependent types). 9014 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9015 9016 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9017 << ParamD->getDeclName() << Arg << NonCanonParam; 9018 MaybeEmitInheritedConstructorNote(S, Templated); 9019 return; 9020 } 9021 9022 case Sema::TDK_Inconsistent: { 9023 assert(ParamD && "no parameter found for inconsistent deduction result"); 9024 int which = 0; 9025 if (isa<TemplateTypeParmDecl>(ParamD)) 9026 which = 0; 9027 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9028 which = 1; 9029 else { 9030 which = 2; 9031 } 9032 9033 S.Diag(Templated->getLocation(), 9034 diag::note_ovl_candidate_inconsistent_deduction) 9035 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9036 << *DeductionFailure.getSecondArg(); 9037 MaybeEmitInheritedConstructorNote(S, Templated); 9038 return; 9039 } 9040 9041 case Sema::TDK_InvalidExplicitArguments: 9042 assert(ParamD && "no parameter found for invalid explicit arguments"); 9043 if (ParamD->getDeclName()) 9044 S.Diag(Templated->getLocation(), 9045 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9046 << ParamD->getDeclName(); 9047 else { 9048 int index = 0; 9049 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9050 index = TTP->getIndex(); 9051 else if (NonTypeTemplateParmDecl *NTTP 9052 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9053 index = NTTP->getIndex(); 9054 else 9055 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9056 S.Diag(Templated->getLocation(), 9057 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9058 << (index + 1); 9059 } 9060 MaybeEmitInheritedConstructorNote(S, Templated); 9061 return; 9062 9063 case Sema::TDK_TooManyArguments: 9064 case Sema::TDK_TooFewArguments: 9065 DiagnoseArityMismatch(S, Templated, NumArgs); 9066 return; 9067 9068 case Sema::TDK_InstantiationDepth: 9069 S.Diag(Templated->getLocation(), 9070 diag::note_ovl_candidate_instantiation_depth); 9071 MaybeEmitInheritedConstructorNote(S, Templated); 9072 return; 9073 9074 case Sema::TDK_SubstitutionFailure: { 9075 // Format the template argument list into the argument string. 9076 SmallString<128> TemplateArgString; 9077 if (TemplateArgumentList *Args = 9078 DeductionFailure.getTemplateArgumentList()) { 9079 TemplateArgString = " "; 9080 TemplateArgString += S.getTemplateArgumentBindingsText( 9081 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9082 } 9083 9084 // If this candidate was disabled by enable_if, say so. 9085 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9086 if (PDiag && PDiag->second.getDiagID() == 9087 diag::err_typename_nested_not_found_enable_if) { 9088 // FIXME: Use the source range of the condition, and the fully-qualified 9089 // name of the enable_if template. These are both present in PDiag. 9090 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9091 << "'enable_if'" << TemplateArgString; 9092 return; 9093 } 9094 9095 // Format the SFINAE diagnostic into the argument string. 9096 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9097 // formatted message in another diagnostic. 9098 SmallString<128> SFINAEArgString; 9099 SourceRange R; 9100 if (PDiag) { 9101 SFINAEArgString = ": "; 9102 R = SourceRange(PDiag->first, PDiag->first); 9103 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9104 } 9105 9106 S.Diag(Templated->getLocation(), 9107 diag::note_ovl_candidate_substitution_failure) 9108 << TemplateArgString << SFINAEArgString << R; 9109 MaybeEmitInheritedConstructorNote(S, Templated); 9110 return; 9111 } 9112 9113 case Sema::TDK_FailedOverloadResolution: { 9114 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9115 S.Diag(Templated->getLocation(), 9116 diag::note_ovl_candidate_failed_overload_resolution) 9117 << R.Expression->getName(); 9118 return; 9119 } 9120 9121 case Sema::TDK_NonDeducedMismatch: { 9122 // FIXME: Provide a source location to indicate what we couldn't match. 9123 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9124 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9125 if (FirstTA.getKind() == TemplateArgument::Template && 9126 SecondTA.getKind() == TemplateArgument::Template) { 9127 TemplateName FirstTN = FirstTA.getAsTemplate(); 9128 TemplateName SecondTN = SecondTA.getAsTemplate(); 9129 if (FirstTN.getKind() == TemplateName::Template && 9130 SecondTN.getKind() == TemplateName::Template) { 9131 if (FirstTN.getAsTemplateDecl()->getName() == 9132 SecondTN.getAsTemplateDecl()->getName()) { 9133 // FIXME: This fixes a bad diagnostic where both templates are named 9134 // the same. This particular case is a bit difficult since: 9135 // 1) It is passed as a string to the diagnostic printer. 9136 // 2) The diagnostic printer only attempts to find a better 9137 // name for types, not decls. 9138 // Ideally, this should folded into the diagnostic printer. 9139 S.Diag(Templated->getLocation(), 9140 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9141 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9142 return; 9143 } 9144 } 9145 } 9146 // FIXME: For generic lambda parameters, check if the function is a lambda 9147 // call operator, and if so, emit a prettier and more informative 9148 // diagnostic that mentions 'auto' and lambda in addition to 9149 // (or instead of?) the canonical template type parameters. 9150 S.Diag(Templated->getLocation(), 9151 diag::note_ovl_candidate_non_deduced_mismatch) 9152 << FirstTA << SecondTA; 9153 return; 9154 } 9155 // TODO: diagnose these individually, then kill off 9156 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9157 case Sema::TDK_MiscellaneousDeductionFailure: 9158 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9159 MaybeEmitInheritedConstructorNote(S, Templated); 9160 return; 9161 } 9162 } 9163 9164 /// Diagnose a failed template-argument deduction, for function calls. 9165 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9166 unsigned NumArgs) { 9167 unsigned TDK = Cand->DeductionFailure.Result; 9168 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9169 if (CheckArityMismatch(S, Cand, NumArgs)) 9170 return; 9171 } 9172 DiagnoseBadDeduction(S, Cand->Function, // pattern 9173 Cand->DeductionFailure, NumArgs); 9174 } 9175 9176 /// CUDA: diagnose an invalid call across targets. 9177 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9178 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9179 FunctionDecl *Callee = Cand->Function; 9180 9181 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9182 CalleeTarget = S.IdentifyCUDATarget(Callee); 9183 9184 std::string FnDesc; 9185 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9186 9187 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9188 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9189 9190 // This could be an implicit constructor for which we could not infer the 9191 // target due to a collsion. Diagnose that case. 9192 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9193 if (Meth != nullptr && Meth->isImplicit()) { 9194 CXXRecordDecl *ParentClass = Meth->getParent(); 9195 Sema::CXXSpecialMember CSM; 9196 9197 switch (FnKind) { 9198 default: 9199 return; 9200 case oc_implicit_default_constructor: 9201 CSM = Sema::CXXDefaultConstructor; 9202 break; 9203 case oc_implicit_copy_constructor: 9204 CSM = Sema::CXXCopyConstructor; 9205 break; 9206 case oc_implicit_move_constructor: 9207 CSM = Sema::CXXMoveConstructor; 9208 break; 9209 case oc_implicit_copy_assignment: 9210 CSM = Sema::CXXCopyAssignment; 9211 break; 9212 case oc_implicit_move_assignment: 9213 CSM = Sema::CXXMoveAssignment; 9214 break; 9215 }; 9216 9217 bool ConstRHS = false; 9218 if (Meth->getNumParams()) { 9219 if (const ReferenceType *RT = 9220 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9221 ConstRHS = RT->getPointeeType().isConstQualified(); 9222 } 9223 } 9224 9225 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9226 /* ConstRHS */ ConstRHS, 9227 /* Diagnose */ true); 9228 } 9229 } 9230 9231 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9232 FunctionDecl *Callee = Cand->Function; 9233 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9234 9235 S.Diag(Callee->getLocation(), 9236 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9237 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9238 } 9239 9240 /// Generates a 'note' diagnostic for an overload candidate. We've 9241 /// already generated a primary error at the call site. 9242 /// 9243 /// It really does need to be a single diagnostic with its caret 9244 /// pointed at the candidate declaration. Yes, this creates some 9245 /// major challenges of technical writing. Yes, this makes pointing 9246 /// out problems with specific arguments quite awkward. It's still 9247 /// better than generating twenty screens of text for every failed 9248 /// overload. 9249 /// 9250 /// It would be great to be able to express per-candidate problems 9251 /// more richly for those diagnostic clients that cared, but we'd 9252 /// still have to be just as careful with the default diagnostics. 9253 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9254 unsigned NumArgs) { 9255 FunctionDecl *Fn = Cand->Function; 9256 9257 // Note deleted candidates, but only if they're viable. 9258 if (Cand->Viable && (Fn->isDeleted() || 9259 S.isFunctionConsideredUnavailable(Fn))) { 9260 std::string FnDesc; 9261 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9262 9263 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9264 << FnKind << FnDesc 9265 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9266 MaybeEmitInheritedConstructorNote(S, Fn); 9267 return; 9268 } 9269 9270 // We don't really have anything else to say about viable candidates. 9271 if (Cand->Viable) { 9272 S.NoteOverloadCandidate(Fn); 9273 return; 9274 } 9275 9276 switch (Cand->FailureKind) { 9277 case ovl_fail_too_many_arguments: 9278 case ovl_fail_too_few_arguments: 9279 return DiagnoseArityMismatch(S, Cand, NumArgs); 9280 9281 case ovl_fail_bad_deduction: 9282 return DiagnoseBadDeduction(S, Cand, NumArgs); 9283 9284 case ovl_fail_illegal_constructor: { 9285 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9286 << (Fn->getPrimaryTemplate() ? 1 : 0); 9287 MaybeEmitInheritedConstructorNote(S, Fn); 9288 return; 9289 } 9290 9291 case ovl_fail_trivial_conversion: 9292 case ovl_fail_bad_final_conversion: 9293 case ovl_fail_final_conversion_not_exact: 9294 return S.NoteOverloadCandidate(Fn); 9295 9296 case ovl_fail_bad_conversion: { 9297 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9298 for (unsigned N = Cand->NumConversions; I != N; ++I) 9299 if (Cand->Conversions[I].isBad()) 9300 return DiagnoseBadConversion(S, Cand, I); 9301 9302 // FIXME: this currently happens when we're called from SemaInit 9303 // when user-conversion overload fails. Figure out how to handle 9304 // those conditions and diagnose them well. 9305 return S.NoteOverloadCandidate(Fn); 9306 } 9307 9308 case ovl_fail_bad_target: 9309 return DiagnoseBadTarget(S, Cand); 9310 9311 case ovl_fail_enable_if: 9312 return DiagnoseFailedEnableIfAttr(S, Cand); 9313 } 9314 } 9315 9316 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9317 // Desugar the type of the surrogate down to a function type, 9318 // retaining as many typedefs as possible while still showing 9319 // the function type (and, therefore, its parameter types). 9320 QualType FnType = Cand->Surrogate->getConversionType(); 9321 bool isLValueReference = false; 9322 bool isRValueReference = false; 9323 bool isPointer = false; 9324 if (const LValueReferenceType *FnTypeRef = 9325 FnType->getAs<LValueReferenceType>()) { 9326 FnType = FnTypeRef->getPointeeType(); 9327 isLValueReference = true; 9328 } else if (const RValueReferenceType *FnTypeRef = 9329 FnType->getAs<RValueReferenceType>()) { 9330 FnType = FnTypeRef->getPointeeType(); 9331 isRValueReference = true; 9332 } 9333 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9334 FnType = FnTypePtr->getPointeeType(); 9335 isPointer = true; 9336 } 9337 // Desugar down to a function type. 9338 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9339 // Reconstruct the pointer/reference as appropriate. 9340 if (isPointer) FnType = S.Context.getPointerType(FnType); 9341 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9342 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9343 9344 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9345 << FnType; 9346 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9347 } 9348 9349 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9350 SourceLocation OpLoc, 9351 OverloadCandidate *Cand) { 9352 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9353 std::string TypeStr("operator"); 9354 TypeStr += Opc; 9355 TypeStr += "("; 9356 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9357 if (Cand->NumConversions == 1) { 9358 TypeStr += ")"; 9359 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9360 } else { 9361 TypeStr += ", "; 9362 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9363 TypeStr += ")"; 9364 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9365 } 9366 } 9367 9368 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9369 OverloadCandidate *Cand) { 9370 unsigned NoOperands = Cand->NumConversions; 9371 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9372 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9373 if (ICS.isBad()) break; // all meaningless after first invalid 9374 if (!ICS.isAmbiguous()) continue; 9375 9376 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9377 S.PDiag(diag::note_ambiguous_type_conversion)); 9378 } 9379 } 9380 9381 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9382 if (Cand->Function) 9383 return Cand->Function->getLocation(); 9384 if (Cand->IsSurrogate) 9385 return Cand->Surrogate->getLocation(); 9386 return SourceLocation(); 9387 } 9388 9389 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9390 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9391 case Sema::TDK_Success: 9392 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9393 9394 case Sema::TDK_Invalid: 9395 case Sema::TDK_Incomplete: 9396 return 1; 9397 9398 case Sema::TDK_Underqualified: 9399 case Sema::TDK_Inconsistent: 9400 return 2; 9401 9402 case Sema::TDK_SubstitutionFailure: 9403 case Sema::TDK_NonDeducedMismatch: 9404 case Sema::TDK_MiscellaneousDeductionFailure: 9405 return 3; 9406 9407 case Sema::TDK_InstantiationDepth: 9408 case Sema::TDK_FailedOverloadResolution: 9409 return 4; 9410 9411 case Sema::TDK_InvalidExplicitArguments: 9412 return 5; 9413 9414 case Sema::TDK_TooManyArguments: 9415 case Sema::TDK_TooFewArguments: 9416 return 6; 9417 } 9418 llvm_unreachable("Unhandled deduction result"); 9419 } 9420 9421 namespace { 9422 struct CompareOverloadCandidatesForDisplay { 9423 Sema &S; 9424 size_t NumArgs; 9425 9426 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs) 9427 : S(S), NumArgs(nArgs) {} 9428 9429 bool operator()(const OverloadCandidate *L, 9430 const OverloadCandidate *R) { 9431 // Fast-path this check. 9432 if (L == R) return false; 9433 9434 // Order first by viability. 9435 if (L->Viable) { 9436 if (!R->Viable) return true; 9437 9438 // TODO: introduce a tri-valued comparison for overload 9439 // candidates. Would be more worthwhile if we had a sort 9440 // that could exploit it. 9441 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9442 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9443 } else if (R->Viable) 9444 return false; 9445 9446 assert(L->Viable == R->Viable); 9447 9448 // Criteria by which we can sort non-viable candidates: 9449 if (!L->Viable) { 9450 // 1. Arity mismatches come after other candidates. 9451 if (L->FailureKind == ovl_fail_too_many_arguments || 9452 L->FailureKind == ovl_fail_too_few_arguments) { 9453 if (R->FailureKind == ovl_fail_too_many_arguments || 9454 R->FailureKind == ovl_fail_too_few_arguments) { 9455 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9456 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9457 if (LDist == RDist) { 9458 if (L->FailureKind == R->FailureKind) 9459 // Sort non-surrogates before surrogates. 9460 return !L->IsSurrogate && R->IsSurrogate; 9461 // Sort candidates requiring fewer parameters than there were 9462 // arguments given after candidates requiring more parameters 9463 // than there were arguments given. 9464 return L->FailureKind == ovl_fail_too_many_arguments; 9465 } 9466 return LDist < RDist; 9467 } 9468 return false; 9469 } 9470 if (R->FailureKind == ovl_fail_too_many_arguments || 9471 R->FailureKind == ovl_fail_too_few_arguments) 9472 return true; 9473 9474 // 2. Bad conversions come first and are ordered by the number 9475 // of bad conversions and quality of good conversions. 9476 if (L->FailureKind == ovl_fail_bad_conversion) { 9477 if (R->FailureKind != ovl_fail_bad_conversion) 9478 return true; 9479 9480 // The conversion that can be fixed with a smaller number of changes, 9481 // comes first. 9482 unsigned numLFixes = L->Fix.NumConversionsFixed; 9483 unsigned numRFixes = R->Fix.NumConversionsFixed; 9484 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9485 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9486 if (numLFixes != numRFixes) { 9487 return numLFixes < numRFixes; 9488 } 9489 9490 // If there's any ordering between the defined conversions... 9491 // FIXME: this might not be transitive. 9492 assert(L->NumConversions == R->NumConversions); 9493 9494 int leftBetter = 0; 9495 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9496 for (unsigned E = L->NumConversions; I != E; ++I) { 9497 switch (CompareImplicitConversionSequences(S, 9498 L->Conversions[I], 9499 R->Conversions[I])) { 9500 case ImplicitConversionSequence::Better: 9501 leftBetter++; 9502 break; 9503 9504 case ImplicitConversionSequence::Worse: 9505 leftBetter--; 9506 break; 9507 9508 case ImplicitConversionSequence::Indistinguishable: 9509 break; 9510 } 9511 } 9512 if (leftBetter > 0) return true; 9513 if (leftBetter < 0) return false; 9514 9515 } else if (R->FailureKind == ovl_fail_bad_conversion) 9516 return false; 9517 9518 if (L->FailureKind == ovl_fail_bad_deduction) { 9519 if (R->FailureKind != ovl_fail_bad_deduction) 9520 return true; 9521 9522 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9523 return RankDeductionFailure(L->DeductionFailure) 9524 < RankDeductionFailure(R->DeductionFailure); 9525 } else if (R->FailureKind == ovl_fail_bad_deduction) 9526 return false; 9527 9528 // TODO: others? 9529 } 9530 9531 // Sort everything else by location. 9532 SourceLocation LLoc = GetLocationForCandidate(L); 9533 SourceLocation RLoc = GetLocationForCandidate(R); 9534 9535 // Put candidates without locations (e.g. builtins) at the end. 9536 if (LLoc.isInvalid()) return false; 9537 if (RLoc.isInvalid()) return true; 9538 9539 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9540 } 9541 }; 9542 } 9543 9544 /// CompleteNonViableCandidate - Normally, overload resolution only 9545 /// computes up to the first. Produces the FixIt set if possible. 9546 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9547 ArrayRef<Expr *> Args) { 9548 assert(!Cand->Viable); 9549 9550 // Don't do anything on failures other than bad conversion. 9551 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9552 9553 // We only want the FixIts if all the arguments can be corrected. 9554 bool Unfixable = false; 9555 // Use a implicit copy initialization to check conversion fixes. 9556 Cand->Fix.setConversionChecker(TryCopyInitialization); 9557 9558 // Skip forward to the first bad conversion. 9559 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9560 unsigned ConvCount = Cand->NumConversions; 9561 while (true) { 9562 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9563 ConvIdx++; 9564 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9565 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9566 break; 9567 } 9568 } 9569 9570 if (ConvIdx == ConvCount) 9571 return; 9572 9573 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9574 "remaining conversion is initialized?"); 9575 9576 // FIXME: this should probably be preserved from the overload 9577 // operation somehow. 9578 bool SuppressUserConversions = false; 9579 9580 const FunctionProtoType* Proto; 9581 unsigned ArgIdx = ConvIdx; 9582 9583 if (Cand->IsSurrogate) { 9584 QualType ConvType 9585 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9586 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9587 ConvType = ConvPtrType->getPointeeType(); 9588 Proto = ConvType->getAs<FunctionProtoType>(); 9589 ArgIdx--; 9590 } else if (Cand->Function) { 9591 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9592 if (isa<CXXMethodDecl>(Cand->Function) && 9593 !isa<CXXConstructorDecl>(Cand->Function)) 9594 ArgIdx--; 9595 } else { 9596 // Builtin binary operator with a bad first conversion. 9597 assert(ConvCount <= 3); 9598 for (; ConvIdx != ConvCount; ++ConvIdx) 9599 Cand->Conversions[ConvIdx] 9600 = TryCopyInitialization(S, Args[ConvIdx], 9601 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9602 SuppressUserConversions, 9603 /*InOverloadResolution*/ true, 9604 /*AllowObjCWritebackConversion=*/ 9605 S.getLangOpts().ObjCAutoRefCount); 9606 return; 9607 } 9608 9609 // Fill in the rest of the conversions. 9610 unsigned NumParams = Proto->getNumParams(); 9611 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9612 if (ArgIdx < NumParams) { 9613 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9614 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9615 /*InOverloadResolution=*/true, 9616 /*AllowObjCWritebackConversion=*/ 9617 S.getLangOpts().ObjCAutoRefCount); 9618 // Store the FixIt in the candidate if it exists. 9619 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9620 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9621 } 9622 else 9623 Cand->Conversions[ConvIdx].setEllipsis(); 9624 } 9625 } 9626 9627 /// PrintOverloadCandidates - When overload resolution fails, prints 9628 /// diagnostic messages containing the candidates in the candidate 9629 /// set. 9630 void OverloadCandidateSet::NoteCandidates(Sema &S, 9631 OverloadCandidateDisplayKind OCD, 9632 ArrayRef<Expr *> Args, 9633 StringRef Opc, 9634 SourceLocation OpLoc) { 9635 // Sort the candidates by viability and position. Sorting directly would 9636 // be prohibitive, so we make a set of pointers and sort those. 9637 SmallVector<OverloadCandidate*, 32> Cands; 9638 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9639 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9640 if (Cand->Viable) 9641 Cands.push_back(Cand); 9642 else if (OCD == OCD_AllCandidates) { 9643 CompleteNonViableCandidate(S, Cand, Args); 9644 if (Cand->Function || Cand->IsSurrogate) 9645 Cands.push_back(Cand); 9646 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9647 // want to list every possible builtin candidate. 9648 } 9649 } 9650 9651 std::sort(Cands.begin(), Cands.end(), 9652 CompareOverloadCandidatesForDisplay(S, Args.size())); 9653 9654 bool ReportedAmbiguousConversions = false; 9655 9656 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9657 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9658 unsigned CandsShown = 0; 9659 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9660 OverloadCandidate *Cand = *I; 9661 9662 // Set an arbitrary limit on the number of candidate functions we'll spam 9663 // the user with. FIXME: This limit should depend on details of the 9664 // candidate list. 9665 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9666 break; 9667 } 9668 ++CandsShown; 9669 9670 if (Cand->Function) 9671 NoteFunctionCandidate(S, Cand, Args.size()); 9672 else if (Cand->IsSurrogate) 9673 NoteSurrogateCandidate(S, Cand); 9674 else { 9675 assert(Cand->Viable && 9676 "Non-viable built-in candidates are not added to Cands."); 9677 // Generally we only see ambiguities including viable builtin 9678 // operators if overload resolution got screwed up by an 9679 // ambiguous user-defined conversion. 9680 // 9681 // FIXME: It's quite possible for different conversions to see 9682 // different ambiguities, though. 9683 if (!ReportedAmbiguousConversions) { 9684 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9685 ReportedAmbiguousConversions = true; 9686 } 9687 9688 // If this is a viable builtin, print it. 9689 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9690 } 9691 } 9692 9693 if (I != E) 9694 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9695 } 9696 9697 static SourceLocation 9698 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9699 return Cand->Specialization ? Cand->Specialization->getLocation() 9700 : SourceLocation(); 9701 } 9702 9703 namespace { 9704 struct CompareTemplateSpecCandidatesForDisplay { 9705 Sema &S; 9706 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9707 9708 bool operator()(const TemplateSpecCandidate *L, 9709 const TemplateSpecCandidate *R) { 9710 // Fast-path this check. 9711 if (L == R) 9712 return false; 9713 9714 // Assuming that both candidates are not matches... 9715 9716 // Sort by the ranking of deduction failures. 9717 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9718 return RankDeductionFailure(L->DeductionFailure) < 9719 RankDeductionFailure(R->DeductionFailure); 9720 9721 // Sort everything else by location. 9722 SourceLocation LLoc = GetLocationForCandidate(L); 9723 SourceLocation RLoc = GetLocationForCandidate(R); 9724 9725 // Put candidates without locations (e.g. builtins) at the end. 9726 if (LLoc.isInvalid()) 9727 return false; 9728 if (RLoc.isInvalid()) 9729 return true; 9730 9731 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9732 } 9733 }; 9734 } 9735 9736 /// Diagnose a template argument deduction failure. 9737 /// We are treating these failures as overload failures due to bad 9738 /// deductions. 9739 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9740 DiagnoseBadDeduction(S, Specialization, // pattern 9741 DeductionFailure, /*NumArgs=*/0); 9742 } 9743 9744 void TemplateSpecCandidateSet::destroyCandidates() { 9745 for (iterator i = begin(), e = end(); i != e; ++i) { 9746 i->DeductionFailure.Destroy(); 9747 } 9748 } 9749 9750 void TemplateSpecCandidateSet::clear() { 9751 destroyCandidates(); 9752 Candidates.clear(); 9753 } 9754 9755 /// NoteCandidates - When no template specialization match is found, prints 9756 /// diagnostic messages containing the non-matching specializations that form 9757 /// the candidate set. 9758 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9759 /// OCD == OCD_AllCandidates and Cand->Viable == false. 9760 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9761 // Sort the candidates by position (assuming no candidate is a match). 9762 // Sorting directly would be prohibitive, so we make a set of pointers 9763 // and sort those. 9764 SmallVector<TemplateSpecCandidate *, 32> Cands; 9765 Cands.reserve(size()); 9766 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9767 if (Cand->Specialization) 9768 Cands.push_back(Cand); 9769 // Otherwise, this is a non-matching builtin candidate. We do not, 9770 // in general, want to list every possible builtin candidate. 9771 } 9772 9773 std::sort(Cands.begin(), Cands.end(), 9774 CompareTemplateSpecCandidatesForDisplay(S)); 9775 9776 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9777 // for generalization purposes (?). 9778 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9779 9780 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9781 unsigned CandsShown = 0; 9782 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9783 TemplateSpecCandidate *Cand = *I; 9784 9785 // Set an arbitrary limit on the number of candidates we'll spam 9786 // the user with. FIXME: This limit should depend on details of the 9787 // candidate list. 9788 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9789 break; 9790 ++CandsShown; 9791 9792 assert(Cand->Specialization && 9793 "Non-matching built-in candidates are not added to Cands."); 9794 Cand->NoteDeductionFailure(S); 9795 } 9796 9797 if (I != E) 9798 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9799 } 9800 9801 // [PossiblyAFunctionType] --> [Return] 9802 // NonFunctionType --> NonFunctionType 9803 // R (A) --> R(A) 9804 // R (*)(A) --> R (A) 9805 // R (&)(A) --> R (A) 9806 // R (S::*)(A) --> R (A) 9807 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9808 QualType Ret = PossiblyAFunctionType; 9809 if (const PointerType *ToTypePtr = 9810 PossiblyAFunctionType->getAs<PointerType>()) 9811 Ret = ToTypePtr->getPointeeType(); 9812 else if (const ReferenceType *ToTypeRef = 9813 PossiblyAFunctionType->getAs<ReferenceType>()) 9814 Ret = ToTypeRef->getPointeeType(); 9815 else if (const MemberPointerType *MemTypePtr = 9816 PossiblyAFunctionType->getAs<MemberPointerType>()) 9817 Ret = MemTypePtr->getPointeeType(); 9818 Ret = 9819 Context.getCanonicalType(Ret).getUnqualifiedType(); 9820 return Ret; 9821 } 9822 9823 namespace { 9824 // A helper class to help with address of function resolution 9825 // - allows us to avoid passing around all those ugly parameters 9826 class AddressOfFunctionResolver { 9827 Sema& S; 9828 Expr* SourceExpr; 9829 const QualType& TargetType; 9830 QualType TargetFunctionType; // Extracted function type from target type 9831 9832 bool Complain; 9833 //DeclAccessPair& ResultFunctionAccessPair; 9834 ASTContext& Context; 9835 9836 bool TargetTypeIsNonStaticMemberFunction; 9837 bool FoundNonTemplateFunction; 9838 bool StaticMemberFunctionFromBoundPointer; 9839 9840 OverloadExpr::FindResult OvlExprInfo; 9841 OverloadExpr *OvlExpr; 9842 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9843 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9844 TemplateSpecCandidateSet FailedCandidates; 9845 9846 public: 9847 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9848 const QualType &TargetType, bool Complain) 9849 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9850 Complain(Complain), Context(S.getASTContext()), 9851 TargetTypeIsNonStaticMemberFunction( 9852 !!TargetType->getAs<MemberPointerType>()), 9853 FoundNonTemplateFunction(false), 9854 StaticMemberFunctionFromBoundPointer(false), 9855 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9856 OvlExpr(OvlExprInfo.Expression), 9857 FailedCandidates(OvlExpr->getNameLoc()) { 9858 ExtractUnqualifiedFunctionTypeFromTargetType(); 9859 9860 if (TargetFunctionType->isFunctionType()) { 9861 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 9862 if (!UME->isImplicitAccess() && 9863 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 9864 StaticMemberFunctionFromBoundPointer = true; 9865 } else if (OvlExpr->hasExplicitTemplateArgs()) { 9866 DeclAccessPair dap; 9867 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 9868 OvlExpr, false, &dap)) { 9869 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 9870 if (!Method->isStatic()) { 9871 // If the target type is a non-function type and the function found 9872 // is a non-static member function, pretend as if that was the 9873 // target, it's the only possible type to end up with. 9874 TargetTypeIsNonStaticMemberFunction = true; 9875 9876 // And skip adding the function if its not in the proper form. 9877 // We'll diagnose this due to an empty set of functions. 9878 if (!OvlExprInfo.HasFormOfMemberPointer) 9879 return; 9880 } 9881 9882 Matches.push_back(std::make_pair(dap, Fn)); 9883 } 9884 return; 9885 } 9886 9887 if (OvlExpr->hasExplicitTemplateArgs()) 9888 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9889 9890 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9891 // C++ [over.over]p4: 9892 // If more than one function is selected, [...] 9893 if (Matches.size() > 1) { 9894 if (FoundNonTemplateFunction) 9895 EliminateAllTemplateMatches(); 9896 else 9897 EliminateAllExceptMostSpecializedTemplate(); 9898 } 9899 } 9900 } 9901 9902 private: 9903 bool isTargetTypeAFunction() const { 9904 return TargetFunctionType->isFunctionType(); 9905 } 9906 9907 // [ToType] [Return] 9908 9909 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9910 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9911 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9912 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9913 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9914 } 9915 9916 // return true if any matching specializations were found 9917 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9918 const DeclAccessPair& CurAccessFunPair) { 9919 if (CXXMethodDecl *Method 9920 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9921 // Skip non-static function templates when converting to pointer, and 9922 // static when converting to member pointer. 9923 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9924 return false; 9925 } 9926 else if (TargetTypeIsNonStaticMemberFunction) 9927 return false; 9928 9929 // C++ [over.over]p2: 9930 // If the name is a function template, template argument deduction is 9931 // done (14.8.2.2), and if the argument deduction succeeds, the 9932 // resulting template argument list is used to generate a single 9933 // function template specialization, which is added to the set of 9934 // overloaded functions considered. 9935 FunctionDecl *Specialization = nullptr; 9936 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9937 if (Sema::TemplateDeductionResult Result 9938 = S.DeduceTemplateArguments(FunctionTemplate, 9939 &OvlExplicitTemplateArgs, 9940 TargetFunctionType, Specialization, 9941 Info, /*InOverloadResolution=*/true)) { 9942 // Make a note of the failed deduction for diagnostics. 9943 FailedCandidates.addCandidate() 9944 .set(FunctionTemplate->getTemplatedDecl(), 9945 MakeDeductionFailureInfo(Context, Result, Info)); 9946 return false; 9947 } 9948 9949 // Template argument deduction ensures that we have an exact match or 9950 // compatible pointer-to-function arguments that would be adjusted by ICS. 9951 // This function template specicalization works. 9952 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9953 assert(S.isSameOrCompatibleFunctionType( 9954 Context.getCanonicalType(Specialization->getType()), 9955 Context.getCanonicalType(TargetFunctionType))); 9956 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9957 return true; 9958 } 9959 9960 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9961 const DeclAccessPair& CurAccessFunPair) { 9962 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9963 // Skip non-static functions when converting to pointer, and static 9964 // when converting to member pointer. 9965 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9966 return false; 9967 } 9968 else if (TargetTypeIsNonStaticMemberFunction) 9969 return false; 9970 9971 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9972 if (S.getLangOpts().CUDA) 9973 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9974 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 9975 return false; 9976 9977 // If any candidate has a placeholder return type, trigger its deduction 9978 // now. 9979 if (S.getLangOpts().CPlusPlus14 && 9980 FunDecl->getReturnType()->isUndeducedType() && 9981 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9982 return false; 9983 9984 QualType ResultTy; 9985 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9986 FunDecl->getType()) || 9987 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9988 ResultTy)) { 9989 Matches.push_back(std::make_pair(CurAccessFunPair, 9990 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9991 FoundNonTemplateFunction = true; 9992 return true; 9993 } 9994 } 9995 9996 return false; 9997 } 9998 9999 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10000 bool Ret = false; 10001 10002 // If the overload expression doesn't have the form of a pointer to 10003 // member, don't try to convert it to a pointer-to-member type. 10004 if (IsInvalidFormOfPointerToMemberFunction()) 10005 return false; 10006 10007 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10008 E = OvlExpr->decls_end(); 10009 I != E; ++I) { 10010 // Look through any using declarations to find the underlying function. 10011 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10012 10013 // C++ [over.over]p3: 10014 // Non-member functions and static member functions match 10015 // targets of type "pointer-to-function" or "reference-to-function." 10016 // Nonstatic member functions match targets of 10017 // type "pointer-to-member-function." 10018 // Note that according to DR 247, the containing class does not matter. 10019 if (FunctionTemplateDecl *FunctionTemplate 10020 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10021 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10022 Ret = true; 10023 } 10024 // If we have explicit template arguments supplied, skip non-templates. 10025 else if (!OvlExpr->hasExplicitTemplateArgs() && 10026 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10027 Ret = true; 10028 } 10029 assert(Ret || Matches.empty()); 10030 return Ret; 10031 } 10032 10033 void EliminateAllExceptMostSpecializedTemplate() { 10034 // [...] and any given function template specialization F1 is 10035 // eliminated if the set contains a second function template 10036 // specialization whose function template is more specialized 10037 // than the function template of F1 according to the partial 10038 // ordering rules of 14.5.5.2. 10039 10040 // The algorithm specified above is quadratic. We instead use a 10041 // two-pass algorithm (similar to the one used to identify the 10042 // best viable function in an overload set) that identifies the 10043 // best function template (if it exists). 10044 10045 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10046 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10047 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10048 10049 // TODO: It looks like FailedCandidates does not serve much purpose 10050 // here, since the no_viable diagnostic has index 0. 10051 UnresolvedSetIterator Result = S.getMostSpecialized( 10052 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10053 SourceExpr->getLocStart(), S.PDiag(), 10054 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10055 .second->getDeclName(), 10056 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10057 Complain, TargetFunctionType); 10058 10059 if (Result != MatchesCopy.end()) { 10060 // Make it the first and only element 10061 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10062 Matches[0].second = cast<FunctionDecl>(*Result); 10063 Matches.resize(1); 10064 } 10065 } 10066 10067 void EliminateAllTemplateMatches() { 10068 // [...] any function template specializations in the set are 10069 // eliminated if the set also contains a non-template function, [...] 10070 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10071 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10072 ++I; 10073 else { 10074 Matches[I] = Matches[--N]; 10075 Matches.set_size(N); 10076 } 10077 } 10078 } 10079 10080 public: 10081 void ComplainNoMatchesFound() const { 10082 assert(Matches.empty()); 10083 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10084 << OvlExpr->getName() << TargetFunctionType 10085 << OvlExpr->getSourceRange(); 10086 if (FailedCandidates.empty()) 10087 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 10088 else { 10089 // We have some deduction failure messages. Use them to diagnose 10090 // the function templates, and diagnose the non-template candidates 10091 // normally. 10092 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10093 IEnd = OvlExpr->decls_end(); 10094 I != IEnd; ++I) 10095 if (FunctionDecl *Fun = 10096 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10097 S.NoteOverloadCandidate(Fun, TargetFunctionType); 10098 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10099 } 10100 } 10101 10102 bool IsInvalidFormOfPointerToMemberFunction() const { 10103 return TargetTypeIsNonStaticMemberFunction && 10104 !OvlExprInfo.HasFormOfMemberPointer; 10105 } 10106 10107 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10108 // TODO: Should we condition this on whether any functions might 10109 // have matched, or is it more appropriate to do that in callers? 10110 // TODO: a fixit wouldn't hurt. 10111 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10112 << TargetType << OvlExpr->getSourceRange(); 10113 } 10114 10115 bool IsStaticMemberFunctionFromBoundPointer() const { 10116 return StaticMemberFunctionFromBoundPointer; 10117 } 10118 10119 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10120 S.Diag(OvlExpr->getLocStart(), 10121 diag::err_invalid_form_pointer_member_function) 10122 << OvlExpr->getSourceRange(); 10123 } 10124 10125 void ComplainOfInvalidConversion() const { 10126 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10127 << OvlExpr->getName() << TargetType; 10128 } 10129 10130 void ComplainMultipleMatchesFound() const { 10131 assert(Matches.size() > 1); 10132 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10133 << OvlExpr->getName() 10134 << OvlExpr->getSourceRange(); 10135 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 10136 } 10137 10138 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10139 10140 int getNumMatches() const { return Matches.size(); } 10141 10142 FunctionDecl* getMatchingFunctionDecl() const { 10143 if (Matches.size() != 1) return nullptr; 10144 return Matches[0].second; 10145 } 10146 10147 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10148 if (Matches.size() != 1) return nullptr; 10149 return &Matches[0].first; 10150 } 10151 }; 10152 } 10153 10154 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10155 /// an overloaded function (C++ [over.over]), where @p From is an 10156 /// expression with overloaded function type and @p ToType is the type 10157 /// we're trying to resolve to. For example: 10158 /// 10159 /// @code 10160 /// int f(double); 10161 /// int f(int); 10162 /// 10163 /// int (*pfd)(double) = f; // selects f(double) 10164 /// @endcode 10165 /// 10166 /// This routine returns the resulting FunctionDecl if it could be 10167 /// resolved, and NULL otherwise. When @p Complain is true, this 10168 /// routine will emit diagnostics if there is an error. 10169 FunctionDecl * 10170 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10171 QualType TargetType, 10172 bool Complain, 10173 DeclAccessPair &FoundResult, 10174 bool *pHadMultipleCandidates) { 10175 assert(AddressOfExpr->getType() == Context.OverloadTy); 10176 10177 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10178 Complain); 10179 int NumMatches = Resolver.getNumMatches(); 10180 FunctionDecl *Fn = nullptr; 10181 if (NumMatches == 0 && Complain) { 10182 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10183 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10184 else 10185 Resolver.ComplainNoMatchesFound(); 10186 } 10187 else if (NumMatches > 1 && Complain) 10188 Resolver.ComplainMultipleMatchesFound(); 10189 else if (NumMatches == 1) { 10190 Fn = Resolver.getMatchingFunctionDecl(); 10191 assert(Fn); 10192 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10193 if (Complain) { 10194 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10195 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10196 else 10197 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10198 } 10199 } 10200 10201 if (pHadMultipleCandidates) 10202 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10203 return Fn; 10204 } 10205 10206 /// \brief Given an expression that refers to an overloaded function, try to 10207 /// resolve that overloaded function expression down to a single function. 10208 /// 10209 /// This routine can only resolve template-ids that refer to a single function 10210 /// template, where that template-id refers to a single template whose template 10211 /// arguments are either provided by the template-id or have defaults, 10212 /// as described in C++0x [temp.arg.explicit]p3. 10213 /// 10214 /// If no template-ids are found, no diagnostics are emitted and NULL is 10215 /// returned. 10216 FunctionDecl * 10217 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10218 bool Complain, 10219 DeclAccessPair *FoundResult) { 10220 // C++ [over.over]p1: 10221 // [...] [Note: any redundant set of parentheses surrounding the 10222 // overloaded function name is ignored (5.1). ] 10223 // C++ [over.over]p1: 10224 // [...] The overloaded function name can be preceded by the & 10225 // operator. 10226 10227 // If we didn't actually find any template-ids, we're done. 10228 if (!ovl->hasExplicitTemplateArgs()) 10229 return nullptr; 10230 10231 TemplateArgumentListInfo ExplicitTemplateArgs; 10232 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 10233 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10234 10235 // Look through all of the overloaded functions, searching for one 10236 // whose type matches exactly. 10237 FunctionDecl *Matched = nullptr; 10238 for (UnresolvedSetIterator I = ovl->decls_begin(), 10239 E = ovl->decls_end(); I != E; ++I) { 10240 // C++0x [temp.arg.explicit]p3: 10241 // [...] In contexts where deduction is done and fails, or in contexts 10242 // where deduction is not done, if a template argument list is 10243 // specified and it, along with any default template arguments, 10244 // identifies a single function template specialization, then the 10245 // template-id is an lvalue for the function template specialization. 10246 FunctionTemplateDecl *FunctionTemplate 10247 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10248 10249 // C++ [over.over]p2: 10250 // If the name is a function template, template argument deduction is 10251 // done (14.8.2.2), and if the argument deduction succeeds, the 10252 // resulting template argument list is used to generate a single 10253 // function template specialization, which is added to the set of 10254 // overloaded functions considered. 10255 FunctionDecl *Specialization = nullptr; 10256 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10257 if (TemplateDeductionResult Result 10258 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10259 Specialization, Info, 10260 /*InOverloadResolution=*/true)) { 10261 // Make a note of the failed deduction for diagnostics. 10262 // TODO: Actually use the failed-deduction info? 10263 FailedCandidates.addCandidate() 10264 .set(FunctionTemplate->getTemplatedDecl(), 10265 MakeDeductionFailureInfo(Context, Result, Info)); 10266 continue; 10267 } 10268 10269 assert(Specialization && "no specialization and no error?"); 10270 10271 // Multiple matches; we can't resolve to a single declaration. 10272 if (Matched) { 10273 if (Complain) { 10274 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10275 << ovl->getName(); 10276 NoteAllOverloadCandidates(ovl); 10277 } 10278 return nullptr; 10279 } 10280 10281 Matched = Specialization; 10282 if (FoundResult) *FoundResult = I.getPair(); 10283 } 10284 10285 if (Matched && getLangOpts().CPlusPlus14 && 10286 Matched->getReturnType()->isUndeducedType() && 10287 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10288 return nullptr; 10289 10290 return Matched; 10291 } 10292 10293 10294 10295 10296 // Resolve and fix an overloaded expression that can be resolved 10297 // because it identifies a single function template specialization. 10298 // 10299 // Last three arguments should only be supplied if Complain = true 10300 // 10301 // Return true if it was logically possible to so resolve the 10302 // expression, regardless of whether or not it succeeded. Always 10303 // returns true if 'complain' is set. 10304 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10305 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10306 bool complain, const SourceRange& OpRangeForComplaining, 10307 QualType DestTypeForComplaining, 10308 unsigned DiagIDForComplaining) { 10309 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10310 10311 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10312 10313 DeclAccessPair found; 10314 ExprResult SingleFunctionExpression; 10315 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10316 ovl.Expression, /*complain*/ false, &found)) { 10317 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10318 SrcExpr = ExprError(); 10319 return true; 10320 } 10321 10322 // It is only correct to resolve to an instance method if we're 10323 // resolving a form that's permitted to be a pointer to member. 10324 // Otherwise we'll end up making a bound member expression, which 10325 // is illegal in all the contexts we resolve like this. 10326 if (!ovl.HasFormOfMemberPointer && 10327 isa<CXXMethodDecl>(fn) && 10328 cast<CXXMethodDecl>(fn)->isInstance()) { 10329 if (!complain) return false; 10330 10331 Diag(ovl.Expression->getExprLoc(), 10332 diag::err_bound_member_function) 10333 << 0 << ovl.Expression->getSourceRange(); 10334 10335 // TODO: I believe we only end up here if there's a mix of 10336 // static and non-static candidates (otherwise the expression 10337 // would have 'bound member' type, not 'overload' type). 10338 // Ideally we would note which candidate was chosen and why 10339 // the static candidates were rejected. 10340 SrcExpr = ExprError(); 10341 return true; 10342 } 10343 10344 // Fix the expression to refer to 'fn'. 10345 SingleFunctionExpression = 10346 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10347 10348 // If desired, do function-to-pointer decay. 10349 if (doFunctionPointerConverion) { 10350 SingleFunctionExpression = 10351 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10352 if (SingleFunctionExpression.isInvalid()) { 10353 SrcExpr = ExprError(); 10354 return true; 10355 } 10356 } 10357 } 10358 10359 if (!SingleFunctionExpression.isUsable()) { 10360 if (complain) { 10361 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10362 << ovl.Expression->getName() 10363 << DestTypeForComplaining 10364 << OpRangeForComplaining 10365 << ovl.Expression->getQualifierLoc().getSourceRange(); 10366 NoteAllOverloadCandidates(SrcExpr.get()); 10367 10368 SrcExpr = ExprError(); 10369 return true; 10370 } 10371 10372 return false; 10373 } 10374 10375 SrcExpr = SingleFunctionExpression; 10376 return true; 10377 } 10378 10379 /// \brief Add a single candidate to the overload set. 10380 static void AddOverloadedCallCandidate(Sema &S, 10381 DeclAccessPair FoundDecl, 10382 TemplateArgumentListInfo *ExplicitTemplateArgs, 10383 ArrayRef<Expr *> Args, 10384 OverloadCandidateSet &CandidateSet, 10385 bool PartialOverloading, 10386 bool KnownValid) { 10387 NamedDecl *Callee = FoundDecl.getDecl(); 10388 if (isa<UsingShadowDecl>(Callee)) 10389 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10390 10391 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10392 if (ExplicitTemplateArgs) { 10393 assert(!KnownValid && "Explicit template arguments?"); 10394 return; 10395 } 10396 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10397 /*SuppressUsedConversions=*/false, 10398 PartialOverloading); 10399 return; 10400 } 10401 10402 if (FunctionTemplateDecl *FuncTemplate 10403 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10404 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10405 ExplicitTemplateArgs, Args, CandidateSet, 10406 /*SuppressUsedConversions=*/false, 10407 PartialOverloading); 10408 return; 10409 } 10410 10411 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10412 } 10413 10414 /// \brief Add the overload candidates named by callee and/or found by argument 10415 /// dependent lookup to the given overload set. 10416 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10417 ArrayRef<Expr *> Args, 10418 OverloadCandidateSet &CandidateSet, 10419 bool PartialOverloading) { 10420 10421 #ifndef NDEBUG 10422 // Verify that ArgumentDependentLookup is consistent with the rules 10423 // in C++0x [basic.lookup.argdep]p3: 10424 // 10425 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10426 // and let Y be the lookup set produced by argument dependent 10427 // lookup (defined as follows). If X contains 10428 // 10429 // -- a declaration of a class member, or 10430 // 10431 // -- a block-scope function declaration that is not a 10432 // using-declaration, or 10433 // 10434 // -- a declaration that is neither a function or a function 10435 // template 10436 // 10437 // then Y is empty. 10438 10439 if (ULE->requiresADL()) { 10440 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10441 E = ULE->decls_end(); I != E; ++I) { 10442 assert(!(*I)->getDeclContext()->isRecord()); 10443 assert(isa<UsingShadowDecl>(*I) || 10444 !(*I)->getDeclContext()->isFunctionOrMethod()); 10445 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10446 } 10447 } 10448 #endif 10449 10450 // It would be nice to avoid this copy. 10451 TemplateArgumentListInfo TABuffer; 10452 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10453 if (ULE->hasExplicitTemplateArgs()) { 10454 ULE->copyTemplateArgumentsInto(TABuffer); 10455 ExplicitTemplateArgs = &TABuffer; 10456 } 10457 10458 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10459 E = ULE->decls_end(); I != E; ++I) 10460 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10461 CandidateSet, PartialOverloading, 10462 /*KnownValid*/ true); 10463 10464 if (ULE->requiresADL()) 10465 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10466 Args, ExplicitTemplateArgs, 10467 CandidateSet, PartialOverloading); 10468 } 10469 10470 /// Determine whether a declaration with the specified name could be moved into 10471 /// a different namespace. 10472 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10473 switch (Name.getCXXOverloadedOperator()) { 10474 case OO_New: case OO_Array_New: 10475 case OO_Delete: case OO_Array_Delete: 10476 return false; 10477 10478 default: 10479 return true; 10480 } 10481 } 10482 10483 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10484 /// template, where the non-dependent name was declared after the template 10485 /// was defined. This is common in code written for a compilers which do not 10486 /// correctly implement two-stage name lookup. 10487 /// 10488 /// Returns true if a viable candidate was found and a diagnostic was issued. 10489 static bool 10490 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10491 const CXXScopeSpec &SS, LookupResult &R, 10492 OverloadCandidateSet::CandidateSetKind CSK, 10493 TemplateArgumentListInfo *ExplicitTemplateArgs, 10494 ArrayRef<Expr *> Args, 10495 bool *DoDiagnoseEmptyLookup = nullptr) { 10496 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10497 return false; 10498 10499 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10500 if (DC->isTransparentContext()) 10501 continue; 10502 10503 SemaRef.LookupQualifiedName(R, DC); 10504 10505 if (!R.empty()) { 10506 R.suppressDiagnostics(); 10507 10508 if (isa<CXXRecordDecl>(DC)) { 10509 // Don't diagnose names we find in classes; we get much better 10510 // diagnostics for these from DiagnoseEmptyLookup. 10511 R.clear(); 10512 if (DoDiagnoseEmptyLookup) 10513 *DoDiagnoseEmptyLookup = true; 10514 return false; 10515 } 10516 10517 OverloadCandidateSet Candidates(FnLoc, CSK); 10518 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10519 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10520 ExplicitTemplateArgs, Args, 10521 Candidates, false, /*KnownValid*/ false); 10522 10523 OverloadCandidateSet::iterator Best; 10524 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10525 // No viable functions. Don't bother the user with notes for functions 10526 // which don't work and shouldn't be found anyway. 10527 R.clear(); 10528 return false; 10529 } 10530 10531 // Find the namespaces where ADL would have looked, and suggest 10532 // declaring the function there instead. 10533 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10534 Sema::AssociatedClassSet AssociatedClasses; 10535 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10536 AssociatedNamespaces, 10537 AssociatedClasses); 10538 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10539 if (canBeDeclaredInNamespace(R.getLookupName())) { 10540 DeclContext *Std = SemaRef.getStdNamespace(); 10541 for (Sema::AssociatedNamespaceSet::iterator 10542 it = AssociatedNamespaces.begin(), 10543 end = AssociatedNamespaces.end(); it != end; ++it) { 10544 // Never suggest declaring a function within namespace 'std'. 10545 if (Std && Std->Encloses(*it)) 10546 continue; 10547 10548 // Never suggest declaring a function within a namespace with a 10549 // reserved name, like __gnu_cxx. 10550 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10551 if (NS && 10552 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10553 continue; 10554 10555 SuggestedNamespaces.insert(*it); 10556 } 10557 } 10558 10559 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10560 << R.getLookupName(); 10561 if (SuggestedNamespaces.empty()) { 10562 SemaRef.Diag(Best->Function->getLocation(), 10563 diag::note_not_found_by_two_phase_lookup) 10564 << R.getLookupName() << 0; 10565 } else if (SuggestedNamespaces.size() == 1) { 10566 SemaRef.Diag(Best->Function->getLocation(), 10567 diag::note_not_found_by_two_phase_lookup) 10568 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10569 } else { 10570 // FIXME: It would be useful to list the associated namespaces here, 10571 // but the diagnostics infrastructure doesn't provide a way to produce 10572 // a localized representation of a list of items. 10573 SemaRef.Diag(Best->Function->getLocation(), 10574 diag::note_not_found_by_two_phase_lookup) 10575 << R.getLookupName() << 2; 10576 } 10577 10578 // Try to recover by calling this function. 10579 return true; 10580 } 10581 10582 R.clear(); 10583 } 10584 10585 return false; 10586 } 10587 10588 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10589 /// template, where the non-dependent operator was declared after the template 10590 /// was defined. 10591 /// 10592 /// Returns true if a viable candidate was found and a diagnostic was issued. 10593 static bool 10594 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10595 SourceLocation OpLoc, 10596 ArrayRef<Expr *> Args) { 10597 DeclarationName OpName = 10598 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10599 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10600 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10601 OverloadCandidateSet::CSK_Operator, 10602 /*ExplicitTemplateArgs=*/nullptr, Args); 10603 } 10604 10605 namespace { 10606 class BuildRecoveryCallExprRAII { 10607 Sema &SemaRef; 10608 public: 10609 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10610 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10611 SemaRef.IsBuildingRecoveryCallExpr = true; 10612 } 10613 10614 ~BuildRecoveryCallExprRAII() { 10615 SemaRef.IsBuildingRecoveryCallExpr = false; 10616 } 10617 }; 10618 10619 } 10620 10621 static std::unique_ptr<CorrectionCandidateCallback> 10622 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 10623 bool HasTemplateArgs, bool AllowTypoCorrection) { 10624 if (!AllowTypoCorrection) 10625 return llvm::make_unique<NoTypoCorrectionCCC>(); 10626 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 10627 HasTemplateArgs, ME); 10628 } 10629 10630 /// Attempts to recover from a call where no functions were found. 10631 /// 10632 /// Returns true if new candidates were found. 10633 static ExprResult 10634 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10635 UnresolvedLookupExpr *ULE, 10636 SourceLocation LParenLoc, 10637 MutableArrayRef<Expr *> Args, 10638 SourceLocation RParenLoc, 10639 bool EmptyLookup, bool AllowTypoCorrection) { 10640 // Do not try to recover if it is already building a recovery call. 10641 // This stops infinite loops for template instantiations like 10642 // 10643 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10644 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10645 // 10646 if (SemaRef.IsBuildingRecoveryCallExpr) 10647 return ExprError(); 10648 BuildRecoveryCallExprRAII RCE(SemaRef); 10649 10650 CXXScopeSpec SS; 10651 SS.Adopt(ULE->getQualifierLoc()); 10652 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10653 10654 TemplateArgumentListInfo TABuffer; 10655 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10656 if (ULE->hasExplicitTemplateArgs()) { 10657 ULE->copyTemplateArgumentsInto(TABuffer); 10658 ExplicitTemplateArgs = &TABuffer; 10659 } 10660 10661 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10662 Sema::LookupOrdinaryName); 10663 bool DoDiagnoseEmptyLookup = EmptyLookup; 10664 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10665 OverloadCandidateSet::CSK_Normal, 10666 ExplicitTemplateArgs, Args, 10667 &DoDiagnoseEmptyLookup) && 10668 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 10669 S, SS, R, 10670 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 10671 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 10672 ExplicitTemplateArgs, Args))) 10673 return ExprError(); 10674 10675 assert(!R.empty() && "lookup results empty despite recovery"); 10676 10677 // Build an implicit member call if appropriate. Just drop the 10678 // casts and such from the call, we don't really care. 10679 ExprResult NewFn = ExprError(); 10680 if ((*R.begin())->isCXXClassMember()) 10681 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10682 R, ExplicitTemplateArgs); 10683 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10684 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10685 ExplicitTemplateArgs); 10686 else 10687 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10688 10689 if (NewFn.isInvalid()) 10690 return ExprError(); 10691 10692 // This shouldn't cause an infinite loop because we're giving it 10693 // an expression with viable lookup results, which should never 10694 // end up here. 10695 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 10696 MultiExprArg(Args.data(), Args.size()), 10697 RParenLoc); 10698 } 10699 10700 /// \brief Constructs and populates an OverloadedCandidateSet from 10701 /// the given function. 10702 /// \returns true when an the ExprResult output parameter has been set. 10703 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10704 UnresolvedLookupExpr *ULE, 10705 MultiExprArg Args, 10706 SourceLocation RParenLoc, 10707 OverloadCandidateSet *CandidateSet, 10708 ExprResult *Result) { 10709 #ifndef NDEBUG 10710 if (ULE->requiresADL()) { 10711 // To do ADL, we must have found an unqualified name. 10712 assert(!ULE->getQualifier() && "qualified name with ADL"); 10713 10714 // We don't perform ADL for implicit declarations of builtins. 10715 // Verify that this was correctly set up. 10716 FunctionDecl *F; 10717 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10718 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10719 F->getBuiltinID() && F->isImplicit()) 10720 llvm_unreachable("performing ADL for builtin"); 10721 10722 // We don't perform ADL in C. 10723 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10724 } 10725 #endif 10726 10727 UnbridgedCastsSet UnbridgedCasts; 10728 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10729 *Result = ExprError(); 10730 return true; 10731 } 10732 10733 // Add the functions denoted by the callee to the set of candidate 10734 // functions, including those from argument-dependent lookup. 10735 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10736 10737 if (getLangOpts().MSVCCompat && 10738 CurContext->isDependentContext() && !isSFINAEContext() && 10739 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10740 10741 OverloadCandidateSet::iterator Best; 10742 if (CandidateSet->empty() || 10743 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 10744 OR_No_Viable_Function) { 10745 // In Microsoft mode, if we are inside a template class member function then 10746 // create a type dependent CallExpr. The goal is to postpone name lookup 10747 // to instantiation time to be able to search into type dependent base 10748 // classes. 10749 CallExpr *CE = new (Context) CallExpr( 10750 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 10751 CE->setTypeDependent(true); 10752 *Result = CE; 10753 return true; 10754 } 10755 } 10756 10757 if (CandidateSet->empty()) 10758 return false; 10759 10760 UnbridgedCasts.restore(); 10761 return false; 10762 } 10763 10764 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10765 /// the completed call expression. If overload resolution fails, emits 10766 /// diagnostics and returns ExprError() 10767 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10768 UnresolvedLookupExpr *ULE, 10769 SourceLocation LParenLoc, 10770 MultiExprArg Args, 10771 SourceLocation RParenLoc, 10772 Expr *ExecConfig, 10773 OverloadCandidateSet *CandidateSet, 10774 OverloadCandidateSet::iterator *Best, 10775 OverloadingResult OverloadResult, 10776 bool AllowTypoCorrection) { 10777 if (CandidateSet->empty()) 10778 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10779 RParenLoc, /*EmptyLookup=*/true, 10780 AllowTypoCorrection); 10781 10782 switch (OverloadResult) { 10783 case OR_Success: { 10784 FunctionDecl *FDecl = (*Best)->Function; 10785 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10786 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10787 return ExprError(); 10788 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10789 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10790 ExecConfig); 10791 } 10792 10793 case OR_No_Viable_Function: { 10794 // Try to recover by looking for viable functions which the user might 10795 // have meant to call. 10796 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10797 Args, RParenLoc, 10798 /*EmptyLookup=*/false, 10799 AllowTypoCorrection); 10800 if (!Recovery.isInvalid()) 10801 return Recovery; 10802 10803 SemaRef.Diag(Fn->getLocStart(), 10804 diag::err_ovl_no_viable_function_in_call) 10805 << ULE->getName() << Fn->getSourceRange(); 10806 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10807 break; 10808 } 10809 10810 case OR_Ambiguous: 10811 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10812 << ULE->getName() << Fn->getSourceRange(); 10813 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10814 break; 10815 10816 case OR_Deleted: { 10817 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10818 << (*Best)->Function->isDeleted() 10819 << ULE->getName() 10820 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10821 << Fn->getSourceRange(); 10822 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10823 10824 // We emitted an error for the unvailable/deleted function call but keep 10825 // the call in the AST. 10826 FunctionDecl *FDecl = (*Best)->Function; 10827 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10828 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10829 ExecConfig); 10830 } 10831 } 10832 10833 // Overload resolution failed. 10834 return ExprError(); 10835 } 10836 10837 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 10838 /// (which eventually refers to the declaration Func) and the call 10839 /// arguments Args/NumArgs, attempt to resolve the function call down 10840 /// to a specific function. If overload resolution succeeds, returns 10841 /// the call expression produced by overload resolution. 10842 /// Otherwise, emits diagnostics and returns ExprError. 10843 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10844 UnresolvedLookupExpr *ULE, 10845 SourceLocation LParenLoc, 10846 MultiExprArg Args, 10847 SourceLocation RParenLoc, 10848 Expr *ExecConfig, 10849 bool AllowTypoCorrection) { 10850 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 10851 OverloadCandidateSet::CSK_Normal); 10852 ExprResult result; 10853 10854 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10855 &result)) 10856 return result; 10857 10858 OverloadCandidateSet::iterator Best; 10859 OverloadingResult OverloadResult = 10860 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10861 10862 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10863 RParenLoc, ExecConfig, &CandidateSet, 10864 &Best, OverloadResult, 10865 AllowTypoCorrection); 10866 } 10867 10868 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10869 return Functions.size() > 1 || 10870 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10871 } 10872 10873 /// \brief Create a unary operation that may resolve to an overloaded 10874 /// operator. 10875 /// 10876 /// \param OpLoc The location of the operator itself (e.g., '*'). 10877 /// 10878 /// \param OpcIn The UnaryOperator::Opcode that describes this 10879 /// operator. 10880 /// 10881 /// \param Fns The set of non-member functions that will be 10882 /// considered by overload resolution. The caller needs to build this 10883 /// set based on the context using, e.g., 10884 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10885 /// set should not contain any member functions; those will be added 10886 /// by CreateOverloadedUnaryOp(). 10887 /// 10888 /// \param Input The input argument. 10889 ExprResult 10890 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10891 const UnresolvedSetImpl &Fns, 10892 Expr *Input) { 10893 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10894 10895 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10896 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10897 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10898 // TODO: provide better source location info. 10899 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10900 10901 if (checkPlaceholderForOverload(*this, Input)) 10902 return ExprError(); 10903 10904 Expr *Args[2] = { Input, nullptr }; 10905 unsigned NumArgs = 1; 10906 10907 // For post-increment and post-decrement, add the implicit '0' as 10908 // the second argument, so that we know this is a post-increment or 10909 // post-decrement. 10910 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10911 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10912 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10913 SourceLocation()); 10914 NumArgs = 2; 10915 } 10916 10917 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10918 10919 if (Input->isTypeDependent()) { 10920 if (Fns.empty()) 10921 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 10922 VK_RValue, OK_Ordinary, OpLoc); 10923 10924 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 10925 UnresolvedLookupExpr *Fn 10926 = UnresolvedLookupExpr::Create(Context, NamingClass, 10927 NestedNameSpecifierLoc(), OpNameInfo, 10928 /*ADL*/ true, IsOverloaded(Fns), 10929 Fns.begin(), Fns.end()); 10930 return new (Context) 10931 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 10932 VK_RValue, OpLoc, false); 10933 } 10934 10935 // Build an empty overload set. 10936 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 10937 10938 // Add the candidates from the given function set. 10939 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 10940 10941 // Add operator candidates that are member functions. 10942 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10943 10944 // Add candidates from ADL. 10945 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 10946 /*ExplicitTemplateArgs*/nullptr, 10947 CandidateSet); 10948 10949 // Add builtin operator candidates. 10950 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10951 10952 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10953 10954 // Perform overload resolution. 10955 OverloadCandidateSet::iterator Best; 10956 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10957 case OR_Success: { 10958 // We found a built-in operator or an overloaded operator. 10959 FunctionDecl *FnDecl = Best->Function; 10960 10961 if (FnDecl) { 10962 // We matched an overloaded operator. Build a call to that 10963 // operator. 10964 10965 // Convert the arguments. 10966 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10967 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 10968 10969 ExprResult InputRes = 10970 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 10971 Best->FoundDecl, Method); 10972 if (InputRes.isInvalid()) 10973 return ExprError(); 10974 Input = InputRes.get(); 10975 } else { 10976 // Convert the arguments. 10977 ExprResult InputInit 10978 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10979 Context, 10980 FnDecl->getParamDecl(0)), 10981 SourceLocation(), 10982 Input); 10983 if (InputInit.isInvalid()) 10984 return ExprError(); 10985 Input = InputInit.get(); 10986 } 10987 10988 // Build the actual expression node. 10989 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10990 HadMultipleCandidates, OpLoc); 10991 if (FnExpr.isInvalid()) 10992 return ExprError(); 10993 10994 // Determine the result type. 10995 QualType ResultTy = FnDecl->getReturnType(); 10996 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10997 ResultTy = ResultTy.getNonLValueExprType(Context); 10998 10999 Args[0] = Input; 11000 CallExpr *TheCall = 11001 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11002 ResultTy, VK, OpLoc, false); 11003 11004 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11005 return ExprError(); 11006 11007 return MaybeBindToTemporary(TheCall); 11008 } else { 11009 // We matched a built-in operator. Convert the arguments, then 11010 // break out so that we will build the appropriate built-in 11011 // operator node. 11012 ExprResult InputRes = 11013 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11014 Best->Conversions[0], AA_Passing); 11015 if (InputRes.isInvalid()) 11016 return ExprError(); 11017 Input = InputRes.get(); 11018 break; 11019 } 11020 } 11021 11022 case OR_No_Viable_Function: 11023 // This is an erroneous use of an operator which can be overloaded by 11024 // a non-member function. Check for non-member operators which were 11025 // defined too late to be candidates. 11026 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11027 // FIXME: Recover by calling the found function. 11028 return ExprError(); 11029 11030 // No viable function; fall through to handling this as a 11031 // built-in operator, which will produce an error message for us. 11032 break; 11033 11034 case OR_Ambiguous: 11035 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11036 << UnaryOperator::getOpcodeStr(Opc) 11037 << Input->getType() 11038 << Input->getSourceRange(); 11039 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11040 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11041 return ExprError(); 11042 11043 case OR_Deleted: 11044 Diag(OpLoc, diag::err_ovl_deleted_oper) 11045 << Best->Function->isDeleted() 11046 << UnaryOperator::getOpcodeStr(Opc) 11047 << getDeletedOrUnavailableSuffix(Best->Function) 11048 << Input->getSourceRange(); 11049 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11050 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11051 return ExprError(); 11052 } 11053 11054 // Either we found no viable overloaded operator or we matched a 11055 // built-in operator. In either case, fall through to trying to 11056 // build a built-in operation. 11057 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11058 } 11059 11060 /// \brief Create a binary operation that may resolve to an overloaded 11061 /// operator. 11062 /// 11063 /// \param OpLoc The location of the operator itself (e.g., '+'). 11064 /// 11065 /// \param OpcIn The BinaryOperator::Opcode that describes this 11066 /// operator. 11067 /// 11068 /// \param Fns The set of non-member functions that will be 11069 /// considered by overload resolution. The caller needs to build this 11070 /// set based on the context using, e.g., 11071 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11072 /// set should not contain any member functions; those will be added 11073 /// by CreateOverloadedBinOp(). 11074 /// 11075 /// \param LHS Left-hand argument. 11076 /// \param RHS Right-hand argument. 11077 ExprResult 11078 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11079 unsigned OpcIn, 11080 const UnresolvedSetImpl &Fns, 11081 Expr *LHS, Expr *RHS) { 11082 Expr *Args[2] = { LHS, RHS }; 11083 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11084 11085 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 11086 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11087 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11088 11089 // If either side is type-dependent, create an appropriate dependent 11090 // expression. 11091 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11092 if (Fns.empty()) { 11093 // If there are no functions to store, just build a dependent 11094 // BinaryOperator or CompoundAssignment. 11095 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11096 return new (Context) BinaryOperator( 11097 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11098 OpLoc, FPFeatures.fp_contract); 11099 11100 return new (Context) CompoundAssignOperator( 11101 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11102 Context.DependentTy, Context.DependentTy, OpLoc, 11103 FPFeatures.fp_contract); 11104 } 11105 11106 // FIXME: save results of ADL from here? 11107 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11108 // TODO: provide better source location info in DNLoc component. 11109 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11110 UnresolvedLookupExpr *Fn 11111 = UnresolvedLookupExpr::Create(Context, NamingClass, 11112 NestedNameSpecifierLoc(), OpNameInfo, 11113 /*ADL*/ true, IsOverloaded(Fns), 11114 Fns.begin(), Fns.end()); 11115 return new (Context) 11116 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11117 VK_RValue, OpLoc, FPFeatures.fp_contract); 11118 } 11119 11120 // Always do placeholder-like conversions on the RHS. 11121 if (checkPlaceholderForOverload(*this, Args[1])) 11122 return ExprError(); 11123 11124 // Do placeholder-like conversion on the LHS; note that we should 11125 // not get here with a PseudoObject LHS. 11126 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11127 if (checkPlaceholderForOverload(*this, Args[0])) 11128 return ExprError(); 11129 11130 // If this is the assignment operator, we only perform overload resolution 11131 // if the left-hand side is a class or enumeration type. This is actually 11132 // a hack. The standard requires that we do overload resolution between the 11133 // various built-in candidates, but as DR507 points out, this can lead to 11134 // problems. So we do it this way, which pretty much follows what GCC does. 11135 // Note that we go the traditional code path for compound assignment forms. 11136 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11137 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11138 11139 // If this is the .* operator, which is not overloadable, just 11140 // create a built-in binary operator. 11141 if (Opc == BO_PtrMemD) 11142 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11143 11144 // Build an empty overload set. 11145 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11146 11147 // Add the candidates from the given function set. 11148 AddFunctionCandidates(Fns, Args, CandidateSet); 11149 11150 // Add operator candidates that are member functions. 11151 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11152 11153 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11154 // performed for an assignment operator (nor for operator[] nor operator->, 11155 // which don't get here). 11156 if (Opc != BO_Assign) 11157 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11158 /*ExplicitTemplateArgs*/ nullptr, 11159 CandidateSet); 11160 11161 // Add builtin operator candidates. 11162 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11163 11164 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11165 11166 // Perform overload resolution. 11167 OverloadCandidateSet::iterator Best; 11168 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11169 case OR_Success: { 11170 // We found a built-in operator or an overloaded operator. 11171 FunctionDecl *FnDecl = Best->Function; 11172 11173 if (FnDecl) { 11174 // We matched an overloaded operator. Build a call to that 11175 // operator. 11176 11177 // Convert the arguments. 11178 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11179 // Best->Access is only meaningful for class members. 11180 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11181 11182 ExprResult Arg1 = 11183 PerformCopyInitialization( 11184 InitializedEntity::InitializeParameter(Context, 11185 FnDecl->getParamDecl(0)), 11186 SourceLocation(), Args[1]); 11187 if (Arg1.isInvalid()) 11188 return ExprError(); 11189 11190 ExprResult Arg0 = 11191 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11192 Best->FoundDecl, Method); 11193 if (Arg0.isInvalid()) 11194 return ExprError(); 11195 Args[0] = Arg0.getAs<Expr>(); 11196 Args[1] = RHS = Arg1.getAs<Expr>(); 11197 } else { 11198 // Convert the arguments. 11199 ExprResult Arg0 = PerformCopyInitialization( 11200 InitializedEntity::InitializeParameter(Context, 11201 FnDecl->getParamDecl(0)), 11202 SourceLocation(), Args[0]); 11203 if (Arg0.isInvalid()) 11204 return ExprError(); 11205 11206 ExprResult Arg1 = 11207 PerformCopyInitialization( 11208 InitializedEntity::InitializeParameter(Context, 11209 FnDecl->getParamDecl(1)), 11210 SourceLocation(), Args[1]); 11211 if (Arg1.isInvalid()) 11212 return ExprError(); 11213 Args[0] = LHS = Arg0.getAs<Expr>(); 11214 Args[1] = RHS = Arg1.getAs<Expr>(); 11215 } 11216 11217 // Build the actual expression node. 11218 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11219 Best->FoundDecl, 11220 HadMultipleCandidates, OpLoc); 11221 if (FnExpr.isInvalid()) 11222 return ExprError(); 11223 11224 // Determine the result type. 11225 QualType ResultTy = FnDecl->getReturnType(); 11226 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11227 ResultTy = ResultTy.getNonLValueExprType(Context); 11228 11229 CXXOperatorCallExpr *TheCall = 11230 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11231 Args, ResultTy, VK, OpLoc, 11232 FPFeatures.fp_contract); 11233 11234 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11235 FnDecl)) 11236 return ExprError(); 11237 11238 ArrayRef<const Expr *> ArgsArray(Args, 2); 11239 // Cut off the implicit 'this'. 11240 if (isa<CXXMethodDecl>(FnDecl)) 11241 ArgsArray = ArgsArray.slice(1); 11242 11243 // Check for a self move. 11244 if (Op == OO_Equal) 11245 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11246 11247 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11248 TheCall->getSourceRange(), VariadicDoesNotApply); 11249 11250 return MaybeBindToTemporary(TheCall); 11251 } else { 11252 // We matched a built-in operator. Convert the arguments, then 11253 // break out so that we will build the appropriate built-in 11254 // operator node. 11255 ExprResult ArgsRes0 = 11256 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11257 Best->Conversions[0], AA_Passing); 11258 if (ArgsRes0.isInvalid()) 11259 return ExprError(); 11260 Args[0] = ArgsRes0.get(); 11261 11262 ExprResult ArgsRes1 = 11263 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11264 Best->Conversions[1], AA_Passing); 11265 if (ArgsRes1.isInvalid()) 11266 return ExprError(); 11267 Args[1] = ArgsRes1.get(); 11268 break; 11269 } 11270 } 11271 11272 case OR_No_Viable_Function: { 11273 // C++ [over.match.oper]p9: 11274 // If the operator is the operator , [...] and there are no 11275 // viable functions, then the operator is assumed to be the 11276 // built-in operator and interpreted according to clause 5. 11277 if (Opc == BO_Comma) 11278 break; 11279 11280 // For class as left operand for assignment or compound assigment 11281 // operator do not fall through to handling in built-in, but report that 11282 // no overloaded assignment operator found 11283 ExprResult Result = ExprError(); 11284 if (Args[0]->getType()->isRecordType() && 11285 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11286 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11287 << BinaryOperator::getOpcodeStr(Opc) 11288 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11289 if (Args[0]->getType()->isIncompleteType()) { 11290 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11291 << Args[0]->getType() 11292 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11293 } 11294 } else { 11295 // This is an erroneous use of an operator which can be overloaded by 11296 // a non-member function. Check for non-member operators which were 11297 // defined too late to be candidates. 11298 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11299 // FIXME: Recover by calling the found function. 11300 return ExprError(); 11301 11302 // No viable function; try to create a built-in operation, which will 11303 // produce an error. Then, show the non-viable candidates. 11304 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11305 } 11306 assert(Result.isInvalid() && 11307 "C++ binary operator overloading is missing candidates!"); 11308 if (Result.isInvalid()) 11309 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11310 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11311 return Result; 11312 } 11313 11314 case OR_Ambiguous: 11315 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11316 << BinaryOperator::getOpcodeStr(Opc) 11317 << Args[0]->getType() << Args[1]->getType() 11318 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11319 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11320 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11321 return ExprError(); 11322 11323 case OR_Deleted: 11324 if (isImplicitlyDeleted(Best->Function)) { 11325 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11326 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11327 << Context.getRecordType(Method->getParent()) 11328 << getSpecialMember(Method); 11329 11330 // The user probably meant to call this special member. Just 11331 // explain why it's deleted. 11332 NoteDeletedFunction(Method); 11333 return ExprError(); 11334 } else { 11335 Diag(OpLoc, diag::err_ovl_deleted_oper) 11336 << Best->Function->isDeleted() 11337 << BinaryOperator::getOpcodeStr(Opc) 11338 << getDeletedOrUnavailableSuffix(Best->Function) 11339 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11340 } 11341 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11342 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11343 return ExprError(); 11344 } 11345 11346 // We matched a built-in operator; build it. 11347 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11348 } 11349 11350 ExprResult 11351 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11352 SourceLocation RLoc, 11353 Expr *Base, Expr *Idx) { 11354 Expr *Args[2] = { Base, Idx }; 11355 DeclarationName OpName = 11356 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11357 11358 // If either side is type-dependent, create an appropriate dependent 11359 // expression. 11360 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11361 11362 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11363 // CHECKME: no 'operator' keyword? 11364 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11365 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11366 UnresolvedLookupExpr *Fn 11367 = UnresolvedLookupExpr::Create(Context, NamingClass, 11368 NestedNameSpecifierLoc(), OpNameInfo, 11369 /*ADL*/ true, /*Overloaded*/ false, 11370 UnresolvedSetIterator(), 11371 UnresolvedSetIterator()); 11372 // Can't add any actual overloads yet 11373 11374 return new (Context) 11375 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11376 Context.DependentTy, VK_RValue, RLoc, false); 11377 } 11378 11379 // Handle placeholders on both operands. 11380 if (checkPlaceholderForOverload(*this, Args[0])) 11381 return ExprError(); 11382 if (checkPlaceholderForOverload(*this, Args[1])) 11383 return ExprError(); 11384 11385 // Build an empty overload set. 11386 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11387 11388 // Subscript can only be overloaded as a member function. 11389 11390 // Add operator candidates that are member functions. 11391 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11392 11393 // Add builtin operator candidates. 11394 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11395 11396 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11397 11398 // Perform overload resolution. 11399 OverloadCandidateSet::iterator Best; 11400 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11401 case OR_Success: { 11402 // We found a built-in operator or an overloaded operator. 11403 FunctionDecl *FnDecl = Best->Function; 11404 11405 if (FnDecl) { 11406 // We matched an overloaded operator. Build a call to that 11407 // operator. 11408 11409 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11410 11411 // Convert the arguments. 11412 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11413 ExprResult Arg0 = 11414 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11415 Best->FoundDecl, Method); 11416 if (Arg0.isInvalid()) 11417 return ExprError(); 11418 Args[0] = Arg0.get(); 11419 11420 // Convert the arguments. 11421 ExprResult InputInit 11422 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11423 Context, 11424 FnDecl->getParamDecl(0)), 11425 SourceLocation(), 11426 Args[1]); 11427 if (InputInit.isInvalid()) 11428 return ExprError(); 11429 11430 Args[1] = InputInit.getAs<Expr>(); 11431 11432 // Build the actual expression node. 11433 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11434 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11435 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11436 Best->FoundDecl, 11437 HadMultipleCandidates, 11438 OpLocInfo.getLoc(), 11439 OpLocInfo.getInfo()); 11440 if (FnExpr.isInvalid()) 11441 return ExprError(); 11442 11443 // Determine the result type 11444 QualType ResultTy = FnDecl->getReturnType(); 11445 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11446 ResultTy = ResultTy.getNonLValueExprType(Context); 11447 11448 CXXOperatorCallExpr *TheCall = 11449 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11450 FnExpr.get(), Args, 11451 ResultTy, VK, RLoc, 11452 false); 11453 11454 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11455 return ExprError(); 11456 11457 return MaybeBindToTemporary(TheCall); 11458 } else { 11459 // We matched a built-in operator. Convert the arguments, then 11460 // break out so that we will build the appropriate built-in 11461 // operator node. 11462 ExprResult ArgsRes0 = 11463 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11464 Best->Conversions[0], AA_Passing); 11465 if (ArgsRes0.isInvalid()) 11466 return ExprError(); 11467 Args[0] = ArgsRes0.get(); 11468 11469 ExprResult ArgsRes1 = 11470 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11471 Best->Conversions[1], AA_Passing); 11472 if (ArgsRes1.isInvalid()) 11473 return ExprError(); 11474 Args[1] = ArgsRes1.get(); 11475 11476 break; 11477 } 11478 } 11479 11480 case OR_No_Viable_Function: { 11481 if (CandidateSet.empty()) 11482 Diag(LLoc, diag::err_ovl_no_oper) 11483 << Args[0]->getType() << /*subscript*/ 0 11484 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11485 else 11486 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11487 << Args[0]->getType() 11488 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11489 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11490 "[]", LLoc); 11491 return ExprError(); 11492 } 11493 11494 case OR_Ambiguous: 11495 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11496 << "[]" 11497 << Args[0]->getType() << Args[1]->getType() 11498 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11499 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11500 "[]", LLoc); 11501 return ExprError(); 11502 11503 case OR_Deleted: 11504 Diag(LLoc, diag::err_ovl_deleted_oper) 11505 << Best->Function->isDeleted() << "[]" 11506 << getDeletedOrUnavailableSuffix(Best->Function) 11507 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11508 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11509 "[]", LLoc); 11510 return ExprError(); 11511 } 11512 11513 // We matched a built-in operator; build it. 11514 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11515 } 11516 11517 /// BuildCallToMemberFunction - Build a call to a member 11518 /// function. MemExpr is the expression that refers to the member 11519 /// function (and includes the object parameter), Args/NumArgs are the 11520 /// arguments to the function call (not including the object 11521 /// parameter). The caller needs to validate that the member 11522 /// expression refers to a non-static member function or an overloaded 11523 /// member function. 11524 ExprResult 11525 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11526 SourceLocation LParenLoc, 11527 MultiExprArg Args, 11528 SourceLocation RParenLoc) { 11529 assert(MemExprE->getType() == Context.BoundMemberTy || 11530 MemExprE->getType() == Context.OverloadTy); 11531 11532 // Dig out the member expression. This holds both the object 11533 // argument and the member function we're referring to. 11534 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11535 11536 // Determine whether this is a call to a pointer-to-member function. 11537 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11538 assert(op->getType() == Context.BoundMemberTy); 11539 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11540 11541 QualType fnType = 11542 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11543 11544 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11545 QualType resultType = proto->getCallResultType(Context); 11546 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11547 11548 // Check that the object type isn't more qualified than the 11549 // member function we're calling. 11550 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11551 11552 QualType objectType = op->getLHS()->getType(); 11553 if (op->getOpcode() == BO_PtrMemI) 11554 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11555 Qualifiers objectQuals = objectType.getQualifiers(); 11556 11557 Qualifiers difference = objectQuals - funcQuals; 11558 difference.removeObjCGCAttr(); 11559 difference.removeAddressSpace(); 11560 if (difference) { 11561 std::string qualsString = difference.getAsString(); 11562 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11563 << fnType.getUnqualifiedType() 11564 << qualsString 11565 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11566 } 11567 11568 if (resultType->isMemberPointerType()) 11569 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11570 RequireCompleteType(LParenLoc, resultType, 0); 11571 11572 CXXMemberCallExpr *call 11573 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11574 resultType, valueKind, RParenLoc); 11575 11576 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11577 call, nullptr)) 11578 return ExprError(); 11579 11580 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 11581 return ExprError(); 11582 11583 if (CheckOtherCall(call, proto)) 11584 return ExprError(); 11585 11586 return MaybeBindToTemporary(call); 11587 } 11588 11589 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 11590 return new (Context) 11591 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 11592 11593 UnbridgedCastsSet UnbridgedCasts; 11594 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11595 return ExprError(); 11596 11597 MemberExpr *MemExpr; 11598 CXXMethodDecl *Method = nullptr; 11599 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 11600 NestedNameSpecifier *Qualifier = nullptr; 11601 if (isa<MemberExpr>(NakedMemExpr)) { 11602 MemExpr = cast<MemberExpr>(NakedMemExpr); 11603 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11604 FoundDecl = MemExpr->getFoundDecl(); 11605 Qualifier = MemExpr->getQualifier(); 11606 UnbridgedCasts.restore(); 11607 } else { 11608 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11609 Qualifier = UnresExpr->getQualifier(); 11610 11611 QualType ObjectType = UnresExpr->getBaseType(); 11612 Expr::Classification ObjectClassification 11613 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11614 : UnresExpr->getBase()->Classify(Context); 11615 11616 // Add overload candidates 11617 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 11618 OverloadCandidateSet::CSK_Normal); 11619 11620 // FIXME: avoid copy. 11621 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 11622 if (UnresExpr->hasExplicitTemplateArgs()) { 11623 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11624 TemplateArgs = &TemplateArgsBuffer; 11625 } 11626 11627 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11628 E = UnresExpr->decls_end(); I != E; ++I) { 11629 11630 NamedDecl *Func = *I; 11631 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11632 if (isa<UsingShadowDecl>(Func)) 11633 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11634 11635 11636 // Microsoft supports direct constructor calls. 11637 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11638 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11639 Args, CandidateSet); 11640 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11641 // If explicit template arguments were provided, we can't call a 11642 // non-template member function. 11643 if (TemplateArgs) 11644 continue; 11645 11646 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11647 ObjectClassification, Args, CandidateSet, 11648 /*SuppressUserConversions=*/false); 11649 } else { 11650 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11651 I.getPair(), ActingDC, TemplateArgs, 11652 ObjectType, ObjectClassification, 11653 Args, CandidateSet, 11654 /*SuppressUsedConversions=*/false); 11655 } 11656 } 11657 11658 DeclarationName DeclName = UnresExpr->getMemberName(); 11659 11660 UnbridgedCasts.restore(); 11661 11662 OverloadCandidateSet::iterator Best; 11663 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11664 Best)) { 11665 case OR_Success: 11666 Method = cast<CXXMethodDecl>(Best->Function); 11667 FoundDecl = Best->FoundDecl; 11668 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11669 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11670 return ExprError(); 11671 // If FoundDecl is different from Method (such as if one is a template 11672 // and the other a specialization), make sure DiagnoseUseOfDecl is 11673 // called on both. 11674 // FIXME: This would be more comprehensively addressed by modifying 11675 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11676 // being used. 11677 if (Method != FoundDecl.getDecl() && 11678 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11679 return ExprError(); 11680 break; 11681 11682 case OR_No_Viable_Function: 11683 Diag(UnresExpr->getMemberLoc(), 11684 diag::err_ovl_no_viable_member_function_in_call) 11685 << DeclName << MemExprE->getSourceRange(); 11686 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11687 // FIXME: Leaking incoming expressions! 11688 return ExprError(); 11689 11690 case OR_Ambiguous: 11691 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11692 << DeclName << MemExprE->getSourceRange(); 11693 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11694 // FIXME: Leaking incoming expressions! 11695 return ExprError(); 11696 11697 case OR_Deleted: 11698 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11699 << Best->Function->isDeleted() 11700 << DeclName 11701 << getDeletedOrUnavailableSuffix(Best->Function) 11702 << MemExprE->getSourceRange(); 11703 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11704 // FIXME: Leaking incoming expressions! 11705 return ExprError(); 11706 } 11707 11708 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11709 11710 // If overload resolution picked a static member, build a 11711 // non-member call based on that function. 11712 if (Method->isStatic()) { 11713 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11714 RParenLoc); 11715 } 11716 11717 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11718 } 11719 11720 QualType ResultType = Method->getReturnType(); 11721 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11722 ResultType = ResultType.getNonLValueExprType(Context); 11723 11724 assert(Method && "Member call to something that isn't a method?"); 11725 CXXMemberCallExpr *TheCall = 11726 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11727 ResultType, VK, RParenLoc); 11728 11729 // (CUDA B.1): Check for invalid calls between targets. 11730 if (getLangOpts().CUDA) { 11731 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 11732 if (CheckCUDATarget(Caller, Method)) { 11733 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 11734 << IdentifyCUDATarget(Method) << Method->getIdentifier() 11735 << IdentifyCUDATarget(Caller); 11736 return ExprError(); 11737 } 11738 } 11739 } 11740 11741 // Check for a valid return type. 11742 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 11743 TheCall, Method)) 11744 return ExprError(); 11745 11746 // Convert the object argument (for a non-static member function call). 11747 // We only need to do this if there was actually an overload; otherwise 11748 // it was done at lookup. 11749 if (!Method->isStatic()) { 11750 ExprResult ObjectArg = 11751 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11752 FoundDecl, Method); 11753 if (ObjectArg.isInvalid()) 11754 return ExprError(); 11755 MemExpr->setBase(ObjectArg.get()); 11756 } 11757 11758 // Convert the rest of the arguments 11759 const FunctionProtoType *Proto = 11760 Method->getType()->getAs<FunctionProtoType>(); 11761 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11762 RParenLoc)) 11763 return ExprError(); 11764 11765 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11766 11767 if (CheckFunctionCall(Method, TheCall, Proto)) 11768 return ExprError(); 11769 11770 if ((isa<CXXConstructorDecl>(CurContext) || 11771 isa<CXXDestructorDecl>(CurContext)) && 11772 TheCall->getMethodDecl()->isPure()) { 11773 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11774 11775 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 11776 MemExpr->performsVirtualDispatch(getLangOpts())) { 11777 Diag(MemExpr->getLocStart(), 11778 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11779 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11780 << MD->getParent()->getDeclName(); 11781 11782 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11783 if (getLangOpts().AppleKext) 11784 Diag(MemExpr->getLocStart(), 11785 diag::note_pure_qualified_call_kext) 11786 << MD->getParent()->getDeclName() 11787 << MD->getDeclName(); 11788 } 11789 } 11790 return MaybeBindToTemporary(TheCall); 11791 } 11792 11793 /// BuildCallToObjectOfClassType - Build a call to an object of class 11794 /// type (C++ [over.call.object]), which can end up invoking an 11795 /// overloaded function call operator (@c operator()) or performing a 11796 /// user-defined conversion on the object argument. 11797 ExprResult 11798 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11799 SourceLocation LParenLoc, 11800 MultiExprArg Args, 11801 SourceLocation RParenLoc) { 11802 if (checkPlaceholderForOverload(*this, Obj)) 11803 return ExprError(); 11804 ExprResult Object = Obj; 11805 11806 UnbridgedCastsSet UnbridgedCasts; 11807 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11808 return ExprError(); 11809 11810 assert(Object.get()->getType()->isRecordType() && 11811 "Requires object type argument"); 11812 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11813 11814 // C++ [over.call.object]p1: 11815 // If the primary-expression E in the function call syntax 11816 // evaluates to a class object of type "cv T", then the set of 11817 // candidate functions includes at least the function call 11818 // operators of T. The function call operators of T are obtained by 11819 // ordinary lookup of the name operator() in the context of 11820 // (E).operator(). 11821 OverloadCandidateSet CandidateSet(LParenLoc, 11822 OverloadCandidateSet::CSK_Operator); 11823 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11824 11825 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11826 diag::err_incomplete_object_call, Object.get())) 11827 return true; 11828 11829 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11830 LookupQualifiedName(R, Record->getDecl()); 11831 R.suppressDiagnostics(); 11832 11833 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11834 Oper != OperEnd; ++Oper) { 11835 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11836 Object.get()->Classify(Context), 11837 Args, CandidateSet, 11838 /*SuppressUserConversions=*/ false); 11839 } 11840 11841 // C++ [over.call.object]p2: 11842 // In addition, for each (non-explicit in C++0x) conversion function 11843 // declared in T of the form 11844 // 11845 // operator conversion-type-id () cv-qualifier; 11846 // 11847 // where cv-qualifier is the same cv-qualification as, or a 11848 // greater cv-qualification than, cv, and where conversion-type-id 11849 // denotes the type "pointer to function of (P1,...,Pn) returning 11850 // R", or the type "reference to pointer to function of 11851 // (P1,...,Pn) returning R", or the type "reference to function 11852 // of (P1,...,Pn) returning R", a surrogate call function [...] 11853 // is also considered as a candidate function. Similarly, 11854 // surrogate call functions are added to the set of candidate 11855 // functions for each conversion function declared in an 11856 // accessible base class provided the function is not hidden 11857 // within T by another intervening declaration. 11858 const auto &Conversions = 11859 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11860 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 11861 NamedDecl *D = *I; 11862 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11863 if (isa<UsingShadowDecl>(D)) 11864 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11865 11866 // Skip over templated conversion functions; they aren't 11867 // surrogates. 11868 if (isa<FunctionTemplateDecl>(D)) 11869 continue; 11870 11871 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11872 if (!Conv->isExplicit()) { 11873 // Strip the reference type (if any) and then the pointer type (if 11874 // any) to get down to what might be a function type. 11875 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11876 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11877 ConvType = ConvPtrType->getPointeeType(); 11878 11879 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11880 { 11881 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11882 Object.get(), Args, CandidateSet); 11883 } 11884 } 11885 } 11886 11887 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11888 11889 // Perform overload resolution. 11890 OverloadCandidateSet::iterator Best; 11891 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11892 Best)) { 11893 case OR_Success: 11894 // Overload resolution succeeded; we'll build the appropriate call 11895 // below. 11896 break; 11897 11898 case OR_No_Viable_Function: 11899 if (CandidateSet.empty()) 11900 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11901 << Object.get()->getType() << /*call*/ 1 11902 << Object.get()->getSourceRange(); 11903 else 11904 Diag(Object.get()->getLocStart(), 11905 diag::err_ovl_no_viable_object_call) 11906 << Object.get()->getType() << Object.get()->getSourceRange(); 11907 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11908 break; 11909 11910 case OR_Ambiguous: 11911 Diag(Object.get()->getLocStart(), 11912 diag::err_ovl_ambiguous_object_call) 11913 << Object.get()->getType() << Object.get()->getSourceRange(); 11914 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11915 break; 11916 11917 case OR_Deleted: 11918 Diag(Object.get()->getLocStart(), 11919 diag::err_ovl_deleted_object_call) 11920 << Best->Function->isDeleted() 11921 << Object.get()->getType() 11922 << getDeletedOrUnavailableSuffix(Best->Function) 11923 << Object.get()->getSourceRange(); 11924 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11925 break; 11926 } 11927 11928 if (Best == CandidateSet.end()) 11929 return true; 11930 11931 UnbridgedCasts.restore(); 11932 11933 if (Best->Function == nullptr) { 11934 // Since there is no function declaration, this is one of the 11935 // surrogate candidates. Dig out the conversion function. 11936 CXXConversionDecl *Conv 11937 = cast<CXXConversionDecl>( 11938 Best->Conversions[0].UserDefined.ConversionFunction); 11939 11940 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 11941 Best->FoundDecl); 11942 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11943 return ExprError(); 11944 assert(Conv == Best->FoundDecl.getDecl() && 11945 "Found Decl & conversion-to-functionptr should be same, right?!"); 11946 // We selected one of the surrogate functions that converts the 11947 // object parameter to a function pointer. Perform the conversion 11948 // on the object argument, then let ActOnCallExpr finish the job. 11949 11950 // Create an implicit member expr to refer to the conversion operator. 11951 // and then call it. 11952 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11953 Conv, HadMultipleCandidates); 11954 if (Call.isInvalid()) 11955 return ExprError(); 11956 // Record usage of conversion in an implicit cast. 11957 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 11958 CK_UserDefinedConversion, Call.get(), 11959 nullptr, VK_RValue); 11960 11961 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11962 } 11963 11964 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 11965 11966 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11967 // that calls this method, using Object for the implicit object 11968 // parameter and passing along the remaining arguments. 11969 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11970 11971 // An error diagnostic has already been printed when parsing the declaration. 11972 if (Method->isInvalidDecl()) 11973 return ExprError(); 11974 11975 const FunctionProtoType *Proto = 11976 Method->getType()->getAs<FunctionProtoType>(); 11977 11978 unsigned NumParams = Proto->getNumParams(); 11979 11980 DeclarationNameInfo OpLocInfo( 11981 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11982 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11983 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11984 HadMultipleCandidates, 11985 OpLocInfo.getLoc(), 11986 OpLocInfo.getInfo()); 11987 if (NewFn.isInvalid()) 11988 return true; 11989 11990 // Build the full argument list for the method call (the implicit object 11991 // parameter is placed at the beginning of the list). 11992 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 11993 MethodArgs[0] = Object.get(); 11994 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 11995 11996 // Once we've built TheCall, all of the expressions are properly 11997 // owned. 11998 QualType ResultTy = Method->getReturnType(); 11999 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12000 ResultTy = ResultTy.getNonLValueExprType(Context); 12001 12002 CXXOperatorCallExpr *TheCall = new (Context) 12003 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12004 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12005 ResultTy, VK, RParenLoc, false); 12006 MethodArgs.reset(); 12007 12008 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12009 return true; 12010 12011 // We may have default arguments. If so, we need to allocate more 12012 // slots in the call for them. 12013 if (Args.size() < NumParams) 12014 TheCall->setNumArgs(Context, NumParams + 1); 12015 12016 bool IsError = false; 12017 12018 // Initialize the implicit object parameter. 12019 ExprResult ObjRes = 12020 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12021 Best->FoundDecl, Method); 12022 if (ObjRes.isInvalid()) 12023 IsError = true; 12024 else 12025 Object = ObjRes; 12026 TheCall->setArg(0, Object.get()); 12027 12028 // Check the argument types. 12029 for (unsigned i = 0; i != NumParams; i++) { 12030 Expr *Arg; 12031 if (i < Args.size()) { 12032 Arg = Args[i]; 12033 12034 // Pass the argument. 12035 12036 ExprResult InputInit 12037 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12038 Context, 12039 Method->getParamDecl(i)), 12040 SourceLocation(), Arg); 12041 12042 IsError |= InputInit.isInvalid(); 12043 Arg = InputInit.getAs<Expr>(); 12044 } else { 12045 ExprResult DefArg 12046 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12047 if (DefArg.isInvalid()) { 12048 IsError = true; 12049 break; 12050 } 12051 12052 Arg = DefArg.getAs<Expr>(); 12053 } 12054 12055 TheCall->setArg(i + 1, Arg); 12056 } 12057 12058 // If this is a variadic call, handle args passed through "...". 12059 if (Proto->isVariadic()) { 12060 // Promote the arguments (C99 6.5.2.2p7). 12061 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12062 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12063 nullptr); 12064 IsError |= Arg.isInvalid(); 12065 TheCall->setArg(i + 1, Arg.get()); 12066 } 12067 } 12068 12069 if (IsError) return true; 12070 12071 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12072 12073 if (CheckFunctionCall(Method, TheCall, Proto)) 12074 return true; 12075 12076 return MaybeBindToTemporary(TheCall); 12077 } 12078 12079 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12080 /// (if one exists), where @c Base is an expression of class type and 12081 /// @c Member is the name of the member we're trying to find. 12082 ExprResult 12083 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12084 bool *NoArrowOperatorFound) { 12085 assert(Base->getType()->isRecordType() && 12086 "left-hand side must have class type"); 12087 12088 if (checkPlaceholderForOverload(*this, Base)) 12089 return ExprError(); 12090 12091 SourceLocation Loc = Base->getExprLoc(); 12092 12093 // C++ [over.ref]p1: 12094 // 12095 // [...] An expression x->m is interpreted as (x.operator->())->m 12096 // for a class object x of type T if T::operator->() exists and if 12097 // the operator is selected as the best match function by the 12098 // overload resolution mechanism (13.3). 12099 DeclarationName OpName = 12100 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12101 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12102 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12103 12104 if (RequireCompleteType(Loc, Base->getType(), 12105 diag::err_typecheck_incomplete_tag, Base)) 12106 return ExprError(); 12107 12108 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12109 LookupQualifiedName(R, BaseRecord->getDecl()); 12110 R.suppressDiagnostics(); 12111 12112 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12113 Oper != OperEnd; ++Oper) { 12114 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12115 None, CandidateSet, /*SuppressUserConversions=*/false); 12116 } 12117 12118 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12119 12120 // Perform overload resolution. 12121 OverloadCandidateSet::iterator Best; 12122 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12123 case OR_Success: 12124 // Overload resolution succeeded; we'll build the call below. 12125 break; 12126 12127 case OR_No_Viable_Function: 12128 if (CandidateSet.empty()) { 12129 QualType BaseType = Base->getType(); 12130 if (NoArrowOperatorFound) { 12131 // Report this specific error to the caller instead of emitting a 12132 // diagnostic, as requested. 12133 *NoArrowOperatorFound = true; 12134 return ExprError(); 12135 } 12136 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12137 << BaseType << Base->getSourceRange(); 12138 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12139 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12140 << FixItHint::CreateReplacement(OpLoc, "."); 12141 } 12142 } else 12143 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12144 << "operator->" << Base->getSourceRange(); 12145 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12146 return ExprError(); 12147 12148 case OR_Ambiguous: 12149 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12150 << "->" << Base->getType() << Base->getSourceRange(); 12151 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12152 return ExprError(); 12153 12154 case OR_Deleted: 12155 Diag(OpLoc, diag::err_ovl_deleted_oper) 12156 << Best->Function->isDeleted() 12157 << "->" 12158 << getDeletedOrUnavailableSuffix(Best->Function) 12159 << Base->getSourceRange(); 12160 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12161 return ExprError(); 12162 } 12163 12164 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12165 12166 // Convert the object parameter. 12167 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12168 ExprResult BaseResult = 12169 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12170 Best->FoundDecl, Method); 12171 if (BaseResult.isInvalid()) 12172 return ExprError(); 12173 Base = BaseResult.get(); 12174 12175 // Build the operator call. 12176 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12177 HadMultipleCandidates, OpLoc); 12178 if (FnExpr.isInvalid()) 12179 return ExprError(); 12180 12181 QualType ResultTy = Method->getReturnType(); 12182 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12183 ResultTy = ResultTy.getNonLValueExprType(Context); 12184 CXXOperatorCallExpr *TheCall = 12185 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12186 Base, ResultTy, VK, OpLoc, false); 12187 12188 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12189 return ExprError(); 12190 12191 return MaybeBindToTemporary(TheCall); 12192 } 12193 12194 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12195 /// a literal operator described by the provided lookup results. 12196 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12197 DeclarationNameInfo &SuffixInfo, 12198 ArrayRef<Expr*> Args, 12199 SourceLocation LitEndLoc, 12200 TemplateArgumentListInfo *TemplateArgs) { 12201 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12202 12203 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12204 OverloadCandidateSet::CSK_Normal); 12205 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12206 /*SuppressUserConversions=*/true); 12207 12208 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12209 12210 // Perform overload resolution. This will usually be trivial, but might need 12211 // to perform substitutions for a literal operator template. 12212 OverloadCandidateSet::iterator Best; 12213 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12214 case OR_Success: 12215 case OR_Deleted: 12216 break; 12217 12218 case OR_No_Viable_Function: 12219 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12220 << R.getLookupName(); 12221 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12222 return ExprError(); 12223 12224 case OR_Ambiguous: 12225 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12226 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12227 return ExprError(); 12228 } 12229 12230 FunctionDecl *FD = Best->Function; 12231 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12232 HadMultipleCandidates, 12233 SuffixInfo.getLoc(), 12234 SuffixInfo.getInfo()); 12235 if (Fn.isInvalid()) 12236 return true; 12237 12238 // Check the argument types. This should almost always be a no-op, except 12239 // that array-to-pointer decay is applied to string literals. 12240 Expr *ConvArgs[2]; 12241 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12242 ExprResult InputInit = PerformCopyInitialization( 12243 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12244 SourceLocation(), Args[ArgIdx]); 12245 if (InputInit.isInvalid()) 12246 return true; 12247 ConvArgs[ArgIdx] = InputInit.get(); 12248 } 12249 12250 QualType ResultTy = FD->getReturnType(); 12251 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12252 ResultTy = ResultTy.getNonLValueExprType(Context); 12253 12254 UserDefinedLiteral *UDL = 12255 new (Context) UserDefinedLiteral(Context, Fn.get(), 12256 llvm::makeArrayRef(ConvArgs, Args.size()), 12257 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12258 12259 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12260 return ExprError(); 12261 12262 if (CheckFunctionCall(FD, UDL, nullptr)) 12263 return ExprError(); 12264 12265 return MaybeBindToTemporary(UDL); 12266 } 12267 12268 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12269 /// given LookupResult is non-empty, it is assumed to describe a member which 12270 /// will be invoked. Otherwise, the function will be found via argument 12271 /// dependent lookup. 12272 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12273 /// otherwise CallExpr is set to ExprError() and some non-success value 12274 /// is returned. 12275 Sema::ForRangeStatus 12276 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 12277 SourceLocation RangeLoc, VarDecl *Decl, 12278 BeginEndFunction BEF, 12279 const DeclarationNameInfo &NameInfo, 12280 LookupResult &MemberLookup, 12281 OverloadCandidateSet *CandidateSet, 12282 Expr *Range, ExprResult *CallExpr) { 12283 CandidateSet->clear(); 12284 if (!MemberLookup.empty()) { 12285 ExprResult MemberRef = 12286 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12287 /*IsPtr=*/false, CXXScopeSpec(), 12288 /*TemplateKWLoc=*/SourceLocation(), 12289 /*FirstQualifierInScope=*/nullptr, 12290 MemberLookup, 12291 /*TemplateArgs=*/nullptr); 12292 if (MemberRef.isInvalid()) { 12293 *CallExpr = ExprError(); 12294 Diag(Range->getLocStart(), diag::note_in_for_range) 12295 << RangeLoc << BEF << Range->getType(); 12296 return FRS_DiagnosticIssued; 12297 } 12298 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12299 if (CallExpr->isInvalid()) { 12300 *CallExpr = ExprError(); 12301 Diag(Range->getLocStart(), diag::note_in_for_range) 12302 << RangeLoc << BEF << Range->getType(); 12303 return FRS_DiagnosticIssued; 12304 } 12305 } else { 12306 UnresolvedSet<0> FoundNames; 12307 UnresolvedLookupExpr *Fn = 12308 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12309 NestedNameSpecifierLoc(), NameInfo, 12310 /*NeedsADL=*/true, /*Overloaded=*/false, 12311 FoundNames.begin(), FoundNames.end()); 12312 12313 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12314 CandidateSet, CallExpr); 12315 if (CandidateSet->empty() || CandidateSetError) { 12316 *CallExpr = ExprError(); 12317 return FRS_NoViableFunction; 12318 } 12319 OverloadCandidateSet::iterator Best; 12320 OverloadingResult OverloadResult = 12321 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12322 12323 if (OverloadResult == OR_No_Viable_Function) { 12324 *CallExpr = ExprError(); 12325 return FRS_NoViableFunction; 12326 } 12327 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12328 Loc, nullptr, CandidateSet, &Best, 12329 OverloadResult, 12330 /*AllowTypoCorrection=*/false); 12331 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12332 *CallExpr = ExprError(); 12333 Diag(Range->getLocStart(), diag::note_in_for_range) 12334 << RangeLoc << BEF << Range->getType(); 12335 return FRS_DiagnosticIssued; 12336 } 12337 } 12338 return FRS_Success; 12339 } 12340 12341 12342 /// FixOverloadedFunctionReference - E is an expression that refers to 12343 /// a C++ overloaded function (possibly with some parentheses and 12344 /// perhaps a '&' around it). We have resolved the overloaded function 12345 /// to the function declaration Fn, so patch up the expression E to 12346 /// refer (possibly indirectly) to Fn. Returns the new expr. 12347 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12348 FunctionDecl *Fn) { 12349 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12350 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12351 Found, Fn); 12352 if (SubExpr == PE->getSubExpr()) 12353 return PE; 12354 12355 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12356 } 12357 12358 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12359 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12360 Found, Fn); 12361 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12362 SubExpr->getType()) && 12363 "Implicit cast type cannot be determined from overload"); 12364 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12365 if (SubExpr == ICE->getSubExpr()) 12366 return ICE; 12367 12368 return ImplicitCastExpr::Create(Context, ICE->getType(), 12369 ICE->getCastKind(), 12370 SubExpr, nullptr, 12371 ICE->getValueKind()); 12372 } 12373 12374 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12375 assert(UnOp->getOpcode() == UO_AddrOf && 12376 "Can only take the address of an overloaded function"); 12377 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12378 if (Method->isStatic()) { 12379 // Do nothing: static member functions aren't any different 12380 // from non-member functions. 12381 } else { 12382 // Fix the subexpression, which really has to be an 12383 // UnresolvedLookupExpr holding an overloaded member function 12384 // or template. 12385 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12386 Found, Fn); 12387 if (SubExpr == UnOp->getSubExpr()) 12388 return UnOp; 12389 12390 assert(isa<DeclRefExpr>(SubExpr) 12391 && "fixed to something other than a decl ref"); 12392 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12393 && "fixed to a member ref with no nested name qualifier"); 12394 12395 // We have taken the address of a pointer to member 12396 // function. Perform the computation here so that we get the 12397 // appropriate pointer to member type. 12398 QualType ClassType 12399 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12400 QualType MemPtrType 12401 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12402 12403 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12404 VK_RValue, OK_Ordinary, 12405 UnOp->getOperatorLoc()); 12406 } 12407 } 12408 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12409 Found, Fn); 12410 if (SubExpr == UnOp->getSubExpr()) 12411 return UnOp; 12412 12413 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12414 Context.getPointerType(SubExpr->getType()), 12415 VK_RValue, OK_Ordinary, 12416 UnOp->getOperatorLoc()); 12417 } 12418 12419 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12420 // FIXME: avoid copy. 12421 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12422 if (ULE->hasExplicitTemplateArgs()) { 12423 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12424 TemplateArgs = &TemplateArgsBuffer; 12425 } 12426 12427 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12428 ULE->getQualifierLoc(), 12429 ULE->getTemplateKeywordLoc(), 12430 Fn, 12431 /*enclosing*/ false, // FIXME? 12432 ULE->getNameLoc(), 12433 Fn->getType(), 12434 VK_LValue, 12435 Found.getDecl(), 12436 TemplateArgs); 12437 MarkDeclRefReferenced(DRE); 12438 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12439 return DRE; 12440 } 12441 12442 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12443 // FIXME: avoid copy. 12444 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12445 if (MemExpr->hasExplicitTemplateArgs()) { 12446 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12447 TemplateArgs = &TemplateArgsBuffer; 12448 } 12449 12450 Expr *Base; 12451 12452 // If we're filling in a static method where we used to have an 12453 // implicit member access, rewrite to a simple decl ref. 12454 if (MemExpr->isImplicitAccess()) { 12455 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12456 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12457 MemExpr->getQualifierLoc(), 12458 MemExpr->getTemplateKeywordLoc(), 12459 Fn, 12460 /*enclosing*/ false, 12461 MemExpr->getMemberLoc(), 12462 Fn->getType(), 12463 VK_LValue, 12464 Found.getDecl(), 12465 TemplateArgs); 12466 MarkDeclRefReferenced(DRE); 12467 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12468 return DRE; 12469 } else { 12470 SourceLocation Loc = MemExpr->getMemberLoc(); 12471 if (MemExpr->getQualifier()) 12472 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12473 CheckCXXThisCapture(Loc); 12474 Base = new (Context) CXXThisExpr(Loc, 12475 MemExpr->getBaseType(), 12476 /*isImplicit=*/true); 12477 } 12478 } else 12479 Base = MemExpr->getBase(); 12480 12481 ExprValueKind valueKind; 12482 QualType type; 12483 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12484 valueKind = VK_LValue; 12485 type = Fn->getType(); 12486 } else { 12487 valueKind = VK_RValue; 12488 type = Context.BoundMemberTy; 12489 } 12490 12491 MemberExpr *ME = MemberExpr::Create( 12492 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 12493 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 12494 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 12495 OK_Ordinary); 12496 ME->setHadMultipleCandidates(true); 12497 MarkMemberReferenced(ME); 12498 return ME; 12499 } 12500 12501 llvm_unreachable("Invalid reference to overloaded function"); 12502 } 12503 12504 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12505 DeclAccessPair Found, 12506 FunctionDecl *Fn) { 12507 return FixOverloadedFunctionReference(E.get(), Found, Fn); 12508 } 12509