SemaOverload.cpp revision 7419d013fd2c4dda596066f4864d5c40e85ba330
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/PartialDiagnostic.h" 24#include "clang/Lex/Preprocessor.h" 25#include "clang/Sema/Initialization.h" 26#include "clang/Sema/Lookup.h" 27#include "clang/Sema/SemaInternal.h" 28#include "clang/Sema/Template.h" 29#include "clang/Sema/TemplateDeduction.h" 30#include "llvm/ADT/DenseSet.h" 31#include "llvm/ADT/STLExtras.h" 32#include "llvm/ADT/SmallPtrSet.h" 33#include "llvm/ADT/SmallString.h" 34#include <algorithm> 35 36namespace clang { 37using namespace sema; 38 39/// A convenience routine for creating a decayed reference to a function. 40static ExprResult 41CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 42 bool HadMultipleCandidates, 43 SourceLocation Loc = SourceLocation(), 44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 45 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 46 return ExprError(); 47 // If FoundDecl is different from Fn (such as if one is a template 48 // and the other a specialization), make sure DiagnoseUseOfDecl is 49 // called on both. 50 // FIXME: This would be more comprehensively addressed by modifying 51 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 52 // being used. 53 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 54 return ExprError(); 55 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 56 VK_LValue, Loc, LocInfo); 57 if (HadMultipleCandidates) 58 DRE->setHadMultipleCandidates(true); 59 60 S.MarkDeclRefReferenced(DRE); 61 62 ExprResult E = S.Owned(DRE); 63 E = S.DefaultFunctionArrayConversion(E.take()); 64 if (E.isInvalid()) 65 return ExprError(); 66 return E; 67} 68 69static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 70 bool InOverloadResolution, 71 StandardConversionSequence &SCS, 72 bool CStyle, 73 bool AllowObjCWritebackConversion); 74 75static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 76 QualType &ToType, 77 bool InOverloadResolution, 78 StandardConversionSequence &SCS, 79 bool CStyle); 80static OverloadingResult 81IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 82 UserDefinedConversionSequence& User, 83 OverloadCandidateSet& Conversions, 84 bool AllowExplicit); 85 86 87static ImplicitConversionSequence::CompareKind 88CompareStandardConversionSequences(Sema &S, 89 const StandardConversionSequence& SCS1, 90 const StandardConversionSequence& SCS2); 91 92static ImplicitConversionSequence::CompareKind 93CompareQualificationConversions(Sema &S, 94 const StandardConversionSequence& SCS1, 95 const StandardConversionSequence& SCS2); 96 97static ImplicitConversionSequence::CompareKind 98CompareDerivedToBaseConversions(Sema &S, 99 const StandardConversionSequence& SCS1, 100 const StandardConversionSequence& SCS2); 101 102 103 104/// GetConversionCategory - Retrieve the implicit conversion 105/// category corresponding to the given implicit conversion kind. 106ImplicitConversionCategory 107GetConversionCategory(ImplicitConversionKind Kind) { 108 static const ImplicitConversionCategory 109 Category[(int)ICK_Num_Conversion_Kinds] = { 110 ICC_Identity, 111 ICC_Lvalue_Transformation, 112 ICC_Lvalue_Transformation, 113 ICC_Lvalue_Transformation, 114 ICC_Identity, 115 ICC_Qualification_Adjustment, 116 ICC_Promotion, 117 ICC_Promotion, 118 ICC_Promotion, 119 ICC_Conversion, 120 ICC_Conversion, 121 ICC_Conversion, 122 ICC_Conversion, 123 ICC_Conversion, 124 ICC_Conversion, 125 ICC_Conversion, 126 ICC_Conversion, 127 ICC_Conversion, 128 ICC_Conversion, 129 ICC_Conversion, 130 ICC_Conversion, 131 ICC_Conversion 132 }; 133 return Category[(int)Kind]; 134} 135 136/// GetConversionRank - Retrieve the implicit conversion rank 137/// corresponding to the given implicit conversion kind. 138ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 139 static const ImplicitConversionRank 140 Rank[(int)ICK_Num_Conversion_Kinds] = { 141 ICR_Exact_Match, 142 ICR_Exact_Match, 143 ICR_Exact_Match, 144 ICR_Exact_Match, 145 ICR_Exact_Match, 146 ICR_Exact_Match, 147 ICR_Promotion, 148 ICR_Promotion, 149 ICR_Promotion, 150 ICR_Conversion, 151 ICR_Conversion, 152 ICR_Conversion, 153 ICR_Conversion, 154 ICR_Conversion, 155 ICR_Conversion, 156 ICR_Conversion, 157 ICR_Conversion, 158 ICR_Conversion, 159 ICR_Conversion, 160 ICR_Conversion, 161 ICR_Complex_Real_Conversion, 162 ICR_Conversion, 163 ICR_Conversion, 164 ICR_Writeback_Conversion 165 }; 166 return Rank[(int)Kind]; 167} 168 169/// GetImplicitConversionName - Return the name of this kind of 170/// implicit conversion. 171const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 172 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 173 "No conversion", 174 "Lvalue-to-rvalue", 175 "Array-to-pointer", 176 "Function-to-pointer", 177 "Noreturn adjustment", 178 "Qualification", 179 "Integral promotion", 180 "Floating point promotion", 181 "Complex promotion", 182 "Integral conversion", 183 "Floating conversion", 184 "Complex conversion", 185 "Floating-integral conversion", 186 "Pointer conversion", 187 "Pointer-to-member conversion", 188 "Boolean conversion", 189 "Compatible-types conversion", 190 "Derived-to-base conversion", 191 "Vector conversion", 192 "Vector splat", 193 "Complex-real conversion", 194 "Block Pointer conversion", 195 "Transparent Union Conversion" 196 "Writeback conversion" 197 }; 198 return Name[Kind]; 199} 200 201/// StandardConversionSequence - Set the standard conversion 202/// sequence to the identity conversion. 203void StandardConversionSequence::setAsIdentityConversion() { 204 First = ICK_Identity; 205 Second = ICK_Identity; 206 Third = ICK_Identity; 207 DeprecatedStringLiteralToCharPtr = false; 208 QualificationIncludesObjCLifetime = false; 209 ReferenceBinding = false; 210 DirectBinding = false; 211 IsLvalueReference = true; 212 BindsToFunctionLvalue = false; 213 BindsToRvalue = false; 214 BindsImplicitObjectArgumentWithoutRefQualifier = false; 215 ObjCLifetimeConversionBinding = false; 216 CopyConstructor = 0; 217} 218 219/// getRank - Retrieve the rank of this standard conversion sequence 220/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 221/// implicit conversions. 222ImplicitConversionRank StandardConversionSequence::getRank() const { 223 ImplicitConversionRank Rank = ICR_Exact_Match; 224 if (GetConversionRank(First) > Rank) 225 Rank = GetConversionRank(First); 226 if (GetConversionRank(Second) > Rank) 227 Rank = GetConversionRank(Second); 228 if (GetConversionRank(Third) > Rank) 229 Rank = GetConversionRank(Third); 230 return Rank; 231} 232 233/// isPointerConversionToBool - Determines whether this conversion is 234/// a conversion of a pointer or pointer-to-member to bool. This is 235/// used as part of the ranking of standard conversion sequences 236/// (C++ 13.3.3.2p4). 237bool StandardConversionSequence::isPointerConversionToBool() const { 238 // Note that FromType has not necessarily been transformed by the 239 // array-to-pointer or function-to-pointer implicit conversions, so 240 // check for their presence as well as checking whether FromType is 241 // a pointer. 242 if (getToType(1)->isBooleanType() && 243 (getFromType()->isPointerType() || 244 getFromType()->isObjCObjectPointerType() || 245 getFromType()->isBlockPointerType() || 246 getFromType()->isNullPtrType() || 247 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 248 return true; 249 250 return false; 251} 252 253/// isPointerConversionToVoidPointer - Determines whether this 254/// conversion is a conversion of a pointer to a void pointer. This is 255/// used as part of the ranking of standard conversion sequences (C++ 256/// 13.3.3.2p4). 257bool 258StandardConversionSequence:: 259isPointerConversionToVoidPointer(ASTContext& Context) const { 260 QualType FromType = getFromType(); 261 QualType ToType = getToType(1); 262 263 // Note that FromType has not necessarily been transformed by the 264 // array-to-pointer implicit conversion, so check for its presence 265 // and redo the conversion to get a pointer. 266 if (First == ICK_Array_To_Pointer) 267 FromType = Context.getArrayDecayedType(FromType); 268 269 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 270 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 271 return ToPtrType->getPointeeType()->isVoidType(); 272 273 return false; 274} 275 276/// Skip any implicit casts which could be either part of a narrowing conversion 277/// or after one in an implicit conversion. 278static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 279 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 280 switch (ICE->getCastKind()) { 281 case CK_NoOp: 282 case CK_IntegralCast: 283 case CK_IntegralToBoolean: 284 case CK_IntegralToFloating: 285 case CK_FloatingToIntegral: 286 case CK_FloatingToBoolean: 287 case CK_FloatingCast: 288 Converted = ICE->getSubExpr(); 289 continue; 290 291 default: 292 return Converted; 293 } 294 } 295 296 return Converted; 297} 298 299/// Check if this standard conversion sequence represents a narrowing 300/// conversion, according to C++11 [dcl.init.list]p7. 301/// 302/// \param Ctx The AST context. 303/// \param Converted The result of applying this standard conversion sequence. 304/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 305/// value of the expression prior to the narrowing conversion. 306/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 307/// type of the expression prior to the narrowing conversion. 308NarrowingKind 309StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 310 const Expr *Converted, 311 APValue &ConstantValue, 312 QualType &ConstantType) const { 313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 314 315 // C++11 [dcl.init.list]p7: 316 // A narrowing conversion is an implicit conversion ... 317 QualType FromType = getToType(0); 318 QualType ToType = getToType(1); 319 switch (Second) { 320 // -- from a floating-point type to an integer type, or 321 // 322 // -- from an integer type or unscoped enumeration type to a floating-point 323 // type, except where the source is a constant expression and the actual 324 // value after conversion will fit into the target type and will produce 325 // the original value when converted back to the original type, or 326 case ICK_Floating_Integral: 327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 328 return NK_Type_Narrowing; 329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 330 llvm::APSInt IntConstantValue; 331 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 332 if (Initializer && 333 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 334 // Convert the integer to the floating type. 335 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 336 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 337 llvm::APFloat::rmNearestTiesToEven); 338 // And back. 339 llvm::APSInt ConvertedValue = IntConstantValue; 340 bool ignored; 341 Result.convertToInteger(ConvertedValue, 342 llvm::APFloat::rmTowardZero, &ignored); 343 // If the resulting value is different, this was a narrowing conversion. 344 if (IntConstantValue != ConvertedValue) { 345 ConstantValue = APValue(IntConstantValue); 346 ConstantType = Initializer->getType(); 347 return NK_Constant_Narrowing; 348 } 349 } else { 350 // Variables are always narrowings. 351 return NK_Variable_Narrowing; 352 } 353 } 354 return NK_Not_Narrowing; 355 356 // -- from long double to double or float, or from double to float, except 357 // where the source is a constant expression and the actual value after 358 // conversion is within the range of values that can be represented (even 359 // if it cannot be represented exactly), or 360 case ICK_Floating_Conversion: 361 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 362 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 363 // FromType is larger than ToType. 364 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 365 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 366 // Constant! 367 assert(ConstantValue.isFloat()); 368 llvm::APFloat FloatVal = ConstantValue.getFloat(); 369 // Convert the source value into the target type. 370 bool ignored; 371 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 372 Ctx.getFloatTypeSemantics(ToType), 373 llvm::APFloat::rmNearestTiesToEven, &ignored); 374 // If there was no overflow, the source value is within the range of 375 // values that can be represented. 376 if (ConvertStatus & llvm::APFloat::opOverflow) { 377 ConstantType = Initializer->getType(); 378 return NK_Constant_Narrowing; 379 } 380 } else { 381 return NK_Variable_Narrowing; 382 } 383 } 384 return NK_Not_Narrowing; 385 386 // -- from an integer type or unscoped enumeration type to an integer type 387 // that cannot represent all the values of the original type, except where 388 // the source is a constant expression and the actual value after 389 // conversion will fit into the target type and will produce the original 390 // value when converted back to the original type. 391 case ICK_Boolean_Conversion: // Bools are integers too. 392 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 393 // Boolean conversions can be from pointers and pointers to members 394 // [conv.bool], and those aren't considered narrowing conversions. 395 return NK_Not_Narrowing; 396 } // Otherwise, fall through to the integral case. 397 case ICK_Integral_Conversion: { 398 assert(FromType->isIntegralOrUnscopedEnumerationType()); 399 assert(ToType->isIntegralOrUnscopedEnumerationType()); 400 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 401 const unsigned FromWidth = Ctx.getIntWidth(FromType); 402 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 403 const unsigned ToWidth = Ctx.getIntWidth(ToType); 404 405 if (FromWidth > ToWidth || 406 (FromWidth == ToWidth && FromSigned != ToSigned) || 407 (FromSigned && !ToSigned)) { 408 // Not all values of FromType can be represented in ToType. 409 llvm::APSInt InitializerValue; 410 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 411 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 412 // Such conversions on variables are always narrowing. 413 return NK_Variable_Narrowing; 414 } 415 bool Narrowing = false; 416 if (FromWidth < ToWidth) { 417 // Negative -> unsigned is narrowing. Otherwise, more bits is never 418 // narrowing. 419 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 420 Narrowing = true; 421 } else { 422 // Add a bit to the InitializerValue so we don't have to worry about 423 // signed vs. unsigned comparisons. 424 InitializerValue = InitializerValue.extend( 425 InitializerValue.getBitWidth() + 1); 426 // Convert the initializer to and from the target width and signed-ness. 427 llvm::APSInt ConvertedValue = InitializerValue; 428 ConvertedValue = ConvertedValue.trunc(ToWidth); 429 ConvertedValue.setIsSigned(ToSigned); 430 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 431 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 432 // If the result is different, this was a narrowing conversion. 433 if (ConvertedValue != InitializerValue) 434 Narrowing = true; 435 } 436 if (Narrowing) { 437 ConstantType = Initializer->getType(); 438 ConstantValue = APValue(InitializerValue); 439 return NK_Constant_Narrowing; 440 } 441 } 442 return NK_Not_Narrowing; 443 } 444 445 default: 446 // Other kinds of conversions are not narrowings. 447 return NK_Not_Narrowing; 448 } 449} 450 451/// DebugPrint - Print this standard conversion sequence to standard 452/// error. Useful for debugging overloading issues. 453void StandardConversionSequence::DebugPrint() const { 454 raw_ostream &OS = llvm::errs(); 455 bool PrintedSomething = false; 456 if (First != ICK_Identity) { 457 OS << GetImplicitConversionName(First); 458 PrintedSomething = true; 459 } 460 461 if (Second != ICK_Identity) { 462 if (PrintedSomething) { 463 OS << " -> "; 464 } 465 OS << GetImplicitConversionName(Second); 466 467 if (CopyConstructor) { 468 OS << " (by copy constructor)"; 469 } else if (DirectBinding) { 470 OS << " (direct reference binding)"; 471 } else if (ReferenceBinding) { 472 OS << " (reference binding)"; 473 } 474 PrintedSomething = true; 475 } 476 477 if (Third != ICK_Identity) { 478 if (PrintedSomething) { 479 OS << " -> "; 480 } 481 OS << GetImplicitConversionName(Third); 482 PrintedSomething = true; 483 } 484 485 if (!PrintedSomething) { 486 OS << "No conversions required"; 487 } 488} 489 490/// DebugPrint - Print this user-defined conversion sequence to standard 491/// error. Useful for debugging overloading issues. 492void UserDefinedConversionSequence::DebugPrint() const { 493 raw_ostream &OS = llvm::errs(); 494 if (Before.First || Before.Second || Before.Third) { 495 Before.DebugPrint(); 496 OS << " -> "; 497 } 498 if (ConversionFunction) 499 OS << '\'' << *ConversionFunction << '\''; 500 else 501 OS << "aggregate initialization"; 502 if (After.First || After.Second || After.Third) { 503 OS << " -> "; 504 After.DebugPrint(); 505 } 506} 507 508/// DebugPrint - Print this implicit conversion sequence to standard 509/// error. Useful for debugging overloading issues. 510void ImplicitConversionSequence::DebugPrint() const { 511 raw_ostream &OS = llvm::errs(); 512 switch (ConversionKind) { 513 case StandardConversion: 514 OS << "Standard conversion: "; 515 Standard.DebugPrint(); 516 break; 517 case UserDefinedConversion: 518 OS << "User-defined conversion: "; 519 UserDefined.DebugPrint(); 520 break; 521 case EllipsisConversion: 522 OS << "Ellipsis conversion"; 523 break; 524 case AmbiguousConversion: 525 OS << "Ambiguous conversion"; 526 break; 527 case BadConversion: 528 OS << "Bad conversion"; 529 break; 530 } 531 532 OS << "\n"; 533} 534 535void AmbiguousConversionSequence::construct() { 536 new (&conversions()) ConversionSet(); 537} 538 539void AmbiguousConversionSequence::destruct() { 540 conversions().~ConversionSet(); 541} 542 543void 544AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 545 FromTypePtr = O.FromTypePtr; 546 ToTypePtr = O.ToTypePtr; 547 new (&conversions()) ConversionSet(O.conversions()); 548} 549 550namespace { 551 // Structure used by OverloadCandidate::DeductionFailureInfo to store 552 // template argument information. 553 struct DFIArguments { 554 TemplateArgument FirstArg; 555 TemplateArgument SecondArg; 556 }; 557 // Structure used by OverloadCandidate::DeductionFailureInfo to store 558 // template parameter and template argument information. 559 struct DFIParamWithArguments : DFIArguments { 560 TemplateParameter Param; 561 }; 562} 563 564/// \brief Convert from Sema's representation of template deduction information 565/// to the form used in overload-candidate information. 566OverloadCandidate::DeductionFailureInfo 567static MakeDeductionFailureInfo(ASTContext &Context, 568 Sema::TemplateDeductionResult TDK, 569 TemplateDeductionInfo &Info) { 570 OverloadCandidate::DeductionFailureInfo Result; 571 Result.Result = static_cast<unsigned>(TDK); 572 Result.HasDiagnostic = false; 573 Result.Data = 0; 574 switch (TDK) { 575 case Sema::TDK_Success: 576 case Sema::TDK_Invalid: 577 case Sema::TDK_InstantiationDepth: 578 case Sema::TDK_TooManyArguments: 579 case Sema::TDK_TooFewArguments: 580 break; 581 582 case Sema::TDK_Incomplete: 583 case Sema::TDK_InvalidExplicitArguments: 584 Result.Data = Info.Param.getOpaqueValue(); 585 break; 586 587 case Sema::TDK_NonDeducedMismatch: { 588 // FIXME: Should allocate from normal heap so that we can free this later. 589 DFIArguments *Saved = new (Context) DFIArguments; 590 Saved->FirstArg = Info.FirstArg; 591 Saved->SecondArg = Info.SecondArg; 592 Result.Data = Saved; 593 break; 594 } 595 596 case Sema::TDK_Inconsistent: 597 case Sema::TDK_Underqualified: { 598 // FIXME: Should allocate from normal heap so that we can free this later. 599 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 600 Saved->Param = Info.Param; 601 Saved->FirstArg = Info.FirstArg; 602 Saved->SecondArg = Info.SecondArg; 603 Result.Data = Saved; 604 break; 605 } 606 607 case Sema::TDK_SubstitutionFailure: 608 Result.Data = Info.take(); 609 if (Info.hasSFINAEDiagnostic()) { 610 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 611 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 612 Info.takeSFINAEDiagnostic(*Diag); 613 Result.HasDiagnostic = true; 614 } 615 break; 616 617 case Sema::TDK_FailedOverloadResolution: 618 Result.Data = Info.Expression; 619 break; 620 621 case Sema::TDK_MiscellaneousDeductionFailure: 622 break; 623 } 624 625 return Result; 626} 627 628void OverloadCandidate::DeductionFailureInfo::Destroy() { 629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 630 case Sema::TDK_Success: 631 case Sema::TDK_Invalid: 632 case Sema::TDK_InstantiationDepth: 633 case Sema::TDK_Incomplete: 634 case Sema::TDK_TooManyArguments: 635 case Sema::TDK_TooFewArguments: 636 case Sema::TDK_InvalidExplicitArguments: 637 case Sema::TDK_FailedOverloadResolution: 638 break; 639 640 case Sema::TDK_Inconsistent: 641 case Sema::TDK_Underqualified: 642 case Sema::TDK_NonDeducedMismatch: 643 // FIXME: Destroy the data? 644 Data = 0; 645 break; 646 647 case Sema::TDK_SubstitutionFailure: 648 // FIXME: Destroy the template argument list? 649 Data = 0; 650 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 651 Diag->~PartialDiagnosticAt(); 652 HasDiagnostic = false; 653 } 654 break; 655 656 // Unhandled 657 case Sema::TDK_MiscellaneousDeductionFailure: 658 break; 659 } 660} 661 662PartialDiagnosticAt * 663OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 664 if (HasDiagnostic) 665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 666 return 0; 667} 668 669TemplateParameter 670OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 671 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 672 case Sema::TDK_Success: 673 case Sema::TDK_Invalid: 674 case Sema::TDK_InstantiationDepth: 675 case Sema::TDK_TooManyArguments: 676 case Sema::TDK_TooFewArguments: 677 case Sema::TDK_SubstitutionFailure: 678 case Sema::TDK_NonDeducedMismatch: 679 case Sema::TDK_FailedOverloadResolution: 680 return TemplateParameter(); 681 682 case Sema::TDK_Incomplete: 683 case Sema::TDK_InvalidExplicitArguments: 684 return TemplateParameter::getFromOpaqueValue(Data); 685 686 case Sema::TDK_Inconsistent: 687 case Sema::TDK_Underqualified: 688 return static_cast<DFIParamWithArguments*>(Data)->Param; 689 690 // Unhandled 691 case Sema::TDK_MiscellaneousDeductionFailure: 692 break; 693 } 694 695 return TemplateParameter(); 696} 697 698TemplateArgumentList * 699OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 701 case Sema::TDK_Success: 702 case Sema::TDK_Invalid: 703 case Sema::TDK_InstantiationDepth: 704 case Sema::TDK_TooManyArguments: 705 case Sema::TDK_TooFewArguments: 706 case Sema::TDK_Incomplete: 707 case Sema::TDK_InvalidExplicitArguments: 708 case Sema::TDK_Inconsistent: 709 case Sema::TDK_Underqualified: 710 case Sema::TDK_NonDeducedMismatch: 711 case Sema::TDK_FailedOverloadResolution: 712 return 0; 713 714 case Sema::TDK_SubstitutionFailure: 715 return static_cast<TemplateArgumentList*>(Data); 716 717 // Unhandled 718 case Sema::TDK_MiscellaneousDeductionFailure: 719 break; 720 } 721 722 return 0; 723} 724 725const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 727 case Sema::TDK_Success: 728 case Sema::TDK_Invalid: 729 case Sema::TDK_InstantiationDepth: 730 case Sema::TDK_Incomplete: 731 case Sema::TDK_TooManyArguments: 732 case Sema::TDK_TooFewArguments: 733 case Sema::TDK_InvalidExplicitArguments: 734 case Sema::TDK_SubstitutionFailure: 735 case Sema::TDK_FailedOverloadResolution: 736 return 0; 737 738 case Sema::TDK_Inconsistent: 739 case Sema::TDK_Underqualified: 740 case Sema::TDK_NonDeducedMismatch: 741 return &static_cast<DFIArguments*>(Data)->FirstArg; 742 743 // Unhandled 744 case Sema::TDK_MiscellaneousDeductionFailure: 745 break; 746 } 747 748 return 0; 749} 750 751const TemplateArgument * 752OverloadCandidate::DeductionFailureInfo::getSecondArg() { 753 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 754 case Sema::TDK_Success: 755 case Sema::TDK_Invalid: 756 case Sema::TDK_InstantiationDepth: 757 case Sema::TDK_Incomplete: 758 case Sema::TDK_TooManyArguments: 759 case Sema::TDK_TooFewArguments: 760 case Sema::TDK_InvalidExplicitArguments: 761 case Sema::TDK_SubstitutionFailure: 762 case Sema::TDK_FailedOverloadResolution: 763 return 0; 764 765 case Sema::TDK_Inconsistent: 766 case Sema::TDK_Underqualified: 767 case Sema::TDK_NonDeducedMismatch: 768 return &static_cast<DFIArguments*>(Data)->SecondArg; 769 770 // Unhandled 771 case Sema::TDK_MiscellaneousDeductionFailure: 772 break; 773 } 774 775 return 0; 776} 777 778Expr * 779OverloadCandidate::DeductionFailureInfo::getExpr() { 780 if (static_cast<Sema::TemplateDeductionResult>(Result) == 781 Sema::TDK_FailedOverloadResolution) 782 return static_cast<Expr*>(Data); 783 784 return 0; 785} 786 787void OverloadCandidateSet::destroyCandidates() { 788 for (iterator i = begin(), e = end(); i != e; ++i) { 789 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 790 i->Conversions[ii].~ImplicitConversionSequence(); 791 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 792 i->DeductionFailure.Destroy(); 793 } 794} 795 796void OverloadCandidateSet::clear() { 797 destroyCandidates(); 798 NumInlineSequences = 0; 799 Candidates.clear(); 800 Functions.clear(); 801} 802 803namespace { 804 class UnbridgedCastsSet { 805 struct Entry { 806 Expr **Addr; 807 Expr *Saved; 808 }; 809 SmallVector<Entry, 2> Entries; 810 811 public: 812 void save(Sema &S, Expr *&E) { 813 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 814 Entry entry = { &E, E }; 815 Entries.push_back(entry); 816 E = S.stripARCUnbridgedCast(E); 817 } 818 819 void restore() { 820 for (SmallVectorImpl<Entry>::iterator 821 i = Entries.begin(), e = Entries.end(); i != e; ++i) 822 *i->Addr = i->Saved; 823 } 824 }; 825} 826 827/// checkPlaceholderForOverload - Do any interesting placeholder-like 828/// preprocessing on the given expression. 829/// 830/// \param unbridgedCasts a collection to which to add unbridged casts; 831/// without this, they will be immediately diagnosed as errors 832/// 833/// Return true on unrecoverable error. 834static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 835 UnbridgedCastsSet *unbridgedCasts = 0) { 836 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 837 // We can't handle overloaded expressions here because overload 838 // resolution might reasonably tweak them. 839 if (placeholder->getKind() == BuiltinType::Overload) return false; 840 841 // If the context potentially accepts unbridged ARC casts, strip 842 // the unbridged cast and add it to the collection for later restoration. 843 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 844 unbridgedCasts) { 845 unbridgedCasts->save(S, E); 846 return false; 847 } 848 849 // Go ahead and check everything else. 850 ExprResult result = S.CheckPlaceholderExpr(E); 851 if (result.isInvalid()) 852 return true; 853 854 E = result.take(); 855 return false; 856 } 857 858 // Nothing to do. 859 return false; 860} 861 862/// checkArgPlaceholdersForOverload - Check a set of call operands for 863/// placeholders. 864static bool checkArgPlaceholdersForOverload(Sema &S, 865 MultiExprArg Args, 866 UnbridgedCastsSet &unbridged) { 867 for (unsigned i = 0, e = Args.size(); i != e; ++i) 868 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 869 return true; 870 871 return false; 872} 873 874// IsOverload - Determine whether the given New declaration is an 875// overload of the declarations in Old. This routine returns false if 876// New and Old cannot be overloaded, e.g., if New has the same 877// signature as some function in Old (C++ 1.3.10) or if the Old 878// declarations aren't functions (or function templates) at all. When 879// it does return false, MatchedDecl will point to the decl that New 880// cannot be overloaded with. This decl may be a UsingShadowDecl on 881// top of the underlying declaration. 882// 883// Example: Given the following input: 884// 885// void f(int, float); // #1 886// void f(int, int); // #2 887// int f(int, int); // #3 888// 889// When we process #1, there is no previous declaration of "f", 890// so IsOverload will not be used. 891// 892// When we process #2, Old contains only the FunctionDecl for #1. By 893// comparing the parameter types, we see that #1 and #2 are overloaded 894// (since they have different signatures), so this routine returns 895// false; MatchedDecl is unchanged. 896// 897// When we process #3, Old is an overload set containing #1 and #2. We 898// compare the signatures of #3 to #1 (they're overloaded, so we do 899// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 900// identical (return types of functions are not part of the 901// signature), IsOverload returns false and MatchedDecl will be set to 902// point to the FunctionDecl for #2. 903// 904// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 905// into a class by a using declaration. The rules for whether to hide 906// shadow declarations ignore some properties which otherwise figure 907// into a function template's signature. 908Sema::OverloadKind 909Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 910 NamedDecl *&Match, bool NewIsUsingDecl) { 911 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 912 I != E; ++I) { 913 NamedDecl *OldD = *I; 914 915 bool OldIsUsingDecl = false; 916 if (isa<UsingShadowDecl>(OldD)) { 917 OldIsUsingDecl = true; 918 919 // We can always introduce two using declarations into the same 920 // context, even if they have identical signatures. 921 if (NewIsUsingDecl) continue; 922 923 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 924 } 925 926 // If either declaration was introduced by a using declaration, 927 // we'll need to use slightly different rules for matching. 928 // Essentially, these rules are the normal rules, except that 929 // function templates hide function templates with different 930 // return types or template parameter lists. 931 bool UseMemberUsingDeclRules = 932 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 933 !New->getFriendObjectKind(); 934 935 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 936 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 937 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 939 continue; 940 } 941 942 Match = *I; 943 return Ovl_Match; 944 } 945 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 946 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 947 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 948 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 949 continue; 950 } 951 952 if (!shouldLinkPossiblyHiddenDecl(*I, New)) 953 continue; 954 955 Match = *I; 956 return Ovl_Match; 957 } 958 } else if (isa<UsingDecl>(OldD)) { 959 // We can overload with these, which can show up when doing 960 // redeclaration checks for UsingDecls. 961 assert(Old.getLookupKind() == LookupUsingDeclName); 962 } else if (isa<TagDecl>(OldD)) { 963 // We can always overload with tags by hiding them. 964 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 965 // Optimistically assume that an unresolved using decl will 966 // overload; if it doesn't, we'll have to diagnose during 967 // template instantiation. 968 } else { 969 // (C++ 13p1): 970 // Only function declarations can be overloaded; object and type 971 // declarations cannot be overloaded. 972 Match = *I; 973 return Ovl_NonFunction; 974 } 975 } 976 977 return Ovl_Overload; 978} 979 980static bool canBeOverloaded(const FunctionDecl &D) { 981 if (D.getAttr<OverloadableAttr>()) 982 return true; 983 if (D.isExternC()) 984 return false; 985 986 // Main cannot be overloaded (basic.start.main). 987 if (D.isMain()) 988 return false; 989 990 return true; 991} 992 993static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old, 994 bool UseUsingDeclRules) { 995 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 996 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 997 998 // C++ [temp.fct]p2: 999 // A function template can be overloaded with other function templates 1000 // and with normal (non-template) functions. 1001 if ((OldTemplate == 0) != (NewTemplate == 0)) 1002 return true; 1003 1004 // Is the function New an overload of the function Old? 1005 QualType OldQType = S.Context.getCanonicalType(Old->getType()); 1006 QualType NewQType = S.Context.getCanonicalType(New->getType()); 1007 1008 // Compare the signatures (C++ 1.3.10) of the two functions to 1009 // determine whether they are overloads. If we find any mismatch 1010 // in the signature, they are overloads. 1011 1012 // If either of these functions is a K&R-style function (no 1013 // prototype), then we consider them to have matching signatures. 1014 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1015 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1016 return false; 1017 1018 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 1019 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 1020 1021 // The signature of a function includes the types of its 1022 // parameters (C++ 1.3.10), which includes the presence or absence 1023 // of the ellipsis; see C++ DR 357). 1024 if (OldQType != NewQType && 1025 (OldType->getNumArgs() != NewType->getNumArgs() || 1026 OldType->isVariadic() != NewType->isVariadic() || 1027 !S.FunctionArgTypesAreEqual(OldType, NewType))) 1028 return true; 1029 1030 // C++ [temp.over.link]p4: 1031 // The signature of a function template consists of its function 1032 // signature, its return type and its template parameter list. The names 1033 // of the template parameters are significant only for establishing the 1034 // relationship between the template parameters and the rest of the 1035 // signature. 1036 // 1037 // We check the return type and template parameter lists for function 1038 // templates first; the remaining checks follow. 1039 // 1040 // However, we don't consider either of these when deciding whether 1041 // a member introduced by a shadow declaration is hidden. 1042 if (!UseUsingDeclRules && NewTemplate && 1043 (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1044 OldTemplate->getTemplateParameters(), 1045 false, S.TPL_TemplateMatch) || 1046 OldType->getResultType() != NewType->getResultType())) 1047 return true; 1048 1049 // If the function is a class member, its signature includes the 1050 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1051 // 1052 // As part of this, also check whether one of the member functions 1053 // is static, in which case they are not overloads (C++ 1054 // 13.1p2). While not part of the definition of the signature, 1055 // this check is important to determine whether these functions 1056 // can be overloaded. 1057 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1058 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1059 if (OldMethod && NewMethod && 1060 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1061 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1062 if (!UseUsingDeclRules && 1063 (OldMethod->getRefQualifier() == RQ_None || 1064 NewMethod->getRefQualifier() == RQ_None)) { 1065 // C++0x [over.load]p2: 1066 // - Member function declarations with the same name and the same 1067 // parameter-type-list as well as member function template 1068 // declarations with the same name, the same parameter-type-list, and 1069 // the same template parameter lists cannot be overloaded if any of 1070 // them, but not all, have a ref-qualifier (8.3.5). 1071 S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1072 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1073 S.Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1074 } 1075 return true; 1076 } 1077 1078 // We may not have applied the implicit const for a constexpr member 1079 // function yet (because we haven't yet resolved whether this is a static 1080 // or non-static member function). Add it now, on the assumption that this 1081 // is a redeclaration of OldMethod. 1082 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1083 if (!S.getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() && 1084 !isa<CXXConstructorDecl>(NewMethod)) 1085 NewQuals |= Qualifiers::Const; 1086 if (OldMethod->getTypeQualifiers() != NewQuals) 1087 return true; 1088 } 1089 1090 // The signatures match; this is not an overload. 1091 return false; 1092} 1093 1094bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1095 bool UseUsingDeclRules) { 1096 if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules)) 1097 return false; 1098 1099 // If both of the functions are extern "C", then they are not 1100 // overloads. 1101 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New)) 1102 return false; 1103 1104 return true; 1105} 1106 1107/// \brief Checks availability of the function depending on the current 1108/// function context. Inside an unavailable function, unavailability is ignored. 1109/// 1110/// \returns true if \arg FD is unavailable and current context is inside 1111/// an available function, false otherwise. 1112bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1113 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1114} 1115 1116/// \brief Tries a user-defined conversion from From to ToType. 1117/// 1118/// Produces an implicit conversion sequence for when a standard conversion 1119/// is not an option. See TryImplicitConversion for more information. 1120static ImplicitConversionSequence 1121TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1122 bool SuppressUserConversions, 1123 bool AllowExplicit, 1124 bool InOverloadResolution, 1125 bool CStyle, 1126 bool AllowObjCWritebackConversion) { 1127 ImplicitConversionSequence ICS; 1128 1129 if (SuppressUserConversions) { 1130 // We're not in the case above, so there is no conversion that 1131 // we can perform. 1132 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1133 return ICS; 1134 } 1135 1136 // Attempt user-defined conversion. 1137 OverloadCandidateSet Conversions(From->getExprLoc()); 1138 OverloadingResult UserDefResult 1139 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1140 AllowExplicit); 1141 1142 if (UserDefResult == OR_Success) { 1143 ICS.setUserDefined(); 1144 // C++ [over.ics.user]p4: 1145 // A conversion of an expression of class type to the same class 1146 // type is given Exact Match rank, and a conversion of an 1147 // expression of class type to a base class of that type is 1148 // given Conversion rank, in spite of the fact that a copy 1149 // constructor (i.e., a user-defined conversion function) is 1150 // called for those cases. 1151 if (CXXConstructorDecl *Constructor 1152 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1153 QualType FromCanon 1154 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1155 QualType ToCanon 1156 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1157 if (Constructor->isCopyConstructor() && 1158 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1159 // Turn this into a "standard" conversion sequence, so that it 1160 // gets ranked with standard conversion sequences. 1161 ICS.setStandard(); 1162 ICS.Standard.setAsIdentityConversion(); 1163 ICS.Standard.setFromType(From->getType()); 1164 ICS.Standard.setAllToTypes(ToType); 1165 ICS.Standard.CopyConstructor = Constructor; 1166 if (ToCanon != FromCanon) 1167 ICS.Standard.Second = ICK_Derived_To_Base; 1168 } 1169 } 1170 1171 // C++ [over.best.ics]p4: 1172 // However, when considering the argument of a user-defined 1173 // conversion function that is a candidate by 13.3.1.3 when 1174 // invoked for the copying of the temporary in the second step 1175 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1176 // 13.3.1.6 in all cases, only standard conversion sequences and 1177 // ellipsis conversion sequences are allowed. 1178 if (SuppressUserConversions && ICS.isUserDefined()) { 1179 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1180 } 1181 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1182 ICS.setAmbiguous(); 1183 ICS.Ambiguous.setFromType(From->getType()); 1184 ICS.Ambiguous.setToType(ToType); 1185 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1186 Cand != Conversions.end(); ++Cand) 1187 if (Cand->Viable) 1188 ICS.Ambiguous.addConversion(Cand->Function); 1189 } else { 1190 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1191 } 1192 1193 return ICS; 1194} 1195 1196/// TryImplicitConversion - Attempt to perform an implicit conversion 1197/// from the given expression (Expr) to the given type (ToType). This 1198/// function returns an implicit conversion sequence that can be used 1199/// to perform the initialization. Given 1200/// 1201/// void f(float f); 1202/// void g(int i) { f(i); } 1203/// 1204/// this routine would produce an implicit conversion sequence to 1205/// describe the initialization of f from i, which will be a standard 1206/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1207/// 4.1) followed by a floating-integral conversion (C++ 4.9). 1208// 1209/// Note that this routine only determines how the conversion can be 1210/// performed; it does not actually perform the conversion. As such, 1211/// it will not produce any diagnostics if no conversion is available, 1212/// but will instead return an implicit conversion sequence of kind 1213/// "BadConversion". 1214/// 1215/// If @p SuppressUserConversions, then user-defined conversions are 1216/// not permitted. 1217/// If @p AllowExplicit, then explicit user-defined conversions are 1218/// permitted. 1219/// 1220/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1221/// writeback conversion, which allows __autoreleasing id* parameters to 1222/// be initialized with __strong id* or __weak id* arguments. 1223static ImplicitConversionSequence 1224TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1225 bool SuppressUserConversions, 1226 bool AllowExplicit, 1227 bool InOverloadResolution, 1228 bool CStyle, 1229 bool AllowObjCWritebackConversion) { 1230 ImplicitConversionSequence ICS; 1231 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1232 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1233 ICS.setStandard(); 1234 return ICS; 1235 } 1236 1237 if (!S.getLangOpts().CPlusPlus) { 1238 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1239 return ICS; 1240 } 1241 1242 // C++ [over.ics.user]p4: 1243 // A conversion of an expression of class type to the same class 1244 // type is given Exact Match rank, and a conversion of an 1245 // expression of class type to a base class of that type is 1246 // given Conversion rank, in spite of the fact that a copy/move 1247 // constructor (i.e., a user-defined conversion function) is 1248 // called for those cases. 1249 QualType FromType = From->getType(); 1250 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1251 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1252 S.IsDerivedFrom(FromType, ToType))) { 1253 ICS.setStandard(); 1254 ICS.Standard.setAsIdentityConversion(); 1255 ICS.Standard.setFromType(FromType); 1256 ICS.Standard.setAllToTypes(ToType); 1257 1258 // We don't actually check at this point whether there is a valid 1259 // copy/move constructor, since overloading just assumes that it 1260 // exists. When we actually perform initialization, we'll find the 1261 // appropriate constructor to copy the returned object, if needed. 1262 ICS.Standard.CopyConstructor = 0; 1263 1264 // Determine whether this is considered a derived-to-base conversion. 1265 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1266 ICS.Standard.Second = ICK_Derived_To_Base; 1267 1268 return ICS; 1269 } 1270 1271 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1272 AllowExplicit, InOverloadResolution, CStyle, 1273 AllowObjCWritebackConversion); 1274} 1275 1276ImplicitConversionSequence 1277Sema::TryImplicitConversion(Expr *From, QualType ToType, 1278 bool SuppressUserConversions, 1279 bool AllowExplicit, 1280 bool InOverloadResolution, 1281 bool CStyle, 1282 bool AllowObjCWritebackConversion) { 1283 return clang::TryImplicitConversion(*this, From, ToType, 1284 SuppressUserConversions, AllowExplicit, 1285 InOverloadResolution, CStyle, 1286 AllowObjCWritebackConversion); 1287} 1288 1289/// PerformImplicitConversion - Perform an implicit conversion of the 1290/// expression From to the type ToType. Returns the 1291/// converted expression. Flavor is the kind of conversion we're 1292/// performing, used in the error message. If @p AllowExplicit, 1293/// explicit user-defined conversions are permitted. 1294ExprResult 1295Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1296 AssignmentAction Action, bool AllowExplicit) { 1297 ImplicitConversionSequence ICS; 1298 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1299} 1300 1301ExprResult 1302Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1303 AssignmentAction Action, bool AllowExplicit, 1304 ImplicitConversionSequence& ICS) { 1305 if (checkPlaceholderForOverload(*this, From)) 1306 return ExprError(); 1307 1308 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1309 bool AllowObjCWritebackConversion 1310 = getLangOpts().ObjCAutoRefCount && 1311 (Action == AA_Passing || Action == AA_Sending); 1312 1313 ICS = clang::TryImplicitConversion(*this, From, ToType, 1314 /*SuppressUserConversions=*/false, 1315 AllowExplicit, 1316 /*InOverloadResolution=*/false, 1317 /*CStyle=*/false, 1318 AllowObjCWritebackConversion); 1319 return PerformImplicitConversion(From, ToType, ICS, Action); 1320} 1321 1322/// \brief Determine whether the conversion from FromType to ToType is a valid 1323/// conversion that strips "noreturn" off the nested function type. 1324bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1325 QualType &ResultTy) { 1326 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1327 return false; 1328 1329 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1330 // where F adds one of the following at most once: 1331 // - a pointer 1332 // - a member pointer 1333 // - a block pointer 1334 CanQualType CanTo = Context.getCanonicalType(ToType); 1335 CanQualType CanFrom = Context.getCanonicalType(FromType); 1336 Type::TypeClass TyClass = CanTo->getTypeClass(); 1337 if (TyClass != CanFrom->getTypeClass()) return false; 1338 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1339 if (TyClass == Type::Pointer) { 1340 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1341 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1342 } else if (TyClass == Type::BlockPointer) { 1343 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1344 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1345 } else if (TyClass == Type::MemberPointer) { 1346 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1347 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1348 } else { 1349 return false; 1350 } 1351 1352 TyClass = CanTo->getTypeClass(); 1353 if (TyClass != CanFrom->getTypeClass()) return false; 1354 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1355 return false; 1356 } 1357 1358 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1359 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1360 if (!EInfo.getNoReturn()) return false; 1361 1362 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1363 assert(QualType(FromFn, 0).isCanonical()); 1364 if (QualType(FromFn, 0) != CanTo) return false; 1365 1366 ResultTy = ToType; 1367 return true; 1368} 1369 1370/// \brief Determine whether the conversion from FromType to ToType is a valid 1371/// vector conversion. 1372/// 1373/// \param ICK Will be set to the vector conversion kind, if this is a vector 1374/// conversion. 1375static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1376 QualType ToType, ImplicitConversionKind &ICK) { 1377 // We need at least one of these types to be a vector type to have a vector 1378 // conversion. 1379 if (!ToType->isVectorType() && !FromType->isVectorType()) 1380 return false; 1381 1382 // Identical types require no conversions. 1383 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1384 return false; 1385 1386 // There are no conversions between extended vector types, only identity. 1387 if (ToType->isExtVectorType()) { 1388 // There are no conversions between extended vector types other than the 1389 // identity conversion. 1390 if (FromType->isExtVectorType()) 1391 return false; 1392 1393 // Vector splat from any arithmetic type to a vector. 1394 if (FromType->isArithmeticType()) { 1395 ICK = ICK_Vector_Splat; 1396 return true; 1397 } 1398 } 1399 1400 // We can perform the conversion between vector types in the following cases: 1401 // 1)vector types are equivalent AltiVec and GCC vector types 1402 // 2)lax vector conversions are permitted and the vector types are of the 1403 // same size 1404 if (ToType->isVectorType() && FromType->isVectorType()) { 1405 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1406 (Context.getLangOpts().LaxVectorConversions && 1407 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1408 ICK = ICK_Vector_Conversion; 1409 return true; 1410 } 1411 } 1412 1413 return false; 1414} 1415 1416static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1417 bool InOverloadResolution, 1418 StandardConversionSequence &SCS, 1419 bool CStyle); 1420 1421/// IsStandardConversion - Determines whether there is a standard 1422/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1423/// expression From to the type ToType. Standard conversion sequences 1424/// only consider non-class types; for conversions that involve class 1425/// types, use TryImplicitConversion. If a conversion exists, SCS will 1426/// contain the standard conversion sequence required to perform this 1427/// conversion and this routine will return true. Otherwise, this 1428/// routine will return false and the value of SCS is unspecified. 1429static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1430 bool InOverloadResolution, 1431 StandardConversionSequence &SCS, 1432 bool CStyle, 1433 bool AllowObjCWritebackConversion) { 1434 QualType FromType = From->getType(); 1435 1436 // Standard conversions (C++ [conv]) 1437 SCS.setAsIdentityConversion(); 1438 SCS.DeprecatedStringLiteralToCharPtr = false; 1439 SCS.IncompatibleObjC = false; 1440 SCS.setFromType(FromType); 1441 SCS.CopyConstructor = 0; 1442 1443 // There are no standard conversions for class types in C++, so 1444 // abort early. When overloading in C, however, we do permit 1445 if (FromType->isRecordType() || ToType->isRecordType()) { 1446 if (S.getLangOpts().CPlusPlus) 1447 return false; 1448 1449 // When we're overloading in C, we allow, as standard conversions, 1450 } 1451 1452 // The first conversion can be an lvalue-to-rvalue conversion, 1453 // array-to-pointer conversion, or function-to-pointer conversion 1454 // (C++ 4p1). 1455 1456 if (FromType == S.Context.OverloadTy) { 1457 DeclAccessPair AccessPair; 1458 if (FunctionDecl *Fn 1459 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1460 AccessPair)) { 1461 // We were able to resolve the address of the overloaded function, 1462 // so we can convert to the type of that function. 1463 FromType = Fn->getType(); 1464 1465 // we can sometimes resolve &foo<int> regardless of ToType, so check 1466 // if the type matches (identity) or we are converting to bool 1467 if (!S.Context.hasSameUnqualifiedType( 1468 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1469 QualType resultTy; 1470 // if the function type matches except for [[noreturn]], it's ok 1471 if (!S.IsNoReturnConversion(FromType, 1472 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1473 // otherwise, only a boolean conversion is standard 1474 if (!ToType->isBooleanType()) 1475 return false; 1476 } 1477 1478 // Check if the "from" expression is taking the address of an overloaded 1479 // function and recompute the FromType accordingly. Take advantage of the 1480 // fact that non-static member functions *must* have such an address-of 1481 // expression. 1482 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1483 if (Method && !Method->isStatic()) { 1484 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1485 "Non-unary operator on non-static member address"); 1486 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1487 == UO_AddrOf && 1488 "Non-address-of operator on non-static member address"); 1489 const Type *ClassType 1490 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1491 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1492 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1493 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1494 UO_AddrOf && 1495 "Non-address-of operator for overloaded function expression"); 1496 FromType = S.Context.getPointerType(FromType); 1497 } 1498 1499 // Check that we've computed the proper type after overload resolution. 1500 assert(S.Context.hasSameType( 1501 FromType, 1502 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1503 } else { 1504 return false; 1505 } 1506 } 1507 // Lvalue-to-rvalue conversion (C++11 4.1): 1508 // A glvalue (3.10) of a non-function, non-array type T can 1509 // be converted to a prvalue. 1510 bool argIsLValue = From->isGLValue(); 1511 if (argIsLValue && 1512 !FromType->isFunctionType() && !FromType->isArrayType() && 1513 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1514 SCS.First = ICK_Lvalue_To_Rvalue; 1515 1516 // C11 6.3.2.1p2: 1517 // ... if the lvalue has atomic type, the value has the non-atomic version 1518 // of the type of the lvalue ... 1519 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1520 FromType = Atomic->getValueType(); 1521 1522 // If T is a non-class type, the type of the rvalue is the 1523 // cv-unqualified version of T. Otherwise, the type of the rvalue 1524 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1525 // just strip the qualifiers because they don't matter. 1526 FromType = FromType.getUnqualifiedType(); 1527 } else if (FromType->isArrayType()) { 1528 // Array-to-pointer conversion (C++ 4.2) 1529 SCS.First = ICK_Array_To_Pointer; 1530 1531 // An lvalue or rvalue of type "array of N T" or "array of unknown 1532 // bound of T" can be converted to an rvalue of type "pointer to 1533 // T" (C++ 4.2p1). 1534 FromType = S.Context.getArrayDecayedType(FromType); 1535 1536 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1537 // This conversion is deprecated. (C++ D.4). 1538 SCS.DeprecatedStringLiteralToCharPtr = true; 1539 1540 // For the purpose of ranking in overload resolution 1541 // (13.3.3.1.1), this conversion is considered an 1542 // array-to-pointer conversion followed by a qualification 1543 // conversion (4.4). (C++ 4.2p2) 1544 SCS.Second = ICK_Identity; 1545 SCS.Third = ICK_Qualification; 1546 SCS.QualificationIncludesObjCLifetime = false; 1547 SCS.setAllToTypes(FromType); 1548 return true; 1549 } 1550 } else if (FromType->isFunctionType() && argIsLValue) { 1551 // Function-to-pointer conversion (C++ 4.3). 1552 SCS.First = ICK_Function_To_Pointer; 1553 1554 // An lvalue of function type T can be converted to an rvalue of 1555 // type "pointer to T." The result is a pointer to the 1556 // function. (C++ 4.3p1). 1557 FromType = S.Context.getPointerType(FromType); 1558 } else { 1559 // We don't require any conversions for the first step. 1560 SCS.First = ICK_Identity; 1561 } 1562 SCS.setToType(0, FromType); 1563 1564 // The second conversion can be an integral promotion, floating 1565 // point promotion, integral conversion, floating point conversion, 1566 // floating-integral conversion, pointer conversion, 1567 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1568 // For overloading in C, this can also be a "compatible-type" 1569 // conversion. 1570 bool IncompatibleObjC = false; 1571 ImplicitConversionKind SecondICK = ICK_Identity; 1572 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1573 // The unqualified versions of the types are the same: there's no 1574 // conversion to do. 1575 SCS.Second = ICK_Identity; 1576 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1577 // Integral promotion (C++ 4.5). 1578 SCS.Second = ICK_Integral_Promotion; 1579 FromType = ToType.getUnqualifiedType(); 1580 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1581 // Floating point promotion (C++ 4.6). 1582 SCS.Second = ICK_Floating_Promotion; 1583 FromType = ToType.getUnqualifiedType(); 1584 } else if (S.IsComplexPromotion(FromType, ToType)) { 1585 // Complex promotion (Clang extension) 1586 SCS.Second = ICK_Complex_Promotion; 1587 FromType = ToType.getUnqualifiedType(); 1588 } else if (ToType->isBooleanType() && 1589 (FromType->isArithmeticType() || 1590 FromType->isAnyPointerType() || 1591 FromType->isBlockPointerType() || 1592 FromType->isMemberPointerType() || 1593 FromType->isNullPtrType())) { 1594 // Boolean conversions (C++ 4.12). 1595 SCS.Second = ICK_Boolean_Conversion; 1596 FromType = S.Context.BoolTy; 1597 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1598 ToType->isIntegralType(S.Context)) { 1599 // Integral conversions (C++ 4.7). 1600 SCS.Second = ICK_Integral_Conversion; 1601 FromType = ToType.getUnqualifiedType(); 1602 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1603 // Complex conversions (C99 6.3.1.6) 1604 SCS.Second = ICK_Complex_Conversion; 1605 FromType = ToType.getUnqualifiedType(); 1606 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1607 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1608 // Complex-real conversions (C99 6.3.1.7) 1609 SCS.Second = ICK_Complex_Real; 1610 FromType = ToType.getUnqualifiedType(); 1611 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1612 // Floating point conversions (C++ 4.8). 1613 SCS.Second = ICK_Floating_Conversion; 1614 FromType = ToType.getUnqualifiedType(); 1615 } else if ((FromType->isRealFloatingType() && 1616 ToType->isIntegralType(S.Context)) || 1617 (FromType->isIntegralOrUnscopedEnumerationType() && 1618 ToType->isRealFloatingType())) { 1619 // Floating-integral conversions (C++ 4.9). 1620 SCS.Second = ICK_Floating_Integral; 1621 FromType = ToType.getUnqualifiedType(); 1622 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1623 SCS.Second = ICK_Block_Pointer_Conversion; 1624 } else if (AllowObjCWritebackConversion && 1625 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1626 SCS.Second = ICK_Writeback_Conversion; 1627 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1628 FromType, IncompatibleObjC)) { 1629 // Pointer conversions (C++ 4.10). 1630 SCS.Second = ICK_Pointer_Conversion; 1631 SCS.IncompatibleObjC = IncompatibleObjC; 1632 FromType = FromType.getUnqualifiedType(); 1633 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1634 InOverloadResolution, FromType)) { 1635 // Pointer to member conversions (4.11). 1636 SCS.Second = ICK_Pointer_Member; 1637 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1638 SCS.Second = SecondICK; 1639 FromType = ToType.getUnqualifiedType(); 1640 } else if (!S.getLangOpts().CPlusPlus && 1641 S.Context.typesAreCompatible(ToType, FromType)) { 1642 // Compatible conversions (Clang extension for C function overloading) 1643 SCS.Second = ICK_Compatible_Conversion; 1644 FromType = ToType.getUnqualifiedType(); 1645 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1646 // Treat a conversion that strips "noreturn" as an identity conversion. 1647 SCS.Second = ICK_NoReturn_Adjustment; 1648 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1649 InOverloadResolution, 1650 SCS, CStyle)) { 1651 SCS.Second = ICK_TransparentUnionConversion; 1652 FromType = ToType; 1653 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1654 CStyle)) { 1655 // tryAtomicConversion has updated the standard conversion sequence 1656 // appropriately. 1657 return true; 1658 } else if (ToType->isEventT() && 1659 From->isIntegerConstantExpr(S.getASTContext()) && 1660 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1661 SCS.Second = ICK_Zero_Event_Conversion; 1662 FromType = ToType; 1663 } else { 1664 // No second conversion required. 1665 SCS.Second = ICK_Identity; 1666 } 1667 SCS.setToType(1, FromType); 1668 1669 QualType CanonFrom; 1670 QualType CanonTo; 1671 // The third conversion can be a qualification conversion (C++ 4p1). 1672 bool ObjCLifetimeConversion; 1673 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1674 ObjCLifetimeConversion)) { 1675 SCS.Third = ICK_Qualification; 1676 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1677 FromType = ToType; 1678 CanonFrom = S.Context.getCanonicalType(FromType); 1679 CanonTo = S.Context.getCanonicalType(ToType); 1680 } else { 1681 // No conversion required 1682 SCS.Third = ICK_Identity; 1683 1684 // C++ [over.best.ics]p6: 1685 // [...] Any difference in top-level cv-qualification is 1686 // subsumed by the initialization itself and does not constitute 1687 // a conversion. [...] 1688 CanonFrom = S.Context.getCanonicalType(FromType); 1689 CanonTo = S.Context.getCanonicalType(ToType); 1690 if (CanonFrom.getLocalUnqualifiedType() 1691 == CanonTo.getLocalUnqualifiedType() && 1692 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1693 FromType = ToType; 1694 CanonFrom = CanonTo; 1695 } 1696 } 1697 SCS.setToType(2, FromType); 1698 1699 // If we have not converted the argument type to the parameter type, 1700 // this is a bad conversion sequence. 1701 if (CanonFrom != CanonTo) 1702 return false; 1703 1704 return true; 1705} 1706 1707static bool 1708IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1709 QualType &ToType, 1710 bool InOverloadResolution, 1711 StandardConversionSequence &SCS, 1712 bool CStyle) { 1713 1714 const RecordType *UT = ToType->getAsUnionType(); 1715 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1716 return false; 1717 // The field to initialize within the transparent union. 1718 RecordDecl *UD = UT->getDecl(); 1719 // It's compatible if the expression matches any of the fields. 1720 for (RecordDecl::field_iterator it = UD->field_begin(), 1721 itend = UD->field_end(); 1722 it != itend; ++it) { 1723 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1724 CStyle, /*ObjCWritebackConversion=*/false)) { 1725 ToType = it->getType(); 1726 return true; 1727 } 1728 } 1729 return false; 1730} 1731 1732/// IsIntegralPromotion - Determines whether the conversion from the 1733/// expression From (whose potentially-adjusted type is FromType) to 1734/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1735/// sets PromotedType to the promoted type. 1736bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1737 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1738 // All integers are built-in. 1739 if (!To) { 1740 return false; 1741 } 1742 1743 // An rvalue of type char, signed char, unsigned char, short int, or 1744 // unsigned short int can be converted to an rvalue of type int if 1745 // int can represent all the values of the source type; otherwise, 1746 // the source rvalue can be converted to an rvalue of type unsigned 1747 // int (C++ 4.5p1). 1748 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1749 !FromType->isEnumeralType()) { 1750 if (// We can promote any signed, promotable integer type to an int 1751 (FromType->isSignedIntegerType() || 1752 // We can promote any unsigned integer type whose size is 1753 // less than int to an int. 1754 (!FromType->isSignedIntegerType() && 1755 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1756 return To->getKind() == BuiltinType::Int; 1757 } 1758 1759 return To->getKind() == BuiltinType::UInt; 1760 } 1761 1762 // C++11 [conv.prom]p3: 1763 // A prvalue of an unscoped enumeration type whose underlying type is not 1764 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1765 // following types that can represent all the values of the enumeration 1766 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1767 // unsigned int, long int, unsigned long int, long long int, or unsigned 1768 // long long int. If none of the types in that list can represent all the 1769 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1770 // type can be converted to an rvalue a prvalue of the extended integer type 1771 // with lowest integer conversion rank (4.13) greater than the rank of long 1772 // long in which all the values of the enumeration can be represented. If 1773 // there are two such extended types, the signed one is chosen. 1774 // C++11 [conv.prom]p4: 1775 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1776 // can be converted to a prvalue of its underlying type. Moreover, if 1777 // integral promotion can be applied to its underlying type, a prvalue of an 1778 // unscoped enumeration type whose underlying type is fixed can also be 1779 // converted to a prvalue of the promoted underlying type. 1780 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1781 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1782 // provided for a scoped enumeration. 1783 if (FromEnumType->getDecl()->isScoped()) 1784 return false; 1785 1786 // We can perform an integral promotion to the underlying type of the enum, 1787 // even if that's not the promoted type. 1788 if (FromEnumType->getDecl()->isFixed()) { 1789 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1790 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1791 IsIntegralPromotion(From, Underlying, ToType); 1792 } 1793 1794 // We have already pre-calculated the promotion type, so this is trivial. 1795 if (ToType->isIntegerType() && 1796 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1797 return Context.hasSameUnqualifiedType(ToType, 1798 FromEnumType->getDecl()->getPromotionType()); 1799 } 1800 1801 // C++0x [conv.prom]p2: 1802 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1803 // to an rvalue a prvalue of the first of the following types that can 1804 // represent all the values of its underlying type: int, unsigned int, 1805 // long int, unsigned long int, long long int, or unsigned long long int. 1806 // If none of the types in that list can represent all the values of its 1807 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1808 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1809 // type. 1810 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1811 ToType->isIntegerType()) { 1812 // Determine whether the type we're converting from is signed or 1813 // unsigned. 1814 bool FromIsSigned = FromType->isSignedIntegerType(); 1815 uint64_t FromSize = Context.getTypeSize(FromType); 1816 1817 // The types we'll try to promote to, in the appropriate 1818 // order. Try each of these types. 1819 QualType PromoteTypes[6] = { 1820 Context.IntTy, Context.UnsignedIntTy, 1821 Context.LongTy, Context.UnsignedLongTy , 1822 Context.LongLongTy, Context.UnsignedLongLongTy 1823 }; 1824 for (int Idx = 0; Idx < 6; ++Idx) { 1825 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1826 if (FromSize < ToSize || 1827 (FromSize == ToSize && 1828 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1829 // We found the type that we can promote to. If this is the 1830 // type we wanted, we have a promotion. Otherwise, no 1831 // promotion. 1832 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1833 } 1834 } 1835 } 1836 1837 // An rvalue for an integral bit-field (9.6) can be converted to an 1838 // rvalue of type int if int can represent all the values of the 1839 // bit-field; otherwise, it can be converted to unsigned int if 1840 // unsigned int can represent all the values of the bit-field. If 1841 // the bit-field is larger yet, no integral promotion applies to 1842 // it. If the bit-field has an enumerated type, it is treated as any 1843 // other value of that type for promotion purposes (C++ 4.5p3). 1844 // FIXME: We should delay checking of bit-fields until we actually perform the 1845 // conversion. 1846 using llvm::APSInt; 1847 if (From) 1848 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1849 APSInt BitWidth; 1850 if (FromType->isIntegralType(Context) && 1851 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1852 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1853 ToSize = Context.getTypeSize(ToType); 1854 1855 // Are we promoting to an int from a bitfield that fits in an int? 1856 if (BitWidth < ToSize || 1857 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1858 return To->getKind() == BuiltinType::Int; 1859 } 1860 1861 // Are we promoting to an unsigned int from an unsigned bitfield 1862 // that fits into an unsigned int? 1863 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1864 return To->getKind() == BuiltinType::UInt; 1865 } 1866 1867 return false; 1868 } 1869 } 1870 1871 // An rvalue of type bool can be converted to an rvalue of type int, 1872 // with false becoming zero and true becoming one (C++ 4.5p4). 1873 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1874 return true; 1875 } 1876 1877 return false; 1878} 1879 1880/// IsFloatingPointPromotion - Determines whether the conversion from 1881/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1882/// returns true and sets PromotedType to the promoted type. 1883bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1884 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1885 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1886 /// An rvalue of type float can be converted to an rvalue of type 1887 /// double. (C++ 4.6p1). 1888 if (FromBuiltin->getKind() == BuiltinType::Float && 1889 ToBuiltin->getKind() == BuiltinType::Double) 1890 return true; 1891 1892 // C99 6.3.1.5p1: 1893 // When a float is promoted to double or long double, or a 1894 // double is promoted to long double [...]. 1895 if (!getLangOpts().CPlusPlus && 1896 (FromBuiltin->getKind() == BuiltinType::Float || 1897 FromBuiltin->getKind() == BuiltinType::Double) && 1898 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1899 return true; 1900 1901 // Half can be promoted to float. 1902 if (!getLangOpts().NativeHalfType && 1903 FromBuiltin->getKind() == BuiltinType::Half && 1904 ToBuiltin->getKind() == BuiltinType::Float) 1905 return true; 1906 } 1907 1908 return false; 1909} 1910 1911/// \brief Determine if a conversion is a complex promotion. 1912/// 1913/// A complex promotion is defined as a complex -> complex conversion 1914/// where the conversion between the underlying real types is a 1915/// floating-point or integral promotion. 1916bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1917 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1918 if (!FromComplex) 1919 return false; 1920 1921 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1922 if (!ToComplex) 1923 return false; 1924 1925 return IsFloatingPointPromotion(FromComplex->getElementType(), 1926 ToComplex->getElementType()) || 1927 IsIntegralPromotion(0, FromComplex->getElementType(), 1928 ToComplex->getElementType()); 1929} 1930 1931/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1932/// the pointer type FromPtr to a pointer to type ToPointee, with the 1933/// same type qualifiers as FromPtr has on its pointee type. ToType, 1934/// if non-empty, will be a pointer to ToType that may or may not have 1935/// the right set of qualifiers on its pointee. 1936/// 1937static QualType 1938BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1939 QualType ToPointee, QualType ToType, 1940 ASTContext &Context, 1941 bool StripObjCLifetime = false) { 1942 assert((FromPtr->getTypeClass() == Type::Pointer || 1943 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1944 "Invalid similarly-qualified pointer type"); 1945 1946 /// Conversions to 'id' subsume cv-qualifier conversions. 1947 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1948 return ToType.getUnqualifiedType(); 1949 1950 QualType CanonFromPointee 1951 = Context.getCanonicalType(FromPtr->getPointeeType()); 1952 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1953 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1954 1955 if (StripObjCLifetime) 1956 Quals.removeObjCLifetime(); 1957 1958 // Exact qualifier match -> return the pointer type we're converting to. 1959 if (CanonToPointee.getLocalQualifiers() == Quals) { 1960 // ToType is exactly what we need. Return it. 1961 if (!ToType.isNull()) 1962 return ToType.getUnqualifiedType(); 1963 1964 // Build a pointer to ToPointee. It has the right qualifiers 1965 // already. 1966 if (isa<ObjCObjectPointerType>(ToType)) 1967 return Context.getObjCObjectPointerType(ToPointee); 1968 return Context.getPointerType(ToPointee); 1969 } 1970 1971 // Just build a canonical type that has the right qualifiers. 1972 QualType QualifiedCanonToPointee 1973 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1974 1975 if (isa<ObjCObjectPointerType>(ToType)) 1976 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1977 return Context.getPointerType(QualifiedCanonToPointee); 1978} 1979 1980static bool isNullPointerConstantForConversion(Expr *Expr, 1981 bool InOverloadResolution, 1982 ASTContext &Context) { 1983 // Handle value-dependent integral null pointer constants correctly. 1984 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1985 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1986 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1987 return !InOverloadResolution; 1988 1989 return Expr->isNullPointerConstant(Context, 1990 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1991 : Expr::NPC_ValueDependentIsNull); 1992} 1993 1994/// IsPointerConversion - Determines whether the conversion of the 1995/// expression From, which has the (possibly adjusted) type FromType, 1996/// can be converted to the type ToType via a pointer conversion (C++ 1997/// 4.10). If so, returns true and places the converted type (that 1998/// might differ from ToType in its cv-qualifiers at some level) into 1999/// ConvertedType. 2000/// 2001/// This routine also supports conversions to and from block pointers 2002/// and conversions with Objective-C's 'id', 'id<protocols...>', and 2003/// pointers to interfaces. FIXME: Once we've determined the 2004/// appropriate overloading rules for Objective-C, we may want to 2005/// split the Objective-C checks into a different routine; however, 2006/// GCC seems to consider all of these conversions to be pointer 2007/// conversions, so for now they live here. IncompatibleObjC will be 2008/// set if the conversion is an allowed Objective-C conversion that 2009/// should result in a warning. 2010bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2011 bool InOverloadResolution, 2012 QualType& ConvertedType, 2013 bool &IncompatibleObjC) { 2014 IncompatibleObjC = false; 2015 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2016 IncompatibleObjC)) 2017 return true; 2018 2019 // Conversion from a null pointer constant to any Objective-C pointer type. 2020 if (ToType->isObjCObjectPointerType() && 2021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2022 ConvertedType = ToType; 2023 return true; 2024 } 2025 2026 // Blocks: Block pointers can be converted to void*. 2027 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2028 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2029 ConvertedType = ToType; 2030 return true; 2031 } 2032 // Blocks: A null pointer constant can be converted to a block 2033 // pointer type. 2034 if (ToType->isBlockPointerType() && 2035 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2036 ConvertedType = ToType; 2037 return true; 2038 } 2039 2040 // If the left-hand-side is nullptr_t, the right side can be a null 2041 // pointer constant. 2042 if (ToType->isNullPtrType() && 2043 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2044 ConvertedType = ToType; 2045 return true; 2046 } 2047 2048 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2049 if (!ToTypePtr) 2050 return false; 2051 2052 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2053 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2054 ConvertedType = ToType; 2055 return true; 2056 } 2057 2058 // Beyond this point, both types need to be pointers 2059 // , including objective-c pointers. 2060 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2061 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2062 !getLangOpts().ObjCAutoRefCount) { 2063 ConvertedType = BuildSimilarlyQualifiedPointerType( 2064 FromType->getAs<ObjCObjectPointerType>(), 2065 ToPointeeType, 2066 ToType, Context); 2067 return true; 2068 } 2069 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2070 if (!FromTypePtr) 2071 return false; 2072 2073 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2074 2075 // If the unqualified pointee types are the same, this can't be a 2076 // pointer conversion, so don't do all of the work below. 2077 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2078 return false; 2079 2080 // An rvalue of type "pointer to cv T," where T is an object type, 2081 // can be converted to an rvalue of type "pointer to cv void" (C++ 2082 // 4.10p2). 2083 if (FromPointeeType->isIncompleteOrObjectType() && 2084 ToPointeeType->isVoidType()) { 2085 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2086 ToPointeeType, 2087 ToType, Context, 2088 /*StripObjCLifetime=*/true); 2089 return true; 2090 } 2091 2092 // MSVC allows implicit function to void* type conversion. 2093 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2094 ToPointeeType->isVoidType()) { 2095 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2096 ToPointeeType, 2097 ToType, Context); 2098 return true; 2099 } 2100 2101 // When we're overloading in C, we allow a special kind of pointer 2102 // conversion for compatible-but-not-identical pointee types. 2103 if (!getLangOpts().CPlusPlus && 2104 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2105 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2106 ToPointeeType, 2107 ToType, Context); 2108 return true; 2109 } 2110 2111 // C++ [conv.ptr]p3: 2112 // 2113 // An rvalue of type "pointer to cv D," where D is a class type, 2114 // can be converted to an rvalue of type "pointer to cv B," where 2115 // B is a base class (clause 10) of D. If B is an inaccessible 2116 // (clause 11) or ambiguous (10.2) base class of D, a program that 2117 // necessitates this conversion is ill-formed. The result of the 2118 // conversion is a pointer to the base class sub-object of the 2119 // derived class object. The null pointer value is converted to 2120 // the null pointer value of the destination type. 2121 // 2122 // Note that we do not check for ambiguity or inaccessibility 2123 // here. That is handled by CheckPointerConversion. 2124 if (getLangOpts().CPlusPlus && 2125 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2126 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2127 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2128 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2129 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2130 ToPointeeType, 2131 ToType, Context); 2132 return true; 2133 } 2134 2135 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2136 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2137 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2138 ToPointeeType, 2139 ToType, Context); 2140 return true; 2141 } 2142 2143 return false; 2144} 2145 2146/// \brief Adopt the given qualifiers for the given type. 2147static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2148 Qualifiers TQs = T.getQualifiers(); 2149 2150 // Check whether qualifiers already match. 2151 if (TQs == Qs) 2152 return T; 2153 2154 if (Qs.compatiblyIncludes(TQs)) 2155 return Context.getQualifiedType(T, Qs); 2156 2157 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2158} 2159 2160/// isObjCPointerConversion - Determines whether this is an 2161/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2162/// with the same arguments and return values. 2163bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2164 QualType& ConvertedType, 2165 bool &IncompatibleObjC) { 2166 if (!getLangOpts().ObjC1) 2167 return false; 2168 2169 // The set of qualifiers on the type we're converting from. 2170 Qualifiers FromQualifiers = FromType.getQualifiers(); 2171 2172 // First, we handle all conversions on ObjC object pointer types. 2173 const ObjCObjectPointerType* ToObjCPtr = 2174 ToType->getAs<ObjCObjectPointerType>(); 2175 const ObjCObjectPointerType *FromObjCPtr = 2176 FromType->getAs<ObjCObjectPointerType>(); 2177 2178 if (ToObjCPtr && FromObjCPtr) { 2179 // If the pointee types are the same (ignoring qualifications), 2180 // then this is not a pointer conversion. 2181 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2182 FromObjCPtr->getPointeeType())) 2183 return false; 2184 2185 // Check for compatible 2186 // Objective C++: We're able to convert between "id" or "Class" and a 2187 // pointer to any interface (in both directions). 2188 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2189 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2190 return true; 2191 } 2192 // Conversions with Objective-C's id<...>. 2193 if ((FromObjCPtr->isObjCQualifiedIdType() || 2194 ToObjCPtr->isObjCQualifiedIdType()) && 2195 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2196 /*compare=*/false)) { 2197 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2198 return true; 2199 } 2200 // Objective C++: We're able to convert from a pointer to an 2201 // interface to a pointer to a different interface. 2202 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2203 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2204 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2205 if (getLangOpts().CPlusPlus && LHS && RHS && 2206 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2207 FromObjCPtr->getPointeeType())) 2208 return false; 2209 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2210 ToObjCPtr->getPointeeType(), 2211 ToType, Context); 2212 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2213 return true; 2214 } 2215 2216 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2217 // Okay: this is some kind of implicit downcast of Objective-C 2218 // interfaces, which is permitted. However, we're going to 2219 // complain about it. 2220 IncompatibleObjC = true; 2221 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2222 ToObjCPtr->getPointeeType(), 2223 ToType, Context); 2224 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2225 return true; 2226 } 2227 } 2228 // Beyond this point, both types need to be C pointers or block pointers. 2229 QualType ToPointeeType; 2230 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2231 ToPointeeType = ToCPtr->getPointeeType(); 2232 else if (const BlockPointerType *ToBlockPtr = 2233 ToType->getAs<BlockPointerType>()) { 2234 // Objective C++: We're able to convert from a pointer to any object 2235 // to a block pointer type. 2236 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2237 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2238 return true; 2239 } 2240 ToPointeeType = ToBlockPtr->getPointeeType(); 2241 } 2242 else if (FromType->getAs<BlockPointerType>() && 2243 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2244 // Objective C++: We're able to convert from a block pointer type to a 2245 // pointer to any object. 2246 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2247 return true; 2248 } 2249 else 2250 return false; 2251 2252 QualType FromPointeeType; 2253 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2254 FromPointeeType = FromCPtr->getPointeeType(); 2255 else if (const BlockPointerType *FromBlockPtr = 2256 FromType->getAs<BlockPointerType>()) 2257 FromPointeeType = FromBlockPtr->getPointeeType(); 2258 else 2259 return false; 2260 2261 // If we have pointers to pointers, recursively check whether this 2262 // is an Objective-C conversion. 2263 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2264 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2265 IncompatibleObjC)) { 2266 // We always complain about this conversion. 2267 IncompatibleObjC = true; 2268 ConvertedType = Context.getPointerType(ConvertedType); 2269 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2270 return true; 2271 } 2272 // Allow conversion of pointee being objective-c pointer to another one; 2273 // as in I* to id. 2274 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2275 ToPointeeType->getAs<ObjCObjectPointerType>() && 2276 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2277 IncompatibleObjC)) { 2278 2279 ConvertedType = Context.getPointerType(ConvertedType); 2280 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2281 return true; 2282 } 2283 2284 // If we have pointers to functions or blocks, check whether the only 2285 // differences in the argument and result types are in Objective-C 2286 // pointer conversions. If so, we permit the conversion (but 2287 // complain about it). 2288 const FunctionProtoType *FromFunctionType 2289 = FromPointeeType->getAs<FunctionProtoType>(); 2290 const FunctionProtoType *ToFunctionType 2291 = ToPointeeType->getAs<FunctionProtoType>(); 2292 if (FromFunctionType && ToFunctionType) { 2293 // If the function types are exactly the same, this isn't an 2294 // Objective-C pointer conversion. 2295 if (Context.getCanonicalType(FromPointeeType) 2296 == Context.getCanonicalType(ToPointeeType)) 2297 return false; 2298 2299 // Perform the quick checks that will tell us whether these 2300 // function types are obviously different. 2301 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2302 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2303 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2304 return false; 2305 2306 bool HasObjCConversion = false; 2307 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2308 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2309 // Okay, the types match exactly. Nothing to do. 2310 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2311 ToFunctionType->getResultType(), 2312 ConvertedType, IncompatibleObjC)) { 2313 // Okay, we have an Objective-C pointer conversion. 2314 HasObjCConversion = true; 2315 } else { 2316 // Function types are too different. Abort. 2317 return false; 2318 } 2319 2320 // Check argument types. 2321 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2322 ArgIdx != NumArgs; ++ArgIdx) { 2323 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2324 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2325 if (Context.getCanonicalType(FromArgType) 2326 == Context.getCanonicalType(ToArgType)) { 2327 // Okay, the types match exactly. Nothing to do. 2328 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2329 ConvertedType, IncompatibleObjC)) { 2330 // Okay, we have an Objective-C pointer conversion. 2331 HasObjCConversion = true; 2332 } else { 2333 // Argument types are too different. Abort. 2334 return false; 2335 } 2336 } 2337 2338 if (HasObjCConversion) { 2339 // We had an Objective-C conversion. Allow this pointer 2340 // conversion, but complain about it. 2341 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2342 IncompatibleObjC = true; 2343 return true; 2344 } 2345 } 2346 2347 return false; 2348} 2349 2350/// \brief Determine whether this is an Objective-C writeback conversion, 2351/// used for parameter passing when performing automatic reference counting. 2352/// 2353/// \param FromType The type we're converting form. 2354/// 2355/// \param ToType The type we're converting to. 2356/// 2357/// \param ConvertedType The type that will be produced after applying 2358/// this conversion. 2359bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2360 QualType &ConvertedType) { 2361 if (!getLangOpts().ObjCAutoRefCount || 2362 Context.hasSameUnqualifiedType(FromType, ToType)) 2363 return false; 2364 2365 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2366 QualType ToPointee; 2367 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2368 ToPointee = ToPointer->getPointeeType(); 2369 else 2370 return false; 2371 2372 Qualifiers ToQuals = ToPointee.getQualifiers(); 2373 if (!ToPointee->isObjCLifetimeType() || 2374 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2375 !ToQuals.withoutObjCLifetime().empty()) 2376 return false; 2377 2378 // Argument must be a pointer to __strong to __weak. 2379 QualType FromPointee; 2380 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2381 FromPointee = FromPointer->getPointeeType(); 2382 else 2383 return false; 2384 2385 Qualifiers FromQuals = FromPointee.getQualifiers(); 2386 if (!FromPointee->isObjCLifetimeType() || 2387 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2388 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2389 return false; 2390 2391 // Make sure that we have compatible qualifiers. 2392 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2393 if (!ToQuals.compatiblyIncludes(FromQuals)) 2394 return false; 2395 2396 // Remove qualifiers from the pointee type we're converting from; they 2397 // aren't used in the compatibility check belong, and we'll be adding back 2398 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2399 FromPointee = FromPointee.getUnqualifiedType(); 2400 2401 // The unqualified form of the pointee types must be compatible. 2402 ToPointee = ToPointee.getUnqualifiedType(); 2403 bool IncompatibleObjC; 2404 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2405 FromPointee = ToPointee; 2406 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2407 IncompatibleObjC)) 2408 return false; 2409 2410 /// \brief Construct the type we're converting to, which is a pointer to 2411 /// __autoreleasing pointee. 2412 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2413 ConvertedType = Context.getPointerType(FromPointee); 2414 return true; 2415} 2416 2417bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2418 QualType& ConvertedType) { 2419 QualType ToPointeeType; 2420 if (const BlockPointerType *ToBlockPtr = 2421 ToType->getAs<BlockPointerType>()) 2422 ToPointeeType = ToBlockPtr->getPointeeType(); 2423 else 2424 return false; 2425 2426 QualType FromPointeeType; 2427 if (const BlockPointerType *FromBlockPtr = 2428 FromType->getAs<BlockPointerType>()) 2429 FromPointeeType = FromBlockPtr->getPointeeType(); 2430 else 2431 return false; 2432 // We have pointer to blocks, check whether the only 2433 // differences in the argument and result types are in Objective-C 2434 // pointer conversions. If so, we permit the conversion. 2435 2436 const FunctionProtoType *FromFunctionType 2437 = FromPointeeType->getAs<FunctionProtoType>(); 2438 const FunctionProtoType *ToFunctionType 2439 = ToPointeeType->getAs<FunctionProtoType>(); 2440 2441 if (!FromFunctionType || !ToFunctionType) 2442 return false; 2443 2444 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2445 return true; 2446 2447 // Perform the quick checks that will tell us whether these 2448 // function types are obviously different. 2449 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2450 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2451 return false; 2452 2453 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2454 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2455 if (FromEInfo != ToEInfo) 2456 return false; 2457 2458 bool IncompatibleObjC = false; 2459 if (Context.hasSameType(FromFunctionType->getResultType(), 2460 ToFunctionType->getResultType())) { 2461 // Okay, the types match exactly. Nothing to do. 2462 } else { 2463 QualType RHS = FromFunctionType->getResultType(); 2464 QualType LHS = ToFunctionType->getResultType(); 2465 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2466 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2467 LHS = LHS.getUnqualifiedType(); 2468 2469 if (Context.hasSameType(RHS,LHS)) { 2470 // OK exact match. 2471 } else if (isObjCPointerConversion(RHS, LHS, 2472 ConvertedType, IncompatibleObjC)) { 2473 if (IncompatibleObjC) 2474 return false; 2475 // Okay, we have an Objective-C pointer conversion. 2476 } 2477 else 2478 return false; 2479 } 2480 2481 // Check argument types. 2482 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2483 ArgIdx != NumArgs; ++ArgIdx) { 2484 IncompatibleObjC = false; 2485 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2486 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2487 if (Context.hasSameType(FromArgType, ToArgType)) { 2488 // Okay, the types match exactly. Nothing to do. 2489 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2490 ConvertedType, IncompatibleObjC)) { 2491 if (IncompatibleObjC) 2492 return false; 2493 // Okay, we have an Objective-C pointer conversion. 2494 } else 2495 // Argument types are too different. Abort. 2496 return false; 2497 } 2498 if (LangOpts.ObjCAutoRefCount && 2499 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2500 ToFunctionType)) 2501 return false; 2502 2503 ConvertedType = ToType; 2504 return true; 2505} 2506 2507enum { 2508 ft_default, 2509 ft_different_class, 2510 ft_parameter_arity, 2511 ft_parameter_mismatch, 2512 ft_return_type, 2513 ft_qualifer_mismatch 2514}; 2515 2516/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2517/// function types. Catches different number of parameter, mismatch in 2518/// parameter types, and different return types. 2519void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2520 QualType FromType, QualType ToType) { 2521 // If either type is not valid, include no extra info. 2522 if (FromType.isNull() || ToType.isNull()) { 2523 PDiag << ft_default; 2524 return; 2525 } 2526 2527 // Get the function type from the pointers. 2528 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2529 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2530 *ToMember = ToType->getAs<MemberPointerType>(); 2531 if (FromMember->getClass() != ToMember->getClass()) { 2532 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2533 << QualType(FromMember->getClass(), 0); 2534 return; 2535 } 2536 FromType = FromMember->getPointeeType(); 2537 ToType = ToMember->getPointeeType(); 2538 } 2539 2540 if (FromType->isPointerType()) 2541 FromType = FromType->getPointeeType(); 2542 if (ToType->isPointerType()) 2543 ToType = ToType->getPointeeType(); 2544 2545 // Remove references. 2546 FromType = FromType.getNonReferenceType(); 2547 ToType = ToType.getNonReferenceType(); 2548 2549 // Don't print extra info for non-specialized template functions. 2550 if (FromType->isInstantiationDependentType() && 2551 !FromType->getAs<TemplateSpecializationType>()) { 2552 PDiag << ft_default; 2553 return; 2554 } 2555 2556 // No extra info for same types. 2557 if (Context.hasSameType(FromType, ToType)) { 2558 PDiag << ft_default; 2559 return; 2560 } 2561 2562 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2563 *ToFunction = ToType->getAs<FunctionProtoType>(); 2564 2565 // Both types need to be function types. 2566 if (!FromFunction || !ToFunction) { 2567 PDiag << ft_default; 2568 return; 2569 } 2570 2571 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2572 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2573 << FromFunction->getNumArgs(); 2574 return; 2575 } 2576 2577 // Handle different parameter types. 2578 unsigned ArgPos; 2579 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2580 PDiag << ft_parameter_mismatch << ArgPos + 1 2581 << ToFunction->getArgType(ArgPos) 2582 << FromFunction->getArgType(ArgPos); 2583 return; 2584 } 2585 2586 // Handle different return type. 2587 if (!Context.hasSameType(FromFunction->getResultType(), 2588 ToFunction->getResultType())) { 2589 PDiag << ft_return_type << ToFunction->getResultType() 2590 << FromFunction->getResultType(); 2591 return; 2592 } 2593 2594 unsigned FromQuals = FromFunction->getTypeQuals(), 2595 ToQuals = ToFunction->getTypeQuals(); 2596 if (FromQuals != ToQuals) { 2597 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2598 return; 2599 } 2600 2601 // Unable to find a difference, so add no extra info. 2602 PDiag << ft_default; 2603} 2604 2605/// FunctionArgTypesAreEqual - This routine checks two function proto types 2606/// for equality of their argument types. Caller has already checked that 2607/// they have same number of arguments. If the parameters are different, 2608/// ArgPos will have the parameter index of the first different parameter. 2609bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2610 const FunctionProtoType *NewType, 2611 unsigned *ArgPos) { 2612 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2613 N = NewType->arg_type_begin(), 2614 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2615 if (!Context.hasSameType(*O, *N)) { 2616 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2617 return false; 2618 } 2619 } 2620 return true; 2621} 2622 2623/// CheckPointerConversion - Check the pointer conversion from the 2624/// expression From to the type ToType. This routine checks for 2625/// ambiguous or inaccessible derived-to-base pointer 2626/// conversions for which IsPointerConversion has already returned 2627/// true. It returns true and produces a diagnostic if there was an 2628/// error, or returns false otherwise. 2629bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2630 CastKind &Kind, 2631 CXXCastPath& BasePath, 2632 bool IgnoreBaseAccess) { 2633 QualType FromType = From->getType(); 2634 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2635 2636 Kind = CK_BitCast; 2637 2638 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2639 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2640 Expr::NPCK_ZeroExpression) { 2641 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2642 DiagRuntimeBehavior(From->getExprLoc(), From, 2643 PDiag(diag::warn_impcast_bool_to_null_pointer) 2644 << ToType << From->getSourceRange()); 2645 else if (!isUnevaluatedContext()) 2646 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2647 << ToType << From->getSourceRange(); 2648 } 2649 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2650 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2651 QualType FromPointeeType = FromPtrType->getPointeeType(), 2652 ToPointeeType = ToPtrType->getPointeeType(); 2653 2654 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2655 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2656 // We must have a derived-to-base conversion. Check an 2657 // ambiguous or inaccessible conversion. 2658 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2659 From->getExprLoc(), 2660 From->getSourceRange(), &BasePath, 2661 IgnoreBaseAccess)) 2662 return true; 2663 2664 // The conversion was successful. 2665 Kind = CK_DerivedToBase; 2666 } 2667 } 2668 } else if (const ObjCObjectPointerType *ToPtrType = 2669 ToType->getAs<ObjCObjectPointerType>()) { 2670 if (const ObjCObjectPointerType *FromPtrType = 2671 FromType->getAs<ObjCObjectPointerType>()) { 2672 // Objective-C++ conversions are always okay. 2673 // FIXME: We should have a different class of conversions for the 2674 // Objective-C++ implicit conversions. 2675 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2676 return false; 2677 } else if (FromType->isBlockPointerType()) { 2678 Kind = CK_BlockPointerToObjCPointerCast; 2679 } else { 2680 Kind = CK_CPointerToObjCPointerCast; 2681 } 2682 } else if (ToType->isBlockPointerType()) { 2683 if (!FromType->isBlockPointerType()) 2684 Kind = CK_AnyPointerToBlockPointerCast; 2685 } 2686 2687 // We shouldn't fall into this case unless it's valid for other 2688 // reasons. 2689 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2690 Kind = CK_NullToPointer; 2691 2692 return false; 2693} 2694 2695/// IsMemberPointerConversion - Determines whether the conversion of the 2696/// expression From, which has the (possibly adjusted) type FromType, can be 2697/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2698/// If so, returns true and places the converted type (that might differ from 2699/// ToType in its cv-qualifiers at some level) into ConvertedType. 2700bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2701 QualType ToType, 2702 bool InOverloadResolution, 2703 QualType &ConvertedType) { 2704 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2705 if (!ToTypePtr) 2706 return false; 2707 2708 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2709 if (From->isNullPointerConstant(Context, 2710 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2711 : Expr::NPC_ValueDependentIsNull)) { 2712 ConvertedType = ToType; 2713 return true; 2714 } 2715 2716 // Otherwise, both types have to be member pointers. 2717 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2718 if (!FromTypePtr) 2719 return false; 2720 2721 // A pointer to member of B can be converted to a pointer to member of D, 2722 // where D is derived from B (C++ 4.11p2). 2723 QualType FromClass(FromTypePtr->getClass(), 0); 2724 QualType ToClass(ToTypePtr->getClass(), 0); 2725 2726 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2727 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2728 IsDerivedFrom(ToClass, FromClass)) { 2729 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2730 ToClass.getTypePtr()); 2731 return true; 2732 } 2733 2734 return false; 2735} 2736 2737/// CheckMemberPointerConversion - Check the member pointer conversion from the 2738/// expression From to the type ToType. This routine checks for ambiguous or 2739/// virtual or inaccessible base-to-derived member pointer conversions 2740/// for which IsMemberPointerConversion has already returned true. It returns 2741/// true and produces a diagnostic if there was an error, or returns false 2742/// otherwise. 2743bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2744 CastKind &Kind, 2745 CXXCastPath &BasePath, 2746 bool IgnoreBaseAccess) { 2747 QualType FromType = From->getType(); 2748 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2749 if (!FromPtrType) { 2750 // This must be a null pointer to member pointer conversion 2751 assert(From->isNullPointerConstant(Context, 2752 Expr::NPC_ValueDependentIsNull) && 2753 "Expr must be null pointer constant!"); 2754 Kind = CK_NullToMemberPointer; 2755 return false; 2756 } 2757 2758 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2759 assert(ToPtrType && "No member pointer cast has a target type " 2760 "that is not a member pointer."); 2761 2762 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2763 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2764 2765 // FIXME: What about dependent types? 2766 assert(FromClass->isRecordType() && "Pointer into non-class."); 2767 assert(ToClass->isRecordType() && "Pointer into non-class."); 2768 2769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2770 /*DetectVirtual=*/true); 2771 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2772 assert(DerivationOkay && 2773 "Should not have been called if derivation isn't OK."); 2774 (void)DerivationOkay; 2775 2776 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2777 getUnqualifiedType())) { 2778 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2779 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2780 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2781 return true; 2782 } 2783 2784 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2785 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2786 << FromClass << ToClass << QualType(VBase, 0) 2787 << From->getSourceRange(); 2788 return true; 2789 } 2790 2791 if (!IgnoreBaseAccess) 2792 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2793 Paths.front(), 2794 diag::err_downcast_from_inaccessible_base); 2795 2796 // Must be a base to derived member conversion. 2797 BuildBasePathArray(Paths, BasePath); 2798 Kind = CK_BaseToDerivedMemberPointer; 2799 return false; 2800} 2801 2802/// IsQualificationConversion - Determines whether the conversion from 2803/// an rvalue of type FromType to ToType is a qualification conversion 2804/// (C++ 4.4). 2805/// 2806/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2807/// when the qualification conversion involves a change in the Objective-C 2808/// object lifetime. 2809bool 2810Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2811 bool CStyle, bool &ObjCLifetimeConversion) { 2812 FromType = Context.getCanonicalType(FromType); 2813 ToType = Context.getCanonicalType(ToType); 2814 ObjCLifetimeConversion = false; 2815 2816 // If FromType and ToType are the same type, this is not a 2817 // qualification conversion. 2818 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2819 return false; 2820 2821 // (C++ 4.4p4): 2822 // A conversion can add cv-qualifiers at levels other than the first 2823 // in multi-level pointers, subject to the following rules: [...] 2824 bool PreviousToQualsIncludeConst = true; 2825 bool UnwrappedAnyPointer = false; 2826 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2827 // Within each iteration of the loop, we check the qualifiers to 2828 // determine if this still looks like a qualification 2829 // conversion. Then, if all is well, we unwrap one more level of 2830 // pointers or pointers-to-members and do it all again 2831 // until there are no more pointers or pointers-to-members left to 2832 // unwrap. 2833 UnwrappedAnyPointer = true; 2834 2835 Qualifiers FromQuals = FromType.getQualifiers(); 2836 Qualifiers ToQuals = ToType.getQualifiers(); 2837 2838 // Objective-C ARC: 2839 // Check Objective-C lifetime conversions. 2840 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2841 UnwrappedAnyPointer) { 2842 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2843 ObjCLifetimeConversion = true; 2844 FromQuals.removeObjCLifetime(); 2845 ToQuals.removeObjCLifetime(); 2846 } else { 2847 // Qualification conversions cannot cast between different 2848 // Objective-C lifetime qualifiers. 2849 return false; 2850 } 2851 } 2852 2853 // Allow addition/removal of GC attributes but not changing GC attributes. 2854 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2855 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2856 FromQuals.removeObjCGCAttr(); 2857 ToQuals.removeObjCGCAttr(); 2858 } 2859 2860 // -- for every j > 0, if const is in cv 1,j then const is in cv 2861 // 2,j, and similarly for volatile. 2862 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2863 return false; 2864 2865 // -- if the cv 1,j and cv 2,j are different, then const is in 2866 // every cv for 0 < k < j. 2867 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2868 && !PreviousToQualsIncludeConst) 2869 return false; 2870 2871 // Keep track of whether all prior cv-qualifiers in the "to" type 2872 // include const. 2873 PreviousToQualsIncludeConst 2874 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2875 } 2876 2877 // We are left with FromType and ToType being the pointee types 2878 // after unwrapping the original FromType and ToType the same number 2879 // of types. If we unwrapped any pointers, and if FromType and 2880 // ToType have the same unqualified type (since we checked 2881 // qualifiers above), then this is a qualification conversion. 2882 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2883} 2884 2885/// \brief - Determine whether this is a conversion from a scalar type to an 2886/// atomic type. 2887/// 2888/// If successful, updates \c SCS's second and third steps in the conversion 2889/// sequence to finish the conversion. 2890static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2891 bool InOverloadResolution, 2892 StandardConversionSequence &SCS, 2893 bool CStyle) { 2894 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2895 if (!ToAtomic) 2896 return false; 2897 2898 StandardConversionSequence InnerSCS; 2899 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2900 InOverloadResolution, InnerSCS, 2901 CStyle, /*AllowObjCWritebackConversion=*/false)) 2902 return false; 2903 2904 SCS.Second = InnerSCS.Second; 2905 SCS.setToType(1, InnerSCS.getToType(1)); 2906 SCS.Third = InnerSCS.Third; 2907 SCS.QualificationIncludesObjCLifetime 2908 = InnerSCS.QualificationIncludesObjCLifetime; 2909 SCS.setToType(2, InnerSCS.getToType(2)); 2910 return true; 2911} 2912 2913static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2914 CXXConstructorDecl *Constructor, 2915 QualType Type) { 2916 const FunctionProtoType *CtorType = 2917 Constructor->getType()->getAs<FunctionProtoType>(); 2918 if (CtorType->getNumArgs() > 0) { 2919 QualType FirstArg = CtorType->getArgType(0); 2920 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2921 return true; 2922 } 2923 return false; 2924} 2925 2926static OverloadingResult 2927IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2928 CXXRecordDecl *To, 2929 UserDefinedConversionSequence &User, 2930 OverloadCandidateSet &CandidateSet, 2931 bool AllowExplicit) { 2932 DeclContext::lookup_result R = S.LookupConstructors(To); 2933 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2934 Con != ConEnd; ++Con) { 2935 NamedDecl *D = *Con; 2936 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2937 2938 // Find the constructor (which may be a template). 2939 CXXConstructorDecl *Constructor = 0; 2940 FunctionTemplateDecl *ConstructorTmpl 2941 = dyn_cast<FunctionTemplateDecl>(D); 2942 if (ConstructorTmpl) 2943 Constructor 2944 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2945 else 2946 Constructor = cast<CXXConstructorDecl>(D); 2947 2948 bool Usable = !Constructor->isInvalidDecl() && 2949 S.isInitListConstructor(Constructor) && 2950 (AllowExplicit || !Constructor->isExplicit()); 2951 if (Usable) { 2952 // If the first argument is (a reference to) the target type, 2953 // suppress conversions. 2954 bool SuppressUserConversions = 2955 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2956 if (ConstructorTmpl) 2957 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2958 /*ExplicitArgs*/ 0, 2959 From, CandidateSet, 2960 SuppressUserConversions); 2961 else 2962 S.AddOverloadCandidate(Constructor, FoundDecl, 2963 From, CandidateSet, 2964 SuppressUserConversions); 2965 } 2966 } 2967 2968 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2969 2970 OverloadCandidateSet::iterator Best; 2971 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2972 case OR_Success: { 2973 // Record the standard conversion we used and the conversion function. 2974 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2975 QualType ThisType = Constructor->getThisType(S.Context); 2976 // Initializer lists don't have conversions as such. 2977 User.Before.setAsIdentityConversion(); 2978 User.HadMultipleCandidates = HadMultipleCandidates; 2979 User.ConversionFunction = Constructor; 2980 User.FoundConversionFunction = Best->FoundDecl; 2981 User.After.setAsIdentityConversion(); 2982 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2983 User.After.setAllToTypes(ToType); 2984 return OR_Success; 2985 } 2986 2987 case OR_No_Viable_Function: 2988 return OR_No_Viable_Function; 2989 case OR_Deleted: 2990 return OR_Deleted; 2991 case OR_Ambiguous: 2992 return OR_Ambiguous; 2993 } 2994 2995 llvm_unreachable("Invalid OverloadResult!"); 2996} 2997 2998/// Determines whether there is a user-defined conversion sequence 2999/// (C++ [over.ics.user]) that converts expression From to the type 3000/// ToType. If such a conversion exists, User will contain the 3001/// user-defined conversion sequence that performs such a conversion 3002/// and this routine will return true. Otherwise, this routine returns 3003/// false and User is unspecified. 3004/// 3005/// \param AllowExplicit true if the conversion should consider C++0x 3006/// "explicit" conversion functions as well as non-explicit conversion 3007/// functions (C++0x [class.conv.fct]p2). 3008static OverloadingResult 3009IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3010 UserDefinedConversionSequence &User, 3011 OverloadCandidateSet &CandidateSet, 3012 bool AllowExplicit) { 3013 // Whether we will only visit constructors. 3014 bool ConstructorsOnly = false; 3015 3016 // If the type we are conversion to is a class type, enumerate its 3017 // constructors. 3018 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3019 // C++ [over.match.ctor]p1: 3020 // When objects of class type are direct-initialized (8.5), or 3021 // copy-initialized from an expression of the same or a 3022 // derived class type (8.5), overload resolution selects the 3023 // constructor. [...] For copy-initialization, the candidate 3024 // functions are all the converting constructors (12.3.1) of 3025 // that class. The argument list is the expression-list within 3026 // the parentheses of the initializer. 3027 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3028 (From->getType()->getAs<RecordType>() && 3029 S.IsDerivedFrom(From->getType(), ToType))) 3030 ConstructorsOnly = true; 3031 3032 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3033 // RequireCompleteType may have returned true due to some invalid decl 3034 // during template instantiation, but ToType may be complete enough now 3035 // to try to recover. 3036 if (ToType->isIncompleteType()) { 3037 // We're not going to find any constructors. 3038 } else if (CXXRecordDecl *ToRecordDecl 3039 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3040 3041 Expr **Args = &From; 3042 unsigned NumArgs = 1; 3043 bool ListInitializing = false; 3044 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3045 // But first, see if there is an init-list-contructor that will work. 3046 OverloadingResult Result = IsInitializerListConstructorConversion( 3047 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3048 if (Result != OR_No_Viable_Function) 3049 return Result; 3050 // Never mind. 3051 CandidateSet.clear(); 3052 3053 // If we're list-initializing, we pass the individual elements as 3054 // arguments, not the entire list. 3055 Args = InitList->getInits(); 3056 NumArgs = InitList->getNumInits(); 3057 ListInitializing = true; 3058 } 3059 3060 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3061 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3062 Con != ConEnd; ++Con) { 3063 NamedDecl *D = *Con; 3064 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3065 3066 // Find the constructor (which may be a template). 3067 CXXConstructorDecl *Constructor = 0; 3068 FunctionTemplateDecl *ConstructorTmpl 3069 = dyn_cast<FunctionTemplateDecl>(D); 3070 if (ConstructorTmpl) 3071 Constructor 3072 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3073 else 3074 Constructor = cast<CXXConstructorDecl>(D); 3075 3076 bool Usable = !Constructor->isInvalidDecl(); 3077 if (ListInitializing) 3078 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3079 else 3080 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3081 if (Usable) { 3082 bool SuppressUserConversions = !ConstructorsOnly; 3083 if (SuppressUserConversions && ListInitializing) { 3084 SuppressUserConversions = false; 3085 if (NumArgs == 1) { 3086 // If the first argument is (a reference to) the target type, 3087 // suppress conversions. 3088 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3089 S.Context, Constructor, ToType); 3090 } 3091 } 3092 if (ConstructorTmpl) 3093 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3094 /*ExplicitArgs*/ 0, 3095 llvm::makeArrayRef(Args, NumArgs), 3096 CandidateSet, SuppressUserConversions); 3097 else 3098 // Allow one user-defined conversion when user specifies a 3099 // From->ToType conversion via an static cast (c-style, etc). 3100 S.AddOverloadCandidate(Constructor, FoundDecl, 3101 llvm::makeArrayRef(Args, NumArgs), 3102 CandidateSet, SuppressUserConversions); 3103 } 3104 } 3105 } 3106 } 3107 3108 // Enumerate conversion functions, if we're allowed to. 3109 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3110 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3111 // No conversion functions from incomplete types. 3112 } else if (const RecordType *FromRecordType 3113 = From->getType()->getAs<RecordType>()) { 3114 if (CXXRecordDecl *FromRecordDecl 3115 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3116 // Add all of the conversion functions as candidates. 3117 std::pair<CXXRecordDecl::conversion_iterator, 3118 CXXRecordDecl::conversion_iterator> 3119 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3120 for (CXXRecordDecl::conversion_iterator 3121 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3122 DeclAccessPair FoundDecl = I.getPair(); 3123 NamedDecl *D = FoundDecl.getDecl(); 3124 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3125 if (isa<UsingShadowDecl>(D)) 3126 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3127 3128 CXXConversionDecl *Conv; 3129 FunctionTemplateDecl *ConvTemplate; 3130 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3131 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3132 else 3133 Conv = cast<CXXConversionDecl>(D); 3134 3135 if (AllowExplicit || !Conv->isExplicit()) { 3136 if (ConvTemplate) 3137 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3138 ActingContext, From, ToType, 3139 CandidateSet); 3140 else 3141 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3142 From, ToType, CandidateSet); 3143 } 3144 } 3145 } 3146 } 3147 3148 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3149 3150 OverloadCandidateSet::iterator Best; 3151 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3152 case OR_Success: 3153 // Record the standard conversion we used and the conversion function. 3154 if (CXXConstructorDecl *Constructor 3155 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3156 // C++ [over.ics.user]p1: 3157 // If the user-defined conversion is specified by a 3158 // constructor (12.3.1), the initial standard conversion 3159 // sequence converts the source type to the type required by 3160 // the argument of the constructor. 3161 // 3162 QualType ThisType = Constructor->getThisType(S.Context); 3163 if (isa<InitListExpr>(From)) { 3164 // Initializer lists don't have conversions as such. 3165 User.Before.setAsIdentityConversion(); 3166 } else { 3167 if (Best->Conversions[0].isEllipsis()) 3168 User.EllipsisConversion = true; 3169 else { 3170 User.Before = Best->Conversions[0].Standard; 3171 User.EllipsisConversion = false; 3172 } 3173 } 3174 User.HadMultipleCandidates = HadMultipleCandidates; 3175 User.ConversionFunction = Constructor; 3176 User.FoundConversionFunction = Best->FoundDecl; 3177 User.After.setAsIdentityConversion(); 3178 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3179 User.After.setAllToTypes(ToType); 3180 return OR_Success; 3181 } 3182 if (CXXConversionDecl *Conversion 3183 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3184 // C++ [over.ics.user]p1: 3185 // 3186 // [...] If the user-defined conversion is specified by a 3187 // conversion function (12.3.2), the initial standard 3188 // conversion sequence converts the source type to the 3189 // implicit object parameter of the conversion function. 3190 User.Before = Best->Conversions[0].Standard; 3191 User.HadMultipleCandidates = HadMultipleCandidates; 3192 User.ConversionFunction = Conversion; 3193 User.FoundConversionFunction = Best->FoundDecl; 3194 User.EllipsisConversion = false; 3195 3196 // C++ [over.ics.user]p2: 3197 // The second standard conversion sequence converts the 3198 // result of the user-defined conversion to the target type 3199 // for the sequence. Since an implicit conversion sequence 3200 // is an initialization, the special rules for 3201 // initialization by user-defined conversion apply when 3202 // selecting the best user-defined conversion for a 3203 // user-defined conversion sequence (see 13.3.3 and 3204 // 13.3.3.1). 3205 User.After = Best->FinalConversion; 3206 return OR_Success; 3207 } 3208 llvm_unreachable("Not a constructor or conversion function?"); 3209 3210 case OR_No_Viable_Function: 3211 return OR_No_Viable_Function; 3212 case OR_Deleted: 3213 // No conversion here! We're done. 3214 return OR_Deleted; 3215 3216 case OR_Ambiguous: 3217 return OR_Ambiguous; 3218 } 3219 3220 llvm_unreachable("Invalid OverloadResult!"); 3221} 3222 3223bool 3224Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3225 ImplicitConversionSequence ICS; 3226 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3227 OverloadingResult OvResult = 3228 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3229 CandidateSet, false); 3230 if (OvResult == OR_Ambiguous) 3231 Diag(From->getLocStart(), 3232 diag::err_typecheck_ambiguous_condition) 3233 << From->getType() << ToType << From->getSourceRange(); 3234 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3235 if (!ToType->isIncompleteType() || 3236 !RequireCompleteType(From->getLocStart(), ToType, 3237 diag::err_typecheck_nonviable_condition_incomplete, 3238 From->getType(), From->getSourceRange())) 3239 Diag(From->getLocStart(), 3240 diag::err_typecheck_nonviable_condition) 3241 << From->getType() << From->getSourceRange() << ToType; 3242 } 3243 else 3244 return false; 3245 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3246 return true; 3247} 3248 3249/// \brief Compare the user-defined conversion functions or constructors 3250/// of two user-defined conversion sequences to determine whether any ordering 3251/// is possible. 3252static ImplicitConversionSequence::CompareKind 3253compareConversionFunctions(Sema &S, 3254 FunctionDecl *Function1, 3255 FunctionDecl *Function2) { 3256 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3257 return ImplicitConversionSequence::Indistinguishable; 3258 3259 // Objective-C++: 3260 // If both conversion functions are implicitly-declared conversions from 3261 // a lambda closure type to a function pointer and a block pointer, 3262 // respectively, always prefer the conversion to a function pointer, 3263 // because the function pointer is more lightweight and is more likely 3264 // to keep code working. 3265 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3266 if (!Conv1) 3267 return ImplicitConversionSequence::Indistinguishable; 3268 3269 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3270 if (!Conv2) 3271 return ImplicitConversionSequence::Indistinguishable; 3272 3273 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3274 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3275 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3276 if (Block1 != Block2) 3277 return Block1? ImplicitConversionSequence::Worse 3278 : ImplicitConversionSequence::Better; 3279 } 3280 3281 return ImplicitConversionSequence::Indistinguishable; 3282} 3283 3284/// CompareImplicitConversionSequences - Compare two implicit 3285/// conversion sequences to determine whether one is better than the 3286/// other or if they are indistinguishable (C++ 13.3.3.2). 3287static ImplicitConversionSequence::CompareKind 3288CompareImplicitConversionSequences(Sema &S, 3289 const ImplicitConversionSequence& ICS1, 3290 const ImplicitConversionSequence& ICS2) 3291{ 3292 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3293 // conversion sequences (as defined in 13.3.3.1) 3294 // -- a standard conversion sequence (13.3.3.1.1) is a better 3295 // conversion sequence than a user-defined conversion sequence or 3296 // an ellipsis conversion sequence, and 3297 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3298 // conversion sequence than an ellipsis conversion sequence 3299 // (13.3.3.1.3). 3300 // 3301 // C++0x [over.best.ics]p10: 3302 // For the purpose of ranking implicit conversion sequences as 3303 // described in 13.3.3.2, the ambiguous conversion sequence is 3304 // treated as a user-defined sequence that is indistinguishable 3305 // from any other user-defined conversion sequence. 3306 if (ICS1.getKindRank() < ICS2.getKindRank()) 3307 return ImplicitConversionSequence::Better; 3308 if (ICS2.getKindRank() < ICS1.getKindRank()) 3309 return ImplicitConversionSequence::Worse; 3310 3311 // The following checks require both conversion sequences to be of 3312 // the same kind. 3313 if (ICS1.getKind() != ICS2.getKind()) 3314 return ImplicitConversionSequence::Indistinguishable; 3315 3316 ImplicitConversionSequence::CompareKind Result = 3317 ImplicitConversionSequence::Indistinguishable; 3318 3319 // Two implicit conversion sequences of the same form are 3320 // indistinguishable conversion sequences unless one of the 3321 // following rules apply: (C++ 13.3.3.2p3): 3322 if (ICS1.isStandard()) 3323 Result = CompareStandardConversionSequences(S, 3324 ICS1.Standard, ICS2.Standard); 3325 else if (ICS1.isUserDefined()) { 3326 // User-defined conversion sequence U1 is a better conversion 3327 // sequence than another user-defined conversion sequence U2 if 3328 // they contain the same user-defined conversion function or 3329 // constructor and if the second standard conversion sequence of 3330 // U1 is better than the second standard conversion sequence of 3331 // U2 (C++ 13.3.3.2p3). 3332 if (ICS1.UserDefined.ConversionFunction == 3333 ICS2.UserDefined.ConversionFunction) 3334 Result = CompareStandardConversionSequences(S, 3335 ICS1.UserDefined.After, 3336 ICS2.UserDefined.After); 3337 else 3338 Result = compareConversionFunctions(S, 3339 ICS1.UserDefined.ConversionFunction, 3340 ICS2.UserDefined.ConversionFunction); 3341 } 3342 3343 // List-initialization sequence L1 is a better conversion sequence than 3344 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3345 // for some X and L2 does not. 3346 if (Result == ImplicitConversionSequence::Indistinguishable && 3347 !ICS1.isBad() && 3348 ICS1.isListInitializationSequence() && 3349 ICS2.isListInitializationSequence()) { 3350 if (ICS1.isStdInitializerListElement() && 3351 !ICS2.isStdInitializerListElement()) 3352 return ImplicitConversionSequence::Better; 3353 if (!ICS1.isStdInitializerListElement() && 3354 ICS2.isStdInitializerListElement()) 3355 return ImplicitConversionSequence::Worse; 3356 } 3357 3358 return Result; 3359} 3360 3361static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3362 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3363 Qualifiers Quals; 3364 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3365 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3366 } 3367 3368 return Context.hasSameUnqualifiedType(T1, T2); 3369} 3370 3371// Per 13.3.3.2p3, compare the given standard conversion sequences to 3372// determine if one is a proper subset of the other. 3373static ImplicitConversionSequence::CompareKind 3374compareStandardConversionSubsets(ASTContext &Context, 3375 const StandardConversionSequence& SCS1, 3376 const StandardConversionSequence& SCS2) { 3377 ImplicitConversionSequence::CompareKind Result 3378 = ImplicitConversionSequence::Indistinguishable; 3379 3380 // the identity conversion sequence is considered to be a subsequence of 3381 // any non-identity conversion sequence 3382 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3383 return ImplicitConversionSequence::Better; 3384 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3385 return ImplicitConversionSequence::Worse; 3386 3387 if (SCS1.Second != SCS2.Second) { 3388 if (SCS1.Second == ICK_Identity) 3389 Result = ImplicitConversionSequence::Better; 3390 else if (SCS2.Second == ICK_Identity) 3391 Result = ImplicitConversionSequence::Worse; 3392 else 3393 return ImplicitConversionSequence::Indistinguishable; 3394 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3395 return ImplicitConversionSequence::Indistinguishable; 3396 3397 if (SCS1.Third == SCS2.Third) { 3398 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3399 : ImplicitConversionSequence::Indistinguishable; 3400 } 3401 3402 if (SCS1.Third == ICK_Identity) 3403 return Result == ImplicitConversionSequence::Worse 3404 ? ImplicitConversionSequence::Indistinguishable 3405 : ImplicitConversionSequence::Better; 3406 3407 if (SCS2.Third == ICK_Identity) 3408 return Result == ImplicitConversionSequence::Better 3409 ? ImplicitConversionSequence::Indistinguishable 3410 : ImplicitConversionSequence::Worse; 3411 3412 return ImplicitConversionSequence::Indistinguishable; 3413} 3414 3415/// \brief Determine whether one of the given reference bindings is better 3416/// than the other based on what kind of bindings they are. 3417static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3418 const StandardConversionSequence &SCS2) { 3419 // C++0x [over.ics.rank]p3b4: 3420 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3421 // implicit object parameter of a non-static member function declared 3422 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3423 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3424 // lvalue reference to a function lvalue and S2 binds an rvalue 3425 // reference*. 3426 // 3427 // FIXME: Rvalue references. We're going rogue with the above edits, 3428 // because the semantics in the current C++0x working paper (N3225 at the 3429 // time of this writing) break the standard definition of std::forward 3430 // and std::reference_wrapper when dealing with references to functions. 3431 // Proposed wording changes submitted to CWG for consideration. 3432 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3433 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3434 return false; 3435 3436 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3437 SCS2.IsLvalueReference) || 3438 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3439 !SCS2.IsLvalueReference); 3440} 3441 3442/// CompareStandardConversionSequences - Compare two standard 3443/// conversion sequences to determine whether one is better than the 3444/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3445static ImplicitConversionSequence::CompareKind 3446CompareStandardConversionSequences(Sema &S, 3447 const StandardConversionSequence& SCS1, 3448 const StandardConversionSequence& SCS2) 3449{ 3450 // Standard conversion sequence S1 is a better conversion sequence 3451 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3452 3453 // -- S1 is a proper subsequence of S2 (comparing the conversion 3454 // sequences in the canonical form defined by 13.3.3.1.1, 3455 // excluding any Lvalue Transformation; the identity conversion 3456 // sequence is considered to be a subsequence of any 3457 // non-identity conversion sequence) or, if not that, 3458 if (ImplicitConversionSequence::CompareKind CK 3459 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3460 return CK; 3461 3462 // -- the rank of S1 is better than the rank of S2 (by the rules 3463 // defined below), or, if not that, 3464 ImplicitConversionRank Rank1 = SCS1.getRank(); 3465 ImplicitConversionRank Rank2 = SCS2.getRank(); 3466 if (Rank1 < Rank2) 3467 return ImplicitConversionSequence::Better; 3468 else if (Rank2 < Rank1) 3469 return ImplicitConversionSequence::Worse; 3470 3471 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3472 // are indistinguishable unless one of the following rules 3473 // applies: 3474 3475 // A conversion that is not a conversion of a pointer, or 3476 // pointer to member, to bool is better than another conversion 3477 // that is such a conversion. 3478 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3479 return SCS2.isPointerConversionToBool() 3480 ? ImplicitConversionSequence::Better 3481 : ImplicitConversionSequence::Worse; 3482 3483 // C++ [over.ics.rank]p4b2: 3484 // 3485 // If class B is derived directly or indirectly from class A, 3486 // conversion of B* to A* is better than conversion of B* to 3487 // void*, and conversion of A* to void* is better than conversion 3488 // of B* to void*. 3489 bool SCS1ConvertsToVoid 3490 = SCS1.isPointerConversionToVoidPointer(S.Context); 3491 bool SCS2ConvertsToVoid 3492 = SCS2.isPointerConversionToVoidPointer(S.Context); 3493 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3494 // Exactly one of the conversion sequences is a conversion to 3495 // a void pointer; it's the worse conversion. 3496 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3497 : ImplicitConversionSequence::Worse; 3498 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3499 // Neither conversion sequence converts to a void pointer; compare 3500 // their derived-to-base conversions. 3501 if (ImplicitConversionSequence::CompareKind DerivedCK 3502 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3503 return DerivedCK; 3504 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3505 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3506 // Both conversion sequences are conversions to void 3507 // pointers. Compare the source types to determine if there's an 3508 // inheritance relationship in their sources. 3509 QualType FromType1 = SCS1.getFromType(); 3510 QualType FromType2 = SCS2.getFromType(); 3511 3512 // Adjust the types we're converting from via the array-to-pointer 3513 // conversion, if we need to. 3514 if (SCS1.First == ICK_Array_To_Pointer) 3515 FromType1 = S.Context.getArrayDecayedType(FromType1); 3516 if (SCS2.First == ICK_Array_To_Pointer) 3517 FromType2 = S.Context.getArrayDecayedType(FromType2); 3518 3519 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3520 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3521 3522 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3523 return ImplicitConversionSequence::Better; 3524 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3525 return ImplicitConversionSequence::Worse; 3526 3527 // Objective-C++: If one interface is more specific than the 3528 // other, it is the better one. 3529 const ObjCObjectPointerType* FromObjCPtr1 3530 = FromType1->getAs<ObjCObjectPointerType>(); 3531 const ObjCObjectPointerType* FromObjCPtr2 3532 = FromType2->getAs<ObjCObjectPointerType>(); 3533 if (FromObjCPtr1 && FromObjCPtr2) { 3534 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3535 FromObjCPtr2); 3536 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3537 FromObjCPtr1); 3538 if (AssignLeft != AssignRight) { 3539 return AssignLeft? ImplicitConversionSequence::Better 3540 : ImplicitConversionSequence::Worse; 3541 } 3542 } 3543 } 3544 3545 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3546 // bullet 3). 3547 if (ImplicitConversionSequence::CompareKind QualCK 3548 = CompareQualificationConversions(S, SCS1, SCS2)) 3549 return QualCK; 3550 3551 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3552 // Check for a better reference binding based on the kind of bindings. 3553 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3554 return ImplicitConversionSequence::Better; 3555 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3556 return ImplicitConversionSequence::Worse; 3557 3558 // C++ [over.ics.rank]p3b4: 3559 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3560 // which the references refer are the same type except for 3561 // top-level cv-qualifiers, and the type to which the reference 3562 // initialized by S2 refers is more cv-qualified than the type 3563 // to which the reference initialized by S1 refers. 3564 QualType T1 = SCS1.getToType(2); 3565 QualType T2 = SCS2.getToType(2); 3566 T1 = S.Context.getCanonicalType(T1); 3567 T2 = S.Context.getCanonicalType(T2); 3568 Qualifiers T1Quals, T2Quals; 3569 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3570 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3571 if (UnqualT1 == UnqualT2) { 3572 // Objective-C++ ARC: If the references refer to objects with different 3573 // lifetimes, prefer bindings that don't change lifetime. 3574 if (SCS1.ObjCLifetimeConversionBinding != 3575 SCS2.ObjCLifetimeConversionBinding) { 3576 return SCS1.ObjCLifetimeConversionBinding 3577 ? ImplicitConversionSequence::Worse 3578 : ImplicitConversionSequence::Better; 3579 } 3580 3581 // If the type is an array type, promote the element qualifiers to the 3582 // type for comparison. 3583 if (isa<ArrayType>(T1) && T1Quals) 3584 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3585 if (isa<ArrayType>(T2) && T2Quals) 3586 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3587 if (T2.isMoreQualifiedThan(T1)) 3588 return ImplicitConversionSequence::Better; 3589 else if (T1.isMoreQualifiedThan(T2)) 3590 return ImplicitConversionSequence::Worse; 3591 } 3592 } 3593 3594 // In Microsoft mode, prefer an integral conversion to a 3595 // floating-to-integral conversion if the integral conversion 3596 // is between types of the same size. 3597 // For example: 3598 // void f(float); 3599 // void f(int); 3600 // int main { 3601 // long a; 3602 // f(a); 3603 // } 3604 // Here, MSVC will call f(int) instead of generating a compile error 3605 // as clang will do in standard mode. 3606 if (S.getLangOpts().MicrosoftMode && 3607 SCS1.Second == ICK_Integral_Conversion && 3608 SCS2.Second == ICK_Floating_Integral && 3609 S.Context.getTypeSize(SCS1.getFromType()) == 3610 S.Context.getTypeSize(SCS1.getToType(2))) 3611 return ImplicitConversionSequence::Better; 3612 3613 return ImplicitConversionSequence::Indistinguishable; 3614} 3615 3616/// CompareQualificationConversions - Compares two standard conversion 3617/// sequences to determine whether they can be ranked based on their 3618/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3619ImplicitConversionSequence::CompareKind 3620CompareQualificationConversions(Sema &S, 3621 const StandardConversionSequence& SCS1, 3622 const StandardConversionSequence& SCS2) { 3623 // C++ 13.3.3.2p3: 3624 // -- S1 and S2 differ only in their qualification conversion and 3625 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3626 // cv-qualification signature of type T1 is a proper subset of 3627 // the cv-qualification signature of type T2, and S1 is not the 3628 // deprecated string literal array-to-pointer conversion (4.2). 3629 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3630 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3631 return ImplicitConversionSequence::Indistinguishable; 3632 3633 // FIXME: the example in the standard doesn't use a qualification 3634 // conversion (!) 3635 QualType T1 = SCS1.getToType(2); 3636 QualType T2 = SCS2.getToType(2); 3637 T1 = S.Context.getCanonicalType(T1); 3638 T2 = S.Context.getCanonicalType(T2); 3639 Qualifiers T1Quals, T2Quals; 3640 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3641 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3642 3643 // If the types are the same, we won't learn anything by unwrapped 3644 // them. 3645 if (UnqualT1 == UnqualT2) 3646 return ImplicitConversionSequence::Indistinguishable; 3647 3648 // If the type is an array type, promote the element qualifiers to the type 3649 // for comparison. 3650 if (isa<ArrayType>(T1) && T1Quals) 3651 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3652 if (isa<ArrayType>(T2) && T2Quals) 3653 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3654 3655 ImplicitConversionSequence::CompareKind Result 3656 = ImplicitConversionSequence::Indistinguishable; 3657 3658 // Objective-C++ ARC: 3659 // Prefer qualification conversions not involving a change in lifetime 3660 // to qualification conversions that do not change lifetime. 3661 if (SCS1.QualificationIncludesObjCLifetime != 3662 SCS2.QualificationIncludesObjCLifetime) { 3663 Result = SCS1.QualificationIncludesObjCLifetime 3664 ? ImplicitConversionSequence::Worse 3665 : ImplicitConversionSequence::Better; 3666 } 3667 3668 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3669 // Within each iteration of the loop, we check the qualifiers to 3670 // determine if this still looks like a qualification 3671 // conversion. Then, if all is well, we unwrap one more level of 3672 // pointers or pointers-to-members and do it all again 3673 // until there are no more pointers or pointers-to-members left 3674 // to unwrap. This essentially mimics what 3675 // IsQualificationConversion does, but here we're checking for a 3676 // strict subset of qualifiers. 3677 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3678 // The qualifiers are the same, so this doesn't tell us anything 3679 // about how the sequences rank. 3680 ; 3681 else if (T2.isMoreQualifiedThan(T1)) { 3682 // T1 has fewer qualifiers, so it could be the better sequence. 3683 if (Result == ImplicitConversionSequence::Worse) 3684 // Neither has qualifiers that are a subset of the other's 3685 // qualifiers. 3686 return ImplicitConversionSequence::Indistinguishable; 3687 3688 Result = ImplicitConversionSequence::Better; 3689 } else if (T1.isMoreQualifiedThan(T2)) { 3690 // T2 has fewer qualifiers, so it could be the better sequence. 3691 if (Result == ImplicitConversionSequence::Better) 3692 // Neither has qualifiers that are a subset of the other's 3693 // qualifiers. 3694 return ImplicitConversionSequence::Indistinguishable; 3695 3696 Result = ImplicitConversionSequence::Worse; 3697 } else { 3698 // Qualifiers are disjoint. 3699 return ImplicitConversionSequence::Indistinguishable; 3700 } 3701 3702 // If the types after this point are equivalent, we're done. 3703 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3704 break; 3705 } 3706 3707 // Check that the winning standard conversion sequence isn't using 3708 // the deprecated string literal array to pointer conversion. 3709 switch (Result) { 3710 case ImplicitConversionSequence::Better: 3711 if (SCS1.DeprecatedStringLiteralToCharPtr) 3712 Result = ImplicitConversionSequence::Indistinguishable; 3713 break; 3714 3715 case ImplicitConversionSequence::Indistinguishable: 3716 break; 3717 3718 case ImplicitConversionSequence::Worse: 3719 if (SCS2.DeprecatedStringLiteralToCharPtr) 3720 Result = ImplicitConversionSequence::Indistinguishable; 3721 break; 3722 } 3723 3724 return Result; 3725} 3726 3727/// CompareDerivedToBaseConversions - Compares two standard conversion 3728/// sequences to determine whether they can be ranked based on their 3729/// various kinds of derived-to-base conversions (C++ 3730/// [over.ics.rank]p4b3). As part of these checks, we also look at 3731/// conversions between Objective-C interface types. 3732ImplicitConversionSequence::CompareKind 3733CompareDerivedToBaseConversions(Sema &S, 3734 const StandardConversionSequence& SCS1, 3735 const StandardConversionSequence& SCS2) { 3736 QualType FromType1 = SCS1.getFromType(); 3737 QualType ToType1 = SCS1.getToType(1); 3738 QualType FromType2 = SCS2.getFromType(); 3739 QualType ToType2 = SCS2.getToType(1); 3740 3741 // Adjust the types we're converting from via the array-to-pointer 3742 // conversion, if we need to. 3743 if (SCS1.First == ICK_Array_To_Pointer) 3744 FromType1 = S.Context.getArrayDecayedType(FromType1); 3745 if (SCS2.First == ICK_Array_To_Pointer) 3746 FromType2 = S.Context.getArrayDecayedType(FromType2); 3747 3748 // Canonicalize all of the types. 3749 FromType1 = S.Context.getCanonicalType(FromType1); 3750 ToType1 = S.Context.getCanonicalType(ToType1); 3751 FromType2 = S.Context.getCanonicalType(FromType2); 3752 ToType2 = S.Context.getCanonicalType(ToType2); 3753 3754 // C++ [over.ics.rank]p4b3: 3755 // 3756 // If class B is derived directly or indirectly from class A and 3757 // class C is derived directly or indirectly from B, 3758 // 3759 // Compare based on pointer conversions. 3760 if (SCS1.Second == ICK_Pointer_Conversion && 3761 SCS2.Second == ICK_Pointer_Conversion && 3762 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3763 FromType1->isPointerType() && FromType2->isPointerType() && 3764 ToType1->isPointerType() && ToType2->isPointerType()) { 3765 QualType FromPointee1 3766 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3767 QualType ToPointee1 3768 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3769 QualType FromPointee2 3770 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3771 QualType ToPointee2 3772 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3773 3774 // -- conversion of C* to B* is better than conversion of C* to A*, 3775 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3776 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3777 return ImplicitConversionSequence::Better; 3778 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3779 return ImplicitConversionSequence::Worse; 3780 } 3781 3782 // -- conversion of B* to A* is better than conversion of C* to A*, 3783 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3784 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3785 return ImplicitConversionSequence::Better; 3786 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3787 return ImplicitConversionSequence::Worse; 3788 } 3789 } else if (SCS1.Second == ICK_Pointer_Conversion && 3790 SCS2.Second == ICK_Pointer_Conversion) { 3791 const ObjCObjectPointerType *FromPtr1 3792 = FromType1->getAs<ObjCObjectPointerType>(); 3793 const ObjCObjectPointerType *FromPtr2 3794 = FromType2->getAs<ObjCObjectPointerType>(); 3795 const ObjCObjectPointerType *ToPtr1 3796 = ToType1->getAs<ObjCObjectPointerType>(); 3797 const ObjCObjectPointerType *ToPtr2 3798 = ToType2->getAs<ObjCObjectPointerType>(); 3799 3800 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3801 // Apply the same conversion ranking rules for Objective-C pointer types 3802 // that we do for C++ pointers to class types. However, we employ the 3803 // Objective-C pseudo-subtyping relationship used for assignment of 3804 // Objective-C pointer types. 3805 bool FromAssignLeft 3806 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3807 bool FromAssignRight 3808 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3809 bool ToAssignLeft 3810 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3811 bool ToAssignRight 3812 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3813 3814 // A conversion to an a non-id object pointer type or qualified 'id' 3815 // type is better than a conversion to 'id'. 3816 if (ToPtr1->isObjCIdType() && 3817 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3818 return ImplicitConversionSequence::Worse; 3819 if (ToPtr2->isObjCIdType() && 3820 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3821 return ImplicitConversionSequence::Better; 3822 3823 // A conversion to a non-id object pointer type is better than a 3824 // conversion to a qualified 'id' type 3825 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3826 return ImplicitConversionSequence::Worse; 3827 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3828 return ImplicitConversionSequence::Better; 3829 3830 // A conversion to an a non-Class object pointer type or qualified 'Class' 3831 // type is better than a conversion to 'Class'. 3832 if (ToPtr1->isObjCClassType() && 3833 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3834 return ImplicitConversionSequence::Worse; 3835 if (ToPtr2->isObjCClassType() && 3836 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3837 return ImplicitConversionSequence::Better; 3838 3839 // A conversion to a non-Class object pointer type is better than a 3840 // conversion to a qualified 'Class' type. 3841 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3842 return ImplicitConversionSequence::Worse; 3843 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3844 return ImplicitConversionSequence::Better; 3845 3846 // -- "conversion of C* to B* is better than conversion of C* to A*," 3847 if (S.Context.hasSameType(FromType1, FromType2) && 3848 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3849 (ToAssignLeft != ToAssignRight)) 3850 return ToAssignLeft? ImplicitConversionSequence::Worse 3851 : ImplicitConversionSequence::Better; 3852 3853 // -- "conversion of B* to A* is better than conversion of C* to A*," 3854 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3855 (FromAssignLeft != FromAssignRight)) 3856 return FromAssignLeft? ImplicitConversionSequence::Better 3857 : ImplicitConversionSequence::Worse; 3858 } 3859 } 3860 3861 // Ranking of member-pointer types. 3862 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3863 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3864 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3865 const MemberPointerType * FromMemPointer1 = 3866 FromType1->getAs<MemberPointerType>(); 3867 const MemberPointerType * ToMemPointer1 = 3868 ToType1->getAs<MemberPointerType>(); 3869 const MemberPointerType * FromMemPointer2 = 3870 FromType2->getAs<MemberPointerType>(); 3871 const MemberPointerType * ToMemPointer2 = 3872 ToType2->getAs<MemberPointerType>(); 3873 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3874 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3875 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3876 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3877 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3878 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3879 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3880 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3881 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3882 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3883 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3884 return ImplicitConversionSequence::Worse; 3885 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3886 return ImplicitConversionSequence::Better; 3887 } 3888 // conversion of B::* to C::* is better than conversion of A::* to C::* 3889 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3890 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3891 return ImplicitConversionSequence::Better; 3892 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3893 return ImplicitConversionSequence::Worse; 3894 } 3895 } 3896 3897 if (SCS1.Second == ICK_Derived_To_Base) { 3898 // -- conversion of C to B is better than conversion of C to A, 3899 // -- binding of an expression of type C to a reference of type 3900 // B& is better than binding an expression of type C to a 3901 // reference of type A&, 3902 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3903 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3904 if (S.IsDerivedFrom(ToType1, ToType2)) 3905 return ImplicitConversionSequence::Better; 3906 else if (S.IsDerivedFrom(ToType2, ToType1)) 3907 return ImplicitConversionSequence::Worse; 3908 } 3909 3910 // -- conversion of B to A is better than conversion of C to A. 3911 // -- binding of an expression of type B to a reference of type 3912 // A& is better than binding an expression of type C to a 3913 // reference of type A&, 3914 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3915 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3916 if (S.IsDerivedFrom(FromType2, FromType1)) 3917 return ImplicitConversionSequence::Better; 3918 else if (S.IsDerivedFrom(FromType1, FromType2)) 3919 return ImplicitConversionSequence::Worse; 3920 } 3921 } 3922 3923 return ImplicitConversionSequence::Indistinguishable; 3924} 3925 3926/// \brief Determine whether the given type is valid, e.g., it is not an invalid 3927/// C++ class. 3928static bool isTypeValid(QualType T) { 3929 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3930 return !Record->isInvalidDecl(); 3931 3932 return true; 3933} 3934 3935/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3936/// determine whether they are reference-related, 3937/// reference-compatible, reference-compatible with added 3938/// qualification, or incompatible, for use in C++ initialization by 3939/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3940/// type, and the first type (T1) is the pointee type of the reference 3941/// type being initialized. 3942Sema::ReferenceCompareResult 3943Sema::CompareReferenceRelationship(SourceLocation Loc, 3944 QualType OrigT1, QualType OrigT2, 3945 bool &DerivedToBase, 3946 bool &ObjCConversion, 3947 bool &ObjCLifetimeConversion) { 3948 assert(!OrigT1->isReferenceType() && 3949 "T1 must be the pointee type of the reference type"); 3950 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3951 3952 QualType T1 = Context.getCanonicalType(OrigT1); 3953 QualType T2 = Context.getCanonicalType(OrigT2); 3954 Qualifiers T1Quals, T2Quals; 3955 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3956 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3957 3958 // C++ [dcl.init.ref]p4: 3959 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3960 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3961 // T1 is a base class of T2. 3962 DerivedToBase = false; 3963 ObjCConversion = false; 3964 ObjCLifetimeConversion = false; 3965 if (UnqualT1 == UnqualT2) { 3966 // Nothing to do. 3967 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3968 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3969 IsDerivedFrom(UnqualT2, UnqualT1)) 3970 DerivedToBase = true; 3971 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3972 UnqualT2->isObjCObjectOrInterfaceType() && 3973 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3974 ObjCConversion = true; 3975 else 3976 return Ref_Incompatible; 3977 3978 // At this point, we know that T1 and T2 are reference-related (at 3979 // least). 3980 3981 // If the type is an array type, promote the element qualifiers to the type 3982 // for comparison. 3983 if (isa<ArrayType>(T1) && T1Quals) 3984 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3985 if (isa<ArrayType>(T2) && T2Quals) 3986 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3987 3988 // C++ [dcl.init.ref]p4: 3989 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3990 // reference-related to T2 and cv1 is the same cv-qualification 3991 // as, or greater cv-qualification than, cv2. For purposes of 3992 // overload resolution, cases for which cv1 is greater 3993 // cv-qualification than cv2 are identified as 3994 // reference-compatible with added qualification (see 13.3.3.2). 3995 // 3996 // Note that we also require equivalence of Objective-C GC and address-space 3997 // qualifiers when performing these computations, so that e.g., an int in 3998 // address space 1 is not reference-compatible with an int in address 3999 // space 2. 4000 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4001 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4002 T1Quals.removeObjCLifetime(); 4003 T2Quals.removeObjCLifetime(); 4004 ObjCLifetimeConversion = true; 4005 } 4006 4007 if (T1Quals == T2Quals) 4008 return Ref_Compatible; 4009 else if (T1Quals.compatiblyIncludes(T2Quals)) 4010 return Ref_Compatible_With_Added_Qualification; 4011 else 4012 return Ref_Related; 4013} 4014 4015/// \brief Look for a user-defined conversion to an value reference-compatible 4016/// with DeclType. Return true if something definite is found. 4017static bool 4018FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4019 QualType DeclType, SourceLocation DeclLoc, 4020 Expr *Init, QualType T2, bool AllowRvalues, 4021 bool AllowExplicit) { 4022 assert(T2->isRecordType() && "Can only find conversions of record types."); 4023 CXXRecordDecl *T2RecordDecl 4024 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4025 4026 OverloadCandidateSet CandidateSet(DeclLoc); 4027 std::pair<CXXRecordDecl::conversion_iterator, 4028 CXXRecordDecl::conversion_iterator> 4029 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4030 for (CXXRecordDecl::conversion_iterator 4031 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4032 NamedDecl *D = *I; 4033 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4034 if (isa<UsingShadowDecl>(D)) 4035 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4036 4037 FunctionTemplateDecl *ConvTemplate 4038 = dyn_cast<FunctionTemplateDecl>(D); 4039 CXXConversionDecl *Conv; 4040 if (ConvTemplate) 4041 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4042 else 4043 Conv = cast<CXXConversionDecl>(D); 4044 4045 // If this is an explicit conversion, and we're not allowed to consider 4046 // explicit conversions, skip it. 4047 if (!AllowExplicit && Conv->isExplicit()) 4048 continue; 4049 4050 if (AllowRvalues) { 4051 bool DerivedToBase = false; 4052 bool ObjCConversion = false; 4053 bool ObjCLifetimeConversion = false; 4054 4055 // If we are initializing an rvalue reference, don't permit conversion 4056 // functions that return lvalues. 4057 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4058 const ReferenceType *RefType 4059 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4060 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4061 continue; 4062 } 4063 4064 if (!ConvTemplate && 4065 S.CompareReferenceRelationship( 4066 DeclLoc, 4067 Conv->getConversionType().getNonReferenceType() 4068 .getUnqualifiedType(), 4069 DeclType.getNonReferenceType().getUnqualifiedType(), 4070 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4071 Sema::Ref_Incompatible) 4072 continue; 4073 } else { 4074 // If the conversion function doesn't return a reference type, 4075 // it can't be considered for this conversion. An rvalue reference 4076 // is only acceptable if its referencee is a function type. 4077 4078 const ReferenceType *RefType = 4079 Conv->getConversionType()->getAs<ReferenceType>(); 4080 if (!RefType || 4081 (!RefType->isLValueReferenceType() && 4082 !RefType->getPointeeType()->isFunctionType())) 4083 continue; 4084 } 4085 4086 if (ConvTemplate) 4087 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4088 Init, DeclType, CandidateSet); 4089 else 4090 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4091 DeclType, CandidateSet); 4092 } 4093 4094 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4095 4096 OverloadCandidateSet::iterator Best; 4097 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4098 case OR_Success: 4099 // C++ [over.ics.ref]p1: 4100 // 4101 // [...] If the parameter binds directly to the result of 4102 // applying a conversion function to the argument 4103 // expression, the implicit conversion sequence is a 4104 // user-defined conversion sequence (13.3.3.1.2), with the 4105 // second standard conversion sequence either an identity 4106 // conversion or, if the conversion function returns an 4107 // entity of a type that is a derived class of the parameter 4108 // type, a derived-to-base Conversion. 4109 if (!Best->FinalConversion.DirectBinding) 4110 return false; 4111 4112 ICS.setUserDefined(); 4113 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4114 ICS.UserDefined.After = Best->FinalConversion; 4115 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4116 ICS.UserDefined.ConversionFunction = Best->Function; 4117 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4118 ICS.UserDefined.EllipsisConversion = false; 4119 assert(ICS.UserDefined.After.ReferenceBinding && 4120 ICS.UserDefined.After.DirectBinding && 4121 "Expected a direct reference binding!"); 4122 return true; 4123 4124 case OR_Ambiguous: 4125 ICS.setAmbiguous(); 4126 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4127 Cand != CandidateSet.end(); ++Cand) 4128 if (Cand->Viable) 4129 ICS.Ambiguous.addConversion(Cand->Function); 4130 return true; 4131 4132 case OR_No_Viable_Function: 4133 case OR_Deleted: 4134 // There was no suitable conversion, or we found a deleted 4135 // conversion; continue with other checks. 4136 return false; 4137 } 4138 4139 llvm_unreachable("Invalid OverloadResult!"); 4140} 4141 4142/// \brief Compute an implicit conversion sequence for reference 4143/// initialization. 4144static ImplicitConversionSequence 4145TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4146 SourceLocation DeclLoc, 4147 bool SuppressUserConversions, 4148 bool AllowExplicit) { 4149 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4150 4151 // Most paths end in a failed conversion. 4152 ImplicitConversionSequence ICS; 4153 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4154 4155 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4156 QualType T2 = Init->getType(); 4157 4158 // If the initializer is the address of an overloaded function, try 4159 // to resolve the overloaded function. If all goes well, T2 is the 4160 // type of the resulting function. 4161 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4162 DeclAccessPair Found; 4163 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4164 false, Found)) 4165 T2 = Fn->getType(); 4166 } 4167 4168 // Compute some basic properties of the types and the initializer. 4169 bool isRValRef = DeclType->isRValueReferenceType(); 4170 bool DerivedToBase = false; 4171 bool ObjCConversion = false; 4172 bool ObjCLifetimeConversion = false; 4173 Expr::Classification InitCategory = Init->Classify(S.Context); 4174 Sema::ReferenceCompareResult RefRelationship 4175 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4176 ObjCConversion, ObjCLifetimeConversion); 4177 4178 4179 // C++0x [dcl.init.ref]p5: 4180 // A reference to type "cv1 T1" is initialized by an expression 4181 // of type "cv2 T2" as follows: 4182 4183 // -- If reference is an lvalue reference and the initializer expression 4184 if (!isRValRef) { 4185 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4186 // reference-compatible with "cv2 T2," or 4187 // 4188 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4189 if (InitCategory.isLValue() && 4190 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4191 // C++ [over.ics.ref]p1: 4192 // When a parameter of reference type binds directly (8.5.3) 4193 // to an argument expression, the implicit conversion sequence 4194 // is the identity conversion, unless the argument expression 4195 // has a type that is a derived class of the parameter type, 4196 // in which case the implicit conversion sequence is a 4197 // derived-to-base Conversion (13.3.3.1). 4198 ICS.setStandard(); 4199 ICS.Standard.First = ICK_Identity; 4200 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4201 : ObjCConversion? ICK_Compatible_Conversion 4202 : ICK_Identity; 4203 ICS.Standard.Third = ICK_Identity; 4204 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4205 ICS.Standard.setToType(0, T2); 4206 ICS.Standard.setToType(1, T1); 4207 ICS.Standard.setToType(2, T1); 4208 ICS.Standard.ReferenceBinding = true; 4209 ICS.Standard.DirectBinding = true; 4210 ICS.Standard.IsLvalueReference = !isRValRef; 4211 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4212 ICS.Standard.BindsToRvalue = false; 4213 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4214 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4215 ICS.Standard.CopyConstructor = 0; 4216 4217 // Nothing more to do: the inaccessibility/ambiguity check for 4218 // derived-to-base conversions is suppressed when we're 4219 // computing the implicit conversion sequence (C++ 4220 // [over.best.ics]p2). 4221 return ICS; 4222 } 4223 4224 // -- has a class type (i.e., T2 is a class type), where T1 is 4225 // not reference-related to T2, and can be implicitly 4226 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4227 // is reference-compatible with "cv3 T3" 92) (this 4228 // conversion is selected by enumerating the applicable 4229 // conversion functions (13.3.1.6) and choosing the best 4230 // one through overload resolution (13.3)), 4231 if (!SuppressUserConversions && T2->isRecordType() && 4232 !S.RequireCompleteType(DeclLoc, T2, 0) && 4233 RefRelationship == Sema::Ref_Incompatible) { 4234 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4235 Init, T2, /*AllowRvalues=*/false, 4236 AllowExplicit)) 4237 return ICS; 4238 } 4239 } 4240 4241 // -- Otherwise, the reference shall be an lvalue reference to a 4242 // non-volatile const type (i.e., cv1 shall be const), or the reference 4243 // shall be an rvalue reference. 4244 // 4245 // We actually handle one oddity of C++ [over.ics.ref] at this 4246 // point, which is that, due to p2 (which short-circuits reference 4247 // binding by only attempting a simple conversion for non-direct 4248 // bindings) and p3's strange wording, we allow a const volatile 4249 // reference to bind to an rvalue. Hence the check for the presence 4250 // of "const" rather than checking for "const" being the only 4251 // qualifier. 4252 // This is also the point where rvalue references and lvalue inits no longer 4253 // go together. 4254 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4255 return ICS; 4256 4257 // -- If the initializer expression 4258 // 4259 // -- is an xvalue, class prvalue, array prvalue or function 4260 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4261 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4262 (InitCategory.isXValue() || 4263 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4264 (InitCategory.isLValue() && T2->isFunctionType()))) { 4265 ICS.setStandard(); 4266 ICS.Standard.First = ICK_Identity; 4267 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4268 : ObjCConversion? ICK_Compatible_Conversion 4269 : ICK_Identity; 4270 ICS.Standard.Third = ICK_Identity; 4271 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4272 ICS.Standard.setToType(0, T2); 4273 ICS.Standard.setToType(1, T1); 4274 ICS.Standard.setToType(2, T1); 4275 ICS.Standard.ReferenceBinding = true; 4276 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4277 // binding unless we're binding to a class prvalue. 4278 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4279 // allow the use of rvalue references in C++98/03 for the benefit of 4280 // standard library implementors; therefore, we need the xvalue check here. 4281 ICS.Standard.DirectBinding = 4282 S.getLangOpts().CPlusPlus11 || 4283 (InitCategory.isPRValue() && !T2->isRecordType()); 4284 ICS.Standard.IsLvalueReference = !isRValRef; 4285 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4286 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4287 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4288 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4289 ICS.Standard.CopyConstructor = 0; 4290 return ICS; 4291 } 4292 4293 // -- has a class type (i.e., T2 is a class type), where T1 is not 4294 // reference-related to T2, and can be implicitly converted to 4295 // an xvalue, class prvalue, or function lvalue of type 4296 // "cv3 T3", where "cv1 T1" is reference-compatible with 4297 // "cv3 T3", 4298 // 4299 // then the reference is bound to the value of the initializer 4300 // expression in the first case and to the result of the conversion 4301 // in the second case (or, in either case, to an appropriate base 4302 // class subobject). 4303 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4304 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4305 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4306 Init, T2, /*AllowRvalues=*/true, 4307 AllowExplicit)) { 4308 // In the second case, if the reference is an rvalue reference 4309 // and the second standard conversion sequence of the 4310 // user-defined conversion sequence includes an lvalue-to-rvalue 4311 // conversion, the program is ill-formed. 4312 if (ICS.isUserDefined() && isRValRef && 4313 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4314 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4315 4316 return ICS; 4317 } 4318 4319 // -- Otherwise, a temporary of type "cv1 T1" is created and 4320 // initialized from the initializer expression using the 4321 // rules for a non-reference copy initialization (8.5). The 4322 // reference is then bound to the temporary. If T1 is 4323 // reference-related to T2, cv1 must be the same 4324 // cv-qualification as, or greater cv-qualification than, 4325 // cv2; otherwise, the program is ill-formed. 4326 if (RefRelationship == Sema::Ref_Related) { 4327 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4328 // we would be reference-compatible or reference-compatible with 4329 // added qualification. But that wasn't the case, so the reference 4330 // initialization fails. 4331 // 4332 // Note that we only want to check address spaces and cvr-qualifiers here. 4333 // ObjC GC and lifetime qualifiers aren't important. 4334 Qualifiers T1Quals = T1.getQualifiers(); 4335 Qualifiers T2Quals = T2.getQualifiers(); 4336 T1Quals.removeObjCGCAttr(); 4337 T1Quals.removeObjCLifetime(); 4338 T2Quals.removeObjCGCAttr(); 4339 T2Quals.removeObjCLifetime(); 4340 if (!T1Quals.compatiblyIncludes(T2Quals)) 4341 return ICS; 4342 } 4343 4344 // If at least one of the types is a class type, the types are not 4345 // related, and we aren't allowed any user conversions, the 4346 // reference binding fails. This case is important for breaking 4347 // recursion, since TryImplicitConversion below will attempt to 4348 // create a temporary through the use of a copy constructor. 4349 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4350 (T1->isRecordType() || T2->isRecordType())) 4351 return ICS; 4352 4353 // If T1 is reference-related to T2 and the reference is an rvalue 4354 // reference, the initializer expression shall not be an lvalue. 4355 if (RefRelationship >= Sema::Ref_Related && 4356 isRValRef && Init->Classify(S.Context).isLValue()) 4357 return ICS; 4358 4359 // C++ [over.ics.ref]p2: 4360 // When a parameter of reference type is not bound directly to 4361 // an argument expression, the conversion sequence is the one 4362 // required to convert the argument expression to the 4363 // underlying type of the reference according to 4364 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4365 // to copy-initializing a temporary of the underlying type with 4366 // the argument expression. Any difference in top-level 4367 // cv-qualification is subsumed by the initialization itself 4368 // and does not constitute a conversion. 4369 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4370 /*AllowExplicit=*/false, 4371 /*InOverloadResolution=*/false, 4372 /*CStyle=*/false, 4373 /*AllowObjCWritebackConversion=*/false); 4374 4375 // Of course, that's still a reference binding. 4376 if (ICS.isStandard()) { 4377 ICS.Standard.ReferenceBinding = true; 4378 ICS.Standard.IsLvalueReference = !isRValRef; 4379 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4380 ICS.Standard.BindsToRvalue = true; 4381 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4382 ICS.Standard.ObjCLifetimeConversionBinding = false; 4383 } else if (ICS.isUserDefined()) { 4384 // Don't allow rvalue references to bind to lvalues. 4385 if (DeclType->isRValueReferenceType()) { 4386 if (const ReferenceType *RefType 4387 = ICS.UserDefined.ConversionFunction->getResultType() 4388 ->getAs<LValueReferenceType>()) { 4389 if (!RefType->getPointeeType()->isFunctionType()) { 4390 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4391 DeclType); 4392 return ICS; 4393 } 4394 } 4395 } 4396 4397 ICS.UserDefined.After.ReferenceBinding = true; 4398 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4399 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4400 ICS.UserDefined.After.BindsToRvalue = true; 4401 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4402 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4403 } 4404 4405 return ICS; 4406} 4407 4408static ImplicitConversionSequence 4409TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4410 bool SuppressUserConversions, 4411 bool InOverloadResolution, 4412 bool AllowObjCWritebackConversion, 4413 bool AllowExplicit = false); 4414 4415/// TryListConversion - Try to copy-initialize a value of type ToType from the 4416/// initializer list From. 4417static ImplicitConversionSequence 4418TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4419 bool SuppressUserConversions, 4420 bool InOverloadResolution, 4421 bool AllowObjCWritebackConversion) { 4422 // C++11 [over.ics.list]p1: 4423 // When an argument is an initializer list, it is not an expression and 4424 // special rules apply for converting it to a parameter type. 4425 4426 ImplicitConversionSequence Result; 4427 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4428 Result.setListInitializationSequence(); 4429 4430 // We need a complete type for what follows. Incomplete types can never be 4431 // initialized from init lists. 4432 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4433 return Result; 4434 4435 // C++11 [over.ics.list]p2: 4436 // If the parameter type is std::initializer_list<X> or "array of X" and 4437 // all the elements can be implicitly converted to X, the implicit 4438 // conversion sequence is the worst conversion necessary to convert an 4439 // element of the list to X. 4440 bool toStdInitializerList = false; 4441 QualType X; 4442 if (ToType->isArrayType()) 4443 X = S.Context.getAsArrayType(ToType)->getElementType(); 4444 else 4445 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4446 if (!X.isNull()) { 4447 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4448 Expr *Init = From->getInit(i); 4449 ImplicitConversionSequence ICS = 4450 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4451 InOverloadResolution, 4452 AllowObjCWritebackConversion); 4453 // If a single element isn't convertible, fail. 4454 if (ICS.isBad()) { 4455 Result = ICS; 4456 break; 4457 } 4458 // Otherwise, look for the worst conversion. 4459 if (Result.isBad() || 4460 CompareImplicitConversionSequences(S, ICS, Result) == 4461 ImplicitConversionSequence::Worse) 4462 Result = ICS; 4463 } 4464 4465 // For an empty list, we won't have computed any conversion sequence. 4466 // Introduce the identity conversion sequence. 4467 if (From->getNumInits() == 0) { 4468 Result.setStandard(); 4469 Result.Standard.setAsIdentityConversion(); 4470 Result.Standard.setFromType(ToType); 4471 Result.Standard.setAllToTypes(ToType); 4472 } 4473 4474 Result.setListInitializationSequence(); 4475 Result.setStdInitializerListElement(toStdInitializerList); 4476 return Result; 4477 } 4478 4479 // C++11 [over.ics.list]p3: 4480 // Otherwise, if the parameter is a non-aggregate class X and overload 4481 // resolution chooses a single best constructor [...] the implicit 4482 // conversion sequence is a user-defined conversion sequence. If multiple 4483 // constructors are viable but none is better than the others, the 4484 // implicit conversion sequence is a user-defined conversion sequence. 4485 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4486 // This function can deal with initializer lists. 4487 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4488 /*AllowExplicit=*/false, 4489 InOverloadResolution, /*CStyle=*/false, 4490 AllowObjCWritebackConversion); 4491 Result.setListInitializationSequence(); 4492 return Result; 4493 } 4494 4495 // C++11 [over.ics.list]p4: 4496 // Otherwise, if the parameter has an aggregate type which can be 4497 // initialized from the initializer list [...] the implicit conversion 4498 // sequence is a user-defined conversion sequence. 4499 if (ToType->isAggregateType()) { 4500 // Type is an aggregate, argument is an init list. At this point it comes 4501 // down to checking whether the initialization works. 4502 // FIXME: Find out whether this parameter is consumed or not. 4503 InitializedEntity Entity = 4504 InitializedEntity::InitializeParameter(S.Context, ToType, 4505 /*Consumed=*/false); 4506 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4507 Result.setUserDefined(); 4508 Result.UserDefined.Before.setAsIdentityConversion(); 4509 // Initializer lists don't have a type. 4510 Result.UserDefined.Before.setFromType(QualType()); 4511 Result.UserDefined.Before.setAllToTypes(QualType()); 4512 4513 Result.UserDefined.After.setAsIdentityConversion(); 4514 Result.UserDefined.After.setFromType(ToType); 4515 Result.UserDefined.After.setAllToTypes(ToType); 4516 Result.UserDefined.ConversionFunction = 0; 4517 } 4518 return Result; 4519 } 4520 4521 // C++11 [over.ics.list]p5: 4522 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4523 if (ToType->isReferenceType()) { 4524 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4525 // mention initializer lists in any way. So we go by what list- 4526 // initialization would do and try to extrapolate from that. 4527 4528 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4529 4530 // If the initializer list has a single element that is reference-related 4531 // to the parameter type, we initialize the reference from that. 4532 if (From->getNumInits() == 1) { 4533 Expr *Init = From->getInit(0); 4534 4535 QualType T2 = Init->getType(); 4536 4537 // If the initializer is the address of an overloaded function, try 4538 // to resolve the overloaded function. If all goes well, T2 is the 4539 // type of the resulting function. 4540 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4541 DeclAccessPair Found; 4542 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4543 Init, ToType, false, Found)) 4544 T2 = Fn->getType(); 4545 } 4546 4547 // Compute some basic properties of the types and the initializer. 4548 bool dummy1 = false; 4549 bool dummy2 = false; 4550 bool dummy3 = false; 4551 Sema::ReferenceCompareResult RefRelationship 4552 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4553 dummy2, dummy3); 4554 4555 if (RefRelationship >= Sema::Ref_Related) 4556 return TryReferenceInit(S, Init, ToType, 4557 /*FIXME:*/From->getLocStart(), 4558 SuppressUserConversions, 4559 /*AllowExplicit=*/false); 4560 } 4561 4562 // Otherwise, we bind the reference to a temporary created from the 4563 // initializer list. 4564 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4565 InOverloadResolution, 4566 AllowObjCWritebackConversion); 4567 if (Result.isFailure()) 4568 return Result; 4569 assert(!Result.isEllipsis() && 4570 "Sub-initialization cannot result in ellipsis conversion."); 4571 4572 // Can we even bind to a temporary? 4573 if (ToType->isRValueReferenceType() || 4574 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4575 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4576 Result.UserDefined.After; 4577 SCS.ReferenceBinding = true; 4578 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4579 SCS.BindsToRvalue = true; 4580 SCS.BindsToFunctionLvalue = false; 4581 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4582 SCS.ObjCLifetimeConversionBinding = false; 4583 } else 4584 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4585 From, ToType); 4586 return Result; 4587 } 4588 4589 // C++11 [over.ics.list]p6: 4590 // Otherwise, if the parameter type is not a class: 4591 if (!ToType->isRecordType()) { 4592 // - if the initializer list has one element, the implicit conversion 4593 // sequence is the one required to convert the element to the 4594 // parameter type. 4595 unsigned NumInits = From->getNumInits(); 4596 if (NumInits == 1) 4597 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4598 SuppressUserConversions, 4599 InOverloadResolution, 4600 AllowObjCWritebackConversion); 4601 // - if the initializer list has no elements, the implicit conversion 4602 // sequence is the identity conversion. 4603 else if (NumInits == 0) { 4604 Result.setStandard(); 4605 Result.Standard.setAsIdentityConversion(); 4606 Result.Standard.setFromType(ToType); 4607 Result.Standard.setAllToTypes(ToType); 4608 } 4609 Result.setListInitializationSequence(); 4610 return Result; 4611 } 4612 4613 // C++11 [over.ics.list]p7: 4614 // In all cases other than those enumerated above, no conversion is possible 4615 return Result; 4616} 4617 4618/// TryCopyInitialization - Try to copy-initialize a value of type 4619/// ToType from the expression From. Return the implicit conversion 4620/// sequence required to pass this argument, which may be a bad 4621/// conversion sequence (meaning that the argument cannot be passed to 4622/// a parameter of this type). If @p SuppressUserConversions, then we 4623/// do not permit any user-defined conversion sequences. 4624static ImplicitConversionSequence 4625TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4626 bool SuppressUserConversions, 4627 bool InOverloadResolution, 4628 bool AllowObjCWritebackConversion, 4629 bool AllowExplicit) { 4630 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4631 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4632 InOverloadResolution,AllowObjCWritebackConversion); 4633 4634 if (ToType->isReferenceType()) 4635 return TryReferenceInit(S, From, ToType, 4636 /*FIXME:*/From->getLocStart(), 4637 SuppressUserConversions, 4638 AllowExplicit); 4639 4640 return TryImplicitConversion(S, From, ToType, 4641 SuppressUserConversions, 4642 /*AllowExplicit=*/false, 4643 InOverloadResolution, 4644 /*CStyle=*/false, 4645 AllowObjCWritebackConversion); 4646} 4647 4648static bool TryCopyInitialization(const CanQualType FromQTy, 4649 const CanQualType ToQTy, 4650 Sema &S, 4651 SourceLocation Loc, 4652 ExprValueKind FromVK) { 4653 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4654 ImplicitConversionSequence ICS = 4655 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4656 4657 return !ICS.isBad(); 4658} 4659 4660/// TryObjectArgumentInitialization - Try to initialize the object 4661/// parameter of the given member function (@c Method) from the 4662/// expression @p From. 4663static ImplicitConversionSequence 4664TryObjectArgumentInitialization(Sema &S, QualType FromType, 4665 Expr::Classification FromClassification, 4666 CXXMethodDecl *Method, 4667 CXXRecordDecl *ActingContext) { 4668 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4669 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4670 // const volatile object. 4671 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4672 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4673 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4674 4675 // Set up the conversion sequence as a "bad" conversion, to allow us 4676 // to exit early. 4677 ImplicitConversionSequence ICS; 4678 4679 // We need to have an object of class type. 4680 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4681 FromType = PT->getPointeeType(); 4682 4683 // When we had a pointer, it's implicitly dereferenced, so we 4684 // better have an lvalue. 4685 assert(FromClassification.isLValue()); 4686 } 4687 4688 assert(FromType->isRecordType()); 4689 4690 // C++0x [over.match.funcs]p4: 4691 // For non-static member functions, the type of the implicit object 4692 // parameter is 4693 // 4694 // - "lvalue reference to cv X" for functions declared without a 4695 // ref-qualifier or with the & ref-qualifier 4696 // - "rvalue reference to cv X" for functions declared with the && 4697 // ref-qualifier 4698 // 4699 // where X is the class of which the function is a member and cv is the 4700 // cv-qualification on the member function declaration. 4701 // 4702 // However, when finding an implicit conversion sequence for the argument, we 4703 // are not allowed to create temporaries or perform user-defined conversions 4704 // (C++ [over.match.funcs]p5). We perform a simplified version of 4705 // reference binding here, that allows class rvalues to bind to 4706 // non-constant references. 4707 4708 // First check the qualifiers. 4709 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4710 if (ImplicitParamType.getCVRQualifiers() 4711 != FromTypeCanon.getLocalCVRQualifiers() && 4712 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4713 ICS.setBad(BadConversionSequence::bad_qualifiers, 4714 FromType, ImplicitParamType); 4715 return ICS; 4716 } 4717 4718 // Check that we have either the same type or a derived type. It 4719 // affects the conversion rank. 4720 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4721 ImplicitConversionKind SecondKind; 4722 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4723 SecondKind = ICK_Identity; 4724 } else if (S.IsDerivedFrom(FromType, ClassType)) 4725 SecondKind = ICK_Derived_To_Base; 4726 else { 4727 ICS.setBad(BadConversionSequence::unrelated_class, 4728 FromType, ImplicitParamType); 4729 return ICS; 4730 } 4731 4732 // Check the ref-qualifier. 4733 switch (Method->getRefQualifier()) { 4734 case RQ_None: 4735 // Do nothing; we don't care about lvalueness or rvalueness. 4736 break; 4737 4738 case RQ_LValue: 4739 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4740 // non-const lvalue reference cannot bind to an rvalue 4741 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4742 ImplicitParamType); 4743 return ICS; 4744 } 4745 break; 4746 4747 case RQ_RValue: 4748 if (!FromClassification.isRValue()) { 4749 // rvalue reference cannot bind to an lvalue 4750 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4751 ImplicitParamType); 4752 return ICS; 4753 } 4754 break; 4755 } 4756 4757 // Success. Mark this as a reference binding. 4758 ICS.setStandard(); 4759 ICS.Standard.setAsIdentityConversion(); 4760 ICS.Standard.Second = SecondKind; 4761 ICS.Standard.setFromType(FromType); 4762 ICS.Standard.setAllToTypes(ImplicitParamType); 4763 ICS.Standard.ReferenceBinding = true; 4764 ICS.Standard.DirectBinding = true; 4765 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4766 ICS.Standard.BindsToFunctionLvalue = false; 4767 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4768 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4769 = (Method->getRefQualifier() == RQ_None); 4770 return ICS; 4771} 4772 4773/// PerformObjectArgumentInitialization - Perform initialization of 4774/// the implicit object parameter for the given Method with the given 4775/// expression. 4776ExprResult 4777Sema::PerformObjectArgumentInitialization(Expr *From, 4778 NestedNameSpecifier *Qualifier, 4779 NamedDecl *FoundDecl, 4780 CXXMethodDecl *Method) { 4781 QualType FromRecordType, DestType; 4782 QualType ImplicitParamRecordType = 4783 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4784 4785 Expr::Classification FromClassification; 4786 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4787 FromRecordType = PT->getPointeeType(); 4788 DestType = Method->getThisType(Context); 4789 FromClassification = Expr::Classification::makeSimpleLValue(); 4790 } else { 4791 FromRecordType = From->getType(); 4792 DestType = ImplicitParamRecordType; 4793 FromClassification = From->Classify(Context); 4794 } 4795 4796 // Note that we always use the true parent context when performing 4797 // the actual argument initialization. 4798 ImplicitConversionSequence ICS 4799 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4800 Method, Method->getParent()); 4801 if (ICS.isBad()) { 4802 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4803 Qualifiers FromQs = FromRecordType.getQualifiers(); 4804 Qualifiers ToQs = DestType.getQualifiers(); 4805 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4806 if (CVR) { 4807 Diag(From->getLocStart(), 4808 diag::err_member_function_call_bad_cvr) 4809 << Method->getDeclName() << FromRecordType << (CVR - 1) 4810 << From->getSourceRange(); 4811 Diag(Method->getLocation(), diag::note_previous_decl) 4812 << Method->getDeclName(); 4813 return ExprError(); 4814 } 4815 } 4816 4817 return Diag(From->getLocStart(), 4818 diag::err_implicit_object_parameter_init) 4819 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4820 } 4821 4822 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4823 ExprResult FromRes = 4824 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4825 if (FromRes.isInvalid()) 4826 return ExprError(); 4827 From = FromRes.take(); 4828 } 4829 4830 if (!Context.hasSameType(From->getType(), DestType)) 4831 From = ImpCastExprToType(From, DestType, CK_NoOp, 4832 From->getValueKind()).take(); 4833 return Owned(From); 4834} 4835 4836/// TryContextuallyConvertToBool - Attempt to contextually convert the 4837/// expression From to bool (C++0x [conv]p3). 4838static ImplicitConversionSequence 4839TryContextuallyConvertToBool(Sema &S, Expr *From) { 4840 // FIXME: This is pretty broken. 4841 return TryImplicitConversion(S, From, S.Context.BoolTy, 4842 // FIXME: Are these flags correct? 4843 /*SuppressUserConversions=*/false, 4844 /*AllowExplicit=*/true, 4845 /*InOverloadResolution=*/false, 4846 /*CStyle=*/false, 4847 /*AllowObjCWritebackConversion=*/false); 4848} 4849 4850/// PerformContextuallyConvertToBool - Perform a contextual conversion 4851/// of the expression From to bool (C++0x [conv]p3). 4852ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4853 if (checkPlaceholderForOverload(*this, From)) 4854 return ExprError(); 4855 4856 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4857 if (!ICS.isBad()) 4858 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4859 4860 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4861 return Diag(From->getLocStart(), 4862 diag::err_typecheck_bool_condition) 4863 << From->getType() << From->getSourceRange(); 4864 return ExprError(); 4865} 4866 4867/// Check that the specified conversion is permitted in a converted constant 4868/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4869/// is acceptable. 4870static bool CheckConvertedConstantConversions(Sema &S, 4871 StandardConversionSequence &SCS) { 4872 // Since we know that the target type is an integral or unscoped enumeration 4873 // type, most conversion kinds are impossible. All possible First and Third 4874 // conversions are fine. 4875 switch (SCS.Second) { 4876 case ICK_Identity: 4877 case ICK_Integral_Promotion: 4878 case ICK_Integral_Conversion: 4879 case ICK_Zero_Event_Conversion: 4880 return true; 4881 4882 case ICK_Boolean_Conversion: 4883 // Conversion from an integral or unscoped enumeration type to bool is 4884 // classified as ICK_Boolean_Conversion, but it's also an integral 4885 // conversion, so it's permitted in a converted constant expression. 4886 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4887 SCS.getToType(2)->isBooleanType(); 4888 4889 case ICK_Floating_Integral: 4890 case ICK_Complex_Real: 4891 return false; 4892 4893 case ICK_Lvalue_To_Rvalue: 4894 case ICK_Array_To_Pointer: 4895 case ICK_Function_To_Pointer: 4896 case ICK_NoReturn_Adjustment: 4897 case ICK_Qualification: 4898 case ICK_Compatible_Conversion: 4899 case ICK_Vector_Conversion: 4900 case ICK_Vector_Splat: 4901 case ICK_Derived_To_Base: 4902 case ICK_Pointer_Conversion: 4903 case ICK_Pointer_Member: 4904 case ICK_Block_Pointer_Conversion: 4905 case ICK_Writeback_Conversion: 4906 case ICK_Floating_Promotion: 4907 case ICK_Complex_Promotion: 4908 case ICK_Complex_Conversion: 4909 case ICK_Floating_Conversion: 4910 case ICK_TransparentUnionConversion: 4911 llvm_unreachable("unexpected second conversion kind"); 4912 4913 case ICK_Num_Conversion_Kinds: 4914 break; 4915 } 4916 4917 llvm_unreachable("unknown conversion kind"); 4918} 4919 4920/// CheckConvertedConstantExpression - Check that the expression From is a 4921/// converted constant expression of type T, perform the conversion and produce 4922/// the converted expression, per C++11 [expr.const]p3. 4923ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4924 llvm::APSInt &Value, 4925 CCEKind CCE) { 4926 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4927 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4928 4929 if (checkPlaceholderForOverload(*this, From)) 4930 return ExprError(); 4931 4932 // C++11 [expr.const]p3 with proposed wording fixes: 4933 // A converted constant expression of type T is a core constant expression, 4934 // implicitly converted to a prvalue of type T, where the converted 4935 // expression is a literal constant expression and the implicit conversion 4936 // sequence contains only user-defined conversions, lvalue-to-rvalue 4937 // conversions, integral promotions, and integral conversions other than 4938 // narrowing conversions. 4939 ImplicitConversionSequence ICS = 4940 TryImplicitConversion(From, T, 4941 /*SuppressUserConversions=*/false, 4942 /*AllowExplicit=*/false, 4943 /*InOverloadResolution=*/false, 4944 /*CStyle=*/false, 4945 /*AllowObjcWritebackConversion=*/false); 4946 StandardConversionSequence *SCS = 0; 4947 switch (ICS.getKind()) { 4948 case ImplicitConversionSequence::StandardConversion: 4949 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4950 return Diag(From->getLocStart(), 4951 diag::err_typecheck_converted_constant_expression_disallowed) 4952 << From->getType() << From->getSourceRange() << T; 4953 SCS = &ICS.Standard; 4954 break; 4955 case ImplicitConversionSequence::UserDefinedConversion: 4956 // We are converting from class type to an integral or enumeration type, so 4957 // the Before sequence must be trivial. 4958 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4959 return Diag(From->getLocStart(), 4960 diag::err_typecheck_converted_constant_expression_disallowed) 4961 << From->getType() << From->getSourceRange() << T; 4962 SCS = &ICS.UserDefined.After; 4963 break; 4964 case ImplicitConversionSequence::AmbiguousConversion: 4965 case ImplicitConversionSequence::BadConversion: 4966 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4967 return Diag(From->getLocStart(), 4968 diag::err_typecheck_converted_constant_expression) 4969 << From->getType() << From->getSourceRange() << T; 4970 return ExprError(); 4971 4972 case ImplicitConversionSequence::EllipsisConversion: 4973 llvm_unreachable("ellipsis conversion in converted constant expression"); 4974 } 4975 4976 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4977 if (Result.isInvalid()) 4978 return Result; 4979 4980 // Check for a narrowing implicit conversion. 4981 APValue PreNarrowingValue; 4982 QualType PreNarrowingType; 4983 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4984 PreNarrowingType)) { 4985 case NK_Variable_Narrowing: 4986 // Implicit conversion to a narrower type, and the value is not a constant 4987 // expression. We'll diagnose this in a moment. 4988 case NK_Not_Narrowing: 4989 break; 4990 4991 case NK_Constant_Narrowing: 4992 Diag(From->getLocStart(), 4993 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4994 diag::err_cce_narrowing) 4995 << CCE << /*Constant*/1 4996 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4997 break; 4998 4999 case NK_Type_Narrowing: 5000 Diag(From->getLocStart(), 5001 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 5002 diag::err_cce_narrowing) 5003 << CCE << /*Constant*/0 << From->getType() << T; 5004 break; 5005 } 5006 5007 // Check the expression is a constant expression. 5008 SmallVector<PartialDiagnosticAt, 8> Notes; 5009 Expr::EvalResult Eval; 5010 Eval.Diag = &Notes; 5011 5012 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) { 5013 // The expression can't be folded, so we can't keep it at this position in 5014 // the AST. 5015 Result = ExprError(); 5016 } else { 5017 Value = Eval.Val.getInt(); 5018 5019 if (Notes.empty()) { 5020 // It's a constant expression. 5021 return Result; 5022 } 5023 } 5024 5025 // It's not a constant expression. Produce an appropriate diagnostic. 5026 if (Notes.size() == 1 && 5027 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5028 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5029 else { 5030 Diag(From->getLocStart(), diag::err_expr_not_cce) 5031 << CCE << From->getSourceRange(); 5032 for (unsigned I = 0; I < Notes.size(); ++I) 5033 Diag(Notes[I].first, Notes[I].second); 5034 } 5035 return Result; 5036} 5037 5038/// dropPointerConversions - If the given standard conversion sequence 5039/// involves any pointer conversions, remove them. This may change 5040/// the result type of the conversion sequence. 5041static void dropPointerConversion(StandardConversionSequence &SCS) { 5042 if (SCS.Second == ICK_Pointer_Conversion) { 5043 SCS.Second = ICK_Identity; 5044 SCS.Third = ICK_Identity; 5045 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5046 } 5047} 5048 5049/// TryContextuallyConvertToObjCPointer - Attempt to contextually 5050/// convert the expression From to an Objective-C pointer type. 5051static ImplicitConversionSequence 5052TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5053 // Do an implicit conversion to 'id'. 5054 QualType Ty = S.Context.getObjCIdType(); 5055 ImplicitConversionSequence ICS 5056 = TryImplicitConversion(S, From, Ty, 5057 // FIXME: Are these flags correct? 5058 /*SuppressUserConversions=*/false, 5059 /*AllowExplicit=*/true, 5060 /*InOverloadResolution=*/false, 5061 /*CStyle=*/false, 5062 /*AllowObjCWritebackConversion=*/false); 5063 5064 // Strip off any final conversions to 'id'. 5065 switch (ICS.getKind()) { 5066 case ImplicitConversionSequence::BadConversion: 5067 case ImplicitConversionSequence::AmbiguousConversion: 5068 case ImplicitConversionSequence::EllipsisConversion: 5069 break; 5070 5071 case ImplicitConversionSequence::UserDefinedConversion: 5072 dropPointerConversion(ICS.UserDefined.After); 5073 break; 5074 5075 case ImplicitConversionSequence::StandardConversion: 5076 dropPointerConversion(ICS.Standard); 5077 break; 5078 } 5079 5080 return ICS; 5081} 5082 5083/// PerformContextuallyConvertToObjCPointer - Perform a contextual 5084/// conversion of the expression From to an Objective-C pointer type. 5085ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5086 if (checkPlaceholderForOverload(*this, From)) 5087 return ExprError(); 5088 5089 QualType Ty = Context.getObjCIdType(); 5090 ImplicitConversionSequence ICS = 5091 TryContextuallyConvertToObjCPointer(*this, From); 5092 if (!ICS.isBad()) 5093 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5094 return ExprError(); 5095} 5096 5097/// Determine whether the provided type is an integral type, or an enumeration 5098/// type of a permitted flavor. 5099bool Sema::ICEConvertDiagnoser::match(QualType T) { 5100 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5101 : T->isIntegralOrUnscopedEnumerationType(); 5102} 5103 5104static ExprResult 5105diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5106 Sema::ContextualImplicitConverter &Converter, 5107 QualType T, UnresolvedSetImpl &ViableConversions) { 5108 5109 if (Converter.Suppress) 5110 return ExprError(); 5111 5112 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5113 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5114 CXXConversionDecl *Conv = 5115 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5116 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5117 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5118 } 5119 return SemaRef.Owned(From); 5120} 5121 5122static bool 5123diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5124 Sema::ContextualImplicitConverter &Converter, 5125 QualType T, bool HadMultipleCandidates, 5126 UnresolvedSetImpl &ExplicitConversions) { 5127 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5128 DeclAccessPair Found = ExplicitConversions[0]; 5129 CXXConversionDecl *Conversion = 5130 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5131 5132 // The user probably meant to invoke the given explicit 5133 // conversion; use it. 5134 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5135 std::string TypeStr; 5136 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5137 5138 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5139 << FixItHint::CreateInsertion(From->getLocStart(), 5140 "static_cast<" + TypeStr + ">(") 5141 << FixItHint::CreateInsertion( 5142 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")"); 5143 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5144 5145 // If we aren't in a SFINAE context, build a call to the 5146 // explicit conversion function. 5147 if (SemaRef.isSFINAEContext()) 5148 return true; 5149 5150 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5151 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5152 HadMultipleCandidates); 5153 if (Result.isInvalid()) 5154 return true; 5155 // Record usage of conversion in an implicit cast. 5156 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5157 CK_UserDefinedConversion, Result.get(), 0, 5158 Result.get()->getValueKind()); 5159 } 5160 return false; 5161} 5162 5163static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5164 Sema::ContextualImplicitConverter &Converter, 5165 QualType T, bool HadMultipleCandidates, 5166 DeclAccessPair &Found) { 5167 CXXConversionDecl *Conversion = 5168 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5169 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5170 5171 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5172 if (!Converter.SuppressConversion) { 5173 if (SemaRef.isSFINAEContext()) 5174 return true; 5175 5176 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5177 << From->getSourceRange(); 5178 } 5179 5180 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5181 HadMultipleCandidates); 5182 if (Result.isInvalid()) 5183 return true; 5184 // Record usage of conversion in an implicit cast. 5185 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5186 CK_UserDefinedConversion, Result.get(), 0, 5187 Result.get()->getValueKind()); 5188 return false; 5189} 5190 5191static ExprResult finishContextualImplicitConversion( 5192 Sema &SemaRef, SourceLocation Loc, Expr *From, 5193 Sema::ContextualImplicitConverter &Converter) { 5194 if (!Converter.match(From->getType()) && !Converter.Suppress) 5195 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5196 << From->getSourceRange(); 5197 5198 return SemaRef.DefaultLvalueConversion(From); 5199} 5200 5201static void 5202collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5203 UnresolvedSetImpl &ViableConversions, 5204 OverloadCandidateSet &CandidateSet) { 5205 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5206 DeclAccessPair FoundDecl = ViableConversions[I]; 5207 NamedDecl *D = FoundDecl.getDecl(); 5208 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5209 if (isa<UsingShadowDecl>(D)) 5210 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5211 5212 CXXConversionDecl *Conv; 5213 FunctionTemplateDecl *ConvTemplate; 5214 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5215 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5216 else 5217 Conv = cast<CXXConversionDecl>(D); 5218 5219 if (ConvTemplate) 5220 SemaRef.AddTemplateConversionCandidate( 5221 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet); 5222 else 5223 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5224 ToType, CandidateSet); 5225 } 5226} 5227 5228/// \brief Attempt to convert the given expression to a type which is accepted 5229/// by the given converter. 5230/// 5231/// This routine will attempt to convert an expression of class type to a 5232/// type accepted by the specified converter. In C++11 and before, the class 5233/// must have a single non-explicit conversion function converting to a matching 5234/// type. In C++1y, there can be multiple such conversion functions, but only 5235/// one target type. 5236/// 5237/// \param Loc The source location of the construct that requires the 5238/// conversion. 5239/// 5240/// \param From The expression we're converting from. 5241/// 5242/// \param Converter Used to control and diagnose the conversion process. 5243/// 5244/// \returns The expression, converted to an integral or enumeration type if 5245/// successful. 5246ExprResult Sema::PerformContextualImplicitConversion( 5247 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5248 // We can't perform any more checking for type-dependent expressions. 5249 if (From->isTypeDependent()) 5250 return Owned(From); 5251 5252 // Process placeholders immediately. 5253 if (From->hasPlaceholderType()) { 5254 ExprResult result = CheckPlaceholderExpr(From); 5255 if (result.isInvalid()) 5256 return result; 5257 From = result.take(); 5258 } 5259 5260 // If the expression already has a matching type, we're golden. 5261 QualType T = From->getType(); 5262 if (Converter.match(T)) 5263 return DefaultLvalueConversion(From); 5264 5265 // FIXME: Check for missing '()' if T is a function type? 5266 5267 // We can only perform contextual implicit conversions on objects of class 5268 // type. 5269 const RecordType *RecordTy = T->getAs<RecordType>(); 5270 if (!RecordTy || !getLangOpts().CPlusPlus) { 5271 if (!Converter.Suppress) 5272 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5273 return Owned(From); 5274 } 5275 5276 // We must have a complete class type. 5277 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5278 ContextualImplicitConverter &Converter; 5279 Expr *From; 5280 5281 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5282 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5283 5284 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5285 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5286 } 5287 } IncompleteDiagnoser(Converter, From); 5288 5289 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5290 return Owned(From); 5291 5292 // Look for a conversion to an integral or enumeration type. 5293 UnresolvedSet<4> 5294 ViableConversions; // These are *potentially* viable in C++1y. 5295 UnresolvedSet<4> ExplicitConversions; 5296 std::pair<CXXRecordDecl::conversion_iterator, 5297 CXXRecordDecl::conversion_iterator> Conversions = 5298 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5299 5300 bool HadMultipleCandidates = 5301 (std::distance(Conversions.first, Conversions.second) > 1); 5302 5303 // To check that there is only one target type, in C++1y: 5304 QualType ToType; 5305 bool HasUniqueTargetType = true; 5306 5307 // Collect explicit or viable (potentially in C++1y) conversions. 5308 for (CXXRecordDecl::conversion_iterator I = Conversions.first, 5309 E = Conversions.second; 5310 I != E; ++I) { 5311 NamedDecl *D = (*I)->getUnderlyingDecl(); 5312 CXXConversionDecl *Conversion; 5313 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5314 if (ConvTemplate) { 5315 if (getLangOpts().CPlusPlus1y) 5316 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5317 else 5318 continue; // C++11 does not consider conversion operator templates(?). 5319 } else 5320 Conversion = cast<CXXConversionDecl>(D); 5321 5322 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) && 5323 "Conversion operator templates are considered potentially " 5324 "viable in C++1y"); 5325 5326 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5327 if (Converter.match(CurToType) || ConvTemplate) { 5328 5329 if (Conversion->isExplicit()) { 5330 // FIXME: For C++1y, do we need this restriction? 5331 // cf. diagnoseNoViableConversion() 5332 if (!ConvTemplate) 5333 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5334 } else { 5335 if (!ConvTemplate && getLangOpts().CPlusPlus1y) { 5336 if (ToType.isNull()) 5337 ToType = CurToType.getUnqualifiedType(); 5338 else if (HasUniqueTargetType && 5339 (CurToType.getUnqualifiedType() != ToType)) 5340 HasUniqueTargetType = false; 5341 } 5342 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5343 } 5344 } 5345 } 5346 5347 if (getLangOpts().CPlusPlus1y) { 5348 // C++1y [conv]p6: 5349 // ... An expression e of class type E appearing in such a context 5350 // is said to be contextually implicitly converted to a specified 5351 // type T and is well-formed if and only if e can be implicitly 5352 // converted to a type T that is determined as follows: E is searched 5353 // for conversion functions whose return type is cv T or reference to 5354 // cv T such that T is allowed by the context. There shall be 5355 // exactly one such T. 5356 5357 // If no unique T is found: 5358 if (ToType.isNull()) { 5359 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5360 HadMultipleCandidates, 5361 ExplicitConversions)) 5362 return ExprError(); 5363 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5364 } 5365 5366 // If more than one unique Ts are found: 5367 if (!HasUniqueTargetType) 5368 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5369 ViableConversions); 5370 5371 // If one unique T is found: 5372 // First, build a candidate set from the previously recorded 5373 // potentially viable conversions. 5374 OverloadCandidateSet CandidateSet(Loc); 5375 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5376 CandidateSet); 5377 5378 // Then, perform overload resolution over the candidate set. 5379 OverloadCandidateSet::iterator Best; 5380 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5381 case OR_Success: { 5382 // Apply this conversion. 5383 DeclAccessPair Found = 5384 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5385 if (recordConversion(*this, Loc, From, Converter, T, 5386 HadMultipleCandidates, Found)) 5387 return ExprError(); 5388 break; 5389 } 5390 case OR_Ambiguous: 5391 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5392 ViableConversions); 5393 case OR_No_Viable_Function: 5394 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5395 HadMultipleCandidates, 5396 ExplicitConversions)) 5397 return ExprError(); 5398 // fall through 'OR_Deleted' case. 5399 case OR_Deleted: 5400 // We'll complain below about a non-integral condition type. 5401 break; 5402 } 5403 } else { 5404 switch (ViableConversions.size()) { 5405 case 0: { 5406 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5407 HadMultipleCandidates, 5408 ExplicitConversions)) 5409 return ExprError(); 5410 5411 // We'll complain below about a non-integral condition type. 5412 break; 5413 } 5414 case 1: { 5415 // Apply this conversion. 5416 DeclAccessPair Found = ViableConversions[0]; 5417 if (recordConversion(*this, Loc, From, Converter, T, 5418 HadMultipleCandidates, Found)) 5419 return ExprError(); 5420 break; 5421 } 5422 default: 5423 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5424 ViableConversions); 5425 } 5426 } 5427 5428 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5429} 5430 5431/// AddOverloadCandidate - Adds the given function to the set of 5432/// candidate functions, using the given function call arguments. If 5433/// @p SuppressUserConversions, then don't allow user-defined 5434/// conversions via constructors or conversion operators. 5435/// 5436/// \param PartialOverloading true if we are performing "partial" overloading 5437/// based on an incomplete set of function arguments. This feature is used by 5438/// code completion. 5439void 5440Sema::AddOverloadCandidate(FunctionDecl *Function, 5441 DeclAccessPair FoundDecl, 5442 ArrayRef<Expr *> Args, 5443 OverloadCandidateSet& CandidateSet, 5444 bool SuppressUserConversions, 5445 bool PartialOverloading, 5446 bool AllowExplicit) { 5447 const FunctionProtoType* Proto 5448 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5449 assert(Proto && "Functions without a prototype cannot be overloaded"); 5450 assert(!Function->getDescribedFunctionTemplate() && 5451 "Use AddTemplateOverloadCandidate for function templates"); 5452 5453 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5454 if (!isa<CXXConstructorDecl>(Method)) { 5455 // If we get here, it's because we're calling a member function 5456 // that is named without a member access expression (e.g., 5457 // "this->f") that was either written explicitly or created 5458 // implicitly. This can happen with a qualified call to a member 5459 // function, e.g., X::f(). We use an empty type for the implied 5460 // object argument (C++ [over.call.func]p3), and the acting context 5461 // is irrelevant. 5462 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5463 QualType(), Expr::Classification::makeSimpleLValue(), 5464 Args, CandidateSet, SuppressUserConversions); 5465 return; 5466 } 5467 // We treat a constructor like a non-member function, since its object 5468 // argument doesn't participate in overload resolution. 5469 } 5470 5471 if (!CandidateSet.isNewCandidate(Function)) 5472 return; 5473 5474 // Overload resolution is always an unevaluated context. 5475 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5476 5477 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5478 // C++ [class.copy]p3: 5479 // A member function template is never instantiated to perform the copy 5480 // of a class object to an object of its class type. 5481 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5482 if (Args.size() == 1 && 5483 Constructor->isSpecializationCopyingObject() && 5484 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5485 IsDerivedFrom(Args[0]->getType(), ClassType))) 5486 return; 5487 } 5488 5489 // Add this candidate 5490 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5491 Candidate.FoundDecl = FoundDecl; 5492 Candidate.Function = Function; 5493 Candidate.Viable = true; 5494 Candidate.IsSurrogate = false; 5495 Candidate.IgnoreObjectArgument = false; 5496 Candidate.ExplicitCallArguments = Args.size(); 5497 5498 unsigned NumArgsInProto = Proto->getNumArgs(); 5499 5500 // (C++ 13.3.2p2): A candidate function having fewer than m 5501 // parameters is viable only if it has an ellipsis in its parameter 5502 // list (8.3.5). 5503 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5504 !Proto->isVariadic()) { 5505 Candidate.Viable = false; 5506 Candidate.FailureKind = ovl_fail_too_many_arguments; 5507 return; 5508 } 5509 5510 // (C++ 13.3.2p2): A candidate function having more than m parameters 5511 // is viable only if the (m+1)st parameter has a default argument 5512 // (8.3.6). For the purposes of overload resolution, the 5513 // parameter list is truncated on the right, so that there are 5514 // exactly m parameters. 5515 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5516 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5517 // Not enough arguments. 5518 Candidate.Viable = false; 5519 Candidate.FailureKind = ovl_fail_too_few_arguments; 5520 return; 5521 } 5522 5523 // (CUDA B.1): Check for invalid calls between targets. 5524 if (getLangOpts().CUDA) 5525 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5526 if (CheckCUDATarget(Caller, Function)) { 5527 Candidate.Viable = false; 5528 Candidate.FailureKind = ovl_fail_bad_target; 5529 return; 5530 } 5531 5532 // Determine the implicit conversion sequences for each of the 5533 // arguments. 5534 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5535 if (ArgIdx < NumArgsInProto) { 5536 // (C++ 13.3.2p3): for F to be a viable function, there shall 5537 // exist for each argument an implicit conversion sequence 5538 // (13.3.3.1) that converts that argument to the corresponding 5539 // parameter of F. 5540 QualType ParamType = Proto->getArgType(ArgIdx); 5541 Candidate.Conversions[ArgIdx] 5542 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5543 SuppressUserConversions, 5544 /*InOverloadResolution=*/true, 5545 /*AllowObjCWritebackConversion=*/ 5546 getLangOpts().ObjCAutoRefCount, 5547 AllowExplicit); 5548 if (Candidate.Conversions[ArgIdx].isBad()) { 5549 Candidate.Viable = false; 5550 Candidate.FailureKind = ovl_fail_bad_conversion; 5551 break; 5552 } 5553 } else { 5554 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5555 // argument for which there is no corresponding parameter is 5556 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5557 Candidate.Conversions[ArgIdx].setEllipsis(); 5558 } 5559 } 5560} 5561 5562/// \brief Add all of the function declarations in the given function set to 5563/// the overload canddiate set. 5564void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5565 ArrayRef<Expr *> Args, 5566 OverloadCandidateSet& CandidateSet, 5567 bool SuppressUserConversions, 5568 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5569 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5570 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5571 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5572 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5573 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5574 cast<CXXMethodDecl>(FD)->getParent(), 5575 Args[0]->getType(), Args[0]->Classify(Context), 5576 Args.slice(1), CandidateSet, 5577 SuppressUserConversions); 5578 else 5579 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5580 SuppressUserConversions); 5581 } else { 5582 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5583 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5584 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5585 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5586 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5587 ExplicitTemplateArgs, 5588 Args[0]->getType(), 5589 Args[0]->Classify(Context), Args.slice(1), 5590 CandidateSet, SuppressUserConversions); 5591 else 5592 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5593 ExplicitTemplateArgs, Args, 5594 CandidateSet, SuppressUserConversions); 5595 } 5596 } 5597} 5598 5599/// AddMethodCandidate - Adds a named decl (which is some kind of 5600/// method) as a method candidate to the given overload set. 5601void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5602 QualType ObjectType, 5603 Expr::Classification ObjectClassification, 5604 ArrayRef<Expr *> Args, 5605 OverloadCandidateSet& CandidateSet, 5606 bool SuppressUserConversions) { 5607 NamedDecl *Decl = FoundDecl.getDecl(); 5608 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5609 5610 if (isa<UsingShadowDecl>(Decl)) 5611 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5612 5613 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5614 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5615 "Expected a member function template"); 5616 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5617 /*ExplicitArgs*/ 0, 5618 ObjectType, ObjectClassification, 5619 Args, CandidateSet, 5620 SuppressUserConversions); 5621 } else { 5622 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5623 ObjectType, ObjectClassification, 5624 Args, 5625 CandidateSet, SuppressUserConversions); 5626 } 5627} 5628 5629/// AddMethodCandidate - Adds the given C++ member function to the set 5630/// of candidate functions, using the given function call arguments 5631/// and the object argument (@c Object). For example, in a call 5632/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5633/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5634/// allow user-defined conversions via constructors or conversion 5635/// operators. 5636void 5637Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5638 CXXRecordDecl *ActingContext, QualType ObjectType, 5639 Expr::Classification ObjectClassification, 5640 ArrayRef<Expr *> Args, 5641 OverloadCandidateSet& CandidateSet, 5642 bool SuppressUserConversions) { 5643 const FunctionProtoType* Proto 5644 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5645 assert(Proto && "Methods without a prototype cannot be overloaded"); 5646 assert(!isa<CXXConstructorDecl>(Method) && 5647 "Use AddOverloadCandidate for constructors"); 5648 5649 if (!CandidateSet.isNewCandidate(Method)) 5650 return; 5651 5652 // Overload resolution is always an unevaluated context. 5653 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5654 5655 // Add this candidate 5656 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5657 Candidate.FoundDecl = FoundDecl; 5658 Candidate.Function = Method; 5659 Candidate.IsSurrogate = false; 5660 Candidate.IgnoreObjectArgument = false; 5661 Candidate.ExplicitCallArguments = Args.size(); 5662 5663 unsigned NumArgsInProto = Proto->getNumArgs(); 5664 5665 // (C++ 13.3.2p2): A candidate function having fewer than m 5666 // parameters is viable only if it has an ellipsis in its parameter 5667 // list (8.3.5). 5668 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5669 Candidate.Viable = false; 5670 Candidate.FailureKind = ovl_fail_too_many_arguments; 5671 return; 5672 } 5673 5674 // (C++ 13.3.2p2): A candidate function having more than m parameters 5675 // is viable only if the (m+1)st parameter has a default argument 5676 // (8.3.6). For the purposes of overload resolution, the 5677 // parameter list is truncated on the right, so that there are 5678 // exactly m parameters. 5679 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5680 if (Args.size() < MinRequiredArgs) { 5681 // Not enough arguments. 5682 Candidate.Viable = false; 5683 Candidate.FailureKind = ovl_fail_too_few_arguments; 5684 return; 5685 } 5686 5687 Candidate.Viable = true; 5688 5689 if (Method->isStatic() || ObjectType.isNull()) 5690 // The implicit object argument is ignored. 5691 Candidate.IgnoreObjectArgument = true; 5692 else { 5693 // Determine the implicit conversion sequence for the object 5694 // parameter. 5695 Candidate.Conversions[0] 5696 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5697 Method, ActingContext); 5698 if (Candidate.Conversions[0].isBad()) { 5699 Candidate.Viable = false; 5700 Candidate.FailureKind = ovl_fail_bad_conversion; 5701 return; 5702 } 5703 } 5704 5705 // Determine the implicit conversion sequences for each of the 5706 // arguments. 5707 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5708 if (ArgIdx < NumArgsInProto) { 5709 // (C++ 13.3.2p3): for F to be a viable function, there shall 5710 // exist for each argument an implicit conversion sequence 5711 // (13.3.3.1) that converts that argument to the corresponding 5712 // parameter of F. 5713 QualType ParamType = Proto->getArgType(ArgIdx); 5714 Candidate.Conversions[ArgIdx + 1] 5715 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5716 SuppressUserConversions, 5717 /*InOverloadResolution=*/true, 5718 /*AllowObjCWritebackConversion=*/ 5719 getLangOpts().ObjCAutoRefCount); 5720 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5721 Candidate.Viable = false; 5722 Candidate.FailureKind = ovl_fail_bad_conversion; 5723 break; 5724 } 5725 } else { 5726 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5727 // argument for which there is no corresponding parameter is 5728 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5729 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5730 } 5731 } 5732} 5733 5734/// \brief Add a C++ member function template as a candidate to the candidate 5735/// set, using template argument deduction to produce an appropriate member 5736/// function template specialization. 5737void 5738Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5739 DeclAccessPair FoundDecl, 5740 CXXRecordDecl *ActingContext, 5741 TemplateArgumentListInfo *ExplicitTemplateArgs, 5742 QualType ObjectType, 5743 Expr::Classification ObjectClassification, 5744 ArrayRef<Expr *> Args, 5745 OverloadCandidateSet& CandidateSet, 5746 bool SuppressUserConversions) { 5747 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5748 return; 5749 5750 // C++ [over.match.funcs]p7: 5751 // In each case where a candidate is a function template, candidate 5752 // function template specializations are generated using template argument 5753 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5754 // candidate functions in the usual way.113) A given name can refer to one 5755 // or more function templates and also to a set of overloaded non-template 5756 // functions. In such a case, the candidate functions generated from each 5757 // function template are combined with the set of non-template candidate 5758 // functions. 5759 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5760 FunctionDecl *Specialization = 0; 5761 if (TemplateDeductionResult Result 5762 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5763 Specialization, Info)) { 5764 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5765 Candidate.FoundDecl = FoundDecl; 5766 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5767 Candidate.Viable = false; 5768 Candidate.FailureKind = ovl_fail_bad_deduction; 5769 Candidate.IsSurrogate = false; 5770 Candidate.IgnoreObjectArgument = false; 5771 Candidate.ExplicitCallArguments = Args.size(); 5772 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5773 Info); 5774 return; 5775 } 5776 5777 // Add the function template specialization produced by template argument 5778 // deduction as a candidate. 5779 assert(Specialization && "Missing member function template specialization?"); 5780 assert(isa<CXXMethodDecl>(Specialization) && 5781 "Specialization is not a member function?"); 5782 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5783 ActingContext, ObjectType, ObjectClassification, Args, 5784 CandidateSet, SuppressUserConversions); 5785} 5786 5787/// \brief Add a C++ function template specialization as a candidate 5788/// in the candidate set, using template argument deduction to produce 5789/// an appropriate function template specialization. 5790void 5791Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5792 DeclAccessPair FoundDecl, 5793 TemplateArgumentListInfo *ExplicitTemplateArgs, 5794 ArrayRef<Expr *> Args, 5795 OverloadCandidateSet& CandidateSet, 5796 bool SuppressUserConversions) { 5797 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5798 return; 5799 5800 // C++ [over.match.funcs]p7: 5801 // In each case where a candidate is a function template, candidate 5802 // function template specializations are generated using template argument 5803 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5804 // candidate functions in the usual way.113) A given name can refer to one 5805 // or more function templates and also to a set of overloaded non-template 5806 // functions. In such a case, the candidate functions generated from each 5807 // function template are combined with the set of non-template candidate 5808 // functions. 5809 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5810 FunctionDecl *Specialization = 0; 5811 if (TemplateDeductionResult Result 5812 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5813 Specialization, Info)) { 5814 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5815 Candidate.FoundDecl = FoundDecl; 5816 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5817 Candidate.Viable = false; 5818 Candidate.FailureKind = ovl_fail_bad_deduction; 5819 Candidate.IsSurrogate = false; 5820 Candidate.IgnoreObjectArgument = false; 5821 Candidate.ExplicitCallArguments = Args.size(); 5822 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5823 Info); 5824 return; 5825 } 5826 5827 // Add the function template specialization produced by template argument 5828 // deduction as a candidate. 5829 assert(Specialization && "Missing function template specialization?"); 5830 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5831 SuppressUserConversions); 5832} 5833 5834/// AddConversionCandidate - Add a C++ conversion function as a 5835/// candidate in the candidate set (C++ [over.match.conv], 5836/// C++ [over.match.copy]). From is the expression we're converting from, 5837/// and ToType is the type that we're eventually trying to convert to 5838/// (which may or may not be the same type as the type that the 5839/// conversion function produces). 5840void 5841Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5842 DeclAccessPair FoundDecl, 5843 CXXRecordDecl *ActingContext, 5844 Expr *From, QualType ToType, 5845 OverloadCandidateSet& CandidateSet) { 5846 assert(!Conversion->getDescribedFunctionTemplate() && 5847 "Conversion function templates use AddTemplateConversionCandidate"); 5848 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5849 if (!CandidateSet.isNewCandidate(Conversion)) 5850 return; 5851 5852 // If the conversion function has an undeduced return type, trigger its 5853 // deduction now. 5854 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) { 5855 if (DeduceReturnType(Conversion, From->getExprLoc())) 5856 return; 5857 ConvType = Conversion->getConversionType().getNonReferenceType(); 5858 } 5859 5860 // Overload resolution is always an unevaluated context. 5861 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5862 5863 // Add this candidate 5864 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5865 Candidate.FoundDecl = FoundDecl; 5866 Candidate.Function = Conversion; 5867 Candidate.IsSurrogate = false; 5868 Candidate.IgnoreObjectArgument = false; 5869 Candidate.FinalConversion.setAsIdentityConversion(); 5870 Candidate.FinalConversion.setFromType(ConvType); 5871 Candidate.FinalConversion.setAllToTypes(ToType); 5872 Candidate.Viable = true; 5873 Candidate.ExplicitCallArguments = 1; 5874 5875 // C++ [over.match.funcs]p4: 5876 // For conversion functions, the function is considered to be a member of 5877 // the class of the implicit implied object argument for the purpose of 5878 // defining the type of the implicit object parameter. 5879 // 5880 // Determine the implicit conversion sequence for the implicit 5881 // object parameter. 5882 QualType ImplicitParamType = From->getType(); 5883 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5884 ImplicitParamType = FromPtrType->getPointeeType(); 5885 CXXRecordDecl *ConversionContext 5886 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5887 5888 Candidate.Conversions[0] 5889 = TryObjectArgumentInitialization(*this, From->getType(), 5890 From->Classify(Context), 5891 Conversion, ConversionContext); 5892 5893 if (Candidate.Conversions[0].isBad()) { 5894 Candidate.Viable = false; 5895 Candidate.FailureKind = ovl_fail_bad_conversion; 5896 return; 5897 } 5898 5899 // We won't go through a user-define type conversion function to convert a 5900 // derived to base as such conversions are given Conversion Rank. They only 5901 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5902 QualType FromCanon 5903 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5904 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5905 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5906 Candidate.Viable = false; 5907 Candidate.FailureKind = ovl_fail_trivial_conversion; 5908 return; 5909 } 5910 5911 // To determine what the conversion from the result of calling the 5912 // conversion function to the type we're eventually trying to 5913 // convert to (ToType), we need to synthesize a call to the 5914 // conversion function and attempt copy initialization from it. This 5915 // makes sure that we get the right semantics with respect to 5916 // lvalues/rvalues and the type. Fortunately, we can allocate this 5917 // call on the stack and we don't need its arguments to be 5918 // well-formed. 5919 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5920 VK_LValue, From->getLocStart()); 5921 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5922 Context.getPointerType(Conversion->getType()), 5923 CK_FunctionToPointerDecay, 5924 &ConversionRef, VK_RValue); 5925 5926 QualType ConversionType = Conversion->getConversionType(); 5927 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5928 Candidate.Viable = false; 5929 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5930 return; 5931 } 5932 5933 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5934 5935 // Note that it is safe to allocate CallExpr on the stack here because 5936 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5937 // allocator). 5938 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5939 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 5940 From->getLocStart()); 5941 ImplicitConversionSequence ICS = 5942 TryCopyInitialization(*this, &Call, ToType, 5943 /*SuppressUserConversions=*/true, 5944 /*InOverloadResolution=*/false, 5945 /*AllowObjCWritebackConversion=*/false); 5946 5947 switch (ICS.getKind()) { 5948 case ImplicitConversionSequence::StandardConversion: 5949 Candidate.FinalConversion = ICS.Standard; 5950 5951 // C++ [over.ics.user]p3: 5952 // If the user-defined conversion is specified by a specialization of a 5953 // conversion function template, the second standard conversion sequence 5954 // shall have exact match rank. 5955 if (Conversion->getPrimaryTemplate() && 5956 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5957 Candidate.Viable = false; 5958 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5959 } 5960 5961 // C++0x [dcl.init.ref]p5: 5962 // In the second case, if the reference is an rvalue reference and 5963 // the second standard conversion sequence of the user-defined 5964 // conversion sequence includes an lvalue-to-rvalue conversion, the 5965 // program is ill-formed. 5966 if (ToType->isRValueReferenceType() && 5967 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5968 Candidate.Viable = false; 5969 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5970 } 5971 break; 5972 5973 case ImplicitConversionSequence::BadConversion: 5974 Candidate.Viable = false; 5975 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5976 break; 5977 5978 default: 5979 llvm_unreachable( 5980 "Can only end up with a standard conversion sequence or failure"); 5981 } 5982} 5983 5984/// \brief Adds a conversion function template specialization 5985/// candidate to the overload set, using template argument deduction 5986/// to deduce the template arguments of the conversion function 5987/// template from the type that we are converting to (C++ 5988/// [temp.deduct.conv]). 5989void 5990Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5991 DeclAccessPair FoundDecl, 5992 CXXRecordDecl *ActingDC, 5993 Expr *From, QualType ToType, 5994 OverloadCandidateSet &CandidateSet) { 5995 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5996 "Only conversion function templates permitted here"); 5997 5998 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5999 return; 6000 6001 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6002 CXXConversionDecl *Specialization = 0; 6003 if (TemplateDeductionResult Result 6004 = DeduceTemplateArguments(FunctionTemplate, ToType, 6005 Specialization, Info)) { 6006 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6007 Candidate.FoundDecl = FoundDecl; 6008 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6009 Candidate.Viable = false; 6010 Candidate.FailureKind = ovl_fail_bad_deduction; 6011 Candidate.IsSurrogate = false; 6012 Candidate.IgnoreObjectArgument = false; 6013 Candidate.ExplicitCallArguments = 1; 6014 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6015 Info); 6016 return; 6017 } 6018 6019 // Add the conversion function template specialization produced by 6020 // template argument deduction as a candidate. 6021 assert(Specialization && "Missing function template specialization?"); 6022 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6023 CandidateSet); 6024} 6025 6026/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6027/// converts the given @c Object to a function pointer via the 6028/// conversion function @c Conversion, and then attempts to call it 6029/// with the given arguments (C++ [over.call.object]p2-4). Proto is 6030/// the type of function that we'll eventually be calling. 6031void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6032 DeclAccessPair FoundDecl, 6033 CXXRecordDecl *ActingContext, 6034 const FunctionProtoType *Proto, 6035 Expr *Object, 6036 ArrayRef<Expr *> Args, 6037 OverloadCandidateSet& CandidateSet) { 6038 if (!CandidateSet.isNewCandidate(Conversion)) 6039 return; 6040 6041 // Overload resolution is always an unevaluated context. 6042 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6043 6044 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6045 Candidate.FoundDecl = FoundDecl; 6046 Candidate.Function = 0; 6047 Candidate.Surrogate = Conversion; 6048 Candidate.Viable = true; 6049 Candidate.IsSurrogate = true; 6050 Candidate.IgnoreObjectArgument = false; 6051 Candidate.ExplicitCallArguments = Args.size(); 6052 6053 // Determine the implicit conversion sequence for the implicit 6054 // object parameter. 6055 ImplicitConversionSequence ObjectInit 6056 = TryObjectArgumentInitialization(*this, Object->getType(), 6057 Object->Classify(Context), 6058 Conversion, ActingContext); 6059 if (ObjectInit.isBad()) { 6060 Candidate.Viable = false; 6061 Candidate.FailureKind = ovl_fail_bad_conversion; 6062 Candidate.Conversions[0] = ObjectInit; 6063 return; 6064 } 6065 6066 // The first conversion is actually a user-defined conversion whose 6067 // first conversion is ObjectInit's standard conversion (which is 6068 // effectively a reference binding). Record it as such. 6069 Candidate.Conversions[0].setUserDefined(); 6070 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6071 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6072 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6073 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6074 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6075 Candidate.Conversions[0].UserDefined.After 6076 = Candidate.Conversions[0].UserDefined.Before; 6077 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6078 6079 // Find the 6080 unsigned NumArgsInProto = Proto->getNumArgs(); 6081 6082 // (C++ 13.3.2p2): A candidate function having fewer than m 6083 // parameters is viable only if it has an ellipsis in its parameter 6084 // list (8.3.5). 6085 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 6086 Candidate.Viable = false; 6087 Candidate.FailureKind = ovl_fail_too_many_arguments; 6088 return; 6089 } 6090 6091 // Function types don't have any default arguments, so just check if 6092 // we have enough arguments. 6093 if (Args.size() < NumArgsInProto) { 6094 // Not enough arguments. 6095 Candidate.Viable = false; 6096 Candidate.FailureKind = ovl_fail_too_few_arguments; 6097 return; 6098 } 6099 6100 // Determine the implicit conversion sequences for each of the 6101 // arguments. 6102 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6103 if (ArgIdx < NumArgsInProto) { 6104 // (C++ 13.3.2p3): for F to be a viable function, there shall 6105 // exist for each argument an implicit conversion sequence 6106 // (13.3.3.1) that converts that argument to the corresponding 6107 // parameter of F. 6108 QualType ParamType = Proto->getArgType(ArgIdx); 6109 Candidate.Conversions[ArgIdx + 1] 6110 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6111 /*SuppressUserConversions=*/false, 6112 /*InOverloadResolution=*/false, 6113 /*AllowObjCWritebackConversion=*/ 6114 getLangOpts().ObjCAutoRefCount); 6115 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6116 Candidate.Viable = false; 6117 Candidate.FailureKind = ovl_fail_bad_conversion; 6118 break; 6119 } 6120 } else { 6121 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6122 // argument for which there is no corresponding parameter is 6123 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6124 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6125 } 6126 } 6127} 6128 6129/// \brief Add overload candidates for overloaded operators that are 6130/// member functions. 6131/// 6132/// Add the overloaded operator candidates that are member functions 6133/// for the operator Op that was used in an operator expression such 6134/// as "x Op y". , Args/NumArgs provides the operator arguments, and 6135/// CandidateSet will store the added overload candidates. (C++ 6136/// [over.match.oper]). 6137void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6138 SourceLocation OpLoc, 6139 ArrayRef<Expr *> Args, 6140 OverloadCandidateSet& CandidateSet, 6141 SourceRange OpRange) { 6142 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6143 6144 // C++ [over.match.oper]p3: 6145 // For a unary operator @ with an operand of a type whose 6146 // cv-unqualified version is T1, and for a binary operator @ with 6147 // a left operand of a type whose cv-unqualified version is T1 and 6148 // a right operand of a type whose cv-unqualified version is T2, 6149 // three sets of candidate functions, designated member 6150 // candidates, non-member candidates and built-in candidates, are 6151 // constructed as follows: 6152 QualType T1 = Args[0]->getType(); 6153 6154 // -- If T1 is a complete class type or a class currently being 6155 // defined, the set of member candidates is the result of the 6156 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6157 // the set of member candidates is empty. 6158 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6159 // Complete the type if it can be completed. 6160 RequireCompleteType(OpLoc, T1, 0); 6161 // If the type is neither complete nor being defined, bail out now. 6162 if (!T1Rec->getDecl()->getDefinition()) 6163 return; 6164 6165 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6166 LookupQualifiedName(Operators, T1Rec->getDecl()); 6167 Operators.suppressDiagnostics(); 6168 6169 for (LookupResult::iterator Oper = Operators.begin(), 6170 OperEnd = Operators.end(); 6171 Oper != OperEnd; 6172 ++Oper) 6173 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6174 Args[0]->Classify(Context), 6175 Args.slice(1), 6176 CandidateSet, 6177 /* SuppressUserConversions = */ false); 6178 } 6179} 6180 6181/// AddBuiltinCandidate - Add a candidate for a built-in 6182/// operator. ResultTy and ParamTys are the result and parameter types 6183/// of the built-in candidate, respectively. Args and NumArgs are the 6184/// arguments being passed to the candidate. IsAssignmentOperator 6185/// should be true when this built-in candidate is an assignment 6186/// operator. NumContextualBoolArguments is the number of arguments 6187/// (at the beginning of the argument list) that will be contextually 6188/// converted to bool. 6189void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6190 ArrayRef<Expr *> Args, 6191 OverloadCandidateSet& CandidateSet, 6192 bool IsAssignmentOperator, 6193 unsigned NumContextualBoolArguments) { 6194 // Overload resolution is always an unevaluated context. 6195 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6196 6197 // Add this candidate 6198 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6199 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6200 Candidate.Function = 0; 6201 Candidate.IsSurrogate = false; 6202 Candidate.IgnoreObjectArgument = false; 6203 Candidate.BuiltinTypes.ResultTy = ResultTy; 6204 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6205 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6206 6207 // Determine the implicit conversion sequences for each of the 6208 // arguments. 6209 Candidate.Viable = true; 6210 Candidate.ExplicitCallArguments = Args.size(); 6211 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6212 // C++ [over.match.oper]p4: 6213 // For the built-in assignment operators, conversions of the 6214 // left operand are restricted as follows: 6215 // -- no temporaries are introduced to hold the left operand, and 6216 // -- no user-defined conversions are applied to the left 6217 // operand to achieve a type match with the left-most 6218 // parameter of a built-in candidate. 6219 // 6220 // We block these conversions by turning off user-defined 6221 // conversions, since that is the only way that initialization of 6222 // a reference to a non-class type can occur from something that 6223 // is not of the same type. 6224 if (ArgIdx < NumContextualBoolArguments) { 6225 assert(ParamTys[ArgIdx] == Context.BoolTy && 6226 "Contextual conversion to bool requires bool type"); 6227 Candidate.Conversions[ArgIdx] 6228 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6229 } else { 6230 Candidate.Conversions[ArgIdx] 6231 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6232 ArgIdx == 0 && IsAssignmentOperator, 6233 /*InOverloadResolution=*/false, 6234 /*AllowObjCWritebackConversion=*/ 6235 getLangOpts().ObjCAutoRefCount); 6236 } 6237 if (Candidate.Conversions[ArgIdx].isBad()) { 6238 Candidate.Viable = false; 6239 Candidate.FailureKind = ovl_fail_bad_conversion; 6240 break; 6241 } 6242 } 6243} 6244 6245/// BuiltinCandidateTypeSet - A set of types that will be used for the 6246/// candidate operator functions for built-in operators (C++ 6247/// [over.built]). The types are separated into pointer types and 6248/// enumeration types. 6249class BuiltinCandidateTypeSet { 6250 /// TypeSet - A set of types. 6251 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6252 6253 /// PointerTypes - The set of pointer types that will be used in the 6254 /// built-in candidates. 6255 TypeSet PointerTypes; 6256 6257 /// MemberPointerTypes - The set of member pointer types that will be 6258 /// used in the built-in candidates. 6259 TypeSet MemberPointerTypes; 6260 6261 /// EnumerationTypes - The set of enumeration types that will be 6262 /// used in the built-in candidates. 6263 TypeSet EnumerationTypes; 6264 6265 /// \brief The set of vector types that will be used in the built-in 6266 /// candidates. 6267 TypeSet VectorTypes; 6268 6269 /// \brief A flag indicating non-record types are viable candidates 6270 bool HasNonRecordTypes; 6271 6272 /// \brief A flag indicating whether either arithmetic or enumeration types 6273 /// were present in the candidate set. 6274 bool HasArithmeticOrEnumeralTypes; 6275 6276 /// \brief A flag indicating whether the nullptr type was present in the 6277 /// candidate set. 6278 bool HasNullPtrType; 6279 6280 /// Sema - The semantic analysis instance where we are building the 6281 /// candidate type set. 6282 Sema &SemaRef; 6283 6284 /// Context - The AST context in which we will build the type sets. 6285 ASTContext &Context; 6286 6287 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6288 const Qualifiers &VisibleQuals); 6289 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6290 6291public: 6292 /// iterator - Iterates through the types that are part of the set. 6293 typedef TypeSet::iterator iterator; 6294 6295 BuiltinCandidateTypeSet(Sema &SemaRef) 6296 : HasNonRecordTypes(false), 6297 HasArithmeticOrEnumeralTypes(false), 6298 HasNullPtrType(false), 6299 SemaRef(SemaRef), 6300 Context(SemaRef.Context) { } 6301 6302 void AddTypesConvertedFrom(QualType Ty, 6303 SourceLocation Loc, 6304 bool AllowUserConversions, 6305 bool AllowExplicitConversions, 6306 const Qualifiers &VisibleTypeConversionsQuals); 6307 6308 /// pointer_begin - First pointer type found; 6309 iterator pointer_begin() { return PointerTypes.begin(); } 6310 6311 /// pointer_end - Past the last pointer type found; 6312 iterator pointer_end() { return PointerTypes.end(); } 6313 6314 /// member_pointer_begin - First member pointer type found; 6315 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6316 6317 /// member_pointer_end - Past the last member pointer type found; 6318 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6319 6320 /// enumeration_begin - First enumeration type found; 6321 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6322 6323 /// enumeration_end - Past the last enumeration type found; 6324 iterator enumeration_end() { return EnumerationTypes.end(); } 6325 6326 iterator vector_begin() { return VectorTypes.begin(); } 6327 iterator vector_end() { return VectorTypes.end(); } 6328 6329 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6330 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6331 bool hasNullPtrType() const { return HasNullPtrType; } 6332}; 6333 6334/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6335/// the set of pointer types along with any more-qualified variants of 6336/// that type. For example, if @p Ty is "int const *", this routine 6337/// will add "int const *", "int const volatile *", "int const 6338/// restrict *", and "int const volatile restrict *" to the set of 6339/// pointer types. Returns true if the add of @p Ty itself succeeded, 6340/// false otherwise. 6341/// 6342/// FIXME: what to do about extended qualifiers? 6343bool 6344BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6345 const Qualifiers &VisibleQuals) { 6346 6347 // Insert this type. 6348 if (!PointerTypes.insert(Ty)) 6349 return false; 6350 6351 QualType PointeeTy; 6352 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6353 bool buildObjCPtr = false; 6354 if (!PointerTy) { 6355 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6356 PointeeTy = PTy->getPointeeType(); 6357 buildObjCPtr = true; 6358 } else { 6359 PointeeTy = PointerTy->getPointeeType(); 6360 } 6361 6362 // Don't add qualified variants of arrays. For one, they're not allowed 6363 // (the qualifier would sink to the element type), and for another, the 6364 // only overload situation where it matters is subscript or pointer +- int, 6365 // and those shouldn't have qualifier variants anyway. 6366 if (PointeeTy->isArrayType()) 6367 return true; 6368 6369 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6370 bool hasVolatile = VisibleQuals.hasVolatile(); 6371 bool hasRestrict = VisibleQuals.hasRestrict(); 6372 6373 // Iterate through all strict supersets of BaseCVR. 6374 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6375 if ((CVR | BaseCVR) != CVR) continue; 6376 // Skip over volatile if no volatile found anywhere in the types. 6377 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6378 6379 // Skip over restrict if no restrict found anywhere in the types, or if 6380 // the type cannot be restrict-qualified. 6381 if ((CVR & Qualifiers::Restrict) && 6382 (!hasRestrict || 6383 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6384 continue; 6385 6386 // Build qualified pointee type. 6387 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6388 6389 // Build qualified pointer type. 6390 QualType QPointerTy; 6391 if (!buildObjCPtr) 6392 QPointerTy = Context.getPointerType(QPointeeTy); 6393 else 6394 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6395 6396 // Insert qualified pointer type. 6397 PointerTypes.insert(QPointerTy); 6398 } 6399 6400 return true; 6401} 6402 6403/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6404/// to the set of pointer types along with any more-qualified variants of 6405/// that type. For example, if @p Ty is "int const *", this routine 6406/// will add "int const *", "int const volatile *", "int const 6407/// restrict *", and "int const volatile restrict *" to the set of 6408/// pointer types. Returns true if the add of @p Ty itself succeeded, 6409/// false otherwise. 6410/// 6411/// FIXME: what to do about extended qualifiers? 6412bool 6413BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6414 QualType Ty) { 6415 // Insert this type. 6416 if (!MemberPointerTypes.insert(Ty)) 6417 return false; 6418 6419 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6420 assert(PointerTy && "type was not a member pointer type!"); 6421 6422 QualType PointeeTy = PointerTy->getPointeeType(); 6423 // Don't add qualified variants of arrays. For one, they're not allowed 6424 // (the qualifier would sink to the element type), and for another, the 6425 // only overload situation where it matters is subscript or pointer +- int, 6426 // and those shouldn't have qualifier variants anyway. 6427 if (PointeeTy->isArrayType()) 6428 return true; 6429 const Type *ClassTy = PointerTy->getClass(); 6430 6431 // Iterate through all strict supersets of the pointee type's CVR 6432 // qualifiers. 6433 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6434 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6435 if ((CVR | BaseCVR) != CVR) continue; 6436 6437 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6438 MemberPointerTypes.insert( 6439 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6440 } 6441 6442 return true; 6443} 6444 6445/// AddTypesConvertedFrom - Add each of the types to which the type @p 6446/// Ty can be implicit converted to the given set of @p Types. We're 6447/// primarily interested in pointer types and enumeration types. We also 6448/// take member pointer types, for the conditional operator. 6449/// AllowUserConversions is true if we should look at the conversion 6450/// functions of a class type, and AllowExplicitConversions if we 6451/// should also include the explicit conversion functions of a class 6452/// type. 6453void 6454BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6455 SourceLocation Loc, 6456 bool AllowUserConversions, 6457 bool AllowExplicitConversions, 6458 const Qualifiers &VisibleQuals) { 6459 // Only deal with canonical types. 6460 Ty = Context.getCanonicalType(Ty); 6461 6462 // Look through reference types; they aren't part of the type of an 6463 // expression for the purposes of conversions. 6464 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6465 Ty = RefTy->getPointeeType(); 6466 6467 // If we're dealing with an array type, decay to the pointer. 6468 if (Ty->isArrayType()) 6469 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6470 6471 // Otherwise, we don't care about qualifiers on the type. 6472 Ty = Ty.getLocalUnqualifiedType(); 6473 6474 // Flag if we ever add a non-record type. 6475 const RecordType *TyRec = Ty->getAs<RecordType>(); 6476 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6477 6478 // Flag if we encounter an arithmetic type. 6479 HasArithmeticOrEnumeralTypes = 6480 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6481 6482 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6483 PointerTypes.insert(Ty); 6484 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6485 // Insert our type, and its more-qualified variants, into the set 6486 // of types. 6487 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6488 return; 6489 } else if (Ty->isMemberPointerType()) { 6490 // Member pointers are far easier, since the pointee can't be converted. 6491 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6492 return; 6493 } else if (Ty->isEnumeralType()) { 6494 HasArithmeticOrEnumeralTypes = true; 6495 EnumerationTypes.insert(Ty); 6496 } else if (Ty->isVectorType()) { 6497 // We treat vector types as arithmetic types in many contexts as an 6498 // extension. 6499 HasArithmeticOrEnumeralTypes = true; 6500 VectorTypes.insert(Ty); 6501 } else if (Ty->isNullPtrType()) { 6502 HasNullPtrType = true; 6503 } else if (AllowUserConversions && TyRec) { 6504 // No conversion functions in incomplete types. 6505 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6506 return; 6507 6508 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6509 std::pair<CXXRecordDecl::conversion_iterator, 6510 CXXRecordDecl::conversion_iterator> 6511 Conversions = ClassDecl->getVisibleConversionFunctions(); 6512 for (CXXRecordDecl::conversion_iterator 6513 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6514 NamedDecl *D = I.getDecl(); 6515 if (isa<UsingShadowDecl>(D)) 6516 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6517 6518 // Skip conversion function templates; they don't tell us anything 6519 // about which builtin types we can convert to. 6520 if (isa<FunctionTemplateDecl>(D)) 6521 continue; 6522 6523 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6524 if (AllowExplicitConversions || !Conv->isExplicit()) { 6525 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6526 VisibleQuals); 6527 } 6528 } 6529 } 6530} 6531 6532/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6533/// the volatile- and non-volatile-qualified assignment operators for the 6534/// given type to the candidate set. 6535static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6536 QualType T, 6537 ArrayRef<Expr *> Args, 6538 OverloadCandidateSet &CandidateSet) { 6539 QualType ParamTypes[2]; 6540 6541 // T& operator=(T&, T) 6542 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6543 ParamTypes[1] = T; 6544 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6545 /*IsAssignmentOperator=*/true); 6546 6547 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6548 // volatile T& operator=(volatile T&, T) 6549 ParamTypes[0] 6550 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6551 ParamTypes[1] = T; 6552 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6553 /*IsAssignmentOperator=*/true); 6554 } 6555} 6556 6557/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6558/// if any, found in visible type conversion functions found in ArgExpr's type. 6559static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6560 Qualifiers VRQuals; 6561 const RecordType *TyRec; 6562 if (const MemberPointerType *RHSMPType = 6563 ArgExpr->getType()->getAs<MemberPointerType>()) 6564 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6565 else 6566 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6567 if (!TyRec) { 6568 // Just to be safe, assume the worst case. 6569 VRQuals.addVolatile(); 6570 VRQuals.addRestrict(); 6571 return VRQuals; 6572 } 6573 6574 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6575 if (!ClassDecl->hasDefinition()) 6576 return VRQuals; 6577 6578 std::pair<CXXRecordDecl::conversion_iterator, 6579 CXXRecordDecl::conversion_iterator> 6580 Conversions = ClassDecl->getVisibleConversionFunctions(); 6581 6582 for (CXXRecordDecl::conversion_iterator 6583 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6584 NamedDecl *D = I.getDecl(); 6585 if (isa<UsingShadowDecl>(D)) 6586 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6587 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6588 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6589 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6590 CanTy = ResTypeRef->getPointeeType(); 6591 // Need to go down the pointer/mempointer chain and add qualifiers 6592 // as see them. 6593 bool done = false; 6594 while (!done) { 6595 if (CanTy.isRestrictQualified()) 6596 VRQuals.addRestrict(); 6597 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6598 CanTy = ResTypePtr->getPointeeType(); 6599 else if (const MemberPointerType *ResTypeMPtr = 6600 CanTy->getAs<MemberPointerType>()) 6601 CanTy = ResTypeMPtr->getPointeeType(); 6602 else 6603 done = true; 6604 if (CanTy.isVolatileQualified()) 6605 VRQuals.addVolatile(); 6606 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6607 return VRQuals; 6608 } 6609 } 6610 } 6611 return VRQuals; 6612} 6613 6614namespace { 6615 6616/// \brief Helper class to manage the addition of builtin operator overload 6617/// candidates. It provides shared state and utility methods used throughout 6618/// the process, as well as a helper method to add each group of builtin 6619/// operator overloads from the standard to a candidate set. 6620class BuiltinOperatorOverloadBuilder { 6621 // Common instance state available to all overload candidate addition methods. 6622 Sema &S; 6623 ArrayRef<Expr *> Args; 6624 Qualifiers VisibleTypeConversionsQuals; 6625 bool HasArithmeticOrEnumeralCandidateType; 6626 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6627 OverloadCandidateSet &CandidateSet; 6628 6629 // Define some constants used to index and iterate over the arithemetic types 6630 // provided via the getArithmeticType() method below. 6631 // The "promoted arithmetic types" are the arithmetic 6632 // types are that preserved by promotion (C++ [over.built]p2). 6633 static const unsigned FirstIntegralType = 3; 6634 static const unsigned LastIntegralType = 20; 6635 static const unsigned FirstPromotedIntegralType = 3, 6636 LastPromotedIntegralType = 11; 6637 static const unsigned FirstPromotedArithmeticType = 0, 6638 LastPromotedArithmeticType = 11; 6639 static const unsigned NumArithmeticTypes = 20; 6640 6641 /// \brief Get the canonical type for a given arithmetic type index. 6642 CanQualType getArithmeticType(unsigned index) { 6643 assert(index < NumArithmeticTypes); 6644 static CanQualType ASTContext::* const 6645 ArithmeticTypes[NumArithmeticTypes] = { 6646 // Start of promoted types. 6647 &ASTContext::FloatTy, 6648 &ASTContext::DoubleTy, 6649 &ASTContext::LongDoubleTy, 6650 6651 // Start of integral types. 6652 &ASTContext::IntTy, 6653 &ASTContext::LongTy, 6654 &ASTContext::LongLongTy, 6655 &ASTContext::Int128Ty, 6656 &ASTContext::UnsignedIntTy, 6657 &ASTContext::UnsignedLongTy, 6658 &ASTContext::UnsignedLongLongTy, 6659 &ASTContext::UnsignedInt128Ty, 6660 // End of promoted types. 6661 6662 &ASTContext::BoolTy, 6663 &ASTContext::CharTy, 6664 &ASTContext::WCharTy, 6665 &ASTContext::Char16Ty, 6666 &ASTContext::Char32Ty, 6667 &ASTContext::SignedCharTy, 6668 &ASTContext::ShortTy, 6669 &ASTContext::UnsignedCharTy, 6670 &ASTContext::UnsignedShortTy, 6671 // End of integral types. 6672 // FIXME: What about complex? What about half? 6673 }; 6674 return S.Context.*ArithmeticTypes[index]; 6675 } 6676 6677 /// \brief Gets the canonical type resulting from the usual arithemetic 6678 /// converions for the given arithmetic types. 6679 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6680 // Accelerator table for performing the usual arithmetic conversions. 6681 // The rules are basically: 6682 // - if either is floating-point, use the wider floating-point 6683 // - if same signedness, use the higher rank 6684 // - if same size, use unsigned of the higher rank 6685 // - use the larger type 6686 // These rules, together with the axiom that higher ranks are 6687 // never smaller, are sufficient to precompute all of these results 6688 // *except* when dealing with signed types of higher rank. 6689 // (we could precompute SLL x UI for all known platforms, but it's 6690 // better not to make any assumptions). 6691 // We assume that int128 has a higher rank than long long on all platforms. 6692 enum PromotedType { 6693 Dep=-1, 6694 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6695 }; 6696 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6697 [LastPromotedArithmeticType] = { 6698/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6699/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6700/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6701/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6702/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6703/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6704/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6705/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6706/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6707/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6708/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6709 }; 6710 6711 assert(L < LastPromotedArithmeticType); 6712 assert(R < LastPromotedArithmeticType); 6713 int Idx = ConversionsTable[L][R]; 6714 6715 // Fast path: the table gives us a concrete answer. 6716 if (Idx != Dep) return getArithmeticType(Idx); 6717 6718 // Slow path: we need to compare widths. 6719 // An invariant is that the signed type has higher rank. 6720 CanQualType LT = getArithmeticType(L), 6721 RT = getArithmeticType(R); 6722 unsigned LW = S.Context.getIntWidth(LT), 6723 RW = S.Context.getIntWidth(RT); 6724 6725 // If they're different widths, use the signed type. 6726 if (LW > RW) return LT; 6727 else if (LW < RW) return RT; 6728 6729 // Otherwise, use the unsigned type of the signed type's rank. 6730 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6731 assert(L == SLL || R == SLL); 6732 return S.Context.UnsignedLongLongTy; 6733 } 6734 6735 /// \brief Helper method to factor out the common pattern of adding overloads 6736 /// for '++' and '--' builtin operators. 6737 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6738 bool HasVolatile, 6739 bool HasRestrict) { 6740 QualType ParamTypes[2] = { 6741 S.Context.getLValueReferenceType(CandidateTy), 6742 S.Context.IntTy 6743 }; 6744 6745 // Non-volatile version. 6746 if (Args.size() == 1) 6747 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6748 else 6749 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6750 6751 // Use a heuristic to reduce number of builtin candidates in the set: 6752 // add volatile version only if there are conversions to a volatile type. 6753 if (HasVolatile) { 6754 ParamTypes[0] = 6755 S.Context.getLValueReferenceType( 6756 S.Context.getVolatileType(CandidateTy)); 6757 if (Args.size() == 1) 6758 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6759 else 6760 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6761 } 6762 6763 // Add restrict version only if there are conversions to a restrict type 6764 // and our candidate type is a non-restrict-qualified pointer. 6765 if (HasRestrict && CandidateTy->isAnyPointerType() && 6766 !CandidateTy.isRestrictQualified()) { 6767 ParamTypes[0] 6768 = S.Context.getLValueReferenceType( 6769 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6770 if (Args.size() == 1) 6771 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6772 else 6773 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6774 6775 if (HasVolatile) { 6776 ParamTypes[0] 6777 = S.Context.getLValueReferenceType( 6778 S.Context.getCVRQualifiedType(CandidateTy, 6779 (Qualifiers::Volatile | 6780 Qualifiers::Restrict))); 6781 if (Args.size() == 1) 6782 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6783 else 6784 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6785 } 6786 } 6787 6788 } 6789 6790public: 6791 BuiltinOperatorOverloadBuilder( 6792 Sema &S, ArrayRef<Expr *> Args, 6793 Qualifiers VisibleTypeConversionsQuals, 6794 bool HasArithmeticOrEnumeralCandidateType, 6795 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6796 OverloadCandidateSet &CandidateSet) 6797 : S(S), Args(Args), 6798 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6799 HasArithmeticOrEnumeralCandidateType( 6800 HasArithmeticOrEnumeralCandidateType), 6801 CandidateTypes(CandidateTypes), 6802 CandidateSet(CandidateSet) { 6803 // Validate some of our static helper constants in debug builds. 6804 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6805 "Invalid first promoted integral type"); 6806 assert(getArithmeticType(LastPromotedIntegralType - 1) 6807 == S.Context.UnsignedInt128Ty && 6808 "Invalid last promoted integral type"); 6809 assert(getArithmeticType(FirstPromotedArithmeticType) 6810 == S.Context.FloatTy && 6811 "Invalid first promoted arithmetic type"); 6812 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6813 == S.Context.UnsignedInt128Ty && 6814 "Invalid last promoted arithmetic type"); 6815 } 6816 6817 // C++ [over.built]p3: 6818 // 6819 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6820 // is either volatile or empty, there exist candidate operator 6821 // functions of the form 6822 // 6823 // VQ T& operator++(VQ T&); 6824 // T operator++(VQ T&, int); 6825 // 6826 // C++ [over.built]p4: 6827 // 6828 // For every pair (T, VQ), where T is an arithmetic type other 6829 // than bool, and VQ is either volatile or empty, there exist 6830 // candidate operator functions of the form 6831 // 6832 // VQ T& operator--(VQ T&); 6833 // T operator--(VQ T&, int); 6834 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6835 if (!HasArithmeticOrEnumeralCandidateType) 6836 return; 6837 6838 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6839 Arith < NumArithmeticTypes; ++Arith) { 6840 addPlusPlusMinusMinusStyleOverloads( 6841 getArithmeticType(Arith), 6842 VisibleTypeConversionsQuals.hasVolatile(), 6843 VisibleTypeConversionsQuals.hasRestrict()); 6844 } 6845 } 6846 6847 // C++ [over.built]p5: 6848 // 6849 // For every pair (T, VQ), where T is a cv-qualified or 6850 // cv-unqualified object type, and VQ is either volatile or 6851 // empty, there exist candidate operator functions of the form 6852 // 6853 // T*VQ& operator++(T*VQ&); 6854 // T*VQ& operator--(T*VQ&); 6855 // T* operator++(T*VQ&, int); 6856 // T* operator--(T*VQ&, int); 6857 void addPlusPlusMinusMinusPointerOverloads() { 6858 for (BuiltinCandidateTypeSet::iterator 6859 Ptr = CandidateTypes[0].pointer_begin(), 6860 PtrEnd = CandidateTypes[0].pointer_end(); 6861 Ptr != PtrEnd; ++Ptr) { 6862 // Skip pointer types that aren't pointers to object types. 6863 if (!(*Ptr)->getPointeeType()->isObjectType()) 6864 continue; 6865 6866 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6867 (!(*Ptr).isVolatileQualified() && 6868 VisibleTypeConversionsQuals.hasVolatile()), 6869 (!(*Ptr).isRestrictQualified() && 6870 VisibleTypeConversionsQuals.hasRestrict())); 6871 } 6872 } 6873 6874 // C++ [over.built]p6: 6875 // For every cv-qualified or cv-unqualified object type T, there 6876 // exist candidate operator functions of the form 6877 // 6878 // T& operator*(T*); 6879 // 6880 // C++ [over.built]p7: 6881 // For every function type T that does not have cv-qualifiers or a 6882 // ref-qualifier, there exist candidate operator functions of the form 6883 // T& operator*(T*); 6884 void addUnaryStarPointerOverloads() { 6885 for (BuiltinCandidateTypeSet::iterator 6886 Ptr = CandidateTypes[0].pointer_begin(), 6887 PtrEnd = CandidateTypes[0].pointer_end(); 6888 Ptr != PtrEnd; ++Ptr) { 6889 QualType ParamTy = *Ptr; 6890 QualType PointeeTy = ParamTy->getPointeeType(); 6891 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6892 continue; 6893 6894 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6895 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6896 continue; 6897 6898 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6899 &ParamTy, Args, CandidateSet); 6900 } 6901 } 6902 6903 // C++ [over.built]p9: 6904 // For every promoted arithmetic type T, there exist candidate 6905 // operator functions of the form 6906 // 6907 // T operator+(T); 6908 // T operator-(T); 6909 void addUnaryPlusOrMinusArithmeticOverloads() { 6910 if (!HasArithmeticOrEnumeralCandidateType) 6911 return; 6912 6913 for (unsigned Arith = FirstPromotedArithmeticType; 6914 Arith < LastPromotedArithmeticType; ++Arith) { 6915 QualType ArithTy = getArithmeticType(Arith); 6916 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 6917 } 6918 6919 // Extension: We also add these operators for vector types. 6920 for (BuiltinCandidateTypeSet::iterator 6921 Vec = CandidateTypes[0].vector_begin(), 6922 VecEnd = CandidateTypes[0].vector_end(); 6923 Vec != VecEnd; ++Vec) { 6924 QualType VecTy = *Vec; 6925 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 6926 } 6927 } 6928 6929 // C++ [over.built]p8: 6930 // For every type T, there exist candidate operator functions of 6931 // the form 6932 // 6933 // T* operator+(T*); 6934 void addUnaryPlusPointerOverloads() { 6935 for (BuiltinCandidateTypeSet::iterator 6936 Ptr = CandidateTypes[0].pointer_begin(), 6937 PtrEnd = CandidateTypes[0].pointer_end(); 6938 Ptr != PtrEnd; ++Ptr) { 6939 QualType ParamTy = *Ptr; 6940 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 6941 } 6942 } 6943 6944 // C++ [over.built]p10: 6945 // For every promoted integral type T, there exist candidate 6946 // operator functions of the form 6947 // 6948 // T operator~(T); 6949 void addUnaryTildePromotedIntegralOverloads() { 6950 if (!HasArithmeticOrEnumeralCandidateType) 6951 return; 6952 6953 for (unsigned Int = FirstPromotedIntegralType; 6954 Int < LastPromotedIntegralType; ++Int) { 6955 QualType IntTy = getArithmeticType(Int); 6956 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 6957 } 6958 6959 // Extension: We also add this operator for vector types. 6960 for (BuiltinCandidateTypeSet::iterator 6961 Vec = CandidateTypes[0].vector_begin(), 6962 VecEnd = CandidateTypes[0].vector_end(); 6963 Vec != VecEnd; ++Vec) { 6964 QualType VecTy = *Vec; 6965 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 6966 } 6967 } 6968 6969 // C++ [over.match.oper]p16: 6970 // For every pointer to member type T, there exist candidate operator 6971 // functions of the form 6972 // 6973 // bool operator==(T,T); 6974 // bool operator!=(T,T); 6975 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6976 /// Set of (canonical) types that we've already handled. 6977 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6978 6979 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6980 for (BuiltinCandidateTypeSet::iterator 6981 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6982 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6983 MemPtr != MemPtrEnd; 6984 ++MemPtr) { 6985 // Don't add the same builtin candidate twice. 6986 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6987 continue; 6988 6989 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6990 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 6991 } 6992 } 6993 } 6994 6995 // C++ [over.built]p15: 6996 // 6997 // For every T, where T is an enumeration type, a pointer type, or 6998 // std::nullptr_t, there exist candidate operator functions of the form 6999 // 7000 // bool operator<(T, T); 7001 // bool operator>(T, T); 7002 // bool operator<=(T, T); 7003 // bool operator>=(T, T); 7004 // bool operator==(T, T); 7005 // bool operator!=(T, T); 7006 void addRelationalPointerOrEnumeralOverloads() { 7007 // C++ [over.match.oper]p3: 7008 // [...]the built-in candidates include all of the candidate operator 7009 // functions defined in 13.6 that, compared to the given operator, [...] 7010 // do not have the same parameter-type-list as any non-template non-member 7011 // candidate. 7012 // 7013 // Note that in practice, this only affects enumeration types because there 7014 // aren't any built-in candidates of record type, and a user-defined operator 7015 // must have an operand of record or enumeration type. Also, the only other 7016 // overloaded operator with enumeration arguments, operator=, 7017 // cannot be overloaded for enumeration types, so this is the only place 7018 // where we must suppress candidates like this. 7019 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7020 UserDefinedBinaryOperators; 7021 7022 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7023 if (CandidateTypes[ArgIdx].enumeration_begin() != 7024 CandidateTypes[ArgIdx].enumeration_end()) { 7025 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7026 CEnd = CandidateSet.end(); 7027 C != CEnd; ++C) { 7028 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7029 continue; 7030 7031 if (C->Function->isFunctionTemplateSpecialization()) 7032 continue; 7033 7034 QualType FirstParamType = 7035 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7036 QualType SecondParamType = 7037 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7038 7039 // Skip if either parameter isn't of enumeral type. 7040 if (!FirstParamType->isEnumeralType() || 7041 !SecondParamType->isEnumeralType()) 7042 continue; 7043 7044 // Add this operator to the set of known user-defined operators. 7045 UserDefinedBinaryOperators.insert( 7046 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7047 S.Context.getCanonicalType(SecondParamType))); 7048 } 7049 } 7050 } 7051 7052 /// Set of (canonical) types that we've already handled. 7053 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7054 7055 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7056 for (BuiltinCandidateTypeSet::iterator 7057 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7058 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7059 Ptr != PtrEnd; ++Ptr) { 7060 // Don't add the same builtin candidate twice. 7061 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7062 continue; 7063 7064 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7065 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7066 } 7067 for (BuiltinCandidateTypeSet::iterator 7068 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7069 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7070 Enum != EnumEnd; ++Enum) { 7071 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7072 7073 // Don't add the same builtin candidate twice, or if a user defined 7074 // candidate exists. 7075 if (!AddedTypes.insert(CanonType) || 7076 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7077 CanonType))) 7078 continue; 7079 7080 QualType ParamTypes[2] = { *Enum, *Enum }; 7081 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7082 } 7083 7084 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7085 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7086 if (AddedTypes.insert(NullPtrTy) && 7087 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7088 NullPtrTy))) { 7089 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7090 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7091 CandidateSet); 7092 } 7093 } 7094 } 7095 } 7096 7097 // C++ [over.built]p13: 7098 // 7099 // For every cv-qualified or cv-unqualified object type T 7100 // there exist candidate operator functions of the form 7101 // 7102 // T* operator+(T*, ptrdiff_t); 7103 // T& operator[](T*, ptrdiff_t); [BELOW] 7104 // T* operator-(T*, ptrdiff_t); 7105 // T* operator+(ptrdiff_t, T*); 7106 // T& operator[](ptrdiff_t, T*); [BELOW] 7107 // 7108 // C++ [over.built]p14: 7109 // 7110 // For every T, where T is a pointer to object type, there 7111 // exist candidate operator functions of the form 7112 // 7113 // ptrdiff_t operator-(T, T); 7114 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7115 /// Set of (canonical) types that we've already handled. 7116 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7117 7118 for (int Arg = 0; Arg < 2; ++Arg) { 7119 QualType AsymetricParamTypes[2] = { 7120 S.Context.getPointerDiffType(), 7121 S.Context.getPointerDiffType(), 7122 }; 7123 for (BuiltinCandidateTypeSet::iterator 7124 Ptr = CandidateTypes[Arg].pointer_begin(), 7125 PtrEnd = CandidateTypes[Arg].pointer_end(); 7126 Ptr != PtrEnd; ++Ptr) { 7127 QualType PointeeTy = (*Ptr)->getPointeeType(); 7128 if (!PointeeTy->isObjectType()) 7129 continue; 7130 7131 AsymetricParamTypes[Arg] = *Ptr; 7132 if (Arg == 0 || Op == OO_Plus) { 7133 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7134 // T* operator+(ptrdiff_t, T*); 7135 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7136 } 7137 if (Op == OO_Minus) { 7138 // ptrdiff_t operator-(T, T); 7139 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7140 continue; 7141 7142 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7143 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7144 Args, CandidateSet); 7145 } 7146 } 7147 } 7148 } 7149 7150 // C++ [over.built]p12: 7151 // 7152 // For every pair of promoted arithmetic types L and R, there 7153 // exist candidate operator functions of the form 7154 // 7155 // LR operator*(L, R); 7156 // LR operator/(L, R); 7157 // LR operator+(L, R); 7158 // LR operator-(L, R); 7159 // bool operator<(L, R); 7160 // bool operator>(L, R); 7161 // bool operator<=(L, R); 7162 // bool operator>=(L, R); 7163 // bool operator==(L, R); 7164 // bool operator!=(L, R); 7165 // 7166 // where LR is the result of the usual arithmetic conversions 7167 // between types L and R. 7168 // 7169 // C++ [over.built]p24: 7170 // 7171 // For every pair of promoted arithmetic types L and R, there exist 7172 // candidate operator functions of the form 7173 // 7174 // LR operator?(bool, L, R); 7175 // 7176 // where LR is the result of the usual arithmetic conversions 7177 // between types L and R. 7178 // Our candidates ignore the first parameter. 7179 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7180 if (!HasArithmeticOrEnumeralCandidateType) 7181 return; 7182 7183 for (unsigned Left = FirstPromotedArithmeticType; 7184 Left < LastPromotedArithmeticType; ++Left) { 7185 for (unsigned Right = FirstPromotedArithmeticType; 7186 Right < LastPromotedArithmeticType; ++Right) { 7187 QualType LandR[2] = { getArithmeticType(Left), 7188 getArithmeticType(Right) }; 7189 QualType Result = 7190 isComparison ? S.Context.BoolTy 7191 : getUsualArithmeticConversions(Left, Right); 7192 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7193 } 7194 } 7195 7196 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7197 // conditional operator for vector types. 7198 for (BuiltinCandidateTypeSet::iterator 7199 Vec1 = CandidateTypes[0].vector_begin(), 7200 Vec1End = CandidateTypes[0].vector_end(); 7201 Vec1 != Vec1End; ++Vec1) { 7202 for (BuiltinCandidateTypeSet::iterator 7203 Vec2 = CandidateTypes[1].vector_begin(), 7204 Vec2End = CandidateTypes[1].vector_end(); 7205 Vec2 != Vec2End; ++Vec2) { 7206 QualType LandR[2] = { *Vec1, *Vec2 }; 7207 QualType Result = S.Context.BoolTy; 7208 if (!isComparison) { 7209 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7210 Result = *Vec1; 7211 else 7212 Result = *Vec2; 7213 } 7214 7215 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7216 } 7217 } 7218 } 7219 7220 // C++ [over.built]p17: 7221 // 7222 // For every pair of promoted integral types L and R, there 7223 // exist candidate operator functions of the form 7224 // 7225 // LR operator%(L, R); 7226 // LR operator&(L, R); 7227 // LR operator^(L, R); 7228 // LR operator|(L, R); 7229 // L operator<<(L, R); 7230 // L operator>>(L, R); 7231 // 7232 // where LR is the result of the usual arithmetic conversions 7233 // between types L and R. 7234 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7235 if (!HasArithmeticOrEnumeralCandidateType) 7236 return; 7237 7238 for (unsigned Left = FirstPromotedIntegralType; 7239 Left < LastPromotedIntegralType; ++Left) { 7240 for (unsigned Right = FirstPromotedIntegralType; 7241 Right < LastPromotedIntegralType; ++Right) { 7242 QualType LandR[2] = { getArithmeticType(Left), 7243 getArithmeticType(Right) }; 7244 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7245 ? LandR[0] 7246 : getUsualArithmeticConversions(Left, Right); 7247 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7248 } 7249 } 7250 } 7251 7252 // C++ [over.built]p20: 7253 // 7254 // For every pair (T, VQ), where T is an enumeration or 7255 // pointer to member type and VQ is either volatile or 7256 // empty, there exist candidate operator functions of the form 7257 // 7258 // VQ T& operator=(VQ T&, T); 7259 void addAssignmentMemberPointerOrEnumeralOverloads() { 7260 /// Set of (canonical) types that we've already handled. 7261 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7262 7263 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7264 for (BuiltinCandidateTypeSet::iterator 7265 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7266 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7267 Enum != EnumEnd; ++Enum) { 7268 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7269 continue; 7270 7271 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7272 } 7273 7274 for (BuiltinCandidateTypeSet::iterator 7275 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7276 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7277 MemPtr != MemPtrEnd; ++MemPtr) { 7278 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7279 continue; 7280 7281 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7282 } 7283 } 7284 } 7285 7286 // C++ [over.built]p19: 7287 // 7288 // For every pair (T, VQ), where T is any type and VQ is either 7289 // volatile or empty, there exist candidate operator functions 7290 // of the form 7291 // 7292 // T*VQ& operator=(T*VQ&, T*); 7293 // 7294 // C++ [over.built]p21: 7295 // 7296 // For every pair (T, VQ), where T is a cv-qualified or 7297 // cv-unqualified object type and VQ is either volatile or 7298 // empty, there exist candidate operator functions of the form 7299 // 7300 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7301 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7302 void addAssignmentPointerOverloads(bool isEqualOp) { 7303 /// Set of (canonical) types that we've already handled. 7304 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7305 7306 for (BuiltinCandidateTypeSet::iterator 7307 Ptr = CandidateTypes[0].pointer_begin(), 7308 PtrEnd = CandidateTypes[0].pointer_end(); 7309 Ptr != PtrEnd; ++Ptr) { 7310 // If this is operator=, keep track of the builtin candidates we added. 7311 if (isEqualOp) 7312 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7313 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7314 continue; 7315 7316 // non-volatile version 7317 QualType ParamTypes[2] = { 7318 S.Context.getLValueReferenceType(*Ptr), 7319 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7320 }; 7321 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7322 /*IsAssigmentOperator=*/ isEqualOp); 7323 7324 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7325 VisibleTypeConversionsQuals.hasVolatile(); 7326 if (NeedVolatile) { 7327 // volatile version 7328 ParamTypes[0] = 7329 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7330 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7331 /*IsAssigmentOperator=*/isEqualOp); 7332 } 7333 7334 if (!(*Ptr).isRestrictQualified() && 7335 VisibleTypeConversionsQuals.hasRestrict()) { 7336 // restrict version 7337 ParamTypes[0] 7338 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7339 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7340 /*IsAssigmentOperator=*/isEqualOp); 7341 7342 if (NeedVolatile) { 7343 // volatile restrict version 7344 ParamTypes[0] 7345 = S.Context.getLValueReferenceType( 7346 S.Context.getCVRQualifiedType(*Ptr, 7347 (Qualifiers::Volatile | 7348 Qualifiers::Restrict))); 7349 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7350 /*IsAssigmentOperator=*/isEqualOp); 7351 } 7352 } 7353 } 7354 7355 if (isEqualOp) { 7356 for (BuiltinCandidateTypeSet::iterator 7357 Ptr = CandidateTypes[1].pointer_begin(), 7358 PtrEnd = CandidateTypes[1].pointer_end(); 7359 Ptr != PtrEnd; ++Ptr) { 7360 // Make sure we don't add the same candidate twice. 7361 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7362 continue; 7363 7364 QualType ParamTypes[2] = { 7365 S.Context.getLValueReferenceType(*Ptr), 7366 *Ptr, 7367 }; 7368 7369 // non-volatile version 7370 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7371 /*IsAssigmentOperator=*/true); 7372 7373 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7374 VisibleTypeConversionsQuals.hasVolatile(); 7375 if (NeedVolatile) { 7376 // volatile version 7377 ParamTypes[0] = 7378 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7379 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7380 /*IsAssigmentOperator=*/true); 7381 } 7382 7383 if (!(*Ptr).isRestrictQualified() && 7384 VisibleTypeConversionsQuals.hasRestrict()) { 7385 // restrict version 7386 ParamTypes[0] 7387 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7388 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7389 /*IsAssigmentOperator=*/true); 7390 7391 if (NeedVolatile) { 7392 // volatile restrict version 7393 ParamTypes[0] 7394 = S.Context.getLValueReferenceType( 7395 S.Context.getCVRQualifiedType(*Ptr, 7396 (Qualifiers::Volatile | 7397 Qualifiers::Restrict))); 7398 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7399 /*IsAssigmentOperator=*/true); 7400 } 7401 } 7402 } 7403 } 7404 } 7405 7406 // C++ [over.built]p18: 7407 // 7408 // For every triple (L, VQ, R), where L is an arithmetic type, 7409 // VQ is either volatile or empty, and R is a promoted 7410 // arithmetic type, there exist candidate operator functions of 7411 // the form 7412 // 7413 // VQ L& operator=(VQ L&, R); 7414 // VQ L& operator*=(VQ L&, R); 7415 // VQ L& operator/=(VQ L&, R); 7416 // VQ L& operator+=(VQ L&, R); 7417 // VQ L& operator-=(VQ L&, R); 7418 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7419 if (!HasArithmeticOrEnumeralCandidateType) 7420 return; 7421 7422 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7423 for (unsigned Right = FirstPromotedArithmeticType; 7424 Right < LastPromotedArithmeticType; ++Right) { 7425 QualType ParamTypes[2]; 7426 ParamTypes[1] = getArithmeticType(Right); 7427 7428 // Add this built-in operator as a candidate (VQ is empty). 7429 ParamTypes[0] = 7430 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7431 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7432 /*IsAssigmentOperator=*/isEqualOp); 7433 7434 // Add this built-in operator as a candidate (VQ is 'volatile'). 7435 if (VisibleTypeConversionsQuals.hasVolatile()) { 7436 ParamTypes[0] = 7437 S.Context.getVolatileType(getArithmeticType(Left)); 7438 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7439 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7440 /*IsAssigmentOperator=*/isEqualOp); 7441 } 7442 } 7443 } 7444 7445 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7446 for (BuiltinCandidateTypeSet::iterator 7447 Vec1 = CandidateTypes[0].vector_begin(), 7448 Vec1End = CandidateTypes[0].vector_end(); 7449 Vec1 != Vec1End; ++Vec1) { 7450 for (BuiltinCandidateTypeSet::iterator 7451 Vec2 = CandidateTypes[1].vector_begin(), 7452 Vec2End = CandidateTypes[1].vector_end(); 7453 Vec2 != Vec2End; ++Vec2) { 7454 QualType ParamTypes[2]; 7455 ParamTypes[1] = *Vec2; 7456 // Add this built-in operator as a candidate (VQ is empty). 7457 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7458 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7459 /*IsAssigmentOperator=*/isEqualOp); 7460 7461 // Add this built-in operator as a candidate (VQ is 'volatile'). 7462 if (VisibleTypeConversionsQuals.hasVolatile()) { 7463 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7464 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7465 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7466 /*IsAssigmentOperator=*/isEqualOp); 7467 } 7468 } 7469 } 7470 } 7471 7472 // C++ [over.built]p22: 7473 // 7474 // For every triple (L, VQ, R), where L is an integral type, VQ 7475 // is either volatile or empty, and R is a promoted integral 7476 // type, there exist candidate operator functions of the form 7477 // 7478 // VQ L& operator%=(VQ L&, R); 7479 // VQ L& operator<<=(VQ L&, R); 7480 // VQ L& operator>>=(VQ L&, R); 7481 // VQ L& operator&=(VQ L&, R); 7482 // VQ L& operator^=(VQ L&, R); 7483 // VQ L& operator|=(VQ L&, R); 7484 void addAssignmentIntegralOverloads() { 7485 if (!HasArithmeticOrEnumeralCandidateType) 7486 return; 7487 7488 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7489 for (unsigned Right = FirstPromotedIntegralType; 7490 Right < LastPromotedIntegralType; ++Right) { 7491 QualType ParamTypes[2]; 7492 ParamTypes[1] = getArithmeticType(Right); 7493 7494 // Add this built-in operator as a candidate (VQ is empty). 7495 ParamTypes[0] = 7496 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7497 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7498 if (VisibleTypeConversionsQuals.hasVolatile()) { 7499 // Add this built-in operator as a candidate (VQ is 'volatile'). 7500 ParamTypes[0] = getArithmeticType(Left); 7501 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7502 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7503 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7504 } 7505 } 7506 } 7507 } 7508 7509 // C++ [over.operator]p23: 7510 // 7511 // There also exist candidate operator functions of the form 7512 // 7513 // bool operator!(bool); 7514 // bool operator&&(bool, bool); 7515 // bool operator||(bool, bool); 7516 void addExclaimOverload() { 7517 QualType ParamTy = S.Context.BoolTy; 7518 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7519 /*IsAssignmentOperator=*/false, 7520 /*NumContextualBoolArguments=*/1); 7521 } 7522 void addAmpAmpOrPipePipeOverload() { 7523 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7524 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7525 /*IsAssignmentOperator=*/false, 7526 /*NumContextualBoolArguments=*/2); 7527 } 7528 7529 // C++ [over.built]p13: 7530 // 7531 // For every cv-qualified or cv-unqualified object type T there 7532 // exist candidate operator functions of the form 7533 // 7534 // T* operator+(T*, ptrdiff_t); [ABOVE] 7535 // T& operator[](T*, ptrdiff_t); 7536 // T* operator-(T*, ptrdiff_t); [ABOVE] 7537 // T* operator+(ptrdiff_t, T*); [ABOVE] 7538 // T& operator[](ptrdiff_t, T*); 7539 void addSubscriptOverloads() { 7540 for (BuiltinCandidateTypeSet::iterator 7541 Ptr = CandidateTypes[0].pointer_begin(), 7542 PtrEnd = CandidateTypes[0].pointer_end(); 7543 Ptr != PtrEnd; ++Ptr) { 7544 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7545 QualType PointeeType = (*Ptr)->getPointeeType(); 7546 if (!PointeeType->isObjectType()) 7547 continue; 7548 7549 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7550 7551 // T& operator[](T*, ptrdiff_t) 7552 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7553 } 7554 7555 for (BuiltinCandidateTypeSet::iterator 7556 Ptr = CandidateTypes[1].pointer_begin(), 7557 PtrEnd = CandidateTypes[1].pointer_end(); 7558 Ptr != PtrEnd; ++Ptr) { 7559 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7560 QualType PointeeType = (*Ptr)->getPointeeType(); 7561 if (!PointeeType->isObjectType()) 7562 continue; 7563 7564 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7565 7566 // T& operator[](ptrdiff_t, T*) 7567 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7568 } 7569 } 7570 7571 // C++ [over.built]p11: 7572 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7573 // C1 is the same type as C2 or is a derived class of C2, T is an object 7574 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7575 // there exist candidate operator functions of the form 7576 // 7577 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7578 // 7579 // where CV12 is the union of CV1 and CV2. 7580 void addArrowStarOverloads() { 7581 for (BuiltinCandidateTypeSet::iterator 7582 Ptr = CandidateTypes[0].pointer_begin(), 7583 PtrEnd = CandidateTypes[0].pointer_end(); 7584 Ptr != PtrEnd; ++Ptr) { 7585 QualType C1Ty = (*Ptr); 7586 QualType C1; 7587 QualifierCollector Q1; 7588 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7589 if (!isa<RecordType>(C1)) 7590 continue; 7591 // heuristic to reduce number of builtin candidates in the set. 7592 // Add volatile/restrict version only if there are conversions to a 7593 // volatile/restrict type. 7594 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7595 continue; 7596 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7597 continue; 7598 for (BuiltinCandidateTypeSet::iterator 7599 MemPtr = CandidateTypes[1].member_pointer_begin(), 7600 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7601 MemPtr != MemPtrEnd; ++MemPtr) { 7602 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7603 QualType C2 = QualType(mptr->getClass(), 0); 7604 C2 = C2.getUnqualifiedType(); 7605 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7606 break; 7607 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7608 // build CV12 T& 7609 QualType T = mptr->getPointeeType(); 7610 if (!VisibleTypeConversionsQuals.hasVolatile() && 7611 T.isVolatileQualified()) 7612 continue; 7613 if (!VisibleTypeConversionsQuals.hasRestrict() && 7614 T.isRestrictQualified()) 7615 continue; 7616 T = Q1.apply(S.Context, T); 7617 QualType ResultTy = S.Context.getLValueReferenceType(T); 7618 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7619 } 7620 } 7621 } 7622 7623 // Note that we don't consider the first argument, since it has been 7624 // contextually converted to bool long ago. The candidates below are 7625 // therefore added as binary. 7626 // 7627 // C++ [over.built]p25: 7628 // For every type T, where T is a pointer, pointer-to-member, or scoped 7629 // enumeration type, there exist candidate operator functions of the form 7630 // 7631 // T operator?(bool, T, T); 7632 // 7633 void addConditionalOperatorOverloads() { 7634 /// Set of (canonical) types that we've already handled. 7635 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7636 7637 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7638 for (BuiltinCandidateTypeSet::iterator 7639 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7640 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7641 Ptr != PtrEnd; ++Ptr) { 7642 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7643 continue; 7644 7645 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7646 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 7647 } 7648 7649 for (BuiltinCandidateTypeSet::iterator 7650 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7651 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7652 MemPtr != MemPtrEnd; ++MemPtr) { 7653 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7654 continue; 7655 7656 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7657 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 7658 } 7659 7660 if (S.getLangOpts().CPlusPlus11) { 7661 for (BuiltinCandidateTypeSet::iterator 7662 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7663 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7664 Enum != EnumEnd; ++Enum) { 7665 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7666 continue; 7667 7668 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7669 continue; 7670 7671 QualType ParamTypes[2] = { *Enum, *Enum }; 7672 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 7673 } 7674 } 7675 } 7676 } 7677}; 7678 7679} // end anonymous namespace 7680 7681/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7682/// operator overloads to the candidate set (C++ [over.built]), based 7683/// on the operator @p Op and the arguments given. For example, if the 7684/// operator is a binary '+', this routine might add "int 7685/// operator+(int, int)" to cover integer addition. 7686void 7687Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7688 SourceLocation OpLoc, 7689 llvm::ArrayRef<Expr *> Args, 7690 OverloadCandidateSet& CandidateSet) { 7691 // Find all of the types that the arguments can convert to, but only 7692 // if the operator we're looking at has built-in operator candidates 7693 // that make use of these types. Also record whether we encounter non-record 7694 // candidate types or either arithmetic or enumeral candidate types. 7695 Qualifiers VisibleTypeConversionsQuals; 7696 VisibleTypeConversionsQuals.addConst(); 7697 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7698 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7699 7700 bool HasNonRecordCandidateType = false; 7701 bool HasArithmeticOrEnumeralCandidateType = false; 7702 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7703 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7704 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7705 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7706 OpLoc, 7707 true, 7708 (Op == OO_Exclaim || 7709 Op == OO_AmpAmp || 7710 Op == OO_PipePipe), 7711 VisibleTypeConversionsQuals); 7712 HasNonRecordCandidateType = HasNonRecordCandidateType || 7713 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7714 HasArithmeticOrEnumeralCandidateType = 7715 HasArithmeticOrEnumeralCandidateType || 7716 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7717 } 7718 7719 // Exit early when no non-record types have been added to the candidate set 7720 // for any of the arguments to the operator. 7721 // 7722 // We can't exit early for !, ||, or &&, since there we have always have 7723 // 'bool' overloads. 7724 if (!HasNonRecordCandidateType && 7725 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7726 return; 7727 7728 // Setup an object to manage the common state for building overloads. 7729 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 7730 VisibleTypeConversionsQuals, 7731 HasArithmeticOrEnumeralCandidateType, 7732 CandidateTypes, CandidateSet); 7733 7734 // Dispatch over the operation to add in only those overloads which apply. 7735 switch (Op) { 7736 case OO_None: 7737 case NUM_OVERLOADED_OPERATORS: 7738 llvm_unreachable("Expected an overloaded operator"); 7739 7740 case OO_New: 7741 case OO_Delete: 7742 case OO_Array_New: 7743 case OO_Array_Delete: 7744 case OO_Call: 7745 llvm_unreachable( 7746 "Special operators don't use AddBuiltinOperatorCandidates"); 7747 7748 case OO_Comma: 7749 case OO_Arrow: 7750 // C++ [over.match.oper]p3: 7751 // -- For the operator ',', the unary operator '&', or the 7752 // operator '->', the built-in candidates set is empty. 7753 break; 7754 7755 case OO_Plus: // '+' is either unary or binary 7756 if (Args.size() == 1) 7757 OpBuilder.addUnaryPlusPointerOverloads(); 7758 // Fall through. 7759 7760 case OO_Minus: // '-' is either unary or binary 7761 if (Args.size() == 1) { 7762 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7763 } else { 7764 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7765 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7766 } 7767 break; 7768 7769 case OO_Star: // '*' is either unary or binary 7770 if (Args.size() == 1) 7771 OpBuilder.addUnaryStarPointerOverloads(); 7772 else 7773 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7774 break; 7775 7776 case OO_Slash: 7777 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7778 break; 7779 7780 case OO_PlusPlus: 7781 case OO_MinusMinus: 7782 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7783 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7784 break; 7785 7786 case OO_EqualEqual: 7787 case OO_ExclaimEqual: 7788 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7789 // Fall through. 7790 7791 case OO_Less: 7792 case OO_Greater: 7793 case OO_LessEqual: 7794 case OO_GreaterEqual: 7795 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7796 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7797 break; 7798 7799 case OO_Percent: 7800 case OO_Caret: 7801 case OO_Pipe: 7802 case OO_LessLess: 7803 case OO_GreaterGreater: 7804 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7805 break; 7806 7807 case OO_Amp: // '&' is either unary or binary 7808 if (Args.size() == 1) 7809 // C++ [over.match.oper]p3: 7810 // -- For the operator ',', the unary operator '&', or the 7811 // operator '->', the built-in candidates set is empty. 7812 break; 7813 7814 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7815 break; 7816 7817 case OO_Tilde: 7818 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7819 break; 7820 7821 case OO_Equal: 7822 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7823 // Fall through. 7824 7825 case OO_PlusEqual: 7826 case OO_MinusEqual: 7827 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7828 // Fall through. 7829 7830 case OO_StarEqual: 7831 case OO_SlashEqual: 7832 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7833 break; 7834 7835 case OO_PercentEqual: 7836 case OO_LessLessEqual: 7837 case OO_GreaterGreaterEqual: 7838 case OO_AmpEqual: 7839 case OO_CaretEqual: 7840 case OO_PipeEqual: 7841 OpBuilder.addAssignmentIntegralOverloads(); 7842 break; 7843 7844 case OO_Exclaim: 7845 OpBuilder.addExclaimOverload(); 7846 break; 7847 7848 case OO_AmpAmp: 7849 case OO_PipePipe: 7850 OpBuilder.addAmpAmpOrPipePipeOverload(); 7851 break; 7852 7853 case OO_Subscript: 7854 OpBuilder.addSubscriptOverloads(); 7855 break; 7856 7857 case OO_ArrowStar: 7858 OpBuilder.addArrowStarOverloads(); 7859 break; 7860 7861 case OO_Conditional: 7862 OpBuilder.addConditionalOperatorOverloads(); 7863 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7864 break; 7865 } 7866} 7867 7868/// \brief Add function candidates found via argument-dependent lookup 7869/// to the set of overloading candidates. 7870/// 7871/// This routine performs argument-dependent name lookup based on the 7872/// given function name (which may also be an operator name) and adds 7873/// all of the overload candidates found by ADL to the overload 7874/// candidate set (C++ [basic.lookup.argdep]). 7875void 7876Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7877 bool Operator, SourceLocation Loc, 7878 ArrayRef<Expr *> Args, 7879 TemplateArgumentListInfo *ExplicitTemplateArgs, 7880 OverloadCandidateSet& CandidateSet, 7881 bool PartialOverloading) { 7882 ADLResult Fns; 7883 7884 // FIXME: This approach for uniquing ADL results (and removing 7885 // redundant candidates from the set) relies on pointer-equality, 7886 // which means we need to key off the canonical decl. However, 7887 // always going back to the canonical decl might not get us the 7888 // right set of default arguments. What default arguments are 7889 // we supposed to consider on ADL candidates, anyway? 7890 7891 // FIXME: Pass in the explicit template arguments? 7892 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 7893 7894 // Erase all of the candidates we already knew about. 7895 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7896 CandEnd = CandidateSet.end(); 7897 Cand != CandEnd; ++Cand) 7898 if (Cand->Function) { 7899 Fns.erase(Cand->Function); 7900 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7901 Fns.erase(FunTmpl); 7902 } 7903 7904 // For each of the ADL candidates we found, add it to the overload 7905 // set. 7906 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7907 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7908 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7909 if (ExplicitTemplateArgs) 7910 continue; 7911 7912 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7913 PartialOverloading); 7914 } else 7915 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7916 FoundDecl, ExplicitTemplateArgs, 7917 Args, CandidateSet); 7918 } 7919} 7920 7921/// isBetterOverloadCandidate - Determines whether the first overload 7922/// candidate is a better candidate than the second (C++ 13.3.3p1). 7923bool 7924isBetterOverloadCandidate(Sema &S, 7925 const OverloadCandidate &Cand1, 7926 const OverloadCandidate &Cand2, 7927 SourceLocation Loc, 7928 bool UserDefinedConversion) { 7929 // Define viable functions to be better candidates than non-viable 7930 // functions. 7931 if (!Cand2.Viable) 7932 return Cand1.Viable; 7933 else if (!Cand1.Viable) 7934 return false; 7935 7936 // C++ [over.match.best]p1: 7937 // 7938 // -- if F is a static member function, ICS1(F) is defined such 7939 // that ICS1(F) is neither better nor worse than ICS1(G) for 7940 // any function G, and, symmetrically, ICS1(G) is neither 7941 // better nor worse than ICS1(F). 7942 unsigned StartArg = 0; 7943 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7944 StartArg = 1; 7945 7946 // C++ [over.match.best]p1: 7947 // A viable function F1 is defined to be a better function than another 7948 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7949 // conversion sequence than ICSi(F2), and then... 7950 unsigned NumArgs = Cand1.NumConversions; 7951 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7952 bool HasBetterConversion = false; 7953 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7954 switch (CompareImplicitConversionSequences(S, 7955 Cand1.Conversions[ArgIdx], 7956 Cand2.Conversions[ArgIdx])) { 7957 case ImplicitConversionSequence::Better: 7958 // Cand1 has a better conversion sequence. 7959 HasBetterConversion = true; 7960 break; 7961 7962 case ImplicitConversionSequence::Worse: 7963 // Cand1 can't be better than Cand2. 7964 return false; 7965 7966 case ImplicitConversionSequence::Indistinguishable: 7967 // Do nothing. 7968 break; 7969 } 7970 } 7971 7972 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7973 // ICSj(F2), or, if not that, 7974 if (HasBetterConversion) 7975 return true; 7976 7977 // - F1 is a non-template function and F2 is a function template 7978 // specialization, or, if not that, 7979 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7980 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7981 return true; 7982 7983 // -- F1 and F2 are function template specializations, and the function 7984 // template for F1 is more specialized than the template for F2 7985 // according to the partial ordering rules described in 14.5.5.2, or, 7986 // if not that, 7987 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7988 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7989 if (FunctionTemplateDecl *BetterTemplate 7990 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7991 Cand2.Function->getPrimaryTemplate(), 7992 Loc, 7993 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7994 : TPOC_Call, 7995 Cand1.ExplicitCallArguments)) 7996 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7997 } 7998 7999 // -- the context is an initialization by user-defined conversion 8000 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8001 // from the return type of F1 to the destination type (i.e., 8002 // the type of the entity being initialized) is a better 8003 // conversion sequence than the standard conversion sequence 8004 // from the return type of F2 to the destination type. 8005 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8006 isa<CXXConversionDecl>(Cand1.Function) && 8007 isa<CXXConversionDecl>(Cand2.Function)) { 8008 // First check whether we prefer one of the conversion functions over the 8009 // other. This only distinguishes the results in non-standard, extension 8010 // cases such as the conversion from a lambda closure type to a function 8011 // pointer or block. 8012 ImplicitConversionSequence::CompareKind FuncResult 8013 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8014 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 8015 return FuncResult; 8016 8017 switch (CompareStandardConversionSequences(S, 8018 Cand1.FinalConversion, 8019 Cand2.FinalConversion)) { 8020 case ImplicitConversionSequence::Better: 8021 // Cand1 has a better conversion sequence. 8022 return true; 8023 8024 case ImplicitConversionSequence::Worse: 8025 // Cand1 can't be better than Cand2. 8026 return false; 8027 8028 case ImplicitConversionSequence::Indistinguishable: 8029 // Do nothing 8030 break; 8031 } 8032 } 8033 8034 return false; 8035} 8036 8037/// \brief Computes the best viable function (C++ 13.3.3) 8038/// within an overload candidate set. 8039/// 8040/// \param Loc The location of the function name (or operator symbol) for 8041/// which overload resolution occurs. 8042/// 8043/// \param Best If overload resolution was successful or found a deleted 8044/// function, \p Best points to the candidate function found. 8045/// 8046/// \returns The result of overload resolution. 8047OverloadingResult 8048OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8049 iterator &Best, 8050 bool UserDefinedConversion) { 8051 // Find the best viable function. 8052 Best = end(); 8053 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8054 if (Cand->Viable) 8055 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8056 UserDefinedConversion)) 8057 Best = Cand; 8058 } 8059 8060 // If we didn't find any viable functions, abort. 8061 if (Best == end()) 8062 return OR_No_Viable_Function; 8063 8064 // Make sure that this function is better than every other viable 8065 // function. If not, we have an ambiguity. 8066 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8067 if (Cand->Viable && 8068 Cand != Best && 8069 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8070 UserDefinedConversion)) { 8071 Best = end(); 8072 return OR_Ambiguous; 8073 } 8074 } 8075 8076 // Best is the best viable function. 8077 if (Best->Function && 8078 (Best->Function->isDeleted() || 8079 S.isFunctionConsideredUnavailable(Best->Function))) 8080 return OR_Deleted; 8081 8082 return OR_Success; 8083} 8084 8085namespace { 8086 8087enum OverloadCandidateKind { 8088 oc_function, 8089 oc_method, 8090 oc_constructor, 8091 oc_function_template, 8092 oc_method_template, 8093 oc_constructor_template, 8094 oc_implicit_default_constructor, 8095 oc_implicit_copy_constructor, 8096 oc_implicit_move_constructor, 8097 oc_implicit_copy_assignment, 8098 oc_implicit_move_assignment, 8099 oc_implicit_inherited_constructor 8100}; 8101 8102OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8103 FunctionDecl *Fn, 8104 std::string &Description) { 8105 bool isTemplate = false; 8106 8107 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8108 isTemplate = true; 8109 Description = S.getTemplateArgumentBindingsText( 8110 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8111 } 8112 8113 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8114 if (!Ctor->isImplicit()) 8115 return isTemplate ? oc_constructor_template : oc_constructor; 8116 8117 if (Ctor->getInheritedConstructor()) 8118 return oc_implicit_inherited_constructor; 8119 8120 if (Ctor->isDefaultConstructor()) 8121 return oc_implicit_default_constructor; 8122 8123 if (Ctor->isMoveConstructor()) 8124 return oc_implicit_move_constructor; 8125 8126 assert(Ctor->isCopyConstructor() && 8127 "unexpected sort of implicit constructor"); 8128 return oc_implicit_copy_constructor; 8129 } 8130 8131 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8132 // This actually gets spelled 'candidate function' for now, but 8133 // it doesn't hurt to split it out. 8134 if (!Meth->isImplicit()) 8135 return isTemplate ? oc_method_template : oc_method; 8136 8137 if (Meth->isMoveAssignmentOperator()) 8138 return oc_implicit_move_assignment; 8139 8140 if (Meth->isCopyAssignmentOperator()) 8141 return oc_implicit_copy_assignment; 8142 8143 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8144 return oc_method; 8145 } 8146 8147 return isTemplate ? oc_function_template : oc_function; 8148} 8149 8150void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 8151 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8152 if (!Ctor) return; 8153 8154 Ctor = Ctor->getInheritedConstructor(); 8155 if (!Ctor) return; 8156 8157 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8158} 8159 8160} // end anonymous namespace 8161 8162// Notes the location of an overload candidate. 8163void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8164 std::string FnDesc; 8165 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8166 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8167 << (unsigned) K << FnDesc; 8168 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8169 Diag(Fn->getLocation(), PD); 8170 MaybeEmitInheritedConstructorNote(*this, Fn); 8171} 8172 8173//Notes the location of all overload candidates designated through 8174// OverloadedExpr 8175void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8176 assert(OverloadedExpr->getType() == Context.OverloadTy); 8177 8178 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8179 OverloadExpr *OvlExpr = Ovl.Expression; 8180 8181 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8182 IEnd = OvlExpr->decls_end(); 8183 I != IEnd; ++I) { 8184 if (FunctionTemplateDecl *FunTmpl = 8185 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8186 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8187 } else if (FunctionDecl *Fun 8188 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8189 NoteOverloadCandidate(Fun, DestType); 8190 } 8191 } 8192} 8193 8194/// Diagnoses an ambiguous conversion. The partial diagnostic is the 8195/// "lead" diagnostic; it will be given two arguments, the source and 8196/// target types of the conversion. 8197void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8198 Sema &S, 8199 SourceLocation CaretLoc, 8200 const PartialDiagnostic &PDiag) const { 8201 S.Diag(CaretLoc, PDiag) 8202 << Ambiguous.getFromType() << Ambiguous.getToType(); 8203 // FIXME: The note limiting machinery is borrowed from 8204 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8205 // refactoring here. 8206 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8207 unsigned CandsShown = 0; 8208 AmbiguousConversionSequence::const_iterator I, E; 8209 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8210 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8211 break; 8212 ++CandsShown; 8213 S.NoteOverloadCandidate(*I); 8214 } 8215 if (I != E) 8216 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8217} 8218 8219namespace { 8220 8221void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8222 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8223 assert(Conv.isBad()); 8224 assert(Cand->Function && "for now, candidate must be a function"); 8225 FunctionDecl *Fn = Cand->Function; 8226 8227 // There's a conversion slot for the object argument if this is a 8228 // non-constructor method. Note that 'I' corresponds the 8229 // conversion-slot index. 8230 bool isObjectArgument = false; 8231 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8232 if (I == 0) 8233 isObjectArgument = true; 8234 else 8235 I--; 8236 } 8237 8238 std::string FnDesc; 8239 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8240 8241 Expr *FromExpr = Conv.Bad.FromExpr; 8242 QualType FromTy = Conv.Bad.getFromType(); 8243 QualType ToTy = Conv.Bad.getToType(); 8244 8245 if (FromTy == S.Context.OverloadTy) { 8246 assert(FromExpr && "overload set argument came from implicit argument?"); 8247 Expr *E = FromExpr->IgnoreParens(); 8248 if (isa<UnaryOperator>(E)) 8249 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8250 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8251 8252 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8253 << (unsigned) FnKind << FnDesc 8254 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8255 << ToTy << Name << I+1; 8256 MaybeEmitInheritedConstructorNote(S, Fn); 8257 return; 8258 } 8259 8260 // Do some hand-waving analysis to see if the non-viability is due 8261 // to a qualifier mismatch. 8262 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8263 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8264 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8265 CToTy = RT->getPointeeType(); 8266 else { 8267 // TODO: detect and diagnose the full richness of const mismatches. 8268 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8269 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8270 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8271 } 8272 8273 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8274 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8275 Qualifiers FromQs = CFromTy.getQualifiers(); 8276 Qualifiers ToQs = CToTy.getQualifiers(); 8277 8278 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8279 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8280 << (unsigned) FnKind << FnDesc 8281 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8282 << FromTy 8283 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8284 << (unsigned) isObjectArgument << I+1; 8285 MaybeEmitInheritedConstructorNote(S, Fn); 8286 return; 8287 } 8288 8289 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8290 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8291 << (unsigned) FnKind << FnDesc 8292 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8293 << FromTy 8294 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8295 << (unsigned) isObjectArgument << I+1; 8296 MaybeEmitInheritedConstructorNote(S, Fn); 8297 return; 8298 } 8299 8300 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8301 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8302 << (unsigned) FnKind << FnDesc 8303 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8304 << FromTy 8305 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8306 << (unsigned) isObjectArgument << I+1; 8307 MaybeEmitInheritedConstructorNote(S, Fn); 8308 return; 8309 } 8310 8311 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8312 assert(CVR && "unexpected qualifiers mismatch"); 8313 8314 if (isObjectArgument) { 8315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8316 << (unsigned) FnKind << FnDesc 8317 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8318 << FromTy << (CVR - 1); 8319 } else { 8320 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8321 << (unsigned) FnKind << FnDesc 8322 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8323 << FromTy << (CVR - 1) << I+1; 8324 } 8325 MaybeEmitInheritedConstructorNote(S, Fn); 8326 return; 8327 } 8328 8329 // Special diagnostic for failure to convert an initializer list, since 8330 // telling the user that it has type void is not useful. 8331 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8332 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8333 << (unsigned) FnKind << FnDesc 8334 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8335 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8336 MaybeEmitInheritedConstructorNote(S, Fn); 8337 return; 8338 } 8339 8340 // Diagnose references or pointers to incomplete types differently, 8341 // since it's far from impossible that the incompleteness triggered 8342 // the failure. 8343 QualType TempFromTy = FromTy.getNonReferenceType(); 8344 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8345 TempFromTy = PTy->getPointeeType(); 8346 if (TempFromTy->isIncompleteType()) { 8347 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8348 << (unsigned) FnKind << FnDesc 8349 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8350 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8351 MaybeEmitInheritedConstructorNote(S, Fn); 8352 return; 8353 } 8354 8355 // Diagnose base -> derived pointer conversions. 8356 unsigned BaseToDerivedConversion = 0; 8357 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8358 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8359 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8360 FromPtrTy->getPointeeType()) && 8361 !FromPtrTy->getPointeeType()->isIncompleteType() && 8362 !ToPtrTy->getPointeeType()->isIncompleteType() && 8363 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8364 FromPtrTy->getPointeeType())) 8365 BaseToDerivedConversion = 1; 8366 } 8367 } else if (const ObjCObjectPointerType *FromPtrTy 8368 = FromTy->getAs<ObjCObjectPointerType>()) { 8369 if (const ObjCObjectPointerType *ToPtrTy 8370 = ToTy->getAs<ObjCObjectPointerType>()) 8371 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8372 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8373 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8374 FromPtrTy->getPointeeType()) && 8375 FromIface->isSuperClassOf(ToIface)) 8376 BaseToDerivedConversion = 2; 8377 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8378 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8379 !FromTy->isIncompleteType() && 8380 !ToRefTy->getPointeeType()->isIncompleteType() && 8381 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8382 BaseToDerivedConversion = 3; 8383 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8384 ToTy.getNonReferenceType().getCanonicalType() == 8385 FromTy.getNonReferenceType().getCanonicalType()) { 8386 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8387 << (unsigned) FnKind << FnDesc 8388 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8389 << (unsigned) isObjectArgument << I + 1; 8390 MaybeEmitInheritedConstructorNote(S, Fn); 8391 return; 8392 } 8393 } 8394 8395 if (BaseToDerivedConversion) { 8396 S.Diag(Fn->getLocation(), 8397 diag::note_ovl_candidate_bad_base_to_derived_conv) 8398 << (unsigned) FnKind << FnDesc 8399 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8400 << (BaseToDerivedConversion - 1) 8401 << FromTy << ToTy << I+1; 8402 MaybeEmitInheritedConstructorNote(S, Fn); 8403 return; 8404 } 8405 8406 if (isa<ObjCObjectPointerType>(CFromTy) && 8407 isa<PointerType>(CToTy)) { 8408 Qualifiers FromQs = CFromTy.getQualifiers(); 8409 Qualifiers ToQs = CToTy.getQualifiers(); 8410 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8411 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8412 << (unsigned) FnKind << FnDesc 8413 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8414 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8415 MaybeEmitInheritedConstructorNote(S, Fn); 8416 return; 8417 } 8418 } 8419 8420 // Emit the generic diagnostic and, optionally, add the hints to it. 8421 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8422 FDiag << (unsigned) FnKind << FnDesc 8423 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8424 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8425 << (unsigned) (Cand->Fix.Kind); 8426 8427 // If we can fix the conversion, suggest the FixIts. 8428 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8429 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8430 FDiag << *HI; 8431 S.Diag(Fn->getLocation(), FDiag); 8432 8433 MaybeEmitInheritedConstructorNote(S, Fn); 8434} 8435 8436void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8437 unsigned NumFormalArgs) { 8438 // TODO: treat calls to a missing default constructor as a special case 8439 8440 FunctionDecl *Fn = Cand->Function; 8441 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8442 8443 unsigned MinParams = Fn->getMinRequiredArguments(); 8444 8445 // With invalid overloaded operators, it's possible that we think we 8446 // have an arity mismatch when it fact it looks like we have the 8447 // right number of arguments, because only overloaded operators have 8448 // the weird behavior of overloading member and non-member functions. 8449 // Just don't report anything. 8450 if (Fn->isInvalidDecl() && 8451 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8452 return; 8453 8454 // at least / at most / exactly 8455 unsigned mode, modeCount; 8456 if (NumFormalArgs < MinParams) { 8457 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8458 (Cand->FailureKind == ovl_fail_bad_deduction && 8459 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8460 if (MinParams != FnTy->getNumArgs() || 8461 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8462 mode = 0; // "at least" 8463 else 8464 mode = 2; // "exactly" 8465 modeCount = MinParams; 8466 } else { 8467 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8468 (Cand->FailureKind == ovl_fail_bad_deduction && 8469 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8470 if (MinParams != FnTy->getNumArgs()) 8471 mode = 1; // "at most" 8472 else 8473 mode = 2; // "exactly" 8474 modeCount = FnTy->getNumArgs(); 8475 } 8476 8477 std::string Description; 8478 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8479 8480 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8481 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8482 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8483 << Fn->getParamDecl(0) << NumFormalArgs; 8484 else 8485 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8486 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8487 << modeCount << NumFormalArgs; 8488 MaybeEmitInheritedConstructorNote(S, Fn); 8489} 8490 8491/// Diagnose a failed template-argument deduction. 8492void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8493 unsigned NumArgs) { 8494 FunctionDecl *Fn = Cand->Function; // pattern 8495 8496 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8497 NamedDecl *ParamD; 8498 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8499 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8500 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8501 switch (Cand->DeductionFailure.Result) { 8502 case Sema::TDK_Success: 8503 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8504 8505 case Sema::TDK_Incomplete: { 8506 assert(ParamD && "no parameter found for incomplete deduction result"); 8507 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8508 << ParamD->getDeclName(); 8509 MaybeEmitInheritedConstructorNote(S, Fn); 8510 return; 8511 } 8512 8513 case Sema::TDK_Underqualified: { 8514 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8515 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8516 8517 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8518 8519 // Param will have been canonicalized, but it should just be a 8520 // qualified version of ParamD, so move the qualifiers to that. 8521 QualifierCollector Qs; 8522 Qs.strip(Param); 8523 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8524 assert(S.Context.hasSameType(Param, NonCanonParam)); 8525 8526 // Arg has also been canonicalized, but there's nothing we can do 8527 // about that. It also doesn't matter as much, because it won't 8528 // have any template parameters in it (because deduction isn't 8529 // done on dependent types). 8530 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8531 8532 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8533 << ParamD->getDeclName() << Arg << NonCanonParam; 8534 MaybeEmitInheritedConstructorNote(S, Fn); 8535 return; 8536 } 8537 8538 case Sema::TDK_Inconsistent: { 8539 assert(ParamD && "no parameter found for inconsistent deduction result"); 8540 int which = 0; 8541 if (isa<TemplateTypeParmDecl>(ParamD)) 8542 which = 0; 8543 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8544 which = 1; 8545 else { 8546 which = 2; 8547 } 8548 8549 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8550 << which << ParamD->getDeclName() 8551 << *Cand->DeductionFailure.getFirstArg() 8552 << *Cand->DeductionFailure.getSecondArg(); 8553 MaybeEmitInheritedConstructorNote(S, Fn); 8554 return; 8555 } 8556 8557 case Sema::TDK_InvalidExplicitArguments: 8558 assert(ParamD && "no parameter found for invalid explicit arguments"); 8559 if (ParamD->getDeclName()) 8560 S.Diag(Fn->getLocation(), 8561 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8562 << ParamD->getDeclName(); 8563 else { 8564 int index = 0; 8565 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8566 index = TTP->getIndex(); 8567 else if (NonTypeTemplateParmDecl *NTTP 8568 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8569 index = NTTP->getIndex(); 8570 else 8571 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8572 S.Diag(Fn->getLocation(), 8573 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8574 << (index + 1); 8575 } 8576 MaybeEmitInheritedConstructorNote(S, Fn); 8577 return; 8578 8579 case Sema::TDK_TooManyArguments: 8580 case Sema::TDK_TooFewArguments: 8581 DiagnoseArityMismatch(S, Cand, NumArgs); 8582 return; 8583 8584 case Sema::TDK_InstantiationDepth: 8585 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8586 MaybeEmitInheritedConstructorNote(S, Fn); 8587 return; 8588 8589 case Sema::TDK_SubstitutionFailure: { 8590 // Format the template argument list into the argument string. 8591 SmallString<128> TemplateArgString; 8592 if (TemplateArgumentList *Args = 8593 Cand->DeductionFailure.getTemplateArgumentList()) { 8594 TemplateArgString = " "; 8595 TemplateArgString += S.getTemplateArgumentBindingsText( 8596 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8597 } 8598 8599 // If this candidate was disabled by enable_if, say so. 8600 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8601 if (PDiag && PDiag->second.getDiagID() == 8602 diag::err_typename_nested_not_found_enable_if) { 8603 // FIXME: Use the source range of the condition, and the fully-qualified 8604 // name of the enable_if template. These are both present in PDiag. 8605 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8606 << "'enable_if'" << TemplateArgString; 8607 return; 8608 } 8609 8610 // Format the SFINAE diagnostic into the argument string. 8611 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8612 // formatted message in another diagnostic. 8613 SmallString<128> SFINAEArgString; 8614 SourceRange R; 8615 if (PDiag) { 8616 SFINAEArgString = ": "; 8617 R = SourceRange(PDiag->first, PDiag->first); 8618 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8619 } 8620 8621 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8622 << TemplateArgString << SFINAEArgString << R; 8623 MaybeEmitInheritedConstructorNote(S, Fn); 8624 return; 8625 } 8626 8627 case Sema::TDK_FailedOverloadResolution: { 8628 OverloadExpr::FindResult R = 8629 OverloadExpr::find(Cand->DeductionFailure.getExpr()); 8630 S.Diag(Fn->getLocation(), 8631 diag::note_ovl_candidate_failed_overload_resolution) 8632 << R.Expression->getName(); 8633 return; 8634 } 8635 8636 case Sema::TDK_NonDeducedMismatch: { 8637 // FIXME: Provide a source location to indicate what we couldn't match. 8638 TemplateArgument FirstTA = *Cand->DeductionFailure.getFirstArg(); 8639 TemplateArgument SecondTA = *Cand->DeductionFailure.getSecondArg(); 8640 if (FirstTA.getKind() == TemplateArgument::Template && 8641 SecondTA.getKind() == TemplateArgument::Template) { 8642 TemplateName FirstTN = FirstTA.getAsTemplate(); 8643 TemplateName SecondTN = SecondTA.getAsTemplate(); 8644 if (FirstTN.getKind() == TemplateName::Template && 8645 SecondTN.getKind() == TemplateName::Template) { 8646 if (FirstTN.getAsTemplateDecl()->getName() == 8647 SecondTN.getAsTemplateDecl()->getName()) { 8648 // FIXME: This fixes a bad diagnostic where both templates are named 8649 // the same. This particular case is a bit difficult since: 8650 // 1) It is passed as a string to the diagnostic printer. 8651 // 2) The diagnostic printer only attempts to find a better 8652 // name for types, not decls. 8653 // Ideally, this should folded into the diagnostic printer. 8654 S.Diag(Fn->getLocation(), 8655 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 8656 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 8657 return; 8658 } 8659 } 8660 } 8661 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch) 8662 << FirstTA << SecondTA; 8663 return; 8664 } 8665 // TODO: diagnose these individually, then kill off 8666 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8667 case Sema::TDK_MiscellaneousDeductionFailure: 8668 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8669 MaybeEmitInheritedConstructorNote(S, Fn); 8670 return; 8671 } 8672} 8673 8674/// CUDA: diagnose an invalid call across targets. 8675void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8676 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8677 FunctionDecl *Callee = Cand->Function; 8678 8679 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8680 CalleeTarget = S.IdentifyCUDATarget(Callee); 8681 8682 std::string FnDesc; 8683 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8684 8685 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8686 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8687} 8688 8689/// Generates a 'note' diagnostic for an overload candidate. We've 8690/// already generated a primary error at the call site. 8691/// 8692/// It really does need to be a single diagnostic with its caret 8693/// pointed at the candidate declaration. Yes, this creates some 8694/// major challenges of technical writing. Yes, this makes pointing 8695/// out problems with specific arguments quite awkward. It's still 8696/// better than generating twenty screens of text for every failed 8697/// overload. 8698/// 8699/// It would be great to be able to express per-candidate problems 8700/// more richly for those diagnostic clients that cared, but we'd 8701/// still have to be just as careful with the default diagnostics. 8702void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8703 unsigned NumArgs) { 8704 FunctionDecl *Fn = Cand->Function; 8705 8706 // Note deleted candidates, but only if they're viable. 8707 if (Cand->Viable && (Fn->isDeleted() || 8708 S.isFunctionConsideredUnavailable(Fn))) { 8709 std::string FnDesc; 8710 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8711 8712 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8713 << FnKind << FnDesc 8714 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8715 MaybeEmitInheritedConstructorNote(S, Fn); 8716 return; 8717 } 8718 8719 // We don't really have anything else to say about viable candidates. 8720 if (Cand->Viable) { 8721 S.NoteOverloadCandidate(Fn); 8722 return; 8723 } 8724 8725 switch (Cand->FailureKind) { 8726 case ovl_fail_too_many_arguments: 8727 case ovl_fail_too_few_arguments: 8728 return DiagnoseArityMismatch(S, Cand, NumArgs); 8729 8730 case ovl_fail_bad_deduction: 8731 return DiagnoseBadDeduction(S, Cand, NumArgs); 8732 8733 case ovl_fail_trivial_conversion: 8734 case ovl_fail_bad_final_conversion: 8735 case ovl_fail_final_conversion_not_exact: 8736 return S.NoteOverloadCandidate(Fn); 8737 8738 case ovl_fail_bad_conversion: { 8739 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8740 for (unsigned N = Cand->NumConversions; I != N; ++I) 8741 if (Cand->Conversions[I].isBad()) 8742 return DiagnoseBadConversion(S, Cand, I); 8743 8744 // FIXME: this currently happens when we're called from SemaInit 8745 // when user-conversion overload fails. Figure out how to handle 8746 // those conditions and diagnose them well. 8747 return S.NoteOverloadCandidate(Fn); 8748 } 8749 8750 case ovl_fail_bad_target: 8751 return DiagnoseBadTarget(S, Cand); 8752 } 8753} 8754 8755void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8756 // Desugar the type of the surrogate down to a function type, 8757 // retaining as many typedefs as possible while still showing 8758 // the function type (and, therefore, its parameter types). 8759 QualType FnType = Cand->Surrogate->getConversionType(); 8760 bool isLValueReference = false; 8761 bool isRValueReference = false; 8762 bool isPointer = false; 8763 if (const LValueReferenceType *FnTypeRef = 8764 FnType->getAs<LValueReferenceType>()) { 8765 FnType = FnTypeRef->getPointeeType(); 8766 isLValueReference = true; 8767 } else if (const RValueReferenceType *FnTypeRef = 8768 FnType->getAs<RValueReferenceType>()) { 8769 FnType = FnTypeRef->getPointeeType(); 8770 isRValueReference = true; 8771 } 8772 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8773 FnType = FnTypePtr->getPointeeType(); 8774 isPointer = true; 8775 } 8776 // Desugar down to a function type. 8777 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8778 // Reconstruct the pointer/reference as appropriate. 8779 if (isPointer) FnType = S.Context.getPointerType(FnType); 8780 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8781 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8782 8783 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8784 << FnType; 8785 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8786} 8787 8788void NoteBuiltinOperatorCandidate(Sema &S, 8789 StringRef Opc, 8790 SourceLocation OpLoc, 8791 OverloadCandidate *Cand) { 8792 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8793 std::string TypeStr("operator"); 8794 TypeStr += Opc; 8795 TypeStr += "("; 8796 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8797 if (Cand->NumConversions == 1) { 8798 TypeStr += ")"; 8799 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8800 } else { 8801 TypeStr += ", "; 8802 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8803 TypeStr += ")"; 8804 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8805 } 8806} 8807 8808void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8809 OverloadCandidate *Cand) { 8810 unsigned NoOperands = Cand->NumConversions; 8811 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8812 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8813 if (ICS.isBad()) break; // all meaningless after first invalid 8814 if (!ICS.isAmbiguous()) continue; 8815 8816 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8817 S.PDiag(diag::note_ambiguous_type_conversion)); 8818 } 8819} 8820 8821SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8822 if (Cand->Function) 8823 return Cand->Function->getLocation(); 8824 if (Cand->IsSurrogate) 8825 return Cand->Surrogate->getLocation(); 8826 return SourceLocation(); 8827} 8828 8829static unsigned 8830RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8831 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8832 case Sema::TDK_Success: 8833 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8834 8835 case Sema::TDK_Invalid: 8836 case Sema::TDK_Incomplete: 8837 return 1; 8838 8839 case Sema::TDK_Underqualified: 8840 case Sema::TDK_Inconsistent: 8841 return 2; 8842 8843 case Sema::TDK_SubstitutionFailure: 8844 case Sema::TDK_NonDeducedMismatch: 8845 case Sema::TDK_MiscellaneousDeductionFailure: 8846 return 3; 8847 8848 case Sema::TDK_InstantiationDepth: 8849 case Sema::TDK_FailedOverloadResolution: 8850 return 4; 8851 8852 case Sema::TDK_InvalidExplicitArguments: 8853 return 5; 8854 8855 case Sema::TDK_TooManyArguments: 8856 case Sema::TDK_TooFewArguments: 8857 return 6; 8858 } 8859 llvm_unreachable("Unhandled deduction result"); 8860} 8861 8862struct CompareOverloadCandidatesForDisplay { 8863 Sema &S; 8864 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8865 8866 bool operator()(const OverloadCandidate *L, 8867 const OverloadCandidate *R) { 8868 // Fast-path this check. 8869 if (L == R) return false; 8870 8871 // Order first by viability. 8872 if (L->Viable) { 8873 if (!R->Viable) return true; 8874 8875 // TODO: introduce a tri-valued comparison for overload 8876 // candidates. Would be more worthwhile if we had a sort 8877 // that could exploit it. 8878 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8879 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8880 } else if (R->Viable) 8881 return false; 8882 8883 assert(L->Viable == R->Viable); 8884 8885 // Criteria by which we can sort non-viable candidates: 8886 if (!L->Viable) { 8887 // 1. Arity mismatches come after other candidates. 8888 if (L->FailureKind == ovl_fail_too_many_arguments || 8889 L->FailureKind == ovl_fail_too_few_arguments) 8890 return false; 8891 if (R->FailureKind == ovl_fail_too_many_arguments || 8892 R->FailureKind == ovl_fail_too_few_arguments) 8893 return true; 8894 8895 // 2. Bad conversions come first and are ordered by the number 8896 // of bad conversions and quality of good conversions. 8897 if (L->FailureKind == ovl_fail_bad_conversion) { 8898 if (R->FailureKind != ovl_fail_bad_conversion) 8899 return true; 8900 8901 // The conversion that can be fixed with a smaller number of changes, 8902 // comes first. 8903 unsigned numLFixes = L->Fix.NumConversionsFixed; 8904 unsigned numRFixes = R->Fix.NumConversionsFixed; 8905 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8906 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8907 if (numLFixes != numRFixes) { 8908 if (numLFixes < numRFixes) 8909 return true; 8910 else 8911 return false; 8912 } 8913 8914 // If there's any ordering between the defined conversions... 8915 // FIXME: this might not be transitive. 8916 assert(L->NumConversions == R->NumConversions); 8917 8918 int leftBetter = 0; 8919 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8920 for (unsigned E = L->NumConversions; I != E; ++I) { 8921 switch (CompareImplicitConversionSequences(S, 8922 L->Conversions[I], 8923 R->Conversions[I])) { 8924 case ImplicitConversionSequence::Better: 8925 leftBetter++; 8926 break; 8927 8928 case ImplicitConversionSequence::Worse: 8929 leftBetter--; 8930 break; 8931 8932 case ImplicitConversionSequence::Indistinguishable: 8933 break; 8934 } 8935 } 8936 if (leftBetter > 0) return true; 8937 if (leftBetter < 0) return false; 8938 8939 } else if (R->FailureKind == ovl_fail_bad_conversion) 8940 return false; 8941 8942 if (L->FailureKind == ovl_fail_bad_deduction) { 8943 if (R->FailureKind != ovl_fail_bad_deduction) 8944 return true; 8945 8946 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8947 return RankDeductionFailure(L->DeductionFailure) 8948 < RankDeductionFailure(R->DeductionFailure); 8949 } else if (R->FailureKind == ovl_fail_bad_deduction) 8950 return false; 8951 8952 // TODO: others? 8953 } 8954 8955 // Sort everything else by location. 8956 SourceLocation LLoc = GetLocationForCandidate(L); 8957 SourceLocation RLoc = GetLocationForCandidate(R); 8958 8959 // Put candidates without locations (e.g. builtins) at the end. 8960 if (LLoc.isInvalid()) return false; 8961 if (RLoc.isInvalid()) return true; 8962 8963 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8964 } 8965}; 8966 8967/// CompleteNonViableCandidate - Normally, overload resolution only 8968/// computes up to the first. Produces the FixIt set if possible. 8969void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8970 ArrayRef<Expr *> Args) { 8971 assert(!Cand->Viable); 8972 8973 // Don't do anything on failures other than bad conversion. 8974 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8975 8976 // We only want the FixIts if all the arguments can be corrected. 8977 bool Unfixable = false; 8978 // Use a implicit copy initialization to check conversion fixes. 8979 Cand->Fix.setConversionChecker(TryCopyInitialization); 8980 8981 // Skip forward to the first bad conversion. 8982 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8983 unsigned ConvCount = Cand->NumConversions; 8984 while (true) { 8985 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8986 ConvIdx++; 8987 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8988 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8989 break; 8990 } 8991 } 8992 8993 if (ConvIdx == ConvCount) 8994 return; 8995 8996 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8997 "remaining conversion is initialized?"); 8998 8999 // FIXME: this should probably be preserved from the overload 9000 // operation somehow. 9001 bool SuppressUserConversions = false; 9002 9003 const FunctionProtoType* Proto; 9004 unsigned ArgIdx = ConvIdx; 9005 9006 if (Cand->IsSurrogate) { 9007 QualType ConvType 9008 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9009 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9010 ConvType = ConvPtrType->getPointeeType(); 9011 Proto = ConvType->getAs<FunctionProtoType>(); 9012 ArgIdx--; 9013 } else if (Cand->Function) { 9014 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9015 if (isa<CXXMethodDecl>(Cand->Function) && 9016 !isa<CXXConstructorDecl>(Cand->Function)) 9017 ArgIdx--; 9018 } else { 9019 // Builtin binary operator with a bad first conversion. 9020 assert(ConvCount <= 3); 9021 for (; ConvIdx != ConvCount; ++ConvIdx) 9022 Cand->Conversions[ConvIdx] 9023 = TryCopyInitialization(S, Args[ConvIdx], 9024 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9025 SuppressUserConversions, 9026 /*InOverloadResolution*/ true, 9027 /*AllowObjCWritebackConversion=*/ 9028 S.getLangOpts().ObjCAutoRefCount); 9029 return; 9030 } 9031 9032 // Fill in the rest of the conversions. 9033 unsigned NumArgsInProto = Proto->getNumArgs(); 9034 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9035 if (ArgIdx < NumArgsInProto) { 9036 Cand->Conversions[ConvIdx] 9037 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 9038 SuppressUserConversions, 9039 /*InOverloadResolution=*/true, 9040 /*AllowObjCWritebackConversion=*/ 9041 S.getLangOpts().ObjCAutoRefCount); 9042 // Store the FixIt in the candidate if it exists. 9043 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9044 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9045 } 9046 else 9047 Cand->Conversions[ConvIdx].setEllipsis(); 9048 } 9049} 9050 9051} // end anonymous namespace 9052 9053/// PrintOverloadCandidates - When overload resolution fails, prints 9054/// diagnostic messages containing the candidates in the candidate 9055/// set. 9056void OverloadCandidateSet::NoteCandidates(Sema &S, 9057 OverloadCandidateDisplayKind OCD, 9058 ArrayRef<Expr *> Args, 9059 StringRef Opc, 9060 SourceLocation OpLoc) { 9061 // Sort the candidates by viability and position. Sorting directly would 9062 // be prohibitive, so we make a set of pointers and sort those. 9063 SmallVector<OverloadCandidate*, 32> Cands; 9064 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9065 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9066 if (Cand->Viable) 9067 Cands.push_back(Cand); 9068 else if (OCD == OCD_AllCandidates) { 9069 CompleteNonViableCandidate(S, Cand, Args); 9070 if (Cand->Function || Cand->IsSurrogate) 9071 Cands.push_back(Cand); 9072 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9073 // want to list every possible builtin candidate. 9074 } 9075 } 9076 9077 std::sort(Cands.begin(), Cands.end(), 9078 CompareOverloadCandidatesForDisplay(S)); 9079 9080 bool ReportedAmbiguousConversions = false; 9081 9082 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9083 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9084 unsigned CandsShown = 0; 9085 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9086 OverloadCandidate *Cand = *I; 9087 9088 // Set an arbitrary limit on the number of candidate functions we'll spam 9089 // the user with. FIXME: This limit should depend on details of the 9090 // candidate list. 9091 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9092 break; 9093 } 9094 ++CandsShown; 9095 9096 if (Cand->Function) 9097 NoteFunctionCandidate(S, Cand, Args.size()); 9098 else if (Cand->IsSurrogate) 9099 NoteSurrogateCandidate(S, Cand); 9100 else { 9101 assert(Cand->Viable && 9102 "Non-viable built-in candidates are not added to Cands."); 9103 // Generally we only see ambiguities including viable builtin 9104 // operators if overload resolution got screwed up by an 9105 // ambiguous user-defined conversion. 9106 // 9107 // FIXME: It's quite possible for different conversions to see 9108 // different ambiguities, though. 9109 if (!ReportedAmbiguousConversions) { 9110 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9111 ReportedAmbiguousConversions = true; 9112 } 9113 9114 // If this is a viable builtin, print it. 9115 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9116 } 9117 } 9118 9119 if (I != E) 9120 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9121} 9122 9123// [PossiblyAFunctionType] --> [Return] 9124// NonFunctionType --> NonFunctionType 9125// R (A) --> R(A) 9126// R (*)(A) --> R (A) 9127// R (&)(A) --> R (A) 9128// R (S::*)(A) --> R (A) 9129QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9130 QualType Ret = PossiblyAFunctionType; 9131 if (const PointerType *ToTypePtr = 9132 PossiblyAFunctionType->getAs<PointerType>()) 9133 Ret = ToTypePtr->getPointeeType(); 9134 else if (const ReferenceType *ToTypeRef = 9135 PossiblyAFunctionType->getAs<ReferenceType>()) 9136 Ret = ToTypeRef->getPointeeType(); 9137 else if (const MemberPointerType *MemTypePtr = 9138 PossiblyAFunctionType->getAs<MemberPointerType>()) 9139 Ret = MemTypePtr->getPointeeType(); 9140 Ret = 9141 Context.getCanonicalType(Ret).getUnqualifiedType(); 9142 return Ret; 9143} 9144 9145// A helper class to help with address of function resolution 9146// - allows us to avoid passing around all those ugly parameters 9147class AddressOfFunctionResolver 9148{ 9149 Sema& S; 9150 Expr* SourceExpr; 9151 const QualType& TargetType; 9152 QualType TargetFunctionType; // Extracted function type from target type 9153 9154 bool Complain; 9155 //DeclAccessPair& ResultFunctionAccessPair; 9156 ASTContext& Context; 9157 9158 bool TargetTypeIsNonStaticMemberFunction; 9159 bool FoundNonTemplateFunction; 9160 9161 OverloadExpr::FindResult OvlExprInfo; 9162 OverloadExpr *OvlExpr; 9163 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9164 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9165 9166public: 9167 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 9168 const QualType& TargetType, bool Complain) 9169 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9170 Complain(Complain), Context(S.getASTContext()), 9171 TargetTypeIsNonStaticMemberFunction( 9172 !!TargetType->getAs<MemberPointerType>()), 9173 FoundNonTemplateFunction(false), 9174 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9175 OvlExpr(OvlExprInfo.Expression) 9176 { 9177 ExtractUnqualifiedFunctionTypeFromTargetType(); 9178 9179 if (!TargetFunctionType->isFunctionType()) { 9180 if (OvlExpr->hasExplicitTemplateArgs()) { 9181 DeclAccessPair dap; 9182 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 9183 OvlExpr, false, &dap) ) { 9184 9185 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9186 if (!Method->isStatic()) { 9187 // If the target type is a non-function type and the function 9188 // found is a non-static member function, pretend as if that was 9189 // the target, it's the only possible type to end up with. 9190 TargetTypeIsNonStaticMemberFunction = true; 9191 9192 // And skip adding the function if its not in the proper form. 9193 // We'll diagnose this due to an empty set of functions. 9194 if (!OvlExprInfo.HasFormOfMemberPointer) 9195 return; 9196 } 9197 } 9198 9199 Matches.push_back(std::make_pair(dap,Fn)); 9200 } 9201 } 9202 return; 9203 } 9204 9205 if (OvlExpr->hasExplicitTemplateArgs()) 9206 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9207 9208 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9209 // C++ [over.over]p4: 9210 // If more than one function is selected, [...] 9211 if (Matches.size() > 1) { 9212 if (FoundNonTemplateFunction) 9213 EliminateAllTemplateMatches(); 9214 else 9215 EliminateAllExceptMostSpecializedTemplate(); 9216 } 9217 } 9218 } 9219 9220private: 9221 bool isTargetTypeAFunction() const { 9222 return TargetFunctionType->isFunctionType(); 9223 } 9224 9225 // [ToType] [Return] 9226 9227 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9228 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9229 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9230 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9231 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9232 } 9233 9234 // return true if any matching specializations were found 9235 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9236 const DeclAccessPair& CurAccessFunPair) { 9237 if (CXXMethodDecl *Method 9238 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9239 // Skip non-static function templates when converting to pointer, and 9240 // static when converting to member pointer. 9241 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9242 return false; 9243 } 9244 else if (TargetTypeIsNonStaticMemberFunction) 9245 return false; 9246 9247 // C++ [over.over]p2: 9248 // If the name is a function template, template argument deduction is 9249 // done (14.8.2.2), and if the argument deduction succeeds, the 9250 // resulting template argument list is used to generate a single 9251 // function template specialization, which is added to the set of 9252 // overloaded functions considered. 9253 FunctionDecl *Specialization = 0; 9254 TemplateDeductionInfo Info(OvlExpr->getNameLoc()); 9255 if (Sema::TemplateDeductionResult Result 9256 = S.DeduceTemplateArguments(FunctionTemplate, 9257 &OvlExplicitTemplateArgs, 9258 TargetFunctionType, Specialization, 9259 Info, /*InOverloadResolution=*/true)) { 9260 // FIXME: make a note of the failed deduction for diagnostics. 9261 (void)Result; 9262 return false; 9263 } 9264 9265 // Template argument deduction ensures that we have an exact match or 9266 // compatible pointer-to-function arguments that would be adjusted by ICS. 9267 // This function template specicalization works. 9268 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9269 assert(S.isSameOrCompatibleFunctionType( 9270 Context.getCanonicalType(Specialization->getType()), 9271 Context.getCanonicalType(TargetFunctionType))); 9272 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9273 return true; 9274 } 9275 9276 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9277 const DeclAccessPair& CurAccessFunPair) { 9278 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9279 // Skip non-static functions when converting to pointer, and static 9280 // when converting to member pointer. 9281 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9282 return false; 9283 } 9284 else if (TargetTypeIsNonStaticMemberFunction) 9285 return false; 9286 9287 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9288 if (S.getLangOpts().CUDA) 9289 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9290 if (S.CheckCUDATarget(Caller, FunDecl)) 9291 return false; 9292 9293 // If any candidate has a placeholder return type, trigger its deduction 9294 // now. 9295 if (S.getLangOpts().CPlusPlus1y && 9296 FunDecl->getResultType()->isUndeducedType() && 9297 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9298 return false; 9299 9300 QualType ResultTy; 9301 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9302 FunDecl->getType()) || 9303 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9304 ResultTy)) { 9305 Matches.push_back(std::make_pair(CurAccessFunPair, 9306 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9307 FoundNonTemplateFunction = true; 9308 return true; 9309 } 9310 } 9311 9312 return false; 9313 } 9314 9315 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9316 bool Ret = false; 9317 9318 // If the overload expression doesn't have the form of a pointer to 9319 // member, don't try to convert it to a pointer-to-member type. 9320 if (IsInvalidFormOfPointerToMemberFunction()) 9321 return false; 9322 9323 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9324 E = OvlExpr->decls_end(); 9325 I != E; ++I) { 9326 // Look through any using declarations to find the underlying function. 9327 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9328 9329 // C++ [over.over]p3: 9330 // Non-member functions and static member functions match 9331 // targets of type "pointer-to-function" or "reference-to-function." 9332 // Nonstatic member functions match targets of 9333 // type "pointer-to-member-function." 9334 // Note that according to DR 247, the containing class does not matter. 9335 if (FunctionTemplateDecl *FunctionTemplate 9336 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9337 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9338 Ret = true; 9339 } 9340 // If we have explicit template arguments supplied, skip non-templates. 9341 else if (!OvlExpr->hasExplicitTemplateArgs() && 9342 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9343 Ret = true; 9344 } 9345 assert(Ret || Matches.empty()); 9346 return Ret; 9347 } 9348 9349 void EliminateAllExceptMostSpecializedTemplate() { 9350 // [...] and any given function template specialization F1 is 9351 // eliminated if the set contains a second function template 9352 // specialization whose function template is more specialized 9353 // than the function template of F1 according to the partial 9354 // ordering rules of 14.5.5.2. 9355 9356 // The algorithm specified above is quadratic. We instead use a 9357 // two-pass algorithm (similar to the one used to identify the 9358 // best viable function in an overload set) that identifies the 9359 // best function template (if it exists). 9360 9361 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9362 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9363 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9364 9365 UnresolvedSetIterator Result = 9366 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9367 TPOC_Other, 0, SourceExpr->getLocStart(), 9368 S.PDiag(), 9369 S.PDiag(diag::err_addr_ovl_ambiguous) 9370 << Matches[0].second->getDeclName(), 9371 S.PDiag(diag::note_ovl_candidate) 9372 << (unsigned) oc_function_template, 9373 Complain, TargetFunctionType); 9374 9375 if (Result != MatchesCopy.end()) { 9376 // Make it the first and only element 9377 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9378 Matches[0].second = cast<FunctionDecl>(*Result); 9379 Matches.resize(1); 9380 } 9381 } 9382 9383 void EliminateAllTemplateMatches() { 9384 // [...] any function template specializations in the set are 9385 // eliminated if the set also contains a non-template function, [...] 9386 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9387 if (Matches[I].second->getPrimaryTemplate() == 0) 9388 ++I; 9389 else { 9390 Matches[I] = Matches[--N]; 9391 Matches.set_size(N); 9392 } 9393 } 9394 } 9395 9396public: 9397 void ComplainNoMatchesFound() const { 9398 assert(Matches.empty()); 9399 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9400 << OvlExpr->getName() << TargetFunctionType 9401 << OvlExpr->getSourceRange(); 9402 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9403 } 9404 9405 bool IsInvalidFormOfPointerToMemberFunction() const { 9406 return TargetTypeIsNonStaticMemberFunction && 9407 !OvlExprInfo.HasFormOfMemberPointer; 9408 } 9409 9410 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9411 // TODO: Should we condition this on whether any functions might 9412 // have matched, or is it more appropriate to do that in callers? 9413 // TODO: a fixit wouldn't hurt. 9414 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9415 << TargetType << OvlExpr->getSourceRange(); 9416 } 9417 9418 void ComplainOfInvalidConversion() const { 9419 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9420 << OvlExpr->getName() << TargetType; 9421 } 9422 9423 void ComplainMultipleMatchesFound() const { 9424 assert(Matches.size() > 1); 9425 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9426 << OvlExpr->getName() 9427 << OvlExpr->getSourceRange(); 9428 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9429 } 9430 9431 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9432 9433 int getNumMatches() const { return Matches.size(); } 9434 9435 FunctionDecl* getMatchingFunctionDecl() const { 9436 if (Matches.size() != 1) return 0; 9437 return Matches[0].second; 9438 } 9439 9440 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9441 if (Matches.size() != 1) return 0; 9442 return &Matches[0].first; 9443 } 9444}; 9445 9446/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9447/// an overloaded function (C++ [over.over]), where @p From is an 9448/// expression with overloaded function type and @p ToType is the type 9449/// we're trying to resolve to. For example: 9450/// 9451/// @code 9452/// int f(double); 9453/// int f(int); 9454/// 9455/// int (*pfd)(double) = f; // selects f(double) 9456/// @endcode 9457/// 9458/// This routine returns the resulting FunctionDecl if it could be 9459/// resolved, and NULL otherwise. When @p Complain is true, this 9460/// routine will emit diagnostics if there is an error. 9461FunctionDecl * 9462Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9463 QualType TargetType, 9464 bool Complain, 9465 DeclAccessPair &FoundResult, 9466 bool *pHadMultipleCandidates) { 9467 assert(AddressOfExpr->getType() == Context.OverloadTy); 9468 9469 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9470 Complain); 9471 int NumMatches = Resolver.getNumMatches(); 9472 FunctionDecl* Fn = 0; 9473 if (NumMatches == 0 && Complain) { 9474 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9475 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9476 else 9477 Resolver.ComplainNoMatchesFound(); 9478 } 9479 else if (NumMatches > 1 && Complain) 9480 Resolver.ComplainMultipleMatchesFound(); 9481 else if (NumMatches == 1) { 9482 Fn = Resolver.getMatchingFunctionDecl(); 9483 assert(Fn); 9484 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9485 if (Complain) 9486 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9487 } 9488 9489 if (pHadMultipleCandidates) 9490 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9491 return Fn; 9492} 9493 9494/// \brief Given an expression that refers to an overloaded function, try to 9495/// resolve that overloaded function expression down to a single function. 9496/// 9497/// This routine can only resolve template-ids that refer to a single function 9498/// template, where that template-id refers to a single template whose template 9499/// arguments are either provided by the template-id or have defaults, 9500/// as described in C++0x [temp.arg.explicit]p3. 9501FunctionDecl * 9502Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9503 bool Complain, 9504 DeclAccessPair *FoundResult) { 9505 // C++ [over.over]p1: 9506 // [...] [Note: any redundant set of parentheses surrounding the 9507 // overloaded function name is ignored (5.1). ] 9508 // C++ [over.over]p1: 9509 // [...] The overloaded function name can be preceded by the & 9510 // operator. 9511 9512 // If we didn't actually find any template-ids, we're done. 9513 if (!ovl->hasExplicitTemplateArgs()) 9514 return 0; 9515 9516 TemplateArgumentListInfo ExplicitTemplateArgs; 9517 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9518 9519 // Look through all of the overloaded functions, searching for one 9520 // whose type matches exactly. 9521 FunctionDecl *Matched = 0; 9522 for (UnresolvedSetIterator I = ovl->decls_begin(), 9523 E = ovl->decls_end(); I != E; ++I) { 9524 // C++0x [temp.arg.explicit]p3: 9525 // [...] In contexts where deduction is done and fails, or in contexts 9526 // where deduction is not done, if a template argument list is 9527 // specified and it, along with any default template arguments, 9528 // identifies a single function template specialization, then the 9529 // template-id is an lvalue for the function template specialization. 9530 FunctionTemplateDecl *FunctionTemplate 9531 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9532 9533 // C++ [over.over]p2: 9534 // If the name is a function template, template argument deduction is 9535 // done (14.8.2.2), and if the argument deduction succeeds, the 9536 // resulting template argument list is used to generate a single 9537 // function template specialization, which is added to the set of 9538 // overloaded functions considered. 9539 FunctionDecl *Specialization = 0; 9540 TemplateDeductionInfo Info(ovl->getNameLoc()); 9541 if (TemplateDeductionResult Result 9542 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9543 Specialization, Info, 9544 /*InOverloadResolution=*/true)) { 9545 // FIXME: make a note of the failed deduction for diagnostics. 9546 (void)Result; 9547 continue; 9548 } 9549 9550 assert(Specialization && "no specialization and no error?"); 9551 9552 // Multiple matches; we can't resolve to a single declaration. 9553 if (Matched) { 9554 if (Complain) { 9555 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9556 << ovl->getName(); 9557 NoteAllOverloadCandidates(ovl); 9558 } 9559 return 0; 9560 } 9561 9562 Matched = Specialization; 9563 if (FoundResult) *FoundResult = I.getPair(); 9564 } 9565 9566 if (Matched && getLangOpts().CPlusPlus1y && 9567 Matched->getResultType()->isUndeducedType() && 9568 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 9569 return 0; 9570 9571 return Matched; 9572} 9573 9574 9575 9576 9577// Resolve and fix an overloaded expression that can be resolved 9578// because it identifies a single function template specialization. 9579// 9580// Last three arguments should only be supplied if Complain = true 9581// 9582// Return true if it was logically possible to so resolve the 9583// expression, regardless of whether or not it succeeded. Always 9584// returns true if 'complain' is set. 9585bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9586 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9587 bool complain, const SourceRange& OpRangeForComplaining, 9588 QualType DestTypeForComplaining, 9589 unsigned DiagIDForComplaining) { 9590 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9591 9592 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9593 9594 DeclAccessPair found; 9595 ExprResult SingleFunctionExpression; 9596 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9597 ovl.Expression, /*complain*/ false, &found)) { 9598 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9599 SrcExpr = ExprError(); 9600 return true; 9601 } 9602 9603 // It is only correct to resolve to an instance method if we're 9604 // resolving a form that's permitted to be a pointer to member. 9605 // Otherwise we'll end up making a bound member expression, which 9606 // is illegal in all the contexts we resolve like this. 9607 if (!ovl.HasFormOfMemberPointer && 9608 isa<CXXMethodDecl>(fn) && 9609 cast<CXXMethodDecl>(fn)->isInstance()) { 9610 if (!complain) return false; 9611 9612 Diag(ovl.Expression->getExprLoc(), 9613 diag::err_bound_member_function) 9614 << 0 << ovl.Expression->getSourceRange(); 9615 9616 // TODO: I believe we only end up here if there's a mix of 9617 // static and non-static candidates (otherwise the expression 9618 // would have 'bound member' type, not 'overload' type). 9619 // Ideally we would note which candidate was chosen and why 9620 // the static candidates were rejected. 9621 SrcExpr = ExprError(); 9622 return true; 9623 } 9624 9625 // Fix the expression to refer to 'fn'. 9626 SingleFunctionExpression = 9627 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9628 9629 // If desired, do function-to-pointer decay. 9630 if (doFunctionPointerConverion) { 9631 SingleFunctionExpression = 9632 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9633 if (SingleFunctionExpression.isInvalid()) { 9634 SrcExpr = ExprError(); 9635 return true; 9636 } 9637 } 9638 } 9639 9640 if (!SingleFunctionExpression.isUsable()) { 9641 if (complain) { 9642 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9643 << ovl.Expression->getName() 9644 << DestTypeForComplaining 9645 << OpRangeForComplaining 9646 << ovl.Expression->getQualifierLoc().getSourceRange(); 9647 NoteAllOverloadCandidates(SrcExpr.get()); 9648 9649 SrcExpr = ExprError(); 9650 return true; 9651 } 9652 9653 return false; 9654 } 9655 9656 SrcExpr = SingleFunctionExpression; 9657 return true; 9658} 9659 9660/// \brief Add a single candidate to the overload set. 9661static void AddOverloadedCallCandidate(Sema &S, 9662 DeclAccessPair FoundDecl, 9663 TemplateArgumentListInfo *ExplicitTemplateArgs, 9664 ArrayRef<Expr *> Args, 9665 OverloadCandidateSet &CandidateSet, 9666 bool PartialOverloading, 9667 bool KnownValid) { 9668 NamedDecl *Callee = FoundDecl.getDecl(); 9669 if (isa<UsingShadowDecl>(Callee)) 9670 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9671 9672 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9673 if (ExplicitTemplateArgs) { 9674 assert(!KnownValid && "Explicit template arguments?"); 9675 return; 9676 } 9677 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9678 PartialOverloading); 9679 return; 9680 } 9681 9682 if (FunctionTemplateDecl *FuncTemplate 9683 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9684 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9685 ExplicitTemplateArgs, Args, CandidateSet); 9686 return; 9687 } 9688 9689 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9690} 9691 9692/// \brief Add the overload candidates named by callee and/or found by argument 9693/// dependent lookup to the given overload set. 9694void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9695 ArrayRef<Expr *> Args, 9696 OverloadCandidateSet &CandidateSet, 9697 bool PartialOverloading) { 9698 9699#ifndef NDEBUG 9700 // Verify that ArgumentDependentLookup is consistent with the rules 9701 // in C++0x [basic.lookup.argdep]p3: 9702 // 9703 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9704 // and let Y be the lookup set produced by argument dependent 9705 // lookup (defined as follows). If X contains 9706 // 9707 // -- a declaration of a class member, or 9708 // 9709 // -- a block-scope function declaration that is not a 9710 // using-declaration, or 9711 // 9712 // -- a declaration that is neither a function or a function 9713 // template 9714 // 9715 // then Y is empty. 9716 9717 if (ULE->requiresADL()) { 9718 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9719 E = ULE->decls_end(); I != E; ++I) { 9720 assert(!(*I)->getDeclContext()->isRecord()); 9721 assert(isa<UsingShadowDecl>(*I) || 9722 !(*I)->getDeclContext()->isFunctionOrMethod()); 9723 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9724 } 9725 } 9726#endif 9727 9728 // It would be nice to avoid this copy. 9729 TemplateArgumentListInfo TABuffer; 9730 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9731 if (ULE->hasExplicitTemplateArgs()) { 9732 ULE->copyTemplateArgumentsInto(TABuffer); 9733 ExplicitTemplateArgs = &TABuffer; 9734 } 9735 9736 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9737 E = ULE->decls_end(); I != E; ++I) 9738 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9739 CandidateSet, PartialOverloading, 9740 /*KnownValid*/ true); 9741 9742 if (ULE->requiresADL()) 9743 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9744 ULE->getExprLoc(), 9745 Args, ExplicitTemplateArgs, 9746 CandidateSet, PartialOverloading); 9747} 9748 9749/// Determine whether a declaration with the specified name could be moved into 9750/// a different namespace. 9751static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 9752 switch (Name.getCXXOverloadedOperator()) { 9753 case OO_New: case OO_Array_New: 9754 case OO_Delete: case OO_Array_Delete: 9755 return false; 9756 9757 default: 9758 return true; 9759 } 9760} 9761 9762/// Attempt to recover from an ill-formed use of a non-dependent name in a 9763/// template, where the non-dependent name was declared after the template 9764/// was defined. This is common in code written for a compilers which do not 9765/// correctly implement two-stage name lookup. 9766/// 9767/// Returns true if a viable candidate was found and a diagnostic was issued. 9768static bool 9769DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9770 const CXXScopeSpec &SS, LookupResult &R, 9771 TemplateArgumentListInfo *ExplicitTemplateArgs, 9772 ArrayRef<Expr *> Args) { 9773 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9774 return false; 9775 9776 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9777 if (DC->isTransparentContext()) 9778 continue; 9779 9780 SemaRef.LookupQualifiedName(R, DC); 9781 9782 if (!R.empty()) { 9783 R.suppressDiagnostics(); 9784 9785 if (isa<CXXRecordDecl>(DC)) { 9786 // Don't diagnose names we find in classes; we get much better 9787 // diagnostics for these from DiagnoseEmptyLookup. 9788 R.clear(); 9789 return false; 9790 } 9791 9792 OverloadCandidateSet Candidates(FnLoc); 9793 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9794 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9795 ExplicitTemplateArgs, Args, 9796 Candidates, false, /*KnownValid*/ false); 9797 9798 OverloadCandidateSet::iterator Best; 9799 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9800 // No viable functions. Don't bother the user with notes for functions 9801 // which don't work and shouldn't be found anyway. 9802 R.clear(); 9803 return false; 9804 } 9805 9806 // Find the namespaces where ADL would have looked, and suggest 9807 // declaring the function there instead. 9808 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9809 Sema::AssociatedClassSet AssociatedClasses; 9810 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9811 AssociatedNamespaces, 9812 AssociatedClasses); 9813 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9814 if (canBeDeclaredInNamespace(R.getLookupName())) { 9815 DeclContext *Std = SemaRef.getStdNamespace(); 9816 for (Sema::AssociatedNamespaceSet::iterator 9817 it = AssociatedNamespaces.begin(), 9818 end = AssociatedNamespaces.end(); it != end; ++it) { 9819 // Never suggest declaring a function within namespace 'std'. 9820 if (Std && Std->Encloses(*it)) 9821 continue; 9822 9823 // Never suggest declaring a function within a namespace with a 9824 // reserved name, like __gnu_cxx. 9825 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 9826 if (NS && 9827 NS->getQualifiedNameAsString().find("__") != std::string::npos) 9828 continue; 9829 9830 SuggestedNamespaces.insert(*it); 9831 } 9832 } 9833 9834 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9835 << R.getLookupName(); 9836 if (SuggestedNamespaces.empty()) { 9837 SemaRef.Diag(Best->Function->getLocation(), 9838 diag::note_not_found_by_two_phase_lookup) 9839 << R.getLookupName() << 0; 9840 } else if (SuggestedNamespaces.size() == 1) { 9841 SemaRef.Diag(Best->Function->getLocation(), 9842 diag::note_not_found_by_two_phase_lookup) 9843 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9844 } else { 9845 // FIXME: It would be useful to list the associated namespaces here, 9846 // but the diagnostics infrastructure doesn't provide a way to produce 9847 // a localized representation of a list of items. 9848 SemaRef.Diag(Best->Function->getLocation(), 9849 diag::note_not_found_by_two_phase_lookup) 9850 << R.getLookupName() << 2; 9851 } 9852 9853 // Try to recover by calling this function. 9854 return true; 9855 } 9856 9857 R.clear(); 9858 } 9859 9860 return false; 9861} 9862 9863/// Attempt to recover from ill-formed use of a non-dependent operator in a 9864/// template, where the non-dependent operator was declared after the template 9865/// was defined. 9866/// 9867/// Returns true if a viable candidate was found and a diagnostic was issued. 9868static bool 9869DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9870 SourceLocation OpLoc, 9871 ArrayRef<Expr *> Args) { 9872 DeclarationName OpName = 9873 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9874 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9875 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9876 /*ExplicitTemplateArgs=*/0, Args); 9877} 9878 9879namespace { 9880// Callback to limit the allowed keywords and to only accept typo corrections 9881// that are keywords or whose decls refer to functions (or template functions) 9882// that accept the given number of arguments. 9883class RecoveryCallCCC : public CorrectionCandidateCallback { 9884 public: 9885 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9886 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9887 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9888 WantRemainingKeywords = false; 9889 } 9890 9891 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9892 if (!candidate.getCorrectionDecl()) 9893 return candidate.isKeyword(); 9894 9895 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9896 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9897 FunctionDecl *FD = 0; 9898 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9899 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9900 FD = FTD->getTemplatedDecl(); 9901 if (!HasExplicitTemplateArgs && !FD) { 9902 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9903 // If the Decl is neither a function nor a template function, 9904 // determine if it is a pointer or reference to a function. If so, 9905 // check against the number of arguments expected for the pointee. 9906 QualType ValType = cast<ValueDecl>(ND)->getType(); 9907 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9908 ValType = ValType->getPointeeType(); 9909 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9910 if (FPT->getNumArgs() == NumArgs) 9911 return true; 9912 } 9913 } 9914 if (FD && FD->getNumParams() >= NumArgs && 9915 FD->getMinRequiredArguments() <= NumArgs) 9916 return true; 9917 } 9918 return false; 9919 } 9920 9921 private: 9922 unsigned NumArgs; 9923 bool HasExplicitTemplateArgs; 9924}; 9925 9926// Callback that effectively disabled typo correction 9927class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9928 public: 9929 NoTypoCorrectionCCC() { 9930 WantTypeSpecifiers = false; 9931 WantExpressionKeywords = false; 9932 WantCXXNamedCasts = false; 9933 WantRemainingKeywords = false; 9934 } 9935 9936 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9937 return false; 9938 } 9939}; 9940 9941class BuildRecoveryCallExprRAII { 9942 Sema &SemaRef; 9943public: 9944 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 9945 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 9946 SemaRef.IsBuildingRecoveryCallExpr = true; 9947 } 9948 9949 ~BuildRecoveryCallExprRAII() { 9950 SemaRef.IsBuildingRecoveryCallExpr = false; 9951 } 9952}; 9953 9954} 9955 9956/// Attempts to recover from a call where no functions were found. 9957/// 9958/// Returns true if new candidates were found. 9959static ExprResult 9960BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9961 UnresolvedLookupExpr *ULE, 9962 SourceLocation LParenLoc, 9963 llvm::MutableArrayRef<Expr *> Args, 9964 SourceLocation RParenLoc, 9965 bool EmptyLookup, bool AllowTypoCorrection) { 9966 // Do not try to recover if it is already building a recovery call. 9967 // This stops infinite loops for template instantiations like 9968 // 9969 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 9970 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 9971 // 9972 if (SemaRef.IsBuildingRecoveryCallExpr) 9973 return ExprError(); 9974 BuildRecoveryCallExprRAII RCE(SemaRef); 9975 9976 CXXScopeSpec SS; 9977 SS.Adopt(ULE->getQualifierLoc()); 9978 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9979 9980 TemplateArgumentListInfo TABuffer; 9981 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9982 if (ULE->hasExplicitTemplateArgs()) { 9983 ULE->copyTemplateArgumentsInto(TABuffer); 9984 ExplicitTemplateArgs = &TABuffer; 9985 } 9986 9987 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9988 Sema::LookupOrdinaryName); 9989 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9990 NoTypoCorrectionCCC RejectAll; 9991 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9992 (CorrectionCandidateCallback*)&Validator : 9993 (CorrectionCandidateCallback*)&RejectAll; 9994 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9995 ExplicitTemplateArgs, Args) && 9996 (!EmptyLookup || 9997 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9998 ExplicitTemplateArgs, Args))) 9999 return ExprError(); 10000 10001 assert(!R.empty() && "lookup results empty despite recovery"); 10002 10003 // Build an implicit member call if appropriate. Just drop the 10004 // casts and such from the call, we don't really care. 10005 ExprResult NewFn = ExprError(); 10006 if ((*R.begin())->isCXXClassMember()) 10007 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10008 R, ExplicitTemplateArgs); 10009 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10010 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10011 ExplicitTemplateArgs); 10012 else 10013 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10014 10015 if (NewFn.isInvalid()) 10016 return ExprError(); 10017 10018 // This shouldn't cause an infinite loop because we're giving it 10019 // an expression with viable lookup results, which should never 10020 // end up here. 10021 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 10022 MultiExprArg(Args.data(), Args.size()), 10023 RParenLoc); 10024} 10025 10026/// \brief Constructs and populates an OverloadedCandidateSet from 10027/// the given function. 10028/// \returns true when an the ExprResult output parameter has been set. 10029bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10030 UnresolvedLookupExpr *ULE, 10031 MultiExprArg Args, 10032 SourceLocation RParenLoc, 10033 OverloadCandidateSet *CandidateSet, 10034 ExprResult *Result) { 10035#ifndef NDEBUG 10036 if (ULE->requiresADL()) { 10037 // To do ADL, we must have found an unqualified name. 10038 assert(!ULE->getQualifier() && "qualified name with ADL"); 10039 10040 // We don't perform ADL for implicit declarations of builtins. 10041 // Verify that this was correctly set up. 10042 FunctionDecl *F; 10043 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10044 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10045 F->getBuiltinID() && F->isImplicit()) 10046 llvm_unreachable("performing ADL for builtin"); 10047 10048 // We don't perform ADL in C. 10049 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10050 } 10051#endif 10052 10053 UnbridgedCastsSet UnbridgedCasts; 10054 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10055 *Result = ExprError(); 10056 return true; 10057 } 10058 10059 // Add the functions denoted by the callee to the set of candidate 10060 // functions, including those from argument-dependent lookup. 10061 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10062 10063 // If we found nothing, try to recover. 10064 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10065 // out if it fails. 10066 if (CandidateSet->empty()) { 10067 // In Microsoft mode, if we are inside a template class member function then 10068 // create a type dependent CallExpr. The goal is to postpone name lookup 10069 // to instantiation time to be able to search into type dependent base 10070 // classes. 10071 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 10072 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10073 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10074 Context.DependentTy, VK_RValue, 10075 RParenLoc); 10076 CE->setTypeDependent(true); 10077 *Result = Owned(CE); 10078 return true; 10079 } 10080 return false; 10081 } 10082 10083 UnbridgedCasts.restore(); 10084 return false; 10085} 10086 10087/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10088/// the completed call expression. If overload resolution fails, emits 10089/// diagnostics and returns ExprError() 10090static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10091 UnresolvedLookupExpr *ULE, 10092 SourceLocation LParenLoc, 10093 MultiExprArg Args, 10094 SourceLocation RParenLoc, 10095 Expr *ExecConfig, 10096 OverloadCandidateSet *CandidateSet, 10097 OverloadCandidateSet::iterator *Best, 10098 OverloadingResult OverloadResult, 10099 bool AllowTypoCorrection) { 10100 if (CandidateSet->empty()) 10101 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10102 RParenLoc, /*EmptyLookup=*/true, 10103 AllowTypoCorrection); 10104 10105 switch (OverloadResult) { 10106 case OR_Success: { 10107 FunctionDecl *FDecl = (*Best)->Function; 10108 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10109 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10110 return ExprError(); 10111 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10112 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10113 ExecConfig); 10114 } 10115 10116 case OR_No_Viable_Function: { 10117 // Try to recover by looking for viable functions which the user might 10118 // have meant to call. 10119 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10120 Args, RParenLoc, 10121 /*EmptyLookup=*/false, 10122 AllowTypoCorrection); 10123 if (!Recovery.isInvalid()) 10124 return Recovery; 10125 10126 SemaRef.Diag(Fn->getLocStart(), 10127 diag::err_ovl_no_viable_function_in_call) 10128 << ULE->getName() << Fn->getSourceRange(); 10129 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10130 break; 10131 } 10132 10133 case OR_Ambiguous: 10134 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10135 << ULE->getName() << Fn->getSourceRange(); 10136 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10137 break; 10138 10139 case OR_Deleted: { 10140 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10141 << (*Best)->Function->isDeleted() 10142 << ULE->getName() 10143 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10144 << Fn->getSourceRange(); 10145 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10146 10147 // We emitted an error for the unvailable/deleted function call but keep 10148 // the call in the AST. 10149 FunctionDecl *FDecl = (*Best)->Function; 10150 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10151 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10152 ExecConfig); 10153 } 10154 } 10155 10156 // Overload resolution failed. 10157 return ExprError(); 10158} 10159 10160/// BuildOverloadedCallExpr - Given the call expression that calls Fn 10161/// (which eventually refers to the declaration Func) and the call 10162/// arguments Args/NumArgs, attempt to resolve the function call down 10163/// to a specific function. If overload resolution succeeds, returns 10164/// the call expression produced by overload resolution. 10165/// Otherwise, emits diagnostics and returns ExprError. 10166ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10167 UnresolvedLookupExpr *ULE, 10168 SourceLocation LParenLoc, 10169 MultiExprArg Args, 10170 SourceLocation RParenLoc, 10171 Expr *ExecConfig, 10172 bool AllowTypoCorrection) { 10173 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 10174 ExprResult result; 10175 10176 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10177 &result)) 10178 return result; 10179 10180 OverloadCandidateSet::iterator Best; 10181 OverloadingResult OverloadResult = 10182 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10183 10184 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10185 RParenLoc, ExecConfig, &CandidateSet, 10186 &Best, OverloadResult, 10187 AllowTypoCorrection); 10188} 10189 10190static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10191 return Functions.size() > 1 || 10192 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10193} 10194 10195/// \brief Create a unary operation that may resolve to an overloaded 10196/// operator. 10197/// 10198/// \param OpLoc The location of the operator itself (e.g., '*'). 10199/// 10200/// \param OpcIn The UnaryOperator::Opcode that describes this 10201/// operator. 10202/// 10203/// \param Fns The set of non-member functions that will be 10204/// considered by overload resolution. The caller needs to build this 10205/// set based on the context using, e.g., 10206/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10207/// set should not contain any member functions; those will be added 10208/// by CreateOverloadedUnaryOp(). 10209/// 10210/// \param Input The input argument. 10211ExprResult 10212Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10213 const UnresolvedSetImpl &Fns, 10214 Expr *Input) { 10215 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10216 10217 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10218 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10219 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10220 // TODO: provide better source location info. 10221 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10222 10223 if (checkPlaceholderForOverload(*this, Input)) 10224 return ExprError(); 10225 10226 Expr *Args[2] = { Input, 0 }; 10227 unsigned NumArgs = 1; 10228 10229 // For post-increment and post-decrement, add the implicit '0' as 10230 // the second argument, so that we know this is a post-increment or 10231 // post-decrement. 10232 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10233 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10234 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10235 SourceLocation()); 10236 NumArgs = 2; 10237 } 10238 10239 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10240 10241 if (Input->isTypeDependent()) { 10242 if (Fns.empty()) 10243 return Owned(new (Context) UnaryOperator(Input, 10244 Opc, 10245 Context.DependentTy, 10246 VK_RValue, OK_Ordinary, 10247 OpLoc)); 10248 10249 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10250 UnresolvedLookupExpr *Fn 10251 = UnresolvedLookupExpr::Create(Context, NamingClass, 10252 NestedNameSpecifierLoc(), OpNameInfo, 10253 /*ADL*/ true, IsOverloaded(Fns), 10254 Fns.begin(), Fns.end()); 10255 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, 10256 Context.DependentTy, 10257 VK_RValue, 10258 OpLoc, false)); 10259 } 10260 10261 // Build an empty overload set. 10262 OverloadCandidateSet CandidateSet(OpLoc); 10263 10264 // Add the candidates from the given function set. 10265 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false); 10266 10267 // Add operator candidates that are member functions. 10268 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10269 10270 // Add candidates from ADL. 10271 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc, 10272 ArgsArray, /*ExplicitTemplateArgs*/ 0, 10273 CandidateSet); 10274 10275 // Add builtin operator candidates. 10276 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10277 10278 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10279 10280 // Perform overload resolution. 10281 OverloadCandidateSet::iterator Best; 10282 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10283 case OR_Success: { 10284 // We found a built-in operator or an overloaded operator. 10285 FunctionDecl *FnDecl = Best->Function; 10286 10287 if (FnDecl) { 10288 // We matched an overloaded operator. Build a call to that 10289 // operator. 10290 10291 // Convert the arguments. 10292 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10293 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10294 10295 ExprResult InputRes = 10296 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10297 Best->FoundDecl, Method); 10298 if (InputRes.isInvalid()) 10299 return ExprError(); 10300 Input = InputRes.take(); 10301 } else { 10302 // Convert the arguments. 10303 ExprResult InputInit 10304 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10305 Context, 10306 FnDecl->getParamDecl(0)), 10307 SourceLocation(), 10308 Input); 10309 if (InputInit.isInvalid()) 10310 return ExprError(); 10311 Input = InputInit.take(); 10312 } 10313 10314 // Determine the result type. 10315 QualType ResultTy = FnDecl->getResultType(); 10316 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10317 ResultTy = ResultTy.getNonLValueExprType(Context); 10318 10319 // Build the actual expression node. 10320 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10321 HadMultipleCandidates, OpLoc); 10322 if (FnExpr.isInvalid()) 10323 return ExprError(); 10324 10325 Args[0] = Input; 10326 CallExpr *TheCall = 10327 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray, 10328 ResultTy, VK, OpLoc, false); 10329 10330 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10331 FnDecl)) 10332 return ExprError(); 10333 10334 return MaybeBindToTemporary(TheCall); 10335 } else { 10336 // We matched a built-in operator. Convert the arguments, then 10337 // break out so that we will build the appropriate built-in 10338 // operator node. 10339 ExprResult InputRes = 10340 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10341 Best->Conversions[0], AA_Passing); 10342 if (InputRes.isInvalid()) 10343 return ExprError(); 10344 Input = InputRes.take(); 10345 break; 10346 } 10347 } 10348 10349 case OR_No_Viable_Function: 10350 // This is an erroneous use of an operator which can be overloaded by 10351 // a non-member function. Check for non-member operators which were 10352 // defined too late to be candidates. 10353 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10354 // FIXME: Recover by calling the found function. 10355 return ExprError(); 10356 10357 // No viable function; fall through to handling this as a 10358 // built-in operator, which will produce an error message for us. 10359 break; 10360 10361 case OR_Ambiguous: 10362 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10363 << UnaryOperator::getOpcodeStr(Opc) 10364 << Input->getType() 10365 << Input->getSourceRange(); 10366 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 10367 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10368 return ExprError(); 10369 10370 case OR_Deleted: 10371 Diag(OpLoc, diag::err_ovl_deleted_oper) 10372 << Best->Function->isDeleted() 10373 << UnaryOperator::getOpcodeStr(Opc) 10374 << getDeletedOrUnavailableSuffix(Best->Function) 10375 << Input->getSourceRange(); 10376 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 10377 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10378 return ExprError(); 10379 } 10380 10381 // Either we found no viable overloaded operator or we matched a 10382 // built-in operator. In either case, fall through to trying to 10383 // build a built-in operation. 10384 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10385} 10386 10387/// \brief Create a binary operation that may resolve to an overloaded 10388/// operator. 10389/// 10390/// \param OpLoc The location of the operator itself (e.g., '+'). 10391/// 10392/// \param OpcIn The BinaryOperator::Opcode that describes this 10393/// operator. 10394/// 10395/// \param Fns The set of non-member functions that will be 10396/// considered by overload resolution. The caller needs to build this 10397/// set based on the context using, e.g., 10398/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10399/// set should not contain any member functions; those will be added 10400/// by CreateOverloadedBinOp(). 10401/// 10402/// \param LHS Left-hand argument. 10403/// \param RHS Right-hand argument. 10404ExprResult 10405Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10406 unsigned OpcIn, 10407 const UnresolvedSetImpl &Fns, 10408 Expr *LHS, Expr *RHS) { 10409 Expr *Args[2] = { LHS, RHS }; 10410 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10411 10412 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10413 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10414 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10415 10416 // If either side is type-dependent, create an appropriate dependent 10417 // expression. 10418 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10419 if (Fns.empty()) { 10420 // If there are no functions to store, just build a dependent 10421 // BinaryOperator or CompoundAssignment. 10422 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10423 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10424 Context.DependentTy, 10425 VK_RValue, OK_Ordinary, 10426 OpLoc, 10427 FPFeatures.fp_contract)); 10428 10429 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10430 Context.DependentTy, 10431 VK_LValue, 10432 OK_Ordinary, 10433 Context.DependentTy, 10434 Context.DependentTy, 10435 OpLoc, 10436 FPFeatures.fp_contract)); 10437 } 10438 10439 // FIXME: save results of ADL from here? 10440 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10441 // TODO: provide better source location info in DNLoc component. 10442 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10443 UnresolvedLookupExpr *Fn 10444 = UnresolvedLookupExpr::Create(Context, NamingClass, 10445 NestedNameSpecifierLoc(), OpNameInfo, 10446 /*ADL*/ true, IsOverloaded(Fns), 10447 Fns.begin(), Fns.end()); 10448 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10449 Context.DependentTy, VK_RValue, 10450 OpLoc, FPFeatures.fp_contract)); 10451 } 10452 10453 // Always do placeholder-like conversions on the RHS. 10454 if (checkPlaceholderForOverload(*this, Args[1])) 10455 return ExprError(); 10456 10457 // Do placeholder-like conversion on the LHS; note that we should 10458 // not get here with a PseudoObject LHS. 10459 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10460 if (checkPlaceholderForOverload(*this, Args[0])) 10461 return ExprError(); 10462 10463 // If this is the assignment operator, we only perform overload resolution 10464 // if the left-hand side is a class or enumeration type. This is actually 10465 // a hack. The standard requires that we do overload resolution between the 10466 // various built-in candidates, but as DR507 points out, this can lead to 10467 // problems. So we do it this way, which pretty much follows what GCC does. 10468 // Note that we go the traditional code path for compound assignment forms. 10469 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10470 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10471 10472 // If this is the .* operator, which is not overloadable, just 10473 // create a built-in binary operator. 10474 if (Opc == BO_PtrMemD) 10475 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10476 10477 // Build an empty overload set. 10478 OverloadCandidateSet CandidateSet(OpLoc); 10479 10480 // Add the candidates from the given function set. 10481 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10482 10483 // Add operator candidates that are member functions. 10484 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10485 10486 // Add candidates from ADL. 10487 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10488 OpLoc, Args, 10489 /*ExplicitTemplateArgs*/ 0, 10490 CandidateSet); 10491 10492 // Add builtin operator candidates. 10493 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10494 10495 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10496 10497 // Perform overload resolution. 10498 OverloadCandidateSet::iterator Best; 10499 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10500 case OR_Success: { 10501 // We found a built-in operator or an overloaded operator. 10502 FunctionDecl *FnDecl = Best->Function; 10503 10504 if (FnDecl) { 10505 // We matched an overloaded operator. Build a call to that 10506 // operator. 10507 10508 // Convert the arguments. 10509 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10510 // Best->Access is only meaningful for class members. 10511 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10512 10513 ExprResult Arg1 = 10514 PerformCopyInitialization( 10515 InitializedEntity::InitializeParameter(Context, 10516 FnDecl->getParamDecl(0)), 10517 SourceLocation(), Owned(Args[1])); 10518 if (Arg1.isInvalid()) 10519 return ExprError(); 10520 10521 ExprResult Arg0 = 10522 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10523 Best->FoundDecl, Method); 10524 if (Arg0.isInvalid()) 10525 return ExprError(); 10526 Args[0] = Arg0.takeAs<Expr>(); 10527 Args[1] = RHS = Arg1.takeAs<Expr>(); 10528 } else { 10529 // Convert the arguments. 10530 ExprResult Arg0 = PerformCopyInitialization( 10531 InitializedEntity::InitializeParameter(Context, 10532 FnDecl->getParamDecl(0)), 10533 SourceLocation(), Owned(Args[0])); 10534 if (Arg0.isInvalid()) 10535 return ExprError(); 10536 10537 ExprResult Arg1 = 10538 PerformCopyInitialization( 10539 InitializedEntity::InitializeParameter(Context, 10540 FnDecl->getParamDecl(1)), 10541 SourceLocation(), Owned(Args[1])); 10542 if (Arg1.isInvalid()) 10543 return ExprError(); 10544 Args[0] = LHS = Arg0.takeAs<Expr>(); 10545 Args[1] = RHS = Arg1.takeAs<Expr>(); 10546 } 10547 10548 // Determine the result type. 10549 QualType ResultTy = FnDecl->getResultType(); 10550 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10551 ResultTy = ResultTy.getNonLValueExprType(Context); 10552 10553 // Build the actual expression node. 10554 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10555 Best->FoundDecl, 10556 HadMultipleCandidates, OpLoc); 10557 if (FnExpr.isInvalid()) 10558 return ExprError(); 10559 10560 CXXOperatorCallExpr *TheCall = 10561 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10562 Args, ResultTy, VK, OpLoc, 10563 FPFeatures.fp_contract); 10564 10565 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10566 FnDecl)) 10567 return ExprError(); 10568 10569 ArrayRef<const Expr *> ArgsArray(Args, 2); 10570 // Cut off the implicit 'this'. 10571 if (isa<CXXMethodDecl>(FnDecl)) 10572 ArgsArray = ArgsArray.slice(1); 10573 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 10574 TheCall->getSourceRange(), VariadicDoesNotApply); 10575 10576 return MaybeBindToTemporary(TheCall); 10577 } else { 10578 // We matched a built-in operator. Convert the arguments, then 10579 // break out so that we will build the appropriate built-in 10580 // operator node. 10581 ExprResult ArgsRes0 = 10582 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10583 Best->Conversions[0], AA_Passing); 10584 if (ArgsRes0.isInvalid()) 10585 return ExprError(); 10586 Args[0] = ArgsRes0.take(); 10587 10588 ExprResult ArgsRes1 = 10589 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10590 Best->Conversions[1], AA_Passing); 10591 if (ArgsRes1.isInvalid()) 10592 return ExprError(); 10593 Args[1] = ArgsRes1.take(); 10594 break; 10595 } 10596 } 10597 10598 case OR_No_Viable_Function: { 10599 // C++ [over.match.oper]p9: 10600 // If the operator is the operator , [...] and there are no 10601 // viable functions, then the operator is assumed to be the 10602 // built-in operator and interpreted according to clause 5. 10603 if (Opc == BO_Comma) 10604 break; 10605 10606 // For class as left operand for assignment or compound assigment 10607 // operator do not fall through to handling in built-in, but report that 10608 // no overloaded assignment operator found 10609 ExprResult Result = ExprError(); 10610 if (Args[0]->getType()->isRecordType() && 10611 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10612 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10613 << BinaryOperator::getOpcodeStr(Opc) 10614 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10615 } else { 10616 // This is an erroneous use of an operator which can be overloaded by 10617 // a non-member function. Check for non-member operators which were 10618 // defined too late to be candidates. 10619 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10620 // FIXME: Recover by calling the found function. 10621 return ExprError(); 10622 10623 // No viable function; try to create a built-in operation, which will 10624 // produce an error. Then, show the non-viable candidates. 10625 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10626 } 10627 assert(Result.isInvalid() && 10628 "C++ binary operator overloading is missing candidates!"); 10629 if (Result.isInvalid()) 10630 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10631 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10632 return Result; 10633 } 10634 10635 case OR_Ambiguous: 10636 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10637 << BinaryOperator::getOpcodeStr(Opc) 10638 << Args[0]->getType() << Args[1]->getType() 10639 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10640 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10641 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10642 return ExprError(); 10643 10644 case OR_Deleted: 10645 if (isImplicitlyDeleted(Best->Function)) { 10646 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10647 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10648 << Context.getRecordType(Method->getParent()) 10649 << getSpecialMember(Method); 10650 10651 // The user probably meant to call this special member. Just 10652 // explain why it's deleted. 10653 NoteDeletedFunction(Method); 10654 return ExprError(); 10655 } else { 10656 Diag(OpLoc, diag::err_ovl_deleted_oper) 10657 << Best->Function->isDeleted() 10658 << BinaryOperator::getOpcodeStr(Opc) 10659 << getDeletedOrUnavailableSuffix(Best->Function) 10660 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10661 } 10662 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10663 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10664 return ExprError(); 10665 } 10666 10667 // We matched a built-in operator; build it. 10668 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10669} 10670 10671ExprResult 10672Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10673 SourceLocation RLoc, 10674 Expr *Base, Expr *Idx) { 10675 Expr *Args[2] = { Base, Idx }; 10676 DeclarationName OpName = 10677 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10678 10679 // If either side is type-dependent, create an appropriate dependent 10680 // expression. 10681 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10682 10683 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10684 // CHECKME: no 'operator' keyword? 10685 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10686 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10687 UnresolvedLookupExpr *Fn 10688 = UnresolvedLookupExpr::Create(Context, NamingClass, 10689 NestedNameSpecifierLoc(), OpNameInfo, 10690 /*ADL*/ true, /*Overloaded*/ false, 10691 UnresolvedSetIterator(), 10692 UnresolvedSetIterator()); 10693 // Can't add any actual overloads yet 10694 10695 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10696 Args, 10697 Context.DependentTy, 10698 VK_RValue, 10699 RLoc, false)); 10700 } 10701 10702 // Handle placeholders on both operands. 10703 if (checkPlaceholderForOverload(*this, Args[0])) 10704 return ExprError(); 10705 if (checkPlaceholderForOverload(*this, Args[1])) 10706 return ExprError(); 10707 10708 // Build an empty overload set. 10709 OverloadCandidateSet CandidateSet(LLoc); 10710 10711 // Subscript can only be overloaded as a member function. 10712 10713 // Add operator candidates that are member functions. 10714 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10715 10716 // Add builtin operator candidates. 10717 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10718 10719 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10720 10721 // Perform overload resolution. 10722 OverloadCandidateSet::iterator Best; 10723 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10724 case OR_Success: { 10725 // We found a built-in operator or an overloaded operator. 10726 FunctionDecl *FnDecl = Best->Function; 10727 10728 if (FnDecl) { 10729 // We matched an overloaded operator. Build a call to that 10730 // operator. 10731 10732 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10733 10734 // Convert the arguments. 10735 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10736 ExprResult Arg0 = 10737 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10738 Best->FoundDecl, Method); 10739 if (Arg0.isInvalid()) 10740 return ExprError(); 10741 Args[0] = Arg0.take(); 10742 10743 // Convert the arguments. 10744 ExprResult InputInit 10745 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10746 Context, 10747 FnDecl->getParamDecl(0)), 10748 SourceLocation(), 10749 Owned(Args[1])); 10750 if (InputInit.isInvalid()) 10751 return ExprError(); 10752 10753 Args[1] = InputInit.takeAs<Expr>(); 10754 10755 // Determine the result type 10756 QualType ResultTy = FnDecl->getResultType(); 10757 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10758 ResultTy = ResultTy.getNonLValueExprType(Context); 10759 10760 // Build the actual expression node. 10761 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10762 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10763 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10764 Best->FoundDecl, 10765 HadMultipleCandidates, 10766 OpLocInfo.getLoc(), 10767 OpLocInfo.getInfo()); 10768 if (FnExpr.isInvalid()) 10769 return ExprError(); 10770 10771 CXXOperatorCallExpr *TheCall = 10772 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10773 FnExpr.take(), Args, 10774 ResultTy, VK, RLoc, 10775 false); 10776 10777 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10778 FnDecl)) 10779 return ExprError(); 10780 10781 return MaybeBindToTemporary(TheCall); 10782 } else { 10783 // We matched a built-in operator. Convert the arguments, then 10784 // break out so that we will build the appropriate built-in 10785 // operator node. 10786 ExprResult ArgsRes0 = 10787 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10788 Best->Conversions[0], AA_Passing); 10789 if (ArgsRes0.isInvalid()) 10790 return ExprError(); 10791 Args[0] = ArgsRes0.take(); 10792 10793 ExprResult ArgsRes1 = 10794 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10795 Best->Conversions[1], AA_Passing); 10796 if (ArgsRes1.isInvalid()) 10797 return ExprError(); 10798 Args[1] = ArgsRes1.take(); 10799 10800 break; 10801 } 10802 } 10803 10804 case OR_No_Viable_Function: { 10805 if (CandidateSet.empty()) 10806 Diag(LLoc, diag::err_ovl_no_oper) 10807 << Args[0]->getType() << /*subscript*/ 0 10808 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10809 else 10810 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10811 << Args[0]->getType() 10812 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10813 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10814 "[]", LLoc); 10815 return ExprError(); 10816 } 10817 10818 case OR_Ambiguous: 10819 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10820 << "[]" 10821 << Args[0]->getType() << Args[1]->getType() 10822 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10823 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10824 "[]", LLoc); 10825 return ExprError(); 10826 10827 case OR_Deleted: 10828 Diag(LLoc, diag::err_ovl_deleted_oper) 10829 << Best->Function->isDeleted() << "[]" 10830 << getDeletedOrUnavailableSuffix(Best->Function) 10831 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10832 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10833 "[]", LLoc); 10834 return ExprError(); 10835 } 10836 10837 // We matched a built-in operator; build it. 10838 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10839} 10840 10841/// BuildCallToMemberFunction - Build a call to a member 10842/// function. MemExpr is the expression that refers to the member 10843/// function (and includes the object parameter), Args/NumArgs are the 10844/// arguments to the function call (not including the object 10845/// parameter). The caller needs to validate that the member 10846/// expression refers to a non-static member function or an overloaded 10847/// member function. 10848ExprResult 10849Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10850 SourceLocation LParenLoc, 10851 MultiExprArg Args, 10852 SourceLocation RParenLoc) { 10853 assert(MemExprE->getType() == Context.BoundMemberTy || 10854 MemExprE->getType() == Context.OverloadTy); 10855 10856 // Dig out the member expression. This holds both the object 10857 // argument and the member function we're referring to. 10858 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10859 10860 // Determine whether this is a call to a pointer-to-member function. 10861 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10862 assert(op->getType() == Context.BoundMemberTy); 10863 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10864 10865 QualType fnType = 10866 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10867 10868 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10869 QualType resultType = proto->getCallResultType(Context); 10870 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10871 10872 // Check that the object type isn't more qualified than the 10873 // member function we're calling. 10874 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10875 10876 QualType objectType = op->getLHS()->getType(); 10877 if (op->getOpcode() == BO_PtrMemI) 10878 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10879 Qualifiers objectQuals = objectType.getQualifiers(); 10880 10881 Qualifiers difference = objectQuals - funcQuals; 10882 difference.removeObjCGCAttr(); 10883 difference.removeAddressSpace(); 10884 if (difference) { 10885 std::string qualsString = difference.getAsString(); 10886 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10887 << fnType.getUnqualifiedType() 10888 << qualsString 10889 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10890 } 10891 10892 CXXMemberCallExpr *call 10893 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 10894 resultType, valueKind, RParenLoc); 10895 10896 if (CheckCallReturnType(proto->getResultType(), 10897 op->getRHS()->getLocStart(), 10898 call, 0)) 10899 return ExprError(); 10900 10901 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc)) 10902 return ExprError(); 10903 10904 if (CheckOtherCall(call, proto)) 10905 return ExprError(); 10906 10907 return MaybeBindToTemporary(call); 10908 } 10909 10910 UnbridgedCastsSet UnbridgedCasts; 10911 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 10912 return ExprError(); 10913 10914 MemberExpr *MemExpr; 10915 CXXMethodDecl *Method = 0; 10916 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10917 NestedNameSpecifier *Qualifier = 0; 10918 if (isa<MemberExpr>(NakedMemExpr)) { 10919 MemExpr = cast<MemberExpr>(NakedMemExpr); 10920 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10921 FoundDecl = MemExpr->getFoundDecl(); 10922 Qualifier = MemExpr->getQualifier(); 10923 UnbridgedCasts.restore(); 10924 } else { 10925 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10926 Qualifier = UnresExpr->getQualifier(); 10927 10928 QualType ObjectType = UnresExpr->getBaseType(); 10929 Expr::Classification ObjectClassification 10930 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10931 : UnresExpr->getBase()->Classify(Context); 10932 10933 // Add overload candidates 10934 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10935 10936 // FIXME: avoid copy. 10937 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10938 if (UnresExpr->hasExplicitTemplateArgs()) { 10939 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10940 TemplateArgs = &TemplateArgsBuffer; 10941 } 10942 10943 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10944 E = UnresExpr->decls_end(); I != E; ++I) { 10945 10946 NamedDecl *Func = *I; 10947 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10948 if (isa<UsingShadowDecl>(Func)) 10949 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10950 10951 10952 // Microsoft supports direct constructor calls. 10953 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10954 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10955 Args, CandidateSet); 10956 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10957 // If explicit template arguments were provided, we can't call a 10958 // non-template member function. 10959 if (TemplateArgs) 10960 continue; 10961 10962 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10963 ObjectClassification, Args, CandidateSet, 10964 /*SuppressUserConversions=*/false); 10965 } else { 10966 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10967 I.getPair(), ActingDC, TemplateArgs, 10968 ObjectType, ObjectClassification, 10969 Args, CandidateSet, 10970 /*SuppressUsedConversions=*/false); 10971 } 10972 } 10973 10974 DeclarationName DeclName = UnresExpr->getMemberName(); 10975 10976 UnbridgedCasts.restore(); 10977 10978 OverloadCandidateSet::iterator Best; 10979 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10980 Best)) { 10981 case OR_Success: 10982 Method = cast<CXXMethodDecl>(Best->Function); 10983 FoundDecl = Best->FoundDecl; 10984 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10985 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 10986 return ExprError(); 10987 // If FoundDecl is different from Method (such as if one is a template 10988 // and the other a specialization), make sure DiagnoseUseOfDecl is 10989 // called on both. 10990 // FIXME: This would be more comprehensively addressed by modifying 10991 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 10992 // being used. 10993 if (Method != FoundDecl.getDecl() && 10994 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 10995 return ExprError(); 10996 break; 10997 10998 case OR_No_Viable_Function: 10999 Diag(UnresExpr->getMemberLoc(), 11000 diag::err_ovl_no_viable_member_function_in_call) 11001 << DeclName << MemExprE->getSourceRange(); 11002 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11003 // FIXME: Leaking incoming expressions! 11004 return ExprError(); 11005 11006 case OR_Ambiguous: 11007 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11008 << DeclName << MemExprE->getSourceRange(); 11009 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11010 // FIXME: Leaking incoming expressions! 11011 return ExprError(); 11012 11013 case OR_Deleted: 11014 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11015 << Best->Function->isDeleted() 11016 << DeclName 11017 << getDeletedOrUnavailableSuffix(Best->Function) 11018 << MemExprE->getSourceRange(); 11019 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11020 // FIXME: Leaking incoming expressions! 11021 return ExprError(); 11022 } 11023 11024 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11025 11026 // If overload resolution picked a static member, build a 11027 // non-member call based on that function. 11028 if (Method->isStatic()) { 11029 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11030 RParenLoc); 11031 } 11032 11033 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11034 } 11035 11036 QualType ResultType = Method->getResultType(); 11037 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11038 ResultType = ResultType.getNonLValueExprType(Context); 11039 11040 assert(Method && "Member call to something that isn't a method?"); 11041 CXXMemberCallExpr *TheCall = 11042 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11043 ResultType, VK, RParenLoc); 11044 11045 // Check for a valid return type. 11046 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 11047 TheCall, Method)) 11048 return ExprError(); 11049 11050 // Convert the object argument (for a non-static member function call). 11051 // We only need to do this if there was actually an overload; otherwise 11052 // it was done at lookup. 11053 if (!Method->isStatic()) { 11054 ExprResult ObjectArg = 11055 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11056 FoundDecl, Method); 11057 if (ObjectArg.isInvalid()) 11058 return ExprError(); 11059 MemExpr->setBase(ObjectArg.take()); 11060 } 11061 11062 // Convert the rest of the arguments 11063 const FunctionProtoType *Proto = 11064 Method->getType()->getAs<FunctionProtoType>(); 11065 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11066 RParenLoc)) 11067 return ExprError(); 11068 11069 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11070 11071 if (CheckFunctionCall(Method, TheCall, Proto)) 11072 return ExprError(); 11073 11074 if ((isa<CXXConstructorDecl>(CurContext) || 11075 isa<CXXDestructorDecl>(CurContext)) && 11076 TheCall->getMethodDecl()->isPure()) { 11077 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11078 11079 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11080 Diag(MemExpr->getLocStart(), 11081 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11082 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11083 << MD->getParent()->getDeclName(); 11084 11085 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11086 } 11087 } 11088 return MaybeBindToTemporary(TheCall); 11089} 11090 11091/// BuildCallToObjectOfClassType - Build a call to an object of class 11092/// type (C++ [over.call.object]), which can end up invoking an 11093/// overloaded function call operator (@c operator()) or performing a 11094/// user-defined conversion on the object argument. 11095ExprResult 11096Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11097 SourceLocation LParenLoc, 11098 MultiExprArg Args, 11099 SourceLocation RParenLoc) { 11100 if (checkPlaceholderForOverload(*this, Obj)) 11101 return ExprError(); 11102 ExprResult Object = Owned(Obj); 11103 11104 UnbridgedCastsSet UnbridgedCasts; 11105 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11106 return ExprError(); 11107 11108 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 11109 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11110 11111 // C++ [over.call.object]p1: 11112 // If the primary-expression E in the function call syntax 11113 // evaluates to a class object of type "cv T", then the set of 11114 // candidate functions includes at least the function call 11115 // operators of T. The function call operators of T are obtained by 11116 // ordinary lookup of the name operator() in the context of 11117 // (E).operator(). 11118 OverloadCandidateSet CandidateSet(LParenLoc); 11119 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11120 11121 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11122 diag::err_incomplete_object_call, Object.get())) 11123 return true; 11124 11125 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11126 LookupQualifiedName(R, Record->getDecl()); 11127 R.suppressDiagnostics(); 11128 11129 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11130 Oper != OperEnd; ++Oper) { 11131 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11132 Object.get()->Classify(Context), 11133 Args, CandidateSet, 11134 /*SuppressUserConversions=*/ false); 11135 } 11136 11137 // C++ [over.call.object]p2: 11138 // In addition, for each (non-explicit in C++0x) conversion function 11139 // declared in T of the form 11140 // 11141 // operator conversion-type-id () cv-qualifier; 11142 // 11143 // where cv-qualifier is the same cv-qualification as, or a 11144 // greater cv-qualification than, cv, and where conversion-type-id 11145 // denotes the type "pointer to function of (P1,...,Pn) returning 11146 // R", or the type "reference to pointer to function of 11147 // (P1,...,Pn) returning R", or the type "reference to function 11148 // of (P1,...,Pn) returning R", a surrogate call function [...] 11149 // is also considered as a candidate function. Similarly, 11150 // surrogate call functions are added to the set of candidate 11151 // functions for each conversion function declared in an 11152 // accessible base class provided the function is not hidden 11153 // within T by another intervening declaration. 11154 std::pair<CXXRecordDecl::conversion_iterator, 11155 CXXRecordDecl::conversion_iterator> Conversions 11156 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11157 for (CXXRecordDecl::conversion_iterator 11158 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11159 NamedDecl *D = *I; 11160 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11161 if (isa<UsingShadowDecl>(D)) 11162 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11163 11164 // Skip over templated conversion functions; they aren't 11165 // surrogates. 11166 if (isa<FunctionTemplateDecl>(D)) 11167 continue; 11168 11169 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11170 if (!Conv->isExplicit()) { 11171 // Strip the reference type (if any) and then the pointer type (if 11172 // any) to get down to what might be a function type. 11173 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11174 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11175 ConvType = ConvPtrType->getPointeeType(); 11176 11177 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11178 { 11179 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11180 Object.get(), Args, CandidateSet); 11181 } 11182 } 11183 } 11184 11185 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11186 11187 // Perform overload resolution. 11188 OverloadCandidateSet::iterator Best; 11189 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11190 Best)) { 11191 case OR_Success: 11192 // Overload resolution succeeded; we'll build the appropriate call 11193 // below. 11194 break; 11195 11196 case OR_No_Viable_Function: 11197 if (CandidateSet.empty()) 11198 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11199 << Object.get()->getType() << /*call*/ 1 11200 << Object.get()->getSourceRange(); 11201 else 11202 Diag(Object.get()->getLocStart(), 11203 diag::err_ovl_no_viable_object_call) 11204 << Object.get()->getType() << Object.get()->getSourceRange(); 11205 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11206 break; 11207 11208 case OR_Ambiguous: 11209 Diag(Object.get()->getLocStart(), 11210 diag::err_ovl_ambiguous_object_call) 11211 << Object.get()->getType() << Object.get()->getSourceRange(); 11212 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11213 break; 11214 11215 case OR_Deleted: 11216 Diag(Object.get()->getLocStart(), 11217 diag::err_ovl_deleted_object_call) 11218 << Best->Function->isDeleted() 11219 << Object.get()->getType() 11220 << getDeletedOrUnavailableSuffix(Best->Function) 11221 << Object.get()->getSourceRange(); 11222 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11223 break; 11224 } 11225 11226 if (Best == CandidateSet.end()) 11227 return true; 11228 11229 UnbridgedCasts.restore(); 11230 11231 if (Best->Function == 0) { 11232 // Since there is no function declaration, this is one of the 11233 // surrogate candidates. Dig out the conversion function. 11234 CXXConversionDecl *Conv 11235 = cast<CXXConversionDecl>( 11236 Best->Conversions[0].UserDefined.ConversionFunction); 11237 11238 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11239 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11240 return ExprError(); 11241 assert(Conv == Best->FoundDecl.getDecl() && 11242 "Found Decl & conversion-to-functionptr should be same, right?!"); 11243 // We selected one of the surrogate functions that converts the 11244 // object parameter to a function pointer. Perform the conversion 11245 // on the object argument, then let ActOnCallExpr finish the job. 11246 11247 // Create an implicit member expr to refer to the conversion operator. 11248 // and then call it. 11249 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11250 Conv, HadMultipleCandidates); 11251 if (Call.isInvalid()) 11252 return ExprError(); 11253 // Record usage of conversion in an implicit cast. 11254 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11255 CK_UserDefinedConversion, 11256 Call.get(), 0, VK_RValue)); 11257 11258 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11259 } 11260 11261 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11262 11263 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11264 // that calls this method, using Object for the implicit object 11265 // parameter and passing along the remaining arguments. 11266 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11267 11268 // An error diagnostic has already been printed when parsing the declaration. 11269 if (Method->isInvalidDecl()) 11270 return ExprError(); 11271 11272 const FunctionProtoType *Proto = 11273 Method->getType()->getAs<FunctionProtoType>(); 11274 11275 unsigned NumArgsInProto = Proto->getNumArgs(); 11276 unsigned NumArgsToCheck = Args.size(); 11277 11278 // Build the full argument list for the method call (the 11279 // implicit object parameter is placed at the beginning of the 11280 // list). 11281 Expr **MethodArgs; 11282 if (Args.size() < NumArgsInProto) { 11283 NumArgsToCheck = NumArgsInProto; 11284 MethodArgs = new Expr*[NumArgsInProto + 1]; 11285 } else { 11286 MethodArgs = new Expr*[Args.size() + 1]; 11287 } 11288 MethodArgs[0] = Object.get(); 11289 for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx) 11290 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 11291 11292 DeclarationNameInfo OpLocInfo( 11293 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11294 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11295 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11296 HadMultipleCandidates, 11297 OpLocInfo.getLoc(), 11298 OpLocInfo.getInfo()); 11299 if (NewFn.isInvalid()) 11300 return true; 11301 11302 // Once we've built TheCall, all of the expressions are properly 11303 // owned. 11304 QualType ResultTy = Method->getResultType(); 11305 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11306 ResultTy = ResultTy.getNonLValueExprType(Context); 11307 11308 CXXOperatorCallExpr *TheCall = 11309 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11310 llvm::makeArrayRef(MethodArgs, Args.size()+1), 11311 ResultTy, VK, RParenLoc, false); 11312 delete [] MethodArgs; 11313 11314 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11315 Method)) 11316 return true; 11317 11318 // We may have default arguments. If so, we need to allocate more 11319 // slots in the call for them. 11320 if (Args.size() < NumArgsInProto) 11321 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11322 else if (Args.size() > NumArgsInProto) 11323 NumArgsToCheck = NumArgsInProto; 11324 11325 bool IsError = false; 11326 11327 // Initialize the implicit object parameter. 11328 ExprResult ObjRes = 11329 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11330 Best->FoundDecl, Method); 11331 if (ObjRes.isInvalid()) 11332 IsError = true; 11333 else 11334 Object = ObjRes; 11335 TheCall->setArg(0, Object.take()); 11336 11337 // Check the argument types. 11338 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11339 Expr *Arg; 11340 if (i < Args.size()) { 11341 Arg = Args[i]; 11342 11343 // Pass the argument. 11344 11345 ExprResult InputInit 11346 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11347 Context, 11348 Method->getParamDecl(i)), 11349 SourceLocation(), Arg); 11350 11351 IsError |= InputInit.isInvalid(); 11352 Arg = InputInit.takeAs<Expr>(); 11353 } else { 11354 ExprResult DefArg 11355 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11356 if (DefArg.isInvalid()) { 11357 IsError = true; 11358 break; 11359 } 11360 11361 Arg = DefArg.takeAs<Expr>(); 11362 } 11363 11364 TheCall->setArg(i + 1, Arg); 11365 } 11366 11367 // If this is a variadic call, handle args passed through "...". 11368 if (Proto->isVariadic()) { 11369 // Promote the arguments (C99 6.5.2.2p7). 11370 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) { 11371 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11372 IsError |= Arg.isInvalid(); 11373 TheCall->setArg(i + 1, Arg.take()); 11374 } 11375 } 11376 11377 if (IsError) return true; 11378 11379 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11380 11381 if (CheckFunctionCall(Method, TheCall, Proto)) 11382 return true; 11383 11384 return MaybeBindToTemporary(TheCall); 11385} 11386 11387/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11388/// (if one exists), where @c Base is an expression of class type and 11389/// @c Member is the name of the member we're trying to find. 11390ExprResult 11391Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11392 assert(Base->getType()->isRecordType() && 11393 "left-hand side must have class type"); 11394 11395 if (checkPlaceholderForOverload(*this, Base)) 11396 return ExprError(); 11397 11398 SourceLocation Loc = Base->getExprLoc(); 11399 11400 // C++ [over.ref]p1: 11401 // 11402 // [...] An expression x->m is interpreted as (x.operator->())->m 11403 // for a class object x of type T if T::operator->() exists and if 11404 // the operator is selected as the best match function by the 11405 // overload resolution mechanism (13.3). 11406 DeclarationName OpName = 11407 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11408 OverloadCandidateSet CandidateSet(Loc); 11409 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11410 11411 if (RequireCompleteType(Loc, Base->getType(), 11412 diag::err_typecheck_incomplete_tag, Base)) 11413 return ExprError(); 11414 11415 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11416 LookupQualifiedName(R, BaseRecord->getDecl()); 11417 R.suppressDiagnostics(); 11418 11419 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11420 Oper != OperEnd; ++Oper) { 11421 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11422 None, CandidateSet, /*SuppressUserConversions=*/false); 11423 } 11424 11425 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11426 11427 // Perform overload resolution. 11428 OverloadCandidateSet::iterator Best; 11429 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11430 case OR_Success: 11431 // Overload resolution succeeded; we'll build the call below. 11432 break; 11433 11434 case OR_No_Viable_Function: 11435 if (CandidateSet.empty()) 11436 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11437 << Base->getType() << Base->getSourceRange(); 11438 else 11439 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11440 << "operator->" << Base->getSourceRange(); 11441 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11442 return ExprError(); 11443 11444 case OR_Ambiguous: 11445 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11446 << "->" << Base->getType() << Base->getSourceRange(); 11447 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11448 return ExprError(); 11449 11450 case OR_Deleted: 11451 Diag(OpLoc, diag::err_ovl_deleted_oper) 11452 << Best->Function->isDeleted() 11453 << "->" 11454 << getDeletedOrUnavailableSuffix(Best->Function) 11455 << Base->getSourceRange(); 11456 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11457 return ExprError(); 11458 } 11459 11460 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11461 11462 // Convert the object parameter. 11463 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11464 ExprResult BaseResult = 11465 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11466 Best->FoundDecl, Method); 11467 if (BaseResult.isInvalid()) 11468 return ExprError(); 11469 Base = BaseResult.take(); 11470 11471 // Build the operator call. 11472 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11473 HadMultipleCandidates, OpLoc); 11474 if (FnExpr.isInvalid()) 11475 return ExprError(); 11476 11477 QualType ResultTy = Method->getResultType(); 11478 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11479 ResultTy = ResultTy.getNonLValueExprType(Context); 11480 CXXOperatorCallExpr *TheCall = 11481 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11482 Base, ResultTy, VK, OpLoc, false); 11483 11484 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11485 Method)) 11486 return ExprError(); 11487 11488 return MaybeBindToTemporary(TheCall); 11489} 11490 11491/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11492/// a literal operator described by the provided lookup results. 11493ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11494 DeclarationNameInfo &SuffixInfo, 11495 ArrayRef<Expr*> Args, 11496 SourceLocation LitEndLoc, 11497 TemplateArgumentListInfo *TemplateArgs) { 11498 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11499 11500 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11501 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11502 TemplateArgs); 11503 11504 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11505 11506 // Perform overload resolution. This will usually be trivial, but might need 11507 // to perform substitutions for a literal operator template. 11508 OverloadCandidateSet::iterator Best; 11509 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11510 case OR_Success: 11511 case OR_Deleted: 11512 break; 11513 11514 case OR_No_Viable_Function: 11515 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11516 << R.getLookupName(); 11517 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11518 return ExprError(); 11519 11520 case OR_Ambiguous: 11521 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11522 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11523 return ExprError(); 11524 } 11525 11526 FunctionDecl *FD = Best->Function; 11527 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11528 HadMultipleCandidates, 11529 SuffixInfo.getLoc(), 11530 SuffixInfo.getInfo()); 11531 if (Fn.isInvalid()) 11532 return true; 11533 11534 // Check the argument types. This should almost always be a no-op, except 11535 // that array-to-pointer decay is applied to string literals. 11536 Expr *ConvArgs[2]; 11537 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 11538 ExprResult InputInit = PerformCopyInitialization( 11539 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11540 SourceLocation(), Args[ArgIdx]); 11541 if (InputInit.isInvalid()) 11542 return true; 11543 ConvArgs[ArgIdx] = InputInit.take(); 11544 } 11545 11546 QualType ResultTy = FD->getResultType(); 11547 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11548 ResultTy = ResultTy.getNonLValueExprType(Context); 11549 11550 UserDefinedLiteral *UDL = 11551 new (Context) UserDefinedLiteral(Context, Fn.take(), 11552 llvm::makeArrayRef(ConvArgs, Args.size()), 11553 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11554 11555 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11556 return ExprError(); 11557 11558 if (CheckFunctionCall(FD, UDL, NULL)) 11559 return ExprError(); 11560 11561 return MaybeBindToTemporary(UDL); 11562} 11563 11564/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11565/// given LookupResult is non-empty, it is assumed to describe a member which 11566/// will be invoked. Otherwise, the function will be found via argument 11567/// dependent lookup. 11568/// CallExpr is set to a valid expression and FRS_Success returned on success, 11569/// otherwise CallExpr is set to ExprError() and some non-success value 11570/// is returned. 11571Sema::ForRangeStatus 11572Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11573 SourceLocation RangeLoc, VarDecl *Decl, 11574 BeginEndFunction BEF, 11575 const DeclarationNameInfo &NameInfo, 11576 LookupResult &MemberLookup, 11577 OverloadCandidateSet *CandidateSet, 11578 Expr *Range, ExprResult *CallExpr) { 11579 CandidateSet->clear(); 11580 if (!MemberLookup.empty()) { 11581 ExprResult MemberRef = 11582 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11583 /*IsPtr=*/false, CXXScopeSpec(), 11584 /*TemplateKWLoc=*/SourceLocation(), 11585 /*FirstQualifierInScope=*/0, 11586 MemberLookup, 11587 /*TemplateArgs=*/0); 11588 if (MemberRef.isInvalid()) { 11589 *CallExpr = ExprError(); 11590 Diag(Range->getLocStart(), diag::note_in_for_range) 11591 << RangeLoc << BEF << Range->getType(); 11592 return FRS_DiagnosticIssued; 11593 } 11594 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0); 11595 if (CallExpr->isInvalid()) { 11596 *CallExpr = ExprError(); 11597 Diag(Range->getLocStart(), diag::note_in_for_range) 11598 << RangeLoc << BEF << Range->getType(); 11599 return FRS_DiagnosticIssued; 11600 } 11601 } else { 11602 UnresolvedSet<0> FoundNames; 11603 UnresolvedLookupExpr *Fn = 11604 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11605 NestedNameSpecifierLoc(), NameInfo, 11606 /*NeedsADL=*/true, /*Overloaded=*/false, 11607 FoundNames.begin(), FoundNames.end()); 11608 11609 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 11610 CandidateSet, CallExpr); 11611 if (CandidateSet->empty() || CandidateSetError) { 11612 *CallExpr = ExprError(); 11613 return FRS_NoViableFunction; 11614 } 11615 OverloadCandidateSet::iterator Best; 11616 OverloadingResult OverloadResult = 11617 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11618 11619 if (OverloadResult == OR_No_Viable_Function) { 11620 *CallExpr = ExprError(); 11621 return FRS_NoViableFunction; 11622 } 11623 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 11624 Loc, 0, CandidateSet, &Best, 11625 OverloadResult, 11626 /*AllowTypoCorrection=*/false); 11627 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11628 *CallExpr = ExprError(); 11629 Diag(Range->getLocStart(), diag::note_in_for_range) 11630 << RangeLoc << BEF << Range->getType(); 11631 return FRS_DiagnosticIssued; 11632 } 11633 } 11634 return FRS_Success; 11635} 11636 11637 11638/// FixOverloadedFunctionReference - E is an expression that refers to 11639/// a C++ overloaded function (possibly with some parentheses and 11640/// perhaps a '&' around it). We have resolved the overloaded function 11641/// to the function declaration Fn, so patch up the expression E to 11642/// refer (possibly indirectly) to Fn. Returns the new expr. 11643Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11644 FunctionDecl *Fn) { 11645 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11646 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11647 Found, Fn); 11648 if (SubExpr == PE->getSubExpr()) 11649 return PE; 11650 11651 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11652 } 11653 11654 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11655 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11656 Found, Fn); 11657 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11658 SubExpr->getType()) && 11659 "Implicit cast type cannot be determined from overload"); 11660 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11661 if (SubExpr == ICE->getSubExpr()) 11662 return ICE; 11663 11664 return ImplicitCastExpr::Create(Context, ICE->getType(), 11665 ICE->getCastKind(), 11666 SubExpr, 0, 11667 ICE->getValueKind()); 11668 } 11669 11670 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11671 assert(UnOp->getOpcode() == UO_AddrOf && 11672 "Can only take the address of an overloaded function"); 11673 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11674 if (Method->isStatic()) { 11675 // Do nothing: static member functions aren't any different 11676 // from non-member functions. 11677 } else { 11678 // Fix the sub expression, which really has to be an 11679 // UnresolvedLookupExpr holding an overloaded member function 11680 // or template. 11681 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11682 Found, Fn); 11683 if (SubExpr == UnOp->getSubExpr()) 11684 return UnOp; 11685 11686 assert(isa<DeclRefExpr>(SubExpr) 11687 && "fixed to something other than a decl ref"); 11688 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11689 && "fixed to a member ref with no nested name qualifier"); 11690 11691 // We have taken the address of a pointer to member 11692 // function. Perform the computation here so that we get the 11693 // appropriate pointer to member type. 11694 QualType ClassType 11695 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11696 QualType MemPtrType 11697 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11698 11699 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11700 VK_RValue, OK_Ordinary, 11701 UnOp->getOperatorLoc()); 11702 } 11703 } 11704 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11705 Found, Fn); 11706 if (SubExpr == UnOp->getSubExpr()) 11707 return UnOp; 11708 11709 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11710 Context.getPointerType(SubExpr->getType()), 11711 VK_RValue, OK_Ordinary, 11712 UnOp->getOperatorLoc()); 11713 } 11714 11715 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11716 // FIXME: avoid copy. 11717 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11718 if (ULE->hasExplicitTemplateArgs()) { 11719 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11720 TemplateArgs = &TemplateArgsBuffer; 11721 } 11722 11723 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11724 ULE->getQualifierLoc(), 11725 ULE->getTemplateKeywordLoc(), 11726 Fn, 11727 /*enclosing*/ false, // FIXME? 11728 ULE->getNameLoc(), 11729 Fn->getType(), 11730 VK_LValue, 11731 Found.getDecl(), 11732 TemplateArgs); 11733 MarkDeclRefReferenced(DRE); 11734 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11735 return DRE; 11736 } 11737 11738 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11739 // FIXME: avoid copy. 11740 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11741 if (MemExpr->hasExplicitTemplateArgs()) { 11742 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11743 TemplateArgs = &TemplateArgsBuffer; 11744 } 11745 11746 Expr *Base; 11747 11748 // If we're filling in a static method where we used to have an 11749 // implicit member access, rewrite to a simple decl ref. 11750 if (MemExpr->isImplicitAccess()) { 11751 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11752 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11753 MemExpr->getQualifierLoc(), 11754 MemExpr->getTemplateKeywordLoc(), 11755 Fn, 11756 /*enclosing*/ false, 11757 MemExpr->getMemberLoc(), 11758 Fn->getType(), 11759 VK_LValue, 11760 Found.getDecl(), 11761 TemplateArgs); 11762 MarkDeclRefReferenced(DRE); 11763 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11764 return DRE; 11765 } else { 11766 SourceLocation Loc = MemExpr->getMemberLoc(); 11767 if (MemExpr->getQualifier()) 11768 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11769 CheckCXXThisCapture(Loc); 11770 Base = new (Context) CXXThisExpr(Loc, 11771 MemExpr->getBaseType(), 11772 /*isImplicit=*/true); 11773 } 11774 } else 11775 Base = MemExpr->getBase(); 11776 11777 ExprValueKind valueKind; 11778 QualType type; 11779 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11780 valueKind = VK_LValue; 11781 type = Fn->getType(); 11782 } else { 11783 valueKind = VK_RValue; 11784 type = Context.BoundMemberTy; 11785 } 11786 11787 MemberExpr *ME = MemberExpr::Create(Context, Base, 11788 MemExpr->isArrow(), 11789 MemExpr->getQualifierLoc(), 11790 MemExpr->getTemplateKeywordLoc(), 11791 Fn, 11792 Found, 11793 MemExpr->getMemberNameInfo(), 11794 TemplateArgs, 11795 type, valueKind, OK_Ordinary); 11796 ME->setHadMultipleCandidates(true); 11797 MarkMemberReferenced(ME); 11798 return ME; 11799 } 11800 11801 llvm_unreachable("Invalid reference to overloaded function"); 11802} 11803 11804ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11805 DeclAccessPair Found, 11806 FunctionDecl *Fn) { 11807 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11808} 11809 11810} // end namespace clang 11811