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 // -- from a floating-point type to an integer type, or 290 // 291 // -- from an integer type or unscoped enumeration type to a floating-point 292 // type, except where the source is a constant expression and the actual 293 // value after conversion will fit into the target type and will produce 294 // the original value when converted back to the original type, or 295 case ICK_Floating_Integral: 296 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 297 return NK_Type_Narrowing; 298 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 299 llvm::APSInt IntConstantValue; 300 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 301 if (Initializer && 302 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 303 // Convert the integer to the floating type. 304 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 305 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 306 llvm::APFloat::rmNearestTiesToEven); 307 // And back. 308 llvm::APSInt ConvertedValue = IntConstantValue; 309 bool ignored; 310 Result.convertToInteger(ConvertedValue, 311 llvm::APFloat::rmTowardZero, &ignored); 312 // If the resulting value is different, this was a narrowing conversion. 313 if (IntConstantValue != ConvertedValue) { 314 ConstantValue = APValue(IntConstantValue); 315 ConstantType = Initializer->getType(); 316 return NK_Constant_Narrowing; 317 } 318 } else { 319 // Variables are always narrowings. 320 return NK_Variable_Narrowing; 321 } 322 } 323 return NK_Not_Narrowing; 324 325 // -- from long double to double or float, or from double to float, except 326 // where the source is a constant expression and the actual value after 327 // conversion is within the range of values that can be represented (even 328 // if it cannot be represented exactly), or 329 case ICK_Floating_Conversion: 330 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 331 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 332 // FromType is larger than ToType. 333 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 334 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 335 // Constant! 336 assert(ConstantValue.isFloat()); 337 llvm::APFloat FloatVal = ConstantValue.getFloat(); 338 // Convert the source value into the target type. 339 bool ignored; 340 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 341 Ctx.getFloatTypeSemantics(ToType), 342 llvm::APFloat::rmNearestTiesToEven, &ignored); 343 // If there was no overflow, the source value is within the range of 344 // values that can be represented. 345 if (ConvertStatus & llvm::APFloat::opOverflow) { 346 ConstantType = Initializer->getType(); 347 return NK_Constant_Narrowing; 348 } 349 } else { 350 return NK_Variable_Narrowing; 351 } 352 } 353 return NK_Not_Narrowing; 354 355 // -- from an integer type or unscoped enumeration type to an integer type 356 // that cannot represent all the values of the original type, except where 357 // the source is a constant expression and the actual value after 358 // conversion will fit into the target type and will produce the original 359 // value when converted back to the original type. 360 case ICK_Boolean_Conversion: // Bools are integers too. 361 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 362 // Boolean conversions can be from pointers and pointers to members 363 // [conv.bool], and those aren't considered narrowing conversions. 364 return NK_Not_Narrowing; 365 } // Otherwise, fall through to the integral case. 366 case ICK_Integral_Conversion: { 367 assert(FromType->isIntegralOrUnscopedEnumerationType()); 368 assert(ToType->isIntegralOrUnscopedEnumerationType()); 369 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 370 const unsigned FromWidth = Ctx.getIntWidth(FromType); 371 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 372 const unsigned ToWidth = Ctx.getIntWidth(ToType); 373 374 if (FromWidth > ToWidth || 375 (FromWidth == ToWidth && FromSigned != ToSigned) || 376 (FromSigned && !ToSigned)) { 377 // Not all values of FromType can be represented in ToType. 378 llvm::APSInt InitializerValue; 379 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 380 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 381 // Such conversions on variables are always narrowing. 382 return NK_Variable_Narrowing; 383 } 384 bool Narrowing = false; 385 if (FromWidth < ToWidth) { 386 // Negative -> unsigned is narrowing. Otherwise, more bits is never 387 // narrowing. 388 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 389 Narrowing = true; 390 } else { 391 // Add a bit to the InitializerValue so we don't have to worry about 392 // signed vs. unsigned comparisons. 393 InitializerValue = InitializerValue.extend( 394 InitializerValue.getBitWidth() + 1); 395 // Convert the initializer to and from the target width and signed-ness. 396 llvm::APSInt ConvertedValue = InitializerValue; 397 ConvertedValue = ConvertedValue.trunc(ToWidth); 398 ConvertedValue.setIsSigned(ToSigned); 399 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 400 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 401 // If the result is different, this was a narrowing conversion. 402 if (ConvertedValue != InitializerValue) 403 Narrowing = true; 404 } 405 if (Narrowing) { 406 ConstantType = Initializer->getType(); 407 ConstantValue = APValue(InitializerValue); 408 return NK_Constant_Narrowing; 409 } 410 } 411 return NK_Not_Narrowing; 412 } 413 414 default: 415 // Other kinds of conversions are not narrowings. 416 return NK_Not_Narrowing; 417 } 418 } 419 420 /// dump - Print this standard conversion sequence to standard 421 /// error. Useful for debugging overloading issues. 422 void StandardConversionSequence::dump() const { 423 raw_ostream &OS = llvm::errs(); 424 bool PrintedSomething = false; 425 if (First != ICK_Identity) { 426 OS << GetImplicitConversionName(First); 427 PrintedSomething = true; 428 } 429 430 if (Second != ICK_Identity) { 431 if (PrintedSomething) { 432 OS << " -> "; 433 } 434 OS << GetImplicitConversionName(Second); 435 436 if (CopyConstructor) { 437 OS << " (by copy constructor)"; 438 } else if (DirectBinding) { 439 OS << " (direct reference binding)"; 440 } else if (ReferenceBinding) { 441 OS << " (reference binding)"; 442 } 443 PrintedSomething = true; 444 } 445 446 if (Third != ICK_Identity) { 447 if (PrintedSomething) { 448 OS << " -> "; 449 } 450 OS << GetImplicitConversionName(Third); 451 PrintedSomething = true; 452 } 453 454 if (!PrintedSomething) { 455 OS << "No conversions required"; 456 } 457 } 458 459 /// dump - Print this user-defined conversion sequence to standard 460 /// error. Useful for debugging overloading issues. 461 void UserDefinedConversionSequence::dump() const { 462 raw_ostream &OS = llvm::errs(); 463 if (Before.First || Before.Second || Before.Third) { 464 Before.dump(); 465 OS << " -> "; 466 } 467 if (ConversionFunction) 468 OS << '\'' << *ConversionFunction << '\''; 469 else 470 OS << "aggregate initialization"; 471 if (After.First || After.Second || After.Third) { 472 OS << " -> "; 473 After.dump(); 474 } 475 } 476 477 /// dump - Print this implicit conversion sequence to standard 478 /// error. Useful for debugging overloading issues. 479 void ImplicitConversionSequence::dump() const { 480 raw_ostream &OS = llvm::errs(); 481 if (isStdInitializerListElement()) 482 OS << "Worst std::initializer_list element conversion: "; 483 switch (ConversionKind) { 484 case StandardConversion: 485 OS << "Standard conversion: "; 486 Standard.dump(); 487 break; 488 case UserDefinedConversion: 489 OS << "User-defined conversion: "; 490 UserDefined.dump(); 491 break; 492 case EllipsisConversion: 493 OS << "Ellipsis conversion"; 494 break; 495 case AmbiguousConversion: 496 OS << "Ambiguous conversion"; 497 break; 498 case BadConversion: 499 OS << "Bad conversion"; 500 break; 501 } 502 503 OS << "\n"; 504 } 505 506 void AmbiguousConversionSequence::construct() { 507 new (&conversions()) ConversionSet(); 508 } 509 510 void AmbiguousConversionSequence::destruct() { 511 conversions().~ConversionSet(); 512 } 513 514 void 515 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 516 FromTypePtr = O.FromTypePtr; 517 ToTypePtr = O.ToTypePtr; 518 new (&conversions()) ConversionSet(O.conversions()); 519 } 520 521 namespace { 522 // Structure used by DeductionFailureInfo to store 523 // template argument information. 524 struct DFIArguments { 525 TemplateArgument FirstArg; 526 TemplateArgument SecondArg; 527 }; 528 // Structure used by DeductionFailureInfo to store 529 // template parameter and template argument information. 530 struct DFIParamWithArguments : DFIArguments { 531 TemplateParameter Param; 532 }; 533 } 534 535 /// \brief Convert from Sema's representation of template deduction information 536 /// to the form used in overload-candidate information. 537 DeductionFailureInfo 538 clang::MakeDeductionFailureInfo(ASTContext &Context, 539 Sema::TemplateDeductionResult TDK, 540 TemplateDeductionInfo &Info) { 541 DeductionFailureInfo Result; 542 Result.Result = static_cast<unsigned>(TDK); 543 Result.HasDiagnostic = false; 544 Result.Data = nullptr; 545 switch (TDK) { 546 case Sema::TDK_Success: 547 case Sema::TDK_Invalid: 548 case Sema::TDK_InstantiationDepth: 549 case Sema::TDK_TooManyArguments: 550 case Sema::TDK_TooFewArguments: 551 break; 552 553 case Sema::TDK_Incomplete: 554 case Sema::TDK_InvalidExplicitArguments: 555 Result.Data = Info.Param.getOpaqueValue(); 556 break; 557 558 case Sema::TDK_NonDeducedMismatch: { 559 // FIXME: Should allocate from normal heap so that we can free this later. 560 DFIArguments *Saved = new (Context) DFIArguments; 561 Saved->FirstArg = Info.FirstArg; 562 Saved->SecondArg = Info.SecondArg; 563 Result.Data = Saved; 564 break; 565 } 566 567 case Sema::TDK_Inconsistent: 568 case Sema::TDK_Underqualified: { 569 // FIXME: Should allocate from normal heap so that we can free this later. 570 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 571 Saved->Param = Info.Param; 572 Saved->FirstArg = Info.FirstArg; 573 Saved->SecondArg = Info.SecondArg; 574 Result.Data = Saved; 575 break; 576 } 577 578 case Sema::TDK_SubstitutionFailure: 579 Result.Data = Info.take(); 580 if (Info.hasSFINAEDiagnostic()) { 581 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 582 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 583 Info.takeSFINAEDiagnostic(*Diag); 584 Result.HasDiagnostic = true; 585 } 586 break; 587 588 case Sema::TDK_FailedOverloadResolution: 589 Result.Data = Info.Expression; 590 break; 591 592 case Sema::TDK_MiscellaneousDeductionFailure: 593 break; 594 } 595 596 return Result; 597 } 598 599 void DeductionFailureInfo::Destroy() { 600 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 601 case Sema::TDK_Success: 602 case Sema::TDK_Invalid: 603 case Sema::TDK_InstantiationDepth: 604 case Sema::TDK_Incomplete: 605 case Sema::TDK_TooManyArguments: 606 case Sema::TDK_TooFewArguments: 607 case Sema::TDK_InvalidExplicitArguments: 608 case Sema::TDK_FailedOverloadResolution: 609 break; 610 611 case Sema::TDK_Inconsistent: 612 case Sema::TDK_Underqualified: 613 case Sema::TDK_NonDeducedMismatch: 614 // FIXME: Destroy the data? 615 Data = nullptr; 616 break; 617 618 case Sema::TDK_SubstitutionFailure: 619 // FIXME: Destroy the template argument list? 620 Data = nullptr; 621 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 622 Diag->~PartialDiagnosticAt(); 623 HasDiagnostic = false; 624 } 625 break; 626 627 // Unhandled 628 case Sema::TDK_MiscellaneousDeductionFailure: 629 break; 630 } 631 } 632 633 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 634 if (HasDiagnostic) 635 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 636 return nullptr; 637 } 638 639 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 640 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 641 case Sema::TDK_Success: 642 case Sema::TDK_Invalid: 643 case Sema::TDK_InstantiationDepth: 644 case Sema::TDK_TooManyArguments: 645 case Sema::TDK_TooFewArguments: 646 case Sema::TDK_SubstitutionFailure: 647 case Sema::TDK_NonDeducedMismatch: 648 case Sema::TDK_FailedOverloadResolution: 649 return TemplateParameter(); 650 651 case Sema::TDK_Incomplete: 652 case Sema::TDK_InvalidExplicitArguments: 653 return TemplateParameter::getFromOpaqueValue(Data); 654 655 case Sema::TDK_Inconsistent: 656 case Sema::TDK_Underqualified: 657 return static_cast<DFIParamWithArguments*>(Data)->Param; 658 659 // Unhandled 660 case Sema::TDK_MiscellaneousDeductionFailure: 661 break; 662 } 663 664 return TemplateParameter(); 665 } 666 667 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 668 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 669 case Sema::TDK_Success: 670 case Sema::TDK_Invalid: 671 case Sema::TDK_InstantiationDepth: 672 case Sema::TDK_TooManyArguments: 673 case Sema::TDK_TooFewArguments: 674 case Sema::TDK_Incomplete: 675 case Sema::TDK_InvalidExplicitArguments: 676 case Sema::TDK_Inconsistent: 677 case Sema::TDK_Underqualified: 678 case Sema::TDK_NonDeducedMismatch: 679 case Sema::TDK_FailedOverloadResolution: 680 return nullptr; 681 682 case Sema::TDK_SubstitutionFailure: 683 return static_cast<TemplateArgumentList*>(Data); 684 685 // Unhandled 686 case Sema::TDK_MiscellaneousDeductionFailure: 687 break; 688 } 689 690 return nullptr; 691 } 692 693 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 695 case Sema::TDK_Success: 696 case Sema::TDK_Invalid: 697 case Sema::TDK_InstantiationDepth: 698 case Sema::TDK_Incomplete: 699 case Sema::TDK_TooManyArguments: 700 case Sema::TDK_TooFewArguments: 701 case Sema::TDK_InvalidExplicitArguments: 702 case Sema::TDK_SubstitutionFailure: 703 case Sema::TDK_FailedOverloadResolution: 704 return nullptr; 705 706 case Sema::TDK_Inconsistent: 707 case Sema::TDK_Underqualified: 708 case Sema::TDK_NonDeducedMismatch: 709 return &static_cast<DFIArguments*>(Data)->FirstArg; 710 711 // Unhandled 712 case Sema::TDK_MiscellaneousDeductionFailure: 713 break; 714 } 715 716 return nullptr; 717 } 718 719 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 720 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 721 case Sema::TDK_Success: 722 case Sema::TDK_Invalid: 723 case Sema::TDK_InstantiationDepth: 724 case Sema::TDK_Incomplete: 725 case Sema::TDK_TooManyArguments: 726 case Sema::TDK_TooFewArguments: 727 case Sema::TDK_InvalidExplicitArguments: 728 case Sema::TDK_SubstitutionFailure: 729 case Sema::TDK_FailedOverloadResolution: 730 return nullptr; 731 732 case Sema::TDK_Inconsistent: 733 case Sema::TDK_Underqualified: 734 case Sema::TDK_NonDeducedMismatch: 735 return &static_cast<DFIArguments*>(Data)->SecondArg; 736 737 // Unhandled 738 case Sema::TDK_MiscellaneousDeductionFailure: 739 break; 740 } 741 742 return nullptr; 743 } 744 745 Expr *DeductionFailureInfo::getExpr() { 746 if (static_cast<Sema::TemplateDeductionResult>(Result) == 747 Sema::TDK_FailedOverloadResolution) 748 return static_cast<Expr*>(Data); 749 750 return nullptr; 751 } 752 753 void OverloadCandidateSet::destroyCandidates() { 754 for (iterator i = begin(), e = end(); i != e; ++i) { 755 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 756 i->Conversions[ii].~ImplicitConversionSequence(); 757 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 758 i->DeductionFailure.Destroy(); 759 } 760 } 761 762 void OverloadCandidateSet::clear() { 763 destroyCandidates(); 764 NumInlineSequences = 0; 765 Candidates.clear(); 766 Functions.clear(); 767 } 768 769 namespace { 770 class UnbridgedCastsSet { 771 struct Entry { 772 Expr **Addr; 773 Expr *Saved; 774 }; 775 SmallVector<Entry, 2> Entries; 776 777 public: 778 void save(Sema &S, Expr *&E) { 779 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 780 Entry entry = { &E, E }; 781 Entries.push_back(entry); 782 E = S.stripARCUnbridgedCast(E); 783 } 784 785 void restore() { 786 for (SmallVectorImpl<Entry>::iterator 787 i = Entries.begin(), e = Entries.end(); i != e; ++i) 788 *i->Addr = i->Saved; 789 } 790 }; 791 } 792 793 /// checkPlaceholderForOverload - Do any interesting placeholder-like 794 /// preprocessing on the given expression. 795 /// 796 /// \param unbridgedCasts a collection to which to add unbridged casts; 797 /// without this, they will be immediately diagnosed as errors 798 /// 799 /// Return true on unrecoverable error. 800 static bool 801 checkPlaceholderForOverload(Sema &S, Expr *&E, 802 UnbridgedCastsSet *unbridgedCasts = nullptr) { 803 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 804 // We can't handle overloaded expressions here because overload 805 // resolution might reasonably tweak them. 806 if (placeholder->getKind() == BuiltinType::Overload) return false; 807 808 // If the context potentially accepts unbridged ARC casts, strip 809 // the unbridged cast and add it to the collection for later restoration. 810 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 811 unbridgedCasts) { 812 unbridgedCasts->save(S, E); 813 return false; 814 } 815 816 // Go ahead and check everything else. 817 ExprResult result = S.CheckPlaceholderExpr(E); 818 if (result.isInvalid()) 819 return true; 820 821 E = result.get(); 822 return false; 823 } 824 825 // Nothing to do. 826 return false; 827 } 828 829 /// checkArgPlaceholdersForOverload - Check a set of call operands for 830 /// placeholders. 831 static bool checkArgPlaceholdersForOverload(Sema &S, 832 MultiExprArg Args, 833 UnbridgedCastsSet &unbridged) { 834 for (unsigned i = 0, e = Args.size(); i != e; ++i) 835 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 836 return true; 837 838 return false; 839 } 840 841 // IsOverload - Determine whether the given New declaration is an 842 // overload of the declarations in Old. This routine returns false if 843 // New and Old cannot be overloaded, e.g., if New has the same 844 // signature as some function in Old (C++ 1.3.10) or if the Old 845 // declarations aren't functions (or function templates) at all. When 846 // it does return false, MatchedDecl will point to the decl that New 847 // cannot be overloaded with. This decl may be a UsingShadowDecl on 848 // top of the underlying declaration. 849 // 850 // Example: Given the following input: 851 // 852 // void f(int, float); // #1 853 // void f(int, int); // #2 854 // int f(int, int); // #3 855 // 856 // When we process #1, there is no previous declaration of "f", 857 // so IsOverload will not be used. 858 // 859 // When we process #2, Old contains only the FunctionDecl for #1. By 860 // comparing the parameter types, we see that #1 and #2 are overloaded 861 // (since they have different signatures), so this routine returns 862 // false; MatchedDecl is unchanged. 863 // 864 // When we process #3, Old is an overload set containing #1 and #2. We 865 // compare the signatures of #3 to #1 (they're overloaded, so we do 866 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 867 // identical (return types of functions are not part of the 868 // signature), IsOverload returns false and MatchedDecl will be set to 869 // point to the FunctionDecl for #2. 870 // 871 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 872 // into a class by a using declaration. The rules for whether to hide 873 // shadow declarations ignore some properties which otherwise figure 874 // into a function template's signature. 875 Sema::OverloadKind 876 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 877 NamedDecl *&Match, bool NewIsUsingDecl) { 878 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 879 I != E; ++I) { 880 NamedDecl *OldD = *I; 881 882 bool OldIsUsingDecl = false; 883 if (isa<UsingShadowDecl>(OldD)) { 884 OldIsUsingDecl = true; 885 886 // We can always introduce two using declarations into the same 887 // context, even if they have identical signatures. 888 if (NewIsUsingDecl) continue; 889 890 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 891 } 892 893 // If either declaration was introduced by a using declaration, 894 // we'll need to use slightly different rules for matching. 895 // Essentially, these rules are the normal rules, except that 896 // function templates hide function templates with different 897 // return types or template parameter lists. 898 bool UseMemberUsingDeclRules = 899 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 900 !New->getFriendObjectKind(); 901 902 if (FunctionDecl *OldF = OldD->getAsFunction()) { 903 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 904 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 905 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 906 continue; 907 } 908 909 if (!isa<FunctionTemplateDecl>(OldD) && 910 !shouldLinkPossiblyHiddenDecl(*I, New)) 911 continue; 912 913 Match = *I; 914 return Ovl_Match; 915 } 916 } else if (isa<UsingDecl>(OldD)) { 917 // We can overload with these, which can show up when doing 918 // redeclaration checks for UsingDecls. 919 assert(Old.getLookupKind() == LookupUsingDeclName); 920 } else if (isa<TagDecl>(OldD)) { 921 // We can always overload with tags by hiding them. 922 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 923 // Optimistically assume that an unresolved using decl will 924 // overload; if it doesn't, we'll have to diagnose during 925 // template instantiation. 926 } else { 927 // (C++ 13p1): 928 // Only function declarations can be overloaded; object and type 929 // declarations cannot be overloaded. 930 Match = *I; 931 return Ovl_NonFunction; 932 } 933 } 934 935 return Ovl_Overload; 936 } 937 938 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 939 bool UseUsingDeclRules) { 940 // C++ [basic.start.main]p2: This function shall not be overloaded. 941 if (New->isMain()) 942 return false; 943 944 // MSVCRT user defined entry points cannot be overloaded. 945 if (New->isMSVCRTEntryPoint()) 946 return false; 947 948 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 949 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 950 951 // C++ [temp.fct]p2: 952 // A function template can be overloaded with other function templates 953 // and with normal (non-template) functions. 954 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 955 return true; 956 957 // Is the function New an overload of the function Old? 958 QualType OldQType = Context.getCanonicalType(Old->getType()); 959 QualType NewQType = Context.getCanonicalType(New->getType()); 960 961 // Compare the signatures (C++ 1.3.10) of the two functions to 962 // determine whether they are overloads. If we find any mismatch 963 // in the signature, they are overloads. 964 965 // If either of these functions is a K&R-style function (no 966 // prototype), then we consider them to have matching signatures. 967 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 968 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 969 return false; 970 971 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 972 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 973 974 // The signature of a function includes the types of its 975 // parameters (C++ 1.3.10), which includes the presence or absence 976 // of the ellipsis; see C++ DR 357). 977 if (OldQType != NewQType && 978 (OldType->getNumParams() != NewType->getNumParams() || 979 OldType->isVariadic() != NewType->isVariadic() || 980 !FunctionParamTypesAreEqual(OldType, NewType))) 981 return true; 982 983 // C++ [temp.over.link]p4: 984 // The signature of a function template consists of its function 985 // signature, its return type and its template parameter list. The names 986 // of the template parameters are significant only for establishing the 987 // relationship between the template parameters and the rest of the 988 // signature. 989 // 990 // We check the return type and template parameter lists for function 991 // templates first; the remaining checks follow. 992 // 993 // However, we don't consider either of these when deciding whether 994 // a member introduced by a shadow declaration is hidden. 995 if (!UseUsingDeclRules && NewTemplate && 996 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 997 OldTemplate->getTemplateParameters(), 998 false, TPL_TemplateMatch) || 999 OldType->getReturnType() != NewType->getReturnType())) 1000 return true; 1001 1002 // If the function is a class member, its signature includes the 1003 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1004 // 1005 // As part of this, also check whether one of the member functions 1006 // is static, in which case they are not overloads (C++ 1007 // 13.1p2). While not part of the definition of the signature, 1008 // this check is important to determine whether these functions 1009 // can be overloaded. 1010 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1011 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1012 if (OldMethod && NewMethod && 1013 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1014 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1015 if (!UseUsingDeclRules && 1016 (OldMethod->getRefQualifier() == RQ_None || 1017 NewMethod->getRefQualifier() == RQ_None)) { 1018 // C++0x [over.load]p2: 1019 // - Member function declarations with the same name and the same 1020 // parameter-type-list as well as member function template 1021 // declarations with the same name, the same parameter-type-list, and 1022 // the same template parameter lists cannot be overloaded if any of 1023 // them, but not all, have a ref-qualifier (8.3.5). 1024 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1025 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1026 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1027 } 1028 return true; 1029 } 1030 1031 // We may not have applied the implicit const for a constexpr member 1032 // function yet (because we haven't yet resolved whether this is a static 1033 // or non-static member function). Add it now, on the assumption that this 1034 // is a redeclaration of OldMethod. 1035 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1036 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1037 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1038 !isa<CXXConstructorDecl>(NewMethod)) 1039 NewQuals |= Qualifiers::Const; 1040 1041 // We do not allow overloading based off of '__restrict'. 1042 OldQuals &= ~Qualifiers::Restrict; 1043 NewQuals &= ~Qualifiers::Restrict; 1044 if (OldQuals != NewQuals) 1045 return true; 1046 } 1047 1048 // enable_if attributes are an order-sensitive part of the signature. 1049 for (specific_attr_iterator<EnableIfAttr> 1050 NewI = New->specific_attr_begin<EnableIfAttr>(), 1051 NewE = New->specific_attr_end<EnableIfAttr>(), 1052 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1053 OldE = Old->specific_attr_end<EnableIfAttr>(); 1054 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1055 if (NewI == NewE || OldI == OldE) 1056 return true; 1057 llvm::FoldingSetNodeID NewID, OldID; 1058 NewI->getCond()->Profile(NewID, Context, true); 1059 OldI->getCond()->Profile(OldID, Context, true); 1060 if (NewID != OldID) 1061 return true; 1062 } 1063 1064 // The signatures match; this is not an overload. 1065 return false; 1066 } 1067 1068 /// \brief Checks availability of the function depending on the current 1069 /// function context. Inside an unavailable function, unavailability is ignored. 1070 /// 1071 /// \returns true if \arg FD is unavailable and current context is inside 1072 /// an available function, false otherwise. 1073 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1074 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1075 } 1076 1077 /// \brief Tries a user-defined conversion from From to ToType. 1078 /// 1079 /// Produces an implicit conversion sequence for when a standard conversion 1080 /// is not an option. See TryImplicitConversion for more information. 1081 static ImplicitConversionSequence 1082 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1083 bool SuppressUserConversions, 1084 bool AllowExplicit, 1085 bool InOverloadResolution, 1086 bool CStyle, 1087 bool AllowObjCWritebackConversion, 1088 bool AllowObjCConversionOnExplicit) { 1089 ImplicitConversionSequence ICS; 1090 1091 if (SuppressUserConversions) { 1092 // We're not in the case above, so there is no conversion that 1093 // we can perform. 1094 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1095 return ICS; 1096 } 1097 1098 // Attempt user-defined conversion. 1099 OverloadCandidateSet Conversions(From->getExprLoc(), 1100 OverloadCandidateSet::CSK_Normal); 1101 OverloadingResult UserDefResult 1102 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1103 AllowExplicit, AllowObjCConversionOnExplicit); 1104 1105 if (UserDefResult == OR_Success) { 1106 ICS.setUserDefined(); 1107 ICS.UserDefined.Before.setAsIdentityConversion(); 1108 // C++ [over.ics.user]p4: 1109 // A conversion of an expression of class type to the same class 1110 // type is given Exact Match rank, and a conversion of an 1111 // expression of class type to a base class of that type is 1112 // given Conversion rank, in spite of the fact that a copy 1113 // constructor (i.e., a user-defined conversion function) is 1114 // called for those cases. 1115 if (CXXConstructorDecl *Constructor 1116 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1117 QualType FromCanon 1118 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1119 QualType ToCanon 1120 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1121 if (Constructor->isCopyConstructor() && 1122 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1123 // Turn this into a "standard" conversion sequence, so that it 1124 // gets ranked with standard conversion sequences. 1125 ICS.setStandard(); 1126 ICS.Standard.setAsIdentityConversion(); 1127 ICS.Standard.setFromType(From->getType()); 1128 ICS.Standard.setAllToTypes(ToType); 1129 ICS.Standard.CopyConstructor = Constructor; 1130 if (ToCanon != FromCanon) 1131 ICS.Standard.Second = ICK_Derived_To_Base; 1132 } 1133 } 1134 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1135 ICS.setAmbiguous(); 1136 ICS.Ambiguous.setFromType(From->getType()); 1137 ICS.Ambiguous.setToType(ToType); 1138 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1139 Cand != Conversions.end(); ++Cand) 1140 if (Cand->Viable) 1141 ICS.Ambiguous.addConversion(Cand->Function); 1142 } else { 1143 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1144 } 1145 1146 return ICS; 1147 } 1148 1149 /// TryImplicitConversion - Attempt to perform an implicit conversion 1150 /// from the given expression (Expr) to the given type (ToType). This 1151 /// function returns an implicit conversion sequence that can be used 1152 /// to perform the initialization. Given 1153 /// 1154 /// void f(float f); 1155 /// void g(int i) { f(i); } 1156 /// 1157 /// this routine would produce an implicit conversion sequence to 1158 /// describe the initialization of f from i, which will be a standard 1159 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1160 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1161 // 1162 /// Note that this routine only determines how the conversion can be 1163 /// performed; it does not actually perform the conversion. As such, 1164 /// it will not produce any diagnostics if no conversion is available, 1165 /// but will instead return an implicit conversion sequence of kind 1166 /// "BadConversion". 1167 /// 1168 /// If @p SuppressUserConversions, then user-defined conversions are 1169 /// not permitted. 1170 /// If @p AllowExplicit, then explicit user-defined conversions are 1171 /// permitted. 1172 /// 1173 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1174 /// writeback conversion, which allows __autoreleasing id* parameters to 1175 /// be initialized with __strong id* or __weak id* arguments. 1176 static ImplicitConversionSequence 1177 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1178 bool SuppressUserConversions, 1179 bool AllowExplicit, 1180 bool InOverloadResolution, 1181 bool CStyle, 1182 bool AllowObjCWritebackConversion, 1183 bool AllowObjCConversionOnExplicit) { 1184 ImplicitConversionSequence ICS; 1185 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1186 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1187 ICS.setStandard(); 1188 return ICS; 1189 } 1190 1191 if (!S.getLangOpts().CPlusPlus) { 1192 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1193 return ICS; 1194 } 1195 1196 // C++ [over.ics.user]p4: 1197 // A conversion of an expression of class type to the same class 1198 // type is given Exact Match rank, and a conversion of an 1199 // expression of class type to a base class of that type is 1200 // given Conversion rank, in spite of the fact that a copy/move 1201 // constructor (i.e., a user-defined conversion function) is 1202 // called for those cases. 1203 QualType FromType = From->getType(); 1204 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1205 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1206 S.IsDerivedFrom(FromType, ToType))) { 1207 ICS.setStandard(); 1208 ICS.Standard.setAsIdentityConversion(); 1209 ICS.Standard.setFromType(FromType); 1210 ICS.Standard.setAllToTypes(ToType); 1211 1212 // We don't actually check at this point whether there is a valid 1213 // copy/move constructor, since overloading just assumes that it 1214 // exists. When we actually perform initialization, we'll find the 1215 // appropriate constructor to copy the returned object, if needed. 1216 ICS.Standard.CopyConstructor = nullptr; 1217 1218 // Determine whether this is considered a derived-to-base conversion. 1219 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1220 ICS.Standard.Second = ICK_Derived_To_Base; 1221 1222 return ICS; 1223 } 1224 1225 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1226 AllowExplicit, InOverloadResolution, CStyle, 1227 AllowObjCWritebackConversion, 1228 AllowObjCConversionOnExplicit); 1229 } 1230 1231 ImplicitConversionSequence 1232 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1233 bool SuppressUserConversions, 1234 bool AllowExplicit, 1235 bool InOverloadResolution, 1236 bool CStyle, 1237 bool AllowObjCWritebackConversion) { 1238 return ::TryImplicitConversion(*this, From, ToType, 1239 SuppressUserConversions, AllowExplicit, 1240 InOverloadResolution, CStyle, 1241 AllowObjCWritebackConversion, 1242 /*AllowObjCConversionOnExplicit=*/false); 1243 } 1244 1245 /// PerformImplicitConversion - Perform an implicit conversion of the 1246 /// expression From to the type ToType. Returns the 1247 /// converted expression. Flavor is the kind of conversion we're 1248 /// performing, used in the error message. If @p AllowExplicit, 1249 /// explicit user-defined conversions are permitted. 1250 ExprResult 1251 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1252 AssignmentAction Action, bool AllowExplicit) { 1253 ImplicitConversionSequence ICS; 1254 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1255 } 1256 1257 ExprResult 1258 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1259 AssignmentAction Action, bool AllowExplicit, 1260 ImplicitConversionSequence& ICS) { 1261 if (checkPlaceholderForOverload(*this, From)) 1262 return ExprError(); 1263 1264 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1265 bool AllowObjCWritebackConversion 1266 = getLangOpts().ObjCAutoRefCount && 1267 (Action == AA_Passing || Action == AA_Sending); 1268 if (getLangOpts().ObjC1) 1269 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1270 ToType, From->getType(), From); 1271 ICS = ::TryImplicitConversion(*this, From, ToType, 1272 /*SuppressUserConversions=*/false, 1273 AllowExplicit, 1274 /*InOverloadResolution=*/false, 1275 /*CStyle=*/false, 1276 AllowObjCWritebackConversion, 1277 /*AllowObjCConversionOnExplicit=*/false); 1278 return PerformImplicitConversion(From, ToType, ICS, Action); 1279 } 1280 1281 /// \brief Determine whether the conversion from FromType to ToType is a valid 1282 /// conversion that strips "noreturn" off the nested function type. 1283 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1284 QualType &ResultTy) { 1285 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1286 return false; 1287 1288 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1289 // where F adds one of the following at most once: 1290 // - a pointer 1291 // - a member pointer 1292 // - a block pointer 1293 CanQualType CanTo = Context.getCanonicalType(ToType); 1294 CanQualType CanFrom = Context.getCanonicalType(FromType); 1295 Type::TypeClass TyClass = CanTo->getTypeClass(); 1296 if (TyClass != CanFrom->getTypeClass()) return false; 1297 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1298 if (TyClass == Type::Pointer) { 1299 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1300 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1301 } else if (TyClass == Type::BlockPointer) { 1302 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1303 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1304 } else if (TyClass == Type::MemberPointer) { 1305 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1306 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1307 } else { 1308 return false; 1309 } 1310 1311 TyClass = CanTo->getTypeClass(); 1312 if (TyClass != CanFrom->getTypeClass()) return false; 1313 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1314 return false; 1315 } 1316 1317 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1318 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1319 if (!EInfo.getNoReturn()) return false; 1320 1321 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1322 assert(QualType(FromFn, 0).isCanonical()); 1323 if (QualType(FromFn, 0) != CanTo) return false; 1324 1325 ResultTy = ToType; 1326 return true; 1327 } 1328 1329 /// \brief Determine whether the conversion from FromType to ToType is a valid 1330 /// vector conversion. 1331 /// 1332 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1333 /// conversion. 1334 static bool IsVectorConversion(Sema &S, QualType FromType, 1335 QualType ToType, ImplicitConversionKind &ICK) { 1336 // We need at least one of these types to be a vector type to have a vector 1337 // conversion. 1338 if (!ToType->isVectorType() && !FromType->isVectorType()) 1339 return false; 1340 1341 // Identical types require no conversions. 1342 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1343 return false; 1344 1345 // There are no conversions between extended vector types, only identity. 1346 if (ToType->isExtVectorType()) { 1347 // There are no conversions between extended vector types other than the 1348 // identity conversion. 1349 if (FromType->isExtVectorType()) 1350 return false; 1351 1352 // Vector splat from any arithmetic type to a vector. 1353 if (FromType->isArithmeticType()) { 1354 ICK = ICK_Vector_Splat; 1355 return true; 1356 } 1357 } 1358 1359 // We can perform the conversion between vector types in the following cases: 1360 // 1)vector types are equivalent AltiVec and GCC vector types 1361 // 2)lax vector conversions are permitted and the vector types are of the 1362 // same size 1363 if (ToType->isVectorType() && FromType->isVectorType()) { 1364 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1365 S.isLaxVectorConversion(FromType, ToType)) { 1366 ICK = ICK_Vector_Conversion; 1367 return true; 1368 } 1369 } 1370 1371 return false; 1372 } 1373 1374 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1375 bool InOverloadResolution, 1376 StandardConversionSequence &SCS, 1377 bool CStyle); 1378 1379 /// IsStandardConversion - Determines whether there is a standard 1380 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1381 /// expression From to the type ToType. Standard conversion sequences 1382 /// only consider non-class types; for conversions that involve class 1383 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1384 /// contain the standard conversion sequence required to perform this 1385 /// conversion and this routine will return true. Otherwise, this 1386 /// routine will return false and the value of SCS is unspecified. 1387 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1388 bool InOverloadResolution, 1389 StandardConversionSequence &SCS, 1390 bool CStyle, 1391 bool AllowObjCWritebackConversion) { 1392 QualType FromType = From->getType(); 1393 1394 // Standard conversions (C++ [conv]) 1395 SCS.setAsIdentityConversion(); 1396 SCS.IncompatibleObjC = false; 1397 SCS.setFromType(FromType); 1398 SCS.CopyConstructor = nullptr; 1399 1400 // There are no standard conversions for class types in C++, so 1401 // abort early. When overloading in C, however, we do permit 1402 if (FromType->isRecordType() || ToType->isRecordType()) { 1403 if (S.getLangOpts().CPlusPlus) 1404 return false; 1405 1406 // When we're overloading in C, we allow, as standard conversions, 1407 } 1408 1409 // The first conversion can be an lvalue-to-rvalue conversion, 1410 // array-to-pointer conversion, or function-to-pointer conversion 1411 // (C++ 4p1). 1412 1413 if (FromType == S.Context.OverloadTy) { 1414 DeclAccessPair AccessPair; 1415 if (FunctionDecl *Fn 1416 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1417 AccessPair)) { 1418 // We were able to resolve the address of the overloaded function, 1419 // so we can convert to the type of that function. 1420 FromType = Fn->getType(); 1421 SCS.setFromType(FromType); 1422 1423 // we can sometimes resolve &foo<int> regardless of ToType, so check 1424 // if the type matches (identity) or we are converting to bool 1425 if (!S.Context.hasSameUnqualifiedType( 1426 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1427 QualType resultTy; 1428 // if the function type matches except for [[noreturn]], it's ok 1429 if (!S.IsNoReturnConversion(FromType, 1430 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1431 // otherwise, only a boolean conversion is standard 1432 if (!ToType->isBooleanType()) 1433 return false; 1434 } 1435 1436 // Check if the "from" expression is taking the address of an overloaded 1437 // function and recompute the FromType accordingly. Take advantage of the 1438 // fact that non-static member functions *must* have such an address-of 1439 // expression. 1440 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1441 if (Method && !Method->isStatic()) { 1442 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1443 "Non-unary operator on non-static member address"); 1444 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1445 == UO_AddrOf && 1446 "Non-address-of operator on non-static member address"); 1447 const Type *ClassType 1448 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1449 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1450 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1451 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1452 UO_AddrOf && 1453 "Non-address-of operator for overloaded function expression"); 1454 FromType = S.Context.getPointerType(FromType); 1455 } 1456 1457 // Check that we've computed the proper type after overload resolution. 1458 assert(S.Context.hasSameType( 1459 FromType, 1460 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1461 } else { 1462 return false; 1463 } 1464 } 1465 // Lvalue-to-rvalue conversion (C++11 4.1): 1466 // A glvalue (3.10) of a non-function, non-array type T can 1467 // be converted to a prvalue. 1468 bool argIsLValue = From->isGLValue(); 1469 if (argIsLValue && 1470 !FromType->isFunctionType() && !FromType->isArrayType() && 1471 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1472 SCS.First = ICK_Lvalue_To_Rvalue; 1473 1474 // C11 6.3.2.1p2: 1475 // ... if the lvalue has atomic type, the value has the non-atomic version 1476 // of the type of the lvalue ... 1477 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1478 FromType = Atomic->getValueType(); 1479 1480 // If T is a non-class type, the type of the rvalue is the 1481 // cv-unqualified version of T. Otherwise, the type of the rvalue 1482 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1483 // just strip the qualifiers because they don't matter. 1484 FromType = FromType.getUnqualifiedType(); 1485 } else if (FromType->isArrayType()) { 1486 // Array-to-pointer conversion (C++ 4.2) 1487 SCS.First = ICK_Array_To_Pointer; 1488 1489 // An lvalue or rvalue of type "array of N T" or "array of unknown 1490 // bound of T" can be converted to an rvalue of type "pointer to 1491 // T" (C++ 4.2p1). 1492 FromType = S.Context.getArrayDecayedType(FromType); 1493 1494 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1495 // This conversion is deprecated in C++03 (D.4) 1496 SCS.DeprecatedStringLiteralToCharPtr = true; 1497 1498 // For the purpose of ranking in overload resolution 1499 // (13.3.3.1.1), this conversion is considered an 1500 // array-to-pointer conversion followed by a qualification 1501 // conversion (4.4). (C++ 4.2p2) 1502 SCS.Second = ICK_Identity; 1503 SCS.Third = ICK_Qualification; 1504 SCS.QualificationIncludesObjCLifetime = false; 1505 SCS.setAllToTypes(FromType); 1506 return true; 1507 } 1508 } else if (FromType->isFunctionType() && argIsLValue) { 1509 // Function-to-pointer conversion (C++ 4.3). 1510 SCS.First = ICK_Function_To_Pointer; 1511 1512 // An lvalue of function type T can be converted to an rvalue of 1513 // type "pointer to T." The result is a pointer to the 1514 // function. (C++ 4.3p1). 1515 FromType = S.Context.getPointerType(FromType); 1516 } else { 1517 // We don't require any conversions for the first step. 1518 SCS.First = ICK_Identity; 1519 } 1520 SCS.setToType(0, FromType); 1521 1522 // The second conversion can be an integral promotion, floating 1523 // point promotion, integral conversion, floating point conversion, 1524 // floating-integral conversion, pointer conversion, 1525 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1526 // For overloading in C, this can also be a "compatible-type" 1527 // conversion. 1528 bool IncompatibleObjC = false; 1529 ImplicitConversionKind SecondICK = ICK_Identity; 1530 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1531 // The unqualified versions of the types are the same: there's no 1532 // conversion to do. 1533 SCS.Second = ICK_Identity; 1534 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1535 // Integral promotion (C++ 4.5). 1536 SCS.Second = ICK_Integral_Promotion; 1537 FromType = ToType.getUnqualifiedType(); 1538 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1539 // Floating point promotion (C++ 4.6). 1540 SCS.Second = ICK_Floating_Promotion; 1541 FromType = ToType.getUnqualifiedType(); 1542 } else if (S.IsComplexPromotion(FromType, ToType)) { 1543 // Complex promotion (Clang extension) 1544 SCS.Second = ICK_Complex_Promotion; 1545 FromType = ToType.getUnqualifiedType(); 1546 } else if (ToType->isBooleanType() && 1547 (FromType->isArithmeticType() || 1548 FromType->isAnyPointerType() || 1549 FromType->isBlockPointerType() || 1550 FromType->isMemberPointerType() || 1551 FromType->isNullPtrType())) { 1552 // Boolean conversions (C++ 4.12). 1553 SCS.Second = ICK_Boolean_Conversion; 1554 FromType = S.Context.BoolTy; 1555 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1556 ToType->isIntegralType(S.Context)) { 1557 // Integral conversions (C++ 4.7). 1558 SCS.Second = ICK_Integral_Conversion; 1559 FromType = ToType.getUnqualifiedType(); 1560 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1561 // Complex conversions (C99 6.3.1.6) 1562 SCS.Second = ICK_Complex_Conversion; 1563 FromType = ToType.getUnqualifiedType(); 1564 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1565 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1566 // Complex-real conversions (C99 6.3.1.7) 1567 SCS.Second = ICK_Complex_Real; 1568 FromType = ToType.getUnqualifiedType(); 1569 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1570 // Floating point conversions (C++ 4.8). 1571 SCS.Second = ICK_Floating_Conversion; 1572 FromType = ToType.getUnqualifiedType(); 1573 } else if ((FromType->isRealFloatingType() && 1574 ToType->isIntegralType(S.Context)) || 1575 (FromType->isIntegralOrUnscopedEnumerationType() && 1576 ToType->isRealFloatingType())) { 1577 // Floating-integral conversions (C++ 4.9). 1578 SCS.Second = ICK_Floating_Integral; 1579 FromType = ToType.getUnqualifiedType(); 1580 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1581 SCS.Second = ICK_Block_Pointer_Conversion; 1582 } else if (AllowObjCWritebackConversion && 1583 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1584 SCS.Second = ICK_Writeback_Conversion; 1585 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1586 FromType, IncompatibleObjC)) { 1587 // Pointer conversions (C++ 4.10). 1588 SCS.Second = ICK_Pointer_Conversion; 1589 SCS.IncompatibleObjC = IncompatibleObjC; 1590 FromType = FromType.getUnqualifiedType(); 1591 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1592 InOverloadResolution, FromType)) { 1593 // Pointer to member conversions (4.11). 1594 SCS.Second = ICK_Pointer_Member; 1595 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1596 SCS.Second = SecondICK; 1597 FromType = ToType.getUnqualifiedType(); 1598 } else if (!S.getLangOpts().CPlusPlus && 1599 S.Context.typesAreCompatible(ToType, FromType)) { 1600 // Compatible conversions (Clang extension for C function overloading) 1601 SCS.Second = ICK_Compatible_Conversion; 1602 FromType = ToType.getUnqualifiedType(); 1603 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1604 // Treat a conversion that strips "noreturn" as an identity conversion. 1605 SCS.Second = ICK_NoReturn_Adjustment; 1606 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1607 InOverloadResolution, 1608 SCS, CStyle)) { 1609 SCS.Second = ICK_TransparentUnionConversion; 1610 FromType = ToType; 1611 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1612 CStyle)) { 1613 // tryAtomicConversion has updated the standard conversion sequence 1614 // appropriately. 1615 return true; 1616 } else if (ToType->isEventT() && 1617 From->isIntegerConstantExpr(S.getASTContext()) && 1618 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1619 SCS.Second = ICK_Zero_Event_Conversion; 1620 FromType = ToType; 1621 } else { 1622 // No second conversion required. 1623 SCS.Second = ICK_Identity; 1624 } 1625 SCS.setToType(1, FromType); 1626 1627 QualType CanonFrom; 1628 QualType CanonTo; 1629 // The third conversion can be a qualification conversion (C++ 4p1). 1630 bool ObjCLifetimeConversion; 1631 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1632 ObjCLifetimeConversion)) { 1633 SCS.Third = ICK_Qualification; 1634 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1635 FromType = ToType; 1636 CanonFrom = S.Context.getCanonicalType(FromType); 1637 CanonTo = S.Context.getCanonicalType(ToType); 1638 } else { 1639 // No conversion required 1640 SCS.Third = ICK_Identity; 1641 1642 // C++ [over.best.ics]p6: 1643 // [...] Any difference in top-level cv-qualification is 1644 // subsumed by the initialization itself and does not constitute 1645 // a conversion. [...] 1646 CanonFrom = S.Context.getCanonicalType(FromType); 1647 CanonTo = S.Context.getCanonicalType(ToType); 1648 if (CanonFrom.getLocalUnqualifiedType() 1649 == CanonTo.getLocalUnqualifiedType() && 1650 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1651 FromType = ToType; 1652 CanonFrom = CanonTo; 1653 } 1654 } 1655 SCS.setToType(2, FromType); 1656 1657 // If we have not converted the argument type to the parameter type, 1658 // this is a bad conversion sequence. 1659 if (CanonFrom != CanonTo) 1660 return false; 1661 1662 return true; 1663 } 1664 1665 static bool 1666 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1667 QualType &ToType, 1668 bool InOverloadResolution, 1669 StandardConversionSequence &SCS, 1670 bool CStyle) { 1671 1672 const RecordType *UT = ToType->getAsUnionType(); 1673 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1674 return false; 1675 // The field to initialize within the transparent union. 1676 RecordDecl *UD = UT->getDecl(); 1677 // It's compatible if the expression matches any of the fields. 1678 for (const auto *it : UD->fields()) { 1679 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1680 CStyle, /*ObjCWritebackConversion=*/false)) { 1681 ToType = it->getType(); 1682 return true; 1683 } 1684 } 1685 return false; 1686 } 1687 1688 /// IsIntegralPromotion - Determines whether the conversion from the 1689 /// expression From (whose potentially-adjusted type is FromType) to 1690 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1691 /// sets PromotedType to the promoted type. 1692 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1693 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1694 // All integers are built-in. 1695 if (!To) { 1696 return false; 1697 } 1698 1699 // An rvalue of type char, signed char, unsigned char, short int, or 1700 // unsigned short int can be converted to an rvalue of type int if 1701 // int can represent all the values of the source type; otherwise, 1702 // the source rvalue can be converted to an rvalue of type unsigned 1703 // int (C++ 4.5p1). 1704 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1705 !FromType->isEnumeralType()) { 1706 if (// We can promote any signed, promotable integer type to an int 1707 (FromType->isSignedIntegerType() || 1708 // We can promote any unsigned integer type whose size is 1709 // less than int to an int. 1710 (!FromType->isSignedIntegerType() && 1711 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1712 return To->getKind() == BuiltinType::Int; 1713 } 1714 1715 return To->getKind() == BuiltinType::UInt; 1716 } 1717 1718 // C++11 [conv.prom]p3: 1719 // A prvalue of an unscoped enumeration type whose underlying type is not 1720 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1721 // following types that can represent all the values of the enumeration 1722 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1723 // unsigned int, long int, unsigned long int, long long int, or unsigned 1724 // long long int. If none of the types in that list can represent all the 1725 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1726 // type can be converted to an rvalue a prvalue of the extended integer type 1727 // with lowest integer conversion rank (4.13) greater than the rank of long 1728 // long in which all the values of the enumeration can be represented. If 1729 // there are two such extended types, the signed one is chosen. 1730 // C++11 [conv.prom]p4: 1731 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1732 // can be converted to a prvalue of its underlying type. Moreover, if 1733 // integral promotion can be applied to its underlying type, a prvalue of an 1734 // unscoped enumeration type whose underlying type is fixed can also be 1735 // converted to a prvalue of the promoted underlying type. 1736 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1737 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1738 // provided for a scoped enumeration. 1739 if (FromEnumType->getDecl()->isScoped()) 1740 return false; 1741 1742 // We can perform an integral promotion to the underlying type of the enum, 1743 // even if that's not the promoted type. 1744 if (FromEnumType->getDecl()->isFixed()) { 1745 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1746 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1747 IsIntegralPromotion(From, Underlying, ToType); 1748 } 1749 1750 // We have already pre-calculated the promotion type, so this is trivial. 1751 if (ToType->isIntegerType() && 1752 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1753 return Context.hasSameUnqualifiedType(ToType, 1754 FromEnumType->getDecl()->getPromotionType()); 1755 } 1756 1757 // C++0x [conv.prom]p2: 1758 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1759 // to an rvalue a prvalue of the first of the following types that can 1760 // represent all the values of its underlying type: int, unsigned int, 1761 // long int, unsigned long int, long long int, or unsigned long long int. 1762 // If none of the types in that list can represent all the values of its 1763 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1764 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1765 // type. 1766 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1767 ToType->isIntegerType()) { 1768 // Determine whether the type we're converting from is signed or 1769 // unsigned. 1770 bool FromIsSigned = FromType->isSignedIntegerType(); 1771 uint64_t FromSize = Context.getTypeSize(FromType); 1772 1773 // The types we'll try to promote to, in the appropriate 1774 // order. Try each of these types. 1775 QualType PromoteTypes[6] = { 1776 Context.IntTy, Context.UnsignedIntTy, 1777 Context.LongTy, Context.UnsignedLongTy , 1778 Context.LongLongTy, Context.UnsignedLongLongTy 1779 }; 1780 for (int Idx = 0; Idx < 6; ++Idx) { 1781 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1782 if (FromSize < ToSize || 1783 (FromSize == ToSize && 1784 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1785 // We found the type that we can promote to. If this is the 1786 // type we wanted, we have a promotion. Otherwise, no 1787 // promotion. 1788 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1789 } 1790 } 1791 } 1792 1793 // An rvalue for an integral bit-field (9.6) can be converted to an 1794 // rvalue of type int if int can represent all the values of the 1795 // bit-field; otherwise, it can be converted to unsigned int if 1796 // unsigned int can represent all the values of the bit-field. If 1797 // the bit-field is larger yet, no integral promotion applies to 1798 // it. If the bit-field has an enumerated type, it is treated as any 1799 // other value of that type for promotion purposes (C++ 4.5p3). 1800 // FIXME: We should delay checking of bit-fields until we actually perform the 1801 // conversion. 1802 using llvm::APSInt; 1803 if (From) 1804 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1805 APSInt BitWidth; 1806 if (FromType->isIntegralType(Context) && 1807 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1808 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1809 ToSize = Context.getTypeSize(ToType); 1810 1811 // Are we promoting to an int from a bitfield that fits in an int? 1812 if (BitWidth < ToSize || 1813 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1814 return To->getKind() == BuiltinType::Int; 1815 } 1816 1817 // Are we promoting to an unsigned int from an unsigned bitfield 1818 // that fits into an unsigned int? 1819 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1820 return To->getKind() == BuiltinType::UInt; 1821 } 1822 1823 return false; 1824 } 1825 } 1826 1827 // An rvalue of type bool can be converted to an rvalue of type int, 1828 // with false becoming zero and true becoming one (C++ 4.5p4). 1829 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1830 return true; 1831 } 1832 1833 return false; 1834 } 1835 1836 /// IsFloatingPointPromotion - Determines whether the conversion from 1837 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1838 /// returns true and sets PromotedType to the promoted type. 1839 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1840 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1841 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1842 /// An rvalue of type float can be converted to an rvalue of type 1843 /// double. (C++ 4.6p1). 1844 if (FromBuiltin->getKind() == BuiltinType::Float && 1845 ToBuiltin->getKind() == BuiltinType::Double) 1846 return true; 1847 1848 // C99 6.3.1.5p1: 1849 // When a float is promoted to double or long double, or a 1850 // double is promoted to long double [...]. 1851 if (!getLangOpts().CPlusPlus && 1852 (FromBuiltin->getKind() == BuiltinType::Float || 1853 FromBuiltin->getKind() == BuiltinType::Double) && 1854 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1855 return true; 1856 1857 // Half can be promoted to float. 1858 if (!getLangOpts().NativeHalfType && 1859 FromBuiltin->getKind() == BuiltinType::Half && 1860 ToBuiltin->getKind() == BuiltinType::Float) 1861 return true; 1862 } 1863 1864 return false; 1865 } 1866 1867 /// \brief Determine if a conversion is a complex promotion. 1868 /// 1869 /// A complex promotion is defined as a complex -> complex conversion 1870 /// where the conversion between the underlying real types is a 1871 /// floating-point or integral promotion. 1872 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1873 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1874 if (!FromComplex) 1875 return false; 1876 1877 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1878 if (!ToComplex) 1879 return false; 1880 1881 return IsFloatingPointPromotion(FromComplex->getElementType(), 1882 ToComplex->getElementType()) || 1883 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 1884 ToComplex->getElementType()); 1885 } 1886 1887 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1888 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1889 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1890 /// if non-empty, will be a pointer to ToType that may or may not have 1891 /// the right set of qualifiers on its pointee. 1892 /// 1893 static QualType 1894 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1895 QualType ToPointee, QualType ToType, 1896 ASTContext &Context, 1897 bool StripObjCLifetime = false) { 1898 assert((FromPtr->getTypeClass() == Type::Pointer || 1899 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1900 "Invalid similarly-qualified pointer type"); 1901 1902 /// Conversions to 'id' subsume cv-qualifier conversions. 1903 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1904 return ToType.getUnqualifiedType(); 1905 1906 QualType CanonFromPointee 1907 = Context.getCanonicalType(FromPtr->getPointeeType()); 1908 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1909 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1910 1911 if (StripObjCLifetime) 1912 Quals.removeObjCLifetime(); 1913 1914 // Exact qualifier match -> return the pointer type we're converting to. 1915 if (CanonToPointee.getLocalQualifiers() == Quals) { 1916 // ToType is exactly what we need. Return it. 1917 if (!ToType.isNull()) 1918 return ToType.getUnqualifiedType(); 1919 1920 // Build a pointer to ToPointee. It has the right qualifiers 1921 // already. 1922 if (isa<ObjCObjectPointerType>(ToType)) 1923 return Context.getObjCObjectPointerType(ToPointee); 1924 return Context.getPointerType(ToPointee); 1925 } 1926 1927 // Just build a canonical type that has the right qualifiers. 1928 QualType QualifiedCanonToPointee 1929 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1930 1931 if (isa<ObjCObjectPointerType>(ToType)) 1932 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1933 return Context.getPointerType(QualifiedCanonToPointee); 1934 } 1935 1936 static bool isNullPointerConstantForConversion(Expr *Expr, 1937 bool InOverloadResolution, 1938 ASTContext &Context) { 1939 // Handle value-dependent integral null pointer constants correctly. 1940 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1941 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1942 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1943 return !InOverloadResolution; 1944 1945 return Expr->isNullPointerConstant(Context, 1946 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1947 : Expr::NPC_ValueDependentIsNull); 1948 } 1949 1950 /// IsPointerConversion - Determines whether the conversion of the 1951 /// expression From, which has the (possibly adjusted) type FromType, 1952 /// can be converted to the type ToType via a pointer conversion (C++ 1953 /// 4.10). If so, returns true and places the converted type (that 1954 /// might differ from ToType in its cv-qualifiers at some level) into 1955 /// ConvertedType. 1956 /// 1957 /// This routine also supports conversions to and from block pointers 1958 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 1959 /// pointers to interfaces. FIXME: Once we've determined the 1960 /// appropriate overloading rules for Objective-C, we may want to 1961 /// split the Objective-C checks into a different routine; however, 1962 /// GCC seems to consider all of these conversions to be pointer 1963 /// conversions, so for now they live here. IncompatibleObjC will be 1964 /// set if the conversion is an allowed Objective-C conversion that 1965 /// should result in a warning. 1966 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1967 bool InOverloadResolution, 1968 QualType& ConvertedType, 1969 bool &IncompatibleObjC) { 1970 IncompatibleObjC = false; 1971 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1972 IncompatibleObjC)) 1973 return true; 1974 1975 // Conversion from a null pointer constant to any Objective-C pointer type. 1976 if (ToType->isObjCObjectPointerType() && 1977 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1978 ConvertedType = ToType; 1979 return true; 1980 } 1981 1982 // Blocks: Block pointers can be converted to void*. 1983 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1984 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1985 ConvertedType = ToType; 1986 return true; 1987 } 1988 // Blocks: A null pointer constant can be converted to a block 1989 // pointer type. 1990 if (ToType->isBlockPointerType() && 1991 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1992 ConvertedType = ToType; 1993 return true; 1994 } 1995 1996 // If the left-hand-side is nullptr_t, the right side can be a null 1997 // pointer constant. 1998 if (ToType->isNullPtrType() && 1999 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2000 ConvertedType = ToType; 2001 return true; 2002 } 2003 2004 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2005 if (!ToTypePtr) 2006 return false; 2007 2008 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2009 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2010 ConvertedType = ToType; 2011 return true; 2012 } 2013 2014 // Beyond this point, both types need to be pointers 2015 // , including objective-c pointers. 2016 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2017 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2018 !getLangOpts().ObjCAutoRefCount) { 2019 ConvertedType = BuildSimilarlyQualifiedPointerType( 2020 FromType->getAs<ObjCObjectPointerType>(), 2021 ToPointeeType, 2022 ToType, Context); 2023 return true; 2024 } 2025 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2026 if (!FromTypePtr) 2027 return false; 2028 2029 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2030 2031 // If the unqualified pointee types are the same, this can't be a 2032 // pointer conversion, so don't do all of the work below. 2033 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2034 return false; 2035 2036 // An rvalue of type "pointer to cv T," where T is an object type, 2037 // can be converted to an rvalue of type "pointer to cv void" (C++ 2038 // 4.10p2). 2039 if (FromPointeeType->isIncompleteOrObjectType() && 2040 ToPointeeType->isVoidType()) { 2041 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2042 ToPointeeType, 2043 ToType, Context, 2044 /*StripObjCLifetime=*/true); 2045 return true; 2046 } 2047 2048 // MSVC allows implicit function to void* type conversion. 2049 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2050 ToPointeeType->isVoidType()) { 2051 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2052 ToPointeeType, 2053 ToType, Context); 2054 return true; 2055 } 2056 2057 // When we're overloading in C, we allow a special kind of pointer 2058 // conversion for compatible-but-not-identical pointee types. 2059 if (!getLangOpts().CPlusPlus && 2060 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2061 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2062 ToPointeeType, 2063 ToType, Context); 2064 return true; 2065 } 2066 2067 // C++ [conv.ptr]p3: 2068 // 2069 // An rvalue of type "pointer to cv D," where D is a class type, 2070 // can be converted to an rvalue of type "pointer to cv B," where 2071 // B is a base class (clause 10) of D. If B is an inaccessible 2072 // (clause 11) or ambiguous (10.2) base class of D, a program that 2073 // necessitates this conversion is ill-formed. The result of the 2074 // conversion is a pointer to the base class sub-object of the 2075 // derived class object. The null pointer value is converted to 2076 // the null pointer value of the destination type. 2077 // 2078 // Note that we do not check for ambiguity or inaccessibility 2079 // here. That is handled by CheckPointerConversion. 2080 if (getLangOpts().CPlusPlus && 2081 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2082 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2083 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2084 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2085 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2086 ToPointeeType, 2087 ToType, Context); 2088 return true; 2089 } 2090 2091 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2092 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2093 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2094 ToPointeeType, 2095 ToType, Context); 2096 return true; 2097 } 2098 2099 return false; 2100 } 2101 2102 /// \brief Adopt the given qualifiers for the given type. 2103 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2104 Qualifiers TQs = T.getQualifiers(); 2105 2106 // Check whether qualifiers already match. 2107 if (TQs == Qs) 2108 return T; 2109 2110 if (Qs.compatiblyIncludes(TQs)) 2111 return Context.getQualifiedType(T, Qs); 2112 2113 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2114 } 2115 2116 /// isObjCPointerConversion - Determines whether this is an 2117 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2118 /// with the same arguments and return values. 2119 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2120 QualType& ConvertedType, 2121 bool &IncompatibleObjC) { 2122 if (!getLangOpts().ObjC1) 2123 return false; 2124 2125 // The set of qualifiers on the type we're converting from. 2126 Qualifiers FromQualifiers = FromType.getQualifiers(); 2127 2128 // First, we handle all conversions on ObjC object pointer types. 2129 const ObjCObjectPointerType* ToObjCPtr = 2130 ToType->getAs<ObjCObjectPointerType>(); 2131 const ObjCObjectPointerType *FromObjCPtr = 2132 FromType->getAs<ObjCObjectPointerType>(); 2133 2134 if (ToObjCPtr && FromObjCPtr) { 2135 // If the pointee types are the same (ignoring qualifications), 2136 // then this is not a pointer conversion. 2137 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2138 FromObjCPtr->getPointeeType())) 2139 return false; 2140 2141 // Check for compatible 2142 // Objective C++: We're able to convert between "id" or "Class" and a 2143 // pointer to any interface (in both directions). 2144 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2145 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2146 return true; 2147 } 2148 // Conversions with Objective-C's id<...>. 2149 if ((FromObjCPtr->isObjCQualifiedIdType() || 2150 ToObjCPtr->isObjCQualifiedIdType()) && 2151 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2152 /*compare=*/false)) { 2153 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2154 return true; 2155 } 2156 // Objective C++: We're able to convert from a pointer to an 2157 // interface to a pointer to a different interface. 2158 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2159 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2160 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2161 if (getLangOpts().CPlusPlus && LHS && RHS && 2162 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2163 FromObjCPtr->getPointeeType())) 2164 return false; 2165 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2166 ToObjCPtr->getPointeeType(), 2167 ToType, Context); 2168 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2169 return true; 2170 } 2171 2172 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2173 // Okay: this is some kind of implicit downcast of Objective-C 2174 // interfaces, which is permitted. However, we're going to 2175 // complain about it. 2176 IncompatibleObjC = true; 2177 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2178 ToObjCPtr->getPointeeType(), 2179 ToType, Context); 2180 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2181 return true; 2182 } 2183 } 2184 // Beyond this point, both types need to be C pointers or block pointers. 2185 QualType ToPointeeType; 2186 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2187 ToPointeeType = ToCPtr->getPointeeType(); 2188 else if (const BlockPointerType *ToBlockPtr = 2189 ToType->getAs<BlockPointerType>()) { 2190 // Objective C++: We're able to convert from a pointer to any object 2191 // to a block pointer type. 2192 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2193 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2194 return true; 2195 } 2196 ToPointeeType = ToBlockPtr->getPointeeType(); 2197 } 2198 else if (FromType->getAs<BlockPointerType>() && 2199 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2200 // Objective C++: We're able to convert from a block pointer type to a 2201 // pointer to any object. 2202 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2203 return true; 2204 } 2205 else 2206 return false; 2207 2208 QualType FromPointeeType; 2209 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2210 FromPointeeType = FromCPtr->getPointeeType(); 2211 else if (const BlockPointerType *FromBlockPtr = 2212 FromType->getAs<BlockPointerType>()) 2213 FromPointeeType = FromBlockPtr->getPointeeType(); 2214 else 2215 return false; 2216 2217 // If we have pointers to pointers, recursively check whether this 2218 // is an Objective-C conversion. 2219 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2220 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2221 IncompatibleObjC)) { 2222 // We always complain about this conversion. 2223 IncompatibleObjC = true; 2224 ConvertedType = Context.getPointerType(ConvertedType); 2225 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2226 return true; 2227 } 2228 // Allow conversion of pointee being objective-c pointer to another one; 2229 // as in I* to id. 2230 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2231 ToPointeeType->getAs<ObjCObjectPointerType>() && 2232 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2233 IncompatibleObjC)) { 2234 2235 ConvertedType = Context.getPointerType(ConvertedType); 2236 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2237 return true; 2238 } 2239 2240 // If we have pointers to functions or blocks, check whether the only 2241 // differences in the argument and result types are in Objective-C 2242 // pointer conversions. If so, we permit the conversion (but 2243 // complain about it). 2244 const FunctionProtoType *FromFunctionType 2245 = FromPointeeType->getAs<FunctionProtoType>(); 2246 const FunctionProtoType *ToFunctionType 2247 = ToPointeeType->getAs<FunctionProtoType>(); 2248 if (FromFunctionType && ToFunctionType) { 2249 // If the function types are exactly the same, this isn't an 2250 // Objective-C pointer conversion. 2251 if (Context.getCanonicalType(FromPointeeType) 2252 == Context.getCanonicalType(ToPointeeType)) 2253 return false; 2254 2255 // Perform the quick checks that will tell us whether these 2256 // function types are obviously different. 2257 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2258 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2259 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2260 return false; 2261 2262 bool HasObjCConversion = false; 2263 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2264 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2265 // Okay, the types match exactly. Nothing to do. 2266 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2267 ToFunctionType->getReturnType(), 2268 ConvertedType, IncompatibleObjC)) { 2269 // Okay, we have an Objective-C pointer conversion. 2270 HasObjCConversion = true; 2271 } else { 2272 // Function types are too different. Abort. 2273 return false; 2274 } 2275 2276 // Check argument types. 2277 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2278 ArgIdx != NumArgs; ++ArgIdx) { 2279 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2280 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2281 if (Context.getCanonicalType(FromArgType) 2282 == Context.getCanonicalType(ToArgType)) { 2283 // Okay, the types match exactly. Nothing to do. 2284 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2285 ConvertedType, IncompatibleObjC)) { 2286 // Okay, we have an Objective-C pointer conversion. 2287 HasObjCConversion = true; 2288 } else { 2289 // Argument types are too different. Abort. 2290 return false; 2291 } 2292 } 2293 2294 if (HasObjCConversion) { 2295 // We had an Objective-C conversion. Allow this pointer 2296 // conversion, but complain about it. 2297 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2298 IncompatibleObjC = true; 2299 return true; 2300 } 2301 } 2302 2303 return false; 2304 } 2305 2306 /// \brief Determine whether this is an Objective-C writeback conversion, 2307 /// used for parameter passing when performing automatic reference counting. 2308 /// 2309 /// \param FromType The type we're converting form. 2310 /// 2311 /// \param ToType The type we're converting to. 2312 /// 2313 /// \param ConvertedType The type that will be produced after applying 2314 /// this conversion. 2315 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2316 QualType &ConvertedType) { 2317 if (!getLangOpts().ObjCAutoRefCount || 2318 Context.hasSameUnqualifiedType(FromType, ToType)) 2319 return false; 2320 2321 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2322 QualType ToPointee; 2323 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2324 ToPointee = ToPointer->getPointeeType(); 2325 else 2326 return false; 2327 2328 Qualifiers ToQuals = ToPointee.getQualifiers(); 2329 if (!ToPointee->isObjCLifetimeType() || 2330 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2331 !ToQuals.withoutObjCLifetime().empty()) 2332 return false; 2333 2334 // Argument must be a pointer to __strong to __weak. 2335 QualType FromPointee; 2336 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2337 FromPointee = FromPointer->getPointeeType(); 2338 else 2339 return false; 2340 2341 Qualifiers FromQuals = FromPointee.getQualifiers(); 2342 if (!FromPointee->isObjCLifetimeType() || 2343 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2344 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2345 return false; 2346 2347 // Make sure that we have compatible qualifiers. 2348 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2349 if (!ToQuals.compatiblyIncludes(FromQuals)) 2350 return false; 2351 2352 // Remove qualifiers from the pointee type we're converting from; they 2353 // aren't used in the compatibility check belong, and we'll be adding back 2354 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2355 FromPointee = FromPointee.getUnqualifiedType(); 2356 2357 // The unqualified form of the pointee types must be compatible. 2358 ToPointee = ToPointee.getUnqualifiedType(); 2359 bool IncompatibleObjC; 2360 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2361 FromPointee = ToPointee; 2362 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2363 IncompatibleObjC)) 2364 return false; 2365 2366 /// \brief Construct the type we're converting to, which is a pointer to 2367 /// __autoreleasing pointee. 2368 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2369 ConvertedType = Context.getPointerType(FromPointee); 2370 return true; 2371 } 2372 2373 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2374 QualType& ConvertedType) { 2375 QualType ToPointeeType; 2376 if (const BlockPointerType *ToBlockPtr = 2377 ToType->getAs<BlockPointerType>()) 2378 ToPointeeType = ToBlockPtr->getPointeeType(); 2379 else 2380 return false; 2381 2382 QualType FromPointeeType; 2383 if (const BlockPointerType *FromBlockPtr = 2384 FromType->getAs<BlockPointerType>()) 2385 FromPointeeType = FromBlockPtr->getPointeeType(); 2386 else 2387 return false; 2388 // We have pointer to blocks, check whether the only 2389 // differences in the argument and result types are in Objective-C 2390 // pointer conversions. If so, we permit the conversion. 2391 2392 const FunctionProtoType *FromFunctionType 2393 = FromPointeeType->getAs<FunctionProtoType>(); 2394 const FunctionProtoType *ToFunctionType 2395 = ToPointeeType->getAs<FunctionProtoType>(); 2396 2397 if (!FromFunctionType || !ToFunctionType) 2398 return false; 2399 2400 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2401 return true; 2402 2403 // Perform the quick checks that will tell us whether these 2404 // function types are obviously different. 2405 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2406 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2407 return false; 2408 2409 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2410 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2411 if (FromEInfo != ToEInfo) 2412 return false; 2413 2414 bool IncompatibleObjC = false; 2415 if (Context.hasSameType(FromFunctionType->getReturnType(), 2416 ToFunctionType->getReturnType())) { 2417 // Okay, the types match exactly. Nothing to do. 2418 } else { 2419 QualType RHS = FromFunctionType->getReturnType(); 2420 QualType LHS = ToFunctionType->getReturnType(); 2421 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2422 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2423 LHS = LHS.getUnqualifiedType(); 2424 2425 if (Context.hasSameType(RHS,LHS)) { 2426 // OK exact match. 2427 } else if (isObjCPointerConversion(RHS, LHS, 2428 ConvertedType, IncompatibleObjC)) { 2429 if (IncompatibleObjC) 2430 return false; 2431 // Okay, we have an Objective-C pointer conversion. 2432 } 2433 else 2434 return false; 2435 } 2436 2437 // Check argument types. 2438 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2439 ArgIdx != NumArgs; ++ArgIdx) { 2440 IncompatibleObjC = false; 2441 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2442 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2443 if (Context.hasSameType(FromArgType, ToArgType)) { 2444 // Okay, the types match exactly. Nothing to do. 2445 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2446 ConvertedType, IncompatibleObjC)) { 2447 if (IncompatibleObjC) 2448 return false; 2449 // Okay, we have an Objective-C pointer conversion. 2450 } else 2451 // Argument types are too different. Abort. 2452 return false; 2453 } 2454 if (LangOpts.ObjCAutoRefCount && 2455 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2456 ToFunctionType)) 2457 return false; 2458 2459 ConvertedType = ToType; 2460 return true; 2461 } 2462 2463 enum { 2464 ft_default, 2465 ft_different_class, 2466 ft_parameter_arity, 2467 ft_parameter_mismatch, 2468 ft_return_type, 2469 ft_qualifer_mismatch 2470 }; 2471 2472 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2473 /// function types. Catches different number of parameter, mismatch in 2474 /// parameter types, and different return types. 2475 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2476 QualType FromType, QualType ToType) { 2477 // If either type is not valid, include no extra info. 2478 if (FromType.isNull() || ToType.isNull()) { 2479 PDiag << ft_default; 2480 return; 2481 } 2482 2483 // Get the function type from the pointers. 2484 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2485 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2486 *ToMember = ToType->getAs<MemberPointerType>(); 2487 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2488 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2489 << QualType(FromMember->getClass(), 0); 2490 return; 2491 } 2492 FromType = FromMember->getPointeeType(); 2493 ToType = ToMember->getPointeeType(); 2494 } 2495 2496 if (FromType->isPointerType()) 2497 FromType = FromType->getPointeeType(); 2498 if (ToType->isPointerType()) 2499 ToType = ToType->getPointeeType(); 2500 2501 // Remove references. 2502 FromType = FromType.getNonReferenceType(); 2503 ToType = ToType.getNonReferenceType(); 2504 2505 // Don't print extra info for non-specialized template functions. 2506 if (FromType->isInstantiationDependentType() && 2507 !FromType->getAs<TemplateSpecializationType>()) { 2508 PDiag << ft_default; 2509 return; 2510 } 2511 2512 // No extra info for same types. 2513 if (Context.hasSameType(FromType, ToType)) { 2514 PDiag << ft_default; 2515 return; 2516 } 2517 2518 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2519 *ToFunction = ToType->getAs<FunctionProtoType>(); 2520 2521 // Both types need to be function types. 2522 if (!FromFunction || !ToFunction) { 2523 PDiag << ft_default; 2524 return; 2525 } 2526 2527 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2528 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2529 << FromFunction->getNumParams(); 2530 return; 2531 } 2532 2533 // Handle different parameter types. 2534 unsigned ArgPos; 2535 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2536 PDiag << ft_parameter_mismatch << ArgPos + 1 2537 << ToFunction->getParamType(ArgPos) 2538 << FromFunction->getParamType(ArgPos); 2539 return; 2540 } 2541 2542 // Handle different return type. 2543 if (!Context.hasSameType(FromFunction->getReturnType(), 2544 ToFunction->getReturnType())) { 2545 PDiag << ft_return_type << ToFunction->getReturnType() 2546 << FromFunction->getReturnType(); 2547 return; 2548 } 2549 2550 unsigned FromQuals = FromFunction->getTypeQuals(), 2551 ToQuals = ToFunction->getTypeQuals(); 2552 if (FromQuals != ToQuals) { 2553 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2554 return; 2555 } 2556 2557 // Unable to find a difference, so add no extra info. 2558 PDiag << ft_default; 2559 } 2560 2561 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2562 /// for equality of their argument types. Caller has already checked that 2563 /// they have same number of arguments. If the parameters are different, 2564 /// ArgPos will have the parameter index of the first different parameter. 2565 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2566 const FunctionProtoType *NewType, 2567 unsigned *ArgPos) { 2568 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2569 N = NewType->param_type_begin(), 2570 E = OldType->param_type_end(); 2571 O && (O != E); ++O, ++N) { 2572 if (!Context.hasSameType(O->getUnqualifiedType(), 2573 N->getUnqualifiedType())) { 2574 if (ArgPos) 2575 *ArgPos = O - OldType->param_type_begin(); 2576 return false; 2577 } 2578 } 2579 return true; 2580 } 2581 2582 /// CheckPointerConversion - Check the pointer conversion from the 2583 /// expression From to the type ToType. This routine checks for 2584 /// ambiguous or inaccessible derived-to-base pointer 2585 /// conversions for which IsPointerConversion has already returned 2586 /// true. It returns true and produces a diagnostic if there was an 2587 /// error, or returns false otherwise. 2588 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2589 CastKind &Kind, 2590 CXXCastPath& BasePath, 2591 bool IgnoreBaseAccess) { 2592 QualType FromType = From->getType(); 2593 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2594 2595 Kind = CK_BitCast; 2596 2597 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2598 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2599 Expr::NPCK_ZeroExpression) { 2600 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2601 DiagRuntimeBehavior(From->getExprLoc(), From, 2602 PDiag(diag::warn_impcast_bool_to_null_pointer) 2603 << ToType << From->getSourceRange()); 2604 else if (!isUnevaluatedContext()) 2605 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2606 << ToType << From->getSourceRange(); 2607 } 2608 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2609 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2610 QualType FromPointeeType = FromPtrType->getPointeeType(), 2611 ToPointeeType = ToPtrType->getPointeeType(); 2612 2613 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2614 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2615 // We must have a derived-to-base conversion. Check an 2616 // ambiguous or inaccessible conversion. 2617 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2618 From->getExprLoc(), 2619 From->getSourceRange(), &BasePath, 2620 IgnoreBaseAccess)) 2621 return true; 2622 2623 // The conversion was successful. 2624 Kind = CK_DerivedToBase; 2625 } 2626 } 2627 } else if (const ObjCObjectPointerType *ToPtrType = 2628 ToType->getAs<ObjCObjectPointerType>()) { 2629 if (const ObjCObjectPointerType *FromPtrType = 2630 FromType->getAs<ObjCObjectPointerType>()) { 2631 // Objective-C++ conversions are always okay. 2632 // FIXME: We should have a different class of conversions for the 2633 // Objective-C++ implicit conversions. 2634 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2635 return false; 2636 } else if (FromType->isBlockPointerType()) { 2637 Kind = CK_BlockPointerToObjCPointerCast; 2638 } else { 2639 Kind = CK_CPointerToObjCPointerCast; 2640 } 2641 } else if (ToType->isBlockPointerType()) { 2642 if (!FromType->isBlockPointerType()) 2643 Kind = CK_AnyPointerToBlockPointerCast; 2644 } 2645 2646 // We shouldn't fall into this case unless it's valid for other 2647 // reasons. 2648 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2649 Kind = CK_NullToPointer; 2650 2651 return false; 2652 } 2653 2654 /// IsMemberPointerConversion - Determines whether the conversion of the 2655 /// expression From, which has the (possibly adjusted) type FromType, can be 2656 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2657 /// If so, returns true and places the converted type (that might differ from 2658 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2659 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2660 QualType ToType, 2661 bool InOverloadResolution, 2662 QualType &ConvertedType) { 2663 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2664 if (!ToTypePtr) 2665 return false; 2666 2667 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2668 if (From->isNullPointerConstant(Context, 2669 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2670 : Expr::NPC_ValueDependentIsNull)) { 2671 ConvertedType = ToType; 2672 return true; 2673 } 2674 2675 // Otherwise, both types have to be member pointers. 2676 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2677 if (!FromTypePtr) 2678 return false; 2679 2680 // A pointer to member of B can be converted to a pointer to member of D, 2681 // where D is derived from B (C++ 4.11p2). 2682 QualType FromClass(FromTypePtr->getClass(), 0); 2683 QualType ToClass(ToTypePtr->getClass(), 0); 2684 2685 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2686 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2687 IsDerivedFrom(ToClass, FromClass)) { 2688 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2689 ToClass.getTypePtr()); 2690 return true; 2691 } 2692 2693 return false; 2694 } 2695 2696 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2697 /// expression From to the type ToType. This routine checks for ambiguous or 2698 /// virtual or inaccessible base-to-derived member pointer conversions 2699 /// for which IsMemberPointerConversion has already returned true. It returns 2700 /// true and produces a diagnostic if there was an error, or returns false 2701 /// otherwise. 2702 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2703 CastKind &Kind, 2704 CXXCastPath &BasePath, 2705 bool IgnoreBaseAccess) { 2706 QualType FromType = From->getType(); 2707 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2708 if (!FromPtrType) { 2709 // This must be a null pointer to member pointer conversion 2710 assert(From->isNullPointerConstant(Context, 2711 Expr::NPC_ValueDependentIsNull) && 2712 "Expr must be null pointer constant!"); 2713 Kind = CK_NullToMemberPointer; 2714 return false; 2715 } 2716 2717 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2718 assert(ToPtrType && "No member pointer cast has a target type " 2719 "that is not a member pointer."); 2720 2721 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2722 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2723 2724 // FIXME: What about dependent types? 2725 assert(FromClass->isRecordType() && "Pointer into non-class."); 2726 assert(ToClass->isRecordType() && "Pointer into non-class."); 2727 2728 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2729 /*DetectVirtual=*/true); 2730 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2731 assert(DerivationOkay && 2732 "Should not have been called if derivation isn't OK."); 2733 (void)DerivationOkay; 2734 2735 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2736 getUnqualifiedType())) { 2737 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2738 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2739 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2740 return true; 2741 } 2742 2743 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2744 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2745 << FromClass << ToClass << QualType(VBase, 0) 2746 << From->getSourceRange(); 2747 return true; 2748 } 2749 2750 if (!IgnoreBaseAccess) 2751 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2752 Paths.front(), 2753 diag::err_downcast_from_inaccessible_base); 2754 2755 // Must be a base to derived member conversion. 2756 BuildBasePathArray(Paths, BasePath); 2757 Kind = CK_BaseToDerivedMemberPointer; 2758 return false; 2759 } 2760 2761 /// Determine whether the lifetime conversion between the two given 2762 /// qualifiers sets is nontrivial. 2763 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2764 Qualifiers ToQuals) { 2765 // Converting anything to const __unsafe_unretained is trivial. 2766 if (ToQuals.hasConst() && 2767 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2768 return false; 2769 2770 return true; 2771 } 2772 2773 /// IsQualificationConversion - Determines whether the conversion from 2774 /// an rvalue of type FromType to ToType is a qualification conversion 2775 /// (C++ 4.4). 2776 /// 2777 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2778 /// when the qualification conversion involves a change in the Objective-C 2779 /// object lifetime. 2780 bool 2781 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2782 bool CStyle, bool &ObjCLifetimeConversion) { 2783 FromType = Context.getCanonicalType(FromType); 2784 ToType = Context.getCanonicalType(ToType); 2785 ObjCLifetimeConversion = false; 2786 2787 // If FromType and ToType are the same type, this is not a 2788 // qualification conversion. 2789 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2790 return false; 2791 2792 // (C++ 4.4p4): 2793 // A conversion can add cv-qualifiers at levels other than the first 2794 // in multi-level pointers, subject to the following rules: [...] 2795 bool PreviousToQualsIncludeConst = true; 2796 bool UnwrappedAnyPointer = false; 2797 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2798 // Within each iteration of the loop, we check the qualifiers to 2799 // determine if this still looks like a qualification 2800 // conversion. Then, if all is well, we unwrap one more level of 2801 // pointers or pointers-to-members and do it all again 2802 // until there are no more pointers or pointers-to-members left to 2803 // unwrap. 2804 UnwrappedAnyPointer = true; 2805 2806 Qualifiers FromQuals = FromType.getQualifiers(); 2807 Qualifiers ToQuals = ToType.getQualifiers(); 2808 2809 // Objective-C ARC: 2810 // Check Objective-C lifetime conversions. 2811 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2812 UnwrappedAnyPointer) { 2813 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2814 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2815 ObjCLifetimeConversion = true; 2816 FromQuals.removeObjCLifetime(); 2817 ToQuals.removeObjCLifetime(); 2818 } else { 2819 // Qualification conversions cannot cast between different 2820 // Objective-C lifetime qualifiers. 2821 return false; 2822 } 2823 } 2824 2825 // Allow addition/removal of GC attributes but not changing GC attributes. 2826 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2827 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2828 FromQuals.removeObjCGCAttr(); 2829 ToQuals.removeObjCGCAttr(); 2830 } 2831 2832 // -- for every j > 0, if const is in cv 1,j then const is in cv 2833 // 2,j, and similarly for volatile. 2834 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2835 return false; 2836 2837 // -- if the cv 1,j and cv 2,j are different, then const is in 2838 // every cv for 0 < k < j. 2839 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2840 && !PreviousToQualsIncludeConst) 2841 return false; 2842 2843 // Keep track of whether all prior cv-qualifiers in the "to" type 2844 // include const. 2845 PreviousToQualsIncludeConst 2846 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2847 } 2848 2849 // We are left with FromType and ToType being the pointee types 2850 // after unwrapping the original FromType and ToType the same number 2851 // of types. If we unwrapped any pointers, and if FromType and 2852 // ToType have the same unqualified type (since we checked 2853 // qualifiers above), then this is a qualification conversion. 2854 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2855 } 2856 2857 /// \brief - Determine whether this is a conversion from a scalar type to an 2858 /// atomic type. 2859 /// 2860 /// If successful, updates \c SCS's second and third steps in the conversion 2861 /// sequence to finish the conversion. 2862 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2863 bool InOverloadResolution, 2864 StandardConversionSequence &SCS, 2865 bool CStyle) { 2866 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2867 if (!ToAtomic) 2868 return false; 2869 2870 StandardConversionSequence InnerSCS; 2871 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2872 InOverloadResolution, InnerSCS, 2873 CStyle, /*AllowObjCWritebackConversion=*/false)) 2874 return false; 2875 2876 SCS.Second = InnerSCS.Second; 2877 SCS.setToType(1, InnerSCS.getToType(1)); 2878 SCS.Third = InnerSCS.Third; 2879 SCS.QualificationIncludesObjCLifetime 2880 = InnerSCS.QualificationIncludesObjCLifetime; 2881 SCS.setToType(2, InnerSCS.getToType(2)); 2882 return true; 2883 } 2884 2885 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2886 CXXConstructorDecl *Constructor, 2887 QualType Type) { 2888 const FunctionProtoType *CtorType = 2889 Constructor->getType()->getAs<FunctionProtoType>(); 2890 if (CtorType->getNumParams() > 0) { 2891 QualType FirstArg = CtorType->getParamType(0); 2892 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2893 return true; 2894 } 2895 return false; 2896 } 2897 2898 static OverloadingResult 2899 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2900 CXXRecordDecl *To, 2901 UserDefinedConversionSequence &User, 2902 OverloadCandidateSet &CandidateSet, 2903 bool AllowExplicit) { 2904 DeclContext::lookup_result R = S.LookupConstructors(To); 2905 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2906 Con != ConEnd; ++Con) { 2907 NamedDecl *D = *Con; 2908 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2909 2910 // Find the constructor (which may be a template). 2911 CXXConstructorDecl *Constructor = nullptr; 2912 FunctionTemplateDecl *ConstructorTmpl 2913 = dyn_cast<FunctionTemplateDecl>(D); 2914 if (ConstructorTmpl) 2915 Constructor 2916 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2917 else 2918 Constructor = cast<CXXConstructorDecl>(D); 2919 2920 bool Usable = !Constructor->isInvalidDecl() && 2921 S.isInitListConstructor(Constructor) && 2922 (AllowExplicit || !Constructor->isExplicit()); 2923 if (Usable) { 2924 // If the first argument is (a reference to) the target type, 2925 // suppress conversions. 2926 bool SuppressUserConversions = 2927 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2928 if (ConstructorTmpl) 2929 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2930 /*ExplicitArgs*/ nullptr, 2931 From, CandidateSet, 2932 SuppressUserConversions); 2933 else 2934 S.AddOverloadCandidate(Constructor, FoundDecl, 2935 From, CandidateSet, 2936 SuppressUserConversions); 2937 } 2938 } 2939 2940 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2941 2942 OverloadCandidateSet::iterator Best; 2943 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2944 case OR_Success: { 2945 // Record the standard conversion we used and the conversion function. 2946 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2947 QualType ThisType = Constructor->getThisType(S.Context); 2948 // Initializer lists don't have conversions as such. 2949 User.Before.setAsIdentityConversion(); 2950 User.HadMultipleCandidates = HadMultipleCandidates; 2951 User.ConversionFunction = Constructor; 2952 User.FoundConversionFunction = Best->FoundDecl; 2953 User.After.setAsIdentityConversion(); 2954 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2955 User.After.setAllToTypes(ToType); 2956 return OR_Success; 2957 } 2958 2959 case OR_No_Viable_Function: 2960 return OR_No_Viable_Function; 2961 case OR_Deleted: 2962 return OR_Deleted; 2963 case OR_Ambiguous: 2964 return OR_Ambiguous; 2965 } 2966 2967 llvm_unreachable("Invalid OverloadResult!"); 2968 } 2969 2970 /// Determines whether there is a user-defined conversion sequence 2971 /// (C++ [over.ics.user]) that converts expression From to the type 2972 /// ToType. If such a conversion exists, User will contain the 2973 /// user-defined conversion sequence that performs such a conversion 2974 /// and this routine will return true. Otherwise, this routine returns 2975 /// false and User is unspecified. 2976 /// 2977 /// \param AllowExplicit true if the conversion should consider C++0x 2978 /// "explicit" conversion functions as well as non-explicit conversion 2979 /// functions (C++0x [class.conv.fct]p2). 2980 /// 2981 /// \param AllowObjCConversionOnExplicit true if the conversion should 2982 /// allow an extra Objective-C pointer conversion on uses of explicit 2983 /// constructors. Requires \c AllowExplicit to also be set. 2984 static OverloadingResult 2985 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2986 UserDefinedConversionSequence &User, 2987 OverloadCandidateSet &CandidateSet, 2988 bool AllowExplicit, 2989 bool AllowObjCConversionOnExplicit) { 2990 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 2991 2992 // Whether we will only visit constructors. 2993 bool ConstructorsOnly = false; 2994 2995 // If the type we are conversion to is a class type, enumerate its 2996 // constructors. 2997 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2998 // C++ [over.match.ctor]p1: 2999 // When objects of class type are direct-initialized (8.5), or 3000 // copy-initialized from an expression of the same or a 3001 // derived class type (8.5), overload resolution selects the 3002 // constructor. [...] For copy-initialization, the candidate 3003 // functions are all the converting constructors (12.3.1) of 3004 // that class. The argument list is the expression-list within 3005 // the parentheses of the initializer. 3006 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3007 (From->getType()->getAs<RecordType>() && 3008 S.IsDerivedFrom(From->getType(), ToType))) 3009 ConstructorsOnly = true; 3010 3011 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3012 // RequireCompleteType may have returned true due to some invalid decl 3013 // during template instantiation, but ToType may be complete enough now 3014 // to try to recover. 3015 if (ToType->isIncompleteType()) { 3016 // We're not going to find any constructors. 3017 } else if (CXXRecordDecl *ToRecordDecl 3018 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3019 3020 Expr **Args = &From; 3021 unsigned NumArgs = 1; 3022 bool ListInitializing = false; 3023 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3024 // But first, see if there is an init-list-constructor that will work. 3025 OverloadingResult Result = IsInitializerListConstructorConversion( 3026 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3027 if (Result != OR_No_Viable_Function) 3028 return Result; 3029 // Never mind. 3030 CandidateSet.clear(); 3031 3032 // If we're list-initializing, we pass the individual elements as 3033 // arguments, not the entire list. 3034 Args = InitList->getInits(); 3035 NumArgs = InitList->getNumInits(); 3036 ListInitializing = true; 3037 } 3038 3039 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3040 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3041 Con != ConEnd; ++Con) { 3042 NamedDecl *D = *Con; 3043 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3044 3045 // Find the constructor (which may be a template). 3046 CXXConstructorDecl *Constructor = nullptr; 3047 FunctionTemplateDecl *ConstructorTmpl 3048 = dyn_cast<FunctionTemplateDecl>(D); 3049 if (ConstructorTmpl) 3050 Constructor 3051 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3052 else 3053 Constructor = cast<CXXConstructorDecl>(D); 3054 3055 bool Usable = !Constructor->isInvalidDecl(); 3056 if (ListInitializing) 3057 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3058 else 3059 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3060 if (Usable) { 3061 bool SuppressUserConversions = !ConstructorsOnly; 3062 if (SuppressUserConversions && ListInitializing) { 3063 SuppressUserConversions = false; 3064 if (NumArgs == 1) { 3065 // If the first argument is (a reference to) the target type, 3066 // suppress conversions. 3067 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3068 S.Context, Constructor, ToType); 3069 } 3070 } 3071 if (ConstructorTmpl) 3072 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3073 /*ExplicitArgs*/ nullptr, 3074 llvm::makeArrayRef(Args, NumArgs), 3075 CandidateSet, SuppressUserConversions); 3076 else 3077 // Allow one user-defined conversion when user specifies a 3078 // From->ToType conversion via an static cast (c-style, etc). 3079 S.AddOverloadCandidate(Constructor, FoundDecl, 3080 llvm::makeArrayRef(Args, NumArgs), 3081 CandidateSet, SuppressUserConversions); 3082 } 3083 } 3084 } 3085 } 3086 3087 // Enumerate conversion functions, if we're allowed to. 3088 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3089 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3090 // No conversion functions from incomplete types. 3091 } else if (const RecordType *FromRecordType 3092 = From->getType()->getAs<RecordType>()) { 3093 if (CXXRecordDecl *FromRecordDecl 3094 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3095 // Add all of the conversion functions as candidates. 3096 std::pair<CXXRecordDecl::conversion_iterator, 3097 CXXRecordDecl::conversion_iterator> 3098 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3099 for (CXXRecordDecl::conversion_iterator 3100 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3101 DeclAccessPair FoundDecl = I.getPair(); 3102 NamedDecl *D = FoundDecl.getDecl(); 3103 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3104 if (isa<UsingShadowDecl>(D)) 3105 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3106 3107 CXXConversionDecl *Conv; 3108 FunctionTemplateDecl *ConvTemplate; 3109 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3110 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3111 else 3112 Conv = cast<CXXConversionDecl>(D); 3113 3114 if (AllowExplicit || !Conv->isExplicit()) { 3115 if (ConvTemplate) 3116 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3117 ActingContext, From, ToType, 3118 CandidateSet, 3119 AllowObjCConversionOnExplicit); 3120 else 3121 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3122 From, ToType, CandidateSet, 3123 AllowObjCConversionOnExplicit); 3124 } 3125 } 3126 } 3127 } 3128 3129 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3130 3131 OverloadCandidateSet::iterator Best; 3132 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3133 case OR_Success: 3134 // Record the standard conversion we used and the conversion function. 3135 if (CXXConstructorDecl *Constructor 3136 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3137 // C++ [over.ics.user]p1: 3138 // If the user-defined conversion is specified by a 3139 // constructor (12.3.1), the initial standard conversion 3140 // sequence converts the source type to the type required by 3141 // the argument of the constructor. 3142 // 3143 QualType ThisType = Constructor->getThisType(S.Context); 3144 if (isa<InitListExpr>(From)) { 3145 // Initializer lists don't have conversions as such. 3146 User.Before.setAsIdentityConversion(); 3147 } else { 3148 if (Best->Conversions[0].isEllipsis()) 3149 User.EllipsisConversion = true; 3150 else { 3151 User.Before = Best->Conversions[0].Standard; 3152 User.EllipsisConversion = false; 3153 } 3154 } 3155 User.HadMultipleCandidates = HadMultipleCandidates; 3156 User.ConversionFunction = Constructor; 3157 User.FoundConversionFunction = Best->FoundDecl; 3158 User.After.setAsIdentityConversion(); 3159 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3160 User.After.setAllToTypes(ToType); 3161 return OR_Success; 3162 } 3163 if (CXXConversionDecl *Conversion 3164 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3165 // C++ [over.ics.user]p1: 3166 // 3167 // [...] If the user-defined conversion is specified by a 3168 // conversion function (12.3.2), the initial standard 3169 // conversion sequence converts the source type to the 3170 // implicit object parameter of the conversion function. 3171 User.Before = Best->Conversions[0].Standard; 3172 User.HadMultipleCandidates = HadMultipleCandidates; 3173 User.ConversionFunction = Conversion; 3174 User.FoundConversionFunction = Best->FoundDecl; 3175 User.EllipsisConversion = false; 3176 3177 // C++ [over.ics.user]p2: 3178 // The second standard conversion sequence converts the 3179 // result of the user-defined conversion to the target type 3180 // for the sequence. Since an implicit conversion sequence 3181 // is an initialization, the special rules for 3182 // initialization by user-defined conversion apply when 3183 // selecting the best user-defined conversion for a 3184 // user-defined conversion sequence (see 13.3.3 and 3185 // 13.3.3.1). 3186 User.After = Best->FinalConversion; 3187 return OR_Success; 3188 } 3189 llvm_unreachable("Not a constructor or conversion function?"); 3190 3191 case OR_No_Viable_Function: 3192 return OR_No_Viable_Function; 3193 case OR_Deleted: 3194 // No conversion here! We're done. 3195 return OR_Deleted; 3196 3197 case OR_Ambiguous: 3198 return OR_Ambiguous; 3199 } 3200 3201 llvm_unreachable("Invalid OverloadResult!"); 3202 } 3203 3204 bool 3205 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3206 ImplicitConversionSequence ICS; 3207 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3208 OverloadCandidateSet::CSK_Normal); 3209 OverloadingResult OvResult = 3210 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3211 CandidateSet, false, false); 3212 if (OvResult == OR_Ambiguous) 3213 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3214 << From->getType() << ToType << From->getSourceRange(); 3215 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3216 if (!RequireCompleteType(From->getLocStart(), ToType, 3217 diag::err_typecheck_nonviable_condition_incomplete, 3218 From->getType(), From->getSourceRange())) 3219 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3220 << From->getType() << From->getSourceRange() << ToType; 3221 } else 3222 return false; 3223 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3224 return true; 3225 } 3226 3227 /// \brief Compare the user-defined conversion functions or constructors 3228 /// of two user-defined conversion sequences to determine whether any ordering 3229 /// is possible. 3230 static ImplicitConversionSequence::CompareKind 3231 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3232 FunctionDecl *Function2) { 3233 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3234 return ImplicitConversionSequence::Indistinguishable; 3235 3236 // Objective-C++: 3237 // If both conversion functions are implicitly-declared conversions from 3238 // a lambda closure type to a function pointer and a block pointer, 3239 // respectively, always prefer the conversion to a function pointer, 3240 // because the function pointer is more lightweight and is more likely 3241 // to keep code working. 3242 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3243 if (!Conv1) 3244 return ImplicitConversionSequence::Indistinguishable; 3245 3246 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3247 if (!Conv2) 3248 return ImplicitConversionSequence::Indistinguishable; 3249 3250 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3251 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3252 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3253 if (Block1 != Block2) 3254 return Block1 ? ImplicitConversionSequence::Worse 3255 : ImplicitConversionSequence::Better; 3256 } 3257 3258 return ImplicitConversionSequence::Indistinguishable; 3259 } 3260 3261 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3262 const ImplicitConversionSequence &ICS) { 3263 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3264 (ICS.isUserDefined() && 3265 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3266 } 3267 3268 /// CompareImplicitConversionSequences - Compare two implicit 3269 /// conversion sequences to determine whether one is better than the 3270 /// other or if they are indistinguishable (C++ 13.3.3.2). 3271 static ImplicitConversionSequence::CompareKind 3272 CompareImplicitConversionSequences(Sema &S, 3273 const ImplicitConversionSequence& ICS1, 3274 const ImplicitConversionSequence& ICS2) 3275 { 3276 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3277 // conversion sequences (as defined in 13.3.3.1) 3278 // -- a standard conversion sequence (13.3.3.1.1) is a better 3279 // conversion sequence than a user-defined conversion sequence or 3280 // an ellipsis conversion sequence, and 3281 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3282 // conversion sequence than an ellipsis conversion sequence 3283 // (13.3.3.1.3). 3284 // 3285 // C++0x [over.best.ics]p10: 3286 // For the purpose of ranking implicit conversion sequences as 3287 // described in 13.3.3.2, the ambiguous conversion sequence is 3288 // treated as a user-defined sequence that is indistinguishable 3289 // from any other user-defined conversion sequence. 3290 3291 // String literal to 'char *' conversion has been deprecated in C++03. It has 3292 // been removed from C++11. We still accept this conversion, if it happens at 3293 // the best viable function. Otherwise, this conversion is considered worse 3294 // than ellipsis conversion. Consider this as an extension; this is not in the 3295 // standard. For example: 3296 // 3297 // int &f(...); // #1 3298 // void f(char*); // #2 3299 // void g() { int &r = f("foo"); } 3300 // 3301 // In C++03, we pick #2 as the best viable function. 3302 // In C++11, we pick #1 as the best viable function, because ellipsis 3303 // conversion is better than string-literal to char* conversion (since there 3304 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3305 // convert arguments, #2 would be the best viable function in C++11. 3306 // If the best viable function has this conversion, a warning will be issued 3307 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3308 3309 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3310 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3311 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3312 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3313 ? ImplicitConversionSequence::Worse 3314 : ImplicitConversionSequence::Better; 3315 3316 if (ICS1.getKindRank() < ICS2.getKindRank()) 3317 return ImplicitConversionSequence::Better; 3318 if (ICS2.getKindRank() < ICS1.getKindRank()) 3319 return ImplicitConversionSequence::Worse; 3320 3321 // The following checks require both conversion sequences to be of 3322 // the same kind. 3323 if (ICS1.getKind() != ICS2.getKind()) 3324 return ImplicitConversionSequence::Indistinguishable; 3325 3326 ImplicitConversionSequence::CompareKind Result = 3327 ImplicitConversionSequence::Indistinguishable; 3328 3329 // Two implicit conversion sequences of the same form are 3330 // indistinguishable conversion sequences unless one of the 3331 // following rules apply: (C++ 13.3.3.2p3): 3332 if (ICS1.isStandard()) 3333 Result = CompareStandardConversionSequences(S, 3334 ICS1.Standard, ICS2.Standard); 3335 else if (ICS1.isUserDefined()) { 3336 // User-defined conversion sequence U1 is a better conversion 3337 // sequence than another user-defined conversion sequence U2 if 3338 // they contain the same user-defined conversion function or 3339 // constructor and if the second standard conversion sequence of 3340 // U1 is better than the second standard conversion sequence of 3341 // U2 (C++ 13.3.3.2p3). 3342 if (ICS1.UserDefined.ConversionFunction == 3343 ICS2.UserDefined.ConversionFunction) 3344 Result = CompareStandardConversionSequences(S, 3345 ICS1.UserDefined.After, 3346 ICS2.UserDefined.After); 3347 else 3348 Result = compareConversionFunctions(S, 3349 ICS1.UserDefined.ConversionFunction, 3350 ICS2.UserDefined.ConversionFunction); 3351 } 3352 3353 // List-initialization sequence L1 is a better conversion sequence than 3354 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3355 // for some X and L2 does not. 3356 if (Result == ImplicitConversionSequence::Indistinguishable && 3357 !ICS1.isBad()) { 3358 if (ICS1.isStdInitializerListElement() && 3359 !ICS2.isStdInitializerListElement()) 3360 return ImplicitConversionSequence::Better; 3361 if (!ICS1.isStdInitializerListElement() && 3362 ICS2.isStdInitializerListElement()) 3363 return ImplicitConversionSequence::Worse; 3364 } 3365 3366 return Result; 3367 } 3368 3369 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3370 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3371 Qualifiers Quals; 3372 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3373 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3374 } 3375 3376 return Context.hasSameUnqualifiedType(T1, T2); 3377 } 3378 3379 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3380 // determine if one is a proper subset of the other. 3381 static ImplicitConversionSequence::CompareKind 3382 compareStandardConversionSubsets(ASTContext &Context, 3383 const StandardConversionSequence& SCS1, 3384 const StandardConversionSequence& SCS2) { 3385 ImplicitConversionSequence::CompareKind Result 3386 = ImplicitConversionSequence::Indistinguishable; 3387 3388 // the identity conversion sequence is considered to be a subsequence of 3389 // any non-identity conversion sequence 3390 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3391 return ImplicitConversionSequence::Better; 3392 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3393 return ImplicitConversionSequence::Worse; 3394 3395 if (SCS1.Second != SCS2.Second) { 3396 if (SCS1.Second == ICK_Identity) 3397 Result = ImplicitConversionSequence::Better; 3398 else if (SCS2.Second == ICK_Identity) 3399 Result = ImplicitConversionSequence::Worse; 3400 else 3401 return ImplicitConversionSequence::Indistinguishable; 3402 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3403 return ImplicitConversionSequence::Indistinguishable; 3404 3405 if (SCS1.Third == SCS2.Third) { 3406 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3407 : ImplicitConversionSequence::Indistinguishable; 3408 } 3409 3410 if (SCS1.Third == ICK_Identity) 3411 return Result == ImplicitConversionSequence::Worse 3412 ? ImplicitConversionSequence::Indistinguishable 3413 : ImplicitConversionSequence::Better; 3414 3415 if (SCS2.Third == ICK_Identity) 3416 return Result == ImplicitConversionSequence::Better 3417 ? ImplicitConversionSequence::Indistinguishable 3418 : ImplicitConversionSequence::Worse; 3419 3420 return ImplicitConversionSequence::Indistinguishable; 3421 } 3422 3423 /// \brief Determine whether one of the given reference bindings is better 3424 /// than the other based on what kind of bindings they are. 3425 static bool 3426 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3427 const StandardConversionSequence &SCS2) { 3428 // C++0x [over.ics.rank]p3b4: 3429 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3430 // implicit object parameter of a non-static member function declared 3431 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3432 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3433 // lvalue reference to a function lvalue and S2 binds an rvalue 3434 // reference*. 3435 // 3436 // FIXME: Rvalue references. We're going rogue with the above edits, 3437 // because the semantics in the current C++0x working paper (N3225 at the 3438 // time of this writing) break the standard definition of std::forward 3439 // and std::reference_wrapper when dealing with references to functions. 3440 // Proposed wording changes submitted to CWG for consideration. 3441 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3442 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3443 return false; 3444 3445 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3446 SCS2.IsLvalueReference) || 3447 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3448 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3449 } 3450 3451 /// CompareStandardConversionSequences - Compare two standard 3452 /// conversion sequences to determine whether one is better than the 3453 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3454 static ImplicitConversionSequence::CompareKind 3455 CompareStandardConversionSequences(Sema &S, 3456 const StandardConversionSequence& SCS1, 3457 const StandardConversionSequence& SCS2) 3458 { 3459 // Standard conversion sequence S1 is a better conversion sequence 3460 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3461 3462 // -- S1 is a proper subsequence of S2 (comparing the conversion 3463 // sequences in the canonical form defined by 13.3.3.1.1, 3464 // excluding any Lvalue Transformation; the identity conversion 3465 // sequence is considered to be a subsequence of any 3466 // non-identity conversion sequence) or, if not that, 3467 if (ImplicitConversionSequence::CompareKind CK 3468 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3469 return CK; 3470 3471 // -- the rank of S1 is better than the rank of S2 (by the rules 3472 // defined below), or, if not that, 3473 ImplicitConversionRank Rank1 = SCS1.getRank(); 3474 ImplicitConversionRank Rank2 = SCS2.getRank(); 3475 if (Rank1 < Rank2) 3476 return ImplicitConversionSequence::Better; 3477 else if (Rank2 < Rank1) 3478 return ImplicitConversionSequence::Worse; 3479 3480 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3481 // are indistinguishable unless one of the following rules 3482 // applies: 3483 3484 // A conversion that is not a conversion of a pointer, or 3485 // pointer to member, to bool is better than another conversion 3486 // that is such a conversion. 3487 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3488 return SCS2.isPointerConversionToBool() 3489 ? ImplicitConversionSequence::Better 3490 : ImplicitConversionSequence::Worse; 3491 3492 // C++ [over.ics.rank]p4b2: 3493 // 3494 // If class B is derived directly or indirectly from class A, 3495 // conversion of B* to A* is better than conversion of B* to 3496 // void*, and conversion of A* to void* is better than conversion 3497 // of B* to void*. 3498 bool SCS1ConvertsToVoid 3499 = SCS1.isPointerConversionToVoidPointer(S.Context); 3500 bool SCS2ConvertsToVoid 3501 = SCS2.isPointerConversionToVoidPointer(S.Context); 3502 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3503 // Exactly one of the conversion sequences is a conversion to 3504 // a void pointer; it's the worse conversion. 3505 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3506 : ImplicitConversionSequence::Worse; 3507 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3508 // Neither conversion sequence converts to a void pointer; compare 3509 // their derived-to-base conversions. 3510 if (ImplicitConversionSequence::CompareKind DerivedCK 3511 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3512 return DerivedCK; 3513 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3514 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3515 // Both conversion sequences are conversions to void 3516 // pointers. Compare the source types to determine if there's an 3517 // inheritance relationship in their sources. 3518 QualType FromType1 = SCS1.getFromType(); 3519 QualType FromType2 = SCS2.getFromType(); 3520 3521 // Adjust the types we're converting from via the array-to-pointer 3522 // conversion, if we need to. 3523 if (SCS1.First == ICK_Array_To_Pointer) 3524 FromType1 = S.Context.getArrayDecayedType(FromType1); 3525 if (SCS2.First == ICK_Array_To_Pointer) 3526 FromType2 = S.Context.getArrayDecayedType(FromType2); 3527 3528 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3529 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3530 3531 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3532 return ImplicitConversionSequence::Better; 3533 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3534 return ImplicitConversionSequence::Worse; 3535 3536 // Objective-C++: If one interface is more specific than the 3537 // other, it is the better one. 3538 const ObjCObjectPointerType* FromObjCPtr1 3539 = FromType1->getAs<ObjCObjectPointerType>(); 3540 const ObjCObjectPointerType* FromObjCPtr2 3541 = FromType2->getAs<ObjCObjectPointerType>(); 3542 if (FromObjCPtr1 && FromObjCPtr2) { 3543 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3544 FromObjCPtr2); 3545 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3546 FromObjCPtr1); 3547 if (AssignLeft != AssignRight) { 3548 return AssignLeft? ImplicitConversionSequence::Better 3549 : ImplicitConversionSequence::Worse; 3550 } 3551 } 3552 } 3553 3554 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3555 // bullet 3). 3556 if (ImplicitConversionSequence::CompareKind QualCK 3557 = CompareQualificationConversions(S, SCS1, SCS2)) 3558 return QualCK; 3559 3560 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3561 // Check for a better reference binding based on the kind of bindings. 3562 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3563 return ImplicitConversionSequence::Better; 3564 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3565 return ImplicitConversionSequence::Worse; 3566 3567 // C++ [over.ics.rank]p3b4: 3568 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3569 // which the references refer are the same type except for 3570 // top-level cv-qualifiers, and the type to which the reference 3571 // initialized by S2 refers is more cv-qualified than the type 3572 // to which the reference initialized by S1 refers. 3573 QualType T1 = SCS1.getToType(2); 3574 QualType T2 = SCS2.getToType(2); 3575 T1 = S.Context.getCanonicalType(T1); 3576 T2 = S.Context.getCanonicalType(T2); 3577 Qualifiers T1Quals, T2Quals; 3578 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3579 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3580 if (UnqualT1 == UnqualT2) { 3581 // Objective-C++ ARC: If the references refer to objects with different 3582 // lifetimes, prefer bindings that don't change lifetime. 3583 if (SCS1.ObjCLifetimeConversionBinding != 3584 SCS2.ObjCLifetimeConversionBinding) { 3585 return SCS1.ObjCLifetimeConversionBinding 3586 ? ImplicitConversionSequence::Worse 3587 : ImplicitConversionSequence::Better; 3588 } 3589 3590 // If the type is an array type, promote the element qualifiers to the 3591 // type for comparison. 3592 if (isa<ArrayType>(T1) && T1Quals) 3593 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3594 if (isa<ArrayType>(T2) && T2Quals) 3595 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3596 if (T2.isMoreQualifiedThan(T1)) 3597 return ImplicitConversionSequence::Better; 3598 else if (T1.isMoreQualifiedThan(T2)) 3599 return ImplicitConversionSequence::Worse; 3600 } 3601 } 3602 3603 // In Microsoft mode, prefer an integral conversion to a 3604 // floating-to-integral conversion if the integral conversion 3605 // is between types of the same size. 3606 // For example: 3607 // void f(float); 3608 // void f(int); 3609 // int main { 3610 // long a; 3611 // f(a); 3612 // } 3613 // Here, MSVC will call f(int) instead of generating a compile error 3614 // as clang will do in standard mode. 3615 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3616 SCS2.Second == ICK_Floating_Integral && 3617 S.Context.getTypeSize(SCS1.getFromType()) == 3618 S.Context.getTypeSize(SCS1.getToType(2))) 3619 return ImplicitConversionSequence::Better; 3620 3621 return ImplicitConversionSequence::Indistinguishable; 3622 } 3623 3624 /// CompareQualificationConversions - Compares two standard conversion 3625 /// sequences to determine whether they can be ranked based on their 3626 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3627 static ImplicitConversionSequence::CompareKind 3628 CompareQualificationConversions(Sema &S, 3629 const StandardConversionSequence& SCS1, 3630 const StandardConversionSequence& SCS2) { 3631 // C++ 13.3.3.2p3: 3632 // -- S1 and S2 differ only in their qualification conversion and 3633 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3634 // cv-qualification signature of type T1 is a proper subset of 3635 // the cv-qualification signature of type T2, and S1 is not the 3636 // deprecated string literal array-to-pointer conversion (4.2). 3637 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3638 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3639 return ImplicitConversionSequence::Indistinguishable; 3640 3641 // FIXME: the example in the standard doesn't use a qualification 3642 // conversion (!) 3643 QualType T1 = SCS1.getToType(2); 3644 QualType T2 = SCS2.getToType(2); 3645 T1 = S.Context.getCanonicalType(T1); 3646 T2 = S.Context.getCanonicalType(T2); 3647 Qualifiers T1Quals, T2Quals; 3648 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3649 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3650 3651 // If the types are the same, we won't learn anything by unwrapped 3652 // them. 3653 if (UnqualT1 == UnqualT2) 3654 return ImplicitConversionSequence::Indistinguishable; 3655 3656 // If the type is an array type, promote the element qualifiers to the type 3657 // for comparison. 3658 if (isa<ArrayType>(T1) && T1Quals) 3659 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3660 if (isa<ArrayType>(T2) && T2Quals) 3661 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3662 3663 ImplicitConversionSequence::CompareKind Result 3664 = ImplicitConversionSequence::Indistinguishable; 3665 3666 // Objective-C++ ARC: 3667 // Prefer qualification conversions not involving a change in lifetime 3668 // to qualification conversions that do not change lifetime. 3669 if (SCS1.QualificationIncludesObjCLifetime != 3670 SCS2.QualificationIncludesObjCLifetime) { 3671 Result = SCS1.QualificationIncludesObjCLifetime 3672 ? ImplicitConversionSequence::Worse 3673 : ImplicitConversionSequence::Better; 3674 } 3675 3676 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3677 // Within each iteration of the loop, we check the qualifiers to 3678 // determine if this still looks like a qualification 3679 // conversion. Then, if all is well, we unwrap one more level of 3680 // pointers or pointers-to-members and do it all again 3681 // until there are no more pointers or pointers-to-members left 3682 // to unwrap. This essentially mimics what 3683 // IsQualificationConversion does, but here we're checking for a 3684 // strict subset of qualifiers. 3685 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3686 // The qualifiers are the same, so this doesn't tell us anything 3687 // about how the sequences rank. 3688 ; 3689 else if (T2.isMoreQualifiedThan(T1)) { 3690 // T1 has fewer qualifiers, so it could be the better sequence. 3691 if (Result == ImplicitConversionSequence::Worse) 3692 // Neither has qualifiers that are a subset of the other's 3693 // qualifiers. 3694 return ImplicitConversionSequence::Indistinguishable; 3695 3696 Result = ImplicitConversionSequence::Better; 3697 } else if (T1.isMoreQualifiedThan(T2)) { 3698 // T2 has fewer qualifiers, so it could be the better sequence. 3699 if (Result == ImplicitConversionSequence::Better) 3700 // Neither has qualifiers that are a subset of the other's 3701 // qualifiers. 3702 return ImplicitConversionSequence::Indistinguishable; 3703 3704 Result = ImplicitConversionSequence::Worse; 3705 } else { 3706 // Qualifiers are disjoint. 3707 return ImplicitConversionSequence::Indistinguishable; 3708 } 3709 3710 // If the types after this point are equivalent, we're done. 3711 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3712 break; 3713 } 3714 3715 // Check that the winning standard conversion sequence isn't using 3716 // the deprecated string literal array to pointer conversion. 3717 switch (Result) { 3718 case ImplicitConversionSequence::Better: 3719 if (SCS1.DeprecatedStringLiteralToCharPtr) 3720 Result = ImplicitConversionSequence::Indistinguishable; 3721 break; 3722 3723 case ImplicitConversionSequence::Indistinguishable: 3724 break; 3725 3726 case ImplicitConversionSequence::Worse: 3727 if (SCS2.DeprecatedStringLiteralToCharPtr) 3728 Result = ImplicitConversionSequence::Indistinguishable; 3729 break; 3730 } 3731 3732 return Result; 3733 } 3734 3735 /// CompareDerivedToBaseConversions - Compares two standard conversion 3736 /// sequences to determine whether they can be ranked based on their 3737 /// various kinds of derived-to-base conversions (C++ 3738 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3739 /// conversions between Objective-C interface types. 3740 static ImplicitConversionSequence::CompareKind 3741 CompareDerivedToBaseConversions(Sema &S, 3742 const StandardConversionSequence& SCS1, 3743 const StandardConversionSequence& SCS2) { 3744 QualType FromType1 = SCS1.getFromType(); 3745 QualType ToType1 = SCS1.getToType(1); 3746 QualType FromType2 = SCS2.getFromType(); 3747 QualType ToType2 = SCS2.getToType(1); 3748 3749 // Adjust the types we're converting from via the array-to-pointer 3750 // conversion, if we need to. 3751 if (SCS1.First == ICK_Array_To_Pointer) 3752 FromType1 = S.Context.getArrayDecayedType(FromType1); 3753 if (SCS2.First == ICK_Array_To_Pointer) 3754 FromType2 = S.Context.getArrayDecayedType(FromType2); 3755 3756 // Canonicalize all of the types. 3757 FromType1 = S.Context.getCanonicalType(FromType1); 3758 ToType1 = S.Context.getCanonicalType(ToType1); 3759 FromType2 = S.Context.getCanonicalType(FromType2); 3760 ToType2 = S.Context.getCanonicalType(ToType2); 3761 3762 // C++ [over.ics.rank]p4b3: 3763 // 3764 // If class B is derived directly or indirectly from class A and 3765 // class C is derived directly or indirectly from B, 3766 // 3767 // Compare based on pointer conversions. 3768 if (SCS1.Second == ICK_Pointer_Conversion && 3769 SCS2.Second == ICK_Pointer_Conversion && 3770 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3771 FromType1->isPointerType() && FromType2->isPointerType() && 3772 ToType1->isPointerType() && ToType2->isPointerType()) { 3773 QualType FromPointee1 3774 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3775 QualType ToPointee1 3776 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3777 QualType FromPointee2 3778 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3779 QualType ToPointee2 3780 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3781 3782 // -- conversion of C* to B* is better than conversion of C* to A*, 3783 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3784 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3785 return ImplicitConversionSequence::Better; 3786 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3787 return ImplicitConversionSequence::Worse; 3788 } 3789 3790 // -- conversion of B* to A* is better than conversion of C* to A*, 3791 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3792 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3793 return ImplicitConversionSequence::Better; 3794 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3795 return ImplicitConversionSequence::Worse; 3796 } 3797 } else if (SCS1.Second == ICK_Pointer_Conversion && 3798 SCS2.Second == ICK_Pointer_Conversion) { 3799 const ObjCObjectPointerType *FromPtr1 3800 = FromType1->getAs<ObjCObjectPointerType>(); 3801 const ObjCObjectPointerType *FromPtr2 3802 = FromType2->getAs<ObjCObjectPointerType>(); 3803 const ObjCObjectPointerType *ToPtr1 3804 = ToType1->getAs<ObjCObjectPointerType>(); 3805 const ObjCObjectPointerType *ToPtr2 3806 = ToType2->getAs<ObjCObjectPointerType>(); 3807 3808 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3809 // Apply the same conversion ranking rules for Objective-C pointer types 3810 // that we do for C++ pointers to class types. However, we employ the 3811 // Objective-C pseudo-subtyping relationship used for assignment of 3812 // Objective-C pointer types. 3813 bool FromAssignLeft 3814 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3815 bool FromAssignRight 3816 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3817 bool ToAssignLeft 3818 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3819 bool ToAssignRight 3820 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3821 3822 // A conversion to an a non-id object pointer type or qualified 'id' 3823 // type is better than a conversion to 'id'. 3824 if (ToPtr1->isObjCIdType() && 3825 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3826 return ImplicitConversionSequence::Worse; 3827 if (ToPtr2->isObjCIdType() && 3828 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3829 return ImplicitConversionSequence::Better; 3830 3831 // A conversion to a non-id object pointer type is better than a 3832 // conversion to a qualified 'id' type 3833 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3834 return ImplicitConversionSequence::Worse; 3835 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3836 return ImplicitConversionSequence::Better; 3837 3838 // A conversion to an a non-Class object pointer type or qualified 'Class' 3839 // type is better than a conversion to 'Class'. 3840 if (ToPtr1->isObjCClassType() && 3841 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3842 return ImplicitConversionSequence::Worse; 3843 if (ToPtr2->isObjCClassType() && 3844 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3845 return ImplicitConversionSequence::Better; 3846 3847 // A conversion to a non-Class object pointer type is better than a 3848 // conversion to a qualified 'Class' type. 3849 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3850 return ImplicitConversionSequence::Worse; 3851 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3852 return ImplicitConversionSequence::Better; 3853 3854 // -- "conversion of C* to B* is better than conversion of C* to A*," 3855 if (S.Context.hasSameType(FromType1, FromType2) && 3856 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3857 (ToAssignLeft != ToAssignRight)) 3858 return ToAssignLeft? ImplicitConversionSequence::Worse 3859 : ImplicitConversionSequence::Better; 3860 3861 // -- "conversion of B* to A* is better than conversion of C* to A*," 3862 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3863 (FromAssignLeft != FromAssignRight)) 3864 return FromAssignLeft? ImplicitConversionSequence::Better 3865 : ImplicitConversionSequence::Worse; 3866 } 3867 } 3868 3869 // Ranking of member-pointer types. 3870 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3871 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3872 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3873 const MemberPointerType * FromMemPointer1 = 3874 FromType1->getAs<MemberPointerType>(); 3875 const MemberPointerType * ToMemPointer1 = 3876 ToType1->getAs<MemberPointerType>(); 3877 const MemberPointerType * FromMemPointer2 = 3878 FromType2->getAs<MemberPointerType>(); 3879 const MemberPointerType * ToMemPointer2 = 3880 ToType2->getAs<MemberPointerType>(); 3881 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3882 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3883 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3884 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3885 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3886 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3887 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3888 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3889 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3890 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3891 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3892 return ImplicitConversionSequence::Worse; 3893 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3894 return ImplicitConversionSequence::Better; 3895 } 3896 // conversion of B::* to C::* is better than conversion of A::* to C::* 3897 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3898 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3899 return ImplicitConversionSequence::Better; 3900 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3901 return ImplicitConversionSequence::Worse; 3902 } 3903 } 3904 3905 if (SCS1.Second == ICK_Derived_To_Base) { 3906 // -- conversion of C to B is better than conversion of C to A, 3907 // -- binding of an expression of type C to a reference of type 3908 // B& is better than binding an expression of type C to a 3909 // reference of type A&, 3910 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3911 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3912 if (S.IsDerivedFrom(ToType1, ToType2)) 3913 return ImplicitConversionSequence::Better; 3914 else if (S.IsDerivedFrom(ToType2, ToType1)) 3915 return ImplicitConversionSequence::Worse; 3916 } 3917 3918 // -- conversion of B to A is better than conversion of C to A. 3919 // -- binding of an expression of type B to a reference of type 3920 // A& is better than binding an expression of type C to a 3921 // reference of type A&, 3922 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3923 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3924 if (S.IsDerivedFrom(FromType2, FromType1)) 3925 return ImplicitConversionSequence::Better; 3926 else if (S.IsDerivedFrom(FromType1, FromType2)) 3927 return ImplicitConversionSequence::Worse; 3928 } 3929 } 3930 3931 return ImplicitConversionSequence::Indistinguishable; 3932 } 3933 3934 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3935 /// C++ class. 3936 static bool isTypeValid(QualType T) { 3937 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3938 return !Record->isInvalidDecl(); 3939 3940 return true; 3941 } 3942 3943 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3944 /// determine whether they are reference-related, 3945 /// reference-compatible, reference-compatible with added 3946 /// qualification, or incompatible, for use in C++ initialization by 3947 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3948 /// type, and the first type (T1) is the pointee type of the reference 3949 /// type being initialized. 3950 Sema::ReferenceCompareResult 3951 Sema::CompareReferenceRelationship(SourceLocation Loc, 3952 QualType OrigT1, QualType OrigT2, 3953 bool &DerivedToBase, 3954 bool &ObjCConversion, 3955 bool &ObjCLifetimeConversion) { 3956 assert(!OrigT1->isReferenceType() && 3957 "T1 must be the pointee type of the reference type"); 3958 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3959 3960 QualType T1 = Context.getCanonicalType(OrigT1); 3961 QualType T2 = Context.getCanonicalType(OrigT2); 3962 Qualifiers T1Quals, T2Quals; 3963 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3964 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3965 3966 // C++ [dcl.init.ref]p4: 3967 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3968 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3969 // T1 is a base class of T2. 3970 DerivedToBase = false; 3971 ObjCConversion = false; 3972 ObjCLifetimeConversion = false; 3973 if (UnqualT1 == UnqualT2) { 3974 // Nothing to do. 3975 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3976 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3977 IsDerivedFrom(UnqualT2, UnqualT1)) 3978 DerivedToBase = true; 3979 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3980 UnqualT2->isObjCObjectOrInterfaceType() && 3981 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3982 ObjCConversion = true; 3983 else 3984 return Ref_Incompatible; 3985 3986 // At this point, we know that T1 and T2 are reference-related (at 3987 // least). 3988 3989 // If the type is an array type, promote the element qualifiers to the type 3990 // for comparison. 3991 if (isa<ArrayType>(T1) && T1Quals) 3992 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3993 if (isa<ArrayType>(T2) && T2Quals) 3994 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3995 3996 // C++ [dcl.init.ref]p4: 3997 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3998 // reference-related to T2 and cv1 is the same cv-qualification 3999 // as, or greater cv-qualification than, cv2. For purposes of 4000 // overload resolution, cases for which cv1 is greater 4001 // cv-qualification than cv2 are identified as 4002 // reference-compatible with added qualification (see 13.3.3.2). 4003 // 4004 // Note that we also require equivalence of Objective-C GC and address-space 4005 // qualifiers when performing these computations, so that e.g., an int in 4006 // address space 1 is not reference-compatible with an int in address 4007 // space 2. 4008 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4009 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4010 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4011 ObjCLifetimeConversion = true; 4012 4013 T1Quals.removeObjCLifetime(); 4014 T2Quals.removeObjCLifetime(); 4015 } 4016 4017 if (T1Quals == T2Quals) 4018 return Ref_Compatible; 4019 else if (T1Quals.compatiblyIncludes(T2Quals)) 4020 return Ref_Compatible_With_Added_Qualification; 4021 else 4022 return Ref_Related; 4023 } 4024 4025 /// \brief Look for a user-defined conversion to an value reference-compatible 4026 /// with DeclType. Return true if something definite is found. 4027 static bool 4028 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4029 QualType DeclType, SourceLocation DeclLoc, 4030 Expr *Init, QualType T2, bool AllowRvalues, 4031 bool AllowExplicit) { 4032 assert(T2->isRecordType() && "Can only find conversions of record types."); 4033 CXXRecordDecl *T2RecordDecl 4034 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4035 4036 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4037 std::pair<CXXRecordDecl::conversion_iterator, 4038 CXXRecordDecl::conversion_iterator> 4039 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4040 for (CXXRecordDecl::conversion_iterator 4041 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4042 NamedDecl *D = *I; 4043 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4044 if (isa<UsingShadowDecl>(D)) 4045 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4046 4047 FunctionTemplateDecl *ConvTemplate 4048 = dyn_cast<FunctionTemplateDecl>(D); 4049 CXXConversionDecl *Conv; 4050 if (ConvTemplate) 4051 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4052 else 4053 Conv = cast<CXXConversionDecl>(D); 4054 4055 // If this is an explicit conversion, and we're not allowed to consider 4056 // explicit conversions, skip it. 4057 if (!AllowExplicit && Conv->isExplicit()) 4058 continue; 4059 4060 if (AllowRvalues) { 4061 bool DerivedToBase = false; 4062 bool ObjCConversion = false; 4063 bool ObjCLifetimeConversion = false; 4064 4065 // If we are initializing an rvalue reference, don't permit conversion 4066 // functions that return lvalues. 4067 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4068 const ReferenceType *RefType 4069 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4070 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4071 continue; 4072 } 4073 4074 if (!ConvTemplate && 4075 S.CompareReferenceRelationship( 4076 DeclLoc, 4077 Conv->getConversionType().getNonReferenceType() 4078 .getUnqualifiedType(), 4079 DeclType.getNonReferenceType().getUnqualifiedType(), 4080 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4081 Sema::Ref_Incompatible) 4082 continue; 4083 } else { 4084 // If the conversion function doesn't return a reference type, 4085 // it can't be considered for this conversion. An rvalue reference 4086 // is only acceptable if its referencee is a function type. 4087 4088 const ReferenceType *RefType = 4089 Conv->getConversionType()->getAs<ReferenceType>(); 4090 if (!RefType || 4091 (!RefType->isLValueReferenceType() && 4092 !RefType->getPointeeType()->isFunctionType())) 4093 continue; 4094 } 4095 4096 if (ConvTemplate) 4097 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4098 Init, DeclType, CandidateSet, 4099 /*AllowObjCConversionOnExplicit=*/false); 4100 else 4101 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4102 DeclType, CandidateSet, 4103 /*AllowObjCConversionOnExplicit=*/false); 4104 } 4105 4106 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4107 4108 OverloadCandidateSet::iterator Best; 4109 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4110 case OR_Success: 4111 // C++ [over.ics.ref]p1: 4112 // 4113 // [...] If the parameter binds directly to the result of 4114 // applying a conversion function to the argument 4115 // expression, the implicit conversion sequence is a 4116 // user-defined conversion sequence (13.3.3.1.2), with the 4117 // second standard conversion sequence either an identity 4118 // conversion or, if the conversion function returns an 4119 // entity of a type that is a derived class of the parameter 4120 // type, a derived-to-base Conversion. 4121 if (!Best->FinalConversion.DirectBinding) 4122 return false; 4123 4124 ICS.setUserDefined(); 4125 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4126 ICS.UserDefined.After = Best->FinalConversion; 4127 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4128 ICS.UserDefined.ConversionFunction = Best->Function; 4129 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4130 ICS.UserDefined.EllipsisConversion = false; 4131 assert(ICS.UserDefined.After.ReferenceBinding && 4132 ICS.UserDefined.After.DirectBinding && 4133 "Expected a direct reference binding!"); 4134 return true; 4135 4136 case OR_Ambiguous: 4137 ICS.setAmbiguous(); 4138 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4139 Cand != CandidateSet.end(); ++Cand) 4140 if (Cand->Viable) 4141 ICS.Ambiguous.addConversion(Cand->Function); 4142 return true; 4143 4144 case OR_No_Viable_Function: 4145 case OR_Deleted: 4146 // There was no suitable conversion, or we found a deleted 4147 // conversion; continue with other checks. 4148 return false; 4149 } 4150 4151 llvm_unreachable("Invalid OverloadResult!"); 4152 } 4153 4154 /// \brief Compute an implicit conversion sequence for reference 4155 /// initialization. 4156 static ImplicitConversionSequence 4157 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4158 SourceLocation DeclLoc, 4159 bool SuppressUserConversions, 4160 bool AllowExplicit) { 4161 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4162 4163 // Most paths end in a failed conversion. 4164 ImplicitConversionSequence ICS; 4165 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4166 4167 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4168 QualType T2 = Init->getType(); 4169 4170 // If the initializer is the address of an overloaded function, try 4171 // to resolve the overloaded function. If all goes well, T2 is the 4172 // type of the resulting function. 4173 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4174 DeclAccessPair Found; 4175 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4176 false, Found)) 4177 T2 = Fn->getType(); 4178 } 4179 4180 // Compute some basic properties of the types and the initializer. 4181 bool isRValRef = DeclType->isRValueReferenceType(); 4182 bool DerivedToBase = false; 4183 bool ObjCConversion = false; 4184 bool ObjCLifetimeConversion = false; 4185 Expr::Classification InitCategory = Init->Classify(S.Context); 4186 Sema::ReferenceCompareResult RefRelationship 4187 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4188 ObjCConversion, ObjCLifetimeConversion); 4189 4190 4191 // C++0x [dcl.init.ref]p5: 4192 // A reference to type "cv1 T1" is initialized by an expression 4193 // of type "cv2 T2" as follows: 4194 4195 // -- If reference is an lvalue reference and the initializer expression 4196 if (!isRValRef) { 4197 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4198 // reference-compatible with "cv2 T2," or 4199 // 4200 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4201 if (InitCategory.isLValue() && 4202 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4203 // C++ [over.ics.ref]p1: 4204 // When a parameter of reference type binds directly (8.5.3) 4205 // to an argument expression, the implicit conversion sequence 4206 // is the identity conversion, unless the argument expression 4207 // has a type that is a derived class of the parameter type, 4208 // in which case the implicit conversion sequence is a 4209 // derived-to-base Conversion (13.3.3.1). 4210 ICS.setStandard(); 4211 ICS.Standard.First = ICK_Identity; 4212 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4213 : ObjCConversion? ICK_Compatible_Conversion 4214 : ICK_Identity; 4215 ICS.Standard.Third = ICK_Identity; 4216 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4217 ICS.Standard.setToType(0, T2); 4218 ICS.Standard.setToType(1, T1); 4219 ICS.Standard.setToType(2, T1); 4220 ICS.Standard.ReferenceBinding = true; 4221 ICS.Standard.DirectBinding = true; 4222 ICS.Standard.IsLvalueReference = !isRValRef; 4223 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4224 ICS.Standard.BindsToRvalue = false; 4225 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4226 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4227 ICS.Standard.CopyConstructor = nullptr; 4228 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4229 4230 // Nothing more to do: the inaccessibility/ambiguity check for 4231 // derived-to-base conversions is suppressed when we're 4232 // computing the implicit conversion sequence (C++ 4233 // [over.best.ics]p2). 4234 return ICS; 4235 } 4236 4237 // -- has a class type (i.e., T2 is a class type), where T1 is 4238 // not reference-related to T2, and can be implicitly 4239 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4240 // is reference-compatible with "cv3 T3" 92) (this 4241 // conversion is selected by enumerating the applicable 4242 // conversion functions (13.3.1.6) and choosing the best 4243 // one through overload resolution (13.3)), 4244 if (!SuppressUserConversions && T2->isRecordType() && 4245 !S.RequireCompleteType(DeclLoc, T2, 0) && 4246 RefRelationship == Sema::Ref_Incompatible) { 4247 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4248 Init, T2, /*AllowRvalues=*/false, 4249 AllowExplicit)) 4250 return ICS; 4251 } 4252 } 4253 4254 // -- Otherwise, the reference shall be an lvalue reference to a 4255 // non-volatile const type (i.e., cv1 shall be const), or the reference 4256 // shall be an rvalue reference. 4257 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4258 return ICS; 4259 4260 // -- If the initializer expression 4261 // 4262 // -- is an xvalue, class prvalue, array prvalue or function 4263 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4264 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4265 (InitCategory.isXValue() || 4266 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4267 (InitCategory.isLValue() && T2->isFunctionType()))) { 4268 ICS.setStandard(); 4269 ICS.Standard.First = ICK_Identity; 4270 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4271 : ObjCConversion? ICK_Compatible_Conversion 4272 : ICK_Identity; 4273 ICS.Standard.Third = ICK_Identity; 4274 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4275 ICS.Standard.setToType(0, T2); 4276 ICS.Standard.setToType(1, T1); 4277 ICS.Standard.setToType(2, T1); 4278 ICS.Standard.ReferenceBinding = true; 4279 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4280 // binding unless we're binding to a class prvalue. 4281 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4282 // allow the use of rvalue references in C++98/03 for the benefit of 4283 // standard library implementors; therefore, we need the xvalue check here. 4284 ICS.Standard.DirectBinding = 4285 S.getLangOpts().CPlusPlus11 || 4286 !(InitCategory.isPRValue() || T2->isRecordType()); 4287 ICS.Standard.IsLvalueReference = !isRValRef; 4288 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4289 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4290 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4291 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4292 ICS.Standard.CopyConstructor = nullptr; 4293 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4294 return ICS; 4295 } 4296 4297 // -- has a class type (i.e., T2 is a class type), where T1 is not 4298 // reference-related to T2, and can be implicitly converted to 4299 // an xvalue, class prvalue, or function lvalue of type 4300 // "cv3 T3", where "cv1 T1" is reference-compatible with 4301 // "cv3 T3", 4302 // 4303 // then the reference is bound to the value of the initializer 4304 // expression in the first case and to the result of the conversion 4305 // in the second case (or, in either case, to an appropriate base 4306 // class subobject). 4307 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4308 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4309 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4310 Init, T2, /*AllowRvalues=*/true, 4311 AllowExplicit)) { 4312 // In the second case, if the reference is an rvalue reference 4313 // and the second standard conversion sequence of the 4314 // user-defined conversion sequence includes an lvalue-to-rvalue 4315 // conversion, the program is ill-formed. 4316 if (ICS.isUserDefined() && isRValRef && 4317 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4318 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4319 4320 return ICS; 4321 } 4322 4323 // A temporary of function type cannot be created; don't even try. 4324 if (T1->isFunctionType()) 4325 return ICS; 4326 4327 // -- Otherwise, a temporary of type "cv1 T1" is created and 4328 // initialized from the initializer expression using the 4329 // rules for a non-reference copy initialization (8.5). The 4330 // reference is then bound to the temporary. If T1 is 4331 // reference-related to T2, cv1 must be the same 4332 // cv-qualification as, or greater cv-qualification than, 4333 // cv2; otherwise, the program is ill-formed. 4334 if (RefRelationship == Sema::Ref_Related) { 4335 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4336 // we would be reference-compatible or reference-compatible with 4337 // added qualification. But that wasn't the case, so the reference 4338 // initialization fails. 4339 // 4340 // Note that we only want to check address spaces and cvr-qualifiers here. 4341 // ObjC GC and lifetime qualifiers aren't important. 4342 Qualifiers T1Quals = T1.getQualifiers(); 4343 Qualifiers T2Quals = T2.getQualifiers(); 4344 T1Quals.removeObjCGCAttr(); 4345 T1Quals.removeObjCLifetime(); 4346 T2Quals.removeObjCGCAttr(); 4347 T2Quals.removeObjCLifetime(); 4348 if (!T1Quals.compatiblyIncludes(T2Quals)) 4349 return ICS; 4350 } 4351 4352 // If at least one of the types is a class type, the types are not 4353 // related, and we aren't allowed any user conversions, the 4354 // reference binding fails. This case is important for breaking 4355 // recursion, since TryImplicitConversion below will attempt to 4356 // create a temporary through the use of a copy constructor. 4357 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4358 (T1->isRecordType() || T2->isRecordType())) 4359 return ICS; 4360 4361 // If T1 is reference-related to T2 and the reference is an rvalue 4362 // reference, the initializer expression shall not be an lvalue. 4363 if (RefRelationship >= Sema::Ref_Related && 4364 isRValRef && Init->Classify(S.Context).isLValue()) 4365 return ICS; 4366 4367 // C++ [over.ics.ref]p2: 4368 // When a parameter of reference type is not bound directly to 4369 // an argument expression, the conversion sequence is the one 4370 // required to convert the argument expression to the 4371 // underlying type of the reference according to 4372 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4373 // to copy-initializing a temporary of the underlying type with 4374 // the argument expression. Any difference in top-level 4375 // cv-qualification is subsumed by the initialization itself 4376 // and does not constitute a conversion. 4377 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4378 /*AllowExplicit=*/false, 4379 /*InOverloadResolution=*/false, 4380 /*CStyle=*/false, 4381 /*AllowObjCWritebackConversion=*/false, 4382 /*AllowObjCConversionOnExplicit=*/false); 4383 4384 // Of course, that's still a reference binding. 4385 if (ICS.isStandard()) { 4386 ICS.Standard.ReferenceBinding = true; 4387 ICS.Standard.IsLvalueReference = !isRValRef; 4388 ICS.Standard.BindsToFunctionLvalue = false; 4389 ICS.Standard.BindsToRvalue = true; 4390 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4391 ICS.Standard.ObjCLifetimeConversionBinding = false; 4392 } else if (ICS.isUserDefined()) { 4393 const ReferenceType *LValRefType = 4394 ICS.UserDefined.ConversionFunction->getReturnType() 4395 ->getAs<LValueReferenceType>(); 4396 4397 // C++ [over.ics.ref]p3: 4398 // Except for an implicit object parameter, for which see 13.3.1, a 4399 // standard conversion sequence cannot be formed if it requires [...] 4400 // binding an rvalue reference to an lvalue other than a function 4401 // lvalue. 4402 // Note that the function case is not possible here. 4403 if (DeclType->isRValueReferenceType() && LValRefType) { 4404 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4405 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4406 // reference to an rvalue! 4407 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4408 return ICS; 4409 } 4410 4411 ICS.UserDefined.Before.setAsIdentityConversion(); 4412 ICS.UserDefined.After.ReferenceBinding = true; 4413 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4414 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4415 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4416 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4417 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4418 } 4419 4420 return ICS; 4421 } 4422 4423 static ImplicitConversionSequence 4424 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4425 bool SuppressUserConversions, 4426 bool InOverloadResolution, 4427 bool AllowObjCWritebackConversion, 4428 bool AllowExplicit = false); 4429 4430 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4431 /// initializer list From. 4432 static ImplicitConversionSequence 4433 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4434 bool SuppressUserConversions, 4435 bool InOverloadResolution, 4436 bool AllowObjCWritebackConversion) { 4437 // C++11 [over.ics.list]p1: 4438 // When an argument is an initializer list, it is not an expression and 4439 // special rules apply for converting it to a parameter type. 4440 4441 ImplicitConversionSequence Result; 4442 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4443 4444 // We need a complete type for what follows. Incomplete types can never be 4445 // initialized from init lists. 4446 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4447 return Result; 4448 4449 // C++11 [over.ics.list]p2: 4450 // If the parameter type is std::initializer_list<X> or "array of X" and 4451 // all the elements can be implicitly converted to X, the implicit 4452 // conversion sequence is the worst conversion necessary to convert an 4453 // element of the list to X. 4454 bool toStdInitializerList = false; 4455 QualType X; 4456 if (ToType->isArrayType()) 4457 X = S.Context.getAsArrayType(ToType)->getElementType(); 4458 else 4459 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4460 if (!X.isNull()) { 4461 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4462 Expr *Init = From->getInit(i); 4463 ImplicitConversionSequence ICS = 4464 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4465 InOverloadResolution, 4466 AllowObjCWritebackConversion); 4467 // If a single element isn't convertible, fail. 4468 if (ICS.isBad()) { 4469 Result = ICS; 4470 break; 4471 } 4472 // Otherwise, look for the worst conversion. 4473 if (Result.isBad() || 4474 CompareImplicitConversionSequences(S, ICS, Result) == 4475 ImplicitConversionSequence::Worse) 4476 Result = ICS; 4477 } 4478 4479 // For an empty list, we won't have computed any conversion sequence. 4480 // Introduce the identity conversion sequence. 4481 if (From->getNumInits() == 0) { 4482 Result.setStandard(); 4483 Result.Standard.setAsIdentityConversion(); 4484 Result.Standard.setFromType(ToType); 4485 Result.Standard.setAllToTypes(ToType); 4486 } 4487 4488 Result.setStdInitializerListElement(toStdInitializerList); 4489 return Result; 4490 } 4491 4492 // C++11 [over.ics.list]p3: 4493 // Otherwise, if the parameter is a non-aggregate class X and overload 4494 // resolution chooses a single best constructor [...] the implicit 4495 // conversion sequence is a user-defined conversion sequence. If multiple 4496 // constructors are viable but none is better than the others, the 4497 // implicit conversion sequence is a user-defined conversion sequence. 4498 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4499 // This function can deal with initializer lists. 4500 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4501 /*AllowExplicit=*/false, 4502 InOverloadResolution, /*CStyle=*/false, 4503 AllowObjCWritebackConversion, 4504 /*AllowObjCConversionOnExplicit=*/false); 4505 } 4506 4507 // C++11 [over.ics.list]p4: 4508 // Otherwise, if the parameter has an aggregate type which can be 4509 // initialized from the initializer list [...] the implicit conversion 4510 // sequence is a user-defined conversion sequence. 4511 if (ToType->isAggregateType()) { 4512 // Type is an aggregate, argument is an init list. At this point it comes 4513 // down to checking whether the initialization works. 4514 // FIXME: Find out whether this parameter is consumed or not. 4515 InitializedEntity Entity = 4516 InitializedEntity::InitializeParameter(S.Context, ToType, 4517 /*Consumed=*/false); 4518 if (S.CanPerformCopyInitialization(Entity, From)) { 4519 Result.setUserDefined(); 4520 Result.UserDefined.Before.setAsIdentityConversion(); 4521 // Initializer lists don't have a type. 4522 Result.UserDefined.Before.setFromType(QualType()); 4523 Result.UserDefined.Before.setAllToTypes(QualType()); 4524 4525 Result.UserDefined.After.setAsIdentityConversion(); 4526 Result.UserDefined.After.setFromType(ToType); 4527 Result.UserDefined.After.setAllToTypes(ToType); 4528 Result.UserDefined.ConversionFunction = nullptr; 4529 } 4530 return Result; 4531 } 4532 4533 // C++11 [over.ics.list]p5: 4534 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4535 if (ToType->isReferenceType()) { 4536 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4537 // mention initializer lists in any way. So we go by what list- 4538 // initialization would do and try to extrapolate from that. 4539 4540 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4541 4542 // If the initializer list has a single element that is reference-related 4543 // to the parameter type, we initialize the reference from that. 4544 if (From->getNumInits() == 1) { 4545 Expr *Init = From->getInit(0); 4546 4547 QualType T2 = Init->getType(); 4548 4549 // If the initializer is the address of an overloaded function, try 4550 // to resolve the overloaded function. If all goes well, T2 is the 4551 // type of the resulting function. 4552 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4553 DeclAccessPair Found; 4554 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4555 Init, ToType, false, Found)) 4556 T2 = Fn->getType(); 4557 } 4558 4559 // Compute some basic properties of the types and the initializer. 4560 bool dummy1 = false; 4561 bool dummy2 = false; 4562 bool dummy3 = false; 4563 Sema::ReferenceCompareResult RefRelationship 4564 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4565 dummy2, dummy3); 4566 4567 if (RefRelationship >= Sema::Ref_Related) { 4568 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4569 SuppressUserConversions, 4570 /*AllowExplicit=*/false); 4571 } 4572 } 4573 4574 // Otherwise, we bind the reference to a temporary created from the 4575 // initializer list. 4576 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4577 InOverloadResolution, 4578 AllowObjCWritebackConversion); 4579 if (Result.isFailure()) 4580 return Result; 4581 assert(!Result.isEllipsis() && 4582 "Sub-initialization cannot result in ellipsis conversion."); 4583 4584 // Can we even bind to a temporary? 4585 if (ToType->isRValueReferenceType() || 4586 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4587 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4588 Result.UserDefined.After; 4589 SCS.ReferenceBinding = true; 4590 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4591 SCS.BindsToRvalue = true; 4592 SCS.BindsToFunctionLvalue = false; 4593 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4594 SCS.ObjCLifetimeConversionBinding = false; 4595 } else 4596 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4597 From, ToType); 4598 return Result; 4599 } 4600 4601 // C++11 [over.ics.list]p6: 4602 // Otherwise, if the parameter type is not a class: 4603 if (!ToType->isRecordType()) { 4604 // - if the initializer list has one element, the implicit conversion 4605 // sequence is the one required to convert the element to the 4606 // parameter type. 4607 unsigned NumInits = From->getNumInits(); 4608 if (NumInits == 1) 4609 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4610 SuppressUserConversions, 4611 InOverloadResolution, 4612 AllowObjCWritebackConversion); 4613 // - if the initializer list has no elements, the implicit conversion 4614 // sequence is the identity conversion. 4615 else if (NumInits == 0) { 4616 Result.setStandard(); 4617 Result.Standard.setAsIdentityConversion(); 4618 Result.Standard.setFromType(ToType); 4619 Result.Standard.setAllToTypes(ToType); 4620 } 4621 return Result; 4622 } 4623 4624 // C++11 [over.ics.list]p7: 4625 // In all cases other than those enumerated above, no conversion is possible 4626 return Result; 4627 } 4628 4629 /// TryCopyInitialization - Try to copy-initialize a value of type 4630 /// ToType from the expression From. Return the implicit conversion 4631 /// sequence required to pass this argument, which may be a bad 4632 /// conversion sequence (meaning that the argument cannot be passed to 4633 /// a parameter of this type). If @p SuppressUserConversions, then we 4634 /// do not permit any user-defined conversion sequences. 4635 static ImplicitConversionSequence 4636 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4637 bool SuppressUserConversions, 4638 bool InOverloadResolution, 4639 bool AllowObjCWritebackConversion, 4640 bool AllowExplicit) { 4641 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4642 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4643 InOverloadResolution,AllowObjCWritebackConversion); 4644 4645 if (ToType->isReferenceType()) 4646 return TryReferenceInit(S, From, ToType, 4647 /*FIXME:*/From->getLocStart(), 4648 SuppressUserConversions, 4649 AllowExplicit); 4650 4651 return TryImplicitConversion(S, From, ToType, 4652 SuppressUserConversions, 4653 /*AllowExplicit=*/false, 4654 InOverloadResolution, 4655 /*CStyle=*/false, 4656 AllowObjCWritebackConversion, 4657 /*AllowObjCConversionOnExplicit=*/false); 4658 } 4659 4660 static bool TryCopyInitialization(const CanQualType FromQTy, 4661 const CanQualType ToQTy, 4662 Sema &S, 4663 SourceLocation Loc, 4664 ExprValueKind FromVK) { 4665 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4666 ImplicitConversionSequence ICS = 4667 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4668 4669 return !ICS.isBad(); 4670 } 4671 4672 /// TryObjectArgumentInitialization - Try to initialize the object 4673 /// parameter of the given member function (@c Method) from the 4674 /// expression @p From. 4675 static ImplicitConversionSequence 4676 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4677 Expr::Classification FromClassification, 4678 CXXMethodDecl *Method, 4679 CXXRecordDecl *ActingContext) { 4680 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4681 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4682 // const volatile object. 4683 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4684 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4685 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4686 4687 // Set up the conversion sequence as a "bad" conversion, to allow us 4688 // to exit early. 4689 ImplicitConversionSequence ICS; 4690 4691 // We need to have an object of class type. 4692 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4693 FromType = PT->getPointeeType(); 4694 4695 // When we had a pointer, it's implicitly dereferenced, so we 4696 // better have an lvalue. 4697 assert(FromClassification.isLValue()); 4698 } 4699 4700 assert(FromType->isRecordType()); 4701 4702 // C++0x [over.match.funcs]p4: 4703 // For non-static member functions, the type of the implicit object 4704 // parameter is 4705 // 4706 // - "lvalue reference to cv X" for functions declared without a 4707 // ref-qualifier or with the & ref-qualifier 4708 // - "rvalue reference to cv X" for functions declared with the && 4709 // ref-qualifier 4710 // 4711 // where X is the class of which the function is a member and cv is the 4712 // cv-qualification on the member function declaration. 4713 // 4714 // However, when finding an implicit conversion sequence for the argument, we 4715 // are not allowed to create temporaries or perform user-defined conversions 4716 // (C++ [over.match.funcs]p5). We perform a simplified version of 4717 // reference binding here, that allows class rvalues to bind to 4718 // non-constant references. 4719 4720 // First check the qualifiers. 4721 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4722 if (ImplicitParamType.getCVRQualifiers() 4723 != FromTypeCanon.getLocalCVRQualifiers() && 4724 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4725 ICS.setBad(BadConversionSequence::bad_qualifiers, 4726 FromType, ImplicitParamType); 4727 return ICS; 4728 } 4729 4730 // Check that we have either the same type or a derived type. It 4731 // affects the conversion rank. 4732 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4733 ImplicitConversionKind SecondKind; 4734 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4735 SecondKind = ICK_Identity; 4736 } else if (S.IsDerivedFrom(FromType, ClassType)) 4737 SecondKind = ICK_Derived_To_Base; 4738 else { 4739 ICS.setBad(BadConversionSequence::unrelated_class, 4740 FromType, ImplicitParamType); 4741 return ICS; 4742 } 4743 4744 // Check the ref-qualifier. 4745 switch (Method->getRefQualifier()) { 4746 case RQ_None: 4747 // Do nothing; we don't care about lvalueness or rvalueness. 4748 break; 4749 4750 case RQ_LValue: 4751 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4752 // non-const lvalue reference cannot bind to an rvalue 4753 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4754 ImplicitParamType); 4755 return ICS; 4756 } 4757 break; 4758 4759 case RQ_RValue: 4760 if (!FromClassification.isRValue()) { 4761 // rvalue reference cannot bind to an lvalue 4762 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4763 ImplicitParamType); 4764 return ICS; 4765 } 4766 break; 4767 } 4768 4769 // Success. Mark this as a reference binding. 4770 ICS.setStandard(); 4771 ICS.Standard.setAsIdentityConversion(); 4772 ICS.Standard.Second = SecondKind; 4773 ICS.Standard.setFromType(FromType); 4774 ICS.Standard.setAllToTypes(ImplicitParamType); 4775 ICS.Standard.ReferenceBinding = true; 4776 ICS.Standard.DirectBinding = true; 4777 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4778 ICS.Standard.BindsToFunctionLvalue = false; 4779 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4780 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4781 = (Method->getRefQualifier() == RQ_None); 4782 return ICS; 4783 } 4784 4785 /// PerformObjectArgumentInitialization - Perform initialization of 4786 /// the implicit object parameter for the given Method with the given 4787 /// expression. 4788 ExprResult 4789 Sema::PerformObjectArgumentInitialization(Expr *From, 4790 NestedNameSpecifier *Qualifier, 4791 NamedDecl *FoundDecl, 4792 CXXMethodDecl *Method) { 4793 QualType FromRecordType, DestType; 4794 QualType ImplicitParamRecordType = 4795 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4796 4797 Expr::Classification FromClassification; 4798 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4799 FromRecordType = PT->getPointeeType(); 4800 DestType = Method->getThisType(Context); 4801 FromClassification = Expr::Classification::makeSimpleLValue(); 4802 } else { 4803 FromRecordType = From->getType(); 4804 DestType = ImplicitParamRecordType; 4805 FromClassification = From->Classify(Context); 4806 } 4807 4808 // Note that we always use the true parent context when performing 4809 // the actual argument initialization. 4810 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4811 *this, From->getType(), FromClassification, Method, Method->getParent()); 4812 if (ICS.isBad()) { 4813 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4814 Qualifiers FromQs = FromRecordType.getQualifiers(); 4815 Qualifiers ToQs = DestType.getQualifiers(); 4816 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4817 if (CVR) { 4818 Diag(From->getLocStart(), 4819 diag::err_member_function_call_bad_cvr) 4820 << Method->getDeclName() << FromRecordType << (CVR - 1) 4821 << From->getSourceRange(); 4822 Diag(Method->getLocation(), diag::note_previous_decl) 4823 << Method->getDeclName(); 4824 return ExprError(); 4825 } 4826 } 4827 4828 return Diag(From->getLocStart(), 4829 diag::err_implicit_object_parameter_init) 4830 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4831 } 4832 4833 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4834 ExprResult FromRes = 4835 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4836 if (FromRes.isInvalid()) 4837 return ExprError(); 4838 From = FromRes.get(); 4839 } 4840 4841 if (!Context.hasSameType(From->getType(), DestType)) 4842 From = ImpCastExprToType(From, DestType, CK_NoOp, 4843 From->getValueKind()).get(); 4844 return From; 4845 } 4846 4847 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4848 /// expression From to bool (C++0x [conv]p3). 4849 static ImplicitConversionSequence 4850 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4851 return TryImplicitConversion(S, From, S.Context.BoolTy, 4852 /*SuppressUserConversions=*/false, 4853 /*AllowExplicit=*/true, 4854 /*InOverloadResolution=*/false, 4855 /*CStyle=*/false, 4856 /*AllowObjCWritebackConversion=*/false, 4857 /*AllowObjCConversionOnExplicit=*/false); 4858 } 4859 4860 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4861 /// of the expression From to bool (C++0x [conv]p3). 4862 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4863 if (checkPlaceholderForOverload(*this, From)) 4864 return ExprError(); 4865 4866 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4867 if (!ICS.isBad()) 4868 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4869 4870 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4871 return Diag(From->getLocStart(), 4872 diag::err_typecheck_bool_condition) 4873 << From->getType() << From->getSourceRange(); 4874 return ExprError(); 4875 } 4876 4877 /// Check that the specified conversion is permitted in a converted constant 4878 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4879 /// is acceptable. 4880 static bool CheckConvertedConstantConversions(Sema &S, 4881 StandardConversionSequence &SCS) { 4882 // Since we know that the target type is an integral or unscoped enumeration 4883 // type, most conversion kinds are impossible. All possible First and Third 4884 // conversions are fine. 4885 switch (SCS.Second) { 4886 case ICK_Identity: 4887 case ICK_NoReturn_Adjustment: 4888 case ICK_Integral_Promotion: 4889 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 4890 return true; 4891 4892 case ICK_Boolean_Conversion: 4893 // Conversion from an integral or unscoped enumeration type to bool is 4894 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 4895 // conversion, so we allow it in a converted constant expression. 4896 // 4897 // FIXME: Per core issue 1407, we should not allow this, but that breaks 4898 // a lot of popular code. We should at least add a warning for this 4899 // (non-conforming) extension. 4900 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4901 SCS.getToType(2)->isBooleanType(); 4902 4903 case ICK_Pointer_Conversion: 4904 case ICK_Pointer_Member: 4905 // C++1z: null pointer conversions and null member pointer conversions are 4906 // only permitted if the source type is std::nullptr_t. 4907 return SCS.getFromType()->isNullPtrType(); 4908 4909 case ICK_Floating_Promotion: 4910 case ICK_Complex_Promotion: 4911 case ICK_Floating_Conversion: 4912 case ICK_Complex_Conversion: 4913 case ICK_Floating_Integral: 4914 case ICK_Compatible_Conversion: 4915 case ICK_Derived_To_Base: 4916 case ICK_Vector_Conversion: 4917 case ICK_Vector_Splat: 4918 case ICK_Complex_Real: 4919 case ICK_Block_Pointer_Conversion: 4920 case ICK_TransparentUnionConversion: 4921 case ICK_Writeback_Conversion: 4922 case ICK_Zero_Event_Conversion: 4923 return false; 4924 4925 case ICK_Lvalue_To_Rvalue: 4926 case ICK_Array_To_Pointer: 4927 case ICK_Function_To_Pointer: 4928 llvm_unreachable("found a first conversion kind in Second"); 4929 4930 case ICK_Qualification: 4931 llvm_unreachable("found a third conversion kind in Second"); 4932 4933 case ICK_Num_Conversion_Kinds: 4934 break; 4935 } 4936 4937 llvm_unreachable("unknown conversion kind"); 4938 } 4939 4940 /// CheckConvertedConstantExpression - Check that the expression From is a 4941 /// converted constant expression of type T, perform the conversion and produce 4942 /// the converted expression, per C++11 [expr.const]p3. 4943 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 4944 QualType T, APValue &Value, 4945 Sema::CCEKind CCE, 4946 bool RequireInt) { 4947 assert(S.getLangOpts().CPlusPlus11 && 4948 "converted constant expression outside C++11"); 4949 4950 if (checkPlaceholderForOverload(S, From)) 4951 return ExprError(); 4952 4953 // C++1z [expr.const]p3: 4954 // A converted constant expression of type T is an expression, 4955 // implicitly converted to type T, where the converted 4956 // expression is a constant expression and the implicit conversion 4957 // sequence contains only [... list of conversions ...]. 4958 ImplicitConversionSequence ICS = 4959 TryCopyInitialization(S, From, T, 4960 /*SuppressUserConversions=*/false, 4961 /*InOverloadResolution=*/false, 4962 /*AllowObjcWritebackConversion=*/false, 4963 /*AllowExplicit=*/false); 4964 StandardConversionSequence *SCS = nullptr; 4965 switch (ICS.getKind()) { 4966 case ImplicitConversionSequence::StandardConversion: 4967 SCS = &ICS.Standard; 4968 break; 4969 case ImplicitConversionSequence::UserDefinedConversion: 4970 // We are converting to a non-class type, so the Before sequence 4971 // must be trivial. 4972 SCS = &ICS.UserDefined.After; 4973 break; 4974 case ImplicitConversionSequence::AmbiguousConversion: 4975 case ImplicitConversionSequence::BadConversion: 4976 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 4977 return S.Diag(From->getLocStart(), 4978 diag::err_typecheck_converted_constant_expression) 4979 << From->getType() << From->getSourceRange() << T; 4980 return ExprError(); 4981 4982 case ImplicitConversionSequence::EllipsisConversion: 4983 llvm_unreachable("ellipsis conversion in converted constant expression"); 4984 } 4985 4986 // Check that we would only use permitted conversions. 4987 if (!CheckConvertedConstantConversions(S, *SCS)) { 4988 return S.Diag(From->getLocStart(), 4989 diag::err_typecheck_converted_constant_expression_disallowed) 4990 << From->getType() << From->getSourceRange() << T; 4991 } 4992 // [...] and where the reference binding (if any) binds directly. 4993 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 4994 return S.Diag(From->getLocStart(), 4995 diag::err_typecheck_converted_constant_expression_indirect) 4996 << From->getType() << From->getSourceRange() << T; 4997 } 4998 4999 ExprResult Result = 5000 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5001 if (Result.isInvalid()) 5002 return Result; 5003 5004 // Check for a narrowing implicit conversion. 5005 APValue PreNarrowingValue; 5006 QualType PreNarrowingType; 5007 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5008 PreNarrowingType)) { 5009 case NK_Variable_Narrowing: 5010 // Implicit conversion to a narrower type, and the value is not a constant 5011 // expression. We'll diagnose this in a moment. 5012 case NK_Not_Narrowing: 5013 break; 5014 5015 case NK_Constant_Narrowing: 5016 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5017 << CCE << /*Constant*/1 5018 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5019 break; 5020 5021 case NK_Type_Narrowing: 5022 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5023 << CCE << /*Constant*/0 << From->getType() << T; 5024 break; 5025 } 5026 5027 // Check the expression is a constant expression. 5028 SmallVector<PartialDiagnosticAt, 8> Notes; 5029 Expr::EvalResult Eval; 5030 Eval.Diag = &Notes; 5031 5032 if ((T->isReferenceType() 5033 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5034 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5035 (RequireInt && !Eval.Val.isInt())) { 5036 // The expression can't be folded, so we can't keep it at this position in 5037 // the AST. 5038 Result = ExprError(); 5039 } else { 5040 Value = Eval.Val; 5041 5042 if (Notes.empty()) { 5043 // It's a constant expression. 5044 return Result; 5045 } 5046 } 5047 5048 // It's not a constant expression. Produce an appropriate diagnostic. 5049 if (Notes.size() == 1 && 5050 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5051 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5052 else { 5053 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5054 << CCE << From->getSourceRange(); 5055 for (unsigned I = 0; I < Notes.size(); ++I) 5056 S.Diag(Notes[I].first, Notes[I].second); 5057 } 5058 return ExprError(); 5059 } 5060 5061 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5062 APValue &Value, CCEKind CCE) { 5063 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5064 } 5065 5066 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5067 llvm::APSInt &Value, 5068 CCEKind CCE) { 5069 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5070 5071 APValue V; 5072 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5073 if (!R.isInvalid()) 5074 Value = V.getInt(); 5075 return R; 5076 } 5077 5078 5079 /// dropPointerConversions - If the given standard conversion sequence 5080 /// involves any pointer conversions, remove them. This may change 5081 /// the result type of the conversion sequence. 5082 static void dropPointerConversion(StandardConversionSequence &SCS) { 5083 if (SCS.Second == ICK_Pointer_Conversion) { 5084 SCS.Second = ICK_Identity; 5085 SCS.Third = ICK_Identity; 5086 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5087 } 5088 } 5089 5090 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5091 /// convert the expression From to an Objective-C pointer type. 5092 static ImplicitConversionSequence 5093 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5094 // Do an implicit conversion to 'id'. 5095 QualType Ty = S.Context.getObjCIdType(); 5096 ImplicitConversionSequence ICS 5097 = TryImplicitConversion(S, From, Ty, 5098 // FIXME: Are these flags correct? 5099 /*SuppressUserConversions=*/false, 5100 /*AllowExplicit=*/true, 5101 /*InOverloadResolution=*/false, 5102 /*CStyle=*/false, 5103 /*AllowObjCWritebackConversion=*/false, 5104 /*AllowObjCConversionOnExplicit=*/true); 5105 5106 // Strip off any final conversions to 'id'. 5107 switch (ICS.getKind()) { 5108 case ImplicitConversionSequence::BadConversion: 5109 case ImplicitConversionSequence::AmbiguousConversion: 5110 case ImplicitConversionSequence::EllipsisConversion: 5111 break; 5112 5113 case ImplicitConversionSequence::UserDefinedConversion: 5114 dropPointerConversion(ICS.UserDefined.After); 5115 break; 5116 5117 case ImplicitConversionSequence::StandardConversion: 5118 dropPointerConversion(ICS.Standard); 5119 break; 5120 } 5121 5122 return ICS; 5123 } 5124 5125 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5126 /// conversion of the expression From to an Objective-C pointer type. 5127 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5128 if (checkPlaceholderForOverload(*this, From)) 5129 return ExprError(); 5130 5131 QualType Ty = Context.getObjCIdType(); 5132 ImplicitConversionSequence ICS = 5133 TryContextuallyConvertToObjCPointer(*this, From); 5134 if (!ICS.isBad()) 5135 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5136 return ExprError(); 5137 } 5138 5139 /// Determine whether the provided type is an integral type, or an enumeration 5140 /// type of a permitted flavor. 5141 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5142 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5143 : T->isIntegralOrUnscopedEnumerationType(); 5144 } 5145 5146 static ExprResult 5147 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5148 Sema::ContextualImplicitConverter &Converter, 5149 QualType T, UnresolvedSetImpl &ViableConversions) { 5150 5151 if (Converter.Suppress) 5152 return ExprError(); 5153 5154 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5155 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5156 CXXConversionDecl *Conv = 5157 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5158 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5159 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5160 } 5161 return From; 5162 } 5163 5164 static bool 5165 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5166 Sema::ContextualImplicitConverter &Converter, 5167 QualType T, bool HadMultipleCandidates, 5168 UnresolvedSetImpl &ExplicitConversions) { 5169 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5170 DeclAccessPair Found = ExplicitConversions[0]; 5171 CXXConversionDecl *Conversion = 5172 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5173 5174 // The user probably meant to invoke the given explicit 5175 // conversion; use it. 5176 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5177 std::string TypeStr; 5178 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5179 5180 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5181 << FixItHint::CreateInsertion(From->getLocStart(), 5182 "static_cast<" + TypeStr + ">(") 5183 << FixItHint::CreateInsertion( 5184 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5185 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5186 5187 // If we aren't in a SFINAE context, build a call to the 5188 // explicit conversion function. 5189 if (SemaRef.isSFINAEContext()) 5190 return true; 5191 5192 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5193 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5194 HadMultipleCandidates); 5195 if (Result.isInvalid()) 5196 return true; 5197 // Record usage of conversion in an implicit cast. 5198 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5199 CK_UserDefinedConversion, Result.get(), 5200 nullptr, Result.get()->getValueKind()); 5201 } 5202 return false; 5203 } 5204 5205 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5206 Sema::ContextualImplicitConverter &Converter, 5207 QualType T, bool HadMultipleCandidates, 5208 DeclAccessPair &Found) { 5209 CXXConversionDecl *Conversion = 5210 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5211 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5212 5213 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5214 if (!Converter.SuppressConversion) { 5215 if (SemaRef.isSFINAEContext()) 5216 return true; 5217 5218 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5219 << From->getSourceRange(); 5220 } 5221 5222 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5223 HadMultipleCandidates); 5224 if (Result.isInvalid()) 5225 return true; 5226 // Record usage of conversion in an implicit cast. 5227 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5228 CK_UserDefinedConversion, Result.get(), 5229 nullptr, Result.get()->getValueKind()); 5230 return false; 5231 } 5232 5233 static ExprResult finishContextualImplicitConversion( 5234 Sema &SemaRef, SourceLocation Loc, Expr *From, 5235 Sema::ContextualImplicitConverter &Converter) { 5236 if (!Converter.match(From->getType()) && !Converter.Suppress) 5237 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5238 << From->getSourceRange(); 5239 5240 return SemaRef.DefaultLvalueConversion(From); 5241 } 5242 5243 static void 5244 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5245 UnresolvedSetImpl &ViableConversions, 5246 OverloadCandidateSet &CandidateSet) { 5247 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5248 DeclAccessPair FoundDecl = ViableConversions[I]; 5249 NamedDecl *D = FoundDecl.getDecl(); 5250 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5251 if (isa<UsingShadowDecl>(D)) 5252 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5253 5254 CXXConversionDecl *Conv; 5255 FunctionTemplateDecl *ConvTemplate; 5256 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5257 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5258 else 5259 Conv = cast<CXXConversionDecl>(D); 5260 5261 if (ConvTemplate) 5262 SemaRef.AddTemplateConversionCandidate( 5263 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5264 /*AllowObjCConversionOnExplicit=*/false); 5265 else 5266 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5267 ToType, CandidateSet, 5268 /*AllowObjCConversionOnExplicit=*/false); 5269 } 5270 } 5271 5272 /// \brief Attempt to convert the given expression to a type which is accepted 5273 /// by the given converter. 5274 /// 5275 /// This routine will attempt to convert an expression of class type to a 5276 /// type accepted by the specified converter. In C++11 and before, the class 5277 /// must have a single non-explicit conversion function converting to a matching 5278 /// type. In C++1y, there can be multiple such conversion functions, but only 5279 /// one target type. 5280 /// 5281 /// \param Loc The source location of the construct that requires the 5282 /// conversion. 5283 /// 5284 /// \param From The expression we're converting from. 5285 /// 5286 /// \param Converter Used to control and diagnose the conversion process. 5287 /// 5288 /// \returns The expression, converted to an integral or enumeration type if 5289 /// successful. 5290 ExprResult Sema::PerformContextualImplicitConversion( 5291 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5292 // We can't perform any more checking for type-dependent expressions. 5293 if (From->isTypeDependent()) 5294 return From; 5295 5296 // Process placeholders immediately. 5297 if (From->hasPlaceholderType()) { 5298 ExprResult result = CheckPlaceholderExpr(From); 5299 if (result.isInvalid()) 5300 return result; 5301 From = result.get(); 5302 } 5303 5304 // If the expression already has a matching type, we're golden. 5305 QualType T = From->getType(); 5306 if (Converter.match(T)) 5307 return DefaultLvalueConversion(From); 5308 5309 // FIXME: Check for missing '()' if T is a function type? 5310 5311 // We can only perform contextual implicit conversions on objects of class 5312 // type. 5313 const RecordType *RecordTy = T->getAs<RecordType>(); 5314 if (!RecordTy || !getLangOpts().CPlusPlus) { 5315 if (!Converter.Suppress) 5316 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5317 return From; 5318 } 5319 5320 // We must have a complete class type. 5321 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5322 ContextualImplicitConverter &Converter; 5323 Expr *From; 5324 5325 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5326 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5327 5328 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5329 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5330 } 5331 } IncompleteDiagnoser(Converter, From); 5332 5333 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5334 return From; 5335 5336 // Look for a conversion to an integral or enumeration type. 5337 UnresolvedSet<4> 5338 ViableConversions; // These are *potentially* viable in C++1y. 5339 UnresolvedSet<4> ExplicitConversions; 5340 std::pair<CXXRecordDecl::conversion_iterator, 5341 CXXRecordDecl::conversion_iterator> Conversions = 5342 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5343 5344 bool HadMultipleCandidates = 5345 (std::distance(Conversions.first, Conversions.second) > 1); 5346 5347 // To check that there is only one target type, in C++1y: 5348 QualType ToType; 5349 bool HasUniqueTargetType = true; 5350 5351 // Collect explicit or viable (potentially in C++1y) conversions. 5352 for (CXXRecordDecl::conversion_iterator I = Conversions.first, 5353 E = Conversions.second; 5354 I != E; ++I) { 5355 NamedDecl *D = (*I)->getUnderlyingDecl(); 5356 CXXConversionDecl *Conversion; 5357 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5358 if (ConvTemplate) { 5359 if (getLangOpts().CPlusPlus14) 5360 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5361 else 5362 continue; // C++11 does not consider conversion operator templates(?). 5363 } else 5364 Conversion = cast<CXXConversionDecl>(D); 5365 5366 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5367 "Conversion operator templates are considered potentially " 5368 "viable in C++1y"); 5369 5370 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5371 if (Converter.match(CurToType) || ConvTemplate) { 5372 5373 if (Conversion->isExplicit()) { 5374 // FIXME: For C++1y, do we need this restriction? 5375 // cf. diagnoseNoViableConversion() 5376 if (!ConvTemplate) 5377 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5378 } else { 5379 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5380 if (ToType.isNull()) 5381 ToType = CurToType.getUnqualifiedType(); 5382 else if (HasUniqueTargetType && 5383 (CurToType.getUnqualifiedType() != ToType)) 5384 HasUniqueTargetType = false; 5385 } 5386 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5387 } 5388 } 5389 } 5390 5391 if (getLangOpts().CPlusPlus14) { 5392 // C++1y [conv]p6: 5393 // ... An expression e of class type E appearing in such a context 5394 // is said to be contextually implicitly converted to a specified 5395 // type T and is well-formed if and only if e can be implicitly 5396 // converted to a type T that is determined as follows: E is searched 5397 // for conversion functions whose return type is cv T or reference to 5398 // cv T such that T is allowed by the context. There shall be 5399 // exactly one such T. 5400 5401 // If no unique T is found: 5402 if (ToType.isNull()) { 5403 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5404 HadMultipleCandidates, 5405 ExplicitConversions)) 5406 return ExprError(); 5407 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5408 } 5409 5410 // If more than one unique Ts are found: 5411 if (!HasUniqueTargetType) 5412 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5413 ViableConversions); 5414 5415 // If one unique T is found: 5416 // First, build a candidate set from the previously recorded 5417 // potentially viable conversions. 5418 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5419 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5420 CandidateSet); 5421 5422 // Then, perform overload resolution over the candidate set. 5423 OverloadCandidateSet::iterator Best; 5424 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5425 case OR_Success: { 5426 // Apply this conversion. 5427 DeclAccessPair Found = 5428 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5429 if (recordConversion(*this, Loc, From, Converter, T, 5430 HadMultipleCandidates, Found)) 5431 return ExprError(); 5432 break; 5433 } 5434 case OR_Ambiguous: 5435 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5436 ViableConversions); 5437 case OR_No_Viable_Function: 5438 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5439 HadMultipleCandidates, 5440 ExplicitConversions)) 5441 return ExprError(); 5442 // fall through 'OR_Deleted' case. 5443 case OR_Deleted: 5444 // We'll complain below about a non-integral condition type. 5445 break; 5446 } 5447 } else { 5448 switch (ViableConversions.size()) { 5449 case 0: { 5450 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5451 HadMultipleCandidates, 5452 ExplicitConversions)) 5453 return ExprError(); 5454 5455 // We'll complain below about a non-integral condition type. 5456 break; 5457 } 5458 case 1: { 5459 // Apply this conversion. 5460 DeclAccessPair Found = ViableConversions[0]; 5461 if (recordConversion(*this, Loc, From, Converter, T, 5462 HadMultipleCandidates, Found)) 5463 return ExprError(); 5464 break; 5465 } 5466 default: 5467 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5468 ViableConversions); 5469 } 5470 } 5471 5472 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5473 } 5474 5475 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5476 /// an acceptable non-member overloaded operator for a call whose 5477 /// arguments have types T1 (and, if non-empty, T2). This routine 5478 /// implements the check in C++ [over.match.oper]p3b2 concerning 5479 /// enumeration types. 5480 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5481 FunctionDecl *Fn, 5482 ArrayRef<Expr *> Args) { 5483 QualType T1 = Args[0]->getType(); 5484 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5485 5486 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5487 return true; 5488 5489 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5490 return true; 5491 5492 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5493 if (Proto->getNumParams() < 1) 5494 return false; 5495 5496 if (T1->isEnumeralType()) { 5497 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5498 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5499 return true; 5500 } 5501 5502 if (Proto->getNumParams() < 2) 5503 return false; 5504 5505 if (!T2.isNull() && T2->isEnumeralType()) { 5506 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5507 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5508 return true; 5509 } 5510 5511 return false; 5512 } 5513 5514 /// AddOverloadCandidate - Adds the given function to the set of 5515 /// candidate functions, using the given function call arguments. If 5516 /// @p SuppressUserConversions, then don't allow user-defined 5517 /// conversions via constructors or conversion operators. 5518 /// 5519 /// \param PartialOverloading true if we are performing "partial" overloading 5520 /// based on an incomplete set of function arguments. This feature is used by 5521 /// code completion. 5522 void 5523 Sema::AddOverloadCandidate(FunctionDecl *Function, 5524 DeclAccessPair FoundDecl, 5525 ArrayRef<Expr *> Args, 5526 OverloadCandidateSet &CandidateSet, 5527 bool SuppressUserConversions, 5528 bool PartialOverloading, 5529 bool AllowExplicit) { 5530 const FunctionProtoType *Proto 5531 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5532 assert(Proto && "Functions without a prototype cannot be overloaded"); 5533 assert(!Function->getDescribedFunctionTemplate() && 5534 "Use AddTemplateOverloadCandidate for function templates"); 5535 5536 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5537 if (!isa<CXXConstructorDecl>(Method)) { 5538 // If we get here, it's because we're calling a member function 5539 // that is named without a member access expression (e.g., 5540 // "this->f") that was either written explicitly or created 5541 // implicitly. This can happen with a qualified call to a member 5542 // function, e.g., X::f(). We use an empty type for the implied 5543 // object argument (C++ [over.call.func]p3), and the acting context 5544 // is irrelevant. 5545 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5546 QualType(), Expr::Classification::makeSimpleLValue(), 5547 Args, CandidateSet, SuppressUserConversions, 5548 PartialOverloading); 5549 return; 5550 } 5551 // We treat a constructor like a non-member function, since its object 5552 // argument doesn't participate in overload resolution. 5553 } 5554 5555 if (!CandidateSet.isNewCandidate(Function)) 5556 return; 5557 5558 // C++ [over.match.oper]p3: 5559 // if no operand has a class type, only those non-member functions in the 5560 // lookup set that have a first parameter of type T1 or "reference to 5561 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5562 // is a right operand) a second parameter of type T2 or "reference to 5563 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5564 // candidate functions. 5565 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5566 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5567 return; 5568 5569 // C++11 [class.copy]p11: [DR1402] 5570 // A defaulted move constructor that is defined as deleted is ignored by 5571 // overload resolution. 5572 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5573 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5574 Constructor->isMoveConstructor()) 5575 return; 5576 5577 // Overload resolution is always an unevaluated context. 5578 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5579 5580 // Add this candidate 5581 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5582 Candidate.FoundDecl = FoundDecl; 5583 Candidate.Function = Function; 5584 Candidate.Viable = true; 5585 Candidate.IsSurrogate = false; 5586 Candidate.IgnoreObjectArgument = false; 5587 Candidate.ExplicitCallArguments = Args.size(); 5588 5589 if (Constructor) { 5590 // C++ [class.copy]p3: 5591 // A member function template is never instantiated to perform the copy 5592 // of a class object to an object of its class type. 5593 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5594 if (Args.size() == 1 && 5595 Constructor->isSpecializationCopyingObject() && 5596 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5597 IsDerivedFrom(Args[0]->getType(), ClassType))) { 5598 Candidate.Viable = false; 5599 Candidate.FailureKind = ovl_fail_illegal_constructor; 5600 return; 5601 } 5602 } 5603 5604 unsigned NumParams = Proto->getNumParams(); 5605 5606 // (C++ 13.3.2p2): A candidate function having fewer than m 5607 // parameters is viable only if it has an ellipsis in its parameter 5608 // list (8.3.5). 5609 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5610 !Proto->isVariadic()) { 5611 Candidate.Viable = false; 5612 Candidate.FailureKind = ovl_fail_too_many_arguments; 5613 return; 5614 } 5615 5616 // (C++ 13.3.2p2): A candidate function having more than m parameters 5617 // is viable only if the (m+1)st parameter has a default argument 5618 // (8.3.6). For the purposes of overload resolution, the 5619 // parameter list is truncated on the right, so that there are 5620 // exactly m parameters. 5621 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5622 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5623 // Not enough arguments. 5624 Candidate.Viable = false; 5625 Candidate.FailureKind = ovl_fail_too_few_arguments; 5626 return; 5627 } 5628 5629 // (CUDA B.1): Check for invalid calls between targets. 5630 if (getLangOpts().CUDA) 5631 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5632 // Skip the check for callers that are implicit members, because in this 5633 // case we may not yet know what the member's target is; the target is 5634 // inferred for the member automatically, based on the bases and fields of 5635 // the class. 5636 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5637 Candidate.Viable = false; 5638 Candidate.FailureKind = ovl_fail_bad_target; 5639 return; 5640 } 5641 5642 // Determine the implicit conversion sequences for each of the 5643 // arguments. 5644 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5645 if (ArgIdx < NumParams) { 5646 // (C++ 13.3.2p3): for F to be a viable function, there shall 5647 // exist for each argument an implicit conversion sequence 5648 // (13.3.3.1) that converts that argument to the corresponding 5649 // parameter of F. 5650 QualType ParamType = Proto->getParamType(ArgIdx); 5651 Candidate.Conversions[ArgIdx] 5652 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5653 SuppressUserConversions, 5654 /*InOverloadResolution=*/true, 5655 /*AllowObjCWritebackConversion=*/ 5656 getLangOpts().ObjCAutoRefCount, 5657 AllowExplicit); 5658 if (Candidate.Conversions[ArgIdx].isBad()) { 5659 Candidate.Viable = false; 5660 Candidate.FailureKind = ovl_fail_bad_conversion; 5661 return; 5662 } 5663 } else { 5664 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5665 // argument for which there is no corresponding parameter is 5666 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5667 Candidate.Conversions[ArgIdx].setEllipsis(); 5668 } 5669 } 5670 5671 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5672 Candidate.Viable = false; 5673 Candidate.FailureKind = ovl_fail_enable_if; 5674 Candidate.DeductionFailure.Data = FailedAttr; 5675 return; 5676 } 5677 } 5678 5679 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5680 bool IsInstance) { 5681 SmallVector<ObjCMethodDecl*, 4> Methods; 5682 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5683 return nullptr; 5684 5685 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5686 bool Match = true; 5687 ObjCMethodDecl *Method = Methods[b]; 5688 unsigned NumNamedArgs = Sel.getNumArgs(); 5689 // Method might have more arguments than selector indicates. This is due 5690 // to addition of c-style arguments in method. 5691 if (Method->param_size() > NumNamedArgs) 5692 NumNamedArgs = Method->param_size(); 5693 if (Args.size() < NumNamedArgs) 5694 continue; 5695 5696 for (unsigned i = 0; i < NumNamedArgs; i++) { 5697 // We can't do any type-checking on a type-dependent argument. 5698 if (Args[i]->isTypeDependent()) { 5699 Match = false; 5700 break; 5701 } 5702 5703 ParmVarDecl *param = Method->parameters()[i]; 5704 Expr *argExpr = Args[i]; 5705 assert(argExpr && "SelectBestMethod(): missing expression"); 5706 5707 // Strip the unbridged-cast placeholder expression off unless it's 5708 // a consumed argument. 5709 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5710 !param->hasAttr<CFConsumedAttr>()) 5711 argExpr = stripARCUnbridgedCast(argExpr); 5712 5713 // If the parameter is __unknown_anytype, move on to the next method. 5714 if (param->getType() == Context.UnknownAnyTy) { 5715 Match = false; 5716 break; 5717 } 5718 5719 ImplicitConversionSequence ConversionState 5720 = TryCopyInitialization(*this, argExpr, param->getType(), 5721 /*SuppressUserConversions*/false, 5722 /*InOverloadResolution=*/true, 5723 /*AllowObjCWritebackConversion=*/ 5724 getLangOpts().ObjCAutoRefCount, 5725 /*AllowExplicit*/false); 5726 if (ConversionState.isBad()) { 5727 Match = false; 5728 break; 5729 } 5730 } 5731 // Promote additional arguments to variadic methods. 5732 if (Match && Method->isVariadic()) { 5733 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5734 if (Args[i]->isTypeDependent()) { 5735 Match = false; 5736 break; 5737 } 5738 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5739 nullptr); 5740 if (Arg.isInvalid()) { 5741 Match = false; 5742 break; 5743 } 5744 } 5745 } else { 5746 // Check for extra arguments to non-variadic methods. 5747 if (Args.size() != NumNamedArgs) 5748 Match = false; 5749 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5750 // Special case when selectors have no argument. In this case, select 5751 // one with the most general result type of 'id'. 5752 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5753 QualType ReturnT = Methods[b]->getReturnType(); 5754 if (ReturnT->isObjCIdType()) 5755 return Methods[b]; 5756 } 5757 } 5758 } 5759 5760 if (Match) 5761 return Method; 5762 } 5763 return nullptr; 5764 } 5765 5766 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); } 5767 5768 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5769 bool MissingImplicitThis) { 5770 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but 5771 // we need to find the first failing one. 5772 if (!Function->hasAttrs()) 5773 return nullptr; 5774 AttrVec Attrs = Function->getAttrs(); 5775 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(), 5776 IsNotEnableIfAttr); 5777 if (Attrs.begin() == E) 5778 return nullptr; 5779 std::reverse(Attrs.begin(), E); 5780 5781 SFINAETrap Trap(*this); 5782 5783 // Convert the arguments. 5784 SmallVector<Expr *, 16> ConvertedArgs; 5785 bool InitializationFailed = false; 5786 bool ContainsValueDependentExpr = false; 5787 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5788 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5789 !cast<CXXMethodDecl>(Function)->isStatic() && 5790 !isa<CXXConstructorDecl>(Function)) { 5791 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5792 ExprResult R = 5793 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5794 Method, Method); 5795 if (R.isInvalid()) { 5796 InitializationFailed = true; 5797 break; 5798 } 5799 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5800 ConvertedArgs.push_back(R.get()); 5801 } else { 5802 ExprResult R = 5803 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5804 Context, 5805 Function->getParamDecl(i)), 5806 SourceLocation(), 5807 Args[i]); 5808 if (R.isInvalid()) { 5809 InitializationFailed = true; 5810 break; 5811 } 5812 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5813 ConvertedArgs.push_back(R.get()); 5814 } 5815 } 5816 5817 if (InitializationFailed || Trap.hasErrorOccurred()) 5818 return cast<EnableIfAttr>(Attrs[0]); 5819 5820 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) { 5821 APValue Result; 5822 EnableIfAttr *EIA = cast<EnableIfAttr>(*I); 5823 if (EIA->getCond()->isValueDependent()) { 5824 // Don't even try now, we'll examine it after instantiation. 5825 continue; 5826 } 5827 5828 if (!EIA->getCond()->EvaluateWithSubstitution( 5829 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) { 5830 if (!ContainsValueDependentExpr) 5831 return EIA; 5832 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) { 5833 return EIA; 5834 } 5835 } 5836 return nullptr; 5837 } 5838 5839 /// \brief Add all of the function declarations in the given function set to 5840 /// the overload candidate set. 5841 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5842 ArrayRef<Expr *> Args, 5843 OverloadCandidateSet& CandidateSet, 5844 TemplateArgumentListInfo *ExplicitTemplateArgs, 5845 bool SuppressUserConversions, 5846 bool PartialOverloading) { 5847 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5848 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5849 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5850 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5851 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5852 cast<CXXMethodDecl>(FD)->getParent(), 5853 Args[0]->getType(), Args[0]->Classify(Context), 5854 Args.slice(1), CandidateSet, 5855 SuppressUserConversions, PartialOverloading); 5856 else 5857 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5858 SuppressUserConversions, PartialOverloading); 5859 } else { 5860 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5861 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5862 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5863 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5864 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5865 ExplicitTemplateArgs, 5866 Args[0]->getType(), 5867 Args[0]->Classify(Context), Args.slice(1), 5868 CandidateSet, SuppressUserConversions, 5869 PartialOverloading); 5870 else 5871 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5872 ExplicitTemplateArgs, Args, 5873 CandidateSet, SuppressUserConversions, 5874 PartialOverloading); 5875 } 5876 } 5877 } 5878 5879 /// AddMethodCandidate - Adds a named decl (which is some kind of 5880 /// method) as a method candidate to the given overload set. 5881 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5882 QualType ObjectType, 5883 Expr::Classification ObjectClassification, 5884 ArrayRef<Expr *> Args, 5885 OverloadCandidateSet& CandidateSet, 5886 bool SuppressUserConversions) { 5887 NamedDecl *Decl = FoundDecl.getDecl(); 5888 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5889 5890 if (isa<UsingShadowDecl>(Decl)) 5891 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5892 5893 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5894 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5895 "Expected a member function template"); 5896 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5897 /*ExplicitArgs*/ nullptr, 5898 ObjectType, ObjectClassification, 5899 Args, CandidateSet, 5900 SuppressUserConversions); 5901 } else { 5902 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5903 ObjectType, ObjectClassification, 5904 Args, 5905 CandidateSet, SuppressUserConversions); 5906 } 5907 } 5908 5909 /// AddMethodCandidate - Adds the given C++ member function to the set 5910 /// of candidate functions, using the given function call arguments 5911 /// and the object argument (@c Object). For example, in a call 5912 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5913 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5914 /// allow user-defined conversions via constructors or conversion 5915 /// operators. 5916 void 5917 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5918 CXXRecordDecl *ActingContext, QualType ObjectType, 5919 Expr::Classification ObjectClassification, 5920 ArrayRef<Expr *> Args, 5921 OverloadCandidateSet &CandidateSet, 5922 bool SuppressUserConversions, 5923 bool PartialOverloading) { 5924 const FunctionProtoType *Proto 5925 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5926 assert(Proto && "Methods without a prototype cannot be overloaded"); 5927 assert(!isa<CXXConstructorDecl>(Method) && 5928 "Use AddOverloadCandidate for constructors"); 5929 5930 if (!CandidateSet.isNewCandidate(Method)) 5931 return; 5932 5933 // C++11 [class.copy]p23: [DR1402] 5934 // A defaulted move assignment operator that is defined as deleted is 5935 // ignored by overload resolution. 5936 if (Method->isDefaulted() && Method->isDeleted() && 5937 Method->isMoveAssignmentOperator()) 5938 return; 5939 5940 // Overload resolution is always an unevaluated context. 5941 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5942 5943 // Add this candidate 5944 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5945 Candidate.FoundDecl = FoundDecl; 5946 Candidate.Function = Method; 5947 Candidate.IsSurrogate = false; 5948 Candidate.IgnoreObjectArgument = false; 5949 Candidate.ExplicitCallArguments = Args.size(); 5950 5951 unsigned NumParams = Proto->getNumParams(); 5952 5953 // (C++ 13.3.2p2): A candidate function having fewer than m 5954 // parameters is viable only if it has an ellipsis in its parameter 5955 // list (8.3.5). 5956 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5957 !Proto->isVariadic()) { 5958 Candidate.Viable = false; 5959 Candidate.FailureKind = ovl_fail_too_many_arguments; 5960 return; 5961 } 5962 5963 // (C++ 13.3.2p2): A candidate function having more than m parameters 5964 // is viable only if the (m+1)st parameter has a default argument 5965 // (8.3.6). For the purposes of overload resolution, the 5966 // parameter list is truncated on the right, so that there are 5967 // exactly m parameters. 5968 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5969 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5970 // Not enough arguments. 5971 Candidate.Viable = false; 5972 Candidate.FailureKind = ovl_fail_too_few_arguments; 5973 return; 5974 } 5975 5976 Candidate.Viable = true; 5977 5978 if (Method->isStatic() || ObjectType.isNull()) 5979 // The implicit object argument is ignored. 5980 Candidate.IgnoreObjectArgument = true; 5981 else { 5982 // Determine the implicit conversion sequence for the object 5983 // parameter. 5984 Candidate.Conversions[0] 5985 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5986 Method, ActingContext); 5987 if (Candidate.Conversions[0].isBad()) { 5988 Candidate.Viable = false; 5989 Candidate.FailureKind = ovl_fail_bad_conversion; 5990 return; 5991 } 5992 } 5993 5994 // (CUDA B.1): Check for invalid calls between targets. 5995 if (getLangOpts().CUDA) 5996 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5997 if (CheckCUDATarget(Caller, Method)) { 5998 Candidate.Viable = false; 5999 Candidate.FailureKind = ovl_fail_bad_target; 6000 return; 6001 } 6002 6003 // Determine the implicit conversion sequences for each of the 6004 // arguments. 6005 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6006 if (ArgIdx < NumParams) { 6007 // (C++ 13.3.2p3): for F to be a viable function, there shall 6008 // exist for each argument an implicit conversion sequence 6009 // (13.3.3.1) that converts that argument to the corresponding 6010 // parameter of F. 6011 QualType ParamType = Proto->getParamType(ArgIdx); 6012 Candidate.Conversions[ArgIdx + 1] 6013 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6014 SuppressUserConversions, 6015 /*InOverloadResolution=*/true, 6016 /*AllowObjCWritebackConversion=*/ 6017 getLangOpts().ObjCAutoRefCount); 6018 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6019 Candidate.Viable = false; 6020 Candidate.FailureKind = ovl_fail_bad_conversion; 6021 return; 6022 } 6023 } else { 6024 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6025 // argument for which there is no corresponding parameter is 6026 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6027 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6028 } 6029 } 6030 6031 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6032 Candidate.Viable = false; 6033 Candidate.FailureKind = ovl_fail_enable_if; 6034 Candidate.DeductionFailure.Data = FailedAttr; 6035 return; 6036 } 6037 } 6038 6039 /// \brief Add a C++ member function template as a candidate to the candidate 6040 /// set, using template argument deduction to produce an appropriate member 6041 /// function template specialization. 6042 void 6043 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6044 DeclAccessPair FoundDecl, 6045 CXXRecordDecl *ActingContext, 6046 TemplateArgumentListInfo *ExplicitTemplateArgs, 6047 QualType ObjectType, 6048 Expr::Classification ObjectClassification, 6049 ArrayRef<Expr *> Args, 6050 OverloadCandidateSet& CandidateSet, 6051 bool SuppressUserConversions, 6052 bool PartialOverloading) { 6053 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6054 return; 6055 6056 // C++ [over.match.funcs]p7: 6057 // In each case where a candidate is a function template, candidate 6058 // function template specializations are generated using template argument 6059 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6060 // candidate functions in the usual way.113) A given name can refer to one 6061 // or more function templates and also to a set of overloaded non-template 6062 // functions. In such a case, the candidate functions generated from each 6063 // function template are combined with the set of non-template candidate 6064 // functions. 6065 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6066 FunctionDecl *Specialization = nullptr; 6067 if (TemplateDeductionResult Result 6068 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6069 Specialization, Info, PartialOverloading)) { 6070 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6071 Candidate.FoundDecl = FoundDecl; 6072 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6073 Candidate.Viable = false; 6074 Candidate.FailureKind = ovl_fail_bad_deduction; 6075 Candidate.IsSurrogate = false; 6076 Candidate.IgnoreObjectArgument = false; 6077 Candidate.ExplicitCallArguments = Args.size(); 6078 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6079 Info); 6080 return; 6081 } 6082 6083 // Add the function template specialization produced by template argument 6084 // deduction as a candidate. 6085 assert(Specialization && "Missing member function template specialization?"); 6086 assert(isa<CXXMethodDecl>(Specialization) && 6087 "Specialization is not a member function?"); 6088 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6089 ActingContext, ObjectType, ObjectClassification, Args, 6090 CandidateSet, SuppressUserConversions, PartialOverloading); 6091 } 6092 6093 /// \brief Add a C++ function template specialization as a candidate 6094 /// in the candidate set, using template argument deduction to produce 6095 /// an appropriate function template specialization. 6096 void 6097 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6098 DeclAccessPair FoundDecl, 6099 TemplateArgumentListInfo *ExplicitTemplateArgs, 6100 ArrayRef<Expr *> Args, 6101 OverloadCandidateSet& CandidateSet, 6102 bool SuppressUserConversions, 6103 bool PartialOverloading) { 6104 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6105 return; 6106 6107 // C++ [over.match.funcs]p7: 6108 // In each case where a candidate is a function template, candidate 6109 // function template specializations are generated using template argument 6110 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6111 // candidate functions in the usual way.113) A given name can refer to one 6112 // or more function templates and also to a set of overloaded non-template 6113 // functions. In such a case, the candidate functions generated from each 6114 // function template are combined with the set of non-template candidate 6115 // functions. 6116 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6117 FunctionDecl *Specialization = nullptr; 6118 if (TemplateDeductionResult Result 6119 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6120 Specialization, Info, PartialOverloading)) { 6121 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6122 Candidate.FoundDecl = FoundDecl; 6123 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6124 Candidate.Viable = false; 6125 Candidate.FailureKind = ovl_fail_bad_deduction; 6126 Candidate.IsSurrogate = false; 6127 Candidate.IgnoreObjectArgument = false; 6128 Candidate.ExplicitCallArguments = Args.size(); 6129 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6130 Info); 6131 return; 6132 } 6133 6134 // Add the function template specialization produced by template argument 6135 // deduction as a candidate. 6136 assert(Specialization && "Missing function template specialization?"); 6137 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6138 SuppressUserConversions, PartialOverloading); 6139 } 6140 6141 /// Determine whether this is an allowable conversion from the result 6142 /// of an explicit conversion operator to the expected type, per C++ 6143 /// [over.match.conv]p1 and [over.match.ref]p1. 6144 /// 6145 /// \param ConvType The return type of the conversion function. 6146 /// 6147 /// \param ToType The type we are converting to. 6148 /// 6149 /// \param AllowObjCPointerConversion Allow a conversion from one 6150 /// Objective-C pointer to another. 6151 /// 6152 /// \returns true if the conversion is allowable, false otherwise. 6153 static bool isAllowableExplicitConversion(Sema &S, 6154 QualType ConvType, QualType ToType, 6155 bool AllowObjCPointerConversion) { 6156 QualType ToNonRefType = ToType.getNonReferenceType(); 6157 6158 // Easy case: the types are the same. 6159 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6160 return true; 6161 6162 // Allow qualification conversions. 6163 bool ObjCLifetimeConversion; 6164 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6165 ObjCLifetimeConversion)) 6166 return true; 6167 6168 // If we're not allowed to consider Objective-C pointer conversions, 6169 // we're done. 6170 if (!AllowObjCPointerConversion) 6171 return false; 6172 6173 // Is this an Objective-C pointer conversion? 6174 bool IncompatibleObjC = false; 6175 QualType ConvertedType; 6176 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6177 IncompatibleObjC); 6178 } 6179 6180 /// AddConversionCandidate - Add a C++ conversion function as a 6181 /// candidate in the candidate set (C++ [over.match.conv], 6182 /// C++ [over.match.copy]). From is the expression we're converting from, 6183 /// and ToType is the type that we're eventually trying to convert to 6184 /// (which may or may not be the same type as the type that the 6185 /// conversion function produces). 6186 void 6187 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6188 DeclAccessPair FoundDecl, 6189 CXXRecordDecl *ActingContext, 6190 Expr *From, QualType ToType, 6191 OverloadCandidateSet& CandidateSet, 6192 bool AllowObjCConversionOnExplicit) { 6193 assert(!Conversion->getDescribedFunctionTemplate() && 6194 "Conversion function templates use AddTemplateConversionCandidate"); 6195 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6196 if (!CandidateSet.isNewCandidate(Conversion)) 6197 return; 6198 6199 // If the conversion function has an undeduced return type, trigger its 6200 // deduction now. 6201 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6202 if (DeduceReturnType(Conversion, From->getExprLoc())) 6203 return; 6204 ConvType = Conversion->getConversionType().getNonReferenceType(); 6205 } 6206 6207 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6208 // operator is only a candidate if its return type is the target type or 6209 // can be converted to the target type with a qualification conversion. 6210 if (Conversion->isExplicit() && 6211 !isAllowableExplicitConversion(*this, ConvType, ToType, 6212 AllowObjCConversionOnExplicit)) 6213 return; 6214 6215 // Overload resolution is always an unevaluated context. 6216 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6217 6218 // Add this candidate 6219 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6220 Candidate.FoundDecl = FoundDecl; 6221 Candidate.Function = Conversion; 6222 Candidate.IsSurrogate = false; 6223 Candidate.IgnoreObjectArgument = false; 6224 Candidate.FinalConversion.setAsIdentityConversion(); 6225 Candidate.FinalConversion.setFromType(ConvType); 6226 Candidate.FinalConversion.setAllToTypes(ToType); 6227 Candidate.Viable = true; 6228 Candidate.ExplicitCallArguments = 1; 6229 6230 // C++ [over.match.funcs]p4: 6231 // For conversion functions, the function is considered to be a member of 6232 // the class of the implicit implied object argument for the purpose of 6233 // defining the type of the implicit object parameter. 6234 // 6235 // Determine the implicit conversion sequence for the implicit 6236 // object parameter. 6237 QualType ImplicitParamType = From->getType(); 6238 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6239 ImplicitParamType = FromPtrType->getPointeeType(); 6240 CXXRecordDecl *ConversionContext 6241 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6242 6243 Candidate.Conversions[0] 6244 = TryObjectArgumentInitialization(*this, From->getType(), 6245 From->Classify(Context), 6246 Conversion, ConversionContext); 6247 6248 if (Candidate.Conversions[0].isBad()) { 6249 Candidate.Viable = false; 6250 Candidate.FailureKind = ovl_fail_bad_conversion; 6251 return; 6252 } 6253 6254 // We won't go through a user-defined type conversion function to convert a 6255 // derived to base as such conversions are given Conversion Rank. They only 6256 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6257 QualType FromCanon 6258 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6259 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6260 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6261 Candidate.Viable = false; 6262 Candidate.FailureKind = ovl_fail_trivial_conversion; 6263 return; 6264 } 6265 6266 // To determine what the conversion from the result of calling the 6267 // conversion function to the type we're eventually trying to 6268 // convert to (ToType), we need to synthesize a call to the 6269 // conversion function and attempt copy initialization from it. This 6270 // makes sure that we get the right semantics with respect to 6271 // lvalues/rvalues and the type. Fortunately, we can allocate this 6272 // call on the stack and we don't need its arguments to be 6273 // well-formed. 6274 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6275 VK_LValue, From->getLocStart()); 6276 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6277 Context.getPointerType(Conversion->getType()), 6278 CK_FunctionToPointerDecay, 6279 &ConversionRef, VK_RValue); 6280 6281 QualType ConversionType = Conversion->getConversionType(); 6282 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6283 Candidate.Viable = false; 6284 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6285 return; 6286 } 6287 6288 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6289 6290 // Note that it is safe to allocate CallExpr on the stack here because 6291 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6292 // allocator). 6293 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6294 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6295 From->getLocStart()); 6296 ImplicitConversionSequence ICS = 6297 TryCopyInitialization(*this, &Call, ToType, 6298 /*SuppressUserConversions=*/true, 6299 /*InOverloadResolution=*/false, 6300 /*AllowObjCWritebackConversion=*/false); 6301 6302 switch (ICS.getKind()) { 6303 case ImplicitConversionSequence::StandardConversion: 6304 Candidate.FinalConversion = ICS.Standard; 6305 6306 // C++ [over.ics.user]p3: 6307 // If the user-defined conversion is specified by a specialization of a 6308 // conversion function template, the second standard conversion sequence 6309 // shall have exact match rank. 6310 if (Conversion->getPrimaryTemplate() && 6311 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6312 Candidate.Viable = false; 6313 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6314 return; 6315 } 6316 6317 // C++0x [dcl.init.ref]p5: 6318 // In the second case, if the reference is an rvalue reference and 6319 // the second standard conversion sequence of the user-defined 6320 // conversion sequence includes an lvalue-to-rvalue conversion, the 6321 // program is ill-formed. 6322 if (ToType->isRValueReferenceType() && 6323 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6324 Candidate.Viable = false; 6325 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6326 return; 6327 } 6328 break; 6329 6330 case ImplicitConversionSequence::BadConversion: 6331 Candidate.Viable = false; 6332 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6333 return; 6334 6335 default: 6336 llvm_unreachable( 6337 "Can only end up with a standard conversion sequence or failure"); 6338 } 6339 6340 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6341 Candidate.Viable = false; 6342 Candidate.FailureKind = ovl_fail_enable_if; 6343 Candidate.DeductionFailure.Data = FailedAttr; 6344 return; 6345 } 6346 } 6347 6348 /// \brief Adds a conversion function template specialization 6349 /// candidate to the overload set, using template argument deduction 6350 /// to deduce the template arguments of the conversion function 6351 /// template from the type that we are converting to (C++ 6352 /// [temp.deduct.conv]). 6353 void 6354 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6355 DeclAccessPair FoundDecl, 6356 CXXRecordDecl *ActingDC, 6357 Expr *From, QualType ToType, 6358 OverloadCandidateSet &CandidateSet, 6359 bool AllowObjCConversionOnExplicit) { 6360 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6361 "Only conversion function templates permitted here"); 6362 6363 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6364 return; 6365 6366 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6367 CXXConversionDecl *Specialization = nullptr; 6368 if (TemplateDeductionResult Result 6369 = DeduceTemplateArguments(FunctionTemplate, ToType, 6370 Specialization, Info)) { 6371 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6372 Candidate.FoundDecl = FoundDecl; 6373 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6374 Candidate.Viable = false; 6375 Candidate.FailureKind = ovl_fail_bad_deduction; 6376 Candidate.IsSurrogate = false; 6377 Candidate.IgnoreObjectArgument = false; 6378 Candidate.ExplicitCallArguments = 1; 6379 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6380 Info); 6381 return; 6382 } 6383 6384 // Add the conversion function template specialization produced by 6385 // template argument deduction as a candidate. 6386 assert(Specialization && "Missing function template specialization?"); 6387 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6388 CandidateSet, AllowObjCConversionOnExplicit); 6389 } 6390 6391 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6392 /// converts the given @c Object to a function pointer via the 6393 /// conversion function @c Conversion, and then attempts to call it 6394 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6395 /// the type of function that we'll eventually be calling. 6396 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6397 DeclAccessPair FoundDecl, 6398 CXXRecordDecl *ActingContext, 6399 const FunctionProtoType *Proto, 6400 Expr *Object, 6401 ArrayRef<Expr *> Args, 6402 OverloadCandidateSet& CandidateSet) { 6403 if (!CandidateSet.isNewCandidate(Conversion)) 6404 return; 6405 6406 // Overload resolution is always an unevaluated context. 6407 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6408 6409 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6410 Candidate.FoundDecl = FoundDecl; 6411 Candidate.Function = nullptr; 6412 Candidate.Surrogate = Conversion; 6413 Candidate.Viable = true; 6414 Candidate.IsSurrogate = true; 6415 Candidate.IgnoreObjectArgument = false; 6416 Candidate.ExplicitCallArguments = Args.size(); 6417 6418 // Determine the implicit conversion sequence for the implicit 6419 // object parameter. 6420 ImplicitConversionSequence ObjectInit 6421 = TryObjectArgumentInitialization(*this, Object->getType(), 6422 Object->Classify(Context), 6423 Conversion, ActingContext); 6424 if (ObjectInit.isBad()) { 6425 Candidate.Viable = false; 6426 Candidate.FailureKind = ovl_fail_bad_conversion; 6427 Candidate.Conversions[0] = ObjectInit; 6428 return; 6429 } 6430 6431 // The first conversion is actually a user-defined conversion whose 6432 // first conversion is ObjectInit's standard conversion (which is 6433 // effectively a reference binding). Record it as such. 6434 Candidate.Conversions[0].setUserDefined(); 6435 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6436 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6437 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6438 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6439 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6440 Candidate.Conversions[0].UserDefined.After 6441 = Candidate.Conversions[0].UserDefined.Before; 6442 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6443 6444 // Find the 6445 unsigned NumParams = Proto->getNumParams(); 6446 6447 // (C++ 13.3.2p2): A candidate function having fewer than m 6448 // parameters is viable only if it has an ellipsis in its parameter 6449 // list (8.3.5). 6450 if (Args.size() > NumParams && !Proto->isVariadic()) { 6451 Candidate.Viable = false; 6452 Candidate.FailureKind = ovl_fail_too_many_arguments; 6453 return; 6454 } 6455 6456 // Function types don't have any default arguments, so just check if 6457 // we have enough arguments. 6458 if (Args.size() < NumParams) { 6459 // Not enough arguments. 6460 Candidate.Viable = false; 6461 Candidate.FailureKind = ovl_fail_too_few_arguments; 6462 return; 6463 } 6464 6465 // Determine the implicit conversion sequences for each of the 6466 // arguments. 6467 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6468 if (ArgIdx < NumParams) { 6469 // (C++ 13.3.2p3): for F to be a viable function, there shall 6470 // exist for each argument an implicit conversion sequence 6471 // (13.3.3.1) that converts that argument to the corresponding 6472 // parameter of F. 6473 QualType ParamType = Proto->getParamType(ArgIdx); 6474 Candidate.Conversions[ArgIdx + 1] 6475 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6476 /*SuppressUserConversions=*/false, 6477 /*InOverloadResolution=*/false, 6478 /*AllowObjCWritebackConversion=*/ 6479 getLangOpts().ObjCAutoRefCount); 6480 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6481 Candidate.Viable = false; 6482 Candidate.FailureKind = ovl_fail_bad_conversion; 6483 return; 6484 } 6485 } else { 6486 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6487 // argument for which there is no corresponding parameter is 6488 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6489 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6490 } 6491 } 6492 6493 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6494 Candidate.Viable = false; 6495 Candidate.FailureKind = ovl_fail_enable_if; 6496 Candidate.DeductionFailure.Data = FailedAttr; 6497 return; 6498 } 6499 } 6500 6501 /// \brief Add overload candidates for overloaded operators that are 6502 /// member functions. 6503 /// 6504 /// Add the overloaded operator candidates that are member functions 6505 /// for the operator Op that was used in an operator expression such 6506 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6507 /// CandidateSet will store the added overload candidates. (C++ 6508 /// [over.match.oper]). 6509 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6510 SourceLocation OpLoc, 6511 ArrayRef<Expr *> Args, 6512 OverloadCandidateSet& CandidateSet, 6513 SourceRange OpRange) { 6514 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6515 6516 // C++ [over.match.oper]p3: 6517 // For a unary operator @ with an operand of a type whose 6518 // cv-unqualified version is T1, and for a binary operator @ with 6519 // a left operand of a type whose cv-unqualified version is T1 and 6520 // a right operand of a type whose cv-unqualified version is T2, 6521 // three sets of candidate functions, designated member 6522 // candidates, non-member candidates and built-in candidates, are 6523 // constructed as follows: 6524 QualType T1 = Args[0]->getType(); 6525 6526 // -- If T1 is a complete class type or a class currently being 6527 // defined, the set of member candidates is the result of the 6528 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6529 // the set of member candidates is empty. 6530 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6531 // Complete the type if it can be completed. 6532 RequireCompleteType(OpLoc, T1, 0); 6533 // If the type is neither complete nor being defined, bail out now. 6534 if (!T1Rec->getDecl()->getDefinition()) 6535 return; 6536 6537 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6538 LookupQualifiedName(Operators, T1Rec->getDecl()); 6539 Operators.suppressDiagnostics(); 6540 6541 for (LookupResult::iterator Oper = Operators.begin(), 6542 OperEnd = Operators.end(); 6543 Oper != OperEnd; 6544 ++Oper) 6545 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6546 Args[0]->Classify(Context), 6547 Args.slice(1), 6548 CandidateSet, 6549 /* SuppressUserConversions = */ false); 6550 } 6551 } 6552 6553 /// AddBuiltinCandidate - Add a candidate for a built-in 6554 /// operator. ResultTy and ParamTys are the result and parameter types 6555 /// of the built-in candidate, respectively. Args and NumArgs are the 6556 /// arguments being passed to the candidate. IsAssignmentOperator 6557 /// should be true when this built-in candidate is an assignment 6558 /// operator. NumContextualBoolArguments is the number of arguments 6559 /// (at the beginning of the argument list) that will be contextually 6560 /// converted to bool. 6561 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6562 ArrayRef<Expr *> Args, 6563 OverloadCandidateSet& CandidateSet, 6564 bool IsAssignmentOperator, 6565 unsigned NumContextualBoolArguments) { 6566 // Overload resolution is always an unevaluated context. 6567 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6568 6569 // Add this candidate 6570 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6571 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6572 Candidate.Function = nullptr; 6573 Candidate.IsSurrogate = false; 6574 Candidate.IgnoreObjectArgument = false; 6575 Candidate.BuiltinTypes.ResultTy = ResultTy; 6576 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6577 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6578 6579 // Determine the implicit conversion sequences for each of the 6580 // arguments. 6581 Candidate.Viable = true; 6582 Candidate.ExplicitCallArguments = Args.size(); 6583 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6584 // C++ [over.match.oper]p4: 6585 // For the built-in assignment operators, conversions of the 6586 // left operand are restricted as follows: 6587 // -- no temporaries are introduced to hold the left operand, and 6588 // -- no user-defined conversions are applied to the left 6589 // operand to achieve a type match with the left-most 6590 // parameter of a built-in candidate. 6591 // 6592 // We block these conversions by turning off user-defined 6593 // conversions, since that is the only way that initialization of 6594 // a reference to a non-class type can occur from something that 6595 // is not of the same type. 6596 if (ArgIdx < NumContextualBoolArguments) { 6597 assert(ParamTys[ArgIdx] == Context.BoolTy && 6598 "Contextual conversion to bool requires bool type"); 6599 Candidate.Conversions[ArgIdx] 6600 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6601 } else { 6602 Candidate.Conversions[ArgIdx] 6603 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6604 ArgIdx == 0 && IsAssignmentOperator, 6605 /*InOverloadResolution=*/false, 6606 /*AllowObjCWritebackConversion=*/ 6607 getLangOpts().ObjCAutoRefCount); 6608 } 6609 if (Candidate.Conversions[ArgIdx].isBad()) { 6610 Candidate.Viable = false; 6611 Candidate.FailureKind = ovl_fail_bad_conversion; 6612 break; 6613 } 6614 } 6615 } 6616 6617 namespace { 6618 6619 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6620 /// candidate operator functions for built-in operators (C++ 6621 /// [over.built]). The types are separated into pointer types and 6622 /// enumeration types. 6623 class BuiltinCandidateTypeSet { 6624 /// TypeSet - A set of types. 6625 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6626 6627 /// PointerTypes - The set of pointer types that will be used in the 6628 /// built-in candidates. 6629 TypeSet PointerTypes; 6630 6631 /// MemberPointerTypes - The set of member pointer types that will be 6632 /// used in the built-in candidates. 6633 TypeSet MemberPointerTypes; 6634 6635 /// EnumerationTypes - The set of enumeration types that will be 6636 /// used in the built-in candidates. 6637 TypeSet EnumerationTypes; 6638 6639 /// \brief The set of vector types that will be used in the built-in 6640 /// candidates. 6641 TypeSet VectorTypes; 6642 6643 /// \brief A flag indicating non-record types are viable candidates 6644 bool HasNonRecordTypes; 6645 6646 /// \brief A flag indicating whether either arithmetic or enumeration types 6647 /// were present in the candidate set. 6648 bool HasArithmeticOrEnumeralTypes; 6649 6650 /// \brief A flag indicating whether the nullptr type was present in the 6651 /// candidate set. 6652 bool HasNullPtrType; 6653 6654 /// Sema - The semantic analysis instance where we are building the 6655 /// candidate type set. 6656 Sema &SemaRef; 6657 6658 /// Context - The AST context in which we will build the type sets. 6659 ASTContext &Context; 6660 6661 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6662 const Qualifiers &VisibleQuals); 6663 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6664 6665 public: 6666 /// iterator - Iterates through the types that are part of the set. 6667 typedef TypeSet::iterator iterator; 6668 6669 BuiltinCandidateTypeSet(Sema &SemaRef) 6670 : HasNonRecordTypes(false), 6671 HasArithmeticOrEnumeralTypes(false), 6672 HasNullPtrType(false), 6673 SemaRef(SemaRef), 6674 Context(SemaRef.Context) { } 6675 6676 void AddTypesConvertedFrom(QualType Ty, 6677 SourceLocation Loc, 6678 bool AllowUserConversions, 6679 bool AllowExplicitConversions, 6680 const Qualifiers &VisibleTypeConversionsQuals); 6681 6682 /// pointer_begin - First pointer type found; 6683 iterator pointer_begin() { return PointerTypes.begin(); } 6684 6685 /// pointer_end - Past the last pointer type found; 6686 iterator pointer_end() { return PointerTypes.end(); } 6687 6688 /// member_pointer_begin - First member pointer type found; 6689 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6690 6691 /// member_pointer_end - Past the last member pointer type found; 6692 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6693 6694 /// enumeration_begin - First enumeration type found; 6695 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6696 6697 /// enumeration_end - Past the last enumeration type found; 6698 iterator enumeration_end() { return EnumerationTypes.end(); } 6699 6700 iterator vector_begin() { return VectorTypes.begin(); } 6701 iterator vector_end() { return VectorTypes.end(); } 6702 6703 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6704 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6705 bool hasNullPtrType() const { return HasNullPtrType; } 6706 }; 6707 6708 } // end anonymous namespace 6709 6710 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6711 /// the set of pointer types along with any more-qualified variants of 6712 /// that type. For example, if @p Ty is "int const *", this routine 6713 /// will add "int const *", "int const volatile *", "int const 6714 /// restrict *", and "int const volatile restrict *" to the set of 6715 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6716 /// false otherwise. 6717 /// 6718 /// FIXME: what to do about extended qualifiers? 6719 bool 6720 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6721 const Qualifiers &VisibleQuals) { 6722 6723 // Insert this type. 6724 if (!PointerTypes.insert(Ty).second) 6725 return false; 6726 6727 QualType PointeeTy; 6728 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6729 bool buildObjCPtr = false; 6730 if (!PointerTy) { 6731 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6732 PointeeTy = PTy->getPointeeType(); 6733 buildObjCPtr = true; 6734 } else { 6735 PointeeTy = PointerTy->getPointeeType(); 6736 } 6737 6738 // Don't add qualified variants of arrays. For one, they're not allowed 6739 // (the qualifier would sink to the element type), and for another, the 6740 // only overload situation where it matters is subscript or pointer +- int, 6741 // and those shouldn't have qualifier variants anyway. 6742 if (PointeeTy->isArrayType()) 6743 return true; 6744 6745 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6746 bool hasVolatile = VisibleQuals.hasVolatile(); 6747 bool hasRestrict = VisibleQuals.hasRestrict(); 6748 6749 // Iterate through all strict supersets of BaseCVR. 6750 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6751 if ((CVR | BaseCVR) != CVR) continue; 6752 // Skip over volatile if no volatile found anywhere in the types. 6753 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6754 6755 // Skip over restrict if no restrict found anywhere in the types, or if 6756 // the type cannot be restrict-qualified. 6757 if ((CVR & Qualifiers::Restrict) && 6758 (!hasRestrict || 6759 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6760 continue; 6761 6762 // Build qualified pointee type. 6763 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6764 6765 // Build qualified pointer type. 6766 QualType QPointerTy; 6767 if (!buildObjCPtr) 6768 QPointerTy = Context.getPointerType(QPointeeTy); 6769 else 6770 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6771 6772 // Insert qualified pointer type. 6773 PointerTypes.insert(QPointerTy); 6774 } 6775 6776 return true; 6777 } 6778 6779 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6780 /// to the set of pointer types along with any more-qualified variants of 6781 /// that type. For example, if @p Ty is "int const *", this routine 6782 /// will add "int const *", "int const volatile *", "int const 6783 /// restrict *", and "int const volatile restrict *" to the set of 6784 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6785 /// false otherwise. 6786 /// 6787 /// FIXME: what to do about extended qualifiers? 6788 bool 6789 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6790 QualType Ty) { 6791 // Insert this type. 6792 if (!MemberPointerTypes.insert(Ty).second) 6793 return false; 6794 6795 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6796 assert(PointerTy && "type was not a member pointer type!"); 6797 6798 QualType PointeeTy = PointerTy->getPointeeType(); 6799 // Don't add qualified variants of arrays. For one, they're not allowed 6800 // (the qualifier would sink to the element type), and for another, the 6801 // only overload situation where it matters is subscript or pointer +- int, 6802 // and those shouldn't have qualifier variants anyway. 6803 if (PointeeTy->isArrayType()) 6804 return true; 6805 const Type *ClassTy = PointerTy->getClass(); 6806 6807 // Iterate through all strict supersets of the pointee type's CVR 6808 // qualifiers. 6809 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6810 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6811 if ((CVR | BaseCVR) != CVR) continue; 6812 6813 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6814 MemberPointerTypes.insert( 6815 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6816 } 6817 6818 return true; 6819 } 6820 6821 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6822 /// Ty can be implicit converted to the given set of @p Types. We're 6823 /// primarily interested in pointer types and enumeration types. We also 6824 /// take member pointer types, for the conditional operator. 6825 /// AllowUserConversions is true if we should look at the conversion 6826 /// functions of a class type, and AllowExplicitConversions if we 6827 /// should also include the explicit conversion functions of a class 6828 /// type. 6829 void 6830 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6831 SourceLocation Loc, 6832 bool AllowUserConversions, 6833 bool AllowExplicitConversions, 6834 const Qualifiers &VisibleQuals) { 6835 // Only deal with canonical types. 6836 Ty = Context.getCanonicalType(Ty); 6837 6838 // Look through reference types; they aren't part of the type of an 6839 // expression for the purposes of conversions. 6840 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6841 Ty = RefTy->getPointeeType(); 6842 6843 // If we're dealing with an array type, decay to the pointer. 6844 if (Ty->isArrayType()) 6845 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6846 6847 // Otherwise, we don't care about qualifiers on the type. 6848 Ty = Ty.getLocalUnqualifiedType(); 6849 6850 // Flag if we ever add a non-record type. 6851 const RecordType *TyRec = Ty->getAs<RecordType>(); 6852 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6853 6854 // Flag if we encounter an arithmetic type. 6855 HasArithmeticOrEnumeralTypes = 6856 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6857 6858 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6859 PointerTypes.insert(Ty); 6860 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6861 // Insert our type, and its more-qualified variants, into the set 6862 // of types. 6863 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6864 return; 6865 } else if (Ty->isMemberPointerType()) { 6866 // Member pointers are far easier, since the pointee can't be converted. 6867 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6868 return; 6869 } else if (Ty->isEnumeralType()) { 6870 HasArithmeticOrEnumeralTypes = true; 6871 EnumerationTypes.insert(Ty); 6872 } else if (Ty->isVectorType()) { 6873 // We treat vector types as arithmetic types in many contexts as an 6874 // extension. 6875 HasArithmeticOrEnumeralTypes = true; 6876 VectorTypes.insert(Ty); 6877 } else if (Ty->isNullPtrType()) { 6878 HasNullPtrType = true; 6879 } else if (AllowUserConversions && TyRec) { 6880 // No conversion functions in incomplete types. 6881 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6882 return; 6883 6884 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6885 std::pair<CXXRecordDecl::conversion_iterator, 6886 CXXRecordDecl::conversion_iterator> 6887 Conversions = ClassDecl->getVisibleConversionFunctions(); 6888 for (CXXRecordDecl::conversion_iterator 6889 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6890 NamedDecl *D = I.getDecl(); 6891 if (isa<UsingShadowDecl>(D)) 6892 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6893 6894 // Skip conversion function templates; they don't tell us anything 6895 // about which builtin types we can convert to. 6896 if (isa<FunctionTemplateDecl>(D)) 6897 continue; 6898 6899 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6900 if (AllowExplicitConversions || !Conv->isExplicit()) { 6901 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6902 VisibleQuals); 6903 } 6904 } 6905 } 6906 } 6907 6908 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6909 /// the volatile- and non-volatile-qualified assignment operators for the 6910 /// given type to the candidate set. 6911 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6912 QualType T, 6913 ArrayRef<Expr *> Args, 6914 OverloadCandidateSet &CandidateSet) { 6915 QualType ParamTypes[2]; 6916 6917 // T& operator=(T&, T) 6918 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6919 ParamTypes[1] = T; 6920 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6921 /*IsAssignmentOperator=*/true); 6922 6923 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6924 // volatile T& operator=(volatile T&, T) 6925 ParamTypes[0] 6926 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6927 ParamTypes[1] = T; 6928 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6929 /*IsAssignmentOperator=*/true); 6930 } 6931 } 6932 6933 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6934 /// if any, found in visible type conversion functions found in ArgExpr's type. 6935 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6936 Qualifiers VRQuals; 6937 const RecordType *TyRec; 6938 if (const MemberPointerType *RHSMPType = 6939 ArgExpr->getType()->getAs<MemberPointerType>()) 6940 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6941 else 6942 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6943 if (!TyRec) { 6944 // Just to be safe, assume the worst case. 6945 VRQuals.addVolatile(); 6946 VRQuals.addRestrict(); 6947 return VRQuals; 6948 } 6949 6950 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6951 if (!ClassDecl->hasDefinition()) 6952 return VRQuals; 6953 6954 std::pair<CXXRecordDecl::conversion_iterator, 6955 CXXRecordDecl::conversion_iterator> 6956 Conversions = ClassDecl->getVisibleConversionFunctions(); 6957 6958 for (CXXRecordDecl::conversion_iterator 6959 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6960 NamedDecl *D = I.getDecl(); 6961 if (isa<UsingShadowDecl>(D)) 6962 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6963 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6964 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6965 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6966 CanTy = ResTypeRef->getPointeeType(); 6967 // Need to go down the pointer/mempointer chain and add qualifiers 6968 // as see them. 6969 bool done = false; 6970 while (!done) { 6971 if (CanTy.isRestrictQualified()) 6972 VRQuals.addRestrict(); 6973 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6974 CanTy = ResTypePtr->getPointeeType(); 6975 else if (const MemberPointerType *ResTypeMPtr = 6976 CanTy->getAs<MemberPointerType>()) 6977 CanTy = ResTypeMPtr->getPointeeType(); 6978 else 6979 done = true; 6980 if (CanTy.isVolatileQualified()) 6981 VRQuals.addVolatile(); 6982 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6983 return VRQuals; 6984 } 6985 } 6986 } 6987 return VRQuals; 6988 } 6989 6990 namespace { 6991 6992 /// \brief Helper class to manage the addition of builtin operator overload 6993 /// candidates. It provides shared state and utility methods used throughout 6994 /// the process, as well as a helper method to add each group of builtin 6995 /// operator overloads from the standard to a candidate set. 6996 class BuiltinOperatorOverloadBuilder { 6997 // Common instance state available to all overload candidate addition methods. 6998 Sema &S; 6999 ArrayRef<Expr *> Args; 7000 Qualifiers VisibleTypeConversionsQuals; 7001 bool HasArithmeticOrEnumeralCandidateType; 7002 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7003 OverloadCandidateSet &CandidateSet; 7004 7005 // Define some constants used to index and iterate over the arithemetic types 7006 // provided via the getArithmeticType() method below. 7007 // The "promoted arithmetic types" are the arithmetic 7008 // types are that preserved by promotion (C++ [over.built]p2). 7009 static const unsigned FirstIntegralType = 3; 7010 static const unsigned LastIntegralType = 20; 7011 static const unsigned FirstPromotedIntegralType = 3, 7012 LastPromotedIntegralType = 11; 7013 static const unsigned FirstPromotedArithmeticType = 0, 7014 LastPromotedArithmeticType = 11; 7015 static const unsigned NumArithmeticTypes = 20; 7016 7017 /// \brief Get the canonical type for a given arithmetic type index. 7018 CanQualType getArithmeticType(unsigned index) { 7019 assert(index < NumArithmeticTypes); 7020 static CanQualType ASTContext::* const 7021 ArithmeticTypes[NumArithmeticTypes] = { 7022 // Start of promoted types. 7023 &ASTContext::FloatTy, 7024 &ASTContext::DoubleTy, 7025 &ASTContext::LongDoubleTy, 7026 7027 // Start of integral types. 7028 &ASTContext::IntTy, 7029 &ASTContext::LongTy, 7030 &ASTContext::LongLongTy, 7031 &ASTContext::Int128Ty, 7032 &ASTContext::UnsignedIntTy, 7033 &ASTContext::UnsignedLongTy, 7034 &ASTContext::UnsignedLongLongTy, 7035 &ASTContext::UnsignedInt128Ty, 7036 // End of promoted types. 7037 7038 &ASTContext::BoolTy, 7039 &ASTContext::CharTy, 7040 &ASTContext::WCharTy, 7041 &ASTContext::Char16Ty, 7042 &ASTContext::Char32Ty, 7043 &ASTContext::SignedCharTy, 7044 &ASTContext::ShortTy, 7045 &ASTContext::UnsignedCharTy, 7046 &ASTContext::UnsignedShortTy, 7047 // End of integral types. 7048 // FIXME: What about complex? What about half? 7049 }; 7050 return S.Context.*ArithmeticTypes[index]; 7051 } 7052 7053 /// \brief Gets the canonical type resulting from the usual arithemetic 7054 /// converions for the given arithmetic types. 7055 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7056 // Accelerator table for performing the usual arithmetic conversions. 7057 // The rules are basically: 7058 // - if either is floating-point, use the wider floating-point 7059 // - if same signedness, use the higher rank 7060 // - if same size, use unsigned of the higher rank 7061 // - use the larger type 7062 // These rules, together with the axiom that higher ranks are 7063 // never smaller, are sufficient to precompute all of these results 7064 // *except* when dealing with signed types of higher rank. 7065 // (we could precompute SLL x UI for all known platforms, but it's 7066 // better not to make any assumptions). 7067 // We assume that int128 has a higher rank than long long on all platforms. 7068 enum PromotedType { 7069 Dep=-1, 7070 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7071 }; 7072 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7073 [LastPromotedArithmeticType] = { 7074 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7075 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7076 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7077 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7078 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7079 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7080 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7081 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7082 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7083 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7084 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7085 }; 7086 7087 assert(L < LastPromotedArithmeticType); 7088 assert(R < LastPromotedArithmeticType); 7089 int Idx = ConversionsTable[L][R]; 7090 7091 // Fast path: the table gives us a concrete answer. 7092 if (Idx != Dep) return getArithmeticType(Idx); 7093 7094 // Slow path: we need to compare widths. 7095 // An invariant is that the signed type has higher rank. 7096 CanQualType LT = getArithmeticType(L), 7097 RT = getArithmeticType(R); 7098 unsigned LW = S.Context.getIntWidth(LT), 7099 RW = S.Context.getIntWidth(RT); 7100 7101 // If they're different widths, use the signed type. 7102 if (LW > RW) return LT; 7103 else if (LW < RW) return RT; 7104 7105 // Otherwise, use the unsigned type of the signed type's rank. 7106 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7107 assert(L == SLL || R == SLL); 7108 return S.Context.UnsignedLongLongTy; 7109 } 7110 7111 /// \brief Helper method to factor out the common pattern of adding overloads 7112 /// for '++' and '--' builtin operators. 7113 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7114 bool HasVolatile, 7115 bool HasRestrict) { 7116 QualType ParamTypes[2] = { 7117 S.Context.getLValueReferenceType(CandidateTy), 7118 S.Context.IntTy 7119 }; 7120 7121 // Non-volatile version. 7122 if (Args.size() == 1) 7123 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7124 else 7125 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7126 7127 // Use a heuristic to reduce number of builtin candidates in the set: 7128 // add volatile version only if there are conversions to a volatile type. 7129 if (HasVolatile) { 7130 ParamTypes[0] = 7131 S.Context.getLValueReferenceType( 7132 S.Context.getVolatileType(CandidateTy)); 7133 if (Args.size() == 1) 7134 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7135 else 7136 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7137 } 7138 7139 // Add restrict version only if there are conversions to a restrict type 7140 // and our candidate type is a non-restrict-qualified pointer. 7141 if (HasRestrict && CandidateTy->isAnyPointerType() && 7142 !CandidateTy.isRestrictQualified()) { 7143 ParamTypes[0] 7144 = S.Context.getLValueReferenceType( 7145 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7146 if (Args.size() == 1) 7147 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7148 else 7149 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7150 7151 if (HasVolatile) { 7152 ParamTypes[0] 7153 = S.Context.getLValueReferenceType( 7154 S.Context.getCVRQualifiedType(CandidateTy, 7155 (Qualifiers::Volatile | 7156 Qualifiers::Restrict))); 7157 if (Args.size() == 1) 7158 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7159 else 7160 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7161 } 7162 } 7163 7164 } 7165 7166 public: 7167 BuiltinOperatorOverloadBuilder( 7168 Sema &S, ArrayRef<Expr *> Args, 7169 Qualifiers VisibleTypeConversionsQuals, 7170 bool HasArithmeticOrEnumeralCandidateType, 7171 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7172 OverloadCandidateSet &CandidateSet) 7173 : S(S), Args(Args), 7174 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7175 HasArithmeticOrEnumeralCandidateType( 7176 HasArithmeticOrEnumeralCandidateType), 7177 CandidateTypes(CandidateTypes), 7178 CandidateSet(CandidateSet) { 7179 // Validate some of our static helper constants in debug builds. 7180 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7181 "Invalid first promoted integral type"); 7182 assert(getArithmeticType(LastPromotedIntegralType - 1) 7183 == S.Context.UnsignedInt128Ty && 7184 "Invalid last promoted integral type"); 7185 assert(getArithmeticType(FirstPromotedArithmeticType) 7186 == S.Context.FloatTy && 7187 "Invalid first promoted arithmetic type"); 7188 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7189 == S.Context.UnsignedInt128Ty && 7190 "Invalid last promoted arithmetic type"); 7191 } 7192 7193 // C++ [over.built]p3: 7194 // 7195 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7196 // is either volatile or empty, there exist candidate operator 7197 // functions of the form 7198 // 7199 // VQ T& operator++(VQ T&); 7200 // T operator++(VQ T&, int); 7201 // 7202 // C++ [over.built]p4: 7203 // 7204 // For every pair (T, VQ), where T is an arithmetic type other 7205 // than bool, and VQ is either volatile or empty, there exist 7206 // candidate operator functions of the form 7207 // 7208 // VQ T& operator--(VQ T&); 7209 // T operator--(VQ T&, int); 7210 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7211 if (!HasArithmeticOrEnumeralCandidateType) 7212 return; 7213 7214 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7215 Arith < NumArithmeticTypes; ++Arith) { 7216 addPlusPlusMinusMinusStyleOverloads( 7217 getArithmeticType(Arith), 7218 VisibleTypeConversionsQuals.hasVolatile(), 7219 VisibleTypeConversionsQuals.hasRestrict()); 7220 } 7221 } 7222 7223 // C++ [over.built]p5: 7224 // 7225 // For every pair (T, VQ), where T is a cv-qualified or 7226 // cv-unqualified object type, and VQ is either volatile or 7227 // empty, there exist candidate operator functions of the form 7228 // 7229 // T*VQ& operator++(T*VQ&); 7230 // T*VQ& operator--(T*VQ&); 7231 // T* operator++(T*VQ&, int); 7232 // T* operator--(T*VQ&, int); 7233 void addPlusPlusMinusMinusPointerOverloads() { 7234 for (BuiltinCandidateTypeSet::iterator 7235 Ptr = CandidateTypes[0].pointer_begin(), 7236 PtrEnd = CandidateTypes[0].pointer_end(); 7237 Ptr != PtrEnd; ++Ptr) { 7238 // Skip pointer types that aren't pointers to object types. 7239 if (!(*Ptr)->getPointeeType()->isObjectType()) 7240 continue; 7241 7242 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7243 (!(*Ptr).isVolatileQualified() && 7244 VisibleTypeConversionsQuals.hasVolatile()), 7245 (!(*Ptr).isRestrictQualified() && 7246 VisibleTypeConversionsQuals.hasRestrict())); 7247 } 7248 } 7249 7250 // C++ [over.built]p6: 7251 // For every cv-qualified or cv-unqualified object type T, there 7252 // exist candidate operator functions of the form 7253 // 7254 // T& operator*(T*); 7255 // 7256 // C++ [over.built]p7: 7257 // For every function type T that does not have cv-qualifiers or a 7258 // ref-qualifier, there exist candidate operator functions of the form 7259 // T& operator*(T*); 7260 void addUnaryStarPointerOverloads() { 7261 for (BuiltinCandidateTypeSet::iterator 7262 Ptr = CandidateTypes[0].pointer_begin(), 7263 PtrEnd = CandidateTypes[0].pointer_end(); 7264 Ptr != PtrEnd; ++Ptr) { 7265 QualType ParamTy = *Ptr; 7266 QualType PointeeTy = ParamTy->getPointeeType(); 7267 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7268 continue; 7269 7270 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7271 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7272 continue; 7273 7274 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7275 &ParamTy, Args, CandidateSet); 7276 } 7277 } 7278 7279 // C++ [over.built]p9: 7280 // For every promoted arithmetic type T, there exist candidate 7281 // operator functions of the form 7282 // 7283 // T operator+(T); 7284 // T operator-(T); 7285 void addUnaryPlusOrMinusArithmeticOverloads() { 7286 if (!HasArithmeticOrEnumeralCandidateType) 7287 return; 7288 7289 for (unsigned Arith = FirstPromotedArithmeticType; 7290 Arith < LastPromotedArithmeticType; ++Arith) { 7291 QualType ArithTy = getArithmeticType(Arith); 7292 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7293 } 7294 7295 // Extension: We also add these operators for vector types. 7296 for (BuiltinCandidateTypeSet::iterator 7297 Vec = CandidateTypes[0].vector_begin(), 7298 VecEnd = CandidateTypes[0].vector_end(); 7299 Vec != VecEnd; ++Vec) { 7300 QualType VecTy = *Vec; 7301 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7302 } 7303 } 7304 7305 // C++ [over.built]p8: 7306 // For every type T, there exist candidate operator functions of 7307 // the form 7308 // 7309 // T* operator+(T*); 7310 void addUnaryPlusPointerOverloads() { 7311 for (BuiltinCandidateTypeSet::iterator 7312 Ptr = CandidateTypes[0].pointer_begin(), 7313 PtrEnd = CandidateTypes[0].pointer_end(); 7314 Ptr != PtrEnd; ++Ptr) { 7315 QualType ParamTy = *Ptr; 7316 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7317 } 7318 } 7319 7320 // C++ [over.built]p10: 7321 // For every promoted integral type T, there exist candidate 7322 // operator functions of the form 7323 // 7324 // T operator~(T); 7325 void addUnaryTildePromotedIntegralOverloads() { 7326 if (!HasArithmeticOrEnumeralCandidateType) 7327 return; 7328 7329 for (unsigned Int = FirstPromotedIntegralType; 7330 Int < LastPromotedIntegralType; ++Int) { 7331 QualType IntTy = getArithmeticType(Int); 7332 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7333 } 7334 7335 // Extension: We also add this operator for vector types. 7336 for (BuiltinCandidateTypeSet::iterator 7337 Vec = CandidateTypes[0].vector_begin(), 7338 VecEnd = CandidateTypes[0].vector_end(); 7339 Vec != VecEnd; ++Vec) { 7340 QualType VecTy = *Vec; 7341 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7342 } 7343 } 7344 7345 // C++ [over.match.oper]p16: 7346 // For every pointer to member type T, there exist candidate operator 7347 // functions of the form 7348 // 7349 // bool operator==(T,T); 7350 // bool operator!=(T,T); 7351 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7352 /// Set of (canonical) types that we've already handled. 7353 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7354 7355 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7356 for (BuiltinCandidateTypeSet::iterator 7357 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7358 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7359 MemPtr != MemPtrEnd; 7360 ++MemPtr) { 7361 // Don't add the same builtin candidate twice. 7362 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7363 continue; 7364 7365 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7366 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7367 } 7368 } 7369 } 7370 7371 // C++ [over.built]p15: 7372 // 7373 // For every T, where T is an enumeration type, a pointer type, or 7374 // std::nullptr_t, there exist candidate operator functions of the form 7375 // 7376 // bool operator<(T, T); 7377 // bool operator>(T, T); 7378 // bool operator<=(T, T); 7379 // bool operator>=(T, T); 7380 // bool operator==(T, T); 7381 // bool operator!=(T, T); 7382 void addRelationalPointerOrEnumeralOverloads() { 7383 // C++ [over.match.oper]p3: 7384 // [...]the built-in candidates include all of the candidate operator 7385 // functions defined in 13.6 that, compared to the given operator, [...] 7386 // do not have the same parameter-type-list as any non-template non-member 7387 // candidate. 7388 // 7389 // Note that in practice, this only affects enumeration types because there 7390 // aren't any built-in candidates of record type, and a user-defined operator 7391 // must have an operand of record or enumeration type. Also, the only other 7392 // overloaded operator with enumeration arguments, operator=, 7393 // cannot be overloaded for enumeration types, so this is the only place 7394 // where we must suppress candidates like this. 7395 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7396 UserDefinedBinaryOperators; 7397 7398 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7399 if (CandidateTypes[ArgIdx].enumeration_begin() != 7400 CandidateTypes[ArgIdx].enumeration_end()) { 7401 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7402 CEnd = CandidateSet.end(); 7403 C != CEnd; ++C) { 7404 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7405 continue; 7406 7407 if (C->Function->isFunctionTemplateSpecialization()) 7408 continue; 7409 7410 QualType FirstParamType = 7411 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7412 QualType SecondParamType = 7413 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7414 7415 // Skip if either parameter isn't of enumeral type. 7416 if (!FirstParamType->isEnumeralType() || 7417 !SecondParamType->isEnumeralType()) 7418 continue; 7419 7420 // Add this operator to the set of known user-defined operators. 7421 UserDefinedBinaryOperators.insert( 7422 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7423 S.Context.getCanonicalType(SecondParamType))); 7424 } 7425 } 7426 } 7427 7428 /// Set of (canonical) types that we've already handled. 7429 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7430 7431 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7432 for (BuiltinCandidateTypeSet::iterator 7433 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7434 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7435 Ptr != PtrEnd; ++Ptr) { 7436 // Don't add the same builtin candidate twice. 7437 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7438 continue; 7439 7440 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7441 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7442 } 7443 for (BuiltinCandidateTypeSet::iterator 7444 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7445 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7446 Enum != EnumEnd; ++Enum) { 7447 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7448 7449 // Don't add the same builtin candidate twice, or if a user defined 7450 // candidate exists. 7451 if (!AddedTypes.insert(CanonType).second || 7452 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7453 CanonType))) 7454 continue; 7455 7456 QualType ParamTypes[2] = { *Enum, *Enum }; 7457 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7458 } 7459 7460 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7461 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7462 if (AddedTypes.insert(NullPtrTy).second && 7463 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7464 NullPtrTy))) { 7465 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7466 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7467 CandidateSet); 7468 } 7469 } 7470 } 7471 } 7472 7473 // C++ [over.built]p13: 7474 // 7475 // For every cv-qualified or cv-unqualified object type T 7476 // there exist candidate operator functions of the form 7477 // 7478 // T* operator+(T*, ptrdiff_t); 7479 // T& operator[](T*, ptrdiff_t); [BELOW] 7480 // T* operator-(T*, ptrdiff_t); 7481 // T* operator+(ptrdiff_t, T*); 7482 // T& operator[](ptrdiff_t, T*); [BELOW] 7483 // 7484 // C++ [over.built]p14: 7485 // 7486 // For every T, where T is a pointer to object type, there 7487 // exist candidate operator functions of the form 7488 // 7489 // ptrdiff_t operator-(T, T); 7490 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7491 /// Set of (canonical) types that we've already handled. 7492 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7493 7494 for (int Arg = 0; Arg < 2; ++Arg) { 7495 QualType AsymetricParamTypes[2] = { 7496 S.Context.getPointerDiffType(), 7497 S.Context.getPointerDiffType(), 7498 }; 7499 for (BuiltinCandidateTypeSet::iterator 7500 Ptr = CandidateTypes[Arg].pointer_begin(), 7501 PtrEnd = CandidateTypes[Arg].pointer_end(); 7502 Ptr != PtrEnd; ++Ptr) { 7503 QualType PointeeTy = (*Ptr)->getPointeeType(); 7504 if (!PointeeTy->isObjectType()) 7505 continue; 7506 7507 AsymetricParamTypes[Arg] = *Ptr; 7508 if (Arg == 0 || Op == OO_Plus) { 7509 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7510 // T* operator+(ptrdiff_t, T*); 7511 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7512 } 7513 if (Op == OO_Minus) { 7514 // ptrdiff_t operator-(T, T); 7515 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7516 continue; 7517 7518 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7519 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7520 Args, CandidateSet); 7521 } 7522 } 7523 } 7524 } 7525 7526 // C++ [over.built]p12: 7527 // 7528 // For every pair of promoted arithmetic types L and R, there 7529 // exist candidate operator functions of the form 7530 // 7531 // LR operator*(L, R); 7532 // LR operator/(L, R); 7533 // LR operator+(L, R); 7534 // LR operator-(L, R); 7535 // bool operator<(L, R); 7536 // bool operator>(L, R); 7537 // bool operator<=(L, R); 7538 // bool operator>=(L, R); 7539 // bool operator==(L, R); 7540 // bool operator!=(L, R); 7541 // 7542 // where LR is the result of the usual arithmetic conversions 7543 // between types L and R. 7544 // 7545 // C++ [over.built]p24: 7546 // 7547 // For every pair of promoted arithmetic types L and R, there exist 7548 // candidate operator functions of the form 7549 // 7550 // LR operator?(bool, L, R); 7551 // 7552 // where LR is the result of the usual arithmetic conversions 7553 // between types L and R. 7554 // Our candidates ignore the first parameter. 7555 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7556 if (!HasArithmeticOrEnumeralCandidateType) 7557 return; 7558 7559 for (unsigned Left = FirstPromotedArithmeticType; 7560 Left < LastPromotedArithmeticType; ++Left) { 7561 for (unsigned Right = FirstPromotedArithmeticType; 7562 Right < LastPromotedArithmeticType; ++Right) { 7563 QualType LandR[2] = { getArithmeticType(Left), 7564 getArithmeticType(Right) }; 7565 QualType Result = 7566 isComparison ? S.Context.BoolTy 7567 : getUsualArithmeticConversions(Left, Right); 7568 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7569 } 7570 } 7571 7572 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7573 // conditional operator for vector types. 7574 for (BuiltinCandidateTypeSet::iterator 7575 Vec1 = CandidateTypes[0].vector_begin(), 7576 Vec1End = CandidateTypes[0].vector_end(); 7577 Vec1 != Vec1End; ++Vec1) { 7578 for (BuiltinCandidateTypeSet::iterator 7579 Vec2 = CandidateTypes[1].vector_begin(), 7580 Vec2End = CandidateTypes[1].vector_end(); 7581 Vec2 != Vec2End; ++Vec2) { 7582 QualType LandR[2] = { *Vec1, *Vec2 }; 7583 QualType Result = S.Context.BoolTy; 7584 if (!isComparison) { 7585 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7586 Result = *Vec1; 7587 else 7588 Result = *Vec2; 7589 } 7590 7591 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7592 } 7593 } 7594 } 7595 7596 // C++ [over.built]p17: 7597 // 7598 // For every pair of promoted integral types L and R, there 7599 // exist candidate operator functions of the form 7600 // 7601 // LR operator%(L, R); 7602 // LR operator&(L, R); 7603 // LR operator^(L, R); 7604 // LR operator|(L, R); 7605 // L operator<<(L, R); 7606 // L operator>>(L, R); 7607 // 7608 // where LR is the result of the usual arithmetic conversions 7609 // between types L and R. 7610 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7611 if (!HasArithmeticOrEnumeralCandidateType) 7612 return; 7613 7614 for (unsigned Left = FirstPromotedIntegralType; 7615 Left < LastPromotedIntegralType; ++Left) { 7616 for (unsigned Right = FirstPromotedIntegralType; 7617 Right < LastPromotedIntegralType; ++Right) { 7618 QualType LandR[2] = { getArithmeticType(Left), 7619 getArithmeticType(Right) }; 7620 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7621 ? LandR[0] 7622 : getUsualArithmeticConversions(Left, Right); 7623 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7624 } 7625 } 7626 } 7627 7628 // C++ [over.built]p20: 7629 // 7630 // For every pair (T, VQ), where T is an enumeration or 7631 // pointer to member type and VQ is either volatile or 7632 // empty, there exist candidate operator functions of the form 7633 // 7634 // VQ T& operator=(VQ T&, T); 7635 void addAssignmentMemberPointerOrEnumeralOverloads() { 7636 /// Set of (canonical) types that we've already handled. 7637 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7638 7639 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7640 for (BuiltinCandidateTypeSet::iterator 7641 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7642 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7643 Enum != EnumEnd; ++Enum) { 7644 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7645 continue; 7646 7647 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7648 } 7649 7650 for (BuiltinCandidateTypeSet::iterator 7651 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7652 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7653 MemPtr != MemPtrEnd; ++MemPtr) { 7654 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7655 continue; 7656 7657 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7658 } 7659 } 7660 } 7661 7662 // C++ [over.built]p19: 7663 // 7664 // For every pair (T, VQ), where T is any type and VQ is either 7665 // volatile or empty, there exist candidate operator functions 7666 // of the form 7667 // 7668 // T*VQ& operator=(T*VQ&, T*); 7669 // 7670 // C++ [over.built]p21: 7671 // 7672 // For every pair (T, VQ), where T is a cv-qualified or 7673 // cv-unqualified object type and VQ is either volatile or 7674 // empty, there exist candidate operator functions of the form 7675 // 7676 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7677 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7678 void addAssignmentPointerOverloads(bool isEqualOp) { 7679 /// Set of (canonical) types that we've already handled. 7680 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7681 7682 for (BuiltinCandidateTypeSet::iterator 7683 Ptr = CandidateTypes[0].pointer_begin(), 7684 PtrEnd = CandidateTypes[0].pointer_end(); 7685 Ptr != PtrEnd; ++Ptr) { 7686 // If this is operator=, keep track of the builtin candidates we added. 7687 if (isEqualOp) 7688 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7689 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7690 continue; 7691 7692 // non-volatile version 7693 QualType ParamTypes[2] = { 7694 S.Context.getLValueReferenceType(*Ptr), 7695 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7696 }; 7697 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7698 /*IsAssigmentOperator=*/ isEqualOp); 7699 7700 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7701 VisibleTypeConversionsQuals.hasVolatile(); 7702 if (NeedVolatile) { 7703 // volatile version 7704 ParamTypes[0] = 7705 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7706 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7707 /*IsAssigmentOperator=*/isEqualOp); 7708 } 7709 7710 if (!(*Ptr).isRestrictQualified() && 7711 VisibleTypeConversionsQuals.hasRestrict()) { 7712 // restrict version 7713 ParamTypes[0] 7714 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7715 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7716 /*IsAssigmentOperator=*/isEqualOp); 7717 7718 if (NeedVolatile) { 7719 // volatile restrict version 7720 ParamTypes[0] 7721 = S.Context.getLValueReferenceType( 7722 S.Context.getCVRQualifiedType(*Ptr, 7723 (Qualifiers::Volatile | 7724 Qualifiers::Restrict))); 7725 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7726 /*IsAssigmentOperator=*/isEqualOp); 7727 } 7728 } 7729 } 7730 7731 if (isEqualOp) { 7732 for (BuiltinCandidateTypeSet::iterator 7733 Ptr = CandidateTypes[1].pointer_begin(), 7734 PtrEnd = CandidateTypes[1].pointer_end(); 7735 Ptr != PtrEnd; ++Ptr) { 7736 // Make sure we don't add the same candidate twice. 7737 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7738 continue; 7739 7740 QualType ParamTypes[2] = { 7741 S.Context.getLValueReferenceType(*Ptr), 7742 *Ptr, 7743 }; 7744 7745 // non-volatile version 7746 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7747 /*IsAssigmentOperator=*/true); 7748 7749 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7750 VisibleTypeConversionsQuals.hasVolatile(); 7751 if (NeedVolatile) { 7752 // volatile version 7753 ParamTypes[0] = 7754 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7755 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7756 /*IsAssigmentOperator=*/true); 7757 } 7758 7759 if (!(*Ptr).isRestrictQualified() && 7760 VisibleTypeConversionsQuals.hasRestrict()) { 7761 // restrict version 7762 ParamTypes[0] 7763 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7764 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7765 /*IsAssigmentOperator=*/true); 7766 7767 if (NeedVolatile) { 7768 // volatile restrict version 7769 ParamTypes[0] 7770 = S.Context.getLValueReferenceType( 7771 S.Context.getCVRQualifiedType(*Ptr, 7772 (Qualifiers::Volatile | 7773 Qualifiers::Restrict))); 7774 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7775 /*IsAssigmentOperator=*/true); 7776 } 7777 } 7778 } 7779 } 7780 } 7781 7782 // C++ [over.built]p18: 7783 // 7784 // For every triple (L, VQ, R), where L is an arithmetic type, 7785 // VQ is either volatile or empty, and R is a promoted 7786 // arithmetic type, there exist candidate operator functions of 7787 // the form 7788 // 7789 // VQ L& operator=(VQ L&, R); 7790 // VQ L& operator*=(VQ L&, R); 7791 // VQ L& operator/=(VQ L&, R); 7792 // VQ L& operator+=(VQ L&, R); 7793 // VQ L& operator-=(VQ L&, R); 7794 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7795 if (!HasArithmeticOrEnumeralCandidateType) 7796 return; 7797 7798 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7799 for (unsigned Right = FirstPromotedArithmeticType; 7800 Right < LastPromotedArithmeticType; ++Right) { 7801 QualType ParamTypes[2]; 7802 ParamTypes[1] = getArithmeticType(Right); 7803 7804 // Add this built-in operator as a candidate (VQ is empty). 7805 ParamTypes[0] = 7806 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7807 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7808 /*IsAssigmentOperator=*/isEqualOp); 7809 7810 // Add this built-in operator as a candidate (VQ is 'volatile'). 7811 if (VisibleTypeConversionsQuals.hasVolatile()) { 7812 ParamTypes[0] = 7813 S.Context.getVolatileType(getArithmeticType(Left)); 7814 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7815 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7816 /*IsAssigmentOperator=*/isEqualOp); 7817 } 7818 } 7819 } 7820 7821 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7822 for (BuiltinCandidateTypeSet::iterator 7823 Vec1 = CandidateTypes[0].vector_begin(), 7824 Vec1End = CandidateTypes[0].vector_end(); 7825 Vec1 != Vec1End; ++Vec1) { 7826 for (BuiltinCandidateTypeSet::iterator 7827 Vec2 = CandidateTypes[1].vector_begin(), 7828 Vec2End = CandidateTypes[1].vector_end(); 7829 Vec2 != Vec2End; ++Vec2) { 7830 QualType ParamTypes[2]; 7831 ParamTypes[1] = *Vec2; 7832 // Add this built-in operator as a candidate (VQ is empty). 7833 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7834 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7835 /*IsAssigmentOperator=*/isEqualOp); 7836 7837 // Add this built-in operator as a candidate (VQ is 'volatile'). 7838 if (VisibleTypeConversionsQuals.hasVolatile()) { 7839 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7840 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7841 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7842 /*IsAssigmentOperator=*/isEqualOp); 7843 } 7844 } 7845 } 7846 } 7847 7848 // C++ [over.built]p22: 7849 // 7850 // For every triple (L, VQ, R), where L is an integral type, VQ 7851 // is either volatile or empty, and R is a promoted integral 7852 // type, there exist candidate operator functions of the form 7853 // 7854 // VQ L& operator%=(VQ L&, R); 7855 // VQ L& operator<<=(VQ L&, R); 7856 // VQ L& operator>>=(VQ L&, R); 7857 // VQ L& operator&=(VQ L&, R); 7858 // VQ L& operator^=(VQ L&, R); 7859 // VQ L& operator|=(VQ L&, R); 7860 void addAssignmentIntegralOverloads() { 7861 if (!HasArithmeticOrEnumeralCandidateType) 7862 return; 7863 7864 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7865 for (unsigned Right = FirstPromotedIntegralType; 7866 Right < LastPromotedIntegralType; ++Right) { 7867 QualType ParamTypes[2]; 7868 ParamTypes[1] = getArithmeticType(Right); 7869 7870 // Add this built-in operator as a candidate (VQ is empty). 7871 ParamTypes[0] = 7872 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7873 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7874 if (VisibleTypeConversionsQuals.hasVolatile()) { 7875 // Add this built-in operator as a candidate (VQ is 'volatile'). 7876 ParamTypes[0] = getArithmeticType(Left); 7877 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7878 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7879 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7880 } 7881 } 7882 } 7883 } 7884 7885 // C++ [over.operator]p23: 7886 // 7887 // There also exist candidate operator functions of the form 7888 // 7889 // bool operator!(bool); 7890 // bool operator&&(bool, bool); 7891 // bool operator||(bool, bool); 7892 void addExclaimOverload() { 7893 QualType ParamTy = S.Context.BoolTy; 7894 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7895 /*IsAssignmentOperator=*/false, 7896 /*NumContextualBoolArguments=*/1); 7897 } 7898 void addAmpAmpOrPipePipeOverload() { 7899 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7900 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7901 /*IsAssignmentOperator=*/false, 7902 /*NumContextualBoolArguments=*/2); 7903 } 7904 7905 // C++ [over.built]p13: 7906 // 7907 // For every cv-qualified or cv-unqualified object type T there 7908 // exist candidate operator functions of the form 7909 // 7910 // T* operator+(T*, ptrdiff_t); [ABOVE] 7911 // T& operator[](T*, ptrdiff_t); 7912 // T* operator-(T*, ptrdiff_t); [ABOVE] 7913 // T* operator+(ptrdiff_t, T*); [ABOVE] 7914 // T& operator[](ptrdiff_t, T*); 7915 void addSubscriptOverloads() { 7916 for (BuiltinCandidateTypeSet::iterator 7917 Ptr = CandidateTypes[0].pointer_begin(), 7918 PtrEnd = CandidateTypes[0].pointer_end(); 7919 Ptr != PtrEnd; ++Ptr) { 7920 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7921 QualType PointeeType = (*Ptr)->getPointeeType(); 7922 if (!PointeeType->isObjectType()) 7923 continue; 7924 7925 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7926 7927 // T& operator[](T*, ptrdiff_t) 7928 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7929 } 7930 7931 for (BuiltinCandidateTypeSet::iterator 7932 Ptr = CandidateTypes[1].pointer_begin(), 7933 PtrEnd = CandidateTypes[1].pointer_end(); 7934 Ptr != PtrEnd; ++Ptr) { 7935 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7936 QualType PointeeType = (*Ptr)->getPointeeType(); 7937 if (!PointeeType->isObjectType()) 7938 continue; 7939 7940 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7941 7942 // T& operator[](ptrdiff_t, T*) 7943 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7944 } 7945 } 7946 7947 // C++ [over.built]p11: 7948 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7949 // C1 is the same type as C2 or is a derived class of C2, T is an object 7950 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7951 // there exist candidate operator functions of the form 7952 // 7953 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7954 // 7955 // where CV12 is the union of CV1 and CV2. 7956 void addArrowStarOverloads() { 7957 for (BuiltinCandidateTypeSet::iterator 7958 Ptr = CandidateTypes[0].pointer_begin(), 7959 PtrEnd = CandidateTypes[0].pointer_end(); 7960 Ptr != PtrEnd; ++Ptr) { 7961 QualType C1Ty = (*Ptr); 7962 QualType C1; 7963 QualifierCollector Q1; 7964 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7965 if (!isa<RecordType>(C1)) 7966 continue; 7967 // heuristic to reduce number of builtin candidates in the set. 7968 // Add volatile/restrict version only if there are conversions to a 7969 // volatile/restrict type. 7970 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7971 continue; 7972 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7973 continue; 7974 for (BuiltinCandidateTypeSet::iterator 7975 MemPtr = CandidateTypes[1].member_pointer_begin(), 7976 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7977 MemPtr != MemPtrEnd; ++MemPtr) { 7978 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7979 QualType C2 = QualType(mptr->getClass(), 0); 7980 C2 = C2.getUnqualifiedType(); 7981 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7982 break; 7983 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7984 // build CV12 T& 7985 QualType T = mptr->getPointeeType(); 7986 if (!VisibleTypeConversionsQuals.hasVolatile() && 7987 T.isVolatileQualified()) 7988 continue; 7989 if (!VisibleTypeConversionsQuals.hasRestrict() && 7990 T.isRestrictQualified()) 7991 continue; 7992 T = Q1.apply(S.Context, T); 7993 QualType ResultTy = S.Context.getLValueReferenceType(T); 7994 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7995 } 7996 } 7997 } 7998 7999 // Note that we don't consider the first argument, since it has been 8000 // contextually converted to bool long ago. The candidates below are 8001 // therefore added as binary. 8002 // 8003 // C++ [over.built]p25: 8004 // For every type T, where T is a pointer, pointer-to-member, or scoped 8005 // enumeration type, there exist candidate operator functions of the form 8006 // 8007 // T operator?(bool, T, T); 8008 // 8009 void addConditionalOperatorOverloads() { 8010 /// Set of (canonical) types that we've already handled. 8011 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8012 8013 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8014 for (BuiltinCandidateTypeSet::iterator 8015 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8016 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8017 Ptr != PtrEnd; ++Ptr) { 8018 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8019 continue; 8020 8021 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8022 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8023 } 8024 8025 for (BuiltinCandidateTypeSet::iterator 8026 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8027 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8028 MemPtr != MemPtrEnd; ++MemPtr) { 8029 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8030 continue; 8031 8032 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8033 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8034 } 8035 8036 if (S.getLangOpts().CPlusPlus11) { 8037 for (BuiltinCandidateTypeSet::iterator 8038 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8039 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8040 Enum != EnumEnd; ++Enum) { 8041 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8042 continue; 8043 8044 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8045 continue; 8046 8047 QualType ParamTypes[2] = { *Enum, *Enum }; 8048 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8049 } 8050 } 8051 } 8052 } 8053 }; 8054 8055 } // end anonymous namespace 8056 8057 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8058 /// operator overloads to the candidate set (C++ [over.built]), based 8059 /// on the operator @p Op and the arguments given. For example, if the 8060 /// operator is a binary '+', this routine might add "int 8061 /// operator+(int, int)" to cover integer addition. 8062 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8063 SourceLocation OpLoc, 8064 ArrayRef<Expr *> Args, 8065 OverloadCandidateSet &CandidateSet) { 8066 // Find all of the types that the arguments can convert to, but only 8067 // if the operator we're looking at has built-in operator candidates 8068 // that make use of these types. Also record whether we encounter non-record 8069 // candidate types or either arithmetic or enumeral candidate types. 8070 Qualifiers VisibleTypeConversionsQuals; 8071 VisibleTypeConversionsQuals.addConst(); 8072 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8073 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8074 8075 bool HasNonRecordCandidateType = false; 8076 bool HasArithmeticOrEnumeralCandidateType = false; 8077 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8078 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8079 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 8080 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8081 OpLoc, 8082 true, 8083 (Op == OO_Exclaim || 8084 Op == OO_AmpAmp || 8085 Op == OO_PipePipe), 8086 VisibleTypeConversionsQuals); 8087 HasNonRecordCandidateType = HasNonRecordCandidateType || 8088 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8089 HasArithmeticOrEnumeralCandidateType = 8090 HasArithmeticOrEnumeralCandidateType || 8091 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8092 } 8093 8094 // Exit early when no non-record types have been added to the candidate set 8095 // for any of the arguments to the operator. 8096 // 8097 // We can't exit early for !, ||, or &&, since there we have always have 8098 // 'bool' overloads. 8099 if (!HasNonRecordCandidateType && 8100 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8101 return; 8102 8103 // Setup an object to manage the common state for building overloads. 8104 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8105 VisibleTypeConversionsQuals, 8106 HasArithmeticOrEnumeralCandidateType, 8107 CandidateTypes, CandidateSet); 8108 8109 // Dispatch over the operation to add in only those overloads which apply. 8110 switch (Op) { 8111 case OO_None: 8112 case NUM_OVERLOADED_OPERATORS: 8113 llvm_unreachable("Expected an overloaded operator"); 8114 8115 case OO_New: 8116 case OO_Delete: 8117 case OO_Array_New: 8118 case OO_Array_Delete: 8119 case OO_Call: 8120 llvm_unreachable( 8121 "Special operators don't use AddBuiltinOperatorCandidates"); 8122 8123 case OO_Comma: 8124 case OO_Arrow: 8125 // C++ [over.match.oper]p3: 8126 // -- For the operator ',', the unary operator '&', or the 8127 // operator '->', the built-in candidates set is empty. 8128 break; 8129 8130 case OO_Plus: // '+' is either unary or binary 8131 if (Args.size() == 1) 8132 OpBuilder.addUnaryPlusPointerOverloads(); 8133 // Fall through. 8134 8135 case OO_Minus: // '-' is either unary or binary 8136 if (Args.size() == 1) { 8137 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8138 } else { 8139 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8140 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8141 } 8142 break; 8143 8144 case OO_Star: // '*' is either unary or binary 8145 if (Args.size() == 1) 8146 OpBuilder.addUnaryStarPointerOverloads(); 8147 else 8148 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8149 break; 8150 8151 case OO_Slash: 8152 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8153 break; 8154 8155 case OO_PlusPlus: 8156 case OO_MinusMinus: 8157 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8158 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8159 break; 8160 8161 case OO_EqualEqual: 8162 case OO_ExclaimEqual: 8163 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8164 // Fall through. 8165 8166 case OO_Less: 8167 case OO_Greater: 8168 case OO_LessEqual: 8169 case OO_GreaterEqual: 8170 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8171 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8172 break; 8173 8174 case OO_Percent: 8175 case OO_Caret: 8176 case OO_Pipe: 8177 case OO_LessLess: 8178 case OO_GreaterGreater: 8179 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8180 break; 8181 8182 case OO_Amp: // '&' is either unary or binary 8183 if (Args.size() == 1) 8184 // C++ [over.match.oper]p3: 8185 // -- For the operator ',', the unary operator '&', or the 8186 // operator '->', the built-in candidates set is empty. 8187 break; 8188 8189 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8190 break; 8191 8192 case OO_Tilde: 8193 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8194 break; 8195 8196 case OO_Equal: 8197 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8198 // Fall through. 8199 8200 case OO_PlusEqual: 8201 case OO_MinusEqual: 8202 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8203 // Fall through. 8204 8205 case OO_StarEqual: 8206 case OO_SlashEqual: 8207 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8208 break; 8209 8210 case OO_PercentEqual: 8211 case OO_LessLessEqual: 8212 case OO_GreaterGreaterEqual: 8213 case OO_AmpEqual: 8214 case OO_CaretEqual: 8215 case OO_PipeEqual: 8216 OpBuilder.addAssignmentIntegralOverloads(); 8217 break; 8218 8219 case OO_Exclaim: 8220 OpBuilder.addExclaimOverload(); 8221 break; 8222 8223 case OO_AmpAmp: 8224 case OO_PipePipe: 8225 OpBuilder.addAmpAmpOrPipePipeOverload(); 8226 break; 8227 8228 case OO_Subscript: 8229 OpBuilder.addSubscriptOverloads(); 8230 break; 8231 8232 case OO_ArrowStar: 8233 OpBuilder.addArrowStarOverloads(); 8234 break; 8235 8236 case OO_Conditional: 8237 OpBuilder.addConditionalOperatorOverloads(); 8238 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8239 break; 8240 } 8241 } 8242 8243 /// \brief Add function candidates found via argument-dependent lookup 8244 /// to the set of overloading candidates. 8245 /// 8246 /// This routine performs argument-dependent name lookup based on the 8247 /// given function name (which may also be an operator name) and adds 8248 /// all of the overload candidates found by ADL to the overload 8249 /// candidate set (C++ [basic.lookup.argdep]). 8250 void 8251 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8252 SourceLocation Loc, 8253 ArrayRef<Expr *> Args, 8254 TemplateArgumentListInfo *ExplicitTemplateArgs, 8255 OverloadCandidateSet& CandidateSet, 8256 bool PartialOverloading) { 8257 ADLResult Fns; 8258 8259 // FIXME: This approach for uniquing ADL results (and removing 8260 // redundant candidates from the set) relies on pointer-equality, 8261 // which means we need to key off the canonical decl. However, 8262 // always going back to the canonical decl might not get us the 8263 // right set of default arguments. What default arguments are 8264 // we supposed to consider on ADL candidates, anyway? 8265 8266 // FIXME: Pass in the explicit template arguments? 8267 ArgumentDependentLookup(Name, Loc, Args, Fns); 8268 8269 // Erase all of the candidates we already knew about. 8270 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8271 CandEnd = CandidateSet.end(); 8272 Cand != CandEnd; ++Cand) 8273 if (Cand->Function) { 8274 Fns.erase(Cand->Function); 8275 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8276 Fns.erase(FunTmpl); 8277 } 8278 8279 // For each of the ADL candidates we found, add it to the overload 8280 // set. 8281 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8282 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8283 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8284 if (ExplicitTemplateArgs) 8285 continue; 8286 8287 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8288 PartialOverloading); 8289 } else 8290 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8291 FoundDecl, ExplicitTemplateArgs, 8292 Args, CandidateSet, PartialOverloading); 8293 } 8294 } 8295 8296 /// isBetterOverloadCandidate - Determines whether the first overload 8297 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8298 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8299 const OverloadCandidate &Cand2, 8300 SourceLocation Loc, 8301 bool UserDefinedConversion) { 8302 // Define viable functions to be better candidates than non-viable 8303 // functions. 8304 if (!Cand2.Viable) 8305 return Cand1.Viable; 8306 else if (!Cand1.Viable) 8307 return false; 8308 8309 // C++ [over.match.best]p1: 8310 // 8311 // -- if F is a static member function, ICS1(F) is defined such 8312 // that ICS1(F) is neither better nor worse than ICS1(G) for 8313 // any function G, and, symmetrically, ICS1(G) is neither 8314 // better nor worse than ICS1(F). 8315 unsigned StartArg = 0; 8316 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8317 StartArg = 1; 8318 8319 // C++ [over.match.best]p1: 8320 // A viable function F1 is defined to be a better function than another 8321 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8322 // conversion sequence than ICSi(F2), and then... 8323 unsigned NumArgs = Cand1.NumConversions; 8324 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8325 bool HasBetterConversion = false; 8326 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8327 switch (CompareImplicitConversionSequences(S, 8328 Cand1.Conversions[ArgIdx], 8329 Cand2.Conversions[ArgIdx])) { 8330 case ImplicitConversionSequence::Better: 8331 // Cand1 has a better conversion sequence. 8332 HasBetterConversion = true; 8333 break; 8334 8335 case ImplicitConversionSequence::Worse: 8336 // Cand1 can't be better than Cand2. 8337 return false; 8338 8339 case ImplicitConversionSequence::Indistinguishable: 8340 // Do nothing. 8341 break; 8342 } 8343 } 8344 8345 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8346 // ICSj(F2), or, if not that, 8347 if (HasBetterConversion) 8348 return true; 8349 8350 // -- the context is an initialization by user-defined conversion 8351 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8352 // from the return type of F1 to the destination type (i.e., 8353 // the type of the entity being initialized) is a better 8354 // conversion sequence than the standard conversion sequence 8355 // from the return type of F2 to the destination type. 8356 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8357 isa<CXXConversionDecl>(Cand1.Function) && 8358 isa<CXXConversionDecl>(Cand2.Function)) { 8359 // First check whether we prefer one of the conversion functions over the 8360 // other. This only distinguishes the results in non-standard, extension 8361 // cases such as the conversion from a lambda closure type to a function 8362 // pointer or block. 8363 ImplicitConversionSequence::CompareKind Result = 8364 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8365 if (Result == ImplicitConversionSequence::Indistinguishable) 8366 Result = CompareStandardConversionSequences(S, 8367 Cand1.FinalConversion, 8368 Cand2.FinalConversion); 8369 8370 if (Result != ImplicitConversionSequence::Indistinguishable) 8371 return Result == ImplicitConversionSequence::Better; 8372 8373 // FIXME: Compare kind of reference binding if conversion functions 8374 // convert to a reference type used in direct reference binding, per 8375 // C++14 [over.match.best]p1 section 2 bullet 3. 8376 } 8377 8378 // -- F1 is a non-template function and F2 is a function template 8379 // specialization, or, if not that, 8380 bool Cand1IsSpecialization = Cand1.Function && 8381 Cand1.Function->getPrimaryTemplate(); 8382 bool Cand2IsSpecialization = Cand2.Function && 8383 Cand2.Function->getPrimaryTemplate(); 8384 if (Cand1IsSpecialization != Cand2IsSpecialization) 8385 return Cand2IsSpecialization; 8386 8387 // -- F1 and F2 are function template specializations, and the function 8388 // template for F1 is more specialized than the template for F2 8389 // according to the partial ordering rules described in 14.5.5.2, or, 8390 // if not that, 8391 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8392 if (FunctionTemplateDecl *BetterTemplate 8393 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8394 Cand2.Function->getPrimaryTemplate(), 8395 Loc, 8396 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8397 : TPOC_Call, 8398 Cand1.ExplicitCallArguments, 8399 Cand2.ExplicitCallArguments)) 8400 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8401 } 8402 8403 // Check for enable_if value-based overload resolution. 8404 if (Cand1.Function && Cand2.Function && 8405 (Cand1.Function->hasAttr<EnableIfAttr>() || 8406 Cand2.Function->hasAttr<EnableIfAttr>())) { 8407 // FIXME: The next several lines are just 8408 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8409 // instead of reverse order which is how they're stored in the AST. 8410 AttrVec Cand1Attrs; 8411 if (Cand1.Function->hasAttrs()) { 8412 Cand1Attrs = Cand1.Function->getAttrs(); 8413 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(), 8414 IsNotEnableIfAttr), 8415 Cand1Attrs.end()); 8416 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end()); 8417 } 8418 8419 AttrVec Cand2Attrs; 8420 if (Cand2.Function->hasAttrs()) { 8421 Cand2Attrs = Cand2.Function->getAttrs(); 8422 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(), 8423 IsNotEnableIfAttr), 8424 Cand2Attrs.end()); 8425 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end()); 8426 } 8427 8428 // Candidate 1 is better if it has strictly more attributes and 8429 // the common sequence is identical. 8430 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8431 return false; 8432 8433 auto Cand1I = Cand1Attrs.begin(); 8434 for (auto &Cand2A : Cand2Attrs) { 8435 auto &Cand1A = *Cand1I++; 8436 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8437 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID, 8438 S.getASTContext(), true); 8439 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID, 8440 S.getASTContext(), true); 8441 if (Cand1ID != Cand2ID) 8442 return false; 8443 } 8444 8445 return true; 8446 } 8447 8448 return false; 8449 } 8450 8451 /// \brief Computes the best viable function (C++ 13.3.3) 8452 /// within an overload candidate set. 8453 /// 8454 /// \param Loc The location of the function name (or operator symbol) for 8455 /// which overload resolution occurs. 8456 /// 8457 /// \param Best If overload resolution was successful or found a deleted 8458 /// function, \p Best points to the candidate function found. 8459 /// 8460 /// \returns The result of overload resolution. 8461 OverloadingResult 8462 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8463 iterator &Best, 8464 bool UserDefinedConversion) { 8465 // Find the best viable function. 8466 Best = end(); 8467 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8468 if (Cand->Viable) 8469 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8470 UserDefinedConversion)) 8471 Best = Cand; 8472 } 8473 8474 // If we didn't find any viable functions, abort. 8475 if (Best == end()) 8476 return OR_No_Viable_Function; 8477 8478 // Make sure that this function is better than every other viable 8479 // function. If not, we have an ambiguity. 8480 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8481 if (Cand->Viable && 8482 Cand != Best && 8483 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8484 UserDefinedConversion)) { 8485 Best = end(); 8486 return OR_Ambiguous; 8487 } 8488 } 8489 8490 // Best is the best viable function. 8491 if (Best->Function && 8492 (Best->Function->isDeleted() || 8493 S.isFunctionConsideredUnavailable(Best->Function))) 8494 return OR_Deleted; 8495 8496 return OR_Success; 8497 } 8498 8499 namespace { 8500 8501 enum OverloadCandidateKind { 8502 oc_function, 8503 oc_method, 8504 oc_constructor, 8505 oc_function_template, 8506 oc_method_template, 8507 oc_constructor_template, 8508 oc_implicit_default_constructor, 8509 oc_implicit_copy_constructor, 8510 oc_implicit_move_constructor, 8511 oc_implicit_copy_assignment, 8512 oc_implicit_move_assignment, 8513 oc_implicit_inherited_constructor 8514 }; 8515 8516 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8517 FunctionDecl *Fn, 8518 std::string &Description) { 8519 bool isTemplate = false; 8520 8521 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8522 isTemplate = true; 8523 Description = S.getTemplateArgumentBindingsText( 8524 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8525 } 8526 8527 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8528 if (!Ctor->isImplicit()) 8529 return isTemplate ? oc_constructor_template : oc_constructor; 8530 8531 if (Ctor->getInheritedConstructor()) 8532 return oc_implicit_inherited_constructor; 8533 8534 if (Ctor->isDefaultConstructor()) 8535 return oc_implicit_default_constructor; 8536 8537 if (Ctor->isMoveConstructor()) 8538 return oc_implicit_move_constructor; 8539 8540 assert(Ctor->isCopyConstructor() && 8541 "unexpected sort of implicit constructor"); 8542 return oc_implicit_copy_constructor; 8543 } 8544 8545 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8546 // This actually gets spelled 'candidate function' for now, but 8547 // it doesn't hurt to split it out. 8548 if (!Meth->isImplicit()) 8549 return isTemplate ? oc_method_template : oc_method; 8550 8551 if (Meth->isMoveAssignmentOperator()) 8552 return oc_implicit_move_assignment; 8553 8554 if (Meth->isCopyAssignmentOperator()) 8555 return oc_implicit_copy_assignment; 8556 8557 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8558 return oc_method; 8559 } 8560 8561 return isTemplate ? oc_function_template : oc_function; 8562 } 8563 8564 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8565 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8566 if (!Ctor) return; 8567 8568 Ctor = Ctor->getInheritedConstructor(); 8569 if (!Ctor) return; 8570 8571 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8572 } 8573 8574 } // end anonymous namespace 8575 8576 // Notes the location of an overload candidate. 8577 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8578 std::string FnDesc; 8579 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8580 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8581 << (unsigned) K << FnDesc; 8582 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8583 Diag(Fn->getLocation(), PD); 8584 MaybeEmitInheritedConstructorNote(*this, Fn); 8585 } 8586 8587 // Notes the location of all overload candidates designated through 8588 // OverloadedExpr 8589 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8590 assert(OverloadedExpr->getType() == Context.OverloadTy); 8591 8592 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8593 OverloadExpr *OvlExpr = Ovl.Expression; 8594 8595 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8596 IEnd = OvlExpr->decls_end(); 8597 I != IEnd; ++I) { 8598 if (FunctionTemplateDecl *FunTmpl = 8599 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8600 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8601 } else if (FunctionDecl *Fun 8602 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8603 NoteOverloadCandidate(Fun, DestType); 8604 } 8605 } 8606 } 8607 8608 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8609 /// "lead" diagnostic; it will be given two arguments, the source and 8610 /// target types of the conversion. 8611 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8612 Sema &S, 8613 SourceLocation CaretLoc, 8614 const PartialDiagnostic &PDiag) const { 8615 S.Diag(CaretLoc, PDiag) 8616 << Ambiguous.getFromType() << Ambiguous.getToType(); 8617 // FIXME: The note limiting machinery is borrowed from 8618 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8619 // refactoring here. 8620 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8621 unsigned CandsShown = 0; 8622 AmbiguousConversionSequence::const_iterator I, E; 8623 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8624 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8625 break; 8626 ++CandsShown; 8627 S.NoteOverloadCandidate(*I); 8628 } 8629 if (I != E) 8630 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8631 } 8632 8633 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 8634 unsigned I) { 8635 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8636 assert(Conv.isBad()); 8637 assert(Cand->Function && "for now, candidate must be a function"); 8638 FunctionDecl *Fn = Cand->Function; 8639 8640 // There's a conversion slot for the object argument if this is a 8641 // non-constructor method. Note that 'I' corresponds the 8642 // conversion-slot index. 8643 bool isObjectArgument = false; 8644 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8645 if (I == 0) 8646 isObjectArgument = true; 8647 else 8648 I--; 8649 } 8650 8651 std::string FnDesc; 8652 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8653 8654 Expr *FromExpr = Conv.Bad.FromExpr; 8655 QualType FromTy = Conv.Bad.getFromType(); 8656 QualType ToTy = Conv.Bad.getToType(); 8657 8658 if (FromTy == S.Context.OverloadTy) { 8659 assert(FromExpr && "overload set argument came from implicit argument?"); 8660 Expr *E = FromExpr->IgnoreParens(); 8661 if (isa<UnaryOperator>(E)) 8662 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8663 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8664 8665 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8666 << (unsigned) FnKind << FnDesc 8667 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8668 << ToTy << Name << I+1; 8669 MaybeEmitInheritedConstructorNote(S, Fn); 8670 return; 8671 } 8672 8673 // Do some hand-waving analysis to see if the non-viability is due 8674 // to a qualifier mismatch. 8675 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8676 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8677 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8678 CToTy = RT->getPointeeType(); 8679 else { 8680 // TODO: detect and diagnose the full richness of const mismatches. 8681 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8682 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8683 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8684 } 8685 8686 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8687 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8688 Qualifiers FromQs = CFromTy.getQualifiers(); 8689 Qualifiers ToQs = CToTy.getQualifiers(); 8690 8691 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8692 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8693 << (unsigned) FnKind << FnDesc 8694 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8695 << FromTy 8696 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8697 << (unsigned) isObjectArgument << I+1; 8698 MaybeEmitInheritedConstructorNote(S, Fn); 8699 return; 8700 } 8701 8702 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8703 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8704 << (unsigned) FnKind << FnDesc 8705 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8706 << FromTy 8707 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8708 << (unsigned) isObjectArgument << I+1; 8709 MaybeEmitInheritedConstructorNote(S, Fn); 8710 return; 8711 } 8712 8713 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8714 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8715 << (unsigned) FnKind << FnDesc 8716 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8717 << FromTy 8718 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8719 << (unsigned) isObjectArgument << I+1; 8720 MaybeEmitInheritedConstructorNote(S, Fn); 8721 return; 8722 } 8723 8724 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8725 assert(CVR && "unexpected qualifiers mismatch"); 8726 8727 if (isObjectArgument) { 8728 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8729 << (unsigned) FnKind << FnDesc 8730 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8731 << FromTy << (CVR - 1); 8732 } else { 8733 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8734 << (unsigned) FnKind << FnDesc 8735 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8736 << FromTy << (CVR - 1) << I+1; 8737 } 8738 MaybeEmitInheritedConstructorNote(S, Fn); 8739 return; 8740 } 8741 8742 // Special diagnostic for failure to convert an initializer list, since 8743 // telling the user that it has type void is not useful. 8744 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8745 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8746 << (unsigned) FnKind << FnDesc 8747 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8748 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8749 MaybeEmitInheritedConstructorNote(S, Fn); 8750 return; 8751 } 8752 8753 // Diagnose references or pointers to incomplete types differently, 8754 // since it's far from impossible that the incompleteness triggered 8755 // the failure. 8756 QualType TempFromTy = FromTy.getNonReferenceType(); 8757 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8758 TempFromTy = PTy->getPointeeType(); 8759 if (TempFromTy->isIncompleteType()) { 8760 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8761 << (unsigned) FnKind << FnDesc 8762 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8763 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8764 MaybeEmitInheritedConstructorNote(S, Fn); 8765 return; 8766 } 8767 8768 // Diagnose base -> derived pointer conversions. 8769 unsigned BaseToDerivedConversion = 0; 8770 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8771 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8772 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8773 FromPtrTy->getPointeeType()) && 8774 !FromPtrTy->getPointeeType()->isIncompleteType() && 8775 !ToPtrTy->getPointeeType()->isIncompleteType() && 8776 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8777 FromPtrTy->getPointeeType())) 8778 BaseToDerivedConversion = 1; 8779 } 8780 } else if (const ObjCObjectPointerType *FromPtrTy 8781 = FromTy->getAs<ObjCObjectPointerType>()) { 8782 if (const ObjCObjectPointerType *ToPtrTy 8783 = ToTy->getAs<ObjCObjectPointerType>()) 8784 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8785 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8786 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8787 FromPtrTy->getPointeeType()) && 8788 FromIface->isSuperClassOf(ToIface)) 8789 BaseToDerivedConversion = 2; 8790 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8791 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8792 !FromTy->isIncompleteType() && 8793 !ToRefTy->getPointeeType()->isIncompleteType() && 8794 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8795 BaseToDerivedConversion = 3; 8796 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8797 ToTy.getNonReferenceType().getCanonicalType() == 8798 FromTy.getNonReferenceType().getCanonicalType()) { 8799 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8800 << (unsigned) FnKind << FnDesc 8801 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8802 << (unsigned) isObjectArgument << I + 1; 8803 MaybeEmitInheritedConstructorNote(S, Fn); 8804 return; 8805 } 8806 } 8807 8808 if (BaseToDerivedConversion) { 8809 S.Diag(Fn->getLocation(), 8810 diag::note_ovl_candidate_bad_base_to_derived_conv) 8811 << (unsigned) FnKind << FnDesc 8812 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8813 << (BaseToDerivedConversion - 1) 8814 << FromTy << ToTy << I+1; 8815 MaybeEmitInheritedConstructorNote(S, Fn); 8816 return; 8817 } 8818 8819 if (isa<ObjCObjectPointerType>(CFromTy) && 8820 isa<PointerType>(CToTy)) { 8821 Qualifiers FromQs = CFromTy.getQualifiers(); 8822 Qualifiers ToQs = CToTy.getQualifiers(); 8823 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8824 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8825 << (unsigned) FnKind << FnDesc 8826 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8827 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8828 MaybeEmitInheritedConstructorNote(S, Fn); 8829 return; 8830 } 8831 } 8832 8833 // Emit the generic diagnostic and, optionally, add the hints to it. 8834 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8835 FDiag << (unsigned) FnKind << FnDesc 8836 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8837 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8838 << (unsigned) (Cand->Fix.Kind); 8839 8840 // If we can fix the conversion, suggest the FixIts. 8841 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8842 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8843 FDiag << *HI; 8844 S.Diag(Fn->getLocation(), FDiag); 8845 8846 MaybeEmitInheritedConstructorNote(S, Fn); 8847 } 8848 8849 /// Additional arity mismatch diagnosis specific to a function overload 8850 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 8851 /// over a candidate in any candidate set. 8852 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 8853 unsigned NumArgs) { 8854 FunctionDecl *Fn = Cand->Function; 8855 unsigned MinParams = Fn->getMinRequiredArguments(); 8856 8857 // With invalid overloaded operators, it's possible that we think we 8858 // have an arity mismatch when in fact it looks like we have the 8859 // right number of arguments, because only overloaded operators have 8860 // the weird behavior of overloading member and non-member functions. 8861 // Just don't report anything. 8862 if (Fn->isInvalidDecl() && 8863 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8864 return true; 8865 8866 if (NumArgs < MinParams) { 8867 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8868 (Cand->FailureKind == ovl_fail_bad_deduction && 8869 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8870 } else { 8871 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8872 (Cand->FailureKind == ovl_fail_bad_deduction && 8873 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8874 } 8875 8876 return false; 8877 } 8878 8879 /// General arity mismatch diagnosis over a candidate in a candidate set. 8880 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 8881 assert(isa<FunctionDecl>(D) && 8882 "The templated declaration should at least be a function" 8883 " when diagnosing bad template argument deduction due to too many" 8884 " or too few arguments"); 8885 8886 FunctionDecl *Fn = cast<FunctionDecl>(D); 8887 8888 // TODO: treat calls to a missing default constructor as a special case 8889 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8890 unsigned MinParams = Fn->getMinRequiredArguments(); 8891 8892 // at least / at most / exactly 8893 unsigned mode, modeCount; 8894 if (NumFormalArgs < MinParams) { 8895 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 8896 FnTy->isTemplateVariadic()) 8897 mode = 0; // "at least" 8898 else 8899 mode = 2; // "exactly" 8900 modeCount = MinParams; 8901 } else { 8902 if (MinParams != FnTy->getNumParams()) 8903 mode = 1; // "at most" 8904 else 8905 mode = 2; // "exactly" 8906 modeCount = FnTy->getNumParams(); 8907 } 8908 8909 std::string Description; 8910 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8911 8912 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8913 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8914 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 8915 << mode << Fn->getParamDecl(0) << NumFormalArgs; 8916 else 8917 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8918 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 8919 << mode << modeCount << NumFormalArgs; 8920 MaybeEmitInheritedConstructorNote(S, Fn); 8921 } 8922 8923 /// Arity mismatch diagnosis specific to a function overload candidate. 8924 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8925 unsigned NumFormalArgs) { 8926 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 8927 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 8928 } 8929 8930 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 8931 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 8932 return FD->getDescribedFunctionTemplate(); 8933 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 8934 return RD->getDescribedClassTemplate(); 8935 8936 llvm_unreachable("Unsupported: Getting the described template declaration" 8937 " for bad deduction diagnosis"); 8938 } 8939 8940 /// Diagnose a failed template-argument deduction. 8941 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 8942 DeductionFailureInfo &DeductionFailure, 8943 unsigned NumArgs) { 8944 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 8945 NamedDecl *ParamD; 8946 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8947 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8948 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8949 switch (DeductionFailure.Result) { 8950 case Sema::TDK_Success: 8951 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8952 8953 case Sema::TDK_Incomplete: { 8954 assert(ParamD && "no parameter found for incomplete deduction result"); 8955 S.Diag(Templated->getLocation(), 8956 diag::note_ovl_candidate_incomplete_deduction) 8957 << ParamD->getDeclName(); 8958 MaybeEmitInheritedConstructorNote(S, Templated); 8959 return; 8960 } 8961 8962 case Sema::TDK_Underqualified: { 8963 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8964 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8965 8966 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 8967 8968 // Param will have been canonicalized, but it should just be a 8969 // qualified version of ParamD, so move the qualifiers to that. 8970 QualifierCollector Qs; 8971 Qs.strip(Param); 8972 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8973 assert(S.Context.hasSameType(Param, NonCanonParam)); 8974 8975 // Arg has also been canonicalized, but there's nothing we can do 8976 // about that. It also doesn't matter as much, because it won't 8977 // have any template parameters in it (because deduction isn't 8978 // done on dependent types). 8979 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 8980 8981 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 8982 << ParamD->getDeclName() << Arg << NonCanonParam; 8983 MaybeEmitInheritedConstructorNote(S, Templated); 8984 return; 8985 } 8986 8987 case Sema::TDK_Inconsistent: { 8988 assert(ParamD && "no parameter found for inconsistent deduction result"); 8989 int which = 0; 8990 if (isa<TemplateTypeParmDecl>(ParamD)) 8991 which = 0; 8992 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8993 which = 1; 8994 else { 8995 which = 2; 8996 } 8997 8998 S.Diag(Templated->getLocation(), 8999 diag::note_ovl_candidate_inconsistent_deduction) 9000 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9001 << *DeductionFailure.getSecondArg(); 9002 MaybeEmitInheritedConstructorNote(S, Templated); 9003 return; 9004 } 9005 9006 case Sema::TDK_InvalidExplicitArguments: 9007 assert(ParamD && "no parameter found for invalid explicit arguments"); 9008 if (ParamD->getDeclName()) 9009 S.Diag(Templated->getLocation(), 9010 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9011 << ParamD->getDeclName(); 9012 else { 9013 int index = 0; 9014 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9015 index = TTP->getIndex(); 9016 else if (NonTypeTemplateParmDecl *NTTP 9017 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9018 index = NTTP->getIndex(); 9019 else 9020 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9021 S.Diag(Templated->getLocation(), 9022 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9023 << (index + 1); 9024 } 9025 MaybeEmitInheritedConstructorNote(S, Templated); 9026 return; 9027 9028 case Sema::TDK_TooManyArguments: 9029 case Sema::TDK_TooFewArguments: 9030 DiagnoseArityMismatch(S, Templated, NumArgs); 9031 return; 9032 9033 case Sema::TDK_InstantiationDepth: 9034 S.Diag(Templated->getLocation(), 9035 diag::note_ovl_candidate_instantiation_depth); 9036 MaybeEmitInheritedConstructorNote(S, Templated); 9037 return; 9038 9039 case Sema::TDK_SubstitutionFailure: { 9040 // Format the template argument list into the argument string. 9041 SmallString<128> TemplateArgString; 9042 if (TemplateArgumentList *Args = 9043 DeductionFailure.getTemplateArgumentList()) { 9044 TemplateArgString = " "; 9045 TemplateArgString += S.getTemplateArgumentBindingsText( 9046 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9047 } 9048 9049 // If this candidate was disabled by enable_if, say so. 9050 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9051 if (PDiag && PDiag->second.getDiagID() == 9052 diag::err_typename_nested_not_found_enable_if) { 9053 // FIXME: Use the source range of the condition, and the fully-qualified 9054 // name of the enable_if template. These are both present in PDiag. 9055 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9056 << "'enable_if'" << TemplateArgString; 9057 return; 9058 } 9059 9060 // Format the SFINAE diagnostic into the argument string. 9061 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9062 // formatted message in another diagnostic. 9063 SmallString<128> SFINAEArgString; 9064 SourceRange R; 9065 if (PDiag) { 9066 SFINAEArgString = ": "; 9067 R = SourceRange(PDiag->first, PDiag->first); 9068 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9069 } 9070 9071 S.Diag(Templated->getLocation(), 9072 diag::note_ovl_candidate_substitution_failure) 9073 << TemplateArgString << SFINAEArgString << R; 9074 MaybeEmitInheritedConstructorNote(S, Templated); 9075 return; 9076 } 9077 9078 case Sema::TDK_FailedOverloadResolution: { 9079 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9080 S.Diag(Templated->getLocation(), 9081 diag::note_ovl_candidate_failed_overload_resolution) 9082 << R.Expression->getName(); 9083 return; 9084 } 9085 9086 case Sema::TDK_NonDeducedMismatch: { 9087 // FIXME: Provide a source location to indicate what we couldn't match. 9088 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9089 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9090 if (FirstTA.getKind() == TemplateArgument::Template && 9091 SecondTA.getKind() == TemplateArgument::Template) { 9092 TemplateName FirstTN = FirstTA.getAsTemplate(); 9093 TemplateName SecondTN = SecondTA.getAsTemplate(); 9094 if (FirstTN.getKind() == TemplateName::Template && 9095 SecondTN.getKind() == TemplateName::Template) { 9096 if (FirstTN.getAsTemplateDecl()->getName() == 9097 SecondTN.getAsTemplateDecl()->getName()) { 9098 // FIXME: This fixes a bad diagnostic where both templates are named 9099 // the same. This particular case is a bit difficult since: 9100 // 1) It is passed as a string to the diagnostic printer. 9101 // 2) The diagnostic printer only attempts to find a better 9102 // name for types, not decls. 9103 // Ideally, this should folded into the diagnostic printer. 9104 S.Diag(Templated->getLocation(), 9105 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9106 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9107 return; 9108 } 9109 } 9110 } 9111 // FIXME: For generic lambda parameters, check if the function is a lambda 9112 // call operator, and if so, emit a prettier and more informative 9113 // diagnostic that mentions 'auto' and lambda in addition to 9114 // (or instead of?) the canonical template type parameters. 9115 S.Diag(Templated->getLocation(), 9116 diag::note_ovl_candidate_non_deduced_mismatch) 9117 << FirstTA << SecondTA; 9118 return; 9119 } 9120 // TODO: diagnose these individually, then kill off 9121 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9122 case Sema::TDK_MiscellaneousDeductionFailure: 9123 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9124 MaybeEmitInheritedConstructorNote(S, Templated); 9125 return; 9126 } 9127 } 9128 9129 /// Diagnose a failed template-argument deduction, for function calls. 9130 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9131 unsigned NumArgs) { 9132 unsigned TDK = Cand->DeductionFailure.Result; 9133 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9134 if (CheckArityMismatch(S, Cand, NumArgs)) 9135 return; 9136 } 9137 DiagnoseBadDeduction(S, Cand->Function, // pattern 9138 Cand->DeductionFailure, NumArgs); 9139 } 9140 9141 /// CUDA: diagnose an invalid call across targets. 9142 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9143 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9144 FunctionDecl *Callee = Cand->Function; 9145 9146 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9147 CalleeTarget = S.IdentifyCUDATarget(Callee); 9148 9149 std::string FnDesc; 9150 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9151 9152 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9153 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9154 9155 // This could be an implicit constructor for which we could not infer the 9156 // target due to a collsion. Diagnose that case. 9157 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9158 if (Meth != nullptr && Meth->isImplicit()) { 9159 CXXRecordDecl *ParentClass = Meth->getParent(); 9160 Sema::CXXSpecialMember CSM; 9161 9162 switch (FnKind) { 9163 default: 9164 return; 9165 case oc_implicit_default_constructor: 9166 CSM = Sema::CXXDefaultConstructor; 9167 break; 9168 case oc_implicit_copy_constructor: 9169 CSM = Sema::CXXCopyConstructor; 9170 break; 9171 case oc_implicit_move_constructor: 9172 CSM = Sema::CXXMoveConstructor; 9173 break; 9174 case oc_implicit_copy_assignment: 9175 CSM = Sema::CXXCopyAssignment; 9176 break; 9177 case oc_implicit_move_assignment: 9178 CSM = Sema::CXXMoveAssignment; 9179 break; 9180 }; 9181 9182 bool ConstRHS = false; 9183 if (Meth->getNumParams()) { 9184 if (const ReferenceType *RT = 9185 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9186 ConstRHS = RT->getPointeeType().isConstQualified(); 9187 } 9188 } 9189 9190 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9191 /* ConstRHS */ ConstRHS, 9192 /* Diagnose */ true); 9193 } 9194 } 9195 9196 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9197 FunctionDecl *Callee = Cand->Function; 9198 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9199 9200 S.Diag(Callee->getLocation(), 9201 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9202 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9203 } 9204 9205 /// Generates a 'note' diagnostic for an overload candidate. We've 9206 /// already generated a primary error at the call site. 9207 /// 9208 /// It really does need to be a single diagnostic with its caret 9209 /// pointed at the candidate declaration. Yes, this creates some 9210 /// major challenges of technical writing. Yes, this makes pointing 9211 /// out problems with specific arguments quite awkward. It's still 9212 /// better than generating twenty screens of text for every failed 9213 /// overload. 9214 /// 9215 /// It would be great to be able to express per-candidate problems 9216 /// more richly for those diagnostic clients that cared, but we'd 9217 /// still have to be just as careful with the default diagnostics. 9218 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9219 unsigned NumArgs) { 9220 FunctionDecl *Fn = Cand->Function; 9221 9222 // Note deleted candidates, but only if they're viable. 9223 if (Cand->Viable && (Fn->isDeleted() || 9224 S.isFunctionConsideredUnavailable(Fn))) { 9225 std::string FnDesc; 9226 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9227 9228 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9229 << FnKind << FnDesc 9230 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9231 MaybeEmitInheritedConstructorNote(S, Fn); 9232 return; 9233 } 9234 9235 // We don't really have anything else to say about viable candidates. 9236 if (Cand->Viable) { 9237 S.NoteOverloadCandidate(Fn); 9238 return; 9239 } 9240 9241 switch (Cand->FailureKind) { 9242 case ovl_fail_too_many_arguments: 9243 case ovl_fail_too_few_arguments: 9244 return DiagnoseArityMismatch(S, Cand, NumArgs); 9245 9246 case ovl_fail_bad_deduction: 9247 return DiagnoseBadDeduction(S, Cand, NumArgs); 9248 9249 case ovl_fail_illegal_constructor: { 9250 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9251 << (Fn->getPrimaryTemplate() ? 1 : 0); 9252 MaybeEmitInheritedConstructorNote(S, Fn); 9253 return; 9254 } 9255 9256 case ovl_fail_trivial_conversion: 9257 case ovl_fail_bad_final_conversion: 9258 case ovl_fail_final_conversion_not_exact: 9259 return S.NoteOverloadCandidate(Fn); 9260 9261 case ovl_fail_bad_conversion: { 9262 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9263 for (unsigned N = Cand->NumConversions; I != N; ++I) 9264 if (Cand->Conversions[I].isBad()) 9265 return DiagnoseBadConversion(S, Cand, I); 9266 9267 // FIXME: this currently happens when we're called from SemaInit 9268 // when user-conversion overload fails. Figure out how to handle 9269 // those conditions and diagnose them well. 9270 return S.NoteOverloadCandidate(Fn); 9271 } 9272 9273 case ovl_fail_bad_target: 9274 return DiagnoseBadTarget(S, Cand); 9275 9276 case ovl_fail_enable_if: 9277 return DiagnoseFailedEnableIfAttr(S, Cand); 9278 } 9279 } 9280 9281 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9282 // Desugar the type of the surrogate down to a function type, 9283 // retaining as many typedefs as possible while still showing 9284 // the function type (and, therefore, its parameter types). 9285 QualType FnType = Cand->Surrogate->getConversionType(); 9286 bool isLValueReference = false; 9287 bool isRValueReference = false; 9288 bool isPointer = false; 9289 if (const LValueReferenceType *FnTypeRef = 9290 FnType->getAs<LValueReferenceType>()) { 9291 FnType = FnTypeRef->getPointeeType(); 9292 isLValueReference = true; 9293 } else if (const RValueReferenceType *FnTypeRef = 9294 FnType->getAs<RValueReferenceType>()) { 9295 FnType = FnTypeRef->getPointeeType(); 9296 isRValueReference = true; 9297 } 9298 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9299 FnType = FnTypePtr->getPointeeType(); 9300 isPointer = true; 9301 } 9302 // Desugar down to a function type. 9303 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9304 // Reconstruct the pointer/reference as appropriate. 9305 if (isPointer) FnType = S.Context.getPointerType(FnType); 9306 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9307 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9308 9309 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9310 << FnType; 9311 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9312 } 9313 9314 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9315 SourceLocation OpLoc, 9316 OverloadCandidate *Cand) { 9317 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9318 std::string TypeStr("operator"); 9319 TypeStr += Opc; 9320 TypeStr += "("; 9321 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9322 if (Cand->NumConversions == 1) { 9323 TypeStr += ")"; 9324 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9325 } else { 9326 TypeStr += ", "; 9327 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9328 TypeStr += ")"; 9329 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9330 } 9331 } 9332 9333 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9334 OverloadCandidate *Cand) { 9335 unsigned NoOperands = Cand->NumConversions; 9336 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9337 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9338 if (ICS.isBad()) break; // all meaningless after first invalid 9339 if (!ICS.isAmbiguous()) continue; 9340 9341 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9342 S.PDiag(diag::note_ambiguous_type_conversion)); 9343 } 9344 } 9345 9346 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9347 if (Cand->Function) 9348 return Cand->Function->getLocation(); 9349 if (Cand->IsSurrogate) 9350 return Cand->Surrogate->getLocation(); 9351 return SourceLocation(); 9352 } 9353 9354 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9355 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9356 case Sema::TDK_Success: 9357 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9358 9359 case Sema::TDK_Invalid: 9360 case Sema::TDK_Incomplete: 9361 return 1; 9362 9363 case Sema::TDK_Underqualified: 9364 case Sema::TDK_Inconsistent: 9365 return 2; 9366 9367 case Sema::TDK_SubstitutionFailure: 9368 case Sema::TDK_NonDeducedMismatch: 9369 case Sema::TDK_MiscellaneousDeductionFailure: 9370 return 3; 9371 9372 case Sema::TDK_InstantiationDepth: 9373 case Sema::TDK_FailedOverloadResolution: 9374 return 4; 9375 9376 case Sema::TDK_InvalidExplicitArguments: 9377 return 5; 9378 9379 case Sema::TDK_TooManyArguments: 9380 case Sema::TDK_TooFewArguments: 9381 return 6; 9382 } 9383 llvm_unreachable("Unhandled deduction result"); 9384 } 9385 9386 namespace { 9387 struct CompareOverloadCandidatesForDisplay { 9388 Sema &S; 9389 size_t NumArgs; 9390 9391 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs) 9392 : S(S), NumArgs(nArgs) {} 9393 9394 bool operator()(const OverloadCandidate *L, 9395 const OverloadCandidate *R) { 9396 // Fast-path this check. 9397 if (L == R) return false; 9398 9399 // Order first by viability. 9400 if (L->Viable) { 9401 if (!R->Viable) return true; 9402 9403 // TODO: introduce a tri-valued comparison for overload 9404 // candidates. Would be more worthwhile if we had a sort 9405 // that could exploit it. 9406 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9407 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9408 } else if (R->Viable) 9409 return false; 9410 9411 assert(L->Viable == R->Viable); 9412 9413 // Criteria by which we can sort non-viable candidates: 9414 if (!L->Viable) { 9415 // 1. Arity mismatches come after other candidates. 9416 if (L->FailureKind == ovl_fail_too_many_arguments || 9417 L->FailureKind == ovl_fail_too_few_arguments) { 9418 if (R->FailureKind == ovl_fail_too_many_arguments || 9419 R->FailureKind == ovl_fail_too_few_arguments) { 9420 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9421 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9422 if (LDist == RDist) { 9423 if (L->FailureKind == R->FailureKind) 9424 // Sort non-surrogates before surrogates. 9425 return !L->IsSurrogate && R->IsSurrogate; 9426 // Sort candidates requiring fewer parameters than there were 9427 // arguments given after candidates requiring more parameters 9428 // than there were arguments given. 9429 return L->FailureKind == ovl_fail_too_many_arguments; 9430 } 9431 return LDist < RDist; 9432 } 9433 return false; 9434 } 9435 if (R->FailureKind == ovl_fail_too_many_arguments || 9436 R->FailureKind == ovl_fail_too_few_arguments) 9437 return true; 9438 9439 // 2. Bad conversions come first and are ordered by the number 9440 // of bad conversions and quality of good conversions. 9441 if (L->FailureKind == ovl_fail_bad_conversion) { 9442 if (R->FailureKind != ovl_fail_bad_conversion) 9443 return true; 9444 9445 // The conversion that can be fixed with a smaller number of changes, 9446 // comes first. 9447 unsigned numLFixes = L->Fix.NumConversionsFixed; 9448 unsigned numRFixes = R->Fix.NumConversionsFixed; 9449 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9450 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9451 if (numLFixes != numRFixes) { 9452 if (numLFixes < numRFixes) 9453 return true; 9454 else 9455 return false; 9456 } 9457 9458 // If there's any ordering between the defined conversions... 9459 // FIXME: this might not be transitive. 9460 assert(L->NumConversions == R->NumConversions); 9461 9462 int leftBetter = 0; 9463 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9464 for (unsigned E = L->NumConversions; I != E; ++I) { 9465 switch (CompareImplicitConversionSequences(S, 9466 L->Conversions[I], 9467 R->Conversions[I])) { 9468 case ImplicitConversionSequence::Better: 9469 leftBetter++; 9470 break; 9471 9472 case ImplicitConversionSequence::Worse: 9473 leftBetter--; 9474 break; 9475 9476 case ImplicitConversionSequence::Indistinguishable: 9477 break; 9478 } 9479 } 9480 if (leftBetter > 0) return true; 9481 if (leftBetter < 0) return false; 9482 9483 } else if (R->FailureKind == ovl_fail_bad_conversion) 9484 return false; 9485 9486 if (L->FailureKind == ovl_fail_bad_deduction) { 9487 if (R->FailureKind != ovl_fail_bad_deduction) 9488 return true; 9489 9490 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9491 return RankDeductionFailure(L->DeductionFailure) 9492 < RankDeductionFailure(R->DeductionFailure); 9493 } else if (R->FailureKind == ovl_fail_bad_deduction) 9494 return false; 9495 9496 // TODO: others? 9497 } 9498 9499 // Sort everything else by location. 9500 SourceLocation LLoc = GetLocationForCandidate(L); 9501 SourceLocation RLoc = GetLocationForCandidate(R); 9502 9503 // Put candidates without locations (e.g. builtins) at the end. 9504 if (LLoc.isInvalid()) return false; 9505 if (RLoc.isInvalid()) return true; 9506 9507 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9508 } 9509 }; 9510 } 9511 9512 /// CompleteNonViableCandidate - Normally, overload resolution only 9513 /// computes up to the first. Produces the FixIt set if possible. 9514 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9515 ArrayRef<Expr *> Args) { 9516 assert(!Cand->Viable); 9517 9518 // Don't do anything on failures other than bad conversion. 9519 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9520 9521 // We only want the FixIts if all the arguments can be corrected. 9522 bool Unfixable = false; 9523 // Use a implicit copy initialization to check conversion fixes. 9524 Cand->Fix.setConversionChecker(TryCopyInitialization); 9525 9526 // Skip forward to the first bad conversion. 9527 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9528 unsigned ConvCount = Cand->NumConversions; 9529 while (true) { 9530 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9531 ConvIdx++; 9532 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9533 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9534 break; 9535 } 9536 } 9537 9538 if (ConvIdx == ConvCount) 9539 return; 9540 9541 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9542 "remaining conversion is initialized?"); 9543 9544 // FIXME: this should probably be preserved from the overload 9545 // operation somehow. 9546 bool SuppressUserConversions = false; 9547 9548 const FunctionProtoType* Proto; 9549 unsigned ArgIdx = ConvIdx; 9550 9551 if (Cand->IsSurrogate) { 9552 QualType ConvType 9553 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9554 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9555 ConvType = ConvPtrType->getPointeeType(); 9556 Proto = ConvType->getAs<FunctionProtoType>(); 9557 ArgIdx--; 9558 } else if (Cand->Function) { 9559 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9560 if (isa<CXXMethodDecl>(Cand->Function) && 9561 !isa<CXXConstructorDecl>(Cand->Function)) 9562 ArgIdx--; 9563 } else { 9564 // Builtin binary operator with a bad first conversion. 9565 assert(ConvCount <= 3); 9566 for (; ConvIdx != ConvCount; ++ConvIdx) 9567 Cand->Conversions[ConvIdx] 9568 = TryCopyInitialization(S, Args[ConvIdx], 9569 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9570 SuppressUserConversions, 9571 /*InOverloadResolution*/ true, 9572 /*AllowObjCWritebackConversion=*/ 9573 S.getLangOpts().ObjCAutoRefCount); 9574 return; 9575 } 9576 9577 // Fill in the rest of the conversions. 9578 unsigned NumParams = Proto->getNumParams(); 9579 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9580 if (ArgIdx < NumParams) { 9581 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9582 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9583 /*InOverloadResolution=*/true, 9584 /*AllowObjCWritebackConversion=*/ 9585 S.getLangOpts().ObjCAutoRefCount); 9586 // Store the FixIt in the candidate if it exists. 9587 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9588 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9589 } 9590 else 9591 Cand->Conversions[ConvIdx].setEllipsis(); 9592 } 9593 } 9594 9595 /// PrintOverloadCandidates - When overload resolution fails, prints 9596 /// diagnostic messages containing the candidates in the candidate 9597 /// set. 9598 void OverloadCandidateSet::NoteCandidates(Sema &S, 9599 OverloadCandidateDisplayKind OCD, 9600 ArrayRef<Expr *> Args, 9601 StringRef Opc, 9602 SourceLocation OpLoc) { 9603 // Sort the candidates by viability and position. Sorting directly would 9604 // be prohibitive, so we make a set of pointers and sort those. 9605 SmallVector<OverloadCandidate*, 32> Cands; 9606 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9607 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9608 if (Cand->Viable) 9609 Cands.push_back(Cand); 9610 else if (OCD == OCD_AllCandidates) { 9611 CompleteNonViableCandidate(S, Cand, Args); 9612 if (Cand->Function || Cand->IsSurrogate) 9613 Cands.push_back(Cand); 9614 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9615 // want to list every possible builtin candidate. 9616 } 9617 } 9618 9619 std::sort(Cands.begin(), Cands.end(), 9620 CompareOverloadCandidatesForDisplay(S, Args.size())); 9621 9622 bool ReportedAmbiguousConversions = false; 9623 9624 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9625 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9626 unsigned CandsShown = 0; 9627 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9628 OverloadCandidate *Cand = *I; 9629 9630 // Set an arbitrary limit on the number of candidate functions we'll spam 9631 // the user with. FIXME: This limit should depend on details of the 9632 // candidate list. 9633 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9634 break; 9635 } 9636 ++CandsShown; 9637 9638 if (Cand->Function) 9639 NoteFunctionCandidate(S, Cand, Args.size()); 9640 else if (Cand->IsSurrogate) 9641 NoteSurrogateCandidate(S, Cand); 9642 else { 9643 assert(Cand->Viable && 9644 "Non-viable built-in candidates are not added to Cands."); 9645 // Generally we only see ambiguities including viable builtin 9646 // operators if overload resolution got screwed up by an 9647 // ambiguous user-defined conversion. 9648 // 9649 // FIXME: It's quite possible for different conversions to see 9650 // different ambiguities, though. 9651 if (!ReportedAmbiguousConversions) { 9652 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9653 ReportedAmbiguousConversions = true; 9654 } 9655 9656 // If this is a viable builtin, print it. 9657 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9658 } 9659 } 9660 9661 if (I != E) 9662 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9663 } 9664 9665 static SourceLocation 9666 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9667 return Cand->Specialization ? Cand->Specialization->getLocation() 9668 : SourceLocation(); 9669 } 9670 9671 namespace { 9672 struct CompareTemplateSpecCandidatesForDisplay { 9673 Sema &S; 9674 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9675 9676 bool operator()(const TemplateSpecCandidate *L, 9677 const TemplateSpecCandidate *R) { 9678 // Fast-path this check. 9679 if (L == R) 9680 return false; 9681 9682 // Assuming that both candidates are not matches... 9683 9684 // Sort by the ranking of deduction failures. 9685 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9686 return RankDeductionFailure(L->DeductionFailure) < 9687 RankDeductionFailure(R->DeductionFailure); 9688 9689 // Sort everything else by location. 9690 SourceLocation LLoc = GetLocationForCandidate(L); 9691 SourceLocation RLoc = GetLocationForCandidate(R); 9692 9693 // Put candidates without locations (e.g. builtins) at the end. 9694 if (LLoc.isInvalid()) 9695 return false; 9696 if (RLoc.isInvalid()) 9697 return true; 9698 9699 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9700 } 9701 }; 9702 } 9703 9704 /// Diagnose a template argument deduction failure. 9705 /// We are treating these failures as overload failures due to bad 9706 /// deductions. 9707 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9708 DiagnoseBadDeduction(S, Specialization, // pattern 9709 DeductionFailure, /*NumArgs=*/0); 9710 } 9711 9712 void TemplateSpecCandidateSet::destroyCandidates() { 9713 for (iterator i = begin(), e = end(); i != e; ++i) { 9714 i->DeductionFailure.Destroy(); 9715 } 9716 } 9717 9718 void TemplateSpecCandidateSet::clear() { 9719 destroyCandidates(); 9720 Candidates.clear(); 9721 } 9722 9723 /// NoteCandidates - When no template specialization match is found, prints 9724 /// diagnostic messages containing the non-matching specializations that form 9725 /// the candidate set. 9726 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9727 /// OCD == OCD_AllCandidates and Cand->Viable == false. 9728 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9729 // Sort the candidates by position (assuming no candidate is a match). 9730 // Sorting directly would be prohibitive, so we make a set of pointers 9731 // and sort those. 9732 SmallVector<TemplateSpecCandidate *, 32> Cands; 9733 Cands.reserve(size()); 9734 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9735 if (Cand->Specialization) 9736 Cands.push_back(Cand); 9737 // Otherwise, this is a non-matching builtin candidate. We do not, 9738 // in general, want to list every possible builtin candidate. 9739 } 9740 9741 std::sort(Cands.begin(), Cands.end(), 9742 CompareTemplateSpecCandidatesForDisplay(S)); 9743 9744 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9745 // for generalization purposes (?). 9746 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9747 9748 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9749 unsigned CandsShown = 0; 9750 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9751 TemplateSpecCandidate *Cand = *I; 9752 9753 // Set an arbitrary limit on the number of candidates we'll spam 9754 // the user with. FIXME: This limit should depend on details of the 9755 // candidate list. 9756 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9757 break; 9758 ++CandsShown; 9759 9760 assert(Cand->Specialization && 9761 "Non-matching built-in candidates are not added to Cands."); 9762 Cand->NoteDeductionFailure(S); 9763 } 9764 9765 if (I != E) 9766 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9767 } 9768 9769 // [PossiblyAFunctionType] --> [Return] 9770 // NonFunctionType --> NonFunctionType 9771 // R (A) --> R(A) 9772 // R (*)(A) --> R (A) 9773 // R (&)(A) --> R (A) 9774 // R (S::*)(A) --> R (A) 9775 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9776 QualType Ret = PossiblyAFunctionType; 9777 if (const PointerType *ToTypePtr = 9778 PossiblyAFunctionType->getAs<PointerType>()) 9779 Ret = ToTypePtr->getPointeeType(); 9780 else if (const ReferenceType *ToTypeRef = 9781 PossiblyAFunctionType->getAs<ReferenceType>()) 9782 Ret = ToTypeRef->getPointeeType(); 9783 else if (const MemberPointerType *MemTypePtr = 9784 PossiblyAFunctionType->getAs<MemberPointerType>()) 9785 Ret = MemTypePtr->getPointeeType(); 9786 Ret = 9787 Context.getCanonicalType(Ret).getUnqualifiedType(); 9788 return Ret; 9789 } 9790 9791 namespace { 9792 // A helper class to help with address of function resolution 9793 // - allows us to avoid passing around all those ugly parameters 9794 class AddressOfFunctionResolver { 9795 Sema& S; 9796 Expr* SourceExpr; 9797 const QualType& TargetType; 9798 QualType TargetFunctionType; // Extracted function type from target type 9799 9800 bool Complain; 9801 //DeclAccessPair& ResultFunctionAccessPair; 9802 ASTContext& Context; 9803 9804 bool TargetTypeIsNonStaticMemberFunction; 9805 bool FoundNonTemplateFunction; 9806 bool StaticMemberFunctionFromBoundPointer; 9807 9808 OverloadExpr::FindResult OvlExprInfo; 9809 OverloadExpr *OvlExpr; 9810 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9811 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9812 TemplateSpecCandidateSet FailedCandidates; 9813 9814 public: 9815 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9816 const QualType &TargetType, bool Complain) 9817 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9818 Complain(Complain), Context(S.getASTContext()), 9819 TargetTypeIsNonStaticMemberFunction( 9820 !!TargetType->getAs<MemberPointerType>()), 9821 FoundNonTemplateFunction(false), 9822 StaticMemberFunctionFromBoundPointer(false), 9823 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9824 OvlExpr(OvlExprInfo.Expression), 9825 FailedCandidates(OvlExpr->getNameLoc()) { 9826 ExtractUnqualifiedFunctionTypeFromTargetType(); 9827 9828 if (TargetFunctionType->isFunctionType()) { 9829 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 9830 if (!UME->isImplicitAccess() && 9831 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 9832 StaticMemberFunctionFromBoundPointer = true; 9833 } else if (OvlExpr->hasExplicitTemplateArgs()) { 9834 DeclAccessPair dap; 9835 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 9836 OvlExpr, false, &dap)) { 9837 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 9838 if (!Method->isStatic()) { 9839 // If the target type is a non-function type and the function found 9840 // is a non-static member function, pretend as if that was the 9841 // target, it's the only possible type to end up with. 9842 TargetTypeIsNonStaticMemberFunction = true; 9843 9844 // And skip adding the function if its not in the proper form. 9845 // We'll diagnose this due to an empty set of functions. 9846 if (!OvlExprInfo.HasFormOfMemberPointer) 9847 return; 9848 } 9849 9850 Matches.push_back(std::make_pair(dap, Fn)); 9851 } 9852 return; 9853 } 9854 9855 if (OvlExpr->hasExplicitTemplateArgs()) 9856 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9857 9858 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9859 // C++ [over.over]p4: 9860 // If more than one function is selected, [...] 9861 if (Matches.size() > 1) { 9862 if (FoundNonTemplateFunction) 9863 EliminateAllTemplateMatches(); 9864 else 9865 EliminateAllExceptMostSpecializedTemplate(); 9866 } 9867 } 9868 } 9869 9870 private: 9871 bool isTargetTypeAFunction() const { 9872 return TargetFunctionType->isFunctionType(); 9873 } 9874 9875 // [ToType] [Return] 9876 9877 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9878 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9879 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9880 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9881 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9882 } 9883 9884 // return true if any matching specializations were found 9885 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9886 const DeclAccessPair& CurAccessFunPair) { 9887 if (CXXMethodDecl *Method 9888 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9889 // Skip non-static function templates when converting to pointer, and 9890 // static when converting to member pointer. 9891 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9892 return false; 9893 } 9894 else if (TargetTypeIsNonStaticMemberFunction) 9895 return false; 9896 9897 // C++ [over.over]p2: 9898 // If the name is a function template, template argument deduction is 9899 // done (14.8.2.2), and if the argument deduction succeeds, the 9900 // resulting template argument list is used to generate a single 9901 // function template specialization, which is added to the set of 9902 // overloaded functions considered. 9903 FunctionDecl *Specialization = nullptr; 9904 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9905 if (Sema::TemplateDeductionResult Result 9906 = S.DeduceTemplateArguments(FunctionTemplate, 9907 &OvlExplicitTemplateArgs, 9908 TargetFunctionType, Specialization, 9909 Info, /*InOverloadResolution=*/true)) { 9910 // Make a note of the failed deduction for diagnostics. 9911 FailedCandidates.addCandidate() 9912 .set(FunctionTemplate->getTemplatedDecl(), 9913 MakeDeductionFailureInfo(Context, Result, Info)); 9914 return false; 9915 } 9916 9917 // Template argument deduction ensures that we have an exact match or 9918 // compatible pointer-to-function arguments that would be adjusted by ICS. 9919 // This function template specicalization works. 9920 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9921 assert(S.isSameOrCompatibleFunctionType( 9922 Context.getCanonicalType(Specialization->getType()), 9923 Context.getCanonicalType(TargetFunctionType))); 9924 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9925 return true; 9926 } 9927 9928 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9929 const DeclAccessPair& CurAccessFunPair) { 9930 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9931 // Skip non-static functions when converting to pointer, and static 9932 // when converting to member pointer. 9933 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9934 return false; 9935 } 9936 else if (TargetTypeIsNonStaticMemberFunction) 9937 return false; 9938 9939 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9940 if (S.getLangOpts().CUDA) 9941 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9942 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 9943 return false; 9944 9945 // If any candidate has a placeholder return type, trigger its deduction 9946 // now. 9947 if (S.getLangOpts().CPlusPlus14 && 9948 FunDecl->getReturnType()->isUndeducedType() && 9949 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9950 return false; 9951 9952 QualType ResultTy; 9953 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9954 FunDecl->getType()) || 9955 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9956 ResultTy)) { 9957 Matches.push_back(std::make_pair(CurAccessFunPair, 9958 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9959 FoundNonTemplateFunction = true; 9960 return true; 9961 } 9962 } 9963 9964 return false; 9965 } 9966 9967 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9968 bool Ret = false; 9969 9970 // If the overload expression doesn't have the form of a pointer to 9971 // member, don't try to convert it to a pointer-to-member type. 9972 if (IsInvalidFormOfPointerToMemberFunction()) 9973 return false; 9974 9975 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9976 E = OvlExpr->decls_end(); 9977 I != E; ++I) { 9978 // Look through any using declarations to find the underlying function. 9979 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9980 9981 // C++ [over.over]p3: 9982 // Non-member functions and static member functions match 9983 // targets of type "pointer-to-function" or "reference-to-function." 9984 // Nonstatic member functions match targets of 9985 // type "pointer-to-member-function." 9986 // Note that according to DR 247, the containing class does not matter. 9987 if (FunctionTemplateDecl *FunctionTemplate 9988 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9989 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9990 Ret = true; 9991 } 9992 // If we have explicit template arguments supplied, skip non-templates. 9993 else if (!OvlExpr->hasExplicitTemplateArgs() && 9994 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9995 Ret = true; 9996 } 9997 assert(Ret || Matches.empty()); 9998 return Ret; 9999 } 10000 10001 void EliminateAllExceptMostSpecializedTemplate() { 10002 // [...] and any given function template specialization F1 is 10003 // eliminated if the set contains a second function template 10004 // specialization whose function template is more specialized 10005 // than the function template of F1 according to the partial 10006 // ordering rules of 14.5.5.2. 10007 10008 // The algorithm specified above is quadratic. We instead use a 10009 // two-pass algorithm (similar to the one used to identify the 10010 // best viable function in an overload set) that identifies the 10011 // best function template (if it exists). 10012 10013 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10014 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10015 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10016 10017 // TODO: It looks like FailedCandidates does not serve much purpose 10018 // here, since the no_viable diagnostic has index 0. 10019 UnresolvedSetIterator Result = S.getMostSpecialized( 10020 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10021 SourceExpr->getLocStart(), S.PDiag(), 10022 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10023 .second->getDeclName(), 10024 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10025 Complain, TargetFunctionType); 10026 10027 if (Result != MatchesCopy.end()) { 10028 // Make it the first and only element 10029 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10030 Matches[0].second = cast<FunctionDecl>(*Result); 10031 Matches.resize(1); 10032 } 10033 } 10034 10035 void EliminateAllTemplateMatches() { 10036 // [...] any function template specializations in the set are 10037 // eliminated if the set also contains a non-template function, [...] 10038 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10039 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10040 ++I; 10041 else { 10042 Matches[I] = Matches[--N]; 10043 Matches.set_size(N); 10044 } 10045 } 10046 } 10047 10048 public: 10049 void ComplainNoMatchesFound() const { 10050 assert(Matches.empty()); 10051 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10052 << OvlExpr->getName() << TargetFunctionType 10053 << OvlExpr->getSourceRange(); 10054 if (FailedCandidates.empty()) 10055 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 10056 else { 10057 // We have some deduction failure messages. Use them to diagnose 10058 // the function templates, and diagnose the non-template candidates 10059 // normally. 10060 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10061 IEnd = OvlExpr->decls_end(); 10062 I != IEnd; ++I) 10063 if (FunctionDecl *Fun = 10064 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10065 S.NoteOverloadCandidate(Fun, TargetFunctionType); 10066 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10067 } 10068 } 10069 10070 bool IsInvalidFormOfPointerToMemberFunction() const { 10071 return TargetTypeIsNonStaticMemberFunction && 10072 !OvlExprInfo.HasFormOfMemberPointer; 10073 } 10074 10075 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10076 // TODO: Should we condition this on whether any functions might 10077 // have matched, or is it more appropriate to do that in callers? 10078 // TODO: a fixit wouldn't hurt. 10079 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10080 << TargetType << OvlExpr->getSourceRange(); 10081 } 10082 10083 bool IsStaticMemberFunctionFromBoundPointer() const { 10084 return StaticMemberFunctionFromBoundPointer; 10085 } 10086 10087 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10088 S.Diag(OvlExpr->getLocStart(), 10089 diag::err_invalid_form_pointer_member_function) 10090 << OvlExpr->getSourceRange(); 10091 } 10092 10093 void ComplainOfInvalidConversion() const { 10094 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10095 << OvlExpr->getName() << TargetType; 10096 } 10097 10098 void ComplainMultipleMatchesFound() const { 10099 assert(Matches.size() > 1); 10100 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10101 << OvlExpr->getName() 10102 << OvlExpr->getSourceRange(); 10103 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 10104 } 10105 10106 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10107 10108 int getNumMatches() const { return Matches.size(); } 10109 10110 FunctionDecl* getMatchingFunctionDecl() const { 10111 if (Matches.size() != 1) return nullptr; 10112 return Matches[0].second; 10113 } 10114 10115 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10116 if (Matches.size() != 1) return nullptr; 10117 return &Matches[0].first; 10118 } 10119 }; 10120 } 10121 10122 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10123 /// an overloaded function (C++ [over.over]), where @p From is an 10124 /// expression with overloaded function type and @p ToType is the type 10125 /// we're trying to resolve to. For example: 10126 /// 10127 /// @code 10128 /// int f(double); 10129 /// int f(int); 10130 /// 10131 /// int (*pfd)(double) = f; // selects f(double) 10132 /// @endcode 10133 /// 10134 /// This routine returns the resulting FunctionDecl if it could be 10135 /// resolved, and NULL otherwise. When @p Complain is true, this 10136 /// routine will emit diagnostics if there is an error. 10137 FunctionDecl * 10138 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10139 QualType TargetType, 10140 bool Complain, 10141 DeclAccessPair &FoundResult, 10142 bool *pHadMultipleCandidates) { 10143 assert(AddressOfExpr->getType() == Context.OverloadTy); 10144 10145 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10146 Complain); 10147 int NumMatches = Resolver.getNumMatches(); 10148 FunctionDecl *Fn = nullptr; 10149 if (NumMatches == 0 && Complain) { 10150 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10151 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10152 else 10153 Resolver.ComplainNoMatchesFound(); 10154 } 10155 else if (NumMatches > 1 && Complain) 10156 Resolver.ComplainMultipleMatchesFound(); 10157 else if (NumMatches == 1) { 10158 Fn = Resolver.getMatchingFunctionDecl(); 10159 assert(Fn); 10160 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10161 if (Complain) { 10162 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10163 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10164 else 10165 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10166 } 10167 } 10168 10169 if (pHadMultipleCandidates) 10170 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10171 return Fn; 10172 } 10173 10174 /// \brief Given an expression that refers to an overloaded function, try to 10175 /// resolve that overloaded function expression down to a single function. 10176 /// 10177 /// This routine can only resolve template-ids that refer to a single function 10178 /// template, where that template-id refers to a single template whose template 10179 /// arguments are either provided by the template-id or have defaults, 10180 /// as described in C++0x [temp.arg.explicit]p3. 10181 /// 10182 /// If no template-ids are found, no diagnostics are emitted and NULL is 10183 /// returned. 10184 FunctionDecl * 10185 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10186 bool Complain, 10187 DeclAccessPair *FoundResult) { 10188 // C++ [over.over]p1: 10189 // [...] [Note: any redundant set of parentheses surrounding the 10190 // overloaded function name is ignored (5.1). ] 10191 // C++ [over.over]p1: 10192 // [...] The overloaded function name can be preceded by the & 10193 // operator. 10194 10195 // If we didn't actually find any template-ids, we're done. 10196 if (!ovl->hasExplicitTemplateArgs()) 10197 return nullptr; 10198 10199 TemplateArgumentListInfo ExplicitTemplateArgs; 10200 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 10201 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10202 10203 // Look through all of the overloaded functions, searching for one 10204 // whose type matches exactly. 10205 FunctionDecl *Matched = nullptr; 10206 for (UnresolvedSetIterator I = ovl->decls_begin(), 10207 E = ovl->decls_end(); I != E; ++I) { 10208 // C++0x [temp.arg.explicit]p3: 10209 // [...] In contexts where deduction is done and fails, or in contexts 10210 // where deduction is not done, if a template argument list is 10211 // specified and it, along with any default template arguments, 10212 // identifies a single function template specialization, then the 10213 // template-id is an lvalue for the function template specialization. 10214 FunctionTemplateDecl *FunctionTemplate 10215 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10216 10217 // C++ [over.over]p2: 10218 // If the name is a function template, template argument deduction is 10219 // done (14.8.2.2), and if the argument deduction succeeds, the 10220 // resulting template argument list is used to generate a single 10221 // function template specialization, which is added to the set of 10222 // overloaded functions considered. 10223 FunctionDecl *Specialization = nullptr; 10224 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10225 if (TemplateDeductionResult Result 10226 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10227 Specialization, Info, 10228 /*InOverloadResolution=*/true)) { 10229 // Make a note of the failed deduction for diagnostics. 10230 // TODO: Actually use the failed-deduction info? 10231 FailedCandidates.addCandidate() 10232 .set(FunctionTemplate->getTemplatedDecl(), 10233 MakeDeductionFailureInfo(Context, Result, Info)); 10234 continue; 10235 } 10236 10237 assert(Specialization && "no specialization and no error?"); 10238 10239 // Multiple matches; we can't resolve to a single declaration. 10240 if (Matched) { 10241 if (Complain) { 10242 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10243 << ovl->getName(); 10244 NoteAllOverloadCandidates(ovl); 10245 } 10246 return nullptr; 10247 } 10248 10249 Matched = Specialization; 10250 if (FoundResult) *FoundResult = I.getPair(); 10251 } 10252 10253 if (Matched && getLangOpts().CPlusPlus14 && 10254 Matched->getReturnType()->isUndeducedType() && 10255 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10256 return nullptr; 10257 10258 return Matched; 10259 } 10260 10261 10262 10263 10264 // Resolve and fix an overloaded expression that can be resolved 10265 // because it identifies a single function template specialization. 10266 // 10267 // Last three arguments should only be supplied if Complain = true 10268 // 10269 // Return true if it was logically possible to so resolve the 10270 // expression, regardless of whether or not it succeeded. Always 10271 // returns true if 'complain' is set. 10272 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10273 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10274 bool complain, const SourceRange& OpRangeForComplaining, 10275 QualType DestTypeForComplaining, 10276 unsigned DiagIDForComplaining) { 10277 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10278 10279 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10280 10281 DeclAccessPair found; 10282 ExprResult SingleFunctionExpression; 10283 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10284 ovl.Expression, /*complain*/ false, &found)) { 10285 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10286 SrcExpr = ExprError(); 10287 return true; 10288 } 10289 10290 // It is only correct to resolve to an instance method if we're 10291 // resolving a form that's permitted to be a pointer to member. 10292 // Otherwise we'll end up making a bound member expression, which 10293 // is illegal in all the contexts we resolve like this. 10294 if (!ovl.HasFormOfMemberPointer && 10295 isa<CXXMethodDecl>(fn) && 10296 cast<CXXMethodDecl>(fn)->isInstance()) { 10297 if (!complain) return false; 10298 10299 Diag(ovl.Expression->getExprLoc(), 10300 diag::err_bound_member_function) 10301 << 0 << ovl.Expression->getSourceRange(); 10302 10303 // TODO: I believe we only end up here if there's a mix of 10304 // static and non-static candidates (otherwise the expression 10305 // would have 'bound member' type, not 'overload' type). 10306 // Ideally we would note which candidate was chosen and why 10307 // the static candidates were rejected. 10308 SrcExpr = ExprError(); 10309 return true; 10310 } 10311 10312 // Fix the expression to refer to 'fn'. 10313 SingleFunctionExpression = 10314 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10315 10316 // If desired, do function-to-pointer decay. 10317 if (doFunctionPointerConverion) { 10318 SingleFunctionExpression = 10319 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10320 if (SingleFunctionExpression.isInvalid()) { 10321 SrcExpr = ExprError(); 10322 return true; 10323 } 10324 } 10325 } 10326 10327 if (!SingleFunctionExpression.isUsable()) { 10328 if (complain) { 10329 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10330 << ovl.Expression->getName() 10331 << DestTypeForComplaining 10332 << OpRangeForComplaining 10333 << ovl.Expression->getQualifierLoc().getSourceRange(); 10334 NoteAllOverloadCandidates(SrcExpr.get()); 10335 10336 SrcExpr = ExprError(); 10337 return true; 10338 } 10339 10340 return false; 10341 } 10342 10343 SrcExpr = SingleFunctionExpression; 10344 return true; 10345 } 10346 10347 /// \brief Add a single candidate to the overload set. 10348 static void AddOverloadedCallCandidate(Sema &S, 10349 DeclAccessPair FoundDecl, 10350 TemplateArgumentListInfo *ExplicitTemplateArgs, 10351 ArrayRef<Expr *> Args, 10352 OverloadCandidateSet &CandidateSet, 10353 bool PartialOverloading, 10354 bool KnownValid) { 10355 NamedDecl *Callee = FoundDecl.getDecl(); 10356 if (isa<UsingShadowDecl>(Callee)) 10357 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10358 10359 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10360 if (ExplicitTemplateArgs) { 10361 assert(!KnownValid && "Explicit template arguments?"); 10362 return; 10363 } 10364 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10365 /*SuppressUsedConversions=*/false, 10366 PartialOverloading); 10367 return; 10368 } 10369 10370 if (FunctionTemplateDecl *FuncTemplate 10371 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10372 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10373 ExplicitTemplateArgs, Args, CandidateSet, 10374 /*SuppressUsedConversions=*/false, 10375 PartialOverloading); 10376 return; 10377 } 10378 10379 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10380 } 10381 10382 /// \brief Add the overload candidates named by callee and/or found by argument 10383 /// dependent lookup to the given overload set. 10384 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10385 ArrayRef<Expr *> Args, 10386 OverloadCandidateSet &CandidateSet, 10387 bool PartialOverloading) { 10388 10389 #ifndef NDEBUG 10390 // Verify that ArgumentDependentLookup is consistent with the rules 10391 // in C++0x [basic.lookup.argdep]p3: 10392 // 10393 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10394 // and let Y be the lookup set produced by argument dependent 10395 // lookup (defined as follows). If X contains 10396 // 10397 // -- a declaration of a class member, or 10398 // 10399 // -- a block-scope function declaration that is not a 10400 // using-declaration, or 10401 // 10402 // -- a declaration that is neither a function or a function 10403 // template 10404 // 10405 // then Y is empty. 10406 10407 if (ULE->requiresADL()) { 10408 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10409 E = ULE->decls_end(); I != E; ++I) { 10410 assert(!(*I)->getDeclContext()->isRecord()); 10411 assert(isa<UsingShadowDecl>(*I) || 10412 !(*I)->getDeclContext()->isFunctionOrMethod()); 10413 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10414 } 10415 } 10416 #endif 10417 10418 // It would be nice to avoid this copy. 10419 TemplateArgumentListInfo TABuffer; 10420 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10421 if (ULE->hasExplicitTemplateArgs()) { 10422 ULE->copyTemplateArgumentsInto(TABuffer); 10423 ExplicitTemplateArgs = &TABuffer; 10424 } 10425 10426 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10427 E = ULE->decls_end(); I != E; ++I) 10428 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10429 CandidateSet, PartialOverloading, 10430 /*KnownValid*/ true); 10431 10432 if (ULE->requiresADL()) 10433 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10434 Args, ExplicitTemplateArgs, 10435 CandidateSet, PartialOverloading); 10436 } 10437 10438 /// Determine whether a declaration with the specified name could be moved into 10439 /// a different namespace. 10440 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10441 switch (Name.getCXXOverloadedOperator()) { 10442 case OO_New: case OO_Array_New: 10443 case OO_Delete: case OO_Array_Delete: 10444 return false; 10445 10446 default: 10447 return true; 10448 } 10449 } 10450 10451 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10452 /// template, where the non-dependent name was declared after the template 10453 /// was defined. This is common in code written for a compilers which do not 10454 /// correctly implement two-stage name lookup. 10455 /// 10456 /// Returns true if a viable candidate was found and a diagnostic was issued. 10457 static bool 10458 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10459 const CXXScopeSpec &SS, LookupResult &R, 10460 OverloadCandidateSet::CandidateSetKind CSK, 10461 TemplateArgumentListInfo *ExplicitTemplateArgs, 10462 ArrayRef<Expr *> Args) { 10463 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10464 return false; 10465 10466 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10467 if (DC->isTransparentContext()) 10468 continue; 10469 10470 SemaRef.LookupQualifiedName(R, DC); 10471 10472 if (!R.empty()) { 10473 R.suppressDiagnostics(); 10474 10475 if (isa<CXXRecordDecl>(DC)) { 10476 // Don't diagnose names we find in classes; we get much better 10477 // diagnostics for these from DiagnoseEmptyLookup. 10478 R.clear(); 10479 return false; 10480 } 10481 10482 OverloadCandidateSet Candidates(FnLoc, CSK); 10483 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10484 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10485 ExplicitTemplateArgs, Args, 10486 Candidates, false, /*KnownValid*/ false); 10487 10488 OverloadCandidateSet::iterator Best; 10489 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10490 // No viable functions. Don't bother the user with notes for functions 10491 // which don't work and shouldn't be found anyway. 10492 R.clear(); 10493 return false; 10494 } 10495 10496 // Find the namespaces where ADL would have looked, and suggest 10497 // declaring the function there instead. 10498 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10499 Sema::AssociatedClassSet AssociatedClasses; 10500 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10501 AssociatedNamespaces, 10502 AssociatedClasses); 10503 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10504 if (canBeDeclaredInNamespace(R.getLookupName())) { 10505 DeclContext *Std = SemaRef.getStdNamespace(); 10506 for (Sema::AssociatedNamespaceSet::iterator 10507 it = AssociatedNamespaces.begin(), 10508 end = AssociatedNamespaces.end(); it != end; ++it) { 10509 // Never suggest declaring a function within namespace 'std'. 10510 if (Std && Std->Encloses(*it)) 10511 continue; 10512 10513 // Never suggest declaring a function within a namespace with a 10514 // reserved name, like __gnu_cxx. 10515 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10516 if (NS && 10517 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10518 continue; 10519 10520 SuggestedNamespaces.insert(*it); 10521 } 10522 } 10523 10524 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10525 << R.getLookupName(); 10526 if (SuggestedNamespaces.empty()) { 10527 SemaRef.Diag(Best->Function->getLocation(), 10528 diag::note_not_found_by_two_phase_lookup) 10529 << R.getLookupName() << 0; 10530 } else if (SuggestedNamespaces.size() == 1) { 10531 SemaRef.Diag(Best->Function->getLocation(), 10532 diag::note_not_found_by_two_phase_lookup) 10533 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10534 } else { 10535 // FIXME: It would be useful to list the associated namespaces here, 10536 // but the diagnostics infrastructure doesn't provide a way to produce 10537 // a localized representation of a list of items. 10538 SemaRef.Diag(Best->Function->getLocation(), 10539 diag::note_not_found_by_two_phase_lookup) 10540 << R.getLookupName() << 2; 10541 } 10542 10543 // Try to recover by calling this function. 10544 return true; 10545 } 10546 10547 R.clear(); 10548 } 10549 10550 return false; 10551 } 10552 10553 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10554 /// template, where the non-dependent operator was declared after the template 10555 /// was defined. 10556 /// 10557 /// Returns true if a viable candidate was found and a diagnostic was issued. 10558 static bool 10559 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10560 SourceLocation OpLoc, 10561 ArrayRef<Expr *> Args) { 10562 DeclarationName OpName = 10563 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10564 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10565 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10566 OverloadCandidateSet::CSK_Operator, 10567 /*ExplicitTemplateArgs=*/nullptr, Args); 10568 } 10569 10570 namespace { 10571 class BuildRecoveryCallExprRAII { 10572 Sema &SemaRef; 10573 public: 10574 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10575 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10576 SemaRef.IsBuildingRecoveryCallExpr = true; 10577 } 10578 10579 ~BuildRecoveryCallExprRAII() { 10580 SemaRef.IsBuildingRecoveryCallExpr = false; 10581 } 10582 }; 10583 10584 } 10585 10586 static std::unique_ptr<CorrectionCandidateCallback> 10587 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 10588 bool HasTemplateArgs, bool AllowTypoCorrection) { 10589 if (!AllowTypoCorrection) 10590 return llvm::make_unique<NoTypoCorrectionCCC>(); 10591 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 10592 HasTemplateArgs, ME); 10593 } 10594 10595 /// Attempts to recover from a call where no functions were found. 10596 /// 10597 /// Returns true if new candidates were found. 10598 static ExprResult 10599 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10600 UnresolvedLookupExpr *ULE, 10601 SourceLocation LParenLoc, 10602 MutableArrayRef<Expr *> Args, 10603 SourceLocation RParenLoc, 10604 bool EmptyLookup, bool AllowTypoCorrection) { 10605 // Do not try to recover if it is already building a recovery call. 10606 // This stops infinite loops for template instantiations like 10607 // 10608 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10609 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10610 // 10611 if (SemaRef.IsBuildingRecoveryCallExpr) 10612 return ExprError(); 10613 BuildRecoveryCallExprRAII RCE(SemaRef); 10614 10615 CXXScopeSpec SS; 10616 SS.Adopt(ULE->getQualifierLoc()); 10617 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10618 10619 TemplateArgumentListInfo TABuffer; 10620 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10621 if (ULE->hasExplicitTemplateArgs()) { 10622 ULE->copyTemplateArgumentsInto(TABuffer); 10623 ExplicitTemplateArgs = &TABuffer; 10624 } 10625 10626 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10627 Sema::LookupOrdinaryName); 10628 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10629 OverloadCandidateSet::CSK_Normal, 10630 ExplicitTemplateArgs, Args) && 10631 (!EmptyLookup || 10632 SemaRef.DiagnoseEmptyLookup( 10633 S, SS, R, 10634 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 10635 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 10636 ExplicitTemplateArgs, Args))) 10637 return ExprError(); 10638 10639 assert(!R.empty() && "lookup results empty despite recovery"); 10640 10641 // Build an implicit member call if appropriate. Just drop the 10642 // casts and such from the call, we don't really care. 10643 ExprResult NewFn = ExprError(); 10644 if ((*R.begin())->isCXXClassMember()) 10645 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10646 R, ExplicitTemplateArgs); 10647 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10648 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10649 ExplicitTemplateArgs); 10650 else 10651 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10652 10653 if (NewFn.isInvalid()) 10654 return ExprError(); 10655 10656 // This shouldn't cause an infinite loop because we're giving it 10657 // an expression with viable lookup results, which should never 10658 // end up here. 10659 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 10660 MultiExprArg(Args.data(), Args.size()), 10661 RParenLoc); 10662 } 10663 10664 /// \brief Constructs and populates an OverloadedCandidateSet from 10665 /// the given function. 10666 /// \returns true when an the ExprResult output parameter has been set. 10667 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10668 UnresolvedLookupExpr *ULE, 10669 MultiExprArg Args, 10670 SourceLocation RParenLoc, 10671 OverloadCandidateSet *CandidateSet, 10672 ExprResult *Result) { 10673 #ifndef NDEBUG 10674 if (ULE->requiresADL()) { 10675 // To do ADL, we must have found an unqualified name. 10676 assert(!ULE->getQualifier() && "qualified name with ADL"); 10677 10678 // We don't perform ADL for implicit declarations of builtins. 10679 // Verify that this was correctly set up. 10680 FunctionDecl *F; 10681 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10682 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10683 F->getBuiltinID() && F->isImplicit()) 10684 llvm_unreachable("performing ADL for builtin"); 10685 10686 // We don't perform ADL in C. 10687 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10688 } 10689 #endif 10690 10691 UnbridgedCastsSet UnbridgedCasts; 10692 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10693 *Result = ExprError(); 10694 return true; 10695 } 10696 10697 // Add the functions denoted by the callee to the set of candidate 10698 // functions, including those from argument-dependent lookup. 10699 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10700 10701 // If we found nothing, try to recover. 10702 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10703 // out if it fails. 10704 if (CandidateSet->empty()) { 10705 // In Microsoft mode, if we are inside a template class member function then 10706 // create a type dependent CallExpr. The goal is to postpone name lookup 10707 // to instantiation time to be able to search into type dependent base 10708 // classes. 10709 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && 10710 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10711 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10712 Context.DependentTy, VK_RValue, 10713 RParenLoc); 10714 CE->setTypeDependent(true); 10715 *Result = CE; 10716 return true; 10717 } 10718 return false; 10719 } 10720 10721 UnbridgedCasts.restore(); 10722 return false; 10723 } 10724 10725 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10726 /// the completed call expression. If overload resolution fails, emits 10727 /// diagnostics and returns ExprError() 10728 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10729 UnresolvedLookupExpr *ULE, 10730 SourceLocation LParenLoc, 10731 MultiExprArg Args, 10732 SourceLocation RParenLoc, 10733 Expr *ExecConfig, 10734 OverloadCandidateSet *CandidateSet, 10735 OverloadCandidateSet::iterator *Best, 10736 OverloadingResult OverloadResult, 10737 bool AllowTypoCorrection) { 10738 if (CandidateSet->empty()) 10739 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10740 RParenLoc, /*EmptyLookup=*/true, 10741 AllowTypoCorrection); 10742 10743 switch (OverloadResult) { 10744 case OR_Success: { 10745 FunctionDecl *FDecl = (*Best)->Function; 10746 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10747 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10748 return ExprError(); 10749 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10750 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10751 ExecConfig); 10752 } 10753 10754 case OR_No_Viable_Function: { 10755 // Try to recover by looking for viable functions which the user might 10756 // have meant to call. 10757 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10758 Args, RParenLoc, 10759 /*EmptyLookup=*/false, 10760 AllowTypoCorrection); 10761 if (!Recovery.isInvalid()) 10762 return Recovery; 10763 10764 SemaRef.Diag(Fn->getLocStart(), 10765 diag::err_ovl_no_viable_function_in_call) 10766 << ULE->getName() << Fn->getSourceRange(); 10767 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10768 break; 10769 } 10770 10771 case OR_Ambiguous: 10772 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10773 << ULE->getName() << Fn->getSourceRange(); 10774 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10775 break; 10776 10777 case OR_Deleted: { 10778 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10779 << (*Best)->Function->isDeleted() 10780 << ULE->getName() 10781 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10782 << Fn->getSourceRange(); 10783 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10784 10785 // We emitted an error for the unvailable/deleted function call but keep 10786 // the call in the AST. 10787 FunctionDecl *FDecl = (*Best)->Function; 10788 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10789 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10790 ExecConfig); 10791 } 10792 } 10793 10794 // Overload resolution failed. 10795 return ExprError(); 10796 } 10797 10798 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 10799 /// (which eventually refers to the declaration Func) and the call 10800 /// arguments Args/NumArgs, attempt to resolve the function call down 10801 /// to a specific function. If overload resolution succeeds, returns 10802 /// the call expression produced by overload resolution. 10803 /// Otherwise, emits diagnostics and returns ExprError. 10804 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10805 UnresolvedLookupExpr *ULE, 10806 SourceLocation LParenLoc, 10807 MultiExprArg Args, 10808 SourceLocation RParenLoc, 10809 Expr *ExecConfig, 10810 bool AllowTypoCorrection) { 10811 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 10812 OverloadCandidateSet::CSK_Normal); 10813 ExprResult result; 10814 10815 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10816 &result)) 10817 return result; 10818 10819 OverloadCandidateSet::iterator Best; 10820 OverloadingResult OverloadResult = 10821 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10822 10823 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10824 RParenLoc, ExecConfig, &CandidateSet, 10825 &Best, OverloadResult, 10826 AllowTypoCorrection); 10827 } 10828 10829 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10830 return Functions.size() > 1 || 10831 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10832 } 10833 10834 /// \brief Create a unary operation that may resolve to an overloaded 10835 /// operator. 10836 /// 10837 /// \param OpLoc The location of the operator itself (e.g., '*'). 10838 /// 10839 /// \param OpcIn The UnaryOperator::Opcode that describes this 10840 /// operator. 10841 /// 10842 /// \param Fns The set of non-member functions that will be 10843 /// considered by overload resolution. The caller needs to build this 10844 /// set based on the context using, e.g., 10845 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10846 /// set should not contain any member functions; those will be added 10847 /// by CreateOverloadedUnaryOp(). 10848 /// 10849 /// \param Input The input argument. 10850 ExprResult 10851 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10852 const UnresolvedSetImpl &Fns, 10853 Expr *Input) { 10854 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10855 10856 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10857 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10858 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10859 // TODO: provide better source location info. 10860 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10861 10862 if (checkPlaceholderForOverload(*this, Input)) 10863 return ExprError(); 10864 10865 Expr *Args[2] = { Input, nullptr }; 10866 unsigned NumArgs = 1; 10867 10868 // For post-increment and post-decrement, add the implicit '0' as 10869 // the second argument, so that we know this is a post-increment or 10870 // post-decrement. 10871 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10872 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10873 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10874 SourceLocation()); 10875 NumArgs = 2; 10876 } 10877 10878 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10879 10880 if (Input->isTypeDependent()) { 10881 if (Fns.empty()) 10882 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 10883 VK_RValue, OK_Ordinary, OpLoc); 10884 10885 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 10886 UnresolvedLookupExpr *Fn 10887 = UnresolvedLookupExpr::Create(Context, NamingClass, 10888 NestedNameSpecifierLoc(), OpNameInfo, 10889 /*ADL*/ true, IsOverloaded(Fns), 10890 Fns.begin(), Fns.end()); 10891 return new (Context) 10892 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 10893 VK_RValue, OpLoc, false); 10894 } 10895 10896 // Build an empty overload set. 10897 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 10898 10899 // Add the candidates from the given function set. 10900 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 10901 10902 // Add operator candidates that are member functions. 10903 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10904 10905 // Add candidates from ADL. 10906 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 10907 /*ExplicitTemplateArgs*/nullptr, 10908 CandidateSet); 10909 10910 // Add builtin operator candidates. 10911 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10912 10913 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10914 10915 // Perform overload resolution. 10916 OverloadCandidateSet::iterator Best; 10917 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10918 case OR_Success: { 10919 // We found a built-in operator or an overloaded operator. 10920 FunctionDecl *FnDecl = Best->Function; 10921 10922 if (FnDecl) { 10923 // We matched an overloaded operator. Build a call to that 10924 // operator. 10925 10926 // Convert the arguments. 10927 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10928 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 10929 10930 ExprResult InputRes = 10931 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 10932 Best->FoundDecl, Method); 10933 if (InputRes.isInvalid()) 10934 return ExprError(); 10935 Input = InputRes.get(); 10936 } else { 10937 // Convert the arguments. 10938 ExprResult InputInit 10939 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10940 Context, 10941 FnDecl->getParamDecl(0)), 10942 SourceLocation(), 10943 Input); 10944 if (InputInit.isInvalid()) 10945 return ExprError(); 10946 Input = InputInit.get(); 10947 } 10948 10949 // Build the actual expression node. 10950 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10951 HadMultipleCandidates, OpLoc); 10952 if (FnExpr.isInvalid()) 10953 return ExprError(); 10954 10955 // Determine the result type. 10956 QualType ResultTy = FnDecl->getReturnType(); 10957 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10958 ResultTy = ResultTy.getNonLValueExprType(Context); 10959 10960 Args[0] = Input; 10961 CallExpr *TheCall = 10962 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 10963 ResultTy, VK, OpLoc, false); 10964 10965 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 10966 return ExprError(); 10967 10968 return MaybeBindToTemporary(TheCall); 10969 } else { 10970 // We matched a built-in operator. Convert the arguments, then 10971 // break out so that we will build the appropriate built-in 10972 // operator node. 10973 ExprResult InputRes = 10974 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10975 Best->Conversions[0], AA_Passing); 10976 if (InputRes.isInvalid()) 10977 return ExprError(); 10978 Input = InputRes.get(); 10979 break; 10980 } 10981 } 10982 10983 case OR_No_Viable_Function: 10984 // This is an erroneous use of an operator which can be overloaded by 10985 // a non-member function. Check for non-member operators which were 10986 // defined too late to be candidates. 10987 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10988 // FIXME: Recover by calling the found function. 10989 return ExprError(); 10990 10991 // No viable function; fall through to handling this as a 10992 // built-in operator, which will produce an error message for us. 10993 break; 10994 10995 case OR_Ambiguous: 10996 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10997 << UnaryOperator::getOpcodeStr(Opc) 10998 << Input->getType() 10999 << Input->getSourceRange(); 11000 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11001 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11002 return ExprError(); 11003 11004 case OR_Deleted: 11005 Diag(OpLoc, diag::err_ovl_deleted_oper) 11006 << Best->Function->isDeleted() 11007 << UnaryOperator::getOpcodeStr(Opc) 11008 << getDeletedOrUnavailableSuffix(Best->Function) 11009 << Input->getSourceRange(); 11010 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11011 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11012 return ExprError(); 11013 } 11014 11015 // Either we found no viable overloaded operator or we matched a 11016 // built-in operator. In either case, fall through to trying to 11017 // build a built-in operation. 11018 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11019 } 11020 11021 /// \brief Create a binary operation that may resolve to an overloaded 11022 /// operator. 11023 /// 11024 /// \param OpLoc The location of the operator itself (e.g., '+'). 11025 /// 11026 /// \param OpcIn The BinaryOperator::Opcode that describes this 11027 /// operator. 11028 /// 11029 /// \param Fns The set of non-member functions that will be 11030 /// considered by overload resolution. The caller needs to build this 11031 /// set based on the context using, e.g., 11032 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11033 /// set should not contain any member functions; those will be added 11034 /// by CreateOverloadedBinOp(). 11035 /// 11036 /// \param LHS Left-hand argument. 11037 /// \param RHS Right-hand argument. 11038 ExprResult 11039 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11040 unsigned OpcIn, 11041 const UnresolvedSetImpl &Fns, 11042 Expr *LHS, Expr *RHS) { 11043 Expr *Args[2] = { LHS, RHS }; 11044 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11045 11046 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 11047 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11048 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11049 11050 // If either side is type-dependent, create an appropriate dependent 11051 // expression. 11052 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11053 if (Fns.empty()) { 11054 // If there are no functions to store, just build a dependent 11055 // BinaryOperator or CompoundAssignment. 11056 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11057 return new (Context) BinaryOperator( 11058 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11059 OpLoc, FPFeatures.fp_contract); 11060 11061 return new (Context) CompoundAssignOperator( 11062 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11063 Context.DependentTy, Context.DependentTy, OpLoc, 11064 FPFeatures.fp_contract); 11065 } 11066 11067 // FIXME: save results of ADL from here? 11068 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11069 // TODO: provide better source location info in DNLoc component. 11070 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11071 UnresolvedLookupExpr *Fn 11072 = UnresolvedLookupExpr::Create(Context, NamingClass, 11073 NestedNameSpecifierLoc(), OpNameInfo, 11074 /*ADL*/ true, IsOverloaded(Fns), 11075 Fns.begin(), Fns.end()); 11076 return new (Context) 11077 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11078 VK_RValue, OpLoc, FPFeatures.fp_contract); 11079 } 11080 11081 // Always do placeholder-like conversions on the RHS. 11082 if (checkPlaceholderForOverload(*this, Args[1])) 11083 return ExprError(); 11084 11085 // Do placeholder-like conversion on the LHS; note that we should 11086 // not get here with a PseudoObject LHS. 11087 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11088 if (checkPlaceholderForOverload(*this, Args[0])) 11089 return ExprError(); 11090 11091 // If this is the assignment operator, we only perform overload resolution 11092 // if the left-hand side is a class or enumeration type. This is actually 11093 // a hack. The standard requires that we do overload resolution between the 11094 // various built-in candidates, but as DR507 points out, this can lead to 11095 // problems. So we do it this way, which pretty much follows what GCC does. 11096 // Note that we go the traditional code path for compound assignment forms. 11097 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11098 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11099 11100 // If this is the .* operator, which is not overloadable, just 11101 // create a built-in binary operator. 11102 if (Opc == BO_PtrMemD) 11103 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11104 11105 // Build an empty overload set. 11106 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11107 11108 // Add the candidates from the given function set. 11109 AddFunctionCandidates(Fns, Args, CandidateSet); 11110 11111 // Add operator candidates that are member functions. 11112 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11113 11114 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11115 // performed for an assignment operator (nor for operator[] nor operator->, 11116 // which don't get here). 11117 if (Opc != BO_Assign) 11118 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11119 /*ExplicitTemplateArgs*/ nullptr, 11120 CandidateSet); 11121 11122 // Add builtin operator candidates. 11123 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11124 11125 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11126 11127 // Perform overload resolution. 11128 OverloadCandidateSet::iterator Best; 11129 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11130 case OR_Success: { 11131 // We found a built-in operator or an overloaded operator. 11132 FunctionDecl *FnDecl = Best->Function; 11133 11134 if (FnDecl) { 11135 // We matched an overloaded operator. Build a call to that 11136 // operator. 11137 11138 // Convert the arguments. 11139 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11140 // Best->Access is only meaningful for class members. 11141 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11142 11143 ExprResult Arg1 = 11144 PerformCopyInitialization( 11145 InitializedEntity::InitializeParameter(Context, 11146 FnDecl->getParamDecl(0)), 11147 SourceLocation(), Args[1]); 11148 if (Arg1.isInvalid()) 11149 return ExprError(); 11150 11151 ExprResult Arg0 = 11152 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11153 Best->FoundDecl, Method); 11154 if (Arg0.isInvalid()) 11155 return ExprError(); 11156 Args[0] = Arg0.getAs<Expr>(); 11157 Args[1] = RHS = Arg1.getAs<Expr>(); 11158 } else { 11159 // Convert the arguments. 11160 ExprResult Arg0 = PerformCopyInitialization( 11161 InitializedEntity::InitializeParameter(Context, 11162 FnDecl->getParamDecl(0)), 11163 SourceLocation(), Args[0]); 11164 if (Arg0.isInvalid()) 11165 return ExprError(); 11166 11167 ExprResult Arg1 = 11168 PerformCopyInitialization( 11169 InitializedEntity::InitializeParameter(Context, 11170 FnDecl->getParamDecl(1)), 11171 SourceLocation(), Args[1]); 11172 if (Arg1.isInvalid()) 11173 return ExprError(); 11174 Args[0] = LHS = Arg0.getAs<Expr>(); 11175 Args[1] = RHS = Arg1.getAs<Expr>(); 11176 } 11177 11178 // Build the actual expression node. 11179 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11180 Best->FoundDecl, 11181 HadMultipleCandidates, OpLoc); 11182 if (FnExpr.isInvalid()) 11183 return ExprError(); 11184 11185 // Determine the result type. 11186 QualType ResultTy = FnDecl->getReturnType(); 11187 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11188 ResultTy = ResultTy.getNonLValueExprType(Context); 11189 11190 CXXOperatorCallExpr *TheCall = 11191 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11192 Args, ResultTy, VK, OpLoc, 11193 FPFeatures.fp_contract); 11194 11195 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11196 FnDecl)) 11197 return ExprError(); 11198 11199 ArrayRef<const Expr *> ArgsArray(Args, 2); 11200 // Cut off the implicit 'this'. 11201 if (isa<CXXMethodDecl>(FnDecl)) 11202 ArgsArray = ArgsArray.slice(1); 11203 11204 // Check for a self move. 11205 if (Op == OO_Equal) 11206 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11207 11208 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 11209 TheCall->getSourceRange(), VariadicDoesNotApply); 11210 11211 return MaybeBindToTemporary(TheCall); 11212 } else { 11213 // We matched a built-in operator. Convert the arguments, then 11214 // break out so that we will build the appropriate built-in 11215 // operator node. 11216 ExprResult ArgsRes0 = 11217 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11218 Best->Conversions[0], AA_Passing); 11219 if (ArgsRes0.isInvalid()) 11220 return ExprError(); 11221 Args[0] = ArgsRes0.get(); 11222 11223 ExprResult ArgsRes1 = 11224 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11225 Best->Conversions[1], AA_Passing); 11226 if (ArgsRes1.isInvalid()) 11227 return ExprError(); 11228 Args[1] = ArgsRes1.get(); 11229 break; 11230 } 11231 } 11232 11233 case OR_No_Viable_Function: { 11234 // C++ [over.match.oper]p9: 11235 // If the operator is the operator , [...] and there are no 11236 // viable functions, then the operator is assumed to be the 11237 // built-in operator and interpreted according to clause 5. 11238 if (Opc == BO_Comma) 11239 break; 11240 11241 // For class as left operand for assignment or compound assigment 11242 // operator do not fall through to handling in built-in, but report that 11243 // no overloaded assignment operator found 11244 ExprResult Result = ExprError(); 11245 if (Args[0]->getType()->isRecordType() && 11246 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11247 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11248 << BinaryOperator::getOpcodeStr(Opc) 11249 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11250 if (Args[0]->getType()->isIncompleteType()) { 11251 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11252 << Args[0]->getType() 11253 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11254 } 11255 } else { 11256 // This is an erroneous use of an operator which can be overloaded by 11257 // a non-member function. Check for non-member operators which were 11258 // defined too late to be candidates. 11259 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11260 // FIXME: Recover by calling the found function. 11261 return ExprError(); 11262 11263 // No viable function; try to create a built-in operation, which will 11264 // produce an error. Then, show the non-viable candidates. 11265 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11266 } 11267 assert(Result.isInvalid() && 11268 "C++ binary operator overloading is missing candidates!"); 11269 if (Result.isInvalid()) 11270 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11271 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11272 return Result; 11273 } 11274 11275 case OR_Ambiguous: 11276 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11277 << BinaryOperator::getOpcodeStr(Opc) 11278 << Args[0]->getType() << Args[1]->getType() 11279 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11280 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11281 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11282 return ExprError(); 11283 11284 case OR_Deleted: 11285 if (isImplicitlyDeleted(Best->Function)) { 11286 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11287 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11288 << Context.getRecordType(Method->getParent()) 11289 << getSpecialMember(Method); 11290 11291 // The user probably meant to call this special member. Just 11292 // explain why it's deleted. 11293 NoteDeletedFunction(Method); 11294 return ExprError(); 11295 } else { 11296 Diag(OpLoc, diag::err_ovl_deleted_oper) 11297 << Best->Function->isDeleted() 11298 << BinaryOperator::getOpcodeStr(Opc) 11299 << getDeletedOrUnavailableSuffix(Best->Function) 11300 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11301 } 11302 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11303 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11304 return ExprError(); 11305 } 11306 11307 // We matched a built-in operator; build it. 11308 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11309 } 11310 11311 ExprResult 11312 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11313 SourceLocation RLoc, 11314 Expr *Base, Expr *Idx) { 11315 Expr *Args[2] = { Base, Idx }; 11316 DeclarationName OpName = 11317 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11318 11319 // If either side is type-dependent, create an appropriate dependent 11320 // expression. 11321 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11322 11323 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11324 // CHECKME: no 'operator' keyword? 11325 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11326 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11327 UnresolvedLookupExpr *Fn 11328 = UnresolvedLookupExpr::Create(Context, NamingClass, 11329 NestedNameSpecifierLoc(), OpNameInfo, 11330 /*ADL*/ true, /*Overloaded*/ false, 11331 UnresolvedSetIterator(), 11332 UnresolvedSetIterator()); 11333 // Can't add any actual overloads yet 11334 11335 return new (Context) 11336 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11337 Context.DependentTy, VK_RValue, RLoc, false); 11338 } 11339 11340 // Handle placeholders on both operands. 11341 if (checkPlaceholderForOverload(*this, Args[0])) 11342 return ExprError(); 11343 if (checkPlaceholderForOverload(*this, Args[1])) 11344 return ExprError(); 11345 11346 // Build an empty overload set. 11347 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11348 11349 // Subscript can only be overloaded as a member function. 11350 11351 // Add operator candidates that are member functions. 11352 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11353 11354 // Add builtin operator candidates. 11355 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11356 11357 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11358 11359 // Perform overload resolution. 11360 OverloadCandidateSet::iterator Best; 11361 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11362 case OR_Success: { 11363 // We found a built-in operator or an overloaded operator. 11364 FunctionDecl *FnDecl = Best->Function; 11365 11366 if (FnDecl) { 11367 // We matched an overloaded operator. Build a call to that 11368 // operator. 11369 11370 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11371 11372 // Convert the arguments. 11373 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11374 ExprResult Arg0 = 11375 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11376 Best->FoundDecl, Method); 11377 if (Arg0.isInvalid()) 11378 return ExprError(); 11379 Args[0] = Arg0.get(); 11380 11381 // Convert the arguments. 11382 ExprResult InputInit 11383 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11384 Context, 11385 FnDecl->getParamDecl(0)), 11386 SourceLocation(), 11387 Args[1]); 11388 if (InputInit.isInvalid()) 11389 return ExprError(); 11390 11391 Args[1] = InputInit.getAs<Expr>(); 11392 11393 // Build the actual expression node. 11394 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11395 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11396 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11397 Best->FoundDecl, 11398 HadMultipleCandidates, 11399 OpLocInfo.getLoc(), 11400 OpLocInfo.getInfo()); 11401 if (FnExpr.isInvalid()) 11402 return ExprError(); 11403 11404 // Determine the result type 11405 QualType ResultTy = FnDecl->getReturnType(); 11406 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11407 ResultTy = ResultTy.getNonLValueExprType(Context); 11408 11409 CXXOperatorCallExpr *TheCall = 11410 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11411 FnExpr.get(), Args, 11412 ResultTy, VK, RLoc, 11413 false); 11414 11415 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11416 return ExprError(); 11417 11418 return MaybeBindToTemporary(TheCall); 11419 } else { 11420 // We matched a built-in operator. Convert the arguments, then 11421 // break out so that we will build the appropriate built-in 11422 // operator node. 11423 ExprResult ArgsRes0 = 11424 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11425 Best->Conversions[0], AA_Passing); 11426 if (ArgsRes0.isInvalid()) 11427 return ExprError(); 11428 Args[0] = ArgsRes0.get(); 11429 11430 ExprResult ArgsRes1 = 11431 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11432 Best->Conversions[1], AA_Passing); 11433 if (ArgsRes1.isInvalid()) 11434 return ExprError(); 11435 Args[1] = ArgsRes1.get(); 11436 11437 break; 11438 } 11439 } 11440 11441 case OR_No_Viable_Function: { 11442 if (CandidateSet.empty()) 11443 Diag(LLoc, diag::err_ovl_no_oper) 11444 << Args[0]->getType() << /*subscript*/ 0 11445 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11446 else 11447 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11448 << Args[0]->getType() 11449 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11450 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11451 "[]", LLoc); 11452 return ExprError(); 11453 } 11454 11455 case OR_Ambiguous: 11456 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11457 << "[]" 11458 << Args[0]->getType() << Args[1]->getType() 11459 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11460 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11461 "[]", LLoc); 11462 return ExprError(); 11463 11464 case OR_Deleted: 11465 Diag(LLoc, diag::err_ovl_deleted_oper) 11466 << Best->Function->isDeleted() << "[]" 11467 << getDeletedOrUnavailableSuffix(Best->Function) 11468 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11469 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11470 "[]", LLoc); 11471 return ExprError(); 11472 } 11473 11474 // We matched a built-in operator; build it. 11475 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11476 } 11477 11478 /// BuildCallToMemberFunction - Build a call to a member 11479 /// function. MemExpr is the expression that refers to the member 11480 /// function (and includes the object parameter), Args/NumArgs are the 11481 /// arguments to the function call (not including the object 11482 /// parameter). The caller needs to validate that the member 11483 /// expression refers to a non-static member function or an overloaded 11484 /// member function. 11485 ExprResult 11486 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11487 SourceLocation LParenLoc, 11488 MultiExprArg Args, 11489 SourceLocation RParenLoc) { 11490 assert(MemExprE->getType() == Context.BoundMemberTy || 11491 MemExprE->getType() == Context.OverloadTy); 11492 11493 // Dig out the member expression. This holds both the object 11494 // argument and the member function we're referring to. 11495 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11496 11497 // Determine whether this is a call to a pointer-to-member function. 11498 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11499 assert(op->getType() == Context.BoundMemberTy); 11500 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11501 11502 QualType fnType = 11503 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11504 11505 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11506 QualType resultType = proto->getCallResultType(Context); 11507 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11508 11509 // Check that the object type isn't more qualified than the 11510 // member function we're calling. 11511 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11512 11513 QualType objectType = op->getLHS()->getType(); 11514 if (op->getOpcode() == BO_PtrMemI) 11515 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11516 Qualifiers objectQuals = objectType.getQualifiers(); 11517 11518 Qualifiers difference = objectQuals - funcQuals; 11519 difference.removeObjCGCAttr(); 11520 difference.removeAddressSpace(); 11521 if (difference) { 11522 std::string qualsString = difference.getAsString(); 11523 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11524 << fnType.getUnqualifiedType() 11525 << qualsString 11526 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11527 } 11528 11529 if (resultType->isMemberPointerType()) 11530 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11531 RequireCompleteType(LParenLoc, resultType, 0); 11532 11533 CXXMemberCallExpr *call 11534 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11535 resultType, valueKind, RParenLoc); 11536 11537 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11538 call, nullptr)) 11539 return ExprError(); 11540 11541 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 11542 return ExprError(); 11543 11544 if (CheckOtherCall(call, proto)) 11545 return ExprError(); 11546 11547 return MaybeBindToTemporary(call); 11548 } 11549 11550 UnbridgedCastsSet UnbridgedCasts; 11551 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11552 return ExprError(); 11553 11554 MemberExpr *MemExpr; 11555 CXXMethodDecl *Method = nullptr; 11556 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 11557 NestedNameSpecifier *Qualifier = nullptr; 11558 if (isa<MemberExpr>(NakedMemExpr)) { 11559 MemExpr = cast<MemberExpr>(NakedMemExpr); 11560 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11561 FoundDecl = MemExpr->getFoundDecl(); 11562 Qualifier = MemExpr->getQualifier(); 11563 UnbridgedCasts.restore(); 11564 } else { 11565 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11566 Qualifier = UnresExpr->getQualifier(); 11567 11568 QualType ObjectType = UnresExpr->getBaseType(); 11569 Expr::Classification ObjectClassification 11570 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11571 : UnresExpr->getBase()->Classify(Context); 11572 11573 // Add overload candidates 11574 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 11575 OverloadCandidateSet::CSK_Normal); 11576 11577 // FIXME: avoid copy. 11578 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 11579 if (UnresExpr->hasExplicitTemplateArgs()) { 11580 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11581 TemplateArgs = &TemplateArgsBuffer; 11582 } 11583 11584 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11585 E = UnresExpr->decls_end(); I != E; ++I) { 11586 11587 NamedDecl *Func = *I; 11588 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11589 if (isa<UsingShadowDecl>(Func)) 11590 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11591 11592 11593 // Microsoft supports direct constructor calls. 11594 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11595 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11596 Args, CandidateSet); 11597 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11598 // If explicit template arguments were provided, we can't call a 11599 // non-template member function. 11600 if (TemplateArgs) 11601 continue; 11602 11603 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11604 ObjectClassification, Args, CandidateSet, 11605 /*SuppressUserConversions=*/false); 11606 } else { 11607 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11608 I.getPair(), ActingDC, TemplateArgs, 11609 ObjectType, ObjectClassification, 11610 Args, CandidateSet, 11611 /*SuppressUsedConversions=*/false); 11612 } 11613 } 11614 11615 DeclarationName DeclName = UnresExpr->getMemberName(); 11616 11617 UnbridgedCasts.restore(); 11618 11619 OverloadCandidateSet::iterator Best; 11620 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11621 Best)) { 11622 case OR_Success: 11623 Method = cast<CXXMethodDecl>(Best->Function); 11624 FoundDecl = Best->FoundDecl; 11625 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11626 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11627 return ExprError(); 11628 // If FoundDecl is different from Method (such as if one is a template 11629 // and the other a specialization), make sure DiagnoseUseOfDecl is 11630 // called on both. 11631 // FIXME: This would be more comprehensively addressed by modifying 11632 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11633 // being used. 11634 if (Method != FoundDecl.getDecl() && 11635 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11636 return ExprError(); 11637 break; 11638 11639 case OR_No_Viable_Function: 11640 Diag(UnresExpr->getMemberLoc(), 11641 diag::err_ovl_no_viable_member_function_in_call) 11642 << DeclName << MemExprE->getSourceRange(); 11643 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11644 // FIXME: Leaking incoming expressions! 11645 return ExprError(); 11646 11647 case OR_Ambiguous: 11648 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11649 << DeclName << MemExprE->getSourceRange(); 11650 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11651 // FIXME: Leaking incoming expressions! 11652 return ExprError(); 11653 11654 case OR_Deleted: 11655 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11656 << Best->Function->isDeleted() 11657 << DeclName 11658 << getDeletedOrUnavailableSuffix(Best->Function) 11659 << MemExprE->getSourceRange(); 11660 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11661 // FIXME: Leaking incoming expressions! 11662 return ExprError(); 11663 } 11664 11665 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11666 11667 // If overload resolution picked a static member, build a 11668 // non-member call based on that function. 11669 if (Method->isStatic()) { 11670 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11671 RParenLoc); 11672 } 11673 11674 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11675 } 11676 11677 QualType ResultType = Method->getReturnType(); 11678 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11679 ResultType = ResultType.getNonLValueExprType(Context); 11680 11681 assert(Method && "Member call to something that isn't a method?"); 11682 CXXMemberCallExpr *TheCall = 11683 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11684 ResultType, VK, RParenLoc); 11685 11686 // (CUDA B.1): Check for invalid calls between targets. 11687 if (getLangOpts().CUDA) { 11688 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 11689 if (CheckCUDATarget(Caller, Method)) { 11690 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 11691 << IdentifyCUDATarget(Method) << Method->getIdentifier() 11692 << IdentifyCUDATarget(Caller); 11693 return ExprError(); 11694 } 11695 } 11696 } 11697 11698 // Check for a valid return type. 11699 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 11700 TheCall, Method)) 11701 return ExprError(); 11702 11703 // Convert the object argument (for a non-static member function call). 11704 // We only need to do this if there was actually an overload; otherwise 11705 // it was done at lookup. 11706 if (!Method->isStatic()) { 11707 ExprResult ObjectArg = 11708 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11709 FoundDecl, Method); 11710 if (ObjectArg.isInvalid()) 11711 return ExprError(); 11712 MemExpr->setBase(ObjectArg.get()); 11713 } 11714 11715 // Convert the rest of the arguments 11716 const FunctionProtoType *Proto = 11717 Method->getType()->getAs<FunctionProtoType>(); 11718 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11719 RParenLoc)) 11720 return ExprError(); 11721 11722 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11723 11724 if (CheckFunctionCall(Method, TheCall, Proto)) 11725 return ExprError(); 11726 11727 if ((isa<CXXConstructorDecl>(CurContext) || 11728 isa<CXXDestructorDecl>(CurContext)) && 11729 TheCall->getMethodDecl()->isPure()) { 11730 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11731 11732 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11733 Diag(MemExpr->getLocStart(), 11734 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11735 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11736 << MD->getParent()->getDeclName(); 11737 11738 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11739 } 11740 } 11741 return MaybeBindToTemporary(TheCall); 11742 } 11743 11744 /// BuildCallToObjectOfClassType - Build a call to an object of class 11745 /// type (C++ [over.call.object]), which can end up invoking an 11746 /// overloaded function call operator (@c operator()) or performing a 11747 /// user-defined conversion on the object argument. 11748 ExprResult 11749 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11750 SourceLocation LParenLoc, 11751 MultiExprArg Args, 11752 SourceLocation RParenLoc) { 11753 if (checkPlaceholderForOverload(*this, Obj)) 11754 return ExprError(); 11755 ExprResult Object = Obj; 11756 11757 UnbridgedCastsSet UnbridgedCasts; 11758 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11759 return ExprError(); 11760 11761 assert(Object.get()->getType()->isRecordType() && 11762 "Requires object type argument"); 11763 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11764 11765 // C++ [over.call.object]p1: 11766 // If the primary-expression E in the function call syntax 11767 // evaluates to a class object of type "cv T", then the set of 11768 // candidate functions includes at least the function call 11769 // operators of T. The function call operators of T are obtained by 11770 // ordinary lookup of the name operator() in the context of 11771 // (E).operator(). 11772 OverloadCandidateSet CandidateSet(LParenLoc, 11773 OverloadCandidateSet::CSK_Operator); 11774 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11775 11776 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11777 diag::err_incomplete_object_call, Object.get())) 11778 return true; 11779 11780 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11781 LookupQualifiedName(R, Record->getDecl()); 11782 R.suppressDiagnostics(); 11783 11784 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11785 Oper != OperEnd; ++Oper) { 11786 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11787 Object.get()->Classify(Context), 11788 Args, CandidateSet, 11789 /*SuppressUserConversions=*/ false); 11790 } 11791 11792 // C++ [over.call.object]p2: 11793 // In addition, for each (non-explicit in C++0x) conversion function 11794 // declared in T of the form 11795 // 11796 // operator conversion-type-id () cv-qualifier; 11797 // 11798 // where cv-qualifier is the same cv-qualification as, or a 11799 // greater cv-qualification than, cv, and where conversion-type-id 11800 // denotes the type "pointer to function of (P1,...,Pn) returning 11801 // R", or the type "reference to pointer to function of 11802 // (P1,...,Pn) returning R", or the type "reference to function 11803 // of (P1,...,Pn) returning R", a surrogate call function [...] 11804 // is also considered as a candidate function. Similarly, 11805 // surrogate call functions are added to the set of candidate 11806 // functions for each conversion function declared in an 11807 // accessible base class provided the function is not hidden 11808 // within T by another intervening declaration. 11809 std::pair<CXXRecordDecl::conversion_iterator, 11810 CXXRecordDecl::conversion_iterator> Conversions 11811 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11812 for (CXXRecordDecl::conversion_iterator 11813 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11814 NamedDecl *D = *I; 11815 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11816 if (isa<UsingShadowDecl>(D)) 11817 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11818 11819 // Skip over templated conversion functions; they aren't 11820 // surrogates. 11821 if (isa<FunctionTemplateDecl>(D)) 11822 continue; 11823 11824 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11825 if (!Conv->isExplicit()) { 11826 // Strip the reference type (if any) and then the pointer type (if 11827 // any) to get down to what might be a function type. 11828 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11829 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11830 ConvType = ConvPtrType->getPointeeType(); 11831 11832 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11833 { 11834 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11835 Object.get(), Args, CandidateSet); 11836 } 11837 } 11838 } 11839 11840 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11841 11842 // Perform overload resolution. 11843 OverloadCandidateSet::iterator Best; 11844 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11845 Best)) { 11846 case OR_Success: 11847 // Overload resolution succeeded; we'll build the appropriate call 11848 // below. 11849 break; 11850 11851 case OR_No_Viable_Function: 11852 if (CandidateSet.empty()) 11853 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11854 << Object.get()->getType() << /*call*/ 1 11855 << Object.get()->getSourceRange(); 11856 else 11857 Diag(Object.get()->getLocStart(), 11858 diag::err_ovl_no_viable_object_call) 11859 << Object.get()->getType() << Object.get()->getSourceRange(); 11860 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11861 break; 11862 11863 case OR_Ambiguous: 11864 Diag(Object.get()->getLocStart(), 11865 diag::err_ovl_ambiguous_object_call) 11866 << Object.get()->getType() << Object.get()->getSourceRange(); 11867 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11868 break; 11869 11870 case OR_Deleted: 11871 Diag(Object.get()->getLocStart(), 11872 diag::err_ovl_deleted_object_call) 11873 << Best->Function->isDeleted() 11874 << Object.get()->getType() 11875 << getDeletedOrUnavailableSuffix(Best->Function) 11876 << Object.get()->getSourceRange(); 11877 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11878 break; 11879 } 11880 11881 if (Best == CandidateSet.end()) 11882 return true; 11883 11884 UnbridgedCasts.restore(); 11885 11886 if (Best->Function == nullptr) { 11887 // Since there is no function declaration, this is one of the 11888 // surrogate candidates. Dig out the conversion function. 11889 CXXConversionDecl *Conv 11890 = cast<CXXConversionDecl>( 11891 Best->Conversions[0].UserDefined.ConversionFunction); 11892 11893 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 11894 Best->FoundDecl); 11895 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11896 return ExprError(); 11897 assert(Conv == Best->FoundDecl.getDecl() && 11898 "Found Decl & conversion-to-functionptr should be same, right?!"); 11899 // We selected one of the surrogate functions that converts the 11900 // object parameter to a function pointer. Perform the conversion 11901 // on the object argument, then let ActOnCallExpr finish the job. 11902 11903 // Create an implicit member expr to refer to the conversion operator. 11904 // and then call it. 11905 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11906 Conv, HadMultipleCandidates); 11907 if (Call.isInvalid()) 11908 return ExprError(); 11909 // Record usage of conversion in an implicit cast. 11910 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 11911 CK_UserDefinedConversion, Call.get(), 11912 nullptr, VK_RValue); 11913 11914 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11915 } 11916 11917 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 11918 11919 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11920 // that calls this method, using Object for the implicit object 11921 // parameter and passing along the remaining arguments. 11922 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11923 11924 // An error diagnostic has already been printed when parsing the declaration. 11925 if (Method->isInvalidDecl()) 11926 return ExprError(); 11927 11928 const FunctionProtoType *Proto = 11929 Method->getType()->getAs<FunctionProtoType>(); 11930 11931 unsigned NumParams = Proto->getNumParams(); 11932 11933 DeclarationNameInfo OpLocInfo( 11934 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11935 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11936 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11937 HadMultipleCandidates, 11938 OpLocInfo.getLoc(), 11939 OpLocInfo.getInfo()); 11940 if (NewFn.isInvalid()) 11941 return true; 11942 11943 // Build the full argument list for the method call (the implicit object 11944 // parameter is placed at the beginning of the list). 11945 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 11946 MethodArgs[0] = Object.get(); 11947 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 11948 11949 // Once we've built TheCall, all of the expressions are properly 11950 // owned. 11951 QualType ResultTy = Method->getReturnType(); 11952 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11953 ResultTy = ResultTy.getNonLValueExprType(Context); 11954 11955 CXXOperatorCallExpr *TheCall = new (Context) 11956 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 11957 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 11958 ResultTy, VK, RParenLoc, false); 11959 MethodArgs.reset(); 11960 11961 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 11962 return true; 11963 11964 // We may have default arguments. If so, we need to allocate more 11965 // slots in the call for them. 11966 if (Args.size() < NumParams) 11967 TheCall->setNumArgs(Context, NumParams + 1); 11968 11969 bool IsError = false; 11970 11971 // Initialize the implicit object parameter. 11972 ExprResult ObjRes = 11973 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 11974 Best->FoundDecl, Method); 11975 if (ObjRes.isInvalid()) 11976 IsError = true; 11977 else 11978 Object = ObjRes; 11979 TheCall->setArg(0, Object.get()); 11980 11981 // Check the argument types. 11982 for (unsigned i = 0; i != NumParams; i++) { 11983 Expr *Arg; 11984 if (i < Args.size()) { 11985 Arg = Args[i]; 11986 11987 // Pass the argument. 11988 11989 ExprResult InputInit 11990 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11991 Context, 11992 Method->getParamDecl(i)), 11993 SourceLocation(), Arg); 11994 11995 IsError |= InputInit.isInvalid(); 11996 Arg = InputInit.getAs<Expr>(); 11997 } else { 11998 ExprResult DefArg 11999 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12000 if (DefArg.isInvalid()) { 12001 IsError = true; 12002 break; 12003 } 12004 12005 Arg = DefArg.getAs<Expr>(); 12006 } 12007 12008 TheCall->setArg(i + 1, Arg); 12009 } 12010 12011 // If this is a variadic call, handle args passed through "...". 12012 if (Proto->isVariadic()) { 12013 // Promote the arguments (C99 6.5.2.2p7). 12014 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12015 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12016 nullptr); 12017 IsError |= Arg.isInvalid(); 12018 TheCall->setArg(i + 1, Arg.get()); 12019 } 12020 } 12021 12022 if (IsError) return true; 12023 12024 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12025 12026 if (CheckFunctionCall(Method, TheCall, Proto)) 12027 return true; 12028 12029 return MaybeBindToTemporary(TheCall); 12030 } 12031 12032 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12033 /// (if one exists), where @c Base is an expression of class type and 12034 /// @c Member is the name of the member we're trying to find. 12035 ExprResult 12036 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12037 bool *NoArrowOperatorFound) { 12038 assert(Base->getType()->isRecordType() && 12039 "left-hand side must have class type"); 12040 12041 if (checkPlaceholderForOverload(*this, Base)) 12042 return ExprError(); 12043 12044 SourceLocation Loc = Base->getExprLoc(); 12045 12046 // C++ [over.ref]p1: 12047 // 12048 // [...] An expression x->m is interpreted as (x.operator->())->m 12049 // for a class object x of type T if T::operator->() exists and if 12050 // the operator is selected as the best match function by the 12051 // overload resolution mechanism (13.3). 12052 DeclarationName OpName = 12053 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12054 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12055 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12056 12057 if (RequireCompleteType(Loc, Base->getType(), 12058 diag::err_typecheck_incomplete_tag, Base)) 12059 return ExprError(); 12060 12061 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12062 LookupQualifiedName(R, BaseRecord->getDecl()); 12063 R.suppressDiagnostics(); 12064 12065 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12066 Oper != OperEnd; ++Oper) { 12067 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12068 None, CandidateSet, /*SuppressUserConversions=*/false); 12069 } 12070 12071 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12072 12073 // Perform overload resolution. 12074 OverloadCandidateSet::iterator Best; 12075 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12076 case OR_Success: 12077 // Overload resolution succeeded; we'll build the call below. 12078 break; 12079 12080 case OR_No_Viable_Function: 12081 if (CandidateSet.empty()) { 12082 QualType BaseType = Base->getType(); 12083 if (NoArrowOperatorFound) { 12084 // Report this specific error to the caller instead of emitting a 12085 // diagnostic, as requested. 12086 *NoArrowOperatorFound = true; 12087 return ExprError(); 12088 } 12089 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12090 << BaseType << Base->getSourceRange(); 12091 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12092 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12093 << FixItHint::CreateReplacement(OpLoc, "."); 12094 } 12095 } else 12096 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12097 << "operator->" << Base->getSourceRange(); 12098 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12099 return ExprError(); 12100 12101 case OR_Ambiguous: 12102 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12103 << "->" << Base->getType() << Base->getSourceRange(); 12104 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12105 return ExprError(); 12106 12107 case OR_Deleted: 12108 Diag(OpLoc, diag::err_ovl_deleted_oper) 12109 << Best->Function->isDeleted() 12110 << "->" 12111 << getDeletedOrUnavailableSuffix(Best->Function) 12112 << Base->getSourceRange(); 12113 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12114 return ExprError(); 12115 } 12116 12117 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12118 12119 // Convert the object parameter. 12120 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12121 ExprResult BaseResult = 12122 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12123 Best->FoundDecl, Method); 12124 if (BaseResult.isInvalid()) 12125 return ExprError(); 12126 Base = BaseResult.get(); 12127 12128 // Build the operator call. 12129 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12130 HadMultipleCandidates, OpLoc); 12131 if (FnExpr.isInvalid()) 12132 return ExprError(); 12133 12134 QualType ResultTy = Method->getReturnType(); 12135 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12136 ResultTy = ResultTy.getNonLValueExprType(Context); 12137 CXXOperatorCallExpr *TheCall = 12138 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12139 Base, ResultTy, VK, OpLoc, false); 12140 12141 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12142 return ExprError(); 12143 12144 return MaybeBindToTemporary(TheCall); 12145 } 12146 12147 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12148 /// a literal operator described by the provided lookup results. 12149 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12150 DeclarationNameInfo &SuffixInfo, 12151 ArrayRef<Expr*> Args, 12152 SourceLocation LitEndLoc, 12153 TemplateArgumentListInfo *TemplateArgs) { 12154 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12155 12156 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12157 OverloadCandidateSet::CSK_Normal); 12158 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12159 /*SuppressUserConversions=*/true); 12160 12161 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12162 12163 // Perform overload resolution. This will usually be trivial, but might need 12164 // to perform substitutions for a literal operator template. 12165 OverloadCandidateSet::iterator Best; 12166 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12167 case OR_Success: 12168 case OR_Deleted: 12169 break; 12170 12171 case OR_No_Viable_Function: 12172 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12173 << R.getLookupName(); 12174 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12175 return ExprError(); 12176 12177 case OR_Ambiguous: 12178 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12179 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12180 return ExprError(); 12181 } 12182 12183 FunctionDecl *FD = Best->Function; 12184 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12185 HadMultipleCandidates, 12186 SuffixInfo.getLoc(), 12187 SuffixInfo.getInfo()); 12188 if (Fn.isInvalid()) 12189 return true; 12190 12191 // Check the argument types. This should almost always be a no-op, except 12192 // that array-to-pointer decay is applied to string literals. 12193 Expr *ConvArgs[2]; 12194 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12195 ExprResult InputInit = PerformCopyInitialization( 12196 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12197 SourceLocation(), Args[ArgIdx]); 12198 if (InputInit.isInvalid()) 12199 return true; 12200 ConvArgs[ArgIdx] = InputInit.get(); 12201 } 12202 12203 QualType ResultTy = FD->getReturnType(); 12204 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12205 ResultTy = ResultTy.getNonLValueExprType(Context); 12206 12207 UserDefinedLiteral *UDL = 12208 new (Context) UserDefinedLiteral(Context, Fn.get(), 12209 llvm::makeArrayRef(ConvArgs, Args.size()), 12210 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12211 12212 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12213 return ExprError(); 12214 12215 if (CheckFunctionCall(FD, UDL, nullptr)) 12216 return ExprError(); 12217 12218 return MaybeBindToTemporary(UDL); 12219 } 12220 12221 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12222 /// given LookupResult is non-empty, it is assumed to describe a member which 12223 /// will be invoked. Otherwise, the function will be found via argument 12224 /// dependent lookup. 12225 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12226 /// otherwise CallExpr is set to ExprError() and some non-success value 12227 /// is returned. 12228 Sema::ForRangeStatus 12229 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 12230 SourceLocation RangeLoc, VarDecl *Decl, 12231 BeginEndFunction BEF, 12232 const DeclarationNameInfo &NameInfo, 12233 LookupResult &MemberLookup, 12234 OverloadCandidateSet *CandidateSet, 12235 Expr *Range, ExprResult *CallExpr) { 12236 CandidateSet->clear(); 12237 if (!MemberLookup.empty()) { 12238 ExprResult MemberRef = 12239 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12240 /*IsPtr=*/false, CXXScopeSpec(), 12241 /*TemplateKWLoc=*/SourceLocation(), 12242 /*FirstQualifierInScope=*/nullptr, 12243 MemberLookup, 12244 /*TemplateArgs=*/nullptr); 12245 if (MemberRef.isInvalid()) { 12246 *CallExpr = ExprError(); 12247 Diag(Range->getLocStart(), diag::note_in_for_range) 12248 << RangeLoc << BEF << Range->getType(); 12249 return FRS_DiagnosticIssued; 12250 } 12251 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12252 if (CallExpr->isInvalid()) { 12253 *CallExpr = ExprError(); 12254 Diag(Range->getLocStart(), diag::note_in_for_range) 12255 << RangeLoc << BEF << Range->getType(); 12256 return FRS_DiagnosticIssued; 12257 } 12258 } else { 12259 UnresolvedSet<0> FoundNames; 12260 UnresolvedLookupExpr *Fn = 12261 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12262 NestedNameSpecifierLoc(), NameInfo, 12263 /*NeedsADL=*/true, /*Overloaded=*/false, 12264 FoundNames.begin(), FoundNames.end()); 12265 12266 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12267 CandidateSet, CallExpr); 12268 if (CandidateSet->empty() || CandidateSetError) { 12269 *CallExpr = ExprError(); 12270 return FRS_NoViableFunction; 12271 } 12272 OverloadCandidateSet::iterator Best; 12273 OverloadingResult OverloadResult = 12274 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12275 12276 if (OverloadResult == OR_No_Viable_Function) { 12277 *CallExpr = ExprError(); 12278 return FRS_NoViableFunction; 12279 } 12280 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12281 Loc, nullptr, CandidateSet, &Best, 12282 OverloadResult, 12283 /*AllowTypoCorrection=*/false); 12284 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12285 *CallExpr = ExprError(); 12286 Diag(Range->getLocStart(), diag::note_in_for_range) 12287 << RangeLoc << BEF << Range->getType(); 12288 return FRS_DiagnosticIssued; 12289 } 12290 } 12291 return FRS_Success; 12292 } 12293 12294 12295 /// FixOverloadedFunctionReference - E is an expression that refers to 12296 /// a C++ overloaded function (possibly with some parentheses and 12297 /// perhaps a '&' around it). We have resolved the overloaded function 12298 /// to the function declaration Fn, so patch up the expression E to 12299 /// refer (possibly indirectly) to Fn. Returns the new expr. 12300 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12301 FunctionDecl *Fn) { 12302 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12303 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12304 Found, Fn); 12305 if (SubExpr == PE->getSubExpr()) 12306 return PE; 12307 12308 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12309 } 12310 12311 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12312 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12313 Found, Fn); 12314 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12315 SubExpr->getType()) && 12316 "Implicit cast type cannot be determined from overload"); 12317 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12318 if (SubExpr == ICE->getSubExpr()) 12319 return ICE; 12320 12321 return ImplicitCastExpr::Create(Context, ICE->getType(), 12322 ICE->getCastKind(), 12323 SubExpr, nullptr, 12324 ICE->getValueKind()); 12325 } 12326 12327 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12328 assert(UnOp->getOpcode() == UO_AddrOf && 12329 "Can only take the address of an overloaded function"); 12330 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12331 if (Method->isStatic()) { 12332 // Do nothing: static member functions aren't any different 12333 // from non-member functions. 12334 } else { 12335 // Fix the subexpression, which really has to be an 12336 // UnresolvedLookupExpr holding an overloaded member function 12337 // or template. 12338 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12339 Found, Fn); 12340 if (SubExpr == UnOp->getSubExpr()) 12341 return UnOp; 12342 12343 assert(isa<DeclRefExpr>(SubExpr) 12344 && "fixed to something other than a decl ref"); 12345 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12346 && "fixed to a member ref with no nested name qualifier"); 12347 12348 // We have taken the address of a pointer to member 12349 // function. Perform the computation here so that we get the 12350 // appropriate pointer to member type. 12351 QualType ClassType 12352 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12353 QualType MemPtrType 12354 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12355 12356 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12357 VK_RValue, OK_Ordinary, 12358 UnOp->getOperatorLoc()); 12359 } 12360 } 12361 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12362 Found, Fn); 12363 if (SubExpr == UnOp->getSubExpr()) 12364 return UnOp; 12365 12366 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12367 Context.getPointerType(SubExpr->getType()), 12368 VK_RValue, OK_Ordinary, 12369 UnOp->getOperatorLoc()); 12370 } 12371 12372 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12373 // FIXME: avoid copy. 12374 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12375 if (ULE->hasExplicitTemplateArgs()) { 12376 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12377 TemplateArgs = &TemplateArgsBuffer; 12378 } 12379 12380 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12381 ULE->getQualifierLoc(), 12382 ULE->getTemplateKeywordLoc(), 12383 Fn, 12384 /*enclosing*/ false, // FIXME? 12385 ULE->getNameLoc(), 12386 Fn->getType(), 12387 VK_LValue, 12388 Found.getDecl(), 12389 TemplateArgs); 12390 MarkDeclRefReferenced(DRE); 12391 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12392 return DRE; 12393 } 12394 12395 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12396 // FIXME: avoid copy. 12397 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12398 if (MemExpr->hasExplicitTemplateArgs()) { 12399 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12400 TemplateArgs = &TemplateArgsBuffer; 12401 } 12402 12403 Expr *Base; 12404 12405 // If we're filling in a static method where we used to have an 12406 // implicit member access, rewrite to a simple decl ref. 12407 if (MemExpr->isImplicitAccess()) { 12408 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12409 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12410 MemExpr->getQualifierLoc(), 12411 MemExpr->getTemplateKeywordLoc(), 12412 Fn, 12413 /*enclosing*/ false, 12414 MemExpr->getMemberLoc(), 12415 Fn->getType(), 12416 VK_LValue, 12417 Found.getDecl(), 12418 TemplateArgs); 12419 MarkDeclRefReferenced(DRE); 12420 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12421 return DRE; 12422 } else { 12423 SourceLocation Loc = MemExpr->getMemberLoc(); 12424 if (MemExpr->getQualifier()) 12425 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12426 CheckCXXThisCapture(Loc); 12427 Base = new (Context) CXXThisExpr(Loc, 12428 MemExpr->getBaseType(), 12429 /*isImplicit=*/true); 12430 } 12431 } else 12432 Base = MemExpr->getBase(); 12433 12434 ExprValueKind valueKind; 12435 QualType type; 12436 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12437 valueKind = VK_LValue; 12438 type = Fn->getType(); 12439 } else { 12440 valueKind = VK_RValue; 12441 type = Context.BoundMemberTy; 12442 } 12443 12444 MemberExpr *ME = MemberExpr::Create(Context, Base, 12445 MemExpr->isArrow(), 12446 MemExpr->getQualifierLoc(), 12447 MemExpr->getTemplateKeywordLoc(), 12448 Fn, 12449 Found, 12450 MemExpr->getMemberNameInfo(), 12451 TemplateArgs, 12452 type, valueKind, OK_Ordinary); 12453 ME->setHadMultipleCandidates(true); 12454 MarkMemberReferenced(ME); 12455 return ME; 12456 } 12457 12458 llvm_unreachable("Invalid reference to overloaded function"); 12459 } 12460 12461 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12462 DeclAccessPair Found, 12463 FunctionDecl *Fn) { 12464 return FixOverloadedFunctionReference(E.get(), Found, Fn); 12465 } 12466