SemaOverload.cpp revision ae19fbba559d8199d1f2b7154863180b0ae22ac7
1//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===// 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/SemaInternal.h" 15#include "clang/Sema/Lookup.h" 16#include "clang/Sema/Initialization.h" 17#include "clang/Sema/Template.h" 18#include "clang/Sema/TemplateDeduction.h" 19#include "clang/Basic/Diagnostic.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/CXXInheritance.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/AST/Expr.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/ExprObjC.h" 27#include "clang/AST/TypeOrdering.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "llvm/ADT/DenseSet.h" 30#include "llvm/ADT/SmallPtrSet.h" 31#include "llvm/ADT/SmallString.h" 32#include "llvm/ADT/STLExtras.h" 33#include <algorithm> 34 35namespace clang { 36using namespace sema; 37 38/// A convenience routine for creating a decayed reference to a 39/// function. 40static ExprResult 41CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates, 42 SourceLocation Loc = SourceLocation(), 43 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 44 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 45 VK_LValue, Loc, LocInfo); 46 if (HadMultipleCandidates) 47 DRE->setHadMultipleCandidates(true); 48 ExprResult E = S.Owned(DRE); 49 E = S.DefaultFunctionArrayConversion(E.take()); 50 if (E.isInvalid()) 51 return ExprError(); 52 return E; 53} 54 55static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 56 bool InOverloadResolution, 57 StandardConversionSequence &SCS, 58 bool CStyle, 59 bool AllowObjCWritebackConversion); 60 61static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 62 QualType &ToType, 63 bool InOverloadResolution, 64 StandardConversionSequence &SCS, 65 bool CStyle); 66static OverloadingResult 67IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 68 UserDefinedConversionSequence& User, 69 OverloadCandidateSet& Conversions, 70 bool AllowExplicit); 71 72 73static ImplicitConversionSequence::CompareKind 74CompareStandardConversionSequences(Sema &S, 75 const StandardConversionSequence& SCS1, 76 const StandardConversionSequence& SCS2); 77 78static ImplicitConversionSequence::CompareKind 79CompareQualificationConversions(Sema &S, 80 const StandardConversionSequence& SCS1, 81 const StandardConversionSequence& SCS2); 82 83static ImplicitConversionSequence::CompareKind 84CompareDerivedToBaseConversions(Sema &S, 85 const StandardConversionSequence& SCS1, 86 const StandardConversionSequence& SCS2); 87 88 89 90/// GetConversionCategory - Retrieve the implicit conversion 91/// category corresponding to the given implicit conversion kind. 92ImplicitConversionCategory 93GetConversionCategory(ImplicitConversionKind Kind) { 94 static const ImplicitConversionCategory 95 Category[(int)ICK_Num_Conversion_Kinds] = { 96 ICC_Identity, 97 ICC_Lvalue_Transformation, 98 ICC_Lvalue_Transformation, 99 ICC_Lvalue_Transformation, 100 ICC_Identity, 101 ICC_Qualification_Adjustment, 102 ICC_Promotion, 103 ICC_Promotion, 104 ICC_Promotion, 105 ICC_Conversion, 106 ICC_Conversion, 107 ICC_Conversion, 108 ICC_Conversion, 109 ICC_Conversion, 110 ICC_Conversion, 111 ICC_Conversion, 112 ICC_Conversion, 113 ICC_Conversion, 114 ICC_Conversion, 115 ICC_Conversion, 116 ICC_Conversion, 117 ICC_Conversion 118 }; 119 return Category[(int)Kind]; 120} 121 122/// GetConversionRank - Retrieve the implicit conversion rank 123/// corresponding to the given implicit conversion kind. 124ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 125 static const ImplicitConversionRank 126 Rank[(int)ICK_Num_Conversion_Kinds] = { 127 ICR_Exact_Match, 128 ICR_Exact_Match, 129 ICR_Exact_Match, 130 ICR_Exact_Match, 131 ICR_Exact_Match, 132 ICR_Exact_Match, 133 ICR_Promotion, 134 ICR_Promotion, 135 ICR_Promotion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Conversion, 146 ICR_Conversion, 147 ICR_Complex_Real_Conversion, 148 ICR_Conversion, 149 ICR_Conversion, 150 ICR_Writeback_Conversion 151 }; 152 return Rank[(int)Kind]; 153} 154 155/// GetImplicitConversionName - Return the name of this kind of 156/// implicit conversion. 157const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 159 "No conversion", 160 "Lvalue-to-rvalue", 161 "Array-to-pointer", 162 "Function-to-pointer", 163 "Noreturn adjustment", 164 "Qualification", 165 "Integral promotion", 166 "Floating point promotion", 167 "Complex promotion", 168 "Integral conversion", 169 "Floating conversion", 170 "Complex conversion", 171 "Floating-integral conversion", 172 "Pointer conversion", 173 "Pointer-to-member conversion", 174 "Boolean conversion", 175 "Compatible-types conversion", 176 "Derived-to-base conversion", 177 "Vector conversion", 178 "Vector splat", 179 "Complex-real conversion", 180 "Block Pointer conversion", 181 "Transparent Union Conversion" 182 "Writeback conversion" 183 }; 184 return Name[Kind]; 185} 186 187/// StandardConversionSequence - Set the standard conversion 188/// sequence to the identity conversion. 189void StandardConversionSequence::setAsIdentityConversion() { 190 First = ICK_Identity; 191 Second = ICK_Identity; 192 Third = ICK_Identity; 193 DeprecatedStringLiteralToCharPtr = false; 194 QualificationIncludesObjCLifetime = false; 195 ReferenceBinding = false; 196 DirectBinding = false; 197 IsLvalueReference = true; 198 BindsToFunctionLvalue = false; 199 BindsToRvalue = false; 200 BindsImplicitObjectArgumentWithoutRefQualifier = false; 201 ObjCLifetimeConversionBinding = false; 202 CopyConstructor = 0; 203} 204 205/// getRank - Retrieve the rank of this standard conversion sequence 206/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 207/// implicit conversions. 208ImplicitConversionRank StandardConversionSequence::getRank() const { 209 ImplicitConversionRank Rank = ICR_Exact_Match; 210 if (GetConversionRank(First) > Rank) 211 Rank = GetConversionRank(First); 212 if (GetConversionRank(Second) > Rank) 213 Rank = GetConversionRank(Second); 214 if (GetConversionRank(Third) > Rank) 215 Rank = GetConversionRank(Third); 216 return Rank; 217} 218 219/// isPointerConversionToBool - Determines whether this conversion is 220/// a conversion of a pointer or pointer-to-member to bool. This is 221/// used as part of the ranking of standard conversion sequences 222/// (C++ 13.3.3.2p4). 223bool StandardConversionSequence::isPointerConversionToBool() const { 224 // Note that FromType has not necessarily been transformed by the 225 // array-to-pointer or function-to-pointer implicit conversions, so 226 // check for their presence as well as checking whether FromType is 227 // a pointer. 228 if (getToType(1)->isBooleanType() && 229 (getFromType()->isPointerType() || 230 getFromType()->isObjCObjectPointerType() || 231 getFromType()->isBlockPointerType() || 232 getFromType()->isNullPtrType() || 233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 234 return true; 235 236 return false; 237} 238 239/// isPointerConversionToVoidPointer - Determines whether this 240/// conversion is a conversion of a pointer to a void pointer. This is 241/// used as part of the ranking of standard conversion sequences (C++ 242/// 13.3.3.2p4). 243bool 244StandardConversionSequence:: 245isPointerConversionToVoidPointer(ASTContext& Context) const { 246 QualType FromType = getFromType(); 247 QualType ToType = getToType(1); 248 249 // Note that FromType has not necessarily been transformed by the 250 // array-to-pointer implicit conversion, so check for its presence 251 // and redo the conversion to get a pointer. 252 if (First == ICK_Array_To_Pointer) 253 FromType = Context.getArrayDecayedType(FromType); 254 255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 257 return ToPtrType->getPointeeType()->isVoidType(); 258 259 return false; 260} 261 262/// Skip any implicit casts which could be either part of a narrowing conversion 263/// or after one in an implicit conversion. 264static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 265 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 266 switch (ICE->getCastKind()) { 267 case CK_NoOp: 268 case CK_IntegralCast: 269 case CK_IntegralToBoolean: 270 case CK_IntegralToFloating: 271 case CK_FloatingToIntegral: 272 case CK_FloatingToBoolean: 273 case CK_FloatingCast: 274 Converted = ICE->getSubExpr(); 275 continue; 276 277 default: 278 return Converted; 279 } 280 } 281 282 return Converted; 283} 284 285/// Check if this standard conversion sequence represents a narrowing 286/// conversion, according to C++11 [dcl.init.list]p7. 287/// 288/// \param Ctx The AST context. 289/// \param Converted The result of applying this standard conversion sequence. 290/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 291/// value of the expression prior to the narrowing conversion. 292/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 293/// type of the expression prior to the narrowing conversion. 294NarrowingKind 295StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 296 const Expr *Converted, 297 APValue &ConstantValue, 298 QualType &ConstantType) const { 299 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 300 301 // C++11 [dcl.init.list]p7: 302 // A narrowing conversion is an implicit conversion ... 303 QualType FromType = getToType(0); 304 QualType ToType = getToType(1); 305 switch (Second) { 306 // -- from a floating-point type to an integer type, or 307 // 308 // -- from an integer type or unscoped enumeration type to a floating-point 309 // type, except where the source is a constant expression and the actual 310 // value after conversion will fit into the target type and will produce 311 // the original value when converted back to the original type, or 312 case ICK_Floating_Integral: 313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 314 return NK_Type_Narrowing; 315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 316 llvm::APSInt IntConstantValue; 317 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 318 if (Initializer && 319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 320 // Convert the integer to the floating type. 321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 323 llvm::APFloat::rmNearestTiesToEven); 324 // And back. 325 llvm::APSInt ConvertedValue = IntConstantValue; 326 bool ignored; 327 Result.convertToInteger(ConvertedValue, 328 llvm::APFloat::rmTowardZero, &ignored); 329 // If the resulting value is different, this was a narrowing conversion. 330 if (IntConstantValue != ConvertedValue) { 331 ConstantValue = APValue(IntConstantValue); 332 ConstantType = Initializer->getType(); 333 return NK_Constant_Narrowing; 334 } 335 } else { 336 // Variables are always narrowings. 337 return NK_Variable_Narrowing; 338 } 339 } 340 return NK_Not_Narrowing; 341 342 // -- from long double to double or float, or from double to float, except 343 // where the source is a constant expression and the actual value after 344 // conversion is within the range of values that can be represented (even 345 // if it cannot be represented exactly), or 346 case ICK_Floating_Conversion: 347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 349 // FromType is larger than ToType. 350 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 352 // Constant! 353 assert(ConstantValue.isFloat()); 354 llvm::APFloat FloatVal = ConstantValue.getFloat(); 355 // Convert the source value into the target type. 356 bool ignored; 357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 358 Ctx.getFloatTypeSemantics(ToType), 359 llvm::APFloat::rmNearestTiesToEven, &ignored); 360 // If there was no overflow, the source value is within the range of 361 // values that can be represented. 362 if (ConvertStatus & llvm::APFloat::opOverflow) { 363 ConstantType = Initializer->getType(); 364 return NK_Constant_Narrowing; 365 } 366 } else { 367 return NK_Variable_Narrowing; 368 } 369 } 370 return NK_Not_Narrowing; 371 372 // -- from an integer type or unscoped enumeration type to an integer type 373 // that cannot represent all the values of the original type, except where 374 // the source is a constant expression and the actual value after 375 // conversion will fit into the target type and will produce the original 376 // value when converted back to the original type. 377 case ICK_Boolean_Conversion: // Bools are integers too. 378 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 379 // Boolean conversions can be from pointers and pointers to members 380 // [conv.bool], and those aren't considered narrowing conversions. 381 return NK_Not_Narrowing; 382 } // Otherwise, fall through to the integral case. 383 case ICK_Integral_Conversion: { 384 assert(FromType->isIntegralOrUnscopedEnumerationType()); 385 assert(ToType->isIntegralOrUnscopedEnumerationType()); 386 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 387 const unsigned FromWidth = Ctx.getIntWidth(FromType); 388 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 389 const unsigned ToWidth = Ctx.getIntWidth(ToType); 390 391 if (FromWidth > ToWidth || 392 (FromWidth == ToWidth && FromSigned != ToSigned) || 393 (FromSigned && !ToSigned)) { 394 // Not all values of FromType can be represented in ToType. 395 llvm::APSInt InitializerValue; 396 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 397 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 398 // Such conversions on variables are always narrowing. 399 return NK_Variable_Narrowing; 400 } 401 bool Narrowing = false; 402 if (FromWidth < ToWidth) { 403 // Negative -> unsigned is narrowing. Otherwise, more bits is never 404 // narrowing. 405 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 406 Narrowing = true; 407 } else { 408 // Add a bit to the InitializerValue so we don't have to worry about 409 // signed vs. unsigned comparisons. 410 InitializerValue = InitializerValue.extend( 411 InitializerValue.getBitWidth() + 1); 412 // Convert the initializer to and from the target width and signed-ness. 413 llvm::APSInt ConvertedValue = InitializerValue; 414 ConvertedValue = ConvertedValue.trunc(ToWidth); 415 ConvertedValue.setIsSigned(ToSigned); 416 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 417 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 418 // If the result is different, this was a narrowing conversion. 419 if (ConvertedValue != InitializerValue) 420 Narrowing = true; 421 } 422 if (Narrowing) { 423 ConstantType = Initializer->getType(); 424 ConstantValue = APValue(InitializerValue); 425 return NK_Constant_Narrowing; 426 } 427 } 428 return NK_Not_Narrowing; 429 } 430 431 default: 432 // Other kinds of conversions are not narrowings. 433 return NK_Not_Narrowing; 434 } 435} 436 437/// DebugPrint - Print this standard conversion sequence to standard 438/// error. Useful for debugging overloading issues. 439void StandardConversionSequence::DebugPrint() const { 440 raw_ostream &OS = llvm::errs(); 441 bool PrintedSomething = false; 442 if (First != ICK_Identity) { 443 OS << GetImplicitConversionName(First); 444 PrintedSomething = true; 445 } 446 447 if (Second != ICK_Identity) { 448 if (PrintedSomething) { 449 OS << " -> "; 450 } 451 OS << GetImplicitConversionName(Second); 452 453 if (CopyConstructor) { 454 OS << " (by copy constructor)"; 455 } else if (DirectBinding) { 456 OS << " (direct reference binding)"; 457 } else if (ReferenceBinding) { 458 OS << " (reference binding)"; 459 } 460 PrintedSomething = true; 461 } 462 463 if (Third != ICK_Identity) { 464 if (PrintedSomething) { 465 OS << " -> "; 466 } 467 OS << GetImplicitConversionName(Third); 468 PrintedSomething = true; 469 } 470 471 if (!PrintedSomething) { 472 OS << "No conversions required"; 473 } 474} 475 476/// DebugPrint - Print this user-defined conversion sequence to standard 477/// error. Useful for debugging overloading issues. 478void UserDefinedConversionSequence::DebugPrint() const { 479 raw_ostream &OS = llvm::errs(); 480 if (Before.First || Before.Second || Before.Third) { 481 Before.DebugPrint(); 482 OS << " -> "; 483 } 484 if (ConversionFunction) 485 OS << '\'' << *ConversionFunction << '\''; 486 else 487 OS << "aggregate initialization"; 488 if (After.First || After.Second || After.Third) { 489 OS << " -> "; 490 After.DebugPrint(); 491 } 492} 493 494/// DebugPrint - Print this implicit conversion sequence to standard 495/// error. Useful for debugging overloading issues. 496void ImplicitConversionSequence::DebugPrint() const { 497 raw_ostream &OS = llvm::errs(); 498 switch (ConversionKind) { 499 case StandardConversion: 500 OS << "Standard conversion: "; 501 Standard.DebugPrint(); 502 break; 503 case UserDefinedConversion: 504 OS << "User-defined conversion: "; 505 UserDefined.DebugPrint(); 506 break; 507 case EllipsisConversion: 508 OS << "Ellipsis conversion"; 509 break; 510 case AmbiguousConversion: 511 OS << "Ambiguous conversion"; 512 break; 513 case BadConversion: 514 OS << "Bad conversion"; 515 break; 516 } 517 518 OS << "\n"; 519} 520 521void AmbiguousConversionSequence::construct() { 522 new (&conversions()) ConversionSet(); 523} 524 525void AmbiguousConversionSequence::destruct() { 526 conversions().~ConversionSet(); 527} 528 529void 530AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 531 FromTypePtr = O.FromTypePtr; 532 ToTypePtr = O.ToTypePtr; 533 new (&conversions()) ConversionSet(O.conversions()); 534} 535 536namespace { 537 // Structure used by OverloadCandidate::DeductionFailureInfo to store 538 // template parameter and template argument information. 539 struct DFIParamWithArguments { 540 TemplateParameter Param; 541 TemplateArgument FirstArg; 542 TemplateArgument SecondArg; 543 }; 544} 545 546/// \brief Convert from Sema's representation of template deduction information 547/// to the form used in overload-candidate information. 548OverloadCandidate::DeductionFailureInfo 549static MakeDeductionFailureInfo(ASTContext &Context, 550 Sema::TemplateDeductionResult TDK, 551 TemplateDeductionInfo &Info) { 552 OverloadCandidate::DeductionFailureInfo Result; 553 Result.Result = static_cast<unsigned>(TDK); 554 Result.HasDiagnostic = false; 555 Result.Data = 0; 556 switch (TDK) { 557 case Sema::TDK_Success: 558 case Sema::TDK_Invalid: 559 case Sema::TDK_InstantiationDepth: 560 case Sema::TDK_TooManyArguments: 561 case Sema::TDK_TooFewArguments: 562 break; 563 564 case Sema::TDK_Incomplete: 565 case Sema::TDK_InvalidExplicitArguments: 566 Result.Data = Info.Param.getOpaqueValue(); 567 break; 568 569 case Sema::TDK_Inconsistent: 570 case Sema::TDK_Underqualified: { 571 // FIXME: Should allocate from normal heap so that we can free this later. 572 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 573 Saved->Param = Info.Param; 574 Saved->FirstArg = Info.FirstArg; 575 Saved->SecondArg = Info.SecondArg; 576 Result.Data = Saved; 577 break; 578 } 579 580 case Sema::TDK_SubstitutionFailure: 581 Result.Data = Info.take(); 582 if (Info.hasSFINAEDiagnostic()) { 583 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 584 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 585 Info.takeSFINAEDiagnostic(*Diag); 586 Result.HasDiagnostic = true; 587 } 588 break; 589 590 case Sema::TDK_NonDeducedMismatch: 591 case Sema::TDK_FailedOverloadResolution: 592 break; 593 } 594 595 return Result; 596} 597 598void OverloadCandidate::DeductionFailureInfo::Destroy() { 599 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 600 case Sema::TDK_Success: 601 case Sema::TDK_Invalid: 602 case Sema::TDK_InstantiationDepth: 603 case Sema::TDK_Incomplete: 604 case Sema::TDK_TooManyArguments: 605 case Sema::TDK_TooFewArguments: 606 case Sema::TDK_InvalidExplicitArguments: 607 break; 608 609 case Sema::TDK_Inconsistent: 610 case Sema::TDK_Underqualified: 611 // FIXME: Destroy the data? 612 Data = 0; 613 break; 614 615 case Sema::TDK_SubstitutionFailure: 616 // FIXME: Destroy the template argument list? 617 Data = 0; 618 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 619 Diag->~PartialDiagnosticAt(); 620 HasDiagnostic = false; 621 } 622 break; 623 624 // Unhandled 625 case Sema::TDK_NonDeducedMismatch: 626 case Sema::TDK_FailedOverloadResolution: 627 break; 628 } 629} 630 631PartialDiagnosticAt * 632OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 633 if (HasDiagnostic) 634 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 635 return 0; 636} 637 638TemplateParameter 639OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 640 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 641 case Sema::TDK_Success: 642 case Sema::TDK_Invalid: 643 case Sema::TDK_InstantiationDepth: 644 case Sema::TDK_TooManyArguments: 645 case Sema::TDK_TooFewArguments: 646 case Sema::TDK_SubstitutionFailure: 647 return TemplateParameter(); 648 649 case Sema::TDK_Incomplete: 650 case Sema::TDK_InvalidExplicitArguments: 651 return TemplateParameter::getFromOpaqueValue(Data); 652 653 case Sema::TDK_Inconsistent: 654 case Sema::TDK_Underqualified: 655 return static_cast<DFIParamWithArguments*>(Data)->Param; 656 657 // Unhandled 658 case Sema::TDK_NonDeducedMismatch: 659 case Sema::TDK_FailedOverloadResolution: 660 break; 661 } 662 663 return TemplateParameter(); 664} 665 666TemplateArgumentList * 667OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 668 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 669 case Sema::TDK_Success: 670 case Sema::TDK_Invalid: 671 case Sema::TDK_InstantiationDepth: 672 case Sema::TDK_TooManyArguments: 673 case Sema::TDK_TooFewArguments: 674 case Sema::TDK_Incomplete: 675 case Sema::TDK_InvalidExplicitArguments: 676 case Sema::TDK_Inconsistent: 677 case Sema::TDK_Underqualified: 678 return 0; 679 680 case Sema::TDK_SubstitutionFailure: 681 return static_cast<TemplateArgumentList*>(Data); 682 683 // Unhandled 684 case Sema::TDK_NonDeducedMismatch: 685 case Sema::TDK_FailedOverloadResolution: 686 break; 687 } 688 689 return 0; 690} 691 692const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 693 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 694 case Sema::TDK_Success: 695 case Sema::TDK_Invalid: 696 case Sema::TDK_InstantiationDepth: 697 case Sema::TDK_Incomplete: 698 case Sema::TDK_TooManyArguments: 699 case Sema::TDK_TooFewArguments: 700 case Sema::TDK_InvalidExplicitArguments: 701 case Sema::TDK_SubstitutionFailure: 702 return 0; 703 704 case Sema::TDK_Inconsistent: 705 case Sema::TDK_Underqualified: 706 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 707 708 // Unhandled 709 case Sema::TDK_NonDeducedMismatch: 710 case Sema::TDK_FailedOverloadResolution: 711 break; 712 } 713 714 return 0; 715} 716 717const TemplateArgument * 718OverloadCandidate::DeductionFailureInfo::getSecondArg() { 719 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 720 case Sema::TDK_Success: 721 case Sema::TDK_Invalid: 722 case Sema::TDK_InstantiationDepth: 723 case Sema::TDK_Incomplete: 724 case Sema::TDK_TooManyArguments: 725 case Sema::TDK_TooFewArguments: 726 case Sema::TDK_InvalidExplicitArguments: 727 case Sema::TDK_SubstitutionFailure: 728 return 0; 729 730 case Sema::TDK_Inconsistent: 731 case Sema::TDK_Underqualified: 732 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 733 734 // Unhandled 735 case Sema::TDK_NonDeducedMismatch: 736 case Sema::TDK_FailedOverloadResolution: 737 break; 738 } 739 740 return 0; 741} 742 743void OverloadCandidateSet::clear() { 744 for (iterator i = begin(), e = end(); i != e; ++i) { 745 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 746 i->Conversions[ii].~ImplicitConversionSequence(); 747 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 748 i->DeductionFailure.Destroy(); 749 } 750 NumInlineSequences = 0; 751 Candidates.clear(); 752 Functions.clear(); 753} 754 755namespace { 756 class UnbridgedCastsSet { 757 struct Entry { 758 Expr **Addr; 759 Expr *Saved; 760 }; 761 SmallVector<Entry, 2> Entries; 762 763 public: 764 void save(Sema &S, Expr *&E) { 765 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 766 Entry entry = { &E, E }; 767 Entries.push_back(entry); 768 E = S.stripARCUnbridgedCast(E); 769 } 770 771 void restore() { 772 for (SmallVectorImpl<Entry>::iterator 773 i = Entries.begin(), e = Entries.end(); i != e; ++i) 774 *i->Addr = i->Saved; 775 } 776 }; 777} 778 779/// checkPlaceholderForOverload - Do any interesting placeholder-like 780/// preprocessing on the given expression. 781/// 782/// \param unbridgedCasts a collection to which to add unbridged casts; 783/// without this, they will be immediately diagnosed as errors 784/// 785/// Return true on unrecoverable error. 786static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 787 UnbridgedCastsSet *unbridgedCasts = 0) { 788 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 789 // We can't handle overloaded expressions here because overload 790 // resolution might reasonably tweak them. 791 if (placeholder->getKind() == BuiltinType::Overload) return false; 792 793 // If the context potentially accepts unbridged ARC casts, strip 794 // the unbridged cast and add it to the collection for later restoration. 795 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 796 unbridgedCasts) { 797 unbridgedCasts->save(S, E); 798 return false; 799 } 800 801 // Go ahead and check everything else. 802 ExprResult result = S.CheckPlaceholderExpr(E); 803 if (result.isInvalid()) 804 return true; 805 806 E = result.take(); 807 return false; 808 } 809 810 // Nothing to do. 811 return false; 812} 813 814/// checkArgPlaceholdersForOverload - Check a set of call operands for 815/// placeholders. 816static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args, 817 unsigned numArgs, 818 UnbridgedCastsSet &unbridged) { 819 for (unsigned i = 0; i != numArgs; ++i) 820 if (checkPlaceholderForOverload(S, args[i], &unbridged)) 821 return true; 822 823 return false; 824} 825 826// IsOverload - Determine whether the given New declaration is an 827// overload of the declarations in Old. This routine returns false if 828// New and Old cannot be overloaded, e.g., if New has the same 829// signature as some function in Old (C++ 1.3.10) or if the Old 830// declarations aren't functions (or function templates) at all. When 831// it does return false, MatchedDecl will point to the decl that New 832// cannot be overloaded with. This decl may be a UsingShadowDecl on 833// top of the underlying declaration. 834// 835// Example: Given the following input: 836// 837// void f(int, float); // #1 838// void f(int, int); // #2 839// int f(int, int); // #3 840// 841// When we process #1, there is no previous declaration of "f", 842// so IsOverload will not be used. 843// 844// When we process #2, Old contains only the FunctionDecl for #1. By 845// comparing the parameter types, we see that #1 and #2 are overloaded 846// (since they have different signatures), so this routine returns 847// false; MatchedDecl is unchanged. 848// 849// When we process #3, Old is an overload set containing #1 and #2. We 850// compare the signatures of #3 to #1 (they're overloaded, so we do 851// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 852// identical (return types of functions are not part of the 853// signature), IsOverload returns false and MatchedDecl will be set to 854// point to the FunctionDecl for #2. 855// 856// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 857// into a class by a using declaration. The rules for whether to hide 858// shadow declarations ignore some properties which otherwise figure 859// into a function template's signature. 860Sema::OverloadKind 861Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 862 NamedDecl *&Match, bool NewIsUsingDecl) { 863 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 864 I != E; ++I) { 865 NamedDecl *OldD = *I; 866 867 bool OldIsUsingDecl = false; 868 if (isa<UsingShadowDecl>(OldD)) { 869 OldIsUsingDecl = true; 870 871 // We can always introduce two using declarations into the same 872 // context, even if they have identical signatures. 873 if (NewIsUsingDecl) continue; 874 875 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 876 } 877 878 // If either declaration was introduced by a using declaration, 879 // we'll need to use slightly different rules for matching. 880 // Essentially, these rules are the normal rules, except that 881 // function templates hide function templates with different 882 // return types or template parameter lists. 883 bool UseMemberUsingDeclRules = 884 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 885 886 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 887 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 888 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 889 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 890 continue; 891 } 892 893 Match = *I; 894 return Ovl_Match; 895 } 896 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 897 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 898 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 899 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 900 continue; 901 } 902 903 Match = *I; 904 return Ovl_Match; 905 } 906 } else if (isa<UsingDecl>(OldD)) { 907 // We can overload with these, which can show up when doing 908 // redeclaration checks for UsingDecls. 909 assert(Old.getLookupKind() == LookupUsingDeclName); 910 } else if (isa<TagDecl>(OldD)) { 911 // We can always overload with tags by hiding them. 912 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 913 // Optimistically assume that an unresolved using decl will 914 // overload; if it doesn't, we'll have to diagnose during 915 // template instantiation. 916 } else { 917 // (C++ 13p1): 918 // Only function declarations can be overloaded; object and type 919 // declarations cannot be overloaded. 920 Match = *I; 921 return Ovl_NonFunction; 922 } 923 } 924 925 return Ovl_Overload; 926} 927 928bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 929 bool UseUsingDeclRules) { 930 // If both of the functions are extern "C", then they are not 931 // overloads. 932 if (Old->isExternC() && New->isExternC()) 933 return false; 934 935 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 936 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 937 938 // C++ [temp.fct]p2: 939 // A function template can be overloaded with other function templates 940 // and with normal (non-template) functions. 941 if ((OldTemplate == 0) != (NewTemplate == 0)) 942 return true; 943 944 // Is the function New an overload of the function Old? 945 QualType OldQType = Context.getCanonicalType(Old->getType()); 946 QualType NewQType = Context.getCanonicalType(New->getType()); 947 948 // Compare the signatures (C++ 1.3.10) of the two functions to 949 // determine whether they are overloads. If we find any mismatch 950 // in the signature, they are overloads. 951 952 // If either of these functions is a K&R-style function (no 953 // prototype), then we consider them to have matching signatures. 954 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 955 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 956 return false; 957 958 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 959 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 960 961 // The signature of a function includes the types of its 962 // parameters (C++ 1.3.10), which includes the presence or absence 963 // of the ellipsis; see C++ DR 357). 964 if (OldQType != NewQType && 965 (OldType->getNumArgs() != NewType->getNumArgs() || 966 OldType->isVariadic() != NewType->isVariadic() || 967 !FunctionArgTypesAreEqual(OldType, NewType))) 968 return true; 969 970 // C++ [temp.over.link]p4: 971 // The signature of a function template consists of its function 972 // signature, its return type and its template parameter list. The names 973 // of the template parameters are significant only for establishing the 974 // relationship between the template parameters and the rest of the 975 // signature. 976 // 977 // We check the return type and template parameter lists for function 978 // templates first; the remaining checks follow. 979 // 980 // However, we don't consider either of these when deciding whether 981 // a member introduced by a shadow declaration is hidden. 982 if (!UseUsingDeclRules && NewTemplate && 983 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 984 OldTemplate->getTemplateParameters(), 985 false, TPL_TemplateMatch) || 986 OldType->getResultType() != NewType->getResultType())) 987 return true; 988 989 // If the function is a class member, its signature includes the 990 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 991 // 992 // As part of this, also check whether one of the member functions 993 // is static, in which case they are not overloads (C++ 994 // 13.1p2). While not part of the definition of the signature, 995 // this check is important to determine whether these functions 996 // can be overloaded. 997 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 998 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 999 if (OldMethod && NewMethod && 1000 !OldMethod->isStatic() && !NewMethod->isStatic() && 1001 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() || 1002 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) { 1003 if (!UseUsingDeclRules && 1004 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() && 1005 (OldMethod->getRefQualifier() == RQ_None || 1006 NewMethod->getRefQualifier() == RQ_None)) { 1007 // C++0x [over.load]p2: 1008 // - Member function declarations with the same name and the same 1009 // parameter-type-list as well as member function template 1010 // declarations with the same name, the same parameter-type-list, and 1011 // the same template parameter lists cannot be overloaded if any of 1012 // them, but not all, have a ref-qualifier (8.3.5). 1013 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1014 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1015 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1016 } 1017 1018 return true; 1019 } 1020 1021 // The signatures match; this is not an overload. 1022 return false; 1023} 1024 1025/// \brief Checks availability of the function depending on the current 1026/// function context. Inside an unavailable function, unavailability is ignored. 1027/// 1028/// \returns true if \arg FD is unavailable and current context is inside 1029/// an available function, false otherwise. 1030bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1031 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1032} 1033 1034/// \brief Tries a user-defined conversion from From to ToType. 1035/// 1036/// Produces an implicit conversion sequence for when a standard conversion 1037/// is not an option. See TryImplicitConversion for more information. 1038static ImplicitConversionSequence 1039TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1040 bool SuppressUserConversions, 1041 bool AllowExplicit, 1042 bool InOverloadResolution, 1043 bool CStyle, 1044 bool AllowObjCWritebackConversion) { 1045 ImplicitConversionSequence ICS; 1046 1047 if (SuppressUserConversions) { 1048 // We're not in the case above, so there is no conversion that 1049 // we can perform. 1050 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1051 return ICS; 1052 } 1053 1054 // Attempt user-defined conversion. 1055 OverloadCandidateSet Conversions(From->getExprLoc()); 1056 OverloadingResult UserDefResult 1057 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1058 AllowExplicit); 1059 1060 if (UserDefResult == OR_Success) { 1061 ICS.setUserDefined(); 1062 // C++ [over.ics.user]p4: 1063 // A conversion of an expression of class type to the same class 1064 // type is given Exact Match rank, and a conversion of an 1065 // expression of class type to a base class of that type is 1066 // given Conversion rank, in spite of the fact that a copy 1067 // constructor (i.e., a user-defined conversion function) is 1068 // called for those cases. 1069 if (CXXConstructorDecl *Constructor 1070 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1071 QualType FromCanon 1072 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1073 QualType ToCanon 1074 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1075 if (Constructor->isCopyConstructor() && 1076 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1077 // Turn this into a "standard" conversion sequence, so that it 1078 // gets ranked with standard conversion sequences. 1079 ICS.setStandard(); 1080 ICS.Standard.setAsIdentityConversion(); 1081 ICS.Standard.setFromType(From->getType()); 1082 ICS.Standard.setAllToTypes(ToType); 1083 ICS.Standard.CopyConstructor = Constructor; 1084 if (ToCanon != FromCanon) 1085 ICS.Standard.Second = ICK_Derived_To_Base; 1086 } 1087 } 1088 1089 // C++ [over.best.ics]p4: 1090 // However, when considering the argument of a user-defined 1091 // conversion function that is a candidate by 13.3.1.3 when 1092 // invoked for the copying of the temporary in the second step 1093 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1094 // 13.3.1.6 in all cases, only standard conversion sequences and 1095 // ellipsis conversion sequences are allowed. 1096 if (SuppressUserConversions && ICS.isUserDefined()) { 1097 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1098 } 1099 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1100 ICS.setAmbiguous(); 1101 ICS.Ambiguous.setFromType(From->getType()); 1102 ICS.Ambiguous.setToType(ToType); 1103 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1104 Cand != Conversions.end(); ++Cand) 1105 if (Cand->Viable) 1106 ICS.Ambiguous.addConversion(Cand->Function); 1107 } else { 1108 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1109 } 1110 1111 return ICS; 1112} 1113 1114/// TryImplicitConversion - Attempt to perform an implicit conversion 1115/// from the given expression (Expr) to the given type (ToType). This 1116/// function returns an implicit conversion sequence that can be used 1117/// to perform the initialization. Given 1118/// 1119/// void f(float f); 1120/// void g(int i) { f(i); } 1121/// 1122/// this routine would produce an implicit conversion sequence to 1123/// describe the initialization of f from i, which will be a standard 1124/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1125/// 4.1) followed by a floating-integral conversion (C++ 4.9). 1126// 1127/// Note that this routine only determines how the conversion can be 1128/// performed; it does not actually perform the conversion. As such, 1129/// it will not produce any diagnostics if no conversion is available, 1130/// but will instead return an implicit conversion sequence of kind 1131/// "BadConversion". 1132/// 1133/// If @p SuppressUserConversions, then user-defined conversions are 1134/// not permitted. 1135/// If @p AllowExplicit, then explicit user-defined conversions are 1136/// permitted. 1137/// 1138/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1139/// writeback conversion, which allows __autoreleasing id* parameters to 1140/// be initialized with __strong id* or __weak id* arguments. 1141static ImplicitConversionSequence 1142TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1143 bool SuppressUserConversions, 1144 bool AllowExplicit, 1145 bool InOverloadResolution, 1146 bool CStyle, 1147 bool AllowObjCWritebackConversion) { 1148 ImplicitConversionSequence ICS; 1149 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1150 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1151 ICS.setStandard(); 1152 return ICS; 1153 } 1154 1155 if (!S.getLangOpts().CPlusPlus) { 1156 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1157 return ICS; 1158 } 1159 1160 // C++ [over.ics.user]p4: 1161 // A conversion of an expression of class type to the same class 1162 // type is given Exact Match rank, and a conversion of an 1163 // expression of class type to a base class of that type is 1164 // given Conversion rank, in spite of the fact that a copy/move 1165 // constructor (i.e., a user-defined conversion function) is 1166 // called for those cases. 1167 QualType FromType = From->getType(); 1168 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1169 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1170 S.IsDerivedFrom(FromType, ToType))) { 1171 ICS.setStandard(); 1172 ICS.Standard.setAsIdentityConversion(); 1173 ICS.Standard.setFromType(FromType); 1174 ICS.Standard.setAllToTypes(ToType); 1175 1176 // We don't actually check at this point whether there is a valid 1177 // copy/move constructor, since overloading just assumes that it 1178 // exists. When we actually perform initialization, we'll find the 1179 // appropriate constructor to copy the returned object, if needed. 1180 ICS.Standard.CopyConstructor = 0; 1181 1182 // Determine whether this is considered a derived-to-base conversion. 1183 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1184 ICS.Standard.Second = ICK_Derived_To_Base; 1185 1186 return ICS; 1187 } 1188 1189 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1190 AllowExplicit, InOverloadResolution, CStyle, 1191 AllowObjCWritebackConversion); 1192} 1193 1194ImplicitConversionSequence 1195Sema::TryImplicitConversion(Expr *From, QualType ToType, 1196 bool SuppressUserConversions, 1197 bool AllowExplicit, 1198 bool InOverloadResolution, 1199 bool CStyle, 1200 bool AllowObjCWritebackConversion) { 1201 return clang::TryImplicitConversion(*this, From, ToType, 1202 SuppressUserConversions, AllowExplicit, 1203 InOverloadResolution, CStyle, 1204 AllowObjCWritebackConversion); 1205} 1206 1207/// PerformImplicitConversion - Perform an implicit conversion of the 1208/// expression From to the type ToType. Returns the 1209/// converted expression. Flavor is the kind of conversion we're 1210/// performing, used in the error message. If @p AllowExplicit, 1211/// explicit user-defined conversions are permitted. 1212ExprResult 1213Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1214 AssignmentAction Action, bool AllowExplicit) { 1215 ImplicitConversionSequence ICS; 1216 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1217} 1218 1219ExprResult 1220Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1221 AssignmentAction Action, bool AllowExplicit, 1222 ImplicitConversionSequence& ICS) { 1223 if (checkPlaceholderForOverload(*this, From)) 1224 return ExprError(); 1225 1226 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1227 bool AllowObjCWritebackConversion 1228 = getLangOpts().ObjCAutoRefCount && 1229 (Action == AA_Passing || Action == AA_Sending); 1230 1231 ICS = clang::TryImplicitConversion(*this, From, ToType, 1232 /*SuppressUserConversions=*/false, 1233 AllowExplicit, 1234 /*InOverloadResolution=*/false, 1235 /*CStyle=*/false, 1236 AllowObjCWritebackConversion); 1237 return PerformImplicitConversion(From, ToType, ICS, Action); 1238} 1239 1240/// \brief Determine whether the conversion from FromType to ToType is a valid 1241/// conversion that strips "noreturn" off the nested function type. 1242bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1243 QualType &ResultTy) { 1244 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1245 return false; 1246 1247 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1248 // where F adds one of the following at most once: 1249 // - a pointer 1250 // - a member pointer 1251 // - a block pointer 1252 CanQualType CanTo = Context.getCanonicalType(ToType); 1253 CanQualType CanFrom = Context.getCanonicalType(FromType); 1254 Type::TypeClass TyClass = CanTo->getTypeClass(); 1255 if (TyClass != CanFrom->getTypeClass()) return false; 1256 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1257 if (TyClass == Type::Pointer) { 1258 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1259 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1260 } else if (TyClass == Type::BlockPointer) { 1261 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1262 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1263 } else if (TyClass == Type::MemberPointer) { 1264 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1265 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1266 } else { 1267 return false; 1268 } 1269 1270 TyClass = CanTo->getTypeClass(); 1271 if (TyClass != CanFrom->getTypeClass()) return false; 1272 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1273 return false; 1274 } 1275 1276 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1277 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1278 if (!EInfo.getNoReturn()) return false; 1279 1280 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1281 assert(QualType(FromFn, 0).isCanonical()); 1282 if (QualType(FromFn, 0) != CanTo) return false; 1283 1284 ResultTy = ToType; 1285 return true; 1286} 1287 1288/// \brief Determine whether the conversion from FromType to ToType is a valid 1289/// vector conversion. 1290/// 1291/// \param ICK Will be set to the vector conversion kind, if this is a vector 1292/// conversion. 1293static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1294 QualType ToType, ImplicitConversionKind &ICK) { 1295 // We need at least one of these types to be a vector type to have a vector 1296 // conversion. 1297 if (!ToType->isVectorType() && !FromType->isVectorType()) 1298 return false; 1299 1300 // Identical types require no conversions. 1301 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1302 return false; 1303 1304 // There are no conversions between extended vector types, only identity. 1305 if (ToType->isExtVectorType()) { 1306 // There are no conversions between extended vector types other than the 1307 // identity conversion. 1308 if (FromType->isExtVectorType()) 1309 return false; 1310 1311 // Vector splat from any arithmetic type to a vector. 1312 if (FromType->isArithmeticType()) { 1313 ICK = ICK_Vector_Splat; 1314 return true; 1315 } 1316 } 1317 1318 // We can perform the conversion between vector types in the following cases: 1319 // 1)vector types are equivalent AltiVec and GCC vector types 1320 // 2)lax vector conversions are permitted and the vector types are of the 1321 // same size 1322 if (ToType->isVectorType() && FromType->isVectorType()) { 1323 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1324 (Context.getLangOpts().LaxVectorConversions && 1325 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1326 ICK = ICK_Vector_Conversion; 1327 return true; 1328 } 1329 } 1330 1331 return false; 1332} 1333 1334static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1335 bool InOverloadResolution, 1336 StandardConversionSequence &SCS, 1337 bool CStyle); 1338 1339/// IsStandardConversion - Determines whether there is a standard 1340/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1341/// expression From to the type ToType. Standard conversion sequences 1342/// only consider non-class types; for conversions that involve class 1343/// types, use TryImplicitConversion. If a conversion exists, SCS will 1344/// contain the standard conversion sequence required to perform this 1345/// conversion and this routine will return true. Otherwise, this 1346/// routine will return false and the value of SCS is unspecified. 1347static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1348 bool InOverloadResolution, 1349 StandardConversionSequence &SCS, 1350 bool CStyle, 1351 bool AllowObjCWritebackConversion) { 1352 QualType FromType = From->getType(); 1353 1354 // Standard conversions (C++ [conv]) 1355 SCS.setAsIdentityConversion(); 1356 SCS.DeprecatedStringLiteralToCharPtr = false; 1357 SCS.IncompatibleObjC = false; 1358 SCS.setFromType(FromType); 1359 SCS.CopyConstructor = 0; 1360 1361 // There are no standard conversions for class types in C++, so 1362 // abort early. When overloading in C, however, we do permit 1363 if (FromType->isRecordType() || ToType->isRecordType()) { 1364 if (S.getLangOpts().CPlusPlus) 1365 return false; 1366 1367 // When we're overloading in C, we allow, as standard conversions, 1368 } 1369 1370 // The first conversion can be an lvalue-to-rvalue conversion, 1371 // array-to-pointer conversion, or function-to-pointer conversion 1372 // (C++ 4p1). 1373 1374 if (FromType == S.Context.OverloadTy) { 1375 DeclAccessPair AccessPair; 1376 if (FunctionDecl *Fn 1377 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1378 AccessPair)) { 1379 // We were able to resolve the address of the overloaded function, 1380 // so we can convert to the type of that function. 1381 FromType = Fn->getType(); 1382 1383 // we can sometimes resolve &foo<int> regardless of ToType, so check 1384 // if the type matches (identity) or we are converting to bool 1385 if (!S.Context.hasSameUnqualifiedType( 1386 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1387 QualType resultTy; 1388 // if the function type matches except for [[noreturn]], it's ok 1389 if (!S.IsNoReturnConversion(FromType, 1390 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1391 // otherwise, only a boolean conversion is standard 1392 if (!ToType->isBooleanType()) 1393 return false; 1394 } 1395 1396 // Check if the "from" expression is taking the address of an overloaded 1397 // function and recompute the FromType accordingly. Take advantage of the 1398 // fact that non-static member functions *must* have such an address-of 1399 // expression. 1400 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1401 if (Method && !Method->isStatic()) { 1402 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1403 "Non-unary operator on non-static member address"); 1404 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1405 == UO_AddrOf && 1406 "Non-address-of operator on non-static member address"); 1407 const Type *ClassType 1408 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1409 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1410 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1411 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1412 UO_AddrOf && 1413 "Non-address-of operator for overloaded function expression"); 1414 FromType = S.Context.getPointerType(FromType); 1415 } 1416 1417 // Check that we've computed the proper type after overload resolution. 1418 assert(S.Context.hasSameType( 1419 FromType, 1420 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1421 } else { 1422 return false; 1423 } 1424 } 1425 // Lvalue-to-rvalue conversion (C++11 4.1): 1426 // A glvalue (3.10) of a non-function, non-array type T can 1427 // be converted to a prvalue. 1428 bool argIsLValue = From->isGLValue(); 1429 if (argIsLValue && 1430 !FromType->isFunctionType() && !FromType->isArrayType() && 1431 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1432 SCS.First = ICK_Lvalue_To_Rvalue; 1433 1434 // C11 6.3.2.1p2: 1435 // ... if the lvalue has atomic type, the value has the non-atomic version 1436 // of the type of the lvalue ... 1437 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1438 FromType = Atomic->getValueType(); 1439 1440 // If T is a non-class type, the type of the rvalue is the 1441 // cv-unqualified version of T. Otherwise, the type of the rvalue 1442 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1443 // just strip the qualifiers because they don't matter. 1444 FromType = FromType.getUnqualifiedType(); 1445 } else if (FromType->isArrayType()) { 1446 // Array-to-pointer conversion (C++ 4.2) 1447 SCS.First = ICK_Array_To_Pointer; 1448 1449 // An lvalue or rvalue of type "array of N T" or "array of unknown 1450 // bound of T" can be converted to an rvalue of type "pointer to 1451 // T" (C++ 4.2p1). 1452 FromType = S.Context.getArrayDecayedType(FromType); 1453 1454 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1455 // This conversion is deprecated. (C++ D.4). 1456 SCS.DeprecatedStringLiteralToCharPtr = true; 1457 1458 // For the purpose of ranking in overload resolution 1459 // (13.3.3.1.1), this conversion is considered an 1460 // array-to-pointer conversion followed by a qualification 1461 // conversion (4.4). (C++ 4.2p2) 1462 SCS.Second = ICK_Identity; 1463 SCS.Third = ICK_Qualification; 1464 SCS.QualificationIncludesObjCLifetime = false; 1465 SCS.setAllToTypes(FromType); 1466 return true; 1467 } 1468 } else if (FromType->isFunctionType() && argIsLValue) { 1469 // Function-to-pointer conversion (C++ 4.3). 1470 SCS.First = ICK_Function_To_Pointer; 1471 1472 // An lvalue of function type T can be converted to an rvalue of 1473 // type "pointer to T." The result is a pointer to the 1474 // function. (C++ 4.3p1). 1475 FromType = S.Context.getPointerType(FromType); 1476 } else { 1477 // We don't require any conversions for the first step. 1478 SCS.First = ICK_Identity; 1479 } 1480 SCS.setToType(0, FromType); 1481 1482 // The second conversion can be an integral promotion, floating 1483 // point promotion, integral conversion, floating point conversion, 1484 // floating-integral conversion, pointer conversion, 1485 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1486 // For overloading in C, this can also be a "compatible-type" 1487 // conversion. 1488 bool IncompatibleObjC = false; 1489 ImplicitConversionKind SecondICK = ICK_Identity; 1490 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1491 // The unqualified versions of the types are the same: there's no 1492 // conversion to do. 1493 SCS.Second = ICK_Identity; 1494 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1495 // Integral promotion (C++ 4.5). 1496 SCS.Second = ICK_Integral_Promotion; 1497 FromType = ToType.getUnqualifiedType(); 1498 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1499 // Floating point promotion (C++ 4.6). 1500 SCS.Second = ICK_Floating_Promotion; 1501 FromType = ToType.getUnqualifiedType(); 1502 } else if (S.IsComplexPromotion(FromType, ToType)) { 1503 // Complex promotion (Clang extension) 1504 SCS.Second = ICK_Complex_Promotion; 1505 FromType = ToType.getUnqualifiedType(); 1506 } else if (ToType->isBooleanType() && 1507 (FromType->isArithmeticType() || 1508 FromType->isAnyPointerType() || 1509 FromType->isBlockPointerType() || 1510 FromType->isMemberPointerType() || 1511 FromType->isNullPtrType())) { 1512 // Boolean conversions (C++ 4.12). 1513 SCS.Second = ICK_Boolean_Conversion; 1514 FromType = S.Context.BoolTy; 1515 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1516 ToType->isIntegralType(S.Context)) { 1517 // Integral conversions (C++ 4.7). 1518 SCS.Second = ICK_Integral_Conversion; 1519 FromType = ToType.getUnqualifiedType(); 1520 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1521 // Complex conversions (C99 6.3.1.6) 1522 SCS.Second = ICK_Complex_Conversion; 1523 FromType = ToType.getUnqualifiedType(); 1524 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1525 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1526 // Complex-real conversions (C99 6.3.1.7) 1527 SCS.Second = ICK_Complex_Real; 1528 FromType = ToType.getUnqualifiedType(); 1529 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1530 // Floating point conversions (C++ 4.8). 1531 SCS.Second = ICK_Floating_Conversion; 1532 FromType = ToType.getUnqualifiedType(); 1533 } else if ((FromType->isRealFloatingType() && 1534 ToType->isIntegralType(S.Context)) || 1535 (FromType->isIntegralOrUnscopedEnumerationType() && 1536 ToType->isRealFloatingType())) { 1537 // Floating-integral conversions (C++ 4.9). 1538 SCS.Second = ICK_Floating_Integral; 1539 FromType = ToType.getUnqualifiedType(); 1540 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1541 SCS.Second = ICK_Block_Pointer_Conversion; 1542 } else if (AllowObjCWritebackConversion && 1543 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1544 SCS.Second = ICK_Writeback_Conversion; 1545 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1546 FromType, IncompatibleObjC)) { 1547 // Pointer conversions (C++ 4.10). 1548 SCS.Second = ICK_Pointer_Conversion; 1549 SCS.IncompatibleObjC = IncompatibleObjC; 1550 FromType = FromType.getUnqualifiedType(); 1551 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1552 InOverloadResolution, FromType)) { 1553 // Pointer to member conversions (4.11). 1554 SCS.Second = ICK_Pointer_Member; 1555 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1556 SCS.Second = SecondICK; 1557 FromType = ToType.getUnqualifiedType(); 1558 } else if (!S.getLangOpts().CPlusPlus && 1559 S.Context.typesAreCompatible(ToType, FromType)) { 1560 // Compatible conversions (Clang extension for C function overloading) 1561 SCS.Second = ICK_Compatible_Conversion; 1562 FromType = ToType.getUnqualifiedType(); 1563 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1564 // Treat a conversion that strips "noreturn" as an identity conversion. 1565 SCS.Second = ICK_NoReturn_Adjustment; 1566 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1567 InOverloadResolution, 1568 SCS, CStyle)) { 1569 SCS.Second = ICK_TransparentUnionConversion; 1570 FromType = ToType; 1571 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1572 CStyle)) { 1573 // tryAtomicConversion has updated the standard conversion sequence 1574 // appropriately. 1575 return true; 1576 } else { 1577 // No second conversion required. 1578 SCS.Second = ICK_Identity; 1579 } 1580 SCS.setToType(1, FromType); 1581 1582 QualType CanonFrom; 1583 QualType CanonTo; 1584 // The third conversion can be a qualification conversion (C++ 4p1). 1585 bool ObjCLifetimeConversion; 1586 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1587 ObjCLifetimeConversion)) { 1588 SCS.Third = ICK_Qualification; 1589 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1590 FromType = ToType; 1591 CanonFrom = S.Context.getCanonicalType(FromType); 1592 CanonTo = S.Context.getCanonicalType(ToType); 1593 } else { 1594 // No conversion required 1595 SCS.Third = ICK_Identity; 1596 1597 // C++ [over.best.ics]p6: 1598 // [...] Any difference in top-level cv-qualification is 1599 // subsumed by the initialization itself and does not constitute 1600 // a conversion. [...] 1601 CanonFrom = S.Context.getCanonicalType(FromType); 1602 CanonTo = S.Context.getCanonicalType(ToType); 1603 if (CanonFrom.getLocalUnqualifiedType() 1604 == CanonTo.getLocalUnqualifiedType() && 1605 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1606 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr() 1607 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) { 1608 FromType = ToType; 1609 CanonFrom = CanonTo; 1610 } 1611 } 1612 SCS.setToType(2, FromType); 1613 1614 // If we have not converted the argument type to the parameter type, 1615 // this is a bad conversion sequence. 1616 if (CanonFrom != CanonTo) 1617 return false; 1618 1619 return true; 1620} 1621 1622static bool 1623IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1624 QualType &ToType, 1625 bool InOverloadResolution, 1626 StandardConversionSequence &SCS, 1627 bool CStyle) { 1628 1629 const RecordType *UT = ToType->getAsUnionType(); 1630 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1631 return false; 1632 // The field to initialize within the transparent union. 1633 RecordDecl *UD = UT->getDecl(); 1634 // It's compatible if the expression matches any of the fields. 1635 for (RecordDecl::field_iterator it = UD->field_begin(), 1636 itend = UD->field_end(); 1637 it != itend; ++it) { 1638 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1639 CStyle, /*ObjCWritebackConversion=*/false)) { 1640 ToType = it->getType(); 1641 return true; 1642 } 1643 } 1644 return false; 1645} 1646 1647/// IsIntegralPromotion - Determines whether the conversion from the 1648/// expression From (whose potentially-adjusted type is FromType) to 1649/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1650/// sets PromotedType to the promoted type. 1651bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1652 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1653 // All integers are built-in. 1654 if (!To) { 1655 return false; 1656 } 1657 1658 // An rvalue of type char, signed char, unsigned char, short int, or 1659 // unsigned short int can be converted to an rvalue of type int if 1660 // int can represent all the values of the source type; otherwise, 1661 // the source rvalue can be converted to an rvalue of type unsigned 1662 // int (C++ 4.5p1). 1663 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1664 !FromType->isEnumeralType()) { 1665 if (// We can promote any signed, promotable integer type to an int 1666 (FromType->isSignedIntegerType() || 1667 // We can promote any unsigned integer type whose size is 1668 // less than int to an int. 1669 (!FromType->isSignedIntegerType() && 1670 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1671 return To->getKind() == BuiltinType::Int; 1672 } 1673 1674 return To->getKind() == BuiltinType::UInt; 1675 } 1676 1677 // C++0x [conv.prom]p3: 1678 // A prvalue of an unscoped enumeration type whose underlying type is not 1679 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1680 // following types that can represent all the values of the enumeration 1681 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1682 // unsigned int, long int, unsigned long int, long long int, or unsigned 1683 // long long int. If none of the types in that list can represent all the 1684 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1685 // type can be converted to an rvalue a prvalue of the extended integer type 1686 // with lowest integer conversion rank (4.13) greater than the rank of long 1687 // long in which all the values of the enumeration can be represented. If 1688 // there are two such extended types, the signed one is chosen. 1689 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1690 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1691 // provided for a scoped enumeration. 1692 if (FromEnumType->getDecl()->isScoped()) 1693 return false; 1694 1695 // We have already pre-calculated the promotion type, so this is trivial. 1696 if (ToType->isIntegerType() && 1697 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1698 return Context.hasSameUnqualifiedType(ToType, 1699 FromEnumType->getDecl()->getPromotionType()); 1700 } 1701 1702 // C++0x [conv.prom]p2: 1703 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1704 // to an rvalue a prvalue of the first of the following types that can 1705 // represent all the values of its underlying type: int, unsigned int, 1706 // long int, unsigned long int, long long int, or unsigned long long int. 1707 // If none of the types in that list can represent all the values of its 1708 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1709 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1710 // type. 1711 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1712 ToType->isIntegerType()) { 1713 // Determine whether the type we're converting from is signed or 1714 // unsigned. 1715 bool FromIsSigned = FromType->isSignedIntegerType(); 1716 uint64_t FromSize = Context.getTypeSize(FromType); 1717 1718 // The types we'll try to promote to, in the appropriate 1719 // order. Try each of these types. 1720 QualType PromoteTypes[6] = { 1721 Context.IntTy, Context.UnsignedIntTy, 1722 Context.LongTy, Context.UnsignedLongTy , 1723 Context.LongLongTy, Context.UnsignedLongLongTy 1724 }; 1725 for (int Idx = 0; Idx < 6; ++Idx) { 1726 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1727 if (FromSize < ToSize || 1728 (FromSize == ToSize && 1729 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1730 // We found the type that we can promote to. If this is the 1731 // type we wanted, we have a promotion. Otherwise, no 1732 // promotion. 1733 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1734 } 1735 } 1736 } 1737 1738 // An rvalue for an integral bit-field (9.6) can be converted to an 1739 // rvalue of type int if int can represent all the values of the 1740 // bit-field; otherwise, it can be converted to unsigned int if 1741 // unsigned int can represent all the values of the bit-field. If 1742 // the bit-field is larger yet, no integral promotion applies to 1743 // it. If the bit-field has an enumerated type, it is treated as any 1744 // other value of that type for promotion purposes (C++ 4.5p3). 1745 // FIXME: We should delay checking of bit-fields until we actually perform the 1746 // conversion. 1747 using llvm::APSInt; 1748 if (From) 1749 if (FieldDecl *MemberDecl = From->getBitField()) { 1750 APSInt BitWidth; 1751 if (FromType->isIntegralType(Context) && 1752 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1753 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1754 ToSize = Context.getTypeSize(ToType); 1755 1756 // Are we promoting to an int from a bitfield that fits in an int? 1757 if (BitWidth < ToSize || 1758 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1759 return To->getKind() == BuiltinType::Int; 1760 } 1761 1762 // Are we promoting to an unsigned int from an unsigned bitfield 1763 // that fits into an unsigned int? 1764 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1765 return To->getKind() == BuiltinType::UInt; 1766 } 1767 1768 return false; 1769 } 1770 } 1771 1772 // An rvalue of type bool can be converted to an rvalue of type int, 1773 // with false becoming zero and true becoming one (C++ 4.5p4). 1774 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1775 return true; 1776 } 1777 1778 return false; 1779} 1780 1781/// IsFloatingPointPromotion - Determines whether the conversion from 1782/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1783/// returns true and sets PromotedType to the promoted type. 1784bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1785 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1786 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1787 /// An rvalue of type float can be converted to an rvalue of type 1788 /// double. (C++ 4.6p1). 1789 if (FromBuiltin->getKind() == BuiltinType::Float && 1790 ToBuiltin->getKind() == BuiltinType::Double) 1791 return true; 1792 1793 // C99 6.3.1.5p1: 1794 // When a float is promoted to double or long double, or a 1795 // double is promoted to long double [...]. 1796 if (!getLangOpts().CPlusPlus && 1797 (FromBuiltin->getKind() == BuiltinType::Float || 1798 FromBuiltin->getKind() == BuiltinType::Double) && 1799 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1800 return true; 1801 1802 // Half can be promoted to float. 1803 if (FromBuiltin->getKind() == BuiltinType::Half && 1804 ToBuiltin->getKind() == BuiltinType::Float) 1805 return true; 1806 } 1807 1808 return false; 1809} 1810 1811/// \brief Determine if a conversion is a complex promotion. 1812/// 1813/// A complex promotion is defined as a complex -> complex conversion 1814/// where the conversion between the underlying real types is a 1815/// floating-point or integral promotion. 1816bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1817 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1818 if (!FromComplex) 1819 return false; 1820 1821 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1822 if (!ToComplex) 1823 return false; 1824 1825 return IsFloatingPointPromotion(FromComplex->getElementType(), 1826 ToComplex->getElementType()) || 1827 IsIntegralPromotion(0, FromComplex->getElementType(), 1828 ToComplex->getElementType()); 1829} 1830 1831/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1832/// the pointer type FromPtr to a pointer to type ToPointee, with the 1833/// same type qualifiers as FromPtr has on its pointee type. ToType, 1834/// if non-empty, will be a pointer to ToType that may or may not have 1835/// the right set of qualifiers on its pointee. 1836/// 1837static QualType 1838BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1839 QualType ToPointee, QualType ToType, 1840 ASTContext &Context, 1841 bool StripObjCLifetime = false) { 1842 assert((FromPtr->getTypeClass() == Type::Pointer || 1843 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1844 "Invalid similarly-qualified pointer type"); 1845 1846 /// Conversions to 'id' subsume cv-qualifier conversions. 1847 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1848 return ToType.getUnqualifiedType(); 1849 1850 QualType CanonFromPointee 1851 = Context.getCanonicalType(FromPtr->getPointeeType()); 1852 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1853 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1854 1855 if (StripObjCLifetime) 1856 Quals.removeObjCLifetime(); 1857 1858 // Exact qualifier match -> return the pointer type we're converting to. 1859 if (CanonToPointee.getLocalQualifiers() == Quals) { 1860 // ToType is exactly what we need. Return it. 1861 if (!ToType.isNull()) 1862 return ToType.getUnqualifiedType(); 1863 1864 // Build a pointer to ToPointee. It has the right qualifiers 1865 // already. 1866 if (isa<ObjCObjectPointerType>(ToType)) 1867 return Context.getObjCObjectPointerType(ToPointee); 1868 return Context.getPointerType(ToPointee); 1869 } 1870 1871 // Just build a canonical type that has the right qualifiers. 1872 QualType QualifiedCanonToPointee 1873 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1874 1875 if (isa<ObjCObjectPointerType>(ToType)) 1876 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1877 return Context.getPointerType(QualifiedCanonToPointee); 1878} 1879 1880static bool isNullPointerConstantForConversion(Expr *Expr, 1881 bool InOverloadResolution, 1882 ASTContext &Context) { 1883 // Handle value-dependent integral null pointer constants correctly. 1884 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1885 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1886 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1887 return !InOverloadResolution; 1888 1889 return Expr->isNullPointerConstant(Context, 1890 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1891 : Expr::NPC_ValueDependentIsNull); 1892} 1893 1894/// IsPointerConversion - Determines whether the conversion of the 1895/// expression From, which has the (possibly adjusted) type FromType, 1896/// can be converted to the type ToType via a pointer conversion (C++ 1897/// 4.10). If so, returns true and places the converted type (that 1898/// might differ from ToType in its cv-qualifiers at some level) into 1899/// ConvertedType. 1900/// 1901/// This routine also supports conversions to and from block pointers 1902/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1903/// pointers to interfaces. FIXME: Once we've determined the 1904/// appropriate overloading rules for Objective-C, we may want to 1905/// split the Objective-C checks into a different routine; however, 1906/// GCC seems to consider all of these conversions to be pointer 1907/// conversions, so for now they live here. IncompatibleObjC will be 1908/// set if the conversion is an allowed Objective-C conversion that 1909/// should result in a warning. 1910bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1911 bool InOverloadResolution, 1912 QualType& ConvertedType, 1913 bool &IncompatibleObjC) { 1914 IncompatibleObjC = false; 1915 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1916 IncompatibleObjC)) 1917 return true; 1918 1919 // Conversion from a null pointer constant to any Objective-C pointer type. 1920 if (ToType->isObjCObjectPointerType() && 1921 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1922 ConvertedType = ToType; 1923 return true; 1924 } 1925 1926 // Blocks: Block pointers can be converted to void*. 1927 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1928 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1929 ConvertedType = ToType; 1930 return true; 1931 } 1932 // Blocks: A null pointer constant can be converted to a block 1933 // pointer type. 1934 if (ToType->isBlockPointerType() && 1935 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1936 ConvertedType = ToType; 1937 return true; 1938 } 1939 1940 // If the left-hand-side is nullptr_t, the right side can be a null 1941 // pointer constant. 1942 if (ToType->isNullPtrType() && 1943 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1944 ConvertedType = ToType; 1945 return true; 1946 } 1947 1948 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 1949 if (!ToTypePtr) 1950 return false; 1951 1952 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 1953 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1954 ConvertedType = ToType; 1955 return true; 1956 } 1957 1958 // Beyond this point, both types need to be pointers 1959 // , including objective-c pointers. 1960 QualType ToPointeeType = ToTypePtr->getPointeeType(); 1961 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 1962 !getLangOpts().ObjCAutoRefCount) { 1963 ConvertedType = BuildSimilarlyQualifiedPointerType( 1964 FromType->getAs<ObjCObjectPointerType>(), 1965 ToPointeeType, 1966 ToType, Context); 1967 return true; 1968 } 1969 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 1970 if (!FromTypePtr) 1971 return false; 1972 1973 QualType FromPointeeType = FromTypePtr->getPointeeType(); 1974 1975 // If the unqualified pointee types are the same, this can't be a 1976 // pointer conversion, so don't do all of the work below. 1977 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 1978 return false; 1979 1980 // An rvalue of type "pointer to cv T," where T is an object type, 1981 // can be converted to an rvalue of type "pointer to cv void" (C++ 1982 // 4.10p2). 1983 if (FromPointeeType->isIncompleteOrObjectType() && 1984 ToPointeeType->isVoidType()) { 1985 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1986 ToPointeeType, 1987 ToType, Context, 1988 /*StripObjCLifetime=*/true); 1989 return true; 1990 } 1991 1992 // MSVC allows implicit function to void* type conversion. 1993 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 1994 ToPointeeType->isVoidType()) { 1995 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1996 ToPointeeType, 1997 ToType, Context); 1998 return true; 1999 } 2000 2001 // When we're overloading in C, we allow a special kind of pointer 2002 // conversion for compatible-but-not-identical pointee types. 2003 if (!getLangOpts().CPlusPlus && 2004 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2005 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2006 ToPointeeType, 2007 ToType, Context); 2008 return true; 2009 } 2010 2011 // C++ [conv.ptr]p3: 2012 // 2013 // An rvalue of type "pointer to cv D," where D is a class type, 2014 // can be converted to an rvalue of type "pointer to cv B," where 2015 // B is a base class (clause 10) of D. If B is an inaccessible 2016 // (clause 11) or ambiguous (10.2) base class of D, a program that 2017 // necessitates this conversion is ill-formed. The result of the 2018 // conversion is a pointer to the base class sub-object of the 2019 // derived class object. The null pointer value is converted to 2020 // the null pointer value of the destination type. 2021 // 2022 // Note that we do not check for ambiguity or inaccessibility 2023 // here. That is handled by CheckPointerConversion. 2024 if (getLangOpts().CPlusPlus && 2025 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2026 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2027 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2028 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2029 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2030 ToPointeeType, 2031 ToType, Context); 2032 return true; 2033 } 2034 2035 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2036 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2037 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2038 ToPointeeType, 2039 ToType, Context); 2040 return true; 2041 } 2042 2043 return false; 2044} 2045 2046/// \brief Adopt the given qualifiers for the given type. 2047static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2048 Qualifiers TQs = T.getQualifiers(); 2049 2050 // Check whether qualifiers already match. 2051 if (TQs == Qs) 2052 return T; 2053 2054 if (Qs.compatiblyIncludes(TQs)) 2055 return Context.getQualifiedType(T, Qs); 2056 2057 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2058} 2059 2060/// isObjCPointerConversion - Determines whether this is an 2061/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2062/// with the same arguments and return values. 2063bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2064 QualType& ConvertedType, 2065 bool &IncompatibleObjC) { 2066 if (!getLangOpts().ObjC1) 2067 return false; 2068 2069 // The set of qualifiers on the type we're converting from. 2070 Qualifiers FromQualifiers = FromType.getQualifiers(); 2071 2072 // First, we handle all conversions on ObjC object pointer types. 2073 const ObjCObjectPointerType* ToObjCPtr = 2074 ToType->getAs<ObjCObjectPointerType>(); 2075 const ObjCObjectPointerType *FromObjCPtr = 2076 FromType->getAs<ObjCObjectPointerType>(); 2077 2078 if (ToObjCPtr && FromObjCPtr) { 2079 // If the pointee types are the same (ignoring qualifications), 2080 // then this is not a pointer conversion. 2081 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2082 FromObjCPtr->getPointeeType())) 2083 return false; 2084 2085 // Check for compatible 2086 // Objective C++: We're able to convert between "id" or "Class" and a 2087 // pointer to any interface (in both directions). 2088 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2089 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2090 return true; 2091 } 2092 // Conversions with Objective-C's id<...>. 2093 if ((FromObjCPtr->isObjCQualifiedIdType() || 2094 ToObjCPtr->isObjCQualifiedIdType()) && 2095 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2096 /*compare=*/false)) { 2097 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2098 return true; 2099 } 2100 // Objective C++: We're able to convert from a pointer to an 2101 // interface to a pointer to a different interface. 2102 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2103 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2104 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2105 if (getLangOpts().CPlusPlus && LHS && RHS && 2106 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2107 FromObjCPtr->getPointeeType())) 2108 return false; 2109 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2110 ToObjCPtr->getPointeeType(), 2111 ToType, Context); 2112 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2113 return true; 2114 } 2115 2116 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2117 // Okay: this is some kind of implicit downcast of Objective-C 2118 // interfaces, which is permitted. However, we're going to 2119 // complain about it. 2120 IncompatibleObjC = true; 2121 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2122 ToObjCPtr->getPointeeType(), 2123 ToType, Context); 2124 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2125 return true; 2126 } 2127 } 2128 // Beyond this point, both types need to be C pointers or block pointers. 2129 QualType ToPointeeType; 2130 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2131 ToPointeeType = ToCPtr->getPointeeType(); 2132 else if (const BlockPointerType *ToBlockPtr = 2133 ToType->getAs<BlockPointerType>()) { 2134 // Objective C++: We're able to convert from a pointer to any object 2135 // to a block pointer type. 2136 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2137 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2138 return true; 2139 } 2140 ToPointeeType = ToBlockPtr->getPointeeType(); 2141 } 2142 else if (FromType->getAs<BlockPointerType>() && 2143 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2144 // Objective C++: We're able to convert from a block pointer type to a 2145 // pointer to any object. 2146 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2147 return true; 2148 } 2149 else 2150 return false; 2151 2152 QualType FromPointeeType; 2153 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2154 FromPointeeType = FromCPtr->getPointeeType(); 2155 else if (const BlockPointerType *FromBlockPtr = 2156 FromType->getAs<BlockPointerType>()) 2157 FromPointeeType = FromBlockPtr->getPointeeType(); 2158 else 2159 return false; 2160 2161 // If we have pointers to pointers, recursively check whether this 2162 // is an Objective-C conversion. 2163 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2164 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2165 IncompatibleObjC)) { 2166 // We always complain about this conversion. 2167 IncompatibleObjC = true; 2168 ConvertedType = Context.getPointerType(ConvertedType); 2169 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2170 return true; 2171 } 2172 // Allow conversion of pointee being objective-c pointer to another one; 2173 // as in I* to id. 2174 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2175 ToPointeeType->getAs<ObjCObjectPointerType>() && 2176 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2177 IncompatibleObjC)) { 2178 2179 ConvertedType = Context.getPointerType(ConvertedType); 2180 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2181 return true; 2182 } 2183 2184 // If we have pointers to functions or blocks, check whether the only 2185 // differences in the argument and result types are in Objective-C 2186 // pointer conversions. If so, we permit the conversion (but 2187 // complain about it). 2188 const FunctionProtoType *FromFunctionType 2189 = FromPointeeType->getAs<FunctionProtoType>(); 2190 const FunctionProtoType *ToFunctionType 2191 = ToPointeeType->getAs<FunctionProtoType>(); 2192 if (FromFunctionType && ToFunctionType) { 2193 // If the function types are exactly the same, this isn't an 2194 // Objective-C pointer conversion. 2195 if (Context.getCanonicalType(FromPointeeType) 2196 == Context.getCanonicalType(ToPointeeType)) 2197 return false; 2198 2199 // Perform the quick checks that will tell us whether these 2200 // function types are obviously different. 2201 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2202 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2203 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2204 return false; 2205 2206 bool HasObjCConversion = false; 2207 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2208 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2209 // Okay, the types match exactly. Nothing to do. 2210 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2211 ToFunctionType->getResultType(), 2212 ConvertedType, IncompatibleObjC)) { 2213 // Okay, we have an Objective-C pointer conversion. 2214 HasObjCConversion = true; 2215 } else { 2216 // Function types are too different. Abort. 2217 return false; 2218 } 2219 2220 // Check argument types. 2221 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2222 ArgIdx != NumArgs; ++ArgIdx) { 2223 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2224 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2225 if (Context.getCanonicalType(FromArgType) 2226 == Context.getCanonicalType(ToArgType)) { 2227 // Okay, the types match exactly. Nothing to do. 2228 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2229 ConvertedType, IncompatibleObjC)) { 2230 // Okay, we have an Objective-C pointer conversion. 2231 HasObjCConversion = true; 2232 } else { 2233 // Argument types are too different. Abort. 2234 return false; 2235 } 2236 } 2237 2238 if (HasObjCConversion) { 2239 // We had an Objective-C conversion. Allow this pointer 2240 // conversion, but complain about it. 2241 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2242 IncompatibleObjC = true; 2243 return true; 2244 } 2245 } 2246 2247 return false; 2248} 2249 2250/// \brief Determine whether this is an Objective-C writeback conversion, 2251/// used for parameter passing when performing automatic reference counting. 2252/// 2253/// \param FromType The type we're converting form. 2254/// 2255/// \param ToType The type we're converting to. 2256/// 2257/// \param ConvertedType The type that will be produced after applying 2258/// this conversion. 2259bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2260 QualType &ConvertedType) { 2261 if (!getLangOpts().ObjCAutoRefCount || 2262 Context.hasSameUnqualifiedType(FromType, ToType)) 2263 return false; 2264 2265 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2266 QualType ToPointee; 2267 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2268 ToPointee = ToPointer->getPointeeType(); 2269 else 2270 return false; 2271 2272 Qualifiers ToQuals = ToPointee.getQualifiers(); 2273 if (!ToPointee->isObjCLifetimeType() || 2274 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2275 !ToQuals.withoutObjCLifetime().empty()) 2276 return false; 2277 2278 // Argument must be a pointer to __strong to __weak. 2279 QualType FromPointee; 2280 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2281 FromPointee = FromPointer->getPointeeType(); 2282 else 2283 return false; 2284 2285 Qualifiers FromQuals = FromPointee.getQualifiers(); 2286 if (!FromPointee->isObjCLifetimeType() || 2287 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2288 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2289 return false; 2290 2291 // Make sure that we have compatible qualifiers. 2292 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2293 if (!ToQuals.compatiblyIncludes(FromQuals)) 2294 return false; 2295 2296 // Remove qualifiers from the pointee type we're converting from; they 2297 // aren't used in the compatibility check belong, and we'll be adding back 2298 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2299 FromPointee = FromPointee.getUnqualifiedType(); 2300 2301 // The unqualified form of the pointee types must be compatible. 2302 ToPointee = ToPointee.getUnqualifiedType(); 2303 bool IncompatibleObjC; 2304 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2305 FromPointee = ToPointee; 2306 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2307 IncompatibleObjC)) 2308 return false; 2309 2310 /// \brief Construct the type we're converting to, which is a pointer to 2311 /// __autoreleasing pointee. 2312 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2313 ConvertedType = Context.getPointerType(FromPointee); 2314 return true; 2315} 2316 2317bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2318 QualType& ConvertedType) { 2319 QualType ToPointeeType; 2320 if (const BlockPointerType *ToBlockPtr = 2321 ToType->getAs<BlockPointerType>()) 2322 ToPointeeType = ToBlockPtr->getPointeeType(); 2323 else 2324 return false; 2325 2326 QualType FromPointeeType; 2327 if (const BlockPointerType *FromBlockPtr = 2328 FromType->getAs<BlockPointerType>()) 2329 FromPointeeType = FromBlockPtr->getPointeeType(); 2330 else 2331 return false; 2332 // We have pointer to blocks, check whether the only 2333 // differences in the argument and result types are in Objective-C 2334 // pointer conversions. If so, we permit the conversion. 2335 2336 const FunctionProtoType *FromFunctionType 2337 = FromPointeeType->getAs<FunctionProtoType>(); 2338 const FunctionProtoType *ToFunctionType 2339 = ToPointeeType->getAs<FunctionProtoType>(); 2340 2341 if (!FromFunctionType || !ToFunctionType) 2342 return false; 2343 2344 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2345 return true; 2346 2347 // Perform the quick checks that will tell us whether these 2348 // function types are obviously different. 2349 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2350 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2351 return false; 2352 2353 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2354 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2355 if (FromEInfo != ToEInfo) 2356 return false; 2357 2358 bool IncompatibleObjC = false; 2359 if (Context.hasSameType(FromFunctionType->getResultType(), 2360 ToFunctionType->getResultType())) { 2361 // Okay, the types match exactly. Nothing to do. 2362 } else { 2363 QualType RHS = FromFunctionType->getResultType(); 2364 QualType LHS = ToFunctionType->getResultType(); 2365 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2366 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2367 LHS = LHS.getUnqualifiedType(); 2368 2369 if (Context.hasSameType(RHS,LHS)) { 2370 // OK exact match. 2371 } else if (isObjCPointerConversion(RHS, LHS, 2372 ConvertedType, IncompatibleObjC)) { 2373 if (IncompatibleObjC) 2374 return false; 2375 // Okay, we have an Objective-C pointer conversion. 2376 } 2377 else 2378 return false; 2379 } 2380 2381 // Check argument types. 2382 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2383 ArgIdx != NumArgs; ++ArgIdx) { 2384 IncompatibleObjC = false; 2385 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2386 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2387 if (Context.hasSameType(FromArgType, ToArgType)) { 2388 // Okay, the types match exactly. Nothing to do. 2389 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2390 ConvertedType, IncompatibleObjC)) { 2391 if (IncompatibleObjC) 2392 return false; 2393 // Okay, we have an Objective-C pointer conversion. 2394 } else 2395 // Argument types are too different. Abort. 2396 return false; 2397 } 2398 if (LangOpts.ObjCAutoRefCount && 2399 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2400 ToFunctionType)) 2401 return false; 2402 2403 ConvertedType = ToType; 2404 return true; 2405} 2406 2407enum { 2408 ft_default, 2409 ft_different_class, 2410 ft_parameter_arity, 2411 ft_parameter_mismatch, 2412 ft_return_type, 2413 ft_qualifer_mismatch 2414}; 2415 2416/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2417/// function types. Catches different number of parameter, mismatch in 2418/// parameter types, and different return types. 2419void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2420 QualType FromType, QualType ToType) { 2421 // If either type is not valid, include no extra info. 2422 if (FromType.isNull() || ToType.isNull()) { 2423 PDiag << ft_default; 2424 return; 2425 } 2426 2427 // Get the function type from the pointers. 2428 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2429 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2430 *ToMember = ToType->getAs<MemberPointerType>(); 2431 if (FromMember->getClass() != ToMember->getClass()) { 2432 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2433 << QualType(FromMember->getClass(), 0); 2434 return; 2435 } 2436 FromType = FromMember->getPointeeType(); 2437 ToType = ToMember->getPointeeType(); 2438 } 2439 2440 if (FromType->isPointerType()) 2441 FromType = FromType->getPointeeType(); 2442 if (ToType->isPointerType()) 2443 ToType = ToType->getPointeeType(); 2444 2445 // Remove references. 2446 FromType = FromType.getNonReferenceType(); 2447 ToType = ToType.getNonReferenceType(); 2448 2449 // Don't print extra info for non-specialized template functions. 2450 if (FromType->isInstantiationDependentType() && 2451 !FromType->getAs<TemplateSpecializationType>()) { 2452 PDiag << ft_default; 2453 return; 2454 } 2455 2456 // No extra info for same types. 2457 if (Context.hasSameType(FromType, ToType)) { 2458 PDiag << ft_default; 2459 return; 2460 } 2461 2462 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2463 *ToFunction = ToType->getAs<FunctionProtoType>(); 2464 2465 // Both types need to be function types. 2466 if (!FromFunction || !ToFunction) { 2467 PDiag << ft_default; 2468 return; 2469 } 2470 2471 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2472 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2473 << FromFunction->getNumArgs(); 2474 return; 2475 } 2476 2477 // Handle different parameter types. 2478 unsigned ArgPos; 2479 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2480 PDiag << ft_parameter_mismatch << ArgPos + 1 2481 << ToFunction->getArgType(ArgPos) 2482 << FromFunction->getArgType(ArgPos); 2483 return; 2484 } 2485 2486 // Handle different return type. 2487 if (!Context.hasSameType(FromFunction->getResultType(), 2488 ToFunction->getResultType())) { 2489 PDiag << ft_return_type << ToFunction->getResultType() 2490 << FromFunction->getResultType(); 2491 return; 2492 } 2493 2494 unsigned FromQuals = FromFunction->getTypeQuals(), 2495 ToQuals = ToFunction->getTypeQuals(); 2496 if (FromQuals != ToQuals) { 2497 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2498 return; 2499 } 2500 2501 // Unable to find a difference, so add no extra info. 2502 PDiag << ft_default; 2503} 2504 2505/// FunctionArgTypesAreEqual - This routine checks two function proto types 2506/// for equality of their argument types. Caller has already checked that 2507/// they have same number of arguments. This routine assumes that Objective-C 2508/// pointer types which only differ in their protocol qualifiers are equal. 2509/// If the parameters are different, ArgPos will have the parameter index 2510/// of the first different parameter. 2511bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2512 const FunctionProtoType *NewType, 2513 unsigned *ArgPos) { 2514 if (!getLangOpts().ObjC1) { 2515 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2516 N = NewType->arg_type_begin(), 2517 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2518 if (!Context.hasSameType(*O, *N)) { 2519 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2520 return false; 2521 } 2522 } 2523 return true; 2524 } 2525 2526 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2527 N = NewType->arg_type_begin(), 2528 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2529 QualType ToType = (*O); 2530 QualType FromType = (*N); 2531 if (!Context.hasSameType(ToType, FromType)) { 2532 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2533 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2534 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2535 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2536 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2537 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2538 continue; 2539 } 2540 else if (const ObjCObjectPointerType *PTTo = 2541 ToType->getAs<ObjCObjectPointerType>()) { 2542 if (const ObjCObjectPointerType *PTFr = 2543 FromType->getAs<ObjCObjectPointerType>()) 2544 if (Context.hasSameUnqualifiedType( 2545 PTTo->getObjectType()->getBaseType(), 2546 PTFr->getObjectType()->getBaseType())) 2547 continue; 2548 } 2549 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2550 return false; 2551 } 2552 } 2553 return true; 2554} 2555 2556/// CheckPointerConversion - Check the pointer conversion from the 2557/// expression From to the type ToType. This routine checks for 2558/// ambiguous or inaccessible derived-to-base pointer 2559/// conversions for which IsPointerConversion has already returned 2560/// true. It returns true and produces a diagnostic if there was an 2561/// error, or returns false otherwise. 2562bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2563 CastKind &Kind, 2564 CXXCastPath& BasePath, 2565 bool IgnoreBaseAccess) { 2566 QualType FromType = From->getType(); 2567 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2568 2569 Kind = CK_BitCast; 2570 2571 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2572 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2573 Expr::NPCK_ZeroExpression) { 2574 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2575 DiagRuntimeBehavior(From->getExprLoc(), From, 2576 PDiag(diag::warn_impcast_bool_to_null_pointer) 2577 << ToType << From->getSourceRange()); 2578 else if (!isUnevaluatedContext()) 2579 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2580 << ToType << From->getSourceRange(); 2581 } 2582 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2583 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2584 QualType FromPointeeType = FromPtrType->getPointeeType(), 2585 ToPointeeType = ToPtrType->getPointeeType(); 2586 2587 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2588 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2589 // We must have a derived-to-base conversion. Check an 2590 // ambiguous or inaccessible conversion. 2591 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2592 From->getExprLoc(), 2593 From->getSourceRange(), &BasePath, 2594 IgnoreBaseAccess)) 2595 return true; 2596 2597 // The conversion was successful. 2598 Kind = CK_DerivedToBase; 2599 } 2600 } 2601 } else if (const ObjCObjectPointerType *ToPtrType = 2602 ToType->getAs<ObjCObjectPointerType>()) { 2603 if (const ObjCObjectPointerType *FromPtrType = 2604 FromType->getAs<ObjCObjectPointerType>()) { 2605 // Objective-C++ conversions are always okay. 2606 // FIXME: We should have a different class of conversions for the 2607 // Objective-C++ implicit conversions. 2608 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2609 return false; 2610 } else if (FromType->isBlockPointerType()) { 2611 Kind = CK_BlockPointerToObjCPointerCast; 2612 } else { 2613 Kind = CK_CPointerToObjCPointerCast; 2614 } 2615 } else if (ToType->isBlockPointerType()) { 2616 if (!FromType->isBlockPointerType()) 2617 Kind = CK_AnyPointerToBlockPointerCast; 2618 } 2619 2620 // We shouldn't fall into this case unless it's valid for other 2621 // reasons. 2622 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2623 Kind = CK_NullToPointer; 2624 2625 return false; 2626} 2627 2628/// IsMemberPointerConversion - Determines whether the conversion of the 2629/// expression From, which has the (possibly adjusted) type FromType, can be 2630/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2631/// If so, returns true and places the converted type (that might differ from 2632/// ToType in its cv-qualifiers at some level) into ConvertedType. 2633bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2634 QualType ToType, 2635 bool InOverloadResolution, 2636 QualType &ConvertedType) { 2637 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2638 if (!ToTypePtr) 2639 return false; 2640 2641 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2642 if (From->isNullPointerConstant(Context, 2643 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2644 : Expr::NPC_ValueDependentIsNull)) { 2645 ConvertedType = ToType; 2646 return true; 2647 } 2648 2649 // Otherwise, both types have to be member pointers. 2650 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2651 if (!FromTypePtr) 2652 return false; 2653 2654 // A pointer to member of B can be converted to a pointer to member of D, 2655 // where D is derived from B (C++ 4.11p2). 2656 QualType FromClass(FromTypePtr->getClass(), 0); 2657 QualType ToClass(ToTypePtr->getClass(), 0); 2658 2659 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2660 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2661 IsDerivedFrom(ToClass, FromClass)) { 2662 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2663 ToClass.getTypePtr()); 2664 return true; 2665 } 2666 2667 return false; 2668} 2669 2670/// CheckMemberPointerConversion - Check the member pointer conversion from the 2671/// expression From to the type ToType. This routine checks for ambiguous or 2672/// virtual or inaccessible base-to-derived member pointer conversions 2673/// for which IsMemberPointerConversion has already returned true. It returns 2674/// true and produces a diagnostic if there was an error, or returns false 2675/// otherwise. 2676bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2677 CastKind &Kind, 2678 CXXCastPath &BasePath, 2679 bool IgnoreBaseAccess) { 2680 QualType FromType = From->getType(); 2681 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2682 if (!FromPtrType) { 2683 // This must be a null pointer to member pointer conversion 2684 assert(From->isNullPointerConstant(Context, 2685 Expr::NPC_ValueDependentIsNull) && 2686 "Expr must be null pointer constant!"); 2687 Kind = CK_NullToMemberPointer; 2688 return false; 2689 } 2690 2691 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2692 assert(ToPtrType && "No member pointer cast has a target type " 2693 "that is not a member pointer."); 2694 2695 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2696 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2697 2698 // FIXME: What about dependent types? 2699 assert(FromClass->isRecordType() && "Pointer into non-class."); 2700 assert(ToClass->isRecordType() && "Pointer into non-class."); 2701 2702 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2703 /*DetectVirtual=*/true); 2704 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2705 assert(DerivationOkay && 2706 "Should not have been called if derivation isn't OK."); 2707 (void)DerivationOkay; 2708 2709 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2710 getUnqualifiedType())) { 2711 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2712 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2713 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2714 return true; 2715 } 2716 2717 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2718 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2719 << FromClass << ToClass << QualType(VBase, 0) 2720 << From->getSourceRange(); 2721 return true; 2722 } 2723 2724 if (!IgnoreBaseAccess) 2725 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2726 Paths.front(), 2727 diag::err_downcast_from_inaccessible_base); 2728 2729 // Must be a base to derived member conversion. 2730 BuildBasePathArray(Paths, BasePath); 2731 Kind = CK_BaseToDerivedMemberPointer; 2732 return false; 2733} 2734 2735/// IsQualificationConversion - Determines whether the conversion from 2736/// an rvalue of type FromType to ToType is a qualification conversion 2737/// (C++ 4.4). 2738/// 2739/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2740/// when the qualification conversion involves a change in the Objective-C 2741/// object lifetime. 2742bool 2743Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2744 bool CStyle, bool &ObjCLifetimeConversion) { 2745 FromType = Context.getCanonicalType(FromType); 2746 ToType = Context.getCanonicalType(ToType); 2747 ObjCLifetimeConversion = false; 2748 2749 // If FromType and ToType are the same type, this is not a 2750 // qualification conversion. 2751 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2752 return false; 2753 2754 // (C++ 4.4p4): 2755 // A conversion can add cv-qualifiers at levels other than the first 2756 // in multi-level pointers, subject to the following rules: [...] 2757 bool PreviousToQualsIncludeConst = true; 2758 bool UnwrappedAnyPointer = false; 2759 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2760 // Within each iteration of the loop, we check the qualifiers to 2761 // determine if this still looks like a qualification 2762 // conversion. Then, if all is well, we unwrap one more level of 2763 // pointers or pointers-to-members and do it all again 2764 // until there are no more pointers or pointers-to-members left to 2765 // unwrap. 2766 UnwrappedAnyPointer = true; 2767 2768 Qualifiers FromQuals = FromType.getQualifiers(); 2769 Qualifiers ToQuals = ToType.getQualifiers(); 2770 2771 // Objective-C ARC: 2772 // Check Objective-C lifetime conversions. 2773 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2774 UnwrappedAnyPointer) { 2775 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2776 ObjCLifetimeConversion = true; 2777 FromQuals.removeObjCLifetime(); 2778 ToQuals.removeObjCLifetime(); 2779 } else { 2780 // Qualification conversions cannot cast between different 2781 // Objective-C lifetime qualifiers. 2782 return false; 2783 } 2784 } 2785 2786 // Allow addition/removal of GC attributes but not changing GC attributes. 2787 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2788 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2789 FromQuals.removeObjCGCAttr(); 2790 ToQuals.removeObjCGCAttr(); 2791 } 2792 2793 // -- for every j > 0, if const is in cv 1,j then const is in cv 2794 // 2,j, and similarly for volatile. 2795 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2796 return false; 2797 2798 // -- if the cv 1,j and cv 2,j are different, then const is in 2799 // every cv for 0 < k < j. 2800 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2801 && !PreviousToQualsIncludeConst) 2802 return false; 2803 2804 // Keep track of whether all prior cv-qualifiers in the "to" type 2805 // include const. 2806 PreviousToQualsIncludeConst 2807 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2808 } 2809 2810 // We are left with FromType and ToType being the pointee types 2811 // after unwrapping the original FromType and ToType the same number 2812 // of types. If we unwrapped any pointers, and if FromType and 2813 // ToType have the same unqualified type (since we checked 2814 // qualifiers above), then this is a qualification conversion. 2815 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2816} 2817 2818/// \brief - Determine whether this is a conversion from a scalar type to an 2819/// atomic type. 2820/// 2821/// If successful, updates \c SCS's second and third steps in the conversion 2822/// sequence to finish the conversion. 2823static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2824 bool InOverloadResolution, 2825 StandardConversionSequence &SCS, 2826 bool CStyle) { 2827 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2828 if (!ToAtomic) 2829 return false; 2830 2831 StandardConversionSequence InnerSCS; 2832 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2833 InOverloadResolution, InnerSCS, 2834 CStyle, /*AllowObjCWritebackConversion=*/false)) 2835 return false; 2836 2837 SCS.Second = InnerSCS.Second; 2838 SCS.setToType(1, InnerSCS.getToType(1)); 2839 SCS.Third = InnerSCS.Third; 2840 SCS.QualificationIncludesObjCLifetime 2841 = InnerSCS.QualificationIncludesObjCLifetime; 2842 SCS.setToType(2, InnerSCS.getToType(2)); 2843 return true; 2844} 2845 2846static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2847 CXXConstructorDecl *Constructor, 2848 QualType Type) { 2849 const FunctionProtoType *CtorType = 2850 Constructor->getType()->getAs<FunctionProtoType>(); 2851 if (CtorType->getNumArgs() > 0) { 2852 QualType FirstArg = CtorType->getArgType(0); 2853 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2854 return true; 2855 } 2856 return false; 2857} 2858 2859static OverloadingResult 2860IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2861 CXXRecordDecl *To, 2862 UserDefinedConversionSequence &User, 2863 OverloadCandidateSet &CandidateSet, 2864 bool AllowExplicit) { 2865 DeclContext::lookup_iterator Con, ConEnd; 2866 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To); 2867 Con != ConEnd; ++Con) { 2868 NamedDecl *D = *Con; 2869 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2870 2871 // Find the constructor (which may be a template). 2872 CXXConstructorDecl *Constructor = 0; 2873 FunctionTemplateDecl *ConstructorTmpl 2874 = dyn_cast<FunctionTemplateDecl>(D); 2875 if (ConstructorTmpl) 2876 Constructor 2877 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2878 else 2879 Constructor = cast<CXXConstructorDecl>(D); 2880 2881 bool Usable = !Constructor->isInvalidDecl() && 2882 S.isInitListConstructor(Constructor) && 2883 (AllowExplicit || !Constructor->isExplicit()); 2884 if (Usable) { 2885 // If the first argument is (a reference to) the target type, 2886 // suppress conversions. 2887 bool SuppressUserConversions = 2888 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2889 if (ConstructorTmpl) 2890 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2891 /*ExplicitArgs*/ 0, 2892 From, CandidateSet, 2893 SuppressUserConversions); 2894 else 2895 S.AddOverloadCandidate(Constructor, FoundDecl, 2896 From, CandidateSet, 2897 SuppressUserConversions); 2898 } 2899 } 2900 2901 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2902 2903 OverloadCandidateSet::iterator Best; 2904 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2905 case OR_Success: { 2906 // Record the standard conversion we used and the conversion function. 2907 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2908 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 2909 2910 QualType ThisType = Constructor->getThisType(S.Context); 2911 // Initializer lists don't have conversions as such. 2912 User.Before.setAsIdentityConversion(); 2913 User.HadMultipleCandidates = HadMultipleCandidates; 2914 User.ConversionFunction = Constructor; 2915 User.FoundConversionFunction = Best->FoundDecl; 2916 User.After.setAsIdentityConversion(); 2917 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2918 User.After.setAllToTypes(ToType); 2919 return OR_Success; 2920 } 2921 2922 case OR_No_Viable_Function: 2923 return OR_No_Viable_Function; 2924 case OR_Deleted: 2925 return OR_Deleted; 2926 case OR_Ambiguous: 2927 return OR_Ambiguous; 2928 } 2929 2930 llvm_unreachable("Invalid OverloadResult!"); 2931} 2932 2933/// Determines whether there is a user-defined conversion sequence 2934/// (C++ [over.ics.user]) that converts expression From to the type 2935/// ToType. If such a conversion exists, User will contain the 2936/// user-defined conversion sequence that performs such a conversion 2937/// and this routine will return true. Otherwise, this routine returns 2938/// false and User is unspecified. 2939/// 2940/// \param AllowExplicit true if the conversion should consider C++0x 2941/// "explicit" conversion functions as well as non-explicit conversion 2942/// functions (C++0x [class.conv.fct]p2). 2943static OverloadingResult 2944IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2945 UserDefinedConversionSequence &User, 2946 OverloadCandidateSet &CandidateSet, 2947 bool AllowExplicit) { 2948 // Whether we will only visit constructors. 2949 bool ConstructorsOnly = false; 2950 2951 // If the type we are conversion to is a class type, enumerate its 2952 // constructors. 2953 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2954 // C++ [over.match.ctor]p1: 2955 // When objects of class type are direct-initialized (8.5), or 2956 // copy-initialized from an expression of the same or a 2957 // derived class type (8.5), overload resolution selects the 2958 // constructor. [...] For copy-initialization, the candidate 2959 // functions are all the converting constructors (12.3.1) of 2960 // that class. The argument list is the expression-list within 2961 // the parentheses of the initializer. 2962 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 2963 (From->getType()->getAs<RecordType>() && 2964 S.IsDerivedFrom(From->getType(), ToType))) 2965 ConstructorsOnly = true; 2966 2967 S.RequireCompleteType(From->getLocStart(), ToType, 0); 2968 // RequireCompleteType may have returned true due to some invalid decl 2969 // during template instantiation, but ToType may be complete enough now 2970 // to try to recover. 2971 if (ToType->isIncompleteType()) { 2972 // We're not going to find any constructors. 2973 } else if (CXXRecordDecl *ToRecordDecl 2974 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 2975 2976 Expr **Args = &From; 2977 unsigned NumArgs = 1; 2978 bool ListInitializing = false; 2979 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 2980 // But first, see if there is an init-list-contructor that will work. 2981 OverloadingResult Result = IsInitializerListConstructorConversion( 2982 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 2983 if (Result != OR_No_Viable_Function) 2984 return Result; 2985 // Never mind. 2986 CandidateSet.clear(); 2987 2988 // If we're list-initializing, we pass the individual elements as 2989 // arguments, not the entire list. 2990 Args = InitList->getInits(); 2991 NumArgs = InitList->getNumInits(); 2992 ListInitializing = true; 2993 } 2994 2995 DeclContext::lookup_iterator Con, ConEnd; 2996 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl); 2997 Con != ConEnd; ++Con) { 2998 NamedDecl *D = *Con; 2999 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3000 3001 // Find the constructor (which may be a template). 3002 CXXConstructorDecl *Constructor = 0; 3003 FunctionTemplateDecl *ConstructorTmpl 3004 = dyn_cast<FunctionTemplateDecl>(D); 3005 if (ConstructorTmpl) 3006 Constructor 3007 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3008 else 3009 Constructor = cast<CXXConstructorDecl>(D); 3010 3011 bool Usable = !Constructor->isInvalidDecl(); 3012 if (ListInitializing) 3013 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3014 else 3015 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3016 if (Usable) { 3017 bool SuppressUserConversions = !ConstructorsOnly; 3018 if (SuppressUserConversions && ListInitializing) { 3019 SuppressUserConversions = false; 3020 if (NumArgs == 1) { 3021 // If the first argument is (a reference to) the target type, 3022 // suppress conversions. 3023 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3024 S.Context, Constructor, ToType); 3025 } 3026 } 3027 if (ConstructorTmpl) 3028 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3029 /*ExplicitArgs*/ 0, 3030 llvm::makeArrayRef(Args, NumArgs), 3031 CandidateSet, SuppressUserConversions); 3032 else 3033 // Allow one user-defined conversion when user specifies a 3034 // From->ToType conversion via an static cast (c-style, etc). 3035 S.AddOverloadCandidate(Constructor, FoundDecl, 3036 llvm::makeArrayRef(Args, NumArgs), 3037 CandidateSet, SuppressUserConversions); 3038 } 3039 } 3040 } 3041 } 3042 3043 // Enumerate conversion functions, if we're allowed to. 3044 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3045 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3046 // No conversion functions from incomplete types. 3047 } else if (const RecordType *FromRecordType 3048 = From->getType()->getAs<RecordType>()) { 3049 if (CXXRecordDecl *FromRecordDecl 3050 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3051 // Add all of the conversion functions as candidates. 3052 const UnresolvedSetImpl *Conversions 3053 = FromRecordDecl->getVisibleConversionFunctions(); 3054 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3055 E = Conversions->end(); I != E; ++I) { 3056 DeclAccessPair FoundDecl = I.getPair(); 3057 NamedDecl *D = FoundDecl.getDecl(); 3058 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3059 if (isa<UsingShadowDecl>(D)) 3060 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3061 3062 CXXConversionDecl *Conv; 3063 FunctionTemplateDecl *ConvTemplate; 3064 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3065 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3066 else 3067 Conv = cast<CXXConversionDecl>(D); 3068 3069 if (AllowExplicit || !Conv->isExplicit()) { 3070 if (ConvTemplate) 3071 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3072 ActingContext, From, ToType, 3073 CandidateSet); 3074 else 3075 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3076 From, ToType, CandidateSet); 3077 } 3078 } 3079 } 3080 } 3081 3082 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3083 3084 OverloadCandidateSet::iterator Best; 3085 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3086 case OR_Success: 3087 // Record the standard conversion we used and the conversion function. 3088 if (CXXConstructorDecl *Constructor 3089 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3090 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 3091 3092 // C++ [over.ics.user]p1: 3093 // If the user-defined conversion is specified by a 3094 // constructor (12.3.1), the initial standard conversion 3095 // sequence converts the source type to the type required by 3096 // the argument of the constructor. 3097 // 3098 QualType ThisType = Constructor->getThisType(S.Context); 3099 if (isa<InitListExpr>(From)) { 3100 // Initializer lists don't have conversions as such. 3101 User.Before.setAsIdentityConversion(); 3102 } else { 3103 if (Best->Conversions[0].isEllipsis()) 3104 User.EllipsisConversion = true; 3105 else { 3106 User.Before = Best->Conversions[0].Standard; 3107 User.EllipsisConversion = false; 3108 } 3109 } 3110 User.HadMultipleCandidates = HadMultipleCandidates; 3111 User.ConversionFunction = Constructor; 3112 User.FoundConversionFunction = Best->FoundDecl; 3113 User.After.setAsIdentityConversion(); 3114 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3115 User.After.setAllToTypes(ToType); 3116 return OR_Success; 3117 } 3118 if (CXXConversionDecl *Conversion 3119 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3120 S.MarkFunctionReferenced(From->getLocStart(), Conversion); 3121 3122 // C++ [over.ics.user]p1: 3123 // 3124 // [...] If the user-defined conversion is specified by a 3125 // conversion function (12.3.2), the initial standard 3126 // conversion sequence converts the source type to the 3127 // implicit object parameter of the conversion function. 3128 User.Before = Best->Conversions[0].Standard; 3129 User.HadMultipleCandidates = HadMultipleCandidates; 3130 User.ConversionFunction = Conversion; 3131 User.FoundConversionFunction = Best->FoundDecl; 3132 User.EllipsisConversion = false; 3133 3134 // C++ [over.ics.user]p2: 3135 // The second standard conversion sequence converts the 3136 // result of the user-defined conversion to the target type 3137 // for the sequence. Since an implicit conversion sequence 3138 // is an initialization, the special rules for 3139 // initialization by user-defined conversion apply when 3140 // selecting the best user-defined conversion for a 3141 // user-defined conversion sequence (see 13.3.3 and 3142 // 13.3.3.1). 3143 User.After = Best->FinalConversion; 3144 return OR_Success; 3145 } 3146 llvm_unreachable("Not a constructor or conversion function?"); 3147 3148 case OR_No_Viable_Function: 3149 return OR_No_Viable_Function; 3150 case OR_Deleted: 3151 // No conversion here! We're done. 3152 return OR_Deleted; 3153 3154 case OR_Ambiguous: 3155 return OR_Ambiguous; 3156 } 3157 3158 llvm_unreachable("Invalid OverloadResult!"); 3159} 3160 3161bool 3162Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3163 ImplicitConversionSequence ICS; 3164 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3165 OverloadingResult OvResult = 3166 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3167 CandidateSet, false); 3168 if (OvResult == OR_Ambiguous) 3169 Diag(From->getLocStart(), 3170 diag::err_typecheck_ambiguous_condition) 3171 << From->getType() << ToType << From->getSourceRange(); 3172 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3173 Diag(From->getLocStart(), 3174 diag::err_typecheck_nonviable_condition) 3175 << From->getType() << ToType << From->getSourceRange(); 3176 else 3177 return false; 3178 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3179 return true; 3180} 3181 3182/// \brief Compare the user-defined conversion functions or constructors 3183/// of two user-defined conversion sequences to determine whether any ordering 3184/// is possible. 3185static ImplicitConversionSequence::CompareKind 3186compareConversionFunctions(Sema &S, 3187 FunctionDecl *Function1, 3188 FunctionDecl *Function2) { 3189 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x) 3190 return ImplicitConversionSequence::Indistinguishable; 3191 3192 // Objective-C++: 3193 // If both conversion functions are implicitly-declared conversions from 3194 // a lambda closure type to a function pointer and a block pointer, 3195 // respectively, always prefer the conversion to a function pointer, 3196 // because the function pointer is more lightweight and is more likely 3197 // to keep code working. 3198 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3199 if (!Conv1) 3200 return ImplicitConversionSequence::Indistinguishable; 3201 3202 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3203 if (!Conv2) 3204 return ImplicitConversionSequence::Indistinguishable; 3205 3206 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3207 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3208 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3209 if (Block1 != Block2) 3210 return Block1? ImplicitConversionSequence::Worse 3211 : ImplicitConversionSequence::Better; 3212 } 3213 3214 return ImplicitConversionSequence::Indistinguishable; 3215} 3216 3217/// CompareImplicitConversionSequences - Compare two implicit 3218/// conversion sequences to determine whether one is better than the 3219/// other or if they are indistinguishable (C++ 13.3.3.2). 3220static ImplicitConversionSequence::CompareKind 3221CompareImplicitConversionSequences(Sema &S, 3222 const ImplicitConversionSequence& ICS1, 3223 const ImplicitConversionSequence& ICS2) 3224{ 3225 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3226 // conversion sequences (as defined in 13.3.3.1) 3227 // -- a standard conversion sequence (13.3.3.1.1) is a better 3228 // conversion sequence than a user-defined conversion sequence or 3229 // an ellipsis conversion sequence, and 3230 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3231 // conversion sequence than an ellipsis conversion sequence 3232 // (13.3.3.1.3). 3233 // 3234 // C++0x [over.best.ics]p10: 3235 // For the purpose of ranking implicit conversion sequences as 3236 // described in 13.3.3.2, the ambiguous conversion sequence is 3237 // treated as a user-defined sequence that is indistinguishable 3238 // from any other user-defined conversion sequence. 3239 if (ICS1.getKindRank() < ICS2.getKindRank()) 3240 return ImplicitConversionSequence::Better; 3241 if (ICS2.getKindRank() < ICS1.getKindRank()) 3242 return ImplicitConversionSequence::Worse; 3243 3244 // The following checks require both conversion sequences to be of 3245 // the same kind. 3246 if (ICS1.getKind() != ICS2.getKind()) 3247 return ImplicitConversionSequence::Indistinguishable; 3248 3249 ImplicitConversionSequence::CompareKind Result = 3250 ImplicitConversionSequence::Indistinguishable; 3251 3252 // Two implicit conversion sequences of the same form are 3253 // indistinguishable conversion sequences unless one of the 3254 // following rules apply: (C++ 13.3.3.2p3): 3255 if (ICS1.isStandard()) 3256 Result = CompareStandardConversionSequences(S, 3257 ICS1.Standard, ICS2.Standard); 3258 else if (ICS1.isUserDefined()) { 3259 // User-defined conversion sequence U1 is a better conversion 3260 // sequence than another user-defined conversion sequence U2 if 3261 // they contain the same user-defined conversion function or 3262 // constructor and if the second standard conversion sequence of 3263 // U1 is better than the second standard conversion sequence of 3264 // U2 (C++ 13.3.3.2p3). 3265 if (ICS1.UserDefined.ConversionFunction == 3266 ICS2.UserDefined.ConversionFunction) 3267 Result = CompareStandardConversionSequences(S, 3268 ICS1.UserDefined.After, 3269 ICS2.UserDefined.After); 3270 else 3271 Result = compareConversionFunctions(S, 3272 ICS1.UserDefined.ConversionFunction, 3273 ICS2.UserDefined.ConversionFunction); 3274 } 3275 3276 // List-initialization sequence L1 is a better conversion sequence than 3277 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3278 // for some X and L2 does not. 3279 if (Result == ImplicitConversionSequence::Indistinguishable && 3280 !ICS1.isBad() && 3281 ICS1.isListInitializationSequence() && 3282 ICS2.isListInitializationSequence()) { 3283 if (ICS1.isStdInitializerListElement() && 3284 !ICS2.isStdInitializerListElement()) 3285 return ImplicitConversionSequence::Better; 3286 if (!ICS1.isStdInitializerListElement() && 3287 ICS2.isStdInitializerListElement()) 3288 return ImplicitConversionSequence::Worse; 3289 } 3290 3291 return Result; 3292} 3293 3294static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3295 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3296 Qualifiers Quals; 3297 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3298 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3299 } 3300 3301 return Context.hasSameUnqualifiedType(T1, T2); 3302} 3303 3304// Per 13.3.3.2p3, compare the given standard conversion sequences to 3305// determine if one is a proper subset of the other. 3306static ImplicitConversionSequence::CompareKind 3307compareStandardConversionSubsets(ASTContext &Context, 3308 const StandardConversionSequence& SCS1, 3309 const StandardConversionSequence& SCS2) { 3310 ImplicitConversionSequence::CompareKind Result 3311 = ImplicitConversionSequence::Indistinguishable; 3312 3313 // the identity conversion sequence is considered to be a subsequence of 3314 // any non-identity conversion sequence 3315 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3316 return ImplicitConversionSequence::Better; 3317 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3318 return ImplicitConversionSequence::Worse; 3319 3320 if (SCS1.Second != SCS2.Second) { 3321 if (SCS1.Second == ICK_Identity) 3322 Result = ImplicitConversionSequence::Better; 3323 else if (SCS2.Second == ICK_Identity) 3324 Result = ImplicitConversionSequence::Worse; 3325 else 3326 return ImplicitConversionSequence::Indistinguishable; 3327 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3328 return ImplicitConversionSequence::Indistinguishable; 3329 3330 if (SCS1.Third == SCS2.Third) { 3331 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3332 : ImplicitConversionSequence::Indistinguishable; 3333 } 3334 3335 if (SCS1.Third == ICK_Identity) 3336 return Result == ImplicitConversionSequence::Worse 3337 ? ImplicitConversionSequence::Indistinguishable 3338 : ImplicitConversionSequence::Better; 3339 3340 if (SCS2.Third == ICK_Identity) 3341 return Result == ImplicitConversionSequence::Better 3342 ? ImplicitConversionSequence::Indistinguishable 3343 : ImplicitConversionSequence::Worse; 3344 3345 return ImplicitConversionSequence::Indistinguishable; 3346} 3347 3348/// \brief Determine whether one of the given reference bindings is better 3349/// than the other based on what kind of bindings they are. 3350static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3351 const StandardConversionSequence &SCS2) { 3352 // C++0x [over.ics.rank]p3b4: 3353 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3354 // implicit object parameter of a non-static member function declared 3355 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3356 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3357 // lvalue reference to a function lvalue and S2 binds an rvalue 3358 // reference*. 3359 // 3360 // FIXME: Rvalue references. We're going rogue with the above edits, 3361 // because the semantics in the current C++0x working paper (N3225 at the 3362 // time of this writing) break the standard definition of std::forward 3363 // and std::reference_wrapper when dealing with references to functions. 3364 // Proposed wording changes submitted to CWG for consideration. 3365 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3366 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3367 return false; 3368 3369 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3370 SCS2.IsLvalueReference) || 3371 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3372 !SCS2.IsLvalueReference); 3373} 3374 3375/// CompareStandardConversionSequences - Compare two standard 3376/// conversion sequences to determine whether one is better than the 3377/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3378static ImplicitConversionSequence::CompareKind 3379CompareStandardConversionSequences(Sema &S, 3380 const StandardConversionSequence& SCS1, 3381 const StandardConversionSequence& SCS2) 3382{ 3383 // Standard conversion sequence S1 is a better conversion sequence 3384 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3385 3386 // -- S1 is a proper subsequence of S2 (comparing the conversion 3387 // sequences in the canonical form defined by 13.3.3.1.1, 3388 // excluding any Lvalue Transformation; the identity conversion 3389 // sequence is considered to be a subsequence of any 3390 // non-identity conversion sequence) or, if not that, 3391 if (ImplicitConversionSequence::CompareKind CK 3392 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3393 return CK; 3394 3395 // -- the rank of S1 is better than the rank of S2 (by the rules 3396 // defined below), or, if not that, 3397 ImplicitConversionRank Rank1 = SCS1.getRank(); 3398 ImplicitConversionRank Rank2 = SCS2.getRank(); 3399 if (Rank1 < Rank2) 3400 return ImplicitConversionSequence::Better; 3401 else if (Rank2 < Rank1) 3402 return ImplicitConversionSequence::Worse; 3403 3404 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3405 // are indistinguishable unless one of the following rules 3406 // applies: 3407 3408 // A conversion that is not a conversion of a pointer, or 3409 // pointer to member, to bool is better than another conversion 3410 // that is such a conversion. 3411 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3412 return SCS2.isPointerConversionToBool() 3413 ? ImplicitConversionSequence::Better 3414 : ImplicitConversionSequence::Worse; 3415 3416 // C++ [over.ics.rank]p4b2: 3417 // 3418 // If class B is derived directly or indirectly from class A, 3419 // conversion of B* to A* is better than conversion of B* to 3420 // void*, and conversion of A* to void* is better than conversion 3421 // of B* to void*. 3422 bool SCS1ConvertsToVoid 3423 = SCS1.isPointerConversionToVoidPointer(S.Context); 3424 bool SCS2ConvertsToVoid 3425 = SCS2.isPointerConversionToVoidPointer(S.Context); 3426 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3427 // Exactly one of the conversion sequences is a conversion to 3428 // a void pointer; it's the worse conversion. 3429 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3430 : ImplicitConversionSequence::Worse; 3431 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3432 // Neither conversion sequence converts to a void pointer; compare 3433 // their derived-to-base conversions. 3434 if (ImplicitConversionSequence::CompareKind DerivedCK 3435 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3436 return DerivedCK; 3437 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3438 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3439 // Both conversion sequences are conversions to void 3440 // pointers. Compare the source types to determine if there's an 3441 // inheritance relationship in their sources. 3442 QualType FromType1 = SCS1.getFromType(); 3443 QualType FromType2 = SCS2.getFromType(); 3444 3445 // Adjust the types we're converting from via the array-to-pointer 3446 // conversion, if we need to. 3447 if (SCS1.First == ICK_Array_To_Pointer) 3448 FromType1 = S.Context.getArrayDecayedType(FromType1); 3449 if (SCS2.First == ICK_Array_To_Pointer) 3450 FromType2 = S.Context.getArrayDecayedType(FromType2); 3451 3452 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3453 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3454 3455 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3456 return ImplicitConversionSequence::Better; 3457 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3458 return ImplicitConversionSequence::Worse; 3459 3460 // Objective-C++: If one interface is more specific than the 3461 // other, it is the better one. 3462 const ObjCObjectPointerType* FromObjCPtr1 3463 = FromType1->getAs<ObjCObjectPointerType>(); 3464 const ObjCObjectPointerType* FromObjCPtr2 3465 = FromType2->getAs<ObjCObjectPointerType>(); 3466 if (FromObjCPtr1 && FromObjCPtr2) { 3467 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3468 FromObjCPtr2); 3469 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3470 FromObjCPtr1); 3471 if (AssignLeft != AssignRight) { 3472 return AssignLeft? ImplicitConversionSequence::Better 3473 : ImplicitConversionSequence::Worse; 3474 } 3475 } 3476 } 3477 3478 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3479 // bullet 3). 3480 if (ImplicitConversionSequence::CompareKind QualCK 3481 = CompareQualificationConversions(S, SCS1, SCS2)) 3482 return QualCK; 3483 3484 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3485 // Check for a better reference binding based on the kind of bindings. 3486 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3487 return ImplicitConversionSequence::Better; 3488 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3489 return ImplicitConversionSequence::Worse; 3490 3491 // C++ [over.ics.rank]p3b4: 3492 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3493 // which the references refer are the same type except for 3494 // top-level cv-qualifiers, and the type to which the reference 3495 // initialized by S2 refers is more cv-qualified than the type 3496 // to which the reference initialized by S1 refers. 3497 QualType T1 = SCS1.getToType(2); 3498 QualType T2 = SCS2.getToType(2); 3499 T1 = S.Context.getCanonicalType(T1); 3500 T2 = S.Context.getCanonicalType(T2); 3501 Qualifiers T1Quals, T2Quals; 3502 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3503 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3504 if (UnqualT1 == UnqualT2) { 3505 // Objective-C++ ARC: If the references refer to objects with different 3506 // lifetimes, prefer bindings that don't change lifetime. 3507 if (SCS1.ObjCLifetimeConversionBinding != 3508 SCS2.ObjCLifetimeConversionBinding) { 3509 return SCS1.ObjCLifetimeConversionBinding 3510 ? ImplicitConversionSequence::Worse 3511 : ImplicitConversionSequence::Better; 3512 } 3513 3514 // If the type is an array type, promote the element qualifiers to the 3515 // type for comparison. 3516 if (isa<ArrayType>(T1) && T1Quals) 3517 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3518 if (isa<ArrayType>(T2) && T2Quals) 3519 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3520 if (T2.isMoreQualifiedThan(T1)) 3521 return ImplicitConversionSequence::Better; 3522 else if (T1.isMoreQualifiedThan(T2)) 3523 return ImplicitConversionSequence::Worse; 3524 } 3525 } 3526 3527 // In Microsoft mode, prefer an integral conversion to a 3528 // floating-to-integral conversion if the integral conversion 3529 // is between types of the same size. 3530 // For example: 3531 // void f(float); 3532 // void f(int); 3533 // int main { 3534 // long a; 3535 // f(a); 3536 // } 3537 // Here, MSVC will call f(int) instead of generating a compile error 3538 // as clang will do in standard mode. 3539 if (S.getLangOpts().MicrosoftMode && 3540 SCS1.Second == ICK_Integral_Conversion && 3541 SCS2.Second == ICK_Floating_Integral && 3542 S.Context.getTypeSize(SCS1.getFromType()) == 3543 S.Context.getTypeSize(SCS1.getToType(2))) 3544 return ImplicitConversionSequence::Better; 3545 3546 return ImplicitConversionSequence::Indistinguishable; 3547} 3548 3549/// CompareQualificationConversions - Compares two standard conversion 3550/// sequences to determine whether they can be ranked based on their 3551/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3552ImplicitConversionSequence::CompareKind 3553CompareQualificationConversions(Sema &S, 3554 const StandardConversionSequence& SCS1, 3555 const StandardConversionSequence& SCS2) { 3556 // C++ 13.3.3.2p3: 3557 // -- S1 and S2 differ only in their qualification conversion and 3558 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3559 // cv-qualification signature of type T1 is a proper subset of 3560 // the cv-qualification signature of type T2, and S1 is not the 3561 // deprecated string literal array-to-pointer conversion (4.2). 3562 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3563 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3564 return ImplicitConversionSequence::Indistinguishable; 3565 3566 // FIXME: the example in the standard doesn't use a qualification 3567 // conversion (!) 3568 QualType T1 = SCS1.getToType(2); 3569 QualType T2 = SCS2.getToType(2); 3570 T1 = S.Context.getCanonicalType(T1); 3571 T2 = S.Context.getCanonicalType(T2); 3572 Qualifiers T1Quals, T2Quals; 3573 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3574 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3575 3576 // If the types are the same, we won't learn anything by unwrapped 3577 // them. 3578 if (UnqualT1 == UnqualT2) 3579 return ImplicitConversionSequence::Indistinguishable; 3580 3581 // If the type is an array type, promote the element qualifiers to the type 3582 // 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 3588 ImplicitConversionSequence::CompareKind Result 3589 = ImplicitConversionSequence::Indistinguishable; 3590 3591 // Objective-C++ ARC: 3592 // Prefer qualification conversions not involving a change in lifetime 3593 // to qualification conversions that do not change lifetime. 3594 if (SCS1.QualificationIncludesObjCLifetime != 3595 SCS2.QualificationIncludesObjCLifetime) { 3596 Result = SCS1.QualificationIncludesObjCLifetime 3597 ? ImplicitConversionSequence::Worse 3598 : ImplicitConversionSequence::Better; 3599 } 3600 3601 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3602 // Within each iteration of the loop, we check the qualifiers to 3603 // determine if this still looks like a qualification 3604 // conversion. Then, if all is well, we unwrap one more level of 3605 // pointers or pointers-to-members and do it all again 3606 // until there are no more pointers or pointers-to-members left 3607 // to unwrap. This essentially mimics what 3608 // IsQualificationConversion does, but here we're checking for a 3609 // strict subset of qualifiers. 3610 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3611 // The qualifiers are the same, so this doesn't tell us anything 3612 // about how the sequences rank. 3613 ; 3614 else if (T2.isMoreQualifiedThan(T1)) { 3615 // T1 has fewer qualifiers, so it could be the better sequence. 3616 if (Result == ImplicitConversionSequence::Worse) 3617 // Neither has qualifiers that are a subset of the other's 3618 // qualifiers. 3619 return ImplicitConversionSequence::Indistinguishable; 3620 3621 Result = ImplicitConversionSequence::Better; 3622 } else if (T1.isMoreQualifiedThan(T2)) { 3623 // T2 has fewer qualifiers, so it could be the better sequence. 3624 if (Result == ImplicitConversionSequence::Better) 3625 // Neither has qualifiers that are a subset of the other's 3626 // qualifiers. 3627 return ImplicitConversionSequence::Indistinguishable; 3628 3629 Result = ImplicitConversionSequence::Worse; 3630 } else { 3631 // Qualifiers are disjoint. 3632 return ImplicitConversionSequence::Indistinguishable; 3633 } 3634 3635 // If the types after this point are equivalent, we're done. 3636 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3637 break; 3638 } 3639 3640 // Check that the winning standard conversion sequence isn't using 3641 // the deprecated string literal array to pointer conversion. 3642 switch (Result) { 3643 case ImplicitConversionSequence::Better: 3644 if (SCS1.DeprecatedStringLiteralToCharPtr) 3645 Result = ImplicitConversionSequence::Indistinguishable; 3646 break; 3647 3648 case ImplicitConversionSequence::Indistinguishable: 3649 break; 3650 3651 case ImplicitConversionSequence::Worse: 3652 if (SCS2.DeprecatedStringLiteralToCharPtr) 3653 Result = ImplicitConversionSequence::Indistinguishable; 3654 break; 3655 } 3656 3657 return Result; 3658} 3659 3660/// CompareDerivedToBaseConversions - Compares two standard conversion 3661/// sequences to determine whether they can be ranked based on their 3662/// various kinds of derived-to-base conversions (C++ 3663/// [over.ics.rank]p4b3). As part of these checks, we also look at 3664/// conversions between Objective-C interface types. 3665ImplicitConversionSequence::CompareKind 3666CompareDerivedToBaseConversions(Sema &S, 3667 const StandardConversionSequence& SCS1, 3668 const StandardConversionSequence& SCS2) { 3669 QualType FromType1 = SCS1.getFromType(); 3670 QualType ToType1 = SCS1.getToType(1); 3671 QualType FromType2 = SCS2.getFromType(); 3672 QualType ToType2 = SCS2.getToType(1); 3673 3674 // Adjust the types we're converting from via the array-to-pointer 3675 // conversion, if we need to. 3676 if (SCS1.First == ICK_Array_To_Pointer) 3677 FromType1 = S.Context.getArrayDecayedType(FromType1); 3678 if (SCS2.First == ICK_Array_To_Pointer) 3679 FromType2 = S.Context.getArrayDecayedType(FromType2); 3680 3681 // Canonicalize all of the types. 3682 FromType1 = S.Context.getCanonicalType(FromType1); 3683 ToType1 = S.Context.getCanonicalType(ToType1); 3684 FromType2 = S.Context.getCanonicalType(FromType2); 3685 ToType2 = S.Context.getCanonicalType(ToType2); 3686 3687 // C++ [over.ics.rank]p4b3: 3688 // 3689 // If class B is derived directly or indirectly from class A and 3690 // class C is derived directly or indirectly from B, 3691 // 3692 // Compare based on pointer conversions. 3693 if (SCS1.Second == ICK_Pointer_Conversion && 3694 SCS2.Second == ICK_Pointer_Conversion && 3695 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3696 FromType1->isPointerType() && FromType2->isPointerType() && 3697 ToType1->isPointerType() && ToType2->isPointerType()) { 3698 QualType FromPointee1 3699 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3700 QualType ToPointee1 3701 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3702 QualType FromPointee2 3703 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3704 QualType ToPointee2 3705 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3706 3707 // -- conversion of C* to B* is better than conversion of C* to A*, 3708 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3709 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3710 return ImplicitConversionSequence::Better; 3711 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3712 return ImplicitConversionSequence::Worse; 3713 } 3714 3715 // -- conversion of B* to A* is better than conversion of C* to A*, 3716 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3717 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3718 return ImplicitConversionSequence::Better; 3719 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3720 return ImplicitConversionSequence::Worse; 3721 } 3722 } else if (SCS1.Second == ICK_Pointer_Conversion && 3723 SCS2.Second == ICK_Pointer_Conversion) { 3724 const ObjCObjectPointerType *FromPtr1 3725 = FromType1->getAs<ObjCObjectPointerType>(); 3726 const ObjCObjectPointerType *FromPtr2 3727 = FromType2->getAs<ObjCObjectPointerType>(); 3728 const ObjCObjectPointerType *ToPtr1 3729 = ToType1->getAs<ObjCObjectPointerType>(); 3730 const ObjCObjectPointerType *ToPtr2 3731 = ToType2->getAs<ObjCObjectPointerType>(); 3732 3733 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3734 // Apply the same conversion ranking rules for Objective-C pointer types 3735 // that we do for C++ pointers to class types. However, we employ the 3736 // Objective-C pseudo-subtyping relationship used for assignment of 3737 // Objective-C pointer types. 3738 bool FromAssignLeft 3739 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3740 bool FromAssignRight 3741 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3742 bool ToAssignLeft 3743 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3744 bool ToAssignRight 3745 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3746 3747 // A conversion to an a non-id object pointer type or qualified 'id' 3748 // type is better than a conversion to 'id'. 3749 if (ToPtr1->isObjCIdType() && 3750 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3751 return ImplicitConversionSequence::Worse; 3752 if (ToPtr2->isObjCIdType() && 3753 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3754 return ImplicitConversionSequence::Better; 3755 3756 // A conversion to a non-id object pointer type is better than a 3757 // conversion to a qualified 'id' type 3758 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3759 return ImplicitConversionSequence::Worse; 3760 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3761 return ImplicitConversionSequence::Better; 3762 3763 // A conversion to an a non-Class object pointer type or qualified 'Class' 3764 // type is better than a conversion to 'Class'. 3765 if (ToPtr1->isObjCClassType() && 3766 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3767 return ImplicitConversionSequence::Worse; 3768 if (ToPtr2->isObjCClassType() && 3769 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3770 return ImplicitConversionSequence::Better; 3771 3772 // A conversion to a non-Class object pointer type is better than a 3773 // conversion to a qualified 'Class' type. 3774 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3775 return ImplicitConversionSequence::Worse; 3776 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3777 return ImplicitConversionSequence::Better; 3778 3779 // -- "conversion of C* to B* is better than conversion of C* to A*," 3780 if (S.Context.hasSameType(FromType1, FromType2) && 3781 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3782 (ToAssignLeft != ToAssignRight)) 3783 return ToAssignLeft? ImplicitConversionSequence::Worse 3784 : ImplicitConversionSequence::Better; 3785 3786 // -- "conversion of B* to A* is better than conversion of C* to A*," 3787 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3788 (FromAssignLeft != FromAssignRight)) 3789 return FromAssignLeft? ImplicitConversionSequence::Better 3790 : ImplicitConversionSequence::Worse; 3791 } 3792 } 3793 3794 // Ranking of member-pointer types. 3795 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3796 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3797 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3798 const MemberPointerType * FromMemPointer1 = 3799 FromType1->getAs<MemberPointerType>(); 3800 const MemberPointerType * ToMemPointer1 = 3801 ToType1->getAs<MemberPointerType>(); 3802 const MemberPointerType * FromMemPointer2 = 3803 FromType2->getAs<MemberPointerType>(); 3804 const MemberPointerType * ToMemPointer2 = 3805 ToType2->getAs<MemberPointerType>(); 3806 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3807 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3808 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3809 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3810 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3811 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3812 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3813 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3814 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3815 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3816 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3817 return ImplicitConversionSequence::Worse; 3818 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3819 return ImplicitConversionSequence::Better; 3820 } 3821 // conversion of B::* to C::* is better than conversion of A::* to C::* 3822 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3823 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3824 return ImplicitConversionSequence::Better; 3825 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3826 return ImplicitConversionSequence::Worse; 3827 } 3828 } 3829 3830 if (SCS1.Second == ICK_Derived_To_Base) { 3831 // -- conversion of C to B is better than conversion of C to A, 3832 // -- binding of an expression of type C to a reference of type 3833 // B& is better than binding an expression of type C to a 3834 // reference of type A&, 3835 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3836 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3837 if (S.IsDerivedFrom(ToType1, ToType2)) 3838 return ImplicitConversionSequence::Better; 3839 else if (S.IsDerivedFrom(ToType2, ToType1)) 3840 return ImplicitConversionSequence::Worse; 3841 } 3842 3843 // -- conversion of B to A is better than conversion of C to A. 3844 // -- binding of an expression of type B to a reference of type 3845 // A& is better than binding an expression of type C to a 3846 // reference of type A&, 3847 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3848 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3849 if (S.IsDerivedFrom(FromType2, FromType1)) 3850 return ImplicitConversionSequence::Better; 3851 else if (S.IsDerivedFrom(FromType1, FromType2)) 3852 return ImplicitConversionSequence::Worse; 3853 } 3854 } 3855 3856 return ImplicitConversionSequence::Indistinguishable; 3857} 3858 3859/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3860/// determine whether they are reference-related, 3861/// reference-compatible, reference-compatible with added 3862/// qualification, or incompatible, for use in C++ initialization by 3863/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3864/// type, and the first type (T1) is the pointee type of the reference 3865/// type being initialized. 3866Sema::ReferenceCompareResult 3867Sema::CompareReferenceRelationship(SourceLocation Loc, 3868 QualType OrigT1, QualType OrigT2, 3869 bool &DerivedToBase, 3870 bool &ObjCConversion, 3871 bool &ObjCLifetimeConversion) { 3872 assert(!OrigT1->isReferenceType() && 3873 "T1 must be the pointee type of the reference type"); 3874 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3875 3876 QualType T1 = Context.getCanonicalType(OrigT1); 3877 QualType T2 = Context.getCanonicalType(OrigT2); 3878 Qualifiers T1Quals, T2Quals; 3879 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3880 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3881 3882 // C++ [dcl.init.ref]p4: 3883 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3884 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3885 // T1 is a base class of T2. 3886 DerivedToBase = false; 3887 ObjCConversion = false; 3888 ObjCLifetimeConversion = false; 3889 if (UnqualT1 == UnqualT2) { 3890 // Nothing to do. 3891 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3892 IsDerivedFrom(UnqualT2, UnqualT1)) 3893 DerivedToBase = true; 3894 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3895 UnqualT2->isObjCObjectOrInterfaceType() && 3896 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3897 ObjCConversion = true; 3898 else 3899 return Ref_Incompatible; 3900 3901 // At this point, we know that T1 and T2 are reference-related (at 3902 // least). 3903 3904 // If the type is an array type, promote the element qualifiers to the type 3905 // for comparison. 3906 if (isa<ArrayType>(T1) && T1Quals) 3907 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3908 if (isa<ArrayType>(T2) && T2Quals) 3909 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3910 3911 // C++ [dcl.init.ref]p4: 3912 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3913 // reference-related to T2 and cv1 is the same cv-qualification 3914 // as, or greater cv-qualification than, cv2. For purposes of 3915 // overload resolution, cases for which cv1 is greater 3916 // cv-qualification than cv2 are identified as 3917 // reference-compatible with added qualification (see 13.3.3.2). 3918 // 3919 // Note that we also require equivalence of Objective-C GC and address-space 3920 // qualifiers when performing these computations, so that e.g., an int in 3921 // address space 1 is not reference-compatible with an int in address 3922 // space 2. 3923 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3924 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3925 T1Quals.removeObjCLifetime(); 3926 T2Quals.removeObjCLifetime(); 3927 ObjCLifetimeConversion = true; 3928 } 3929 3930 if (T1Quals == T2Quals) 3931 return Ref_Compatible; 3932 else if (T1Quals.compatiblyIncludes(T2Quals)) 3933 return Ref_Compatible_With_Added_Qualification; 3934 else 3935 return Ref_Related; 3936} 3937 3938/// \brief Look for a user-defined conversion to an value reference-compatible 3939/// with DeclType. Return true if something definite is found. 3940static bool 3941FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3942 QualType DeclType, SourceLocation DeclLoc, 3943 Expr *Init, QualType T2, bool AllowRvalues, 3944 bool AllowExplicit) { 3945 assert(T2->isRecordType() && "Can only find conversions of record types."); 3946 CXXRecordDecl *T2RecordDecl 3947 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3948 3949 OverloadCandidateSet CandidateSet(DeclLoc); 3950 const UnresolvedSetImpl *Conversions 3951 = T2RecordDecl->getVisibleConversionFunctions(); 3952 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3953 E = Conversions->end(); I != E; ++I) { 3954 NamedDecl *D = *I; 3955 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3956 if (isa<UsingShadowDecl>(D)) 3957 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3958 3959 FunctionTemplateDecl *ConvTemplate 3960 = dyn_cast<FunctionTemplateDecl>(D); 3961 CXXConversionDecl *Conv; 3962 if (ConvTemplate) 3963 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3964 else 3965 Conv = cast<CXXConversionDecl>(D); 3966 3967 // If this is an explicit conversion, and we're not allowed to consider 3968 // explicit conversions, skip it. 3969 if (!AllowExplicit && Conv->isExplicit()) 3970 continue; 3971 3972 if (AllowRvalues) { 3973 bool DerivedToBase = false; 3974 bool ObjCConversion = false; 3975 bool ObjCLifetimeConversion = false; 3976 3977 // If we are initializing an rvalue reference, don't permit conversion 3978 // functions that return lvalues. 3979 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 3980 const ReferenceType *RefType 3981 = Conv->getConversionType()->getAs<LValueReferenceType>(); 3982 if (RefType && !RefType->getPointeeType()->isFunctionType()) 3983 continue; 3984 } 3985 3986 if (!ConvTemplate && 3987 S.CompareReferenceRelationship( 3988 DeclLoc, 3989 Conv->getConversionType().getNonReferenceType() 3990 .getUnqualifiedType(), 3991 DeclType.getNonReferenceType().getUnqualifiedType(), 3992 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 3993 Sema::Ref_Incompatible) 3994 continue; 3995 } else { 3996 // If the conversion function doesn't return a reference type, 3997 // it can't be considered for this conversion. An rvalue reference 3998 // is only acceptable if its referencee is a function type. 3999 4000 const ReferenceType *RefType = 4001 Conv->getConversionType()->getAs<ReferenceType>(); 4002 if (!RefType || 4003 (!RefType->isLValueReferenceType() && 4004 !RefType->getPointeeType()->isFunctionType())) 4005 continue; 4006 } 4007 4008 if (ConvTemplate) 4009 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4010 Init, DeclType, CandidateSet); 4011 else 4012 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4013 DeclType, CandidateSet); 4014 } 4015 4016 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4017 4018 OverloadCandidateSet::iterator Best; 4019 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4020 case OR_Success: 4021 // C++ [over.ics.ref]p1: 4022 // 4023 // [...] If the parameter binds directly to the result of 4024 // applying a conversion function to the argument 4025 // expression, the implicit conversion sequence is a 4026 // user-defined conversion sequence (13.3.3.1.2), with the 4027 // second standard conversion sequence either an identity 4028 // conversion or, if the conversion function returns an 4029 // entity of a type that is a derived class of the parameter 4030 // type, a derived-to-base Conversion. 4031 if (!Best->FinalConversion.DirectBinding) 4032 return false; 4033 4034 if (Best->Function) 4035 S.MarkFunctionReferenced(DeclLoc, Best->Function); 4036 ICS.setUserDefined(); 4037 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4038 ICS.UserDefined.After = Best->FinalConversion; 4039 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4040 ICS.UserDefined.ConversionFunction = Best->Function; 4041 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4042 ICS.UserDefined.EllipsisConversion = false; 4043 assert(ICS.UserDefined.After.ReferenceBinding && 4044 ICS.UserDefined.After.DirectBinding && 4045 "Expected a direct reference binding!"); 4046 return true; 4047 4048 case OR_Ambiguous: 4049 ICS.setAmbiguous(); 4050 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4051 Cand != CandidateSet.end(); ++Cand) 4052 if (Cand->Viable) 4053 ICS.Ambiguous.addConversion(Cand->Function); 4054 return true; 4055 4056 case OR_No_Viable_Function: 4057 case OR_Deleted: 4058 // There was no suitable conversion, or we found a deleted 4059 // conversion; continue with other checks. 4060 return false; 4061 } 4062 4063 llvm_unreachable("Invalid OverloadResult!"); 4064} 4065 4066/// \brief Compute an implicit conversion sequence for reference 4067/// initialization. 4068static ImplicitConversionSequence 4069TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4070 SourceLocation DeclLoc, 4071 bool SuppressUserConversions, 4072 bool AllowExplicit) { 4073 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4074 4075 // Most paths end in a failed conversion. 4076 ImplicitConversionSequence ICS; 4077 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4078 4079 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4080 QualType T2 = Init->getType(); 4081 4082 // If the initializer is the address of an overloaded function, try 4083 // to resolve the overloaded function. If all goes well, T2 is the 4084 // type of the resulting function. 4085 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4086 DeclAccessPair Found; 4087 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4088 false, Found)) 4089 T2 = Fn->getType(); 4090 } 4091 4092 // Compute some basic properties of the types and the initializer. 4093 bool isRValRef = DeclType->isRValueReferenceType(); 4094 bool DerivedToBase = false; 4095 bool ObjCConversion = false; 4096 bool ObjCLifetimeConversion = false; 4097 Expr::Classification InitCategory = Init->Classify(S.Context); 4098 Sema::ReferenceCompareResult RefRelationship 4099 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4100 ObjCConversion, ObjCLifetimeConversion); 4101 4102 4103 // C++0x [dcl.init.ref]p5: 4104 // A reference to type "cv1 T1" is initialized by an expression 4105 // of type "cv2 T2" as follows: 4106 4107 // -- If reference is an lvalue reference and the initializer expression 4108 if (!isRValRef) { 4109 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4110 // reference-compatible with "cv2 T2," or 4111 // 4112 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4113 if (InitCategory.isLValue() && 4114 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4115 // C++ [over.ics.ref]p1: 4116 // When a parameter of reference type binds directly (8.5.3) 4117 // to an argument expression, the implicit conversion sequence 4118 // is the identity conversion, unless the argument expression 4119 // has a type that is a derived class of the parameter type, 4120 // in which case the implicit conversion sequence is a 4121 // derived-to-base Conversion (13.3.3.1). 4122 ICS.setStandard(); 4123 ICS.Standard.First = ICK_Identity; 4124 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4125 : ObjCConversion? ICK_Compatible_Conversion 4126 : ICK_Identity; 4127 ICS.Standard.Third = ICK_Identity; 4128 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4129 ICS.Standard.setToType(0, T2); 4130 ICS.Standard.setToType(1, T1); 4131 ICS.Standard.setToType(2, T1); 4132 ICS.Standard.ReferenceBinding = true; 4133 ICS.Standard.DirectBinding = true; 4134 ICS.Standard.IsLvalueReference = !isRValRef; 4135 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4136 ICS.Standard.BindsToRvalue = false; 4137 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4138 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4139 ICS.Standard.CopyConstructor = 0; 4140 4141 // Nothing more to do: the inaccessibility/ambiguity check for 4142 // derived-to-base conversions is suppressed when we're 4143 // computing the implicit conversion sequence (C++ 4144 // [over.best.ics]p2). 4145 return ICS; 4146 } 4147 4148 // -- has a class type (i.e., T2 is a class type), where T1 is 4149 // not reference-related to T2, and can be implicitly 4150 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4151 // is reference-compatible with "cv3 T3" 92) (this 4152 // conversion is selected by enumerating the applicable 4153 // conversion functions (13.3.1.6) and choosing the best 4154 // one through overload resolution (13.3)), 4155 if (!SuppressUserConversions && T2->isRecordType() && 4156 !S.RequireCompleteType(DeclLoc, T2, 0) && 4157 RefRelationship == Sema::Ref_Incompatible) { 4158 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4159 Init, T2, /*AllowRvalues=*/false, 4160 AllowExplicit)) 4161 return ICS; 4162 } 4163 } 4164 4165 // -- Otherwise, the reference shall be an lvalue reference to a 4166 // non-volatile const type (i.e., cv1 shall be const), or the reference 4167 // shall be an rvalue reference. 4168 // 4169 // We actually handle one oddity of C++ [over.ics.ref] at this 4170 // point, which is that, due to p2 (which short-circuits reference 4171 // binding by only attempting a simple conversion for non-direct 4172 // bindings) and p3's strange wording, we allow a const volatile 4173 // reference to bind to an rvalue. Hence the check for the presence 4174 // of "const" rather than checking for "const" being the only 4175 // qualifier. 4176 // This is also the point where rvalue references and lvalue inits no longer 4177 // go together. 4178 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4179 return ICS; 4180 4181 // -- If the initializer expression 4182 // 4183 // -- is an xvalue, class prvalue, array prvalue or function 4184 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4185 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4186 (InitCategory.isXValue() || 4187 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4188 (InitCategory.isLValue() && T2->isFunctionType()))) { 4189 ICS.setStandard(); 4190 ICS.Standard.First = ICK_Identity; 4191 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4192 : ObjCConversion? ICK_Compatible_Conversion 4193 : ICK_Identity; 4194 ICS.Standard.Third = ICK_Identity; 4195 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4196 ICS.Standard.setToType(0, T2); 4197 ICS.Standard.setToType(1, T1); 4198 ICS.Standard.setToType(2, T1); 4199 ICS.Standard.ReferenceBinding = true; 4200 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4201 // binding unless we're binding to a class prvalue. 4202 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4203 // allow the use of rvalue references in C++98/03 for the benefit of 4204 // standard library implementors; therefore, we need the xvalue check here. 4205 ICS.Standard.DirectBinding = 4206 S.getLangOpts().CPlusPlus0x || 4207 (InitCategory.isPRValue() && !T2->isRecordType()); 4208 ICS.Standard.IsLvalueReference = !isRValRef; 4209 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4210 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4211 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4212 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4213 ICS.Standard.CopyConstructor = 0; 4214 return ICS; 4215 } 4216 4217 // -- has a class type (i.e., T2 is a class type), where T1 is not 4218 // reference-related to T2, and can be implicitly converted to 4219 // an xvalue, class prvalue, or function lvalue of type 4220 // "cv3 T3", where "cv1 T1" is reference-compatible with 4221 // "cv3 T3", 4222 // 4223 // then the reference is bound to the value of the initializer 4224 // expression in the first case and to the result of the conversion 4225 // in the second case (or, in either case, to an appropriate base 4226 // class subobject). 4227 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4228 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4229 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4230 Init, T2, /*AllowRvalues=*/true, 4231 AllowExplicit)) { 4232 // In the second case, if the reference is an rvalue reference 4233 // and the second standard conversion sequence of the 4234 // user-defined conversion sequence includes an lvalue-to-rvalue 4235 // conversion, the program is ill-formed. 4236 if (ICS.isUserDefined() && isRValRef && 4237 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4238 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4239 4240 return ICS; 4241 } 4242 4243 // -- Otherwise, a temporary of type "cv1 T1" is created and 4244 // initialized from the initializer expression using the 4245 // rules for a non-reference copy initialization (8.5). The 4246 // reference is then bound to the temporary. If T1 is 4247 // reference-related to T2, cv1 must be the same 4248 // cv-qualification as, or greater cv-qualification than, 4249 // cv2; otherwise, the program is ill-formed. 4250 if (RefRelationship == Sema::Ref_Related) { 4251 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4252 // we would be reference-compatible or reference-compatible with 4253 // added qualification. But that wasn't the case, so the reference 4254 // initialization fails. 4255 // 4256 // Note that we only want to check address spaces and cvr-qualifiers here. 4257 // ObjC GC and lifetime qualifiers aren't important. 4258 Qualifiers T1Quals = T1.getQualifiers(); 4259 Qualifiers T2Quals = T2.getQualifiers(); 4260 T1Quals.removeObjCGCAttr(); 4261 T1Quals.removeObjCLifetime(); 4262 T2Quals.removeObjCGCAttr(); 4263 T2Quals.removeObjCLifetime(); 4264 if (!T1Quals.compatiblyIncludes(T2Quals)) 4265 return ICS; 4266 } 4267 4268 // If at least one of the types is a class type, the types are not 4269 // related, and we aren't allowed any user conversions, the 4270 // reference binding fails. This case is important for breaking 4271 // recursion, since TryImplicitConversion below will attempt to 4272 // create a temporary through the use of a copy constructor. 4273 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4274 (T1->isRecordType() || T2->isRecordType())) 4275 return ICS; 4276 4277 // If T1 is reference-related to T2 and the reference is an rvalue 4278 // reference, the initializer expression shall not be an lvalue. 4279 if (RefRelationship >= Sema::Ref_Related && 4280 isRValRef && Init->Classify(S.Context).isLValue()) 4281 return ICS; 4282 4283 // C++ [over.ics.ref]p2: 4284 // When a parameter of reference type is not bound directly to 4285 // an argument expression, the conversion sequence is the one 4286 // required to convert the argument expression to the 4287 // underlying type of the reference according to 4288 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4289 // to copy-initializing a temporary of the underlying type with 4290 // the argument expression. Any difference in top-level 4291 // cv-qualification is subsumed by the initialization itself 4292 // and does not constitute a conversion. 4293 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4294 /*AllowExplicit=*/false, 4295 /*InOverloadResolution=*/false, 4296 /*CStyle=*/false, 4297 /*AllowObjCWritebackConversion=*/false); 4298 4299 // Of course, that's still a reference binding. 4300 if (ICS.isStandard()) { 4301 ICS.Standard.ReferenceBinding = true; 4302 ICS.Standard.IsLvalueReference = !isRValRef; 4303 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4304 ICS.Standard.BindsToRvalue = true; 4305 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4306 ICS.Standard.ObjCLifetimeConversionBinding = false; 4307 } else if (ICS.isUserDefined()) { 4308 // Don't allow rvalue references to bind to lvalues. 4309 if (DeclType->isRValueReferenceType()) { 4310 if (const ReferenceType *RefType 4311 = ICS.UserDefined.ConversionFunction->getResultType() 4312 ->getAs<LValueReferenceType>()) { 4313 if (!RefType->getPointeeType()->isFunctionType()) { 4314 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4315 DeclType); 4316 return ICS; 4317 } 4318 } 4319 } 4320 4321 ICS.UserDefined.After.ReferenceBinding = true; 4322 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4323 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4324 ICS.UserDefined.After.BindsToRvalue = true; 4325 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4326 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4327 } 4328 4329 return ICS; 4330} 4331 4332static ImplicitConversionSequence 4333TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4334 bool SuppressUserConversions, 4335 bool InOverloadResolution, 4336 bool AllowObjCWritebackConversion, 4337 bool AllowExplicit = false); 4338 4339/// TryListConversion - Try to copy-initialize a value of type ToType from the 4340/// initializer list From. 4341static ImplicitConversionSequence 4342TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4343 bool SuppressUserConversions, 4344 bool InOverloadResolution, 4345 bool AllowObjCWritebackConversion) { 4346 // C++11 [over.ics.list]p1: 4347 // When an argument is an initializer list, it is not an expression and 4348 // special rules apply for converting it to a parameter type. 4349 4350 ImplicitConversionSequence Result; 4351 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4352 Result.setListInitializationSequence(); 4353 4354 // We need a complete type for what follows. Incomplete types can never be 4355 // initialized from init lists. 4356 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4357 return Result; 4358 4359 // C++11 [over.ics.list]p2: 4360 // If the parameter type is std::initializer_list<X> or "array of X" and 4361 // all the elements can be implicitly converted to X, the implicit 4362 // conversion sequence is the worst conversion necessary to convert an 4363 // element of the list to X. 4364 bool toStdInitializerList = false; 4365 QualType X; 4366 if (ToType->isArrayType()) 4367 X = S.Context.getBaseElementType(ToType); 4368 else 4369 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4370 if (!X.isNull()) { 4371 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4372 Expr *Init = From->getInit(i); 4373 ImplicitConversionSequence ICS = 4374 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4375 InOverloadResolution, 4376 AllowObjCWritebackConversion); 4377 // If a single element isn't convertible, fail. 4378 if (ICS.isBad()) { 4379 Result = ICS; 4380 break; 4381 } 4382 // Otherwise, look for the worst conversion. 4383 if (Result.isBad() || 4384 CompareImplicitConversionSequences(S, ICS, Result) == 4385 ImplicitConversionSequence::Worse) 4386 Result = ICS; 4387 } 4388 4389 // For an empty list, we won't have computed any conversion sequence. 4390 // Introduce the identity conversion sequence. 4391 if (From->getNumInits() == 0) { 4392 Result.setStandard(); 4393 Result.Standard.setAsIdentityConversion(); 4394 Result.Standard.setFromType(ToType); 4395 Result.Standard.setAllToTypes(ToType); 4396 } 4397 4398 Result.setListInitializationSequence(); 4399 Result.setStdInitializerListElement(toStdInitializerList); 4400 return Result; 4401 } 4402 4403 // C++11 [over.ics.list]p3: 4404 // Otherwise, if the parameter is a non-aggregate class X and overload 4405 // resolution chooses a single best constructor [...] the implicit 4406 // conversion sequence is a user-defined conversion sequence. If multiple 4407 // constructors are viable but none is better than the others, the 4408 // implicit conversion sequence is a user-defined conversion sequence. 4409 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4410 // This function can deal with initializer lists. 4411 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4412 /*AllowExplicit=*/false, 4413 InOverloadResolution, /*CStyle=*/false, 4414 AllowObjCWritebackConversion); 4415 Result.setListInitializationSequence(); 4416 return Result; 4417 } 4418 4419 // C++11 [over.ics.list]p4: 4420 // Otherwise, if the parameter has an aggregate type which can be 4421 // initialized from the initializer list [...] the implicit conversion 4422 // sequence is a user-defined conversion sequence. 4423 if (ToType->isAggregateType()) { 4424 // Type is an aggregate, argument is an init list. At this point it comes 4425 // down to checking whether the initialization works. 4426 // FIXME: Find out whether this parameter is consumed or not. 4427 InitializedEntity Entity = 4428 InitializedEntity::InitializeParameter(S.Context, ToType, 4429 /*Consumed=*/false); 4430 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4431 Result.setUserDefined(); 4432 Result.UserDefined.Before.setAsIdentityConversion(); 4433 // Initializer lists don't have a type. 4434 Result.UserDefined.Before.setFromType(QualType()); 4435 Result.UserDefined.Before.setAllToTypes(QualType()); 4436 4437 Result.UserDefined.After.setAsIdentityConversion(); 4438 Result.UserDefined.After.setFromType(ToType); 4439 Result.UserDefined.After.setAllToTypes(ToType); 4440 Result.UserDefined.ConversionFunction = 0; 4441 } 4442 return Result; 4443 } 4444 4445 // C++11 [over.ics.list]p5: 4446 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4447 if (ToType->isReferenceType()) { 4448 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4449 // mention initializer lists in any way. So we go by what list- 4450 // initialization would do and try to extrapolate from that. 4451 4452 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4453 4454 // If the initializer list has a single element that is reference-related 4455 // to the parameter type, we initialize the reference from that. 4456 if (From->getNumInits() == 1) { 4457 Expr *Init = From->getInit(0); 4458 4459 QualType T2 = Init->getType(); 4460 4461 // If the initializer is the address of an overloaded function, try 4462 // to resolve the overloaded function. If all goes well, T2 is the 4463 // type of the resulting function. 4464 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4465 DeclAccessPair Found; 4466 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4467 Init, ToType, false, Found)) 4468 T2 = Fn->getType(); 4469 } 4470 4471 // Compute some basic properties of the types and the initializer. 4472 bool dummy1 = false; 4473 bool dummy2 = false; 4474 bool dummy3 = false; 4475 Sema::ReferenceCompareResult RefRelationship 4476 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4477 dummy2, dummy3); 4478 4479 if (RefRelationship >= Sema::Ref_Related) 4480 return TryReferenceInit(S, Init, ToType, 4481 /*FIXME:*/From->getLocStart(), 4482 SuppressUserConversions, 4483 /*AllowExplicit=*/false); 4484 } 4485 4486 // Otherwise, we bind the reference to a temporary created from the 4487 // initializer list. 4488 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4489 InOverloadResolution, 4490 AllowObjCWritebackConversion); 4491 if (Result.isFailure()) 4492 return Result; 4493 assert(!Result.isEllipsis() && 4494 "Sub-initialization cannot result in ellipsis conversion."); 4495 4496 // Can we even bind to a temporary? 4497 if (ToType->isRValueReferenceType() || 4498 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4499 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4500 Result.UserDefined.After; 4501 SCS.ReferenceBinding = true; 4502 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4503 SCS.BindsToRvalue = true; 4504 SCS.BindsToFunctionLvalue = false; 4505 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4506 SCS.ObjCLifetimeConversionBinding = false; 4507 } else 4508 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4509 From, ToType); 4510 return Result; 4511 } 4512 4513 // C++11 [over.ics.list]p6: 4514 // Otherwise, if the parameter type is not a class: 4515 if (!ToType->isRecordType()) { 4516 // - if the initializer list has one element, the implicit conversion 4517 // sequence is the one required to convert the element to the 4518 // parameter type. 4519 unsigned NumInits = From->getNumInits(); 4520 if (NumInits == 1) 4521 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4522 SuppressUserConversions, 4523 InOverloadResolution, 4524 AllowObjCWritebackConversion); 4525 // - if the initializer list has no elements, the implicit conversion 4526 // sequence is the identity conversion. 4527 else if (NumInits == 0) { 4528 Result.setStandard(); 4529 Result.Standard.setAsIdentityConversion(); 4530 Result.Standard.setFromType(ToType); 4531 Result.Standard.setAllToTypes(ToType); 4532 } 4533 Result.setListInitializationSequence(); 4534 return Result; 4535 } 4536 4537 // C++11 [over.ics.list]p7: 4538 // In all cases other than those enumerated above, no conversion is possible 4539 return Result; 4540} 4541 4542/// TryCopyInitialization - Try to copy-initialize a value of type 4543/// ToType from the expression From. Return the implicit conversion 4544/// sequence required to pass this argument, which may be a bad 4545/// conversion sequence (meaning that the argument cannot be passed to 4546/// a parameter of this type). If @p SuppressUserConversions, then we 4547/// do not permit any user-defined conversion sequences. 4548static ImplicitConversionSequence 4549TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4550 bool SuppressUserConversions, 4551 bool InOverloadResolution, 4552 bool AllowObjCWritebackConversion, 4553 bool AllowExplicit) { 4554 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4555 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4556 InOverloadResolution,AllowObjCWritebackConversion); 4557 4558 if (ToType->isReferenceType()) 4559 return TryReferenceInit(S, From, ToType, 4560 /*FIXME:*/From->getLocStart(), 4561 SuppressUserConversions, 4562 AllowExplicit); 4563 4564 return TryImplicitConversion(S, From, ToType, 4565 SuppressUserConversions, 4566 /*AllowExplicit=*/false, 4567 InOverloadResolution, 4568 /*CStyle=*/false, 4569 AllowObjCWritebackConversion); 4570} 4571 4572static bool TryCopyInitialization(const CanQualType FromQTy, 4573 const CanQualType ToQTy, 4574 Sema &S, 4575 SourceLocation Loc, 4576 ExprValueKind FromVK) { 4577 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4578 ImplicitConversionSequence ICS = 4579 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4580 4581 return !ICS.isBad(); 4582} 4583 4584/// TryObjectArgumentInitialization - Try to initialize the object 4585/// parameter of the given member function (@c Method) from the 4586/// expression @p From. 4587static ImplicitConversionSequence 4588TryObjectArgumentInitialization(Sema &S, QualType OrigFromType, 4589 Expr::Classification FromClassification, 4590 CXXMethodDecl *Method, 4591 CXXRecordDecl *ActingContext) { 4592 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4593 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4594 // const volatile object. 4595 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4596 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4597 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4598 4599 // Set up the conversion sequence as a "bad" conversion, to allow us 4600 // to exit early. 4601 ImplicitConversionSequence ICS; 4602 4603 // We need to have an object of class type. 4604 QualType FromType = OrigFromType; 4605 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4606 FromType = PT->getPointeeType(); 4607 4608 // When we had a pointer, it's implicitly dereferenced, so we 4609 // better have an lvalue. 4610 assert(FromClassification.isLValue()); 4611 } 4612 4613 assert(FromType->isRecordType()); 4614 4615 // C++0x [over.match.funcs]p4: 4616 // For non-static member functions, the type of the implicit object 4617 // parameter is 4618 // 4619 // - "lvalue reference to cv X" for functions declared without a 4620 // ref-qualifier or with the & ref-qualifier 4621 // - "rvalue reference to cv X" for functions declared with the && 4622 // ref-qualifier 4623 // 4624 // where X is the class of which the function is a member and cv is the 4625 // cv-qualification on the member function declaration. 4626 // 4627 // However, when finding an implicit conversion sequence for the argument, we 4628 // are not allowed to create temporaries or perform user-defined conversions 4629 // (C++ [over.match.funcs]p5). We perform a simplified version of 4630 // reference binding here, that allows class rvalues to bind to 4631 // non-constant references. 4632 4633 // First check the qualifiers. 4634 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4635 if (ImplicitParamType.getCVRQualifiers() 4636 != FromTypeCanon.getLocalCVRQualifiers() && 4637 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4638 ICS.setBad(BadConversionSequence::bad_qualifiers, 4639 OrigFromType, ImplicitParamType); 4640 return ICS; 4641 } 4642 4643 // Check that we have either the same type or a derived type. It 4644 // affects the conversion rank. 4645 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4646 ImplicitConversionKind SecondKind; 4647 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4648 SecondKind = ICK_Identity; 4649 } else if (S.IsDerivedFrom(FromType, ClassType)) 4650 SecondKind = ICK_Derived_To_Base; 4651 else { 4652 ICS.setBad(BadConversionSequence::unrelated_class, 4653 FromType, ImplicitParamType); 4654 return ICS; 4655 } 4656 4657 // Check the ref-qualifier. 4658 switch (Method->getRefQualifier()) { 4659 case RQ_None: 4660 // Do nothing; we don't care about lvalueness or rvalueness. 4661 break; 4662 4663 case RQ_LValue: 4664 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4665 // non-const lvalue reference cannot bind to an rvalue 4666 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4667 ImplicitParamType); 4668 return ICS; 4669 } 4670 break; 4671 4672 case RQ_RValue: 4673 if (!FromClassification.isRValue()) { 4674 // rvalue reference cannot bind to an lvalue 4675 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4676 ImplicitParamType); 4677 return ICS; 4678 } 4679 break; 4680 } 4681 4682 // Success. Mark this as a reference binding. 4683 ICS.setStandard(); 4684 ICS.Standard.setAsIdentityConversion(); 4685 ICS.Standard.Second = SecondKind; 4686 ICS.Standard.setFromType(FromType); 4687 ICS.Standard.setAllToTypes(ImplicitParamType); 4688 ICS.Standard.ReferenceBinding = true; 4689 ICS.Standard.DirectBinding = true; 4690 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4691 ICS.Standard.BindsToFunctionLvalue = false; 4692 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4693 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4694 = (Method->getRefQualifier() == RQ_None); 4695 return ICS; 4696} 4697 4698/// PerformObjectArgumentInitialization - Perform initialization of 4699/// the implicit object parameter for the given Method with the given 4700/// expression. 4701ExprResult 4702Sema::PerformObjectArgumentInitialization(Expr *From, 4703 NestedNameSpecifier *Qualifier, 4704 NamedDecl *FoundDecl, 4705 CXXMethodDecl *Method) { 4706 QualType FromRecordType, DestType; 4707 QualType ImplicitParamRecordType = 4708 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4709 4710 Expr::Classification FromClassification; 4711 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4712 FromRecordType = PT->getPointeeType(); 4713 DestType = Method->getThisType(Context); 4714 FromClassification = Expr::Classification::makeSimpleLValue(); 4715 } else { 4716 FromRecordType = From->getType(); 4717 DestType = ImplicitParamRecordType; 4718 FromClassification = From->Classify(Context); 4719 } 4720 4721 // Note that we always use the true parent context when performing 4722 // the actual argument initialization. 4723 ImplicitConversionSequence ICS 4724 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4725 Method, Method->getParent()); 4726 if (ICS.isBad()) { 4727 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4728 Qualifiers FromQs = FromRecordType.getQualifiers(); 4729 Qualifiers ToQs = DestType.getQualifiers(); 4730 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4731 if (CVR) { 4732 Diag(From->getLocStart(), 4733 diag::err_member_function_call_bad_cvr) 4734 << Method->getDeclName() << FromRecordType << (CVR - 1) 4735 << From->getSourceRange(); 4736 Diag(Method->getLocation(), diag::note_previous_decl) 4737 << Method->getDeclName(); 4738 return ExprError(); 4739 } 4740 } 4741 4742 return Diag(From->getLocStart(), 4743 diag::err_implicit_object_parameter_init) 4744 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4745 } 4746 4747 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4748 ExprResult FromRes = 4749 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4750 if (FromRes.isInvalid()) 4751 return ExprError(); 4752 From = FromRes.take(); 4753 } 4754 4755 if (!Context.hasSameType(From->getType(), DestType)) 4756 From = ImpCastExprToType(From, DestType, CK_NoOp, 4757 From->getValueKind()).take(); 4758 return Owned(From); 4759} 4760 4761/// TryContextuallyConvertToBool - Attempt to contextually convert the 4762/// expression From to bool (C++0x [conv]p3). 4763static ImplicitConversionSequence 4764TryContextuallyConvertToBool(Sema &S, Expr *From) { 4765 // FIXME: This is pretty broken. 4766 return TryImplicitConversion(S, From, S.Context.BoolTy, 4767 // FIXME: Are these flags correct? 4768 /*SuppressUserConversions=*/false, 4769 /*AllowExplicit=*/true, 4770 /*InOverloadResolution=*/false, 4771 /*CStyle=*/false, 4772 /*AllowObjCWritebackConversion=*/false); 4773} 4774 4775/// PerformContextuallyConvertToBool - Perform a contextual conversion 4776/// of the expression From to bool (C++0x [conv]p3). 4777ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4778 if (checkPlaceholderForOverload(*this, From)) 4779 return ExprError(); 4780 4781 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4782 if (!ICS.isBad()) 4783 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4784 4785 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4786 return Diag(From->getLocStart(), 4787 diag::err_typecheck_bool_condition) 4788 << From->getType() << From->getSourceRange(); 4789 return ExprError(); 4790} 4791 4792/// Check that the specified conversion is permitted in a converted constant 4793/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4794/// is acceptable. 4795static bool CheckConvertedConstantConversions(Sema &S, 4796 StandardConversionSequence &SCS) { 4797 // Since we know that the target type is an integral or unscoped enumeration 4798 // type, most conversion kinds are impossible. All possible First and Third 4799 // conversions are fine. 4800 switch (SCS.Second) { 4801 case ICK_Identity: 4802 case ICK_Integral_Promotion: 4803 case ICK_Integral_Conversion: 4804 return true; 4805 4806 case ICK_Boolean_Conversion: 4807 case ICK_Floating_Integral: 4808 case ICK_Complex_Real: 4809 return false; 4810 4811 case ICK_Lvalue_To_Rvalue: 4812 case ICK_Array_To_Pointer: 4813 case ICK_Function_To_Pointer: 4814 case ICK_NoReturn_Adjustment: 4815 case ICK_Qualification: 4816 case ICK_Compatible_Conversion: 4817 case ICK_Vector_Conversion: 4818 case ICK_Vector_Splat: 4819 case ICK_Derived_To_Base: 4820 case ICK_Pointer_Conversion: 4821 case ICK_Pointer_Member: 4822 case ICK_Block_Pointer_Conversion: 4823 case ICK_Writeback_Conversion: 4824 case ICK_Floating_Promotion: 4825 case ICK_Complex_Promotion: 4826 case ICK_Complex_Conversion: 4827 case ICK_Floating_Conversion: 4828 case ICK_TransparentUnionConversion: 4829 llvm_unreachable("unexpected second conversion kind"); 4830 4831 case ICK_Num_Conversion_Kinds: 4832 break; 4833 } 4834 4835 llvm_unreachable("unknown conversion kind"); 4836} 4837 4838/// CheckConvertedConstantExpression - Check that the expression From is a 4839/// converted constant expression of type T, perform the conversion and produce 4840/// the converted expression, per C++11 [expr.const]p3. 4841ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4842 llvm::APSInt &Value, 4843 CCEKind CCE) { 4844 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11"); 4845 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4846 4847 if (checkPlaceholderForOverload(*this, From)) 4848 return ExprError(); 4849 4850 // C++11 [expr.const]p3 with proposed wording fixes: 4851 // A converted constant expression of type T is a core constant expression, 4852 // implicitly converted to a prvalue of type T, where the converted 4853 // expression is a literal constant expression and the implicit conversion 4854 // sequence contains only user-defined conversions, lvalue-to-rvalue 4855 // conversions, integral promotions, and integral conversions other than 4856 // narrowing conversions. 4857 ImplicitConversionSequence ICS = 4858 TryImplicitConversion(From, T, 4859 /*SuppressUserConversions=*/false, 4860 /*AllowExplicit=*/false, 4861 /*InOverloadResolution=*/false, 4862 /*CStyle=*/false, 4863 /*AllowObjcWritebackConversion=*/false); 4864 StandardConversionSequence *SCS = 0; 4865 switch (ICS.getKind()) { 4866 case ImplicitConversionSequence::StandardConversion: 4867 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4868 return Diag(From->getLocStart(), 4869 diag::err_typecheck_converted_constant_expression_disallowed) 4870 << From->getType() << From->getSourceRange() << T; 4871 SCS = &ICS.Standard; 4872 break; 4873 case ImplicitConversionSequence::UserDefinedConversion: 4874 // We are converting from class type to an integral or enumeration type, so 4875 // the Before sequence must be trivial. 4876 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4877 return Diag(From->getLocStart(), 4878 diag::err_typecheck_converted_constant_expression_disallowed) 4879 << From->getType() << From->getSourceRange() << T; 4880 SCS = &ICS.UserDefined.After; 4881 break; 4882 case ImplicitConversionSequence::AmbiguousConversion: 4883 case ImplicitConversionSequence::BadConversion: 4884 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4885 return Diag(From->getLocStart(), 4886 diag::err_typecheck_converted_constant_expression) 4887 << From->getType() << From->getSourceRange() << T; 4888 return ExprError(); 4889 4890 case ImplicitConversionSequence::EllipsisConversion: 4891 llvm_unreachable("ellipsis conversion in converted constant expression"); 4892 } 4893 4894 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4895 if (Result.isInvalid()) 4896 return Result; 4897 4898 // Check for a narrowing implicit conversion. 4899 APValue PreNarrowingValue; 4900 QualType PreNarrowingType; 4901 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4902 PreNarrowingType)) { 4903 case NK_Variable_Narrowing: 4904 // Implicit conversion to a narrower type, and the value is not a constant 4905 // expression. We'll diagnose this in a moment. 4906 case NK_Not_Narrowing: 4907 break; 4908 4909 case NK_Constant_Narrowing: 4910 Diag(From->getLocStart(), 4911 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4912 diag::err_cce_narrowing) 4913 << CCE << /*Constant*/1 4914 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4915 break; 4916 4917 case NK_Type_Narrowing: 4918 Diag(From->getLocStart(), 4919 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4920 diag::err_cce_narrowing) 4921 << CCE << /*Constant*/0 << From->getType() << T; 4922 break; 4923 } 4924 4925 // Check the expression is a constant expression. 4926 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 4927 Expr::EvalResult Eval; 4928 Eval.Diag = &Notes; 4929 4930 if (!Result.get()->EvaluateAsRValue(Eval, Context)) { 4931 // The expression can't be folded, so we can't keep it at this position in 4932 // the AST. 4933 Result = ExprError(); 4934 } else { 4935 Value = Eval.Val.getInt(); 4936 4937 if (Notes.empty()) { 4938 // It's a constant expression. 4939 return Result; 4940 } 4941 } 4942 4943 // It's not a constant expression. Produce an appropriate diagnostic. 4944 if (Notes.size() == 1 && 4945 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 4946 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 4947 else { 4948 Diag(From->getLocStart(), diag::err_expr_not_cce) 4949 << CCE << From->getSourceRange(); 4950 for (unsigned I = 0; I < Notes.size(); ++I) 4951 Diag(Notes[I].first, Notes[I].second); 4952 } 4953 return Result; 4954} 4955 4956/// dropPointerConversions - If the given standard conversion sequence 4957/// involves any pointer conversions, remove them. This may change 4958/// the result type of the conversion sequence. 4959static void dropPointerConversion(StandardConversionSequence &SCS) { 4960 if (SCS.Second == ICK_Pointer_Conversion) { 4961 SCS.Second = ICK_Identity; 4962 SCS.Third = ICK_Identity; 4963 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 4964 } 4965} 4966 4967/// TryContextuallyConvertToObjCPointer - Attempt to contextually 4968/// convert the expression From to an Objective-C pointer type. 4969static ImplicitConversionSequence 4970TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 4971 // Do an implicit conversion to 'id'. 4972 QualType Ty = S.Context.getObjCIdType(); 4973 ImplicitConversionSequence ICS 4974 = TryImplicitConversion(S, From, Ty, 4975 // FIXME: Are these flags correct? 4976 /*SuppressUserConversions=*/false, 4977 /*AllowExplicit=*/true, 4978 /*InOverloadResolution=*/false, 4979 /*CStyle=*/false, 4980 /*AllowObjCWritebackConversion=*/false); 4981 4982 // Strip off any final conversions to 'id'. 4983 switch (ICS.getKind()) { 4984 case ImplicitConversionSequence::BadConversion: 4985 case ImplicitConversionSequence::AmbiguousConversion: 4986 case ImplicitConversionSequence::EllipsisConversion: 4987 break; 4988 4989 case ImplicitConversionSequence::UserDefinedConversion: 4990 dropPointerConversion(ICS.UserDefined.After); 4991 break; 4992 4993 case ImplicitConversionSequence::StandardConversion: 4994 dropPointerConversion(ICS.Standard); 4995 break; 4996 } 4997 4998 return ICS; 4999} 5000 5001/// PerformContextuallyConvertToObjCPointer - Perform a contextual 5002/// conversion of the expression From to an Objective-C pointer type. 5003ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5004 if (checkPlaceholderForOverload(*this, From)) 5005 return ExprError(); 5006 5007 QualType Ty = Context.getObjCIdType(); 5008 ImplicitConversionSequence ICS = 5009 TryContextuallyConvertToObjCPointer(*this, From); 5010 if (!ICS.isBad()) 5011 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5012 return ExprError(); 5013} 5014 5015/// Determine whether the provided type is an integral type, or an enumeration 5016/// type of a permitted flavor. 5017static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) { 5018 return AllowScopedEnum ? T->isIntegralOrEnumerationType() 5019 : T->isIntegralOrUnscopedEnumerationType(); 5020} 5021 5022/// \brief Attempt to convert the given expression to an integral or 5023/// enumeration type. 5024/// 5025/// This routine will attempt to convert an expression of class type to an 5026/// integral or enumeration type, if that class type only has a single 5027/// conversion to an integral or enumeration type. 5028/// 5029/// \param Loc The source location of the construct that requires the 5030/// conversion. 5031/// 5032/// \param From The expression we're converting from. 5033/// 5034/// \param Diagnoser Used to output any diagnostics. 5035/// 5036/// \param AllowScopedEnumerations Specifies whether conversions to scoped 5037/// enumerations should be considered. 5038/// 5039/// \returns The expression, converted to an integral or enumeration type if 5040/// successful. 5041ExprResult 5042Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 5043 ICEConvertDiagnoser &Diagnoser, 5044 bool AllowScopedEnumerations) { 5045 // We can't perform any more checking for type-dependent expressions. 5046 if (From->isTypeDependent()) 5047 return Owned(From); 5048 5049 // Process placeholders immediately. 5050 if (From->hasPlaceholderType()) { 5051 ExprResult result = CheckPlaceholderExpr(From); 5052 if (result.isInvalid()) return result; 5053 From = result.take(); 5054 } 5055 5056 // If the expression already has integral or enumeration type, we're golden. 5057 QualType T = From->getType(); 5058 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations)) 5059 return DefaultLvalueConversion(From); 5060 5061 // FIXME: Check for missing '()' if T is a function type? 5062 5063 // If we don't have a class type in C++, there's no way we can get an 5064 // expression of integral or enumeration type. 5065 const RecordType *RecordTy = T->getAs<RecordType>(); 5066 if (!RecordTy || !getLangOpts().CPlusPlus) { 5067 if (!Diagnoser.Suppress) 5068 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange(); 5069 return Owned(From); 5070 } 5071 5072 // We must have a complete class type. 5073 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5074 ICEConvertDiagnoser &Diagnoser; 5075 Expr *From; 5076 5077 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From) 5078 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {} 5079 5080 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5081 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5082 } 5083 } IncompleteDiagnoser(Diagnoser, From); 5084 5085 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5086 return Owned(From); 5087 5088 // Look for a conversion to an integral or enumeration type. 5089 UnresolvedSet<4> ViableConversions; 5090 UnresolvedSet<4> ExplicitConversions; 5091 const UnresolvedSetImpl *Conversions 5092 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5093 5094 bool HadMultipleCandidates = (Conversions->size() > 1); 5095 5096 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 5097 E = Conversions->end(); 5098 I != E; 5099 ++I) { 5100 if (CXXConversionDecl *Conversion 5101 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 5102 if (isIntegralOrEnumerationType( 5103 Conversion->getConversionType().getNonReferenceType(), 5104 AllowScopedEnumerations)) { 5105 if (Conversion->isExplicit()) 5106 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5107 else 5108 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5109 } 5110 } 5111 } 5112 5113 switch (ViableConversions.size()) { 5114 case 0: 5115 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) { 5116 DeclAccessPair Found = ExplicitConversions[0]; 5117 CXXConversionDecl *Conversion 5118 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5119 5120 // The user probably meant to invoke the given explicit 5121 // conversion; use it. 5122 QualType ConvTy 5123 = Conversion->getConversionType().getNonReferenceType(); 5124 std::string TypeStr; 5125 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy()); 5126 5127 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy) 5128 << FixItHint::CreateInsertion(From->getLocStart(), 5129 "static_cast<" + TypeStr + ">(") 5130 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 5131 ")"); 5132 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy); 5133 5134 // If we aren't in a SFINAE context, build a call to the 5135 // explicit conversion function. 5136 if (isSFINAEContext()) 5137 return ExprError(); 5138 5139 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5140 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5141 HadMultipleCandidates); 5142 if (Result.isInvalid()) 5143 return ExprError(); 5144 // Record usage of conversion in an implicit cast. 5145 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5146 CK_UserDefinedConversion, 5147 Result.get(), 0, 5148 Result.get()->getValueKind()); 5149 } 5150 5151 // We'll complain below about a non-integral condition type. 5152 break; 5153 5154 case 1: { 5155 // Apply this conversion. 5156 DeclAccessPair Found = ViableConversions[0]; 5157 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5158 5159 CXXConversionDecl *Conversion 5160 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5161 QualType ConvTy 5162 = Conversion->getConversionType().getNonReferenceType(); 5163 if (!Diagnoser.SuppressConversion) { 5164 if (isSFINAEContext()) 5165 return ExprError(); 5166 5167 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy) 5168 << From->getSourceRange(); 5169 } 5170 5171 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5172 HadMultipleCandidates); 5173 if (Result.isInvalid()) 5174 return ExprError(); 5175 // Record usage of conversion in an implicit cast. 5176 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5177 CK_UserDefinedConversion, 5178 Result.get(), 0, 5179 Result.get()->getValueKind()); 5180 break; 5181 } 5182 5183 default: 5184 if (Diagnoser.Suppress) 5185 return ExprError(); 5186 5187 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange(); 5188 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5189 CXXConversionDecl *Conv 5190 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5191 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5192 Diagnoser.noteAmbiguous(*this, Conv, ConvTy); 5193 } 5194 return Owned(From); 5195 } 5196 5197 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) && 5198 !Diagnoser.Suppress) { 5199 Diagnoser.diagnoseNotInt(*this, Loc, From->getType()) 5200 << From->getSourceRange(); 5201 } 5202 5203 return DefaultLvalueConversion(From); 5204} 5205 5206/// AddOverloadCandidate - Adds the given function to the set of 5207/// candidate functions, using the given function call arguments. If 5208/// @p SuppressUserConversions, then don't allow user-defined 5209/// conversions via constructors or conversion operators. 5210/// 5211/// \param PartialOverloading true if we are performing "partial" overloading 5212/// based on an incomplete set of function arguments. This feature is used by 5213/// code completion. 5214void 5215Sema::AddOverloadCandidate(FunctionDecl *Function, 5216 DeclAccessPair FoundDecl, 5217 llvm::ArrayRef<Expr *> Args, 5218 OverloadCandidateSet& CandidateSet, 5219 bool SuppressUserConversions, 5220 bool PartialOverloading, 5221 bool AllowExplicit) { 5222 const FunctionProtoType* Proto 5223 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5224 assert(Proto && "Functions without a prototype cannot be overloaded"); 5225 assert(!Function->getDescribedFunctionTemplate() && 5226 "Use AddTemplateOverloadCandidate for function templates"); 5227 5228 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5229 if (!isa<CXXConstructorDecl>(Method)) { 5230 // If we get here, it's because we're calling a member function 5231 // that is named without a member access expression (e.g., 5232 // "this->f") that was either written explicitly or created 5233 // implicitly. This can happen with a qualified call to a member 5234 // function, e.g., X::f(). We use an empty type for the implied 5235 // object argument (C++ [over.call.func]p3), and the acting context 5236 // is irrelevant. 5237 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5238 QualType(), Expr::Classification::makeSimpleLValue(), 5239 Args, CandidateSet, SuppressUserConversions); 5240 return; 5241 } 5242 // We treat a constructor like a non-member function, since its object 5243 // argument doesn't participate in overload resolution. 5244 } 5245 5246 if (!CandidateSet.isNewCandidate(Function)) 5247 return; 5248 5249 // Overload resolution is always an unevaluated context. 5250 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5251 5252 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5253 // C++ [class.copy]p3: 5254 // A member function template is never instantiated to perform the copy 5255 // of a class object to an object of its class type. 5256 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5257 if (Args.size() == 1 && 5258 Constructor->isSpecializationCopyingObject() && 5259 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5260 IsDerivedFrom(Args[0]->getType(), ClassType))) 5261 return; 5262 } 5263 5264 // Add this candidate 5265 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5266 Candidate.FoundDecl = FoundDecl; 5267 Candidate.Function = Function; 5268 Candidate.Viable = true; 5269 Candidate.IsSurrogate = false; 5270 Candidate.IgnoreObjectArgument = false; 5271 Candidate.ExplicitCallArguments = Args.size(); 5272 5273 unsigned NumArgsInProto = Proto->getNumArgs(); 5274 5275 // (C++ 13.3.2p2): A candidate function having fewer than m 5276 // parameters is viable only if it has an ellipsis in its parameter 5277 // list (8.3.5). 5278 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5279 !Proto->isVariadic()) { 5280 Candidate.Viable = false; 5281 Candidate.FailureKind = ovl_fail_too_many_arguments; 5282 return; 5283 } 5284 5285 // (C++ 13.3.2p2): A candidate function having more than m parameters 5286 // is viable only if the (m+1)st parameter has a default argument 5287 // (8.3.6). For the purposes of overload resolution, the 5288 // parameter list is truncated on the right, so that there are 5289 // exactly m parameters. 5290 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5291 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5292 // Not enough arguments. 5293 Candidate.Viable = false; 5294 Candidate.FailureKind = ovl_fail_too_few_arguments; 5295 return; 5296 } 5297 5298 // (CUDA B.1): Check for invalid calls between targets. 5299 if (getLangOpts().CUDA) 5300 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5301 if (CheckCUDATarget(Caller, Function)) { 5302 Candidate.Viable = false; 5303 Candidate.FailureKind = ovl_fail_bad_target; 5304 return; 5305 } 5306 5307 // Determine the implicit conversion sequences for each of the 5308 // arguments. 5309 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5310 if (ArgIdx < NumArgsInProto) { 5311 // (C++ 13.3.2p3): for F to be a viable function, there shall 5312 // exist for each argument an implicit conversion sequence 5313 // (13.3.3.1) that converts that argument to the corresponding 5314 // parameter of F. 5315 QualType ParamType = Proto->getArgType(ArgIdx); 5316 Candidate.Conversions[ArgIdx] 5317 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5318 SuppressUserConversions, 5319 /*InOverloadResolution=*/true, 5320 /*AllowObjCWritebackConversion=*/ 5321 getLangOpts().ObjCAutoRefCount, 5322 AllowExplicit); 5323 if (Candidate.Conversions[ArgIdx].isBad()) { 5324 Candidate.Viable = false; 5325 Candidate.FailureKind = ovl_fail_bad_conversion; 5326 break; 5327 } 5328 } else { 5329 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5330 // argument for which there is no corresponding parameter is 5331 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5332 Candidate.Conversions[ArgIdx].setEllipsis(); 5333 } 5334 } 5335} 5336 5337/// \brief Add all of the function declarations in the given function set to 5338/// the overload canddiate set. 5339void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5340 llvm::ArrayRef<Expr *> Args, 5341 OverloadCandidateSet& CandidateSet, 5342 bool SuppressUserConversions, 5343 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5344 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5345 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5346 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5347 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5348 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5349 cast<CXXMethodDecl>(FD)->getParent(), 5350 Args[0]->getType(), Args[0]->Classify(Context), 5351 Args.slice(1), CandidateSet, 5352 SuppressUserConversions); 5353 else 5354 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5355 SuppressUserConversions); 5356 } else { 5357 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5358 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5359 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5360 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5361 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5362 ExplicitTemplateArgs, 5363 Args[0]->getType(), 5364 Args[0]->Classify(Context), Args.slice(1), 5365 CandidateSet, SuppressUserConversions); 5366 else 5367 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5368 ExplicitTemplateArgs, Args, 5369 CandidateSet, SuppressUserConversions); 5370 } 5371 } 5372} 5373 5374/// AddMethodCandidate - Adds a named decl (which is some kind of 5375/// method) as a method candidate to the given overload set. 5376void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5377 QualType ObjectType, 5378 Expr::Classification ObjectClassification, 5379 Expr **Args, unsigned NumArgs, 5380 OverloadCandidateSet& CandidateSet, 5381 bool SuppressUserConversions) { 5382 NamedDecl *Decl = FoundDecl.getDecl(); 5383 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5384 5385 if (isa<UsingShadowDecl>(Decl)) 5386 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5387 5388 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5389 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5390 "Expected a member function template"); 5391 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5392 /*ExplicitArgs*/ 0, 5393 ObjectType, ObjectClassification, 5394 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 5395 SuppressUserConversions); 5396 } else { 5397 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5398 ObjectType, ObjectClassification, 5399 llvm::makeArrayRef(Args, NumArgs), 5400 CandidateSet, SuppressUserConversions); 5401 } 5402} 5403 5404/// AddMethodCandidate - Adds the given C++ member function to the set 5405/// of candidate functions, using the given function call arguments 5406/// and the object argument (@c Object). For example, in a call 5407/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5408/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5409/// allow user-defined conversions via constructors or conversion 5410/// operators. 5411void 5412Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5413 CXXRecordDecl *ActingContext, QualType ObjectType, 5414 Expr::Classification ObjectClassification, 5415 llvm::ArrayRef<Expr *> Args, 5416 OverloadCandidateSet& CandidateSet, 5417 bool SuppressUserConversions) { 5418 const FunctionProtoType* Proto 5419 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5420 assert(Proto && "Methods without a prototype cannot be overloaded"); 5421 assert(!isa<CXXConstructorDecl>(Method) && 5422 "Use AddOverloadCandidate for constructors"); 5423 5424 if (!CandidateSet.isNewCandidate(Method)) 5425 return; 5426 5427 // Overload resolution is always an unevaluated context. 5428 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5429 5430 // Add this candidate 5431 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5432 Candidate.FoundDecl = FoundDecl; 5433 Candidate.Function = Method; 5434 Candidate.IsSurrogate = false; 5435 Candidate.IgnoreObjectArgument = false; 5436 Candidate.ExplicitCallArguments = Args.size(); 5437 5438 unsigned NumArgsInProto = Proto->getNumArgs(); 5439 5440 // (C++ 13.3.2p2): A candidate function having fewer than m 5441 // parameters is viable only if it has an ellipsis in its parameter 5442 // list (8.3.5). 5443 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5444 Candidate.Viable = false; 5445 Candidate.FailureKind = ovl_fail_too_many_arguments; 5446 return; 5447 } 5448 5449 // (C++ 13.3.2p2): A candidate function having more than m parameters 5450 // is viable only if the (m+1)st parameter has a default argument 5451 // (8.3.6). For the purposes of overload resolution, the 5452 // parameter list is truncated on the right, so that there are 5453 // exactly m parameters. 5454 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5455 if (Args.size() < MinRequiredArgs) { 5456 // Not enough arguments. 5457 Candidate.Viable = false; 5458 Candidate.FailureKind = ovl_fail_too_few_arguments; 5459 return; 5460 } 5461 5462 Candidate.Viable = true; 5463 5464 if (Method->isStatic() || ObjectType.isNull()) 5465 // The implicit object argument is ignored. 5466 Candidate.IgnoreObjectArgument = true; 5467 else { 5468 // Determine the implicit conversion sequence for the object 5469 // parameter. 5470 Candidate.Conversions[0] 5471 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5472 Method, ActingContext); 5473 if (Candidate.Conversions[0].isBad()) { 5474 Candidate.Viable = false; 5475 Candidate.FailureKind = ovl_fail_bad_conversion; 5476 return; 5477 } 5478 } 5479 5480 // Determine the implicit conversion sequences for each of the 5481 // arguments. 5482 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5483 if (ArgIdx < NumArgsInProto) { 5484 // (C++ 13.3.2p3): for F to be a viable function, there shall 5485 // exist for each argument an implicit conversion sequence 5486 // (13.3.3.1) that converts that argument to the corresponding 5487 // parameter of F. 5488 QualType ParamType = Proto->getArgType(ArgIdx); 5489 Candidate.Conversions[ArgIdx + 1] 5490 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5491 SuppressUserConversions, 5492 /*InOverloadResolution=*/true, 5493 /*AllowObjCWritebackConversion=*/ 5494 getLangOpts().ObjCAutoRefCount); 5495 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5496 Candidate.Viable = false; 5497 Candidate.FailureKind = ovl_fail_bad_conversion; 5498 break; 5499 } 5500 } else { 5501 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5502 // argument for which there is no corresponding parameter is 5503 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5504 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5505 } 5506 } 5507} 5508 5509/// \brief Add a C++ member function template as a candidate to the candidate 5510/// set, using template argument deduction to produce an appropriate member 5511/// function template specialization. 5512void 5513Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5514 DeclAccessPair FoundDecl, 5515 CXXRecordDecl *ActingContext, 5516 TemplateArgumentListInfo *ExplicitTemplateArgs, 5517 QualType ObjectType, 5518 Expr::Classification ObjectClassification, 5519 llvm::ArrayRef<Expr *> Args, 5520 OverloadCandidateSet& CandidateSet, 5521 bool SuppressUserConversions) { 5522 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5523 return; 5524 5525 // C++ [over.match.funcs]p7: 5526 // In each case where a candidate is a function template, candidate 5527 // function template specializations are generated using template argument 5528 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5529 // candidate functions in the usual way.113) A given name can refer to one 5530 // or more function templates and also to a set of overloaded non-template 5531 // functions. In such a case, the candidate functions generated from each 5532 // function template are combined with the set of non-template candidate 5533 // functions. 5534 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5535 FunctionDecl *Specialization = 0; 5536 if (TemplateDeductionResult Result 5537 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5538 Specialization, Info)) { 5539 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5540 Candidate.FoundDecl = FoundDecl; 5541 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5542 Candidate.Viable = false; 5543 Candidate.FailureKind = ovl_fail_bad_deduction; 5544 Candidate.IsSurrogate = false; 5545 Candidate.IgnoreObjectArgument = false; 5546 Candidate.ExplicitCallArguments = Args.size(); 5547 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5548 Info); 5549 return; 5550 } 5551 5552 // Add the function template specialization produced by template argument 5553 // deduction as a candidate. 5554 assert(Specialization && "Missing member function template specialization?"); 5555 assert(isa<CXXMethodDecl>(Specialization) && 5556 "Specialization is not a member function?"); 5557 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5558 ActingContext, ObjectType, ObjectClassification, Args, 5559 CandidateSet, SuppressUserConversions); 5560} 5561 5562/// \brief Add a C++ function template specialization as a candidate 5563/// in the candidate set, using template argument deduction to produce 5564/// an appropriate function template specialization. 5565void 5566Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5567 DeclAccessPair FoundDecl, 5568 TemplateArgumentListInfo *ExplicitTemplateArgs, 5569 llvm::ArrayRef<Expr *> Args, 5570 OverloadCandidateSet& CandidateSet, 5571 bool SuppressUserConversions) { 5572 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5573 return; 5574 5575 // C++ [over.match.funcs]p7: 5576 // In each case where a candidate is a function template, candidate 5577 // function template specializations are generated using template argument 5578 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5579 // candidate functions in the usual way.113) A given name can refer to one 5580 // or more function templates and also to a set of overloaded non-template 5581 // functions. In such a case, the candidate functions generated from each 5582 // function template are combined with the set of non-template candidate 5583 // functions. 5584 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5585 FunctionDecl *Specialization = 0; 5586 if (TemplateDeductionResult Result 5587 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5588 Specialization, Info)) { 5589 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5590 Candidate.FoundDecl = FoundDecl; 5591 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5592 Candidate.Viable = false; 5593 Candidate.FailureKind = ovl_fail_bad_deduction; 5594 Candidate.IsSurrogate = false; 5595 Candidate.IgnoreObjectArgument = false; 5596 Candidate.ExplicitCallArguments = Args.size(); 5597 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5598 Info); 5599 return; 5600 } 5601 5602 // Add the function template specialization produced by template argument 5603 // deduction as a candidate. 5604 assert(Specialization && "Missing function template specialization?"); 5605 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5606 SuppressUserConversions); 5607} 5608 5609/// AddConversionCandidate - Add a C++ conversion function as a 5610/// candidate in the candidate set (C++ [over.match.conv], 5611/// C++ [over.match.copy]). From is the expression we're converting from, 5612/// and ToType is the type that we're eventually trying to convert to 5613/// (which may or may not be the same type as the type that the 5614/// conversion function produces). 5615void 5616Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5617 DeclAccessPair FoundDecl, 5618 CXXRecordDecl *ActingContext, 5619 Expr *From, QualType ToType, 5620 OverloadCandidateSet& CandidateSet) { 5621 assert(!Conversion->getDescribedFunctionTemplate() && 5622 "Conversion function templates use AddTemplateConversionCandidate"); 5623 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5624 if (!CandidateSet.isNewCandidate(Conversion)) 5625 return; 5626 5627 // Overload resolution is always an unevaluated context. 5628 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5629 5630 // Add this candidate 5631 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5632 Candidate.FoundDecl = FoundDecl; 5633 Candidate.Function = Conversion; 5634 Candidate.IsSurrogate = false; 5635 Candidate.IgnoreObjectArgument = false; 5636 Candidate.FinalConversion.setAsIdentityConversion(); 5637 Candidate.FinalConversion.setFromType(ConvType); 5638 Candidate.FinalConversion.setAllToTypes(ToType); 5639 Candidate.Viable = true; 5640 Candidate.ExplicitCallArguments = 1; 5641 5642 // C++ [over.match.funcs]p4: 5643 // For conversion functions, the function is considered to be a member of 5644 // the class of the implicit implied object argument for the purpose of 5645 // defining the type of the implicit object parameter. 5646 // 5647 // Determine the implicit conversion sequence for the implicit 5648 // object parameter. 5649 QualType ImplicitParamType = From->getType(); 5650 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5651 ImplicitParamType = FromPtrType->getPointeeType(); 5652 CXXRecordDecl *ConversionContext 5653 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5654 5655 Candidate.Conversions[0] 5656 = TryObjectArgumentInitialization(*this, From->getType(), 5657 From->Classify(Context), 5658 Conversion, ConversionContext); 5659 5660 if (Candidate.Conversions[0].isBad()) { 5661 Candidate.Viable = false; 5662 Candidate.FailureKind = ovl_fail_bad_conversion; 5663 return; 5664 } 5665 5666 // We won't go through a user-define type conversion function to convert a 5667 // derived to base as such conversions are given Conversion Rank. They only 5668 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5669 QualType FromCanon 5670 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5671 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5672 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5673 Candidate.Viable = false; 5674 Candidate.FailureKind = ovl_fail_trivial_conversion; 5675 return; 5676 } 5677 5678 // To determine what the conversion from the result of calling the 5679 // conversion function to the type we're eventually trying to 5680 // convert to (ToType), we need to synthesize a call to the 5681 // conversion function and attempt copy initialization from it. This 5682 // makes sure that we get the right semantics with respect to 5683 // lvalues/rvalues and the type. Fortunately, we can allocate this 5684 // call on the stack and we don't need its arguments to be 5685 // well-formed. 5686 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5687 VK_LValue, From->getLocStart()); 5688 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5689 Context.getPointerType(Conversion->getType()), 5690 CK_FunctionToPointerDecay, 5691 &ConversionRef, VK_RValue); 5692 5693 QualType ConversionType = Conversion->getConversionType(); 5694 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5695 Candidate.Viable = false; 5696 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5697 return; 5698 } 5699 5700 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5701 5702 // Note that it is safe to allocate CallExpr on the stack here because 5703 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5704 // allocator). 5705 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5706 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK, 5707 From->getLocStart()); 5708 ImplicitConversionSequence ICS = 5709 TryCopyInitialization(*this, &Call, ToType, 5710 /*SuppressUserConversions=*/true, 5711 /*InOverloadResolution=*/false, 5712 /*AllowObjCWritebackConversion=*/false); 5713 5714 switch (ICS.getKind()) { 5715 case ImplicitConversionSequence::StandardConversion: 5716 Candidate.FinalConversion = ICS.Standard; 5717 5718 // C++ [over.ics.user]p3: 5719 // If the user-defined conversion is specified by a specialization of a 5720 // conversion function template, the second standard conversion sequence 5721 // shall have exact match rank. 5722 if (Conversion->getPrimaryTemplate() && 5723 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5724 Candidate.Viable = false; 5725 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5726 } 5727 5728 // C++0x [dcl.init.ref]p5: 5729 // In the second case, if the reference is an rvalue reference and 5730 // the second standard conversion sequence of the user-defined 5731 // conversion sequence includes an lvalue-to-rvalue conversion, the 5732 // program is ill-formed. 5733 if (ToType->isRValueReferenceType() && 5734 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5735 Candidate.Viable = false; 5736 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5737 } 5738 break; 5739 5740 case ImplicitConversionSequence::BadConversion: 5741 Candidate.Viable = false; 5742 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5743 break; 5744 5745 default: 5746 llvm_unreachable( 5747 "Can only end up with a standard conversion sequence or failure"); 5748 } 5749} 5750 5751/// \brief Adds a conversion function template specialization 5752/// candidate to the overload set, using template argument deduction 5753/// to deduce the template arguments of the conversion function 5754/// template from the type that we are converting to (C++ 5755/// [temp.deduct.conv]). 5756void 5757Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5758 DeclAccessPair FoundDecl, 5759 CXXRecordDecl *ActingDC, 5760 Expr *From, QualType ToType, 5761 OverloadCandidateSet &CandidateSet) { 5762 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5763 "Only conversion function templates permitted here"); 5764 5765 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5766 return; 5767 5768 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5769 CXXConversionDecl *Specialization = 0; 5770 if (TemplateDeductionResult Result 5771 = DeduceTemplateArguments(FunctionTemplate, ToType, 5772 Specialization, Info)) { 5773 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5774 Candidate.FoundDecl = FoundDecl; 5775 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5776 Candidate.Viable = false; 5777 Candidate.FailureKind = ovl_fail_bad_deduction; 5778 Candidate.IsSurrogate = false; 5779 Candidate.IgnoreObjectArgument = false; 5780 Candidate.ExplicitCallArguments = 1; 5781 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5782 Info); 5783 return; 5784 } 5785 5786 // Add the conversion function template specialization produced by 5787 // template argument deduction as a candidate. 5788 assert(Specialization && "Missing function template specialization?"); 5789 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5790 CandidateSet); 5791} 5792 5793/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5794/// converts the given @c Object to a function pointer via the 5795/// conversion function @c Conversion, and then attempts to call it 5796/// with the given arguments (C++ [over.call.object]p2-4). Proto is 5797/// the type of function that we'll eventually be calling. 5798void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5799 DeclAccessPair FoundDecl, 5800 CXXRecordDecl *ActingContext, 5801 const FunctionProtoType *Proto, 5802 Expr *Object, 5803 llvm::ArrayRef<Expr *> Args, 5804 OverloadCandidateSet& CandidateSet) { 5805 if (!CandidateSet.isNewCandidate(Conversion)) 5806 return; 5807 5808 // Overload resolution is always an unevaluated context. 5809 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5810 5811 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5812 Candidate.FoundDecl = FoundDecl; 5813 Candidate.Function = 0; 5814 Candidate.Surrogate = Conversion; 5815 Candidate.Viable = true; 5816 Candidate.IsSurrogate = true; 5817 Candidate.IgnoreObjectArgument = false; 5818 Candidate.ExplicitCallArguments = Args.size(); 5819 5820 // Determine the implicit conversion sequence for the implicit 5821 // object parameter. 5822 ImplicitConversionSequence ObjectInit 5823 = TryObjectArgumentInitialization(*this, Object->getType(), 5824 Object->Classify(Context), 5825 Conversion, ActingContext); 5826 if (ObjectInit.isBad()) { 5827 Candidate.Viable = false; 5828 Candidate.FailureKind = ovl_fail_bad_conversion; 5829 Candidate.Conversions[0] = ObjectInit; 5830 return; 5831 } 5832 5833 // The first conversion is actually a user-defined conversion whose 5834 // first conversion is ObjectInit's standard conversion (which is 5835 // effectively a reference binding). Record it as such. 5836 Candidate.Conversions[0].setUserDefined(); 5837 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 5838 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 5839 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 5840 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 5841 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 5842 Candidate.Conversions[0].UserDefined.After 5843 = Candidate.Conversions[0].UserDefined.Before; 5844 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 5845 5846 // Find the 5847 unsigned NumArgsInProto = Proto->getNumArgs(); 5848 5849 // (C++ 13.3.2p2): A candidate function having fewer than m 5850 // parameters is viable only if it has an ellipsis in its parameter 5851 // list (8.3.5). 5852 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5853 Candidate.Viable = false; 5854 Candidate.FailureKind = ovl_fail_too_many_arguments; 5855 return; 5856 } 5857 5858 // Function types don't have any default arguments, so just check if 5859 // we have enough arguments. 5860 if (Args.size() < NumArgsInProto) { 5861 // Not enough arguments. 5862 Candidate.Viable = false; 5863 Candidate.FailureKind = ovl_fail_too_few_arguments; 5864 return; 5865 } 5866 5867 // Determine the implicit conversion sequences for each of the 5868 // arguments. 5869 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5870 if (ArgIdx < NumArgsInProto) { 5871 // (C++ 13.3.2p3): for F to be a viable function, there shall 5872 // exist for each argument an implicit conversion sequence 5873 // (13.3.3.1) that converts that argument to the corresponding 5874 // parameter of F. 5875 QualType ParamType = Proto->getArgType(ArgIdx); 5876 Candidate.Conversions[ArgIdx + 1] 5877 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5878 /*SuppressUserConversions=*/false, 5879 /*InOverloadResolution=*/false, 5880 /*AllowObjCWritebackConversion=*/ 5881 getLangOpts().ObjCAutoRefCount); 5882 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5883 Candidate.Viable = false; 5884 Candidate.FailureKind = ovl_fail_bad_conversion; 5885 break; 5886 } 5887 } else { 5888 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5889 // argument for which there is no corresponding parameter is 5890 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5891 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5892 } 5893 } 5894} 5895 5896/// \brief Add overload candidates for overloaded operators that are 5897/// member functions. 5898/// 5899/// Add the overloaded operator candidates that are member functions 5900/// for the operator Op that was used in an operator expression such 5901/// as "x Op y". , Args/NumArgs provides the operator arguments, and 5902/// CandidateSet will store the added overload candidates. (C++ 5903/// [over.match.oper]). 5904void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 5905 SourceLocation OpLoc, 5906 Expr **Args, unsigned NumArgs, 5907 OverloadCandidateSet& CandidateSet, 5908 SourceRange OpRange) { 5909 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 5910 5911 // C++ [over.match.oper]p3: 5912 // For a unary operator @ with an operand of a type whose 5913 // cv-unqualified version is T1, and for a binary operator @ with 5914 // a left operand of a type whose cv-unqualified version is T1 and 5915 // a right operand of a type whose cv-unqualified version is T2, 5916 // three sets of candidate functions, designated member 5917 // candidates, non-member candidates and built-in candidates, are 5918 // constructed as follows: 5919 QualType T1 = Args[0]->getType(); 5920 5921 // -- If T1 is a class type, the set of member candidates is the 5922 // result of the qualified lookup of T1::operator@ 5923 // (13.3.1.1.1); otherwise, the set of member candidates is 5924 // empty. 5925 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 5926 // Complete the type if it can be completed. Otherwise, we're done. 5927 if (RequireCompleteType(OpLoc, T1, 0)) 5928 return; 5929 5930 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 5931 LookupQualifiedName(Operators, T1Rec->getDecl()); 5932 Operators.suppressDiagnostics(); 5933 5934 for (LookupResult::iterator Oper = Operators.begin(), 5935 OperEnd = Operators.end(); 5936 Oper != OperEnd; 5937 ++Oper) 5938 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 5939 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 5940 CandidateSet, 5941 /* SuppressUserConversions = */ false); 5942 } 5943} 5944 5945/// AddBuiltinCandidate - Add a candidate for a built-in 5946/// operator. ResultTy and ParamTys are the result and parameter types 5947/// of the built-in candidate, respectively. Args and NumArgs are the 5948/// arguments being passed to the candidate. IsAssignmentOperator 5949/// should be true when this built-in candidate is an assignment 5950/// operator. NumContextualBoolArguments is the number of arguments 5951/// (at the beginning of the argument list) that will be contextually 5952/// converted to bool. 5953void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 5954 Expr **Args, unsigned NumArgs, 5955 OverloadCandidateSet& CandidateSet, 5956 bool IsAssignmentOperator, 5957 unsigned NumContextualBoolArguments) { 5958 // Overload resolution is always an unevaluated context. 5959 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5960 5961 // Add this candidate 5962 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs); 5963 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 5964 Candidate.Function = 0; 5965 Candidate.IsSurrogate = false; 5966 Candidate.IgnoreObjectArgument = false; 5967 Candidate.BuiltinTypes.ResultTy = ResultTy; 5968 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 5969 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 5970 5971 // Determine the implicit conversion sequences for each of the 5972 // arguments. 5973 Candidate.Viable = true; 5974 Candidate.ExplicitCallArguments = NumArgs; 5975 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5976 // C++ [over.match.oper]p4: 5977 // For the built-in assignment operators, conversions of the 5978 // left operand are restricted as follows: 5979 // -- no temporaries are introduced to hold the left operand, and 5980 // -- no user-defined conversions are applied to the left 5981 // operand to achieve a type match with the left-most 5982 // parameter of a built-in candidate. 5983 // 5984 // We block these conversions by turning off user-defined 5985 // conversions, since that is the only way that initialization of 5986 // a reference to a non-class type can occur from something that 5987 // is not of the same type. 5988 if (ArgIdx < NumContextualBoolArguments) { 5989 assert(ParamTys[ArgIdx] == Context.BoolTy && 5990 "Contextual conversion to bool requires bool type"); 5991 Candidate.Conversions[ArgIdx] 5992 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 5993 } else { 5994 Candidate.Conversions[ArgIdx] 5995 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 5996 ArgIdx == 0 && IsAssignmentOperator, 5997 /*InOverloadResolution=*/false, 5998 /*AllowObjCWritebackConversion=*/ 5999 getLangOpts().ObjCAutoRefCount); 6000 } 6001 if (Candidate.Conversions[ArgIdx].isBad()) { 6002 Candidate.Viable = false; 6003 Candidate.FailureKind = ovl_fail_bad_conversion; 6004 break; 6005 } 6006 } 6007} 6008 6009/// BuiltinCandidateTypeSet - A set of types that will be used for the 6010/// candidate operator functions for built-in operators (C++ 6011/// [over.built]). The types are separated into pointer types and 6012/// enumeration types. 6013class BuiltinCandidateTypeSet { 6014 /// TypeSet - A set of types. 6015 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6016 6017 /// PointerTypes - The set of pointer types that will be used in the 6018 /// built-in candidates. 6019 TypeSet PointerTypes; 6020 6021 /// MemberPointerTypes - The set of member pointer types that will be 6022 /// used in the built-in candidates. 6023 TypeSet MemberPointerTypes; 6024 6025 /// EnumerationTypes - The set of enumeration types that will be 6026 /// used in the built-in candidates. 6027 TypeSet EnumerationTypes; 6028 6029 /// \brief The set of vector types that will be used in the built-in 6030 /// candidates. 6031 TypeSet VectorTypes; 6032 6033 /// \brief A flag indicating non-record types are viable candidates 6034 bool HasNonRecordTypes; 6035 6036 /// \brief A flag indicating whether either arithmetic or enumeration types 6037 /// were present in the candidate set. 6038 bool HasArithmeticOrEnumeralTypes; 6039 6040 /// \brief A flag indicating whether the nullptr type was present in the 6041 /// candidate set. 6042 bool HasNullPtrType; 6043 6044 /// Sema - The semantic analysis instance where we are building the 6045 /// candidate type set. 6046 Sema &SemaRef; 6047 6048 /// Context - The AST context in which we will build the type sets. 6049 ASTContext &Context; 6050 6051 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6052 const Qualifiers &VisibleQuals); 6053 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6054 6055public: 6056 /// iterator - Iterates through the types that are part of the set. 6057 typedef TypeSet::iterator iterator; 6058 6059 BuiltinCandidateTypeSet(Sema &SemaRef) 6060 : HasNonRecordTypes(false), 6061 HasArithmeticOrEnumeralTypes(false), 6062 HasNullPtrType(false), 6063 SemaRef(SemaRef), 6064 Context(SemaRef.Context) { } 6065 6066 void AddTypesConvertedFrom(QualType Ty, 6067 SourceLocation Loc, 6068 bool AllowUserConversions, 6069 bool AllowExplicitConversions, 6070 const Qualifiers &VisibleTypeConversionsQuals); 6071 6072 /// pointer_begin - First pointer type found; 6073 iterator pointer_begin() { return PointerTypes.begin(); } 6074 6075 /// pointer_end - Past the last pointer type found; 6076 iterator pointer_end() { return PointerTypes.end(); } 6077 6078 /// member_pointer_begin - First member pointer type found; 6079 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6080 6081 /// member_pointer_end - Past the last member pointer type found; 6082 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6083 6084 /// enumeration_begin - First enumeration type found; 6085 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6086 6087 /// enumeration_end - Past the last enumeration type found; 6088 iterator enumeration_end() { return EnumerationTypes.end(); } 6089 6090 iterator vector_begin() { return VectorTypes.begin(); } 6091 iterator vector_end() { return VectorTypes.end(); } 6092 6093 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6094 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6095 bool hasNullPtrType() const { return HasNullPtrType; } 6096}; 6097 6098/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6099/// the set of pointer types along with any more-qualified variants of 6100/// that type. For example, if @p Ty is "int const *", this routine 6101/// will add "int const *", "int const volatile *", "int const 6102/// restrict *", and "int const volatile restrict *" to the set of 6103/// pointer types. Returns true if the add of @p Ty itself succeeded, 6104/// false otherwise. 6105/// 6106/// FIXME: what to do about extended qualifiers? 6107bool 6108BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6109 const Qualifiers &VisibleQuals) { 6110 6111 // Insert this type. 6112 if (!PointerTypes.insert(Ty)) 6113 return false; 6114 6115 QualType PointeeTy; 6116 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6117 bool buildObjCPtr = false; 6118 if (!PointerTy) { 6119 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6120 PointeeTy = PTy->getPointeeType(); 6121 buildObjCPtr = true; 6122 } else { 6123 PointeeTy = PointerTy->getPointeeType(); 6124 } 6125 6126 // Don't add qualified variants of arrays. For one, they're not allowed 6127 // (the qualifier would sink to the element type), and for another, the 6128 // only overload situation where it matters is subscript or pointer +- int, 6129 // and those shouldn't have qualifier variants anyway. 6130 if (PointeeTy->isArrayType()) 6131 return true; 6132 6133 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6134 bool hasVolatile = VisibleQuals.hasVolatile(); 6135 bool hasRestrict = VisibleQuals.hasRestrict(); 6136 6137 // Iterate through all strict supersets of BaseCVR. 6138 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6139 if ((CVR | BaseCVR) != CVR) continue; 6140 // Skip over volatile if no volatile found anywhere in the types. 6141 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6142 6143 // Skip over restrict if no restrict found anywhere in the types, or if 6144 // the type cannot be restrict-qualified. 6145 if ((CVR & Qualifiers::Restrict) && 6146 (!hasRestrict || 6147 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6148 continue; 6149 6150 // Build qualified pointee type. 6151 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6152 6153 // Build qualified pointer type. 6154 QualType QPointerTy; 6155 if (!buildObjCPtr) 6156 QPointerTy = Context.getPointerType(QPointeeTy); 6157 else 6158 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6159 6160 // Insert qualified pointer type. 6161 PointerTypes.insert(QPointerTy); 6162 } 6163 6164 return true; 6165} 6166 6167/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6168/// to the set of pointer types along with any more-qualified variants of 6169/// that type. For example, if @p Ty is "int const *", this routine 6170/// will add "int const *", "int const volatile *", "int const 6171/// restrict *", and "int const volatile restrict *" to the set of 6172/// pointer types. Returns true if the add of @p Ty itself succeeded, 6173/// false otherwise. 6174/// 6175/// FIXME: what to do about extended qualifiers? 6176bool 6177BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6178 QualType Ty) { 6179 // Insert this type. 6180 if (!MemberPointerTypes.insert(Ty)) 6181 return false; 6182 6183 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6184 assert(PointerTy && "type was not a member pointer type!"); 6185 6186 QualType PointeeTy = PointerTy->getPointeeType(); 6187 // Don't add qualified variants of arrays. For one, they're not allowed 6188 // (the qualifier would sink to the element type), and for another, the 6189 // only overload situation where it matters is subscript or pointer +- int, 6190 // and those shouldn't have qualifier variants anyway. 6191 if (PointeeTy->isArrayType()) 6192 return true; 6193 const Type *ClassTy = PointerTy->getClass(); 6194 6195 // Iterate through all strict supersets of the pointee type's CVR 6196 // qualifiers. 6197 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6198 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6199 if ((CVR | BaseCVR) != CVR) continue; 6200 6201 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6202 MemberPointerTypes.insert( 6203 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6204 } 6205 6206 return true; 6207} 6208 6209/// AddTypesConvertedFrom - Add each of the types to which the type @p 6210/// Ty can be implicit converted to the given set of @p Types. We're 6211/// primarily interested in pointer types and enumeration types. We also 6212/// take member pointer types, for the conditional operator. 6213/// AllowUserConversions is true if we should look at the conversion 6214/// functions of a class type, and AllowExplicitConversions if we 6215/// should also include the explicit conversion functions of a class 6216/// type. 6217void 6218BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6219 SourceLocation Loc, 6220 bool AllowUserConversions, 6221 bool AllowExplicitConversions, 6222 const Qualifiers &VisibleQuals) { 6223 // Only deal with canonical types. 6224 Ty = Context.getCanonicalType(Ty); 6225 6226 // Look through reference types; they aren't part of the type of an 6227 // expression for the purposes of conversions. 6228 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6229 Ty = RefTy->getPointeeType(); 6230 6231 // If we're dealing with an array type, decay to the pointer. 6232 if (Ty->isArrayType()) 6233 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6234 6235 // Otherwise, we don't care about qualifiers on the type. 6236 Ty = Ty.getLocalUnqualifiedType(); 6237 6238 // Flag if we ever add a non-record type. 6239 const RecordType *TyRec = Ty->getAs<RecordType>(); 6240 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6241 6242 // Flag if we encounter an arithmetic type. 6243 HasArithmeticOrEnumeralTypes = 6244 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6245 6246 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6247 PointerTypes.insert(Ty); 6248 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6249 // Insert our type, and its more-qualified variants, into the set 6250 // of types. 6251 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6252 return; 6253 } else if (Ty->isMemberPointerType()) { 6254 // Member pointers are far easier, since the pointee can't be converted. 6255 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6256 return; 6257 } else if (Ty->isEnumeralType()) { 6258 HasArithmeticOrEnumeralTypes = true; 6259 EnumerationTypes.insert(Ty); 6260 } else if (Ty->isVectorType()) { 6261 // We treat vector types as arithmetic types in many contexts as an 6262 // extension. 6263 HasArithmeticOrEnumeralTypes = true; 6264 VectorTypes.insert(Ty); 6265 } else if (Ty->isNullPtrType()) { 6266 HasNullPtrType = true; 6267 } else if (AllowUserConversions && TyRec) { 6268 // No conversion functions in incomplete types. 6269 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6270 return; 6271 6272 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6273 const UnresolvedSetImpl *Conversions 6274 = ClassDecl->getVisibleConversionFunctions(); 6275 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6276 E = Conversions->end(); I != E; ++I) { 6277 NamedDecl *D = I.getDecl(); 6278 if (isa<UsingShadowDecl>(D)) 6279 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6280 6281 // Skip conversion function templates; they don't tell us anything 6282 // about which builtin types we can convert to. 6283 if (isa<FunctionTemplateDecl>(D)) 6284 continue; 6285 6286 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6287 if (AllowExplicitConversions || !Conv->isExplicit()) { 6288 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6289 VisibleQuals); 6290 } 6291 } 6292 } 6293} 6294 6295/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6296/// the volatile- and non-volatile-qualified assignment operators for the 6297/// given type to the candidate set. 6298static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6299 QualType T, 6300 Expr **Args, 6301 unsigned NumArgs, 6302 OverloadCandidateSet &CandidateSet) { 6303 QualType ParamTypes[2]; 6304 6305 // T& operator=(T&, T) 6306 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6307 ParamTypes[1] = T; 6308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6309 /*IsAssignmentOperator=*/true); 6310 6311 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6312 // volatile T& operator=(volatile T&, T) 6313 ParamTypes[0] 6314 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6315 ParamTypes[1] = T; 6316 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6317 /*IsAssignmentOperator=*/true); 6318 } 6319} 6320 6321/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6322/// if any, found in visible type conversion functions found in ArgExpr's type. 6323static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6324 Qualifiers VRQuals; 6325 const RecordType *TyRec; 6326 if (const MemberPointerType *RHSMPType = 6327 ArgExpr->getType()->getAs<MemberPointerType>()) 6328 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6329 else 6330 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6331 if (!TyRec) { 6332 // Just to be safe, assume the worst case. 6333 VRQuals.addVolatile(); 6334 VRQuals.addRestrict(); 6335 return VRQuals; 6336 } 6337 6338 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6339 if (!ClassDecl->hasDefinition()) 6340 return VRQuals; 6341 6342 const UnresolvedSetImpl *Conversions = 6343 ClassDecl->getVisibleConversionFunctions(); 6344 6345 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6346 E = Conversions->end(); I != E; ++I) { 6347 NamedDecl *D = I.getDecl(); 6348 if (isa<UsingShadowDecl>(D)) 6349 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6350 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6351 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6352 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6353 CanTy = ResTypeRef->getPointeeType(); 6354 // Need to go down the pointer/mempointer chain and add qualifiers 6355 // as see them. 6356 bool done = false; 6357 while (!done) { 6358 if (CanTy.isRestrictQualified()) 6359 VRQuals.addRestrict(); 6360 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6361 CanTy = ResTypePtr->getPointeeType(); 6362 else if (const MemberPointerType *ResTypeMPtr = 6363 CanTy->getAs<MemberPointerType>()) 6364 CanTy = ResTypeMPtr->getPointeeType(); 6365 else 6366 done = true; 6367 if (CanTy.isVolatileQualified()) 6368 VRQuals.addVolatile(); 6369 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6370 return VRQuals; 6371 } 6372 } 6373 } 6374 return VRQuals; 6375} 6376 6377namespace { 6378 6379/// \brief Helper class to manage the addition of builtin operator overload 6380/// candidates. It provides shared state and utility methods used throughout 6381/// the process, as well as a helper method to add each group of builtin 6382/// operator overloads from the standard to a candidate set. 6383class BuiltinOperatorOverloadBuilder { 6384 // Common instance state available to all overload candidate addition methods. 6385 Sema &S; 6386 Expr **Args; 6387 unsigned NumArgs; 6388 Qualifiers VisibleTypeConversionsQuals; 6389 bool HasArithmeticOrEnumeralCandidateType; 6390 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6391 OverloadCandidateSet &CandidateSet; 6392 6393 // Define some constants used to index and iterate over the arithemetic types 6394 // provided via the getArithmeticType() method below. 6395 // The "promoted arithmetic types" are the arithmetic 6396 // types are that preserved by promotion (C++ [over.built]p2). 6397 static const unsigned FirstIntegralType = 3; 6398 static const unsigned LastIntegralType = 20; 6399 static const unsigned FirstPromotedIntegralType = 3, 6400 LastPromotedIntegralType = 11; 6401 static const unsigned FirstPromotedArithmeticType = 0, 6402 LastPromotedArithmeticType = 11; 6403 static const unsigned NumArithmeticTypes = 20; 6404 6405 /// \brief Get the canonical type for a given arithmetic type index. 6406 CanQualType getArithmeticType(unsigned index) { 6407 assert(index < NumArithmeticTypes); 6408 static CanQualType ASTContext::* const 6409 ArithmeticTypes[NumArithmeticTypes] = { 6410 // Start of promoted types. 6411 &ASTContext::FloatTy, 6412 &ASTContext::DoubleTy, 6413 &ASTContext::LongDoubleTy, 6414 6415 // Start of integral types. 6416 &ASTContext::IntTy, 6417 &ASTContext::LongTy, 6418 &ASTContext::LongLongTy, 6419 &ASTContext::Int128Ty, 6420 &ASTContext::UnsignedIntTy, 6421 &ASTContext::UnsignedLongTy, 6422 &ASTContext::UnsignedLongLongTy, 6423 &ASTContext::UnsignedInt128Ty, 6424 // End of promoted types. 6425 6426 &ASTContext::BoolTy, 6427 &ASTContext::CharTy, 6428 &ASTContext::WCharTy, 6429 &ASTContext::Char16Ty, 6430 &ASTContext::Char32Ty, 6431 &ASTContext::SignedCharTy, 6432 &ASTContext::ShortTy, 6433 &ASTContext::UnsignedCharTy, 6434 &ASTContext::UnsignedShortTy, 6435 // End of integral types. 6436 // FIXME: What about complex? What about half? 6437 }; 6438 return S.Context.*ArithmeticTypes[index]; 6439 } 6440 6441 /// \brief Gets the canonical type resulting from the usual arithemetic 6442 /// converions for the given arithmetic types. 6443 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6444 // Accelerator table for performing the usual arithmetic conversions. 6445 // The rules are basically: 6446 // - if either is floating-point, use the wider floating-point 6447 // - if same signedness, use the higher rank 6448 // - if same size, use unsigned of the higher rank 6449 // - use the larger type 6450 // These rules, together with the axiom that higher ranks are 6451 // never smaller, are sufficient to precompute all of these results 6452 // *except* when dealing with signed types of higher rank. 6453 // (we could precompute SLL x UI for all known platforms, but it's 6454 // better not to make any assumptions). 6455 // We assume that int128 has a higher rank than long long on all platforms. 6456 enum PromotedType { 6457 Dep=-1, 6458 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6459 }; 6460 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6461 [LastPromotedArithmeticType] = { 6462/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6463/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6464/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6465/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6466/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6467/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6468/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6469/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6470/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6471/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6472/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6473 }; 6474 6475 assert(L < LastPromotedArithmeticType); 6476 assert(R < LastPromotedArithmeticType); 6477 int Idx = ConversionsTable[L][R]; 6478 6479 // Fast path: the table gives us a concrete answer. 6480 if (Idx != Dep) return getArithmeticType(Idx); 6481 6482 // Slow path: we need to compare widths. 6483 // An invariant is that the signed type has higher rank. 6484 CanQualType LT = getArithmeticType(L), 6485 RT = getArithmeticType(R); 6486 unsigned LW = S.Context.getIntWidth(LT), 6487 RW = S.Context.getIntWidth(RT); 6488 6489 // If they're different widths, use the signed type. 6490 if (LW > RW) return LT; 6491 else if (LW < RW) return RT; 6492 6493 // Otherwise, use the unsigned type of the signed type's rank. 6494 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6495 assert(L == SLL || R == SLL); 6496 return S.Context.UnsignedLongLongTy; 6497 } 6498 6499 /// \brief Helper method to factor out the common pattern of adding overloads 6500 /// for '++' and '--' builtin operators. 6501 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6502 bool HasVolatile, 6503 bool HasRestrict) { 6504 QualType ParamTypes[2] = { 6505 S.Context.getLValueReferenceType(CandidateTy), 6506 S.Context.IntTy 6507 }; 6508 6509 // Non-volatile version. 6510 if (NumArgs == 1) 6511 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6512 else 6513 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6514 6515 // Use a heuristic to reduce number of builtin candidates in the set: 6516 // add volatile version only if there are conversions to a volatile type. 6517 if (HasVolatile) { 6518 ParamTypes[0] = 6519 S.Context.getLValueReferenceType( 6520 S.Context.getVolatileType(CandidateTy)); 6521 if (NumArgs == 1) 6522 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6523 else 6524 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6525 } 6526 6527 // Add restrict version only if there are conversions to a restrict type 6528 // and our candidate type is a non-restrict-qualified pointer. 6529 if (HasRestrict && CandidateTy->isAnyPointerType() && 6530 !CandidateTy.isRestrictQualified()) { 6531 ParamTypes[0] 6532 = S.Context.getLValueReferenceType( 6533 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6534 if (NumArgs == 1) 6535 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6536 else 6537 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6538 6539 if (HasVolatile) { 6540 ParamTypes[0] 6541 = S.Context.getLValueReferenceType( 6542 S.Context.getCVRQualifiedType(CandidateTy, 6543 (Qualifiers::Volatile | 6544 Qualifiers::Restrict))); 6545 if (NumArgs == 1) 6546 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, 6547 CandidateSet); 6548 else 6549 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6550 } 6551 } 6552 6553 } 6554 6555public: 6556 BuiltinOperatorOverloadBuilder( 6557 Sema &S, Expr **Args, unsigned NumArgs, 6558 Qualifiers VisibleTypeConversionsQuals, 6559 bool HasArithmeticOrEnumeralCandidateType, 6560 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6561 OverloadCandidateSet &CandidateSet) 6562 : S(S), Args(Args), NumArgs(NumArgs), 6563 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6564 HasArithmeticOrEnumeralCandidateType( 6565 HasArithmeticOrEnumeralCandidateType), 6566 CandidateTypes(CandidateTypes), 6567 CandidateSet(CandidateSet) { 6568 // Validate some of our static helper constants in debug builds. 6569 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6570 "Invalid first promoted integral type"); 6571 assert(getArithmeticType(LastPromotedIntegralType - 1) 6572 == S.Context.UnsignedInt128Ty && 6573 "Invalid last promoted integral type"); 6574 assert(getArithmeticType(FirstPromotedArithmeticType) 6575 == S.Context.FloatTy && 6576 "Invalid first promoted arithmetic type"); 6577 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6578 == S.Context.UnsignedInt128Ty && 6579 "Invalid last promoted arithmetic type"); 6580 } 6581 6582 // C++ [over.built]p3: 6583 // 6584 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6585 // is either volatile or empty, there exist candidate operator 6586 // functions of the form 6587 // 6588 // VQ T& operator++(VQ T&); 6589 // T operator++(VQ T&, int); 6590 // 6591 // C++ [over.built]p4: 6592 // 6593 // For every pair (T, VQ), where T is an arithmetic type other 6594 // than bool, and VQ is either volatile or empty, there exist 6595 // candidate operator functions of the form 6596 // 6597 // VQ T& operator--(VQ T&); 6598 // T operator--(VQ T&, int); 6599 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6600 if (!HasArithmeticOrEnumeralCandidateType) 6601 return; 6602 6603 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6604 Arith < NumArithmeticTypes; ++Arith) { 6605 addPlusPlusMinusMinusStyleOverloads( 6606 getArithmeticType(Arith), 6607 VisibleTypeConversionsQuals.hasVolatile(), 6608 VisibleTypeConversionsQuals.hasRestrict()); 6609 } 6610 } 6611 6612 // C++ [over.built]p5: 6613 // 6614 // For every pair (T, VQ), where T is a cv-qualified or 6615 // cv-unqualified object type, and VQ is either volatile or 6616 // empty, there exist candidate operator functions of the form 6617 // 6618 // T*VQ& operator++(T*VQ&); 6619 // T*VQ& operator--(T*VQ&); 6620 // T* operator++(T*VQ&, int); 6621 // T* operator--(T*VQ&, int); 6622 void addPlusPlusMinusMinusPointerOverloads() { 6623 for (BuiltinCandidateTypeSet::iterator 6624 Ptr = CandidateTypes[0].pointer_begin(), 6625 PtrEnd = CandidateTypes[0].pointer_end(); 6626 Ptr != PtrEnd; ++Ptr) { 6627 // Skip pointer types that aren't pointers to object types. 6628 if (!(*Ptr)->getPointeeType()->isObjectType()) 6629 continue; 6630 6631 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6632 (!(*Ptr).isVolatileQualified() && 6633 VisibleTypeConversionsQuals.hasVolatile()), 6634 (!(*Ptr).isRestrictQualified() && 6635 VisibleTypeConversionsQuals.hasRestrict())); 6636 } 6637 } 6638 6639 // C++ [over.built]p6: 6640 // For every cv-qualified or cv-unqualified object type T, there 6641 // exist candidate operator functions of the form 6642 // 6643 // T& operator*(T*); 6644 // 6645 // C++ [over.built]p7: 6646 // For every function type T that does not have cv-qualifiers or a 6647 // ref-qualifier, there exist candidate operator functions of the form 6648 // T& operator*(T*); 6649 void addUnaryStarPointerOverloads() { 6650 for (BuiltinCandidateTypeSet::iterator 6651 Ptr = CandidateTypes[0].pointer_begin(), 6652 PtrEnd = CandidateTypes[0].pointer_end(); 6653 Ptr != PtrEnd; ++Ptr) { 6654 QualType ParamTy = *Ptr; 6655 QualType PointeeTy = ParamTy->getPointeeType(); 6656 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6657 continue; 6658 6659 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6660 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6661 continue; 6662 6663 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6664 &ParamTy, Args, 1, CandidateSet); 6665 } 6666 } 6667 6668 // C++ [over.built]p9: 6669 // For every promoted arithmetic type T, there exist candidate 6670 // operator functions of the form 6671 // 6672 // T operator+(T); 6673 // T operator-(T); 6674 void addUnaryPlusOrMinusArithmeticOverloads() { 6675 if (!HasArithmeticOrEnumeralCandidateType) 6676 return; 6677 6678 for (unsigned Arith = FirstPromotedArithmeticType; 6679 Arith < LastPromotedArithmeticType; ++Arith) { 6680 QualType ArithTy = getArithmeticType(Arith); 6681 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 6682 } 6683 6684 // Extension: We also add these operators for vector types. 6685 for (BuiltinCandidateTypeSet::iterator 6686 Vec = CandidateTypes[0].vector_begin(), 6687 VecEnd = CandidateTypes[0].vector_end(); 6688 Vec != VecEnd; ++Vec) { 6689 QualType VecTy = *Vec; 6690 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6691 } 6692 } 6693 6694 // C++ [over.built]p8: 6695 // For every type T, there exist candidate operator functions of 6696 // the form 6697 // 6698 // T* operator+(T*); 6699 void addUnaryPlusPointerOverloads() { 6700 for (BuiltinCandidateTypeSet::iterator 6701 Ptr = CandidateTypes[0].pointer_begin(), 6702 PtrEnd = CandidateTypes[0].pointer_end(); 6703 Ptr != PtrEnd; ++Ptr) { 6704 QualType ParamTy = *Ptr; 6705 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 6706 } 6707 } 6708 6709 // C++ [over.built]p10: 6710 // For every promoted integral type T, there exist candidate 6711 // operator functions of the form 6712 // 6713 // T operator~(T); 6714 void addUnaryTildePromotedIntegralOverloads() { 6715 if (!HasArithmeticOrEnumeralCandidateType) 6716 return; 6717 6718 for (unsigned Int = FirstPromotedIntegralType; 6719 Int < LastPromotedIntegralType; ++Int) { 6720 QualType IntTy = getArithmeticType(Int); 6721 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 6722 } 6723 6724 // Extension: We also add this operator for vector types. 6725 for (BuiltinCandidateTypeSet::iterator 6726 Vec = CandidateTypes[0].vector_begin(), 6727 VecEnd = CandidateTypes[0].vector_end(); 6728 Vec != VecEnd; ++Vec) { 6729 QualType VecTy = *Vec; 6730 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6731 } 6732 } 6733 6734 // C++ [over.match.oper]p16: 6735 // For every pointer to member type T, there exist candidate operator 6736 // functions of the form 6737 // 6738 // bool operator==(T,T); 6739 // bool operator!=(T,T); 6740 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6741 /// Set of (canonical) types that we've already handled. 6742 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6743 6744 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6745 for (BuiltinCandidateTypeSet::iterator 6746 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6747 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6748 MemPtr != MemPtrEnd; 6749 ++MemPtr) { 6750 // Don't add the same builtin candidate twice. 6751 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6752 continue; 6753 6754 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6755 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6756 CandidateSet); 6757 } 6758 } 6759 } 6760 6761 // C++ [over.built]p15: 6762 // 6763 // For every T, where T is an enumeration type, a pointer type, or 6764 // std::nullptr_t, there exist candidate operator functions of the form 6765 // 6766 // bool operator<(T, T); 6767 // bool operator>(T, T); 6768 // bool operator<=(T, T); 6769 // bool operator>=(T, T); 6770 // bool operator==(T, T); 6771 // bool operator!=(T, T); 6772 void addRelationalPointerOrEnumeralOverloads() { 6773 // C++ [over.built]p1: 6774 // If there is a user-written candidate with the same name and parameter 6775 // types as a built-in candidate operator function, the built-in operator 6776 // function is hidden and is not included in the set of candidate 6777 // functions. 6778 // 6779 // The text is actually in a note, but if we don't implement it then we end 6780 // up with ambiguities when the user provides an overloaded operator for 6781 // an enumeration type. Note that only enumeration types have this problem, 6782 // so we track which enumeration types we've seen operators for. Also, the 6783 // only other overloaded operator with enumeration argumenst, operator=, 6784 // cannot be overloaded for enumeration types, so this is the only place 6785 // where we must suppress candidates like this. 6786 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6787 UserDefinedBinaryOperators; 6788 6789 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6790 if (CandidateTypes[ArgIdx].enumeration_begin() != 6791 CandidateTypes[ArgIdx].enumeration_end()) { 6792 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6793 CEnd = CandidateSet.end(); 6794 C != CEnd; ++C) { 6795 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 6796 continue; 6797 6798 QualType FirstParamType = 6799 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 6800 QualType SecondParamType = 6801 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 6802 6803 // Skip if either parameter isn't of enumeral type. 6804 if (!FirstParamType->isEnumeralType() || 6805 !SecondParamType->isEnumeralType()) 6806 continue; 6807 6808 // Add this operator to the set of known user-defined operators. 6809 UserDefinedBinaryOperators.insert( 6810 std::make_pair(S.Context.getCanonicalType(FirstParamType), 6811 S.Context.getCanonicalType(SecondParamType))); 6812 } 6813 } 6814 } 6815 6816 /// Set of (canonical) types that we've already handled. 6817 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6818 6819 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6820 for (BuiltinCandidateTypeSet::iterator 6821 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6822 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6823 Ptr != PtrEnd; ++Ptr) { 6824 // Don't add the same builtin candidate twice. 6825 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6826 continue; 6827 6828 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6829 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6830 CandidateSet); 6831 } 6832 for (BuiltinCandidateTypeSet::iterator 6833 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6834 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6835 Enum != EnumEnd; ++Enum) { 6836 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 6837 6838 // Don't add the same builtin candidate twice, or if a user defined 6839 // candidate exists. 6840 if (!AddedTypes.insert(CanonType) || 6841 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 6842 CanonType))) 6843 continue; 6844 6845 QualType ParamTypes[2] = { *Enum, *Enum }; 6846 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6847 CandidateSet); 6848 } 6849 6850 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 6851 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 6852 if (AddedTypes.insert(NullPtrTy) && 6853 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 6854 NullPtrTy))) { 6855 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 6856 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6857 CandidateSet); 6858 } 6859 } 6860 } 6861 } 6862 6863 // C++ [over.built]p13: 6864 // 6865 // For every cv-qualified or cv-unqualified object type T 6866 // there exist candidate operator functions of the form 6867 // 6868 // T* operator+(T*, ptrdiff_t); 6869 // T& operator[](T*, ptrdiff_t); [BELOW] 6870 // T* operator-(T*, ptrdiff_t); 6871 // T* operator+(ptrdiff_t, T*); 6872 // T& operator[](ptrdiff_t, T*); [BELOW] 6873 // 6874 // C++ [over.built]p14: 6875 // 6876 // For every T, where T is a pointer to object type, there 6877 // exist candidate operator functions of the form 6878 // 6879 // ptrdiff_t operator-(T, T); 6880 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 6881 /// Set of (canonical) types that we've already handled. 6882 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6883 6884 for (int Arg = 0; Arg < 2; ++Arg) { 6885 QualType AsymetricParamTypes[2] = { 6886 S.Context.getPointerDiffType(), 6887 S.Context.getPointerDiffType(), 6888 }; 6889 for (BuiltinCandidateTypeSet::iterator 6890 Ptr = CandidateTypes[Arg].pointer_begin(), 6891 PtrEnd = CandidateTypes[Arg].pointer_end(); 6892 Ptr != PtrEnd; ++Ptr) { 6893 QualType PointeeTy = (*Ptr)->getPointeeType(); 6894 if (!PointeeTy->isObjectType()) 6895 continue; 6896 6897 AsymetricParamTypes[Arg] = *Ptr; 6898 if (Arg == 0 || Op == OO_Plus) { 6899 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 6900 // T* operator+(ptrdiff_t, T*); 6901 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 6902 CandidateSet); 6903 } 6904 if (Op == OO_Minus) { 6905 // ptrdiff_t operator-(T, T); 6906 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6907 continue; 6908 6909 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6910 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 6911 Args, 2, CandidateSet); 6912 } 6913 } 6914 } 6915 } 6916 6917 // C++ [over.built]p12: 6918 // 6919 // For every pair of promoted arithmetic types L and R, there 6920 // exist candidate operator functions of the form 6921 // 6922 // LR operator*(L, R); 6923 // LR operator/(L, R); 6924 // LR operator+(L, R); 6925 // LR operator-(L, R); 6926 // bool operator<(L, R); 6927 // bool operator>(L, R); 6928 // bool operator<=(L, R); 6929 // bool operator>=(L, R); 6930 // bool operator==(L, R); 6931 // bool operator!=(L, R); 6932 // 6933 // where LR is the result of the usual arithmetic conversions 6934 // between types L and R. 6935 // 6936 // C++ [over.built]p24: 6937 // 6938 // For every pair of promoted arithmetic types L and R, there exist 6939 // candidate operator functions of the form 6940 // 6941 // LR operator?(bool, L, R); 6942 // 6943 // where LR is the result of the usual arithmetic conversions 6944 // between types L and R. 6945 // Our candidates ignore the first parameter. 6946 void addGenericBinaryArithmeticOverloads(bool isComparison) { 6947 if (!HasArithmeticOrEnumeralCandidateType) 6948 return; 6949 6950 for (unsigned Left = FirstPromotedArithmeticType; 6951 Left < LastPromotedArithmeticType; ++Left) { 6952 for (unsigned Right = FirstPromotedArithmeticType; 6953 Right < LastPromotedArithmeticType; ++Right) { 6954 QualType LandR[2] = { getArithmeticType(Left), 6955 getArithmeticType(Right) }; 6956 QualType Result = 6957 isComparison ? S.Context.BoolTy 6958 : getUsualArithmeticConversions(Left, Right); 6959 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 6960 } 6961 } 6962 6963 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 6964 // conditional operator for vector types. 6965 for (BuiltinCandidateTypeSet::iterator 6966 Vec1 = CandidateTypes[0].vector_begin(), 6967 Vec1End = CandidateTypes[0].vector_end(); 6968 Vec1 != Vec1End; ++Vec1) { 6969 for (BuiltinCandidateTypeSet::iterator 6970 Vec2 = CandidateTypes[1].vector_begin(), 6971 Vec2End = CandidateTypes[1].vector_end(); 6972 Vec2 != Vec2End; ++Vec2) { 6973 QualType LandR[2] = { *Vec1, *Vec2 }; 6974 QualType Result = S.Context.BoolTy; 6975 if (!isComparison) { 6976 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 6977 Result = *Vec1; 6978 else 6979 Result = *Vec2; 6980 } 6981 6982 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 6983 } 6984 } 6985 } 6986 6987 // C++ [over.built]p17: 6988 // 6989 // For every pair of promoted integral types L and R, there 6990 // exist candidate operator functions of the form 6991 // 6992 // LR operator%(L, R); 6993 // LR operator&(L, R); 6994 // LR operator^(L, R); 6995 // LR operator|(L, R); 6996 // L operator<<(L, R); 6997 // L operator>>(L, R); 6998 // 6999 // where LR is the result of the usual arithmetic conversions 7000 // between types L and R. 7001 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7002 if (!HasArithmeticOrEnumeralCandidateType) 7003 return; 7004 7005 for (unsigned Left = FirstPromotedIntegralType; 7006 Left < LastPromotedIntegralType; ++Left) { 7007 for (unsigned Right = FirstPromotedIntegralType; 7008 Right < LastPromotedIntegralType; ++Right) { 7009 QualType LandR[2] = { getArithmeticType(Left), 7010 getArithmeticType(Right) }; 7011 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7012 ? LandR[0] 7013 : getUsualArithmeticConversions(Left, Right); 7014 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7015 } 7016 } 7017 } 7018 7019 // C++ [over.built]p20: 7020 // 7021 // For every pair (T, VQ), where T is an enumeration or 7022 // pointer to member type and VQ is either volatile or 7023 // empty, there exist candidate operator functions of the form 7024 // 7025 // VQ T& operator=(VQ T&, T); 7026 void addAssignmentMemberPointerOrEnumeralOverloads() { 7027 /// Set of (canonical) types that we've already handled. 7028 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7029 7030 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7031 for (BuiltinCandidateTypeSet::iterator 7032 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7033 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7034 Enum != EnumEnd; ++Enum) { 7035 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7036 continue; 7037 7038 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 7039 CandidateSet); 7040 } 7041 7042 for (BuiltinCandidateTypeSet::iterator 7043 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7044 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7045 MemPtr != MemPtrEnd; ++MemPtr) { 7046 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7047 continue; 7048 7049 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 7050 CandidateSet); 7051 } 7052 } 7053 } 7054 7055 // C++ [over.built]p19: 7056 // 7057 // For every pair (T, VQ), where T is any type and VQ is either 7058 // volatile or empty, there exist candidate operator functions 7059 // of the form 7060 // 7061 // T*VQ& operator=(T*VQ&, T*); 7062 // 7063 // C++ [over.built]p21: 7064 // 7065 // For every pair (T, VQ), where T is a cv-qualified or 7066 // cv-unqualified object type and VQ is either volatile or 7067 // empty, there exist candidate operator functions of the form 7068 // 7069 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7070 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7071 void addAssignmentPointerOverloads(bool isEqualOp) { 7072 /// Set of (canonical) types that we've already handled. 7073 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7074 7075 for (BuiltinCandidateTypeSet::iterator 7076 Ptr = CandidateTypes[0].pointer_begin(), 7077 PtrEnd = CandidateTypes[0].pointer_end(); 7078 Ptr != PtrEnd; ++Ptr) { 7079 // If this is operator=, keep track of the builtin candidates we added. 7080 if (isEqualOp) 7081 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7082 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7083 continue; 7084 7085 // non-volatile version 7086 QualType ParamTypes[2] = { 7087 S.Context.getLValueReferenceType(*Ptr), 7088 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7089 }; 7090 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7091 /*IsAssigmentOperator=*/ isEqualOp); 7092 7093 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7094 VisibleTypeConversionsQuals.hasVolatile(); 7095 if (NeedVolatile) { 7096 // volatile version 7097 ParamTypes[0] = 7098 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7099 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7100 /*IsAssigmentOperator=*/isEqualOp); 7101 } 7102 7103 if (!(*Ptr).isRestrictQualified() && 7104 VisibleTypeConversionsQuals.hasRestrict()) { 7105 // restrict version 7106 ParamTypes[0] 7107 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7108 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7109 /*IsAssigmentOperator=*/isEqualOp); 7110 7111 if (NeedVolatile) { 7112 // volatile restrict version 7113 ParamTypes[0] 7114 = S.Context.getLValueReferenceType( 7115 S.Context.getCVRQualifiedType(*Ptr, 7116 (Qualifiers::Volatile | 7117 Qualifiers::Restrict))); 7118 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7119 CandidateSet, 7120 /*IsAssigmentOperator=*/isEqualOp); 7121 } 7122 } 7123 } 7124 7125 if (isEqualOp) { 7126 for (BuiltinCandidateTypeSet::iterator 7127 Ptr = CandidateTypes[1].pointer_begin(), 7128 PtrEnd = CandidateTypes[1].pointer_end(); 7129 Ptr != PtrEnd; ++Ptr) { 7130 // Make sure we don't add the same candidate twice. 7131 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7132 continue; 7133 7134 QualType ParamTypes[2] = { 7135 S.Context.getLValueReferenceType(*Ptr), 7136 *Ptr, 7137 }; 7138 7139 // non-volatile version 7140 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7141 /*IsAssigmentOperator=*/true); 7142 7143 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7144 VisibleTypeConversionsQuals.hasVolatile(); 7145 if (NeedVolatile) { 7146 // volatile version 7147 ParamTypes[0] = 7148 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7149 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7150 CandidateSet, /*IsAssigmentOperator=*/true); 7151 } 7152 7153 if (!(*Ptr).isRestrictQualified() && 7154 VisibleTypeConversionsQuals.hasRestrict()) { 7155 // restrict version 7156 ParamTypes[0] 7157 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7158 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7159 CandidateSet, /*IsAssigmentOperator=*/true); 7160 7161 if (NeedVolatile) { 7162 // volatile restrict version 7163 ParamTypes[0] 7164 = S.Context.getLValueReferenceType( 7165 S.Context.getCVRQualifiedType(*Ptr, 7166 (Qualifiers::Volatile | 7167 Qualifiers::Restrict))); 7168 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7169 CandidateSet, /*IsAssigmentOperator=*/true); 7170 7171 } 7172 } 7173 } 7174 } 7175 } 7176 7177 // C++ [over.built]p18: 7178 // 7179 // For every triple (L, VQ, R), where L is an arithmetic type, 7180 // VQ is either volatile or empty, and R is a promoted 7181 // arithmetic type, there exist candidate operator functions of 7182 // the form 7183 // 7184 // VQ L& operator=(VQ L&, R); 7185 // VQ L& operator*=(VQ L&, R); 7186 // VQ L& operator/=(VQ L&, R); 7187 // VQ L& operator+=(VQ L&, R); 7188 // VQ L& operator-=(VQ L&, R); 7189 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7190 if (!HasArithmeticOrEnumeralCandidateType) 7191 return; 7192 7193 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7194 for (unsigned Right = FirstPromotedArithmeticType; 7195 Right < LastPromotedArithmeticType; ++Right) { 7196 QualType ParamTypes[2]; 7197 ParamTypes[1] = getArithmeticType(Right); 7198 7199 // Add this built-in operator as a candidate (VQ is empty). 7200 ParamTypes[0] = 7201 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7202 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7203 /*IsAssigmentOperator=*/isEqualOp); 7204 7205 // Add this built-in operator as a candidate (VQ is 'volatile'). 7206 if (VisibleTypeConversionsQuals.hasVolatile()) { 7207 ParamTypes[0] = 7208 S.Context.getVolatileType(getArithmeticType(Left)); 7209 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7210 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7211 CandidateSet, 7212 /*IsAssigmentOperator=*/isEqualOp); 7213 } 7214 } 7215 } 7216 7217 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7218 for (BuiltinCandidateTypeSet::iterator 7219 Vec1 = CandidateTypes[0].vector_begin(), 7220 Vec1End = CandidateTypes[0].vector_end(); 7221 Vec1 != Vec1End; ++Vec1) { 7222 for (BuiltinCandidateTypeSet::iterator 7223 Vec2 = CandidateTypes[1].vector_begin(), 7224 Vec2End = CandidateTypes[1].vector_end(); 7225 Vec2 != Vec2End; ++Vec2) { 7226 QualType ParamTypes[2]; 7227 ParamTypes[1] = *Vec2; 7228 // Add this built-in operator as a candidate (VQ is empty). 7229 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7230 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7231 /*IsAssigmentOperator=*/isEqualOp); 7232 7233 // Add this built-in operator as a candidate (VQ is 'volatile'). 7234 if (VisibleTypeConversionsQuals.hasVolatile()) { 7235 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7236 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7237 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7238 CandidateSet, 7239 /*IsAssigmentOperator=*/isEqualOp); 7240 } 7241 } 7242 } 7243 } 7244 7245 // C++ [over.built]p22: 7246 // 7247 // For every triple (L, VQ, R), where L is an integral type, VQ 7248 // is either volatile or empty, and R is a promoted integral 7249 // type, there exist candidate operator functions of the form 7250 // 7251 // VQ L& operator%=(VQ L&, R); 7252 // VQ L& operator<<=(VQ L&, R); 7253 // VQ L& operator>>=(VQ L&, R); 7254 // VQ L& operator&=(VQ L&, R); 7255 // VQ L& operator^=(VQ L&, R); 7256 // VQ L& operator|=(VQ L&, R); 7257 void addAssignmentIntegralOverloads() { 7258 if (!HasArithmeticOrEnumeralCandidateType) 7259 return; 7260 7261 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7262 for (unsigned Right = FirstPromotedIntegralType; 7263 Right < LastPromotedIntegralType; ++Right) { 7264 QualType ParamTypes[2]; 7265 ParamTypes[1] = getArithmeticType(Right); 7266 7267 // Add this built-in operator as a candidate (VQ is empty). 7268 ParamTypes[0] = 7269 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7270 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 7271 if (VisibleTypeConversionsQuals.hasVolatile()) { 7272 // Add this built-in operator as a candidate (VQ is 'volatile'). 7273 ParamTypes[0] = getArithmeticType(Left); 7274 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7275 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7276 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7277 CandidateSet); 7278 } 7279 } 7280 } 7281 } 7282 7283 // C++ [over.operator]p23: 7284 // 7285 // There also exist candidate operator functions of the form 7286 // 7287 // bool operator!(bool); 7288 // bool operator&&(bool, bool); 7289 // bool operator||(bool, bool); 7290 void addExclaimOverload() { 7291 QualType ParamTy = S.Context.BoolTy; 7292 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 7293 /*IsAssignmentOperator=*/false, 7294 /*NumContextualBoolArguments=*/1); 7295 } 7296 void addAmpAmpOrPipePipeOverload() { 7297 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7298 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 7299 /*IsAssignmentOperator=*/false, 7300 /*NumContextualBoolArguments=*/2); 7301 } 7302 7303 // C++ [over.built]p13: 7304 // 7305 // For every cv-qualified or cv-unqualified object type T there 7306 // exist candidate operator functions of the form 7307 // 7308 // T* operator+(T*, ptrdiff_t); [ABOVE] 7309 // T& operator[](T*, ptrdiff_t); 7310 // T* operator-(T*, ptrdiff_t); [ABOVE] 7311 // T* operator+(ptrdiff_t, T*); [ABOVE] 7312 // T& operator[](ptrdiff_t, T*); 7313 void addSubscriptOverloads() { 7314 for (BuiltinCandidateTypeSet::iterator 7315 Ptr = CandidateTypes[0].pointer_begin(), 7316 PtrEnd = CandidateTypes[0].pointer_end(); 7317 Ptr != PtrEnd; ++Ptr) { 7318 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7319 QualType PointeeType = (*Ptr)->getPointeeType(); 7320 if (!PointeeType->isObjectType()) 7321 continue; 7322 7323 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7324 7325 // T& operator[](T*, ptrdiff_t) 7326 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7327 } 7328 7329 for (BuiltinCandidateTypeSet::iterator 7330 Ptr = CandidateTypes[1].pointer_begin(), 7331 PtrEnd = CandidateTypes[1].pointer_end(); 7332 Ptr != PtrEnd; ++Ptr) { 7333 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7334 QualType PointeeType = (*Ptr)->getPointeeType(); 7335 if (!PointeeType->isObjectType()) 7336 continue; 7337 7338 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7339 7340 // T& operator[](ptrdiff_t, T*) 7341 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7342 } 7343 } 7344 7345 // C++ [over.built]p11: 7346 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7347 // C1 is the same type as C2 or is a derived class of C2, T is an object 7348 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7349 // there exist candidate operator functions of the form 7350 // 7351 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7352 // 7353 // where CV12 is the union of CV1 and CV2. 7354 void addArrowStarOverloads() { 7355 for (BuiltinCandidateTypeSet::iterator 7356 Ptr = CandidateTypes[0].pointer_begin(), 7357 PtrEnd = CandidateTypes[0].pointer_end(); 7358 Ptr != PtrEnd; ++Ptr) { 7359 QualType C1Ty = (*Ptr); 7360 QualType C1; 7361 QualifierCollector Q1; 7362 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7363 if (!isa<RecordType>(C1)) 7364 continue; 7365 // heuristic to reduce number of builtin candidates in the set. 7366 // Add volatile/restrict version only if there are conversions to a 7367 // volatile/restrict type. 7368 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7369 continue; 7370 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7371 continue; 7372 for (BuiltinCandidateTypeSet::iterator 7373 MemPtr = CandidateTypes[1].member_pointer_begin(), 7374 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7375 MemPtr != MemPtrEnd; ++MemPtr) { 7376 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7377 QualType C2 = QualType(mptr->getClass(), 0); 7378 C2 = C2.getUnqualifiedType(); 7379 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7380 break; 7381 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7382 // build CV12 T& 7383 QualType T = mptr->getPointeeType(); 7384 if (!VisibleTypeConversionsQuals.hasVolatile() && 7385 T.isVolatileQualified()) 7386 continue; 7387 if (!VisibleTypeConversionsQuals.hasRestrict() && 7388 T.isRestrictQualified()) 7389 continue; 7390 T = Q1.apply(S.Context, T); 7391 QualType ResultTy = S.Context.getLValueReferenceType(T); 7392 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7393 } 7394 } 7395 } 7396 7397 // Note that we don't consider the first argument, since it has been 7398 // contextually converted to bool long ago. The candidates below are 7399 // therefore added as binary. 7400 // 7401 // C++ [over.built]p25: 7402 // For every type T, where T is a pointer, pointer-to-member, or scoped 7403 // enumeration type, there exist candidate operator functions of the form 7404 // 7405 // T operator?(bool, T, T); 7406 // 7407 void addConditionalOperatorOverloads() { 7408 /// Set of (canonical) types that we've already handled. 7409 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7410 7411 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7412 for (BuiltinCandidateTypeSet::iterator 7413 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7414 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7415 Ptr != PtrEnd; ++Ptr) { 7416 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7417 continue; 7418 7419 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7420 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 7421 } 7422 7423 for (BuiltinCandidateTypeSet::iterator 7424 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7425 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7426 MemPtr != MemPtrEnd; ++MemPtr) { 7427 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7428 continue; 7429 7430 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7431 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 7432 } 7433 7434 if (S.getLangOpts().CPlusPlus0x) { 7435 for (BuiltinCandidateTypeSet::iterator 7436 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7437 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7438 Enum != EnumEnd; ++Enum) { 7439 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7440 continue; 7441 7442 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7443 continue; 7444 7445 QualType ParamTypes[2] = { *Enum, *Enum }; 7446 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 7447 } 7448 } 7449 } 7450 } 7451}; 7452 7453} // end anonymous namespace 7454 7455/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7456/// operator overloads to the candidate set (C++ [over.built]), based 7457/// on the operator @p Op and the arguments given. For example, if the 7458/// operator is a binary '+', this routine might add "int 7459/// operator+(int, int)" to cover integer addition. 7460void 7461Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7462 SourceLocation OpLoc, 7463 Expr **Args, unsigned NumArgs, 7464 OverloadCandidateSet& CandidateSet) { 7465 // Find all of the types that the arguments can convert to, but only 7466 // if the operator we're looking at has built-in operator candidates 7467 // that make use of these types. Also record whether we encounter non-record 7468 // candidate types or either arithmetic or enumeral candidate types. 7469 Qualifiers VisibleTypeConversionsQuals; 7470 VisibleTypeConversionsQuals.addConst(); 7471 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7472 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7473 7474 bool HasNonRecordCandidateType = false; 7475 bool HasArithmeticOrEnumeralCandidateType = false; 7476 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7477 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 7478 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7479 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7480 OpLoc, 7481 true, 7482 (Op == OO_Exclaim || 7483 Op == OO_AmpAmp || 7484 Op == OO_PipePipe), 7485 VisibleTypeConversionsQuals); 7486 HasNonRecordCandidateType = HasNonRecordCandidateType || 7487 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7488 HasArithmeticOrEnumeralCandidateType = 7489 HasArithmeticOrEnumeralCandidateType || 7490 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7491 } 7492 7493 // Exit early when no non-record types have been added to the candidate set 7494 // for any of the arguments to the operator. 7495 // 7496 // We can't exit early for !, ||, or &&, since there we have always have 7497 // 'bool' overloads. 7498 if (!HasNonRecordCandidateType && 7499 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7500 return; 7501 7502 // Setup an object to manage the common state for building overloads. 7503 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 7504 VisibleTypeConversionsQuals, 7505 HasArithmeticOrEnumeralCandidateType, 7506 CandidateTypes, CandidateSet); 7507 7508 // Dispatch over the operation to add in only those overloads which apply. 7509 switch (Op) { 7510 case OO_None: 7511 case NUM_OVERLOADED_OPERATORS: 7512 llvm_unreachable("Expected an overloaded operator"); 7513 7514 case OO_New: 7515 case OO_Delete: 7516 case OO_Array_New: 7517 case OO_Array_Delete: 7518 case OO_Call: 7519 llvm_unreachable( 7520 "Special operators don't use AddBuiltinOperatorCandidates"); 7521 7522 case OO_Comma: 7523 case OO_Arrow: 7524 // C++ [over.match.oper]p3: 7525 // -- For the operator ',', the unary operator '&', or the 7526 // operator '->', the built-in candidates set is empty. 7527 break; 7528 7529 case OO_Plus: // '+' is either unary or binary 7530 if (NumArgs == 1) 7531 OpBuilder.addUnaryPlusPointerOverloads(); 7532 // Fall through. 7533 7534 case OO_Minus: // '-' is either unary or binary 7535 if (NumArgs == 1) { 7536 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7537 } else { 7538 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7539 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7540 } 7541 break; 7542 7543 case OO_Star: // '*' is either unary or binary 7544 if (NumArgs == 1) 7545 OpBuilder.addUnaryStarPointerOverloads(); 7546 else 7547 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7548 break; 7549 7550 case OO_Slash: 7551 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7552 break; 7553 7554 case OO_PlusPlus: 7555 case OO_MinusMinus: 7556 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7557 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7558 break; 7559 7560 case OO_EqualEqual: 7561 case OO_ExclaimEqual: 7562 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7563 // Fall through. 7564 7565 case OO_Less: 7566 case OO_Greater: 7567 case OO_LessEqual: 7568 case OO_GreaterEqual: 7569 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7570 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7571 break; 7572 7573 case OO_Percent: 7574 case OO_Caret: 7575 case OO_Pipe: 7576 case OO_LessLess: 7577 case OO_GreaterGreater: 7578 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7579 break; 7580 7581 case OO_Amp: // '&' is either unary or binary 7582 if (NumArgs == 1) 7583 // C++ [over.match.oper]p3: 7584 // -- For the operator ',', the unary operator '&', or the 7585 // operator '->', the built-in candidates set is empty. 7586 break; 7587 7588 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7589 break; 7590 7591 case OO_Tilde: 7592 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7593 break; 7594 7595 case OO_Equal: 7596 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7597 // Fall through. 7598 7599 case OO_PlusEqual: 7600 case OO_MinusEqual: 7601 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7602 // Fall through. 7603 7604 case OO_StarEqual: 7605 case OO_SlashEqual: 7606 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7607 break; 7608 7609 case OO_PercentEqual: 7610 case OO_LessLessEqual: 7611 case OO_GreaterGreaterEqual: 7612 case OO_AmpEqual: 7613 case OO_CaretEqual: 7614 case OO_PipeEqual: 7615 OpBuilder.addAssignmentIntegralOverloads(); 7616 break; 7617 7618 case OO_Exclaim: 7619 OpBuilder.addExclaimOverload(); 7620 break; 7621 7622 case OO_AmpAmp: 7623 case OO_PipePipe: 7624 OpBuilder.addAmpAmpOrPipePipeOverload(); 7625 break; 7626 7627 case OO_Subscript: 7628 OpBuilder.addSubscriptOverloads(); 7629 break; 7630 7631 case OO_ArrowStar: 7632 OpBuilder.addArrowStarOverloads(); 7633 break; 7634 7635 case OO_Conditional: 7636 OpBuilder.addConditionalOperatorOverloads(); 7637 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7638 break; 7639 } 7640} 7641 7642/// \brief Add function candidates found via argument-dependent lookup 7643/// to the set of overloading candidates. 7644/// 7645/// This routine performs argument-dependent name lookup based on the 7646/// given function name (which may also be an operator name) and adds 7647/// all of the overload candidates found by ADL to the overload 7648/// candidate set (C++ [basic.lookup.argdep]). 7649void 7650Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7651 bool Operator, SourceLocation Loc, 7652 llvm::ArrayRef<Expr *> Args, 7653 TemplateArgumentListInfo *ExplicitTemplateArgs, 7654 OverloadCandidateSet& CandidateSet, 7655 bool PartialOverloading, 7656 bool StdNamespaceIsAssociated) { 7657 ADLResult Fns; 7658 7659 // FIXME: This approach for uniquing ADL results (and removing 7660 // redundant candidates from the set) relies on pointer-equality, 7661 // which means we need to key off the canonical decl. However, 7662 // always going back to the canonical decl might not get us the 7663 // right set of default arguments. What default arguments are 7664 // we supposed to consider on ADL candidates, anyway? 7665 7666 // FIXME: Pass in the explicit template arguments? 7667 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns, 7668 StdNamespaceIsAssociated); 7669 7670 // Erase all of the candidates we already knew about. 7671 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7672 CandEnd = CandidateSet.end(); 7673 Cand != CandEnd; ++Cand) 7674 if (Cand->Function) { 7675 Fns.erase(Cand->Function); 7676 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7677 Fns.erase(FunTmpl); 7678 } 7679 7680 // For each of the ADL candidates we found, add it to the overload 7681 // set. 7682 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7683 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7684 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7685 if (ExplicitTemplateArgs) 7686 continue; 7687 7688 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7689 PartialOverloading); 7690 } else 7691 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7692 FoundDecl, ExplicitTemplateArgs, 7693 Args, CandidateSet); 7694 } 7695} 7696 7697/// isBetterOverloadCandidate - Determines whether the first overload 7698/// candidate is a better candidate than the second (C++ 13.3.3p1). 7699bool 7700isBetterOverloadCandidate(Sema &S, 7701 const OverloadCandidate &Cand1, 7702 const OverloadCandidate &Cand2, 7703 SourceLocation Loc, 7704 bool UserDefinedConversion) { 7705 // Define viable functions to be better candidates than non-viable 7706 // functions. 7707 if (!Cand2.Viable) 7708 return Cand1.Viable; 7709 else if (!Cand1.Viable) 7710 return false; 7711 7712 // C++ [over.match.best]p1: 7713 // 7714 // -- if F is a static member function, ICS1(F) is defined such 7715 // that ICS1(F) is neither better nor worse than ICS1(G) for 7716 // any function G, and, symmetrically, ICS1(G) is neither 7717 // better nor worse than ICS1(F). 7718 unsigned StartArg = 0; 7719 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7720 StartArg = 1; 7721 7722 // C++ [over.match.best]p1: 7723 // A viable function F1 is defined to be a better function than another 7724 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7725 // conversion sequence than ICSi(F2), and then... 7726 unsigned NumArgs = Cand1.NumConversions; 7727 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7728 bool HasBetterConversion = false; 7729 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7730 switch (CompareImplicitConversionSequences(S, 7731 Cand1.Conversions[ArgIdx], 7732 Cand2.Conversions[ArgIdx])) { 7733 case ImplicitConversionSequence::Better: 7734 // Cand1 has a better conversion sequence. 7735 HasBetterConversion = true; 7736 break; 7737 7738 case ImplicitConversionSequence::Worse: 7739 // Cand1 can't be better than Cand2. 7740 return false; 7741 7742 case ImplicitConversionSequence::Indistinguishable: 7743 // Do nothing. 7744 break; 7745 } 7746 } 7747 7748 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7749 // ICSj(F2), or, if not that, 7750 if (HasBetterConversion) 7751 return true; 7752 7753 // - F1 is a non-template function and F2 is a function template 7754 // specialization, or, if not that, 7755 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7756 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7757 return true; 7758 7759 // -- F1 and F2 are function template specializations, and the function 7760 // template for F1 is more specialized than the template for F2 7761 // according to the partial ordering rules described in 14.5.5.2, or, 7762 // if not that, 7763 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7764 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7765 if (FunctionTemplateDecl *BetterTemplate 7766 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7767 Cand2.Function->getPrimaryTemplate(), 7768 Loc, 7769 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7770 : TPOC_Call, 7771 Cand1.ExplicitCallArguments)) 7772 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7773 } 7774 7775 // -- the context is an initialization by user-defined conversion 7776 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7777 // from the return type of F1 to the destination type (i.e., 7778 // the type of the entity being initialized) is a better 7779 // conversion sequence than the standard conversion sequence 7780 // from the return type of F2 to the destination type. 7781 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7782 isa<CXXConversionDecl>(Cand1.Function) && 7783 isa<CXXConversionDecl>(Cand2.Function)) { 7784 // First check whether we prefer one of the conversion functions over the 7785 // other. This only distinguishes the results in non-standard, extension 7786 // cases such as the conversion from a lambda closure type to a function 7787 // pointer or block. 7788 ImplicitConversionSequence::CompareKind FuncResult 7789 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7790 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7791 return FuncResult; 7792 7793 switch (CompareStandardConversionSequences(S, 7794 Cand1.FinalConversion, 7795 Cand2.FinalConversion)) { 7796 case ImplicitConversionSequence::Better: 7797 // Cand1 has a better conversion sequence. 7798 return true; 7799 7800 case ImplicitConversionSequence::Worse: 7801 // Cand1 can't be better than Cand2. 7802 return false; 7803 7804 case ImplicitConversionSequence::Indistinguishable: 7805 // Do nothing 7806 break; 7807 } 7808 } 7809 7810 return false; 7811} 7812 7813/// \brief Computes the best viable function (C++ 13.3.3) 7814/// within an overload candidate set. 7815/// 7816/// \param Loc The location of the function name (or operator symbol) for 7817/// which overload resolution occurs. 7818/// 7819/// \param Best If overload resolution was successful or found a deleted 7820/// function, \p Best points to the candidate function found. 7821/// 7822/// \returns The result of overload resolution. 7823OverloadingResult 7824OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 7825 iterator &Best, 7826 bool UserDefinedConversion) { 7827 // Find the best viable function. 7828 Best = end(); 7829 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7830 if (Cand->Viable) 7831 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 7832 UserDefinedConversion)) 7833 Best = Cand; 7834 } 7835 7836 // If we didn't find any viable functions, abort. 7837 if (Best == end()) 7838 return OR_No_Viable_Function; 7839 7840 // Make sure that this function is better than every other viable 7841 // function. If not, we have an ambiguity. 7842 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7843 if (Cand->Viable && 7844 Cand != Best && 7845 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 7846 UserDefinedConversion)) { 7847 Best = end(); 7848 return OR_Ambiguous; 7849 } 7850 } 7851 7852 // Best is the best viable function. 7853 if (Best->Function && 7854 (Best->Function->isDeleted() || 7855 S.isFunctionConsideredUnavailable(Best->Function))) 7856 return OR_Deleted; 7857 7858 return OR_Success; 7859} 7860 7861namespace { 7862 7863enum OverloadCandidateKind { 7864 oc_function, 7865 oc_method, 7866 oc_constructor, 7867 oc_function_template, 7868 oc_method_template, 7869 oc_constructor_template, 7870 oc_implicit_default_constructor, 7871 oc_implicit_copy_constructor, 7872 oc_implicit_move_constructor, 7873 oc_implicit_copy_assignment, 7874 oc_implicit_move_assignment, 7875 oc_implicit_inherited_constructor 7876}; 7877 7878OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 7879 FunctionDecl *Fn, 7880 std::string &Description) { 7881 bool isTemplate = false; 7882 7883 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 7884 isTemplate = true; 7885 Description = S.getTemplateArgumentBindingsText( 7886 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 7887 } 7888 7889 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 7890 if (!Ctor->isImplicit()) 7891 return isTemplate ? oc_constructor_template : oc_constructor; 7892 7893 if (Ctor->getInheritedConstructor()) 7894 return oc_implicit_inherited_constructor; 7895 7896 if (Ctor->isDefaultConstructor()) 7897 return oc_implicit_default_constructor; 7898 7899 if (Ctor->isMoveConstructor()) 7900 return oc_implicit_move_constructor; 7901 7902 assert(Ctor->isCopyConstructor() && 7903 "unexpected sort of implicit constructor"); 7904 return oc_implicit_copy_constructor; 7905 } 7906 7907 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 7908 // This actually gets spelled 'candidate function' for now, but 7909 // it doesn't hurt to split it out. 7910 if (!Meth->isImplicit()) 7911 return isTemplate ? oc_method_template : oc_method; 7912 7913 if (Meth->isMoveAssignmentOperator()) 7914 return oc_implicit_move_assignment; 7915 7916 if (Meth->isCopyAssignmentOperator()) 7917 return oc_implicit_copy_assignment; 7918 7919 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 7920 return oc_method; 7921 } 7922 7923 return isTemplate ? oc_function_template : oc_function; 7924} 7925 7926void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 7927 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 7928 if (!Ctor) return; 7929 7930 Ctor = Ctor->getInheritedConstructor(); 7931 if (!Ctor) return; 7932 7933 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 7934} 7935 7936} // end anonymous namespace 7937 7938// Notes the location of an overload candidate. 7939void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 7940 std::string FnDesc; 7941 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 7942 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 7943 << (unsigned) K << FnDesc; 7944 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 7945 Diag(Fn->getLocation(), PD); 7946 MaybeEmitInheritedConstructorNote(*this, Fn); 7947} 7948 7949//Notes the location of all overload candidates designated through 7950// OverloadedExpr 7951void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 7952 assert(OverloadedExpr->getType() == Context.OverloadTy); 7953 7954 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 7955 OverloadExpr *OvlExpr = Ovl.Expression; 7956 7957 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 7958 IEnd = OvlExpr->decls_end(); 7959 I != IEnd; ++I) { 7960 if (FunctionTemplateDecl *FunTmpl = 7961 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 7962 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 7963 } else if (FunctionDecl *Fun 7964 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 7965 NoteOverloadCandidate(Fun, DestType); 7966 } 7967 } 7968} 7969 7970/// Diagnoses an ambiguous conversion. The partial diagnostic is the 7971/// "lead" diagnostic; it will be given two arguments, the source and 7972/// target types of the conversion. 7973void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 7974 Sema &S, 7975 SourceLocation CaretLoc, 7976 const PartialDiagnostic &PDiag) const { 7977 S.Diag(CaretLoc, PDiag) 7978 << Ambiguous.getFromType() << Ambiguous.getToType(); 7979 for (AmbiguousConversionSequence::const_iterator 7980 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 7981 S.NoteOverloadCandidate(*I); 7982 } 7983} 7984 7985namespace { 7986 7987void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 7988 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 7989 assert(Conv.isBad()); 7990 assert(Cand->Function && "for now, candidate must be a function"); 7991 FunctionDecl *Fn = Cand->Function; 7992 7993 // There's a conversion slot for the object argument if this is a 7994 // non-constructor method. Note that 'I' corresponds the 7995 // conversion-slot index. 7996 bool isObjectArgument = false; 7997 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 7998 if (I == 0) 7999 isObjectArgument = true; 8000 else 8001 I--; 8002 } 8003 8004 std::string FnDesc; 8005 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8006 8007 Expr *FromExpr = Conv.Bad.FromExpr; 8008 QualType FromTy = Conv.Bad.getFromType(); 8009 QualType ToTy = Conv.Bad.getToType(); 8010 8011 if (FromTy == S.Context.OverloadTy) { 8012 assert(FromExpr && "overload set argument came from implicit argument?"); 8013 Expr *E = FromExpr->IgnoreParens(); 8014 if (isa<UnaryOperator>(E)) 8015 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8016 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8017 8018 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8019 << (unsigned) FnKind << FnDesc 8020 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8021 << ToTy << Name << I+1; 8022 MaybeEmitInheritedConstructorNote(S, Fn); 8023 return; 8024 } 8025 8026 // Do some hand-waving analysis to see if the non-viability is due 8027 // to a qualifier mismatch. 8028 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8029 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8030 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8031 CToTy = RT->getPointeeType(); 8032 else { 8033 // TODO: detect and diagnose the full richness of const mismatches. 8034 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8035 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8036 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8037 } 8038 8039 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8040 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8041 Qualifiers FromQs = CFromTy.getQualifiers(); 8042 Qualifiers ToQs = CToTy.getQualifiers(); 8043 8044 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8045 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8046 << (unsigned) FnKind << FnDesc 8047 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8048 << FromTy 8049 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8050 << (unsigned) isObjectArgument << I+1; 8051 MaybeEmitInheritedConstructorNote(S, Fn); 8052 return; 8053 } 8054 8055 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8056 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8057 << (unsigned) FnKind << FnDesc 8058 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8059 << FromTy 8060 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8061 << (unsigned) isObjectArgument << I+1; 8062 MaybeEmitInheritedConstructorNote(S, Fn); 8063 return; 8064 } 8065 8066 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8067 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8068 << (unsigned) FnKind << FnDesc 8069 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8070 << FromTy 8071 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8072 << (unsigned) isObjectArgument << I+1; 8073 MaybeEmitInheritedConstructorNote(S, Fn); 8074 return; 8075 } 8076 8077 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8078 assert(CVR && "unexpected qualifiers mismatch"); 8079 8080 if (isObjectArgument) { 8081 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8082 << (unsigned) FnKind << FnDesc 8083 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8084 << FromTy << (CVR - 1); 8085 } else { 8086 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8087 << (unsigned) FnKind << FnDesc 8088 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8089 << FromTy << (CVR - 1) << I+1; 8090 } 8091 MaybeEmitInheritedConstructorNote(S, Fn); 8092 return; 8093 } 8094 8095 // Special diagnostic for failure to convert an initializer list, since 8096 // telling the user that it has type void is not useful. 8097 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8098 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8099 << (unsigned) FnKind << FnDesc 8100 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8101 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8102 MaybeEmitInheritedConstructorNote(S, Fn); 8103 return; 8104 } 8105 8106 // Diagnose references or pointers to incomplete types differently, 8107 // since it's far from impossible that the incompleteness triggered 8108 // the failure. 8109 QualType TempFromTy = FromTy.getNonReferenceType(); 8110 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8111 TempFromTy = PTy->getPointeeType(); 8112 if (TempFromTy->isIncompleteType()) { 8113 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8114 << (unsigned) FnKind << FnDesc 8115 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8116 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8117 MaybeEmitInheritedConstructorNote(S, Fn); 8118 return; 8119 } 8120 8121 // Diagnose base -> derived pointer conversions. 8122 unsigned BaseToDerivedConversion = 0; 8123 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8124 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8125 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8126 FromPtrTy->getPointeeType()) && 8127 !FromPtrTy->getPointeeType()->isIncompleteType() && 8128 !ToPtrTy->getPointeeType()->isIncompleteType() && 8129 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8130 FromPtrTy->getPointeeType())) 8131 BaseToDerivedConversion = 1; 8132 } 8133 } else if (const ObjCObjectPointerType *FromPtrTy 8134 = FromTy->getAs<ObjCObjectPointerType>()) { 8135 if (const ObjCObjectPointerType *ToPtrTy 8136 = ToTy->getAs<ObjCObjectPointerType>()) 8137 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8138 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8139 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8140 FromPtrTy->getPointeeType()) && 8141 FromIface->isSuperClassOf(ToIface)) 8142 BaseToDerivedConversion = 2; 8143 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8144 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8145 !FromTy->isIncompleteType() && 8146 !ToRefTy->getPointeeType()->isIncompleteType() && 8147 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8148 BaseToDerivedConversion = 3; 8149 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8150 ToTy.getNonReferenceType().getCanonicalType() == 8151 FromTy.getNonReferenceType().getCanonicalType()) { 8152 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8153 << (unsigned) FnKind << FnDesc 8154 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8155 << (unsigned) isObjectArgument << I + 1; 8156 MaybeEmitInheritedConstructorNote(S, Fn); 8157 return; 8158 } 8159 } 8160 8161 if (BaseToDerivedConversion) { 8162 S.Diag(Fn->getLocation(), 8163 diag::note_ovl_candidate_bad_base_to_derived_conv) 8164 << (unsigned) FnKind << FnDesc 8165 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8166 << (BaseToDerivedConversion - 1) 8167 << FromTy << ToTy << I+1; 8168 MaybeEmitInheritedConstructorNote(S, Fn); 8169 return; 8170 } 8171 8172 if (isa<ObjCObjectPointerType>(CFromTy) && 8173 isa<PointerType>(CToTy)) { 8174 Qualifiers FromQs = CFromTy.getQualifiers(); 8175 Qualifiers ToQs = CToTy.getQualifiers(); 8176 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8177 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8178 << (unsigned) FnKind << FnDesc 8179 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8180 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8181 MaybeEmitInheritedConstructorNote(S, Fn); 8182 return; 8183 } 8184 } 8185 8186 // Emit the generic diagnostic and, optionally, add the hints to it. 8187 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8188 FDiag << (unsigned) FnKind << FnDesc 8189 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8190 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8191 << (unsigned) (Cand->Fix.Kind); 8192 8193 // If we can fix the conversion, suggest the FixIts. 8194 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8195 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8196 FDiag << *HI; 8197 S.Diag(Fn->getLocation(), FDiag); 8198 8199 MaybeEmitInheritedConstructorNote(S, Fn); 8200} 8201 8202void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8203 unsigned NumFormalArgs) { 8204 // TODO: treat calls to a missing default constructor as a special case 8205 8206 FunctionDecl *Fn = Cand->Function; 8207 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8208 8209 unsigned MinParams = Fn->getMinRequiredArguments(); 8210 8211 // With invalid overloaded operators, it's possible that we think we 8212 // have an arity mismatch when it fact it looks like we have the 8213 // right number of arguments, because only overloaded operators have 8214 // the weird behavior of overloading member and non-member functions. 8215 // Just don't report anything. 8216 if (Fn->isInvalidDecl() && 8217 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8218 return; 8219 8220 // at least / at most / exactly 8221 unsigned mode, modeCount; 8222 if (NumFormalArgs < MinParams) { 8223 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8224 (Cand->FailureKind == ovl_fail_bad_deduction && 8225 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8226 if (MinParams != FnTy->getNumArgs() || 8227 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8228 mode = 0; // "at least" 8229 else 8230 mode = 2; // "exactly" 8231 modeCount = MinParams; 8232 } else { 8233 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8234 (Cand->FailureKind == ovl_fail_bad_deduction && 8235 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8236 if (MinParams != FnTy->getNumArgs()) 8237 mode = 1; // "at most" 8238 else 8239 mode = 2; // "exactly" 8240 modeCount = FnTy->getNumArgs(); 8241 } 8242 8243 std::string Description; 8244 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8245 8246 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8247 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8248 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8249 << Fn->getParamDecl(0) << NumFormalArgs; 8250 else 8251 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8252 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8253 << modeCount << NumFormalArgs; 8254 MaybeEmitInheritedConstructorNote(S, Fn); 8255} 8256 8257/// Diagnose a failed template-argument deduction. 8258void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8259 unsigned NumArgs) { 8260 FunctionDecl *Fn = Cand->Function; // pattern 8261 8262 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8263 NamedDecl *ParamD; 8264 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8265 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8266 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8267 switch (Cand->DeductionFailure.Result) { 8268 case Sema::TDK_Success: 8269 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8270 8271 case Sema::TDK_Incomplete: { 8272 assert(ParamD && "no parameter found for incomplete deduction result"); 8273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8274 << ParamD->getDeclName(); 8275 MaybeEmitInheritedConstructorNote(S, Fn); 8276 return; 8277 } 8278 8279 case Sema::TDK_Underqualified: { 8280 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8281 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8282 8283 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8284 8285 // Param will have been canonicalized, but it should just be a 8286 // qualified version of ParamD, so move the qualifiers to that. 8287 QualifierCollector Qs; 8288 Qs.strip(Param); 8289 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8290 assert(S.Context.hasSameType(Param, NonCanonParam)); 8291 8292 // Arg has also been canonicalized, but there's nothing we can do 8293 // about that. It also doesn't matter as much, because it won't 8294 // have any template parameters in it (because deduction isn't 8295 // done on dependent types). 8296 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8297 8298 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8299 << ParamD->getDeclName() << Arg << NonCanonParam; 8300 MaybeEmitInheritedConstructorNote(S, Fn); 8301 return; 8302 } 8303 8304 case Sema::TDK_Inconsistent: { 8305 assert(ParamD && "no parameter found for inconsistent deduction result"); 8306 int which = 0; 8307 if (isa<TemplateTypeParmDecl>(ParamD)) 8308 which = 0; 8309 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8310 which = 1; 8311 else { 8312 which = 2; 8313 } 8314 8315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8316 << which << ParamD->getDeclName() 8317 << *Cand->DeductionFailure.getFirstArg() 8318 << *Cand->DeductionFailure.getSecondArg(); 8319 MaybeEmitInheritedConstructorNote(S, Fn); 8320 return; 8321 } 8322 8323 case Sema::TDK_InvalidExplicitArguments: 8324 assert(ParamD && "no parameter found for invalid explicit arguments"); 8325 if (ParamD->getDeclName()) 8326 S.Diag(Fn->getLocation(), 8327 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8328 << ParamD->getDeclName(); 8329 else { 8330 int index = 0; 8331 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8332 index = TTP->getIndex(); 8333 else if (NonTypeTemplateParmDecl *NTTP 8334 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8335 index = NTTP->getIndex(); 8336 else 8337 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8338 S.Diag(Fn->getLocation(), 8339 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8340 << (index + 1); 8341 } 8342 MaybeEmitInheritedConstructorNote(S, Fn); 8343 return; 8344 8345 case Sema::TDK_TooManyArguments: 8346 case Sema::TDK_TooFewArguments: 8347 DiagnoseArityMismatch(S, Cand, NumArgs); 8348 return; 8349 8350 case Sema::TDK_InstantiationDepth: 8351 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8352 MaybeEmitInheritedConstructorNote(S, Fn); 8353 return; 8354 8355 case Sema::TDK_SubstitutionFailure: { 8356 // Format the template argument list into the argument string. 8357 llvm::SmallString<128> TemplateArgString; 8358 if (TemplateArgumentList *Args = 8359 Cand->DeductionFailure.getTemplateArgumentList()) { 8360 TemplateArgString = " "; 8361 TemplateArgString += S.getTemplateArgumentBindingsText( 8362 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8363 } 8364 8365 // If this candidate was disabled by enable_if, say so. 8366 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8367 if (PDiag && PDiag->second.getDiagID() == 8368 diag::err_typename_nested_not_found_enable_if) { 8369 // FIXME: Use the source range of the condition, and the fully-qualified 8370 // name of the enable_if template. These are both present in PDiag. 8371 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8372 << "'enable_if'" << TemplateArgString; 8373 return; 8374 } 8375 8376 // Format the SFINAE diagnostic into the argument string. 8377 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8378 // formatted message in another diagnostic. 8379 llvm::SmallString<128> SFINAEArgString; 8380 SourceRange R; 8381 if (PDiag) { 8382 SFINAEArgString = ": "; 8383 R = SourceRange(PDiag->first, PDiag->first); 8384 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8385 } 8386 8387 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8388 << TemplateArgString << SFINAEArgString << R; 8389 MaybeEmitInheritedConstructorNote(S, Fn); 8390 return; 8391 } 8392 8393 // TODO: diagnose these individually, then kill off 8394 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8395 case Sema::TDK_NonDeducedMismatch: 8396 case Sema::TDK_FailedOverloadResolution: 8397 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8398 MaybeEmitInheritedConstructorNote(S, Fn); 8399 return; 8400 } 8401} 8402 8403/// CUDA: diagnose an invalid call across targets. 8404void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8405 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8406 FunctionDecl *Callee = Cand->Function; 8407 8408 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8409 CalleeTarget = S.IdentifyCUDATarget(Callee); 8410 8411 std::string FnDesc; 8412 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8413 8414 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8415 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8416} 8417 8418/// Generates a 'note' diagnostic for an overload candidate. We've 8419/// already generated a primary error at the call site. 8420/// 8421/// It really does need to be a single diagnostic with its caret 8422/// pointed at the candidate declaration. Yes, this creates some 8423/// major challenges of technical writing. Yes, this makes pointing 8424/// out problems with specific arguments quite awkward. It's still 8425/// better than generating twenty screens of text for every failed 8426/// overload. 8427/// 8428/// It would be great to be able to express per-candidate problems 8429/// more richly for those diagnostic clients that cared, but we'd 8430/// still have to be just as careful with the default diagnostics. 8431void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8432 unsigned NumArgs) { 8433 FunctionDecl *Fn = Cand->Function; 8434 8435 // Note deleted candidates, but only if they're viable. 8436 if (Cand->Viable && (Fn->isDeleted() || 8437 S.isFunctionConsideredUnavailable(Fn))) { 8438 std::string FnDesc; 8439 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8440 8441 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8442 << FnKind << FnDesc 8443 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8444 MaybeEmitInheritedConstructorNote(S, Fn); 8445 return; 8446 } 8447 8448 // We don't really have anything else to say about viable candidates. 8449 if (Cand->Viable) { 8450 S.NoteOverloadCandidate(Fn); 8451 return; 8452 } 8453 8454 switch (Cand->FailureKind) { 8455 case ovl_fail_too_many_arguments: 8456 case ovl_fail_too_few_arguments: 8457 return DiagnoseArityMismatch(S, Cand, NumArgs); 8458 8459 case ovl_fail_bad_deduction: 8460 return DiagnoseBadDeduction(S, Cand, NumArgs); 8461 8462 case ovl_fail_trivial_conversion: 8463 case ovl_fail_bad_final_conversion: 8464 case ovl_fail_final_conversion_not_exact: 8465 return S.NoteOverloadCandidate(Fn); 8466 8467 case ovl_fail_bad_conversion: { 8468 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8469 for (unsigned N = Cand->NumConversions; I != N; ++I) 8470 if (Cand->Conversions[I].isBad()) 8471 return DiagnoseBadConversion(S, Cand, I); 8472 8473 // FIXME: this currently happens when we're called from SemaInit 8474 // when user-conversion overload fails. Figure out how to handle 8475 // those conditions and diagnose them well. 8476 return S.NoteOverloadCandidate(Fn); 8477 } 8478 8479 case ovl_fail_bad_target: 8480 return DiagnoseBadTarget(S, Cand); 8481 } 8482} 8483 8484void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8485 // Desugar the type of the surrogate down to a function type, 8486 // retaining as many typedefs as possible while still showing 8487 // the function type (and, therefore, its parameter types). 8488 QualType FnType = Cand->Surrogate->getConversionType(); 8489 bool isLValueReference = false; 8490 bool isRValueReference = false; 8491 bool isPointer = false; 8492 if (const LValueReferenceType *FnTypeRef = 8493 FnType->getAs<LValueReferenceType>()) { 8494 FnType = FnTypeRef->getPointeeType(); 8495 isLValueReference = true; 8496 } else if (const RValueReferenceType *FnTypeRef = 8497 FnType->getAs<RValueReferenceType>()) { 8498 FnType = FnTypeRef->getPointeeType(); 8499 isRValueReference = true; 8500 } 8501 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8502 FnType = FnTypePtr->getPointeeType(); 8503 isPointer = true; 8504 } 8505 // Desugar down to a function type. 8506 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8507 // Reconstruct the pointer/reference as appropriate. 8508 if (isPointer) FnType = S.Context.getPointerType(FnType); 8509 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8510 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8511 8512 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8513 << FnType; 8514 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8515} 8516 8517void NoteBuiltinOperatorCandidate(Sema &S, 8518 const char *Opc, 8519 SourceLocation OpLoc, 8520 OverloadCandidate *Cand) { 8521 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8522 std::string TypeStr("operator"); 8523 TypeStr += Opc; 8524 TypeStr += "("; 8525 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8526 if (Cand->NumConversions == 1) { 8527 TypeStr += ")"; 8528 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8529 } else { 8530 TypeStr += ", "; 8531 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8532 TypeStr += ")"; 8533 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8534 } 8535} 8536 8537void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8538 OverloadCandidate *Cand) { 8539 unsigned NoOperands = Cand->NumConversions; 8540 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8541 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8542 if (ICS.isBad()) break; // all meaningless after first invalid 8543 if (!ICS.isAmbiguous()) continue; 8544 8545 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8546 S.PDiag(diag::note_ambiguous_type_conversion)); 8547 } 8548} 8549 8550SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8551 if (Cand->Function) 8552 return Cand->Function->getLocation(); 8553 if (Cand->IsSurrogate) 8554 return Cand->Surrogate->getLocation(); 8555 return SourceLocation(); 8556} 8557 8558static unsigned 8559RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8560 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8561 case Sema::TDK_Success: 8562 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8563 8564 case Sema::TDK_Invalid: 8565 case Sema::TDK_Incomplete: 8566 return 1; 8567 8568 case Sema::TDK_Underqualified: 8569 case Sema::TDK_Inconsistent: 8570 return 2; 8571 8572 case Sema::TDK_SubstitutionFailure: 8573 case Sema::TDK_NonDeducedMismatch: 8574 return 3; 8575 8576 case Sema::TDK_InstantiationDepth: 8577 case Sema::TDK_FailedOverloadResolution: 8578 return 4; 8579 8580 case Sema::TDK_InvalidExplicitArguments: 8581 return 5; 8582 8583 case Sema::TDK_TooManyArguments: 8584 case Sema::TDK_TooFewArguments: 8585 return 6; 8586 } 8587 llvm_unreachable("Unhandled deduction result"); 8588} 8589 8590struct CompareOverloadCandidatesForDisplay { 8591 Sema &S; 8592 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8593 8594 bool operator()(const OverloadCandidate *L, 8595 const OverloadCandidate *R) { 8596 // Fast-path this check. 8597 if (L == R) return false; 8598 8599 // Order first by viability. 8600 if (L->Viable) { 8601 if (!R->Viable) return true; 8602 8603 // TODO: introduce a tri-valued comparison for overload 8604 // candidates. Would be more worthwhile if we had a sort 8605 // that could exploit it. 8606 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8607 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8608 } else if (R->Viable) 8609 return false; 8610 8611 assert(L->Viable == R->Viable); 8612 8613 // Criteria by which we can sort non-viable candidates: 8614 if (!L->Viable) { 8615 // 1. Arity mismatches come after other candidates. 8616 if (L->FailureKind == ovl_fail_too_many_arguments || 8617 L->FailureKind == ovl_fail_too_few_arguments) 8618 return false; 8619 if (R->FailureKind == ovl_fail_too_many_arguments || 8620 R->FailureKind == ovl_fail_too_few_arguments) 8621 return true; 8622 8623 // 2. Bad conversions come first and are ordered by the number 8624 // of bad conversions and quality of good conversions. 8625 if (L->FailureKind == ovl_fail_bad_conversion) { 8626 if (R->FailureKind != ovl_fail_bad_conversion) 8627 return true; 8628 8629 // The conversion that can be fixed with a smaller number of changes, 8630 // comes first. 8631 unsigned numLFixes = L->Fix.NumConversionsFixed; 8632 unsigned numRFixes = R->Fix.NumConversionsFixed; 8633 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8634 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8635 if (numLFixes != numRFixes) { 8636 if (numLFixes < numRFixes) 8637 return true; 8638 else 8639 return false; 8640 } 8641 8642 // If there's any ordering between the defined conversions... 8643 // FIXME: this might not be transitive. 8644 assert(L->NumConversions == R->NumConversions); 8645 8646 int leftBetter = 0; 8647 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8648 for (unsigned E = L->NumConversions; I != E; ++I) { 8649 switch (CompareImplicitConversionSequences(S, 8650 L->Conversions[I], 8651 R->Conversions[I])) { 8652 case ImplicitConversionSequence::Better: 8653 leftBetter++; 8654 break; 8655 8656 case ImplicitConversionSequence::Worse: 8657 leftBetter--; 8658 break; 8659 8660 case ImplicitConversionSequence::Indistinguishable: 8661 break; 8662 } 8663 } 8664 if (leftBetter > 0) return true; 8665 if (leftBetter < 0) return false; 8666 8667 } else if (R->FailureKind == ovl_fail_bad_conversion) 8668 return false; 8669 8670 if (L->FailureKind == ovl_fail_bad_deduction) { 8671 if (R->FailureKind != ovl_fail_bad_deduction) 8672 return true; 8673 8674 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8675 return RankDeductionFailure(L->DeductionFailure) 8676 < RankDeductionFailure(R->DeductionFailure); 8677 } else if (R->FailureKind == ovl_fail_bad_deduction) 8678 return false; 8679 8680 // TODO: others? 8681 } 8682 8683 // Sort everything else by location. 8684 SourceLocation LLoc = GetLocationForCandidate(L); 8685 SourceLocation RLoc = GetLocationForCandidate(R); 8686 8687 // Put candidates without locations (e.g. builtins) at the end. 8688 if (LLoc.isInvalid()) return false; 8689 if (RLoc.isInvalid()) return true; 8690 8691 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8692 } 8693}; 8694 8695/// CompleteNonViableCandidate - Normally, overload resolution only 8696/// computes up to the first. Produces the FixIt set if possible. 8697void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8698 llvm::ArrayRef<Expr *> Args) { 8699 assert(!Cand->Viable); 8700 8701 // Don't do anything on failures other than bad conversion. 8702 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8703 8704 // We only want the FixIts if all the arguments can be corrected. 8705 bool Unfixable = false; 8706 // Use a implicit copy initialization to check conversion fixes. 8707 Cand->Fix.setConversionChecker(TryCopyInitialization); 8708 8709 // Skip forward to the first bad conversion. 8710 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8711 unsigned ConvCount = Cand->NumConversions; 8712 while (true) { 8713 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8714 ConvIdx++; 8715 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8716 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8717 break; 8718 } 8719 } 8720 8721 if (ConvIdx == ConvCount) 8722 return; 8723 8724 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8725 "remaining conversion is initialized?"); 8726 8727 // FIXME: this should probably be preserved from the overload 8728 // operation somehow. 8729 bool SuppressUserConversions = false; 8730 8731 const FunctionProtoType* Proto; 8732 unsigned ArgIdx = ConvIdx; 8733 8734 if (Cand->IsSurrogate) { 8735 QualType ConvType 8736 = Cand->Surrogate->getConversionType().getNonReferenceType(); 8737 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8738 ConvType = ConvPtrType->getPointeeType(); 8739 Proto = ConvType->getAs<FunctionProtoType>(); 8740 ArgIdx--; 8741 } else if (Cand->Function) { 8742 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8743 if (isa<CXXMethodDecl>(Cand->Function) && 8744 !isa<CXXConstructorDecl>(Cand->Function)) 8745 ArgIdx--; 8746 } else { 8747 // Builtin binary operator with a bad first conversion. 8748 assert(ConvCount <= 3); 8749 for (; ConvIdx != ConvCount; ++ConvIdx) 8750 Cand->Conversions[ConvIdx] 8751 = TryCopyInitialization(S, Args[ConvIdx], 8752 Cand->BuiltinTypes.ParamTypes[ConvIdx], 8753 SuppressUserConversions, 8754 /*InOverloadResolution*/ true, 8755 /*AllowObjCWritebackConversion=*/ 8756 S.getLangOpts().ObjCAutoRefCount); 8757 return; 8758 } 8759 8760 // Fill in the rest of the conversions. 8761 unsigned NumArgsInProto = Proto->getNumArgs(); 8762 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 8763 if (ArgIdx < NumArgsInProto) { 8764 Cand->Conversions[ConvIdx] 8765 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 8766 SuppressUserConversions, 8767 /*InOverloadResolution=*/true, 8768 /*AllowObjCWritebackConversion=*/ 8769 S.getLangOpts().ObjCAutoRefCount); 8770 // Store the FixIt in the candidate if it exists. 8771 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 8772 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 8773 } 8774 else 8775 Cand->Conversions[ConvIdx].setEllipsis(); 8776 } 8777} 8778 8779} // end anonymous namespace 8780 8781/// PrintOverloadCandidates - When overload resolution fails, prints 8782/// diagnostic messages containing the candidates in the candidate 8783/// set. 8784void OverloadCandidateSet::NoteCandidates(Sema &S, 8785 OverloadCandidateDisplayKind OCD, 8786 llvm::ArrayRef<Expr *> Args, 8787 const char *Opc, 8788 SourceLocation OpLoc) { 8789 // Sort the candidates by viability and position. Sorting directly would 8790 // be prohibitive, so we make a set of pointers and sort those. 8791 SmallVector<OverloadCandidate*, 32> Cands; 8792 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 8793 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 8794 if (Cand->Viable) 8795 Cands.push_back(Cand); 8796 else if (OCD == OCD_AllCandidates) { 8797 CompleteNonViableCandidate(S, Cand, Args); 8798 if (Cand->Function || Cand->IsSurrogate) 8799 Cands.push_back(Cand); 8800 // Otherwise, this a non-viable builtin candidate. We do not, in general, 8801 // want to list every possible builtin candidate. 8802 } 8803 } 8804 8805 std::sort(Cands.begin(), Cands.end(), 8806 CompareOverloadCandidatesForDisplay(S)); 8807 8808 bool ReportedAmbiguousConversions = false; 8809 8810 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 8811 const DiagnosticsEngine::OverloadsShown ShowOverloads = 8812 S.Diags.getShowOverloads(); 8813 unsigned CandsShown = 0; 8814 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 8815 OverloadCandidate *Cand = *I; 8816 8817 // Set an arbitrary limit on the number of candidate functions we'll spam 8818 // the user with. FIXME: This limit should depend on details of the 8819 // candidate list. 8820 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) { 8821 break; 8822 } 8823 ++CandsShown; 8824 8825 if (Cand->Function) 8826 NoteFunctionCandidate(S, Cand, Args.size()); 8827 else if (Cand->IsSurrogate) 8828 NoteSurrogateCandidate(S, Cand); 8829 else { 8830 assert(Cand->Viable && 8831 "Non-viable built-in candidates are not added to Cands."); 8832 // Generally we only see ambiguities including viable builtin 8833 // operators if overload resolution got screwed up by an 8834 // ambiguous user-defined conversion. 8835 // 8836 // FIXME: It's quite possible for different conversions to see 8837 // different ambiguities, though. 8838 if (!ReportedAmbiguousConversions) { 8839 NoteAmbiguousUserConversions(S, OpLoc, Cand); 8840 ReportedAmbiguousConversions = true; 8841 } 8842 8843 // If this is a viable builtin, print it. 8844 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 8845 } 8846 } 8847 8848 if (I != E) 8849 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 8850} 8851 8852// [PossiblyAFunctionType] --> [Return] 8853// NonFunctionType --> NonFunctionType 8854// R (A) --> R(A) 8855// R (*)(A) --> R (A) 8856// R (&)(A) --> R (A) 8857// R (S::*)(A) --> R (A) 8858QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 8859 QualType Ret = PossiblyAFunctionType; 8860 if (const PointerType *ToTypePtr = 8861 PossiblyAFunctionType->getAs<PointerType>()) 8862 Ret = ToTypePtr->getPointeeType(); 8863 else if (const ReferenceType *ToTypeRef = 8864 PossiblyAFunctionType->getAs<ReferenceType>()) 8865 Ret = ToTypeRef->getPointeeType(); 8866 else if (const MemberPointerType *MemTypePtr = 8867 PossiblyAFunctionType->getAs<MemberPointerType>()) 8868 Ret = MemTypePtr->getPointeeType(); 8869 Ret = 8870 Context.getCanonicalType(Ret).getUnqualifiedType(); 8871 return Ret; 8872} 8873 8874// A helper class to help with address of function resolution 8875// - allows us to avoid passing around all those ugly parameters 8876class AddressOfFunctionResolver 8877{ 8878 Sema& S; 8879 Expr* SourceExpr; 8880 const QualType& TargetType; 8881 QualType TargetFunctionType; // Extracted function type from target type 8882 8883 bool Complain; 8884 //DeclAccessPair& ResultFunctionAccessPair; 8885 ASTContext& Context; 8886 8887 bool TargetTypeIsNonStaticMemberFunction; 8888 bool FoundNonTemplateFunction; 8889 8890 OverloadExpr::FindResult OvlExprInfo; 8891 OverloadExpr *OvlExpr; 8892 TemplateArgumentListInfo OvlExplicitTemplateArgs; 8893 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 8894 8895public: 8896 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 8897 const QualType& TargetType, bool Complain) 8898 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 8899 Complain(Complain), Context(S.getASTContext()), 8900 TargetTypeIsNonStaticMemberFunction( 8901 !!TargetType->getAs<MemberPointerType>()), 8902 FoundNonTemplateFunction(false), 8903 OvlExprInfo(OverloadExpr::find(SourceExpr)), 8904 OvlExpr(OvlExprInfo.Expression) 8905 { 8906 ExtractUnqualifiedFunctionTypeFromTargetType(); 8907 8908 if (!TargetFunctionType->isFunctionType()) { 8909 if (OvlExpr->hasExplicitTemplateArgs()) { 8910 DeclAccessPair dap; 8911 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 8912 OvlExpr, false, &dap) ) { 8913 8914 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 8915 if (!Method->isStatic()) { 8916 // If the target type is a non-function type and the function 8917 // found is a non-static member function, pretend as if that was 8918 // the target, it's the only possible type to end up with. 8919 TargetTypeIsNonStaticMemberFunction = true; 8920 8921 // And skip adding the function if its not in the proper form. 8922 // We'll diagnose this due to an empty set of functions. 8923 if (!OvlExprInfo.HasFormOfMemberPointer) 8924 return; 8925 } 8926 } 8927 8928 Matches.push_back(std::make_pair(dap,Fn)); 8929 } 8930 } 8931 return; 8932 } 8933 8934 if (OvlExpr->hasExplicitTemplateArgs()) 8935 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 8936 8937 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 8938 // C++ [over.over]p4: 8939 // If more than one function is selected, [...] 8940 if (Matches.size() > 1) { 8941 if (FoundNonTemplateFunction) 8942 EliminateAllTemplateMatches(); 8943 else 8944 EliminateAllExceptMostSpecializedTemplate(); 8945 } 8946 } 8947 } 8948 8949private: 8950 bool isTargetTypeAFunction() const { 8951 return TargetFunctionType->isFunctionType(); 8952 } 8953 8954 // [ToType] [Return] 8955 8956 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 8957 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 8958 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 8959 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 8960 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 8961 } 8962 8963 // return true if any matching specializations were found 8964 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 8965 const DeclAccessPair& CurAccessFunPair) { 8966 if (CXXMethodDecl *Method 8967 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 8968 // Skip non-static function templates when converting to pointer, and 8969 // static when converting to member pointer. 8970 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 8971 return false; 8972 } 8973 else if (TargetTypeIsNonStaticMemberFunction) 8974 return false; 8975 8976 // C++ [over.over]p2: 8977 // If the name is a function template, template argument deduction is 8978 // done (14.8.2.2), and if the argument deduction succeeds, the 8979 // resulting template argument list is used to generate a single 8980 // function template specialization, which is added to the set of 8981 // overloaded functions considered. 8982 FunctionDecl *Specialization = 0; 8983 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 8984 if (Sema::TemplateDeductionResult Result 8985 = S.DeduceTemplateArguments(FunctionTemplate, 8986 &OvlExplicitTemplateArgs, 8987 TargetFunctionType, Specialization, 8988 Info)) { 8989 // FIXME: make a note of the failed deduction for diagnostics. 8990 (void)Result; 8991 return false; 8992 } 8993 8994 // Template argument deduction ensures that we have an exact match. 8995 // This function template specicalization works. 8996 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 8997 assert(TargetFunctionType 8998 == Context.getCanonicalType(Specialization->getType())); 8999 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9000 return true; 9001 } 9002 9003 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9004 const DeclAccessPair& CurAccessFunPair) { 9005 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9006 // Skip non-static functions when converting to pointer, and static 9007 // when converting to member pointer. 9008 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9009 return false; 9010 } 9011 else if (TargetTypeIsNonStaticMemberFunction) 9012 return false; 9013 9014 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9015 if (S.getLangOpts().CUDA) 9016 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9017 if (S.CheckCUDATarget(Caller, FunDecl)) 9018 return false; 9019 9020 QualType ResultTy; 9021 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9022 FunDecl->getType()) || 9023 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9024 ResultTy)) { 9025 Matches.push_back(std::make_pair(CurAccessFunPair, 9026 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9027 FoundNonTemplateFunction = true; 9028 return true; 9029 } 9030 } 9031 9032 return false; 9033 } 9034 9035 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9036 bool Ret = false; 9037 9038 // If the overload expression doesn't have the form of a pointer to 9039 // member, don't try to convert it to a pointer-to-member type. 9040 if (IsInvalidFormOfPointerToMemberFunction()) 9041 return false; 9042 9043 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9044 E = OvlExpr->decls_end(); 9045 I != E; ++I) { 9046 // Look through any using declarations to find the underlying function. 9047 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9048 9049 // C++ [over.over]p3: 9050 // Non-member functions and static member functions match 9051 // targets of type "pointer-to-function" or "reference-to-function." 9052 // Nonstatic member functions match targets of 9053 // type "pointer-to-member-function." 9054 // Note that according to DR 247, the containing class does not matter. 9055 if (FunctionTemplateDecl *FunctionTemplate 9056 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9057 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9058 Ret = true; 9059 } 9060 // If we have explicit template arguments supplied, skip non-templates. 9061 else if (!OvlExpr->hasExplicitTemplateArgs() && 9062 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9063 Ret = true; 9064 } 9065 assert(Ret || Matches.empty()); 9066 return Ret; 9067 } 9068 9069 void EliminateAllExceptMostSpecializedTemplate() { 9070 // [...] and any given function template specialization F1 is 9071 // eliminated if the set contains a second function template 9072 // specialization whose function template is more specialized 9073 // than the function template of F1 according to the partial 9074 // ordering rules of 14.5.5.2. 9075 9076 // The algorithm specified above is quadratic. We instead use a 9077 // two-pass algorithm (similar to the one used to identify the 9078 // best viable function in an overload set) that identifies the 9079 // best function template (if it exists). 9080 9081 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9082 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9083 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9084 9085 UnresolvedSetIterator Result = 9086 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9087 TPOC_Other, 0, SourceExpr->getLocStart(), 9088 S.PDiag(), 9089 S.PDiag(diag::err_addr_ovl_ambiguous) 9090 << Matches[0].second->getDeclName(), 9091 S.PDiag(diag::note_ovl_candidate) 9092 << (unsigned) oc_function_template, 9093 Complain, TargetFunctionType); 9094 9095 if (Result != MatchesCopy.end()) { 9096 // Make it the first and only element 9097 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9098 Matches[0].second = cast<FunctionDecl>(*Result); 9099 Matches.resize(1); 9100 } 9101 } 9102 9103 void EliminateAllTemplateMatches() { 9104 // [...] any function template specializations in the set are 9105 // eliminated if the set also contains a non-template function, [...] 9106 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9107 if (Matches[I].second->getPrimaryTemplate() == 0) 9108 ++I; 9109 else { 9110 Matches[I] = Matches[--N]; 9111 Matches.set_size(N); 9112 } 9113 } 9114 } 9115 9116public: 9117 void ComplainNoMatchesFound() const { 9118 assert(Matches.empty()); 9119 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9120 << OvlExpr->getName() << TargetFunctionType 9121 << OvlExpr->getSourceRange(); 9122 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9123 } 9124 9125 bool IsInvalidFormOfPointerToMemberFunction() const { 9126 return TargetTypeIsNonStaticMemberFunction && 9127 !OvlExprInfo.HasFormOfMemberPointer; 9128 } 9129 9130 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9131 // TODO: Should we condition this on whether any functions might 9132 // have matched, or is it more appropriate to do that in callers? 9133 // TODO: a fixit wouldn't hurt. 9134 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9135 << TargetType << OvlExpr->getSourceRange(); 9136 } 9137 9138 void ComplainOfInvalidConversion() const { 9139 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9140 << OvlExpr->getName() << TargetType; 9141 } 9142 9143 void ComplainMultipleMatchesFound() const { 9144 assert(Matches.size() > 1); 9145 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9146 << OvlExpr->getName() 9147 << OvlExpr->getSourceRange(); 9148 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9149 } 9150 9151 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9152 9153 int getNumMatches() const { return Matches.size(); } 9154 9155 FunctionDecl* getMatchingFunctionDecl() const { 9156 if (Matches.size() != 1) return 0; 9157 return Matches[0].second; 9158 } 9159 9160 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9161 if (Matches.size() != 1) return 0; 9162 return &Matches[0].first; 9163 } 9164}; 9165 9166/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9167/// an overloaded function (C++ [over.over]), where @p From is an 9168/// expression with overloaded function type and @p ToType is the type 9169/// we're trying to resolve to. For example: 9170/// 9171/// @code 9172/// int f(double); 9173/// int f(int); 9174/// 9175/// int (*pfd)(double) = f; // selects f(double) 9176/// @endcode 9177/// 9178/// This routine returns the resulting FunctionDecl if it could be 9179/// resolved, and NULL otherwise. When @p Complain is true, this 9180/// routine will emit diagnostics if there is an error. 9181FunctionDecl * 9182Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9183 QualType TargetType, 9184 bool Complain, 9185 DeclAccessPair &FoundResult, 9186 bool *pHadMultipleCandidates) { 9187 assert(AddressOfExpr->getType() == Context.OverloadTy); 9188 9189 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9190 Complain); 9191 int NumMatches = Resolver.getNumMatches(); 9192 FunctionDecl* Fn = 0; 9193 if (NumMatches == 0 && Complain) { 9194 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9195 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9196 else 9197 Resolver.ComplainNoMatchesFound(); 9198 } 9199 else if (NumMatches > 1 && Complain) 9200 Resolver.ComplainMultipleMatchesFound(); 9201 else if (NumMatches == 1) { 9202 Fn = Resolver.getMatchingFunctionDecl(); 9203 assert(Fn); 9204 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9205 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn); 9206 if (Complain) 9207 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9208 } 9209 9210 if (pHadMultipleCandidates) 9211 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9212 return Fn; 9213} 9214 9215/// \brief Given an expression that refers to an overloaded function, try to 9216/// resolve that overloaded function expression down to a single function. 9217/// 9218/// This routine can only resolve template-ids that refer to a single function 9219/// template, where that template-id refers to a single template whose template 9220/// arguments are either provided by the template-id or have defaults, 9221/// as described in C++0x [temp.arg.explicit]p3. 9222FunctionDecl * 9223Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9224 bool Complain, 9225 DeclAccessPair *FoundResult) { 9226 // C++ [over.over]p1: 9227 // [...] [Note: any redundant set of parentheses surrounding the 9228 // overloaded function name is ignored (5.1). ] 9229 // C++ [over.over]p1: 9230 // [...] The overloaded function name can be preceded by the & 9231 // operator. 9232 9233 // If we didn't actually find any template-ids, we're done. 9234 if (!ovl->hasExplicitTemplateArgs()) 9235 return 0; 9236 9237 TemplateArgumentListInfo ExplicitTemplateArgs; 9238 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9239 9240 // Look through all of the overloaded functions, searching for one 9241 // whose type matches exactly. 9242 FunctionDecl *Matched = 0; 9243 for (UnresolvedSetIterator I = ovl->decls_begin(), 9244 E = ovl->decls_end(); I != E; ++I) { 9245 // C++0x [temp.arg.explicit]p3: 9246 // [...] In contexts where deduction is done and fails, or in contexts 9247 // where deduction is not done, if a template argument list is 9248 // specified and it, along with any default template arguments, 9249 // identifies a single function template specialization, then the 9250 // template-id is an lvalue for the function template specialization. 9251 FunctionTemplateDecl *FunctionTemplate 9252 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9253 9254 // C++ [over.over]p2: 9255 // If the name is a function template, template argument deduction is 9256 // done (14.8.2.2), and if the argument deduction succeeds, the 9257 // resulting template argument list is used to generate a single 9258 // function template specialization, which is added to the set of 9259 // overloaded functions considered. 9260 FunctionDecl *Specialization = 0; 9261 TemplateDeductionInfo Info(Context, ovl->getNameLoc()); 9262 if (TemplateDeductionResult Result 9263 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9264 Specialization, Info)) { 9265 // FIXME: make a note of the failed deduction for diagnostics. 9266 (void)Result; 9267 continue; 9268 } 9269 9270 assert(Specialization && "no specialization and no error?"); 9271 9272 // Multiple matches; we can't resolve to a single declaration. 9273 if (Matched) { 9274 if (Complain) { 9275 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9276 << ovl->getName(); 9277 NoteAllOverloadCandidates(ovl); 9278 } 9279 return 0; 9280 } 9281 9282 Matched = Specialization; 9283 if (FoundResult) *FoundResult = I.getPair(); 9284 } 9285 9286 return Matched; 9287} 9288 9289 9290 9291 9292// Resolve and fix an overloaded expression that can be resolved 9293// because it identifies a single function template specialization. 9294// 9295// Last three arguments should only be supplied if Complain = true 9296// 9297// Return true if it was logically possible to so resolve the 9298// expression, regardless of whether or not it succeeded. Always 9299// returns true if 'complain' is set. 9300bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9301 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9302 bool complain, const SourceRange& OpRangeForComplaining, 9303 QualType DestTypeForComplaining, 9304 unsigned DiagIDForComplaining) { 9305 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9306 9307 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9308 9309 DeclAccessPair found; 9310 ExprResult SingleFunctionExpression; 9311 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9312 ovl.Expression, /*complain*/ false, &found)) { 9313 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9314 SrcExpr = ExprError(); 9315 return true; 9316 } 9317 9318 // It is only correct to resolve to an instance method if we're 9319 // resolving a form that's permitted to be a pointer to member. 9320 // Otherwise we'll end up making a bound member expression, which 9321 // is illegal in all the contexts we resolve like this. 9322 if (!ovl.HasFormOfMemberPointer && 9323 isa<CXXMethodDecl>(fn) && 9324 cast<CXXMethodDecl>(fn)->isInstance()) { 9325 if (!complain) return false; 9326 9327 Diag(ovl.Expression->getExprLoc(), 9328 diag::err_bound_member_function) 9329 << 0 << ovl.Expression->getSourceRange(); 9330 9331 // TODO: I believe we only end up here if there's a mix of 9332 // static and non-static candidates (otherwise the expression 9333 // would have 'bound member' type, not 'overload' type). 9334 // Ideally we would note which candidate was chosen and why 9335 // the static candidates were rejected. 9336 SrcExpr = ExprError(); 9337 return true; 9338 } 9339 9340 // Fix the expression to refer to 'fn'. 9341 SingleFunctionExpression = 9342 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9343 9344 // If desired, do function-to-pointer decay. 9345 if (doFunctionPointerConverion) { 9346 SingleFunctionExpression = 9347 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9348 if (SingleFunctionExpression.isInvalid()) { 9349 SrcExpr = ExprError(); 9350 return true; 9351 } 9352 } 9353 } 9354 9355 if (!SingleFunctionExpression.isUsable()) { 9356 if (complain) { 9357 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9358 << ovl.Expression->getName() 9359 << DestTypeForComplaining 9360 << OpRangeForComplaining 9361 << ovl.Expression->getQualifierLoc().getSourceRange(); 9362 NoteAllOverloadCandidates(SrcExpr.get()); 9363 9364 SrcExpr = ExprError(); 9365 return true; 9366 } 9367 9368 return false; 9369 } 9370 9371 SrcExpr = SingleFunctionExpression; 9372 return true; 9373} 9374 9375/// \brief Add a single candidate to the overload set. 9376static void AddOverloadedCallCandidate(Sema &S, 9377 DeclAccessPair FoundDecl, 9378 TemplateArgumentListInfo *ExplicitTemplateArgs, 9379 llvm::ArrayRef<Expr *> Args, 9380 OverloadCandidateSet &CandidateSet, 9381 bool PartialOverloading, 9382 bool KnownValid) { 9383 NamedDecl *Callee = FoundDecl.getDecl(); 9384 if (isa<UsingShadowDecl>(Callee)) 9385 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9386 9387 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9388 if (ExplicitTemplateArgs) { 9389 assert(!KnownValid && "Explicit template arguments?"); 9390 return; 9391 } 9392 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9393 PartialOverloading); 9394 return; 9395 } 9396 9397 if (FunctionTemplateDecl *FuncTemplate 9398 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9399 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9400 ExplicitTemplateArgs, Args, CandidateSet); 9401 return; 9402 } 9403 9404 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9405} 9406 9407/// \brief Add the overload candidates named by callee and/or found by argument 9408/// dependent lookup to the given overload set. 9409void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9410 llvm::ArrayRef<Expr *> Args, 9411 OverloadCandidateSet &CandidateSet, 9412 bool PartialOverloading) { 9413 9414#ifndef NDEBUG 9415 // Verify that ArgumentDependentLookup is consistent with the rules 9416 // in C++0x [basic.lookup.argdep]p3: 9417 // 9418 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9419 // and let Y be the lookup set produced by argument dependent 9420 // lookup (defined as follows). If X contains 9421 // 9422 // -- a declaration of a class member, or 9423 // 9424 // -- a block-scope function declaration that is not a 9425 // using-declaration, or 9426 // 9427 // -- a declaration that is neither a function or a function 9428 // template 9429 // 9430 // then Y is empty. 9431 9432 if (ULE->requiresADL()) { 9433 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9434 E = ULE->decls_end(); I != E; ++I) { 9435 assert(!(*I)->getDeclContext()->isRecord()); 9436 assert(isa<UsingShadowDecl>(*I) || 9437 !(*I)->getDeclContext()->isFunctionOrMethod()); 9438 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9439 } 9440 } 9441#endif 9442 9443 // It would be nice to avoid this copy. 9444 TemplateArgumentListInfo TABuffer; 9445 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9446 if (ULE->hasExplicitTemplateArgs()) { 9447 ULE->copyTemplateArgumentsInto(TABuffer); 9448 ExplicitTemplateArgs = &TABuffer; 9449 } 9450 9451 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9452 E = ULE->decls_end(); I != E; ++I) 9453 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9454 CandidateSet, PartialOverloading, 9455 /*KnownValid*/ true); 9456 9457 if (ULE->requiresADL()) 9458 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9459 ULE->getExprLoc(), 9460 Args, ExplicitTemplateArgs, 9461 CandidateSet, PartialOverloading, 9462 ULE->isStdAssociatedNamespace()); 9463} 9464 9465/// Attempt to recover from an ill-formed use of a non-dependent name in a 9466/// template, where the non-dependent name was declared after the template 9467/// was defined. This is common in code written for a compilers which do not 9468/// correctly implement two-stage name lookup. 9469/// 9470/// Returns true if a viable candidate was found and a diagnostic was issued. 9471static bool 9472DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9473 const CXXScopeSpec &SS, LookupResult &R, 9474 TemplateArgumentListInfo *ExplicitTemplateArgs, 9475 llvm::ArrayRef<Expr *> Args) { 9476 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9477 return false; 9478 9479 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9480 if (DC->isTransparentContext()) 9481 continue; 9482 9483 SemaRef.LookupQualifiedName(R, DC); 9484 9485 if (!R.empty()) { 9486 R.suppressDiagnostics(); 9487 9488 if (isa<CXXRecordDecl>(DC)) { 9489 // Don't diagnose names we find in classes; we get much better 9490 // diagnostics for these from DiagnoseEmptyLookup. 9491 R.clear(); 9492 return false; 9493 } 9494 9495 OverloadCandidateSet Candidates(FnLoc); 9496 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9497 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9498 ExplicitTemplateArgs, Args, 9499 Candidates, false, /*KnownValid*/ false); 9500 9501 OverloadCandidateSet::iterator Best; 9502 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9503 // No viable functions. Don't bother the user with notes for functions 9504 // which don't work and shouldn't be found anyway. 9505 R.clear(); 9506 return false; 9507 } 9508 9509 // Find the namespaces where ADL would have looked, and suggest 9510 // declaring the function there instead. 9511 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9512 Sema::AssociatedClassSet AssociatedClasses; 9513 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9514 AssociatedNamespaces, 9515 AssociatedClasses); 9516 // Never suggest declaring a function within namespace 'std'. 9517 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9518 if (DeclContext *Std = SemaRef.getStdNamespace()) { 9519 for (Sema::AssociatedNamespaceSet::iterator 9520 it = AssociatedNamespaces.begin(), 9521 end = AssociatedNamespaces.end(); it != end; ++it) { 9522 if (!Std->Encloses(*it)) 9523 SuggestedNamespaces.insert(*it); 9524 } 9525 } else { 9526 // Lacking the 'std::' namespace, use all of the associated namespaces. 9527 SuggestedNamespaces = AssociatedNamespaces; 9528 } 9529 9530 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9531 << R.getLookupName(); 9532 if (SuggestedNamespaces.empty()) { 9533 SemaRef.Diag(Best->Function->getLocation(), 9534 diag::note_not_found_by_two_phase_lookup) 9535 << R.getLookupName() << 0; 9536 } else if (SuggestedNamespaces.size() == 1) { 9537 SemaRef.Diag(Best->Function->getLocation(), 9538 diag::note_not_found_by_two_phase_lookup) 9539 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9540 } else { 9541 // FIXME: It would be useful to list the associated namespaces here, 9542 // but the diagnostics infrastructure doesn't provide a way to produce 9543 // a localized representation of a list of items. 9544 SemaRef.Diag(Best->Function->getLocation(), 9545 diag::note_not_found_by_two_phase_lookup) 9546 << R.getLookupName() << 2; 9547 } 9548 9549 // Try to recover by calling this function. 9550 return true; 9551 } 9552 9553 R.clear(); 9554 } 9555 9556 return false; 9557} 9558 9559/// Attempt to recover from ill-formed use of a non-dependent operator in a 9560/// template, where the non-dependent operator was declared after the template 9561/// was defined. 9562/// 9563/// Returns true if a viable candidate was found and a diagnostic was issued. 9564static bool 9565DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9566 SourceLocation OpLoc, 9567 llvm::ArrayRef<Expr *> Args) { 9568 DeclarationName OpName = 9569 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9570 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9571 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9572 /*ExplicitTemplateArgs=*/0, Args); 9573} 9574 9575namespace { 9576// Callback to limit the allowed keywords and to only accept typo corrections 9577// that are keywords or whose decls refer to functions (or template functions) 9578// that accept the given number of arguments. 9579class RecoveryCallCCC : public CorrectionCandidateCallback { 9580 public: 9581 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9582 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9583 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9584 WantRemainingKeywords = false; 9585 } 9586 9587 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9588 if (!candidate.getCorrectionDecl()) 9589 return candidate.isKeyword(); 9590 9591 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9592 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9593 FunctionDecl *FD = 0; 9594 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9595 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9596 FD = FTD->getTemplatedDecl(); 9597 if (!HasExplicitTemplateArgs && !FD) { 9598 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9599 // If the Decl is neither a function nor a template function, 9600 // determine if it is a pointer or reference to a function. If so, 9601 // check against the number of arguments expected for the pointee. 9602 QualType ValType = cast<ValueDecl>(ND)->getType(); 9603 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9604 ValType = ValType->getPointeeType(); 9605 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9606 if (FPT->getNumArgs() == NumArgs) 9607 return true; 9608 } 9609 } 9610 if (FD && FD->getNumParams() >= NumArgs && 9611 FD->getMinRequiredArguments() <= NumArgs) 9612 return true; 9613 } 9614 return false; 9615 } 9616 9617 private: 9618 unsigned NumArgs; 9619 bool HasExplicitTemplateArgs; 9620}; 9621 9622// Callback that effectively disabled typo correction 9623class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9624 public: 9625 NoTypoCorrectionCCC() { 9626 WantTypeSpecifiers = false; 9627 WantExpressionKeywords = false; 9628 WantCXXNamedCasts = false; 9629 WantRemainingKeywords = false; 9630 } 9631 9632 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9633 return false; 9634 } 9635}; 9636} 9637 9638/// Attempts to recover from a call where no functions were found. 9639/// 9640/// Returns true if new candidates were found. 9641static ExprResult 9642BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9643 UnresolvedLookupExpr *ULE, 9644 SourceLocation LParenLoc, 9645 llvm::MutableArrayRef<Expr *> Args, 9646 SourceLocation RParenLoc, 9647 bool EmptyLookup, bool AllowTypoCorrection) { 9648 9649 CXXScopeSpec SS; 9650 SS.Adopt(ULE->getQualifierLoc()); 9651 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9652 9653 TemplateArgumentListInfo TABuffer; 9654 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9655 if (ULE->hasExplicitTemplateArgs()) { 9656 ULE->copyTemplateArgumentsInto(TABuffer); 9657 ExplicitTemplateArgs = &TABuffer; 9658 } 9659 9660 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9661 Sema::LookupOrdinaryName); 9662 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9663 NoTypoCorrectionCCC RejectAll; 9664 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9665 (CorrectionCandidateCallback*)&Validator : 9666 (CorrectionCandidateCallback*)&RejectAll; 9667 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9668 ExplicitTemplateArgs, Args) && 9669 (!EmptyLookup || 9670 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9671 ExplicitTemplateArgs, Args))) 9672 return ExprError(); 9673 9674 assert(!R.empty() && "lookup results empty despite recovery"); 9675 9676 // Build an implicit member call if appropriate. Just drop the 9677 // casts and such from the call, we don't really care. 9678 ExprResult NewFn = ExprError(); 9679 if ((*R.begin())->isCXXClassMember()) 9680 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9681 R, ExplicitTemplateArgs); 9682 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9683 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9684 ExplicitTemplateArgs); 9685 else 9686 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9687 9688 if (NewFn.isInvalid()) 9689 return ExprError(); 9690 9691 // This shouldn't cause an infinite loop because we're giving it 9692 // an expression with viable lookup results, which should never 9693 // end up here. 9694 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9695 MultiExprArg(Args.data(), Args.size()), 9696 RParenLoc); 9697} 9698 9699/// \brief Constructs and populates an OverloadedCandidateSet from 9700/// the given function. 9701/// \returns true when an the ExprResult output parameter has been set. 9702bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 9703 UnresolvedLookupExpr *ULE, 9704 Expr **Args, unsigned NumArgs, 9705 SourceLocation RParenLoc, 9706 OverloadCandidateSet *CandidateSet, 9707 ExprResult *Result) { 9708#ifndef NDEBUG 9709 if (ULE->requiresADL()) { 9710 // To do ADL, we must have found an unqualified name. 9711 assert(!ULE->getQualifier() && "qualified name with ADL"); 9712 9713 // We don't perform ADL for implicit declarations of builtins. 9714 // Verify that this was correctly set up. 9715 FunctionDecl *F; 9716 if (ULE->decls_begin() + 1 == ULE->decls_end() && 9717 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 9718 F->getBuiltinID() && F->isImplicit()) 9719 llvm_unreachable("performing ADL for builtin"); 9720 9721 // We don't perform ADL in C. 9722 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 9723 } else 9724 assert(!ULE->isStdAssociatedNamespace() && 9725 "std is associated namespace but not doing ADL"); 9726#endif 9727 9728 UnbridgedCastsSet UnbridgedCasts; 9729 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) { 9730 *Result = ExprError(); 9731 return true; 9732 } 9733 9734 // Add the functions denoted by the callee to the set of candidate 9735 // functions, including those from argument-dependent lookup. 9736 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs), 9737 *CandidateSet); 9738 9739 // If we found nothing, try to recover. 9740 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 9741 // out if it fails. 9742 if (CandidateSet->empty()) { 9743 // In Microsoft mode, if we are inside a template class member function then 9744 // create a type dependent CallExpr. The goal is to postpone name lookup 9745 // to instantiation time to be able to search into type dependent base 9746 // classes. 9747 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 9748 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 9749 CallExpr *CE = new (Context) CallExpr(Context, Fn, 9750 llvm::makeArrayRef(Args, NumArgs), 9751 Context.DependentTy, VK_RValue, 9752 RParenLoc); 9753 CE->setTypeDependent(true); 9754 *Result = Owned(CE); 9755 return true; 9756 } 9757 return false; 9758 } 9759 9760 UnbridgedCasts.restore(); 9761 return false; 9762} 9763 9764/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 9765/// the completed call expression. If overload resolution fails, emits 9766/// diagnostics and returns ExprError() 9767static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9768 UnresolvedLookupExpr *ULE, 9769 SourceLocation LParenLoc, 9770 Expr **Args, unsigned NumArgs, 9771 SourceLocation RParenLoc, 9772 Expr *ExecConfig, 9773 OverloadCandidateSet *CandidateSet, 9774 OverloadCandidateSet::iterator *Best, 9775 OverloadingResult OverloadResult, 9776 bool AllowTypoCorrection) { 9777 if (CandidateSet->empty()) 9778 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9779 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9780 RParenLoc, /*EmptyLookup=*/true, 9781 AllowTypoCorrection); 9782 9783 switch (OverloadResult) { 9784 case OR_Success: { 9785 FunctionDecl *FDecl = (*Best)->Function; 9786 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl); 9787 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 9788 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()); 9789 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9790 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9791 RParenLoc, ExecConfig); 9792 } 9793 9794 case OR_No_Viable_Function: { 9795 // Try to recover by looking for viable functions which the user might 9796 // have meant to call. 9797 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9798 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9799 RParenLoc, 9800 /*EmptyLookup=*/false, 9801 AllowTypoCorrection); 9802 if (!Recovery.isInvalid()) 9803 return Recovery; 9804 9805 SemaRef.Diag(Fn->getLocStart(), 9806 diag::err_ovl_no_viable_function_in_call) 9807 << ULE->getName() << Fn->getSourceRange(); 9808 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9809 llvm::makeArrayRef(Args, NumArgs)); 9810 break; 9811 } 9812 9813 case OR_Ambiguous: 9814 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 9815 << ULE->getName() << Fn->getSourceRange(); 9816 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, 9817 llvm::makeArrayRef(Args, NumArgs)); 9818 break; 9819 9820 case OR_Deleted: { 9821 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 9822 << (*Best)->Function->isDeleted() 9823 << ULE->getName() 9824 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 9825 << Fn->getSourceRange(); 9826 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9827 llvm::makeArrayRef(Args, NumArgs)); 9828 9829 // We emitted an error for the unvailable/deleted function call but keep 9830 // the call in the AST. 9831 FunctionDecl *FDecl = (*Best)->Function; 9832 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9833 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9834 RParenLoc, ExecConfig); 9835 } 9836 } 9837 9838 // Overload resolution failed. 9839 return ExprError(); 9840} 9841 9842/// BuildOverloadedCallExpr - Given the call expression that calls Fn 9843/// (which eventually refers to the declaration Func) and the call 9844/// arguments Args/NumArgs, attempt to resolve the function call down 9845/// to a specific function. If overload resolution succeeds, returns 9846/// the call expression produced by overload resolution. 9847/// Otherwise, emits diagnostics and returns ExprError. 9848ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 9849 UnresolvedLookupExpr *ULE, 9850 SourceLocation LParenLoc, 9851 Expr **Args, unsigned NumArgs, 9852 SourceLocation RParenLoc, 9853 Expr *ExecConfig, 9854 bool AllowTypoCorrection) { 9855 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 9856 ExprResult result; 9857 9858 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc, 9859 &CandidateSet, &result)) 9860 return result; 9861 9862 OverloadCandidateSet::iterator Best; 9863 OverloadingResult OverloadResult = 9864 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 9865 9866 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 9867 RParenLoc, ExecConfig, &CandidateSet, 9868 &Best, OverloadResult, 9869 AllowTypoCorrection); 9870} 9871 9872static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 9873 return Functions.size() > 1 || 9874 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 9875} 9876 9877/// \brief Create a unary operation that may resolve to an overloaded 9878/// operator. 9879/// 9880/// \param OpLoc The location of the operator itself (e.g., '*'). 9881/// 9882/// \param OpcIn The UnaryOperator::Opcode that describes this 9883/// operator. 9884/// 9885/// \param Fns The set of non-member functions that will be 9886/// considered by overload resolution. The caller needs to build this 9887/// set based on the context using, e.g., 9888/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 9889/// set should not contain any member functions; those will be added 9890/// by CreateOverloadedUnaryOp(). 9891/// 9892/// \param Input The input argument. 9893ExprResult 9894Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 9895 const UnresolvedSetImpl &Fns, 9896 Expr *Input) { 9897 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 9898 9899 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 9900 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 9901 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 9902 // TODO: provide better source location info. 9903 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 9904 9905 if (checkPlaceholderForOverload(*this, Input)) 9906 return ExprError(); 9907 9908 Expr *Args[2] = { Input, 0 }; 9909 unsigned NumArgs = 1; 9910 9911 // For post-increment and post-decrement, add the implicit '0' as 9912 // the second argument, so that we know this is a post-increment or 9913 // post-decrement. 9914 if (Opc == UO_PostInc || Opc == UO_PostDec) { 9915 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 9916 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 9917 SourceLocation()); 9918 NumArgs = 2; 9919 } 9920 9921 if (Input->isTypeDependent()) { 9922 if (Fns.empty()) 9923 return Owned(new (Context) UnaryOperator(Input, 9924 Opc, 9925 Context.DependentTy, 9926 VK_RValue, OK_Ordinary, 9927 OpLoc)); 9928 9929 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 9930 UnresolvedLookupExpr *Fn 9931 = UnresolvedLookupExpr::Create(Context, NamingClass, 9932 NestedNameSpecifierLoc(), OpNameInfo, 9933 /*ADL*/ true, IsOverloaded(Fns), 9934 Fns.begin(), Fns.end()); 9935 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 9936 llvm::makeArrayRef(Args, NumArgs), 9937 Context.DependentTy, 9938 VK_RValue, 9939 OpLoc)); 9940 } 9941 9942 // Build an empty overload set. 9943 OverloadCandidateSet CandidateSet(OpLoc); 9944 9945 // Add the candidates from the given function set. 9946 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet, 9947 false); 9948 9949 // Add operator candidates that are member functions. 9950 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 9951 9952 // Add candidates from ADL. 9953 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 9954 OpLoc, llvm::makeArrayRef(Args, NumArgs), 9955 /*ExplicitTemplateArgs*/ 0, 9956 CandidateSet); 9957 9958 // Add builtin operator candidates. 9959 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 9960 9961 bool HadMultipleCandidates = (CandidateSet.size() > 1); 9962 9963 // Perform overload resolution. 9964 OverloadCandidateSet::iterator Best; 9965 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 9966 case OR_Success: { 9967 // We found a built-in operator or an overloaded operator. 9968 FunctionDecl *FnDecl = Best->Function; 9969 9970 if (FnDecl) { 9971 // We matched an overloaded operator. Build a call to that 9972 // operator. 9973 9974 MarkFunctionReferenced(OpLoc, FnDecl); 9975 9976 // Convert the arguments. 9977 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 9978 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 9979 9980 ExprResult InputRes = 9981 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 9982 Best->FoundDecl, Method); 9983 if (InputRes.isInvalid()) 9984 return ExprError(); 9985 Input = InputRes.take(); 9986 } else { 9987 // Convert the arguments. 9988 ExprResult InputInit 9989 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 9990 Context, 9991 FnDecl->getParamDecl(0)), 9992 SourceLocation(), 9993 Input); 9994 if (InputInit.isInvalid()) 9995 return ExprError(); 9996 Input = InputInit.take(); 9997 } 9998 9999 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10000 10001 // Determine the result type. 10002 QualType ResultTy = FnDecl->getResultType(); 10003 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10004 ResultTy = ResultTy.getNonLValueExprType(Context); 10005 10006 // Build the actual expression node. 10007 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10008 HadMultipleCandidates, OpLoc); 10009 if (FnExpr.isInvalid()) 10010 return ExprError(); 10011 10012 Args[0] = Input; 10013 CallExpr *TheCall = 10014 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10015 llvm::makeArrayRef(Args, NumArgs), 10016 ResultTy, VK, OpLoc); 10017 10018 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10019 FnDecl)) 10020 return ExprError(); 10021 10022 return MaybeBindToTemporary(TheCall); 10023 } else { 10024 // We matched a built-in operator. Convert the arguments, then 10025 // break out so that we will build the appropriate built-in 10026 // operator node. 10027 ExprResult InputRes = 10028 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10029 Best->Conversions[0], AA_Passing); 10030 if (InputRes.isInvalid()) 10031 return ExprError(); 10032 Input = InputRes.take(); 10033 break; 10034 } 10035 } 10036 10037 case OR_No_Viable_Function: 10038 // This is an erroneous use of an operator which can be overloaded by 10039 // a non-member function. Check for non-member operators which were 10040 // defined too late to be candidates. 10041 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, 10042 llvm::makeArrayRef(Args, NumArgs))) 10043 // FIXME: Recover by calling the found function. 10044 return ExprError(); 10045 10046 // No viable function; fall through to handling this as a 10047 // built-in operator, which will produce an error message for us. 10048 break; 10049 10050 case OR_Ambiguous: 10051 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10052 << UnaryOperator::getOpcodeStr(Opc) 10053 << Input->getType() 10054 << Input->getSourceRange(); 10055 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10056 llvm::makeArrayRef(Args, NumArgs), 10057 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10058 return ExprError(); 10059 10060 case OR_Deleted: 10061 Diag(OpLoc, diag::err_ovl_deleted_oper) 10062 << Best->Function->isDeleted() 10063 << UnaryOperator::getOpcodeStr(Opc) 10064 << getDeletedOrUnavailableSuffix(Best->Function) 10065 << Input->getSourceRange(); 10066 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10067 llvm::makeArrayRef(Args, NumArgs), 10068 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10069 return ExprError(); 10070 } 10071 10072 // Either we found no viable overloaded operator or we matched a 10073 // built-in operator. In either case, fall through to trying to 10074 // build a built-in operation. 10075 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10076} 10077 10078/// \brief Create a binary operation that may resolve to an overloaded 10079/// operator. 10080/// 10081/// \param OpLoc The location of the operator itself (e.g., '+'). 10082/// 10083/// \param OpcIn The BinaryOperator::Opcode that describes this 10084/// operator. 10085/// 10086/// \param Fns The set of non-member functions that will be 10087/// considered by overload resolution. The caller needs to build this 10088/// set based on the context using, e.g., 10089/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10090/// set should not contain any member functions; those will be added 10091/// by CreateOverloadedBinOp(). 10092/// 10093/// \param LHS Left-hand argument. 10094/// \param RHS Right-hand argument. 10095ExprResult 10096Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10097 unsigned OpcIn, 10098 const UnresolvedSetImpl &Fns, 10099 Expr *LHS, Expr *RHS) { 10100 Expr *Args[2] = { LHS, RHS }; 10101 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10102 10103 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10104 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10105 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10106 10107 // If either side is type-dependent, create an appropriate dependent 10108 // expression. 10109 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10110 if (Fns.empty()) { 10111 // If there are no functions to store, just build a dependent 10112 // BinaryOperator or CompoundAssignment. 10113 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10114 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10115 Context.DependentTy, 10116 VK_RValue, OK_Ordinary, 10117 OpLoc)); 10118 10119 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10120 Context.DependentTy, 10121 VK_LValue, 10122 OK_Ordinary, 10123 Context.DependentTy, 10124 Context.DependentTy, 10125 OpLoc)); 10126 } 10127 10128 // FIXME: save results of ADL from here? 10129 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10130 // TODO: provide better source location info in DNLoc component. 10131 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10132 UnresolvedLookupExpr *Fn 10133 = UnresolvedLookupExpr::Create(Context, NamingClass, 10134 NestedNameSpecifierLoc(), OpNameInfo, 10135 /*ADL*/ true, IsOverloaded(Fns), 10136 Fns.begin(), Fns.end()); 10137 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 10138 Args, 10139 Context.DependentTy, 10140 VK_RValue, 10141 OpLoc)); 10142 } 10143 10144 // Always do placeholder-like conversions on the RHS. 10145 if (checkPlaceholderForOverload(*this, Args[1])) 10146 return ExprError(); 10147 10148 // Do placeholder-like conversion on the LHS; note that we should 10149 // not get here with a PseudoObject LHS. 10150 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10151 if (checkPlaceholderForOverload(*this, Args[0])) 10152 return ExprError(); 10153 10154 // If this is the assignment operator, we only perform overload resolution 10155 // if the left-hand side is a class or enumeration type. This is actually 10156 // a hack. The standard requires that we do overload resolution between the 10157 // various built-in candidates, but as DR507 points out, this can lead to 10158 // problems. So we do it this way, which pretty much follows what GCC does. 10159 // Note that we go the traditional code path for compound assignment forms. 10160 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10161 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10162 10163 // If this is the .* operator, which is not overloadable, just 10164 // create a built-in binary operator. 10165 if (Opc == BO_PtrMemD) 10166 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10167 10168 // Build an empty overload set. 10169 OverloadCandidateSet CandidateSet(OpLoc); 10170 10171 // Add the candidates from the given function set. 10172 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10173 10174 // Add operator candidates that are member functions. 10175 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10176 10177 // Add candidates from ADL. 10178 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10179 OpLoc, Args, 10180 /*ExplicitTemplateArgs*/ 0, 10181 CandidateSet); 10182 10183 // Add builtin operator candidates. 10184 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10185 10186 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10187 10188 // Perform overload resolution. 10189 OverloadCandidateSet::iterator Best; 10190 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10191 case OR_Success: { 10192 // We found a built-in operator or an overloaded operator. 10193 FunctionDecl *FnDecl = Best->Function; 10194 10195 if (FnDecl) { 10196 // We matched an overloaded operator. Build a call to that 10197 // operator. 10198 10199 MarkFunctionReferenced(OpLoc, FnDecl); 10200 10201 // Convert the arguments. 10202 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10203 // Best->Access is only meaningful for class members. 10204 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10205 10206 ExprResult Arg1 = 10207 PerformCopyInitialization( 10208 InitializedEntity::InitializeParameter(Context, 10209 FnDecl->getParamDecl(0)), 10210 SourceLocation(), Owned(Args[1])); 10211 if (Arg1.isInvalid()) 10212 return ExprError(); 10213 10214 ExprResult Arg0 = 10215 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10216 Best->FoundDecl, Method); 10217 if (Arg0.isInvalid()) 10218 return ExprError(); 10219 Args[0] = Arg0.takeAs<Expr>(); 10220 Args[1] = RHS = Arg1.takeAs<Expr>(); 10221 } else { 10222 // Convert the arguments. 10223 ExprResult Arg0 = PerformCopyInitialization( 10224 InitializedEntity::InitializeParameter(Context, 10225 FnDecl->getParamDecl(0)), 10226 SourceLocation(), Owned(Args[0])); 10227 if (Arg0.isInvalid()) 10228 return ExprError(); 10229 10230 ExprResult Arg1 = 10231 PerformCopyInitialization( 10232 InitializedEntity::InitializeParameter(Context, 10233 FnDecl->getParamDecl(1)), 10234 SourceLocation(), Owned(Args[1])); 10235 if (Arg1.isInvalid()) 10236 return ExprError(); 10237 Args[0] = LHS = Arg0.takeAs<Expr>(); 10238 Args[1] = RHS = Arg1.takeAs<Expr>(); 10239 } 10240 10241 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10242 10243 // Determine the result type. 10244 QualType ResultTy = FnDecl->getResultType(); 10245 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10246 ResultTy = ResultTy.getNonLValueExprType(Context); 10247 10248 // Build the actual expression node. 10249 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10250 HadMultipleCandidates, OpLoc); 10251 if (FnExpr.isInvalid()) 10252 return ExprError(); 10253 10254 CXXOperatorCallExpr *TheCall = 10255 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10256 Args, ResultTy, VK, OpLoc); 10257 10258 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10259 FnDecl)) 10260 return ExprError(); 10261 10262 return MaybeBindToTemporary(TheCall); 10263 } else { 10264 // We matched a built-in operator. Convert the arguments, then 10265 // break out so that we will build the appropriate built-in 10266 // operator node. 10267 ExprResult ArgsRes0 = 10268 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10269 Best->Conversions[0], AA_Passing); 10270 if (ArgsRes0.isInvalid()) 10271 return ExprError(); 10272 Args[0] = ArgsRes0.take(); 10273 10274 ExprResult ArgsRes1 = 10275 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10276 Best->Conversions[1], AA_Passing); 10277 if (ArgsRes1.isInvalid()) 10278 return ExprError(); 10279 Args[1] = ArgsRes1.take(); 10280 break; 10281 } 10282 } 10283 10284 case OR_No_Viable_Function: { 10285 // C++ [over.match.oper]p9: 10286 // If the operator is the operator , [...] and there are no 10287 // viable functions, then the operator is assumed to be the 10288 // built-in operator and interpreted according to clause 5. 10289 if (Opc == BO_Comma) 10290 break; 10291 10292 // For class as left operand for assignment or compound assigment 10293 // operator do not fall through to handling in built-in, but report that 10294 // no overloaded assignment operator found 10295 ExprResult Result = ExprError(); 10296 if (Args[0]->getType()->isRecordType() && 10297 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10298 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10299 << BinaryOperator::getOpcodeStr(Opc) 10300 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10301 } else { 10302 // This is an erroneous use of an operator which can be overloaded by 10303 // a non-member function. Check for non-member operators which were 10304 // defined too late to be candidates. 10305 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10306 // FIXME: Recover by calling the found function. 10307 return ExprError(); 10308 10309 // No viable function; try to create a built-in operation, which will 10310 // produce an error. Then, show the non-viable candidates. 10311 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10312 } 10313 assert(Result.isInvalid() && 10314 "C++ binary operator overloading is missing candidates!"); 10315 if (Result.isInvalid()) 10316 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10317 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10318 return Result; 10319 } 10320 10321 case OR_Ambiguous: 10322 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10323 << BinaryOperator::getOpcodeStr(Opc) 10324 << Args[0]->getType() << Args[1]->getType() 10325 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10326 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10327 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10328 return ExprError(); 10329 10330 case OR_Deleted: 10331 if (isImplicitlyDeleted(Best->Function)) { 10332 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10333 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10334 << getSpecialMember(Method) 10335 << BinaryOperator::getOpcodeStr(Opc) 10336 << getDeletedOrUnavailableSuffix(Best->Function); 10337 10338 if (getSpecialMember(Method) != CXXInvalid) { 10339 // The user probably meant to call this special member. Just 10340 // explain why it's deleted. 10341 NoteDeletedFunction(Method); 10342 return ExprError(); 10343 } 10344 } else { 10345 Diag(OpLoc, diag::err_ovl_deleted_oper) 10346 << Best->Function->isDeleted() 10347 << BinaryOperator::getOpcodeStr(Opc) 10348 << getDeletedOrUnavailableSuffix(Best->Function) 10349 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10350 } 10351 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10352 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10353 return ExprError(); 10354 } 10355 10356 // We matched a built-in operator; build it. 10357 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10358} 10359 10360ExprResult 10361Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10362 SourceLocation RLoc, 10363 Expr *Base, Expr *Idx) { 10364 Expr *Args[2] = { Base, Idx }; 10365 DeclarationName OpName = 10366 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10367 10368 // If either side is type-dependent, create an appropriate dependent 10369 // expression. 10370 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10371 10372 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10373 // CHECKME: no 'operator' keyword? 10374 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10375 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10376 UnresolvedLookupExpr *Fn 10377 = UnresolvedLookupExpr::Create(Context, NamingClass, 10378 NestedNameSpecifierLoc(), OpNameInfo, 10379 /*ADL*/ true, /*Overloaded*/ false, 10380 UnresolvedSetIterator(), 10381 UnresolvedSetIterator()); 10382 // Can't add any actual overloads yet 10383 10384 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10385 Args, 10386 Context.DependentTy, 10387 VK_RValue, 10388 RLoc)); 10389 } 10390 10391 // Handle placeholders on both operands. 10392 if (checkPlaceholderForOverload(*this, Args[0])) 10393 return ExprError(); 10394 if (checkPlaceholderForOverload(*this, Args[1])) 10395 return ExprError(); 10396 10397 // Build an empty overload set. 10398 OverloadCandidateSet CandidateSet(LLoc); 10399 10400 // Subscript can only be overloaded as a member function. 10401 10402 // Add operator candidates that are member functions. 10403 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10404 10405 // Add builtin operator candidates. 10406 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10407 10408 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10409 10410 // Perform overload resolution. 10411 OverloadCandidateSet::iterator Best; 10412 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10413 case OR_Success: { 10414 // We found a built-in operator or an overloaded operator. 10415 FunctionDecl *FnDecl = Best->Function; 10416 10417 if (FnDecl) { 10418 // We matched an overloaded operator. Build a call to that 10419 // operator. 10420 10421 MarkFunctionReferenced(LLoc, FnDecl); 10422 10423 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10424 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 10425 10426 // Convert the arguments. 10427 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10428 ExprResult Arg0 = 10429 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10430 Best->FoundDecl, Method); 10431 if (Arg0.isInvalid()) 10432 return ExprError(); 10433 Args[0] = Arg0.take(); 10434 10435 // Convert the arguments. 10436 ExprResult InputInit 10437 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10438 Context, 10439 FnDecl->getParamDecl(0)), 10440 SourceLocation(), 10441 Owned(Args[1])); 10442 if (InputInit.isInvalid()) 10443 return ExprError(); 10444 10445 Args[1] = InputInit.takeAs<Expr>(); 10446 10447 // Determine the result type 10448 QualType ResultTy = FnDecl->getResultType(); 10449 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10450 ResultTy = ResultTy.getNonLValueExprType(Context); 10451 10452 // Build the actual expression node. 10453 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10454 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10455 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10456 HadMultipleCandidates, 10457 OpLocInfo.getLoc(), 10458 OpLocInfo.getInfo()); 10459 if (FnExpr.isInvalid()) 10460 return ExprError(); 10461 10462 CXXOperatorCallExpr *TheCall = 10463 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10464 FnExpr.take(), Args, 10465 ResultTy, VK, RLoc); 10466 10467 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10468 FnDecl)) 10469 return ExprError(); 10470 10471 return MaybeBindToTemporary(TheCall); 10472 } else { 10473 // We matched a built-in operator. Convert the arguments, then 10474 // break out so that we will build the appropriate built-in 10475 // operator node. 10476 ExprResult ArgsRes0 = 10477 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10478 Best->Conversions[0], AA_Passing); 10479 if (ArgsRes0.isInvalid()) 10480 return ExprError(); 10481 Args[0] = ArgsRes0.take(); 10482 10483 ExprResult ArgsRes1 = 10484 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10485 Best->Conversions[1], AA_Passing); 10486 if (ArgsRes1.isInvalid()) 10487 return ExprError(); 10488 Args[1] = ArgsRes1.take(); 10489 10490 break; 10491 } 10492 } 10493 10494 case OR_No_Viable_Function: { 10495 if (CandidateSet.empty()) 10496 Diag(LLoc, diag::err_ovl_no_oper) 10497 << Args[0]->getType() << /*subscript*/ 0 10498 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10499 else 10500 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10501 << Args[0]->getType() 10502 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10503 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10504 "[]", LLoc); 10505 return ExprError(); 10506 } 10507 10508 case OR_Ambiguous: 10509 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10510 << "[]" 10511 << Args[0]->getType() << Args[1]->getType() 10512 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10513 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10514 "[]", LLoc); 10515 return ExprError(); 10516 10517 case OR_Deleted: 10518 Diag(LLoc, diag::err_ovl_deleted_oper) 10519 << Best->Function->isDeleted() << "[]" 10520 << getDeletedOrUnavailableSuffix(Best->Function) 10521 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10522 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10523 "[]", LLoc); 10524 return ExprError(); 10525 } 10526 10527 // We matched a built-in operator; build it. 10528 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10529} 10530 10531/// BuildCallToMemberFunction - Build a call to a member 10532/// function. MemExpr is the expression that refers to the member 10533/// function (and includes the object parameter), Args/NumArgs are the 10534/// arguments to the function call (not including the object 10535/// parameter). The caller needs to validate that the member 10536/// expression refers to a non-static member function or an overloaded 10537/// member function. 10538ExprResult 10539Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10540 SourceLocation LParenLoc, Expr **Args, 10541 unsigned NumArgs, SourceLocation RParenLoc) { 10542 assert(MemExprE->getType() == Context.BoundMemberTy || 10543 MemExprE->getType() == Context.OverloadTy); 10544 10545 // Dig out the member expression. This holds both the object 10546 // argument and the member function we're referring to. 10547 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10548 10549 // Determine whether this is a call to a pointer-to-member function. 10550 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10551 assert(op->getType() == Context.BoundMemberTy); 10552 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10553 10554 QualType fnType = 10555 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10556 10557 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10558 QualType resultType = proto->getCallResultType(Context); 10559 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10560 10561 // Check that the object type isn't more qualified than the 10562 // member function we're calling. 10563 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10564 10565 QualType objectType = op->getLHS()->getType(); 10566 if (op->getOpcode() == BO_PtrMemI) 10567 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10568 Qualifiers objectQuals = objectType.getQualifiers(); 10569 10570 Qualifiers difference = objectQuals - funcQuals; 10571 difference.removeObjCGCAttr(); 10572 difference.removeAddressSpace(); 10573 if (difference) { 10574 std::string qualsString = difference.getAsString(); 10575 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10576 << fnType.getUnqualifiedType() 10577 << qualsString 10578 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10579 } 10580 10581 CXXMemberCallExpr *call 10582 = new (Context) CXXMemberCallExpr(Context, MemExprE, 10583 llvm::makeArrayRef(Args, NumArgs), 10584 resultType, valueKind, RParenLoc); 10585 10586 if (CheckCallReturnType(proto->getResultType(), 10587 op->getRHS()->getLocStart(), 10588 call, 0)) 10589 return ExprError(); 10590 10591 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 10592 return ExprError(); 10593 10594 return MaybeBindToTemporary(call); 10595 } 10596 10597 UnbridgedCastsSet UnbridgedCasts; 10598 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10599 return ExprError(); 10600 10601 MemberExpr *MemExpr; 10602 CXXMethodDecl *Method = 0; 10603 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10604 NestedNameSpecifier *Qualifier = 0; 10605 if (isa<MemberExpr>(NakedMemExpr)) { 10606 MemExpr = cast<MemberExpr>(NakedMemExpr); 10607 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10608 FoundDecl = MemExpr->getFoundDecl(); 10609 Qualifier = MemExpr->getQualifier(); 10610 UnbridgedCasts.restore(); 10611 } else { 10612 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10613 Qualifier = UnresExpr->getQualifier(); 10614 10615 QualType ObjectType = UnresExpr->getBaseType(); 10616 Expr::Classification ObjectClassification 10617 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10618 : UnresExpr->getBase()->Classify(Context); 10619 10620 // Add overload candidates 10621 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10622 10623 // FIXME: avoid copy. 10624 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10625 if (UnresExpr->hasExplicitTemplateArgs()) { 10626 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10627 TemplateArgs = &TemplateArgsBuffer; 10628 } 10629 10630 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10631 E = UnresExpr->decls_end(); I != E; ++I) { 10632 10633 NamedDecl *Func = *I; 10634 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10635 if (isa<UsingShadowDecl>(Func)) 10636 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10637 10638 10639 // Microsoft supports direct constructor calls. 10640 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10641 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10642 llvm::makeArrayRef(Args, NumArgs), CandidateSet); 10643 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10644 // If explicit template arguments were provided, we can't call a 10645 // non-template member function. 10646 if (TemplateArgs) 10647 continue; 10648 10649 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10650 ObjectClassification, 10651 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10652 /*SuppressUserConversions=*/false); 10653 } else { 10654 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10655 I.getPair(), ActingDC, TemplateArgs, 10656 ObjectType, ObjectClassification, 10657 llvm::makeArrayRef(Args, NumArgs), 10658 CandidateSet, 10659 /*SuppressUsedConversions=*/false); 10660 } 10661 } 10662 10663 DeclarationName DeclName = UnresExpr->getMemberName(); 10664 10665 UnbridgedCasts.restore(); 10666 10667 OverloadCandidateSet::iterator Best; 10668 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10669 Best)) { 10670 case OR_Success: 10671 Method = cast<CXXMethodDecl>(Best->Function); 10672 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method); 10673 FoundDecl = Best->FoundDecl; 10674 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10675 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 10676 break; 10677 10678 case OR_No_Viable_Function: 10679 Diag(UnresExpr->getMemberLoc(), 10680 diag::err_ovl_no_viable_member_function_in_call) 10681 << DeclName << MemExprE->getSourceRange(); 10682 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10683 llvm::makeArrayRef(Args, NumArgs)); 10684 // FIXME: Leaking incoming expressions! 10685 return ExprError(); 10686 10687 case OR_Ambiguous: 10688 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10689 << DeclName << MemExprE->getSourceRange(); 10690 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10691 llvm::makeArrayRef(Args, NumArgs)); 10692 // FIXME: Leaking incoming expressions! 10693 return ExprError(); 10694 10695 case OR_Deleted: 10696 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10697 << Best->Function->isDeleted() 10698 << DeclName 10699 << getDeletedOrUnavailableSuffix(Best->Function) 10700 << MemExprE->getSourceRange(); 10701 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10702 llvm::makeArrayRef(Args, NumArgs)); 10703 // FIXME: Leaking incoming expressions! 10704 return ExprError(); 10705 } 10706 10707 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 10708 10709 // If overload resolution picked a static member, build a 10710 // non-member call based on that function. 10711 if (Method->isStatic()) { 10712 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 10713 Args, NumArgs, RParenLoc); 10714 } 10715 10716 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 10717 } 10718 10719 QualType ResultType = Method->getResultType(); 10720 ExprValueKind VK = Expr::getValueKindForType(ResultType); 10721 ResultType = ResultType.getNonLValueExprType(Context); 10722 10723 assert(Method && "Member call to something that isn't a method?"); 10724 CXXMemberCallExpr *TheCall = 10725 new (Context) CXXMemberCallExpr(Context, MemExprE, 10726 llvm::makeArrayRef(Args, NumArgs), 10727 ResultType, VK, RParenLoc); 10728 10729 // Check for a valid return type. 10730 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 10731 TheCall, Method)) 10732 return ExprError(); 10733 10734 // Convert the object argument (for a non-static member function call). 10735 // We only need to do this if there was actually an overload; otherwise 10736 // it was done at lookup. 10737 if (!Method->isStatic()) { 10738 ExprResult ObjectArg = 10739 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 10740 FoundDecl, Method); 10741 if (ObjectArg.isInvalid()) 10742 return ExprError(); 10743 MemExpr->setBase(ObjectArg.take()); 10744 } 10745 10746 // Convert the rest of the arguments 10747 const FunctionProtoType *Proto = 10748 Method->getType()->getAs<FunctionProtoType>(); 10749 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 10750 RParenLoc)) 10751 return ExprError(); 10752 10753 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 10754 10755 if (CheckFunctionCall(Method, TheCall, Proto)) 10756 return ExprError(); 10757 10758 if ((isa<CXXConstructorDecl>(CurContext) || 10759 isa<CXXDestructorDecl>(CurContext)) && 10760 TheCall->getMethodDecl()->isPure()) { 10761 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 10762 10763 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 10764 Diag(MemExpr->getLocStart(), 10765 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 10766 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 10767 << MD->getParent()->getDeclName(); 10768 10769 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 10770 } 10771 } 10772 return MaybeBindToTemporary(TheCall); 10773} 10774 10775/// BuildCallToObjectOfClassType - Build a call to an object of class 10776/// type (C++ [over.call.object]), which can end up invoking an 10777/// overloaded function call operator (@c operator()) or performing a 10778/// user-defined conversion on the object argument. 10779ExprResult 10780Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 10781 SourceLocation LParenLoc, 10782 Expr **Args, unsigned NumArgs, 10783 SourceLocation RParenLoc) { 10784 if (checkPlaceholderForOverload(*this, Obj)) 10785 return ExprError(); 10786 ExprResult Object = Owned(Obj); 10787 10788 UnbridgedCastsSet UnbridgedCasts; 10789 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10790 return ExprError(); 10791 10792 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 10793 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 10794 10795 // C++ [over.call.object]p1: 10796 // If the primary-expression E in the function call syntax 10797 // evaluates to a class object of type "cv T", then the set of 10798 // candidate functions includes at least the function call 10799 // operators of T. The function call operators of T are obtained by 10800 // ordinary lookup of the name operator() in the context of 10801 // (E).operator(). 10802 OverloadCandidateSet CandidateSet(LParenLoc); 10803 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 10804 10805 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 10806 diag::err_incomplete_object_call, Object.get())) 10807 return true; 10808 10809 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 10810 LookupQualifiedName(R, Record->getDecl()); 10811 R.suppressDiagnostics(); 10812 10813 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 10814 Oper != OperEnd; ++Oper) { 10815 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 10816 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 10817 /*SuppressUserConversions=*/ false); 10818 } 10819 10820 // C++ [over.call.object]p2: 10821 // In addition, for each (non-explicit in C++0x) conversion function 10822 // declared in T of the form 10823 // 10824 // operator conversion-type-id () cv-qualifier; 10825 // 10826 // where cv-qualifier is the same cv-qualification as, or a 10827 // greater cv-qualification than, cv, and where conversion-type-id 10828 // denotes the type "pointer to function of (P1,...,Pn) returning 10829 // R", or the type "reference to pointer to function of 10830 // (P1,...,Pn) returning R", or the type "reference to function 10831 // of (P1,...,Pn) returning R", a surrogate call function [...] 10832 // is also considered as a candidate function. Similarly, 10833 // surrogate call functions are added to the set of candidate 10834 // functions for each conversion function declared in an 10835 // accessible base class provided the function is not hidden 10836 // within T by another intervening declaration. 10837 const UnresolvedSetImpl *Conversions 10838 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 10839 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 10840 E = Conversions->end(); I != E; ++I) { 10841 NamedDecl *D = *I; 10842 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 10843 if (isa<UsingShadowDecl>(D)) 10844 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 10845 10846 // Skip over templated conversion functions; they aren't 10847 // surrogates. 10848 if (isa<FunctionTemplateDecl>(D)) 10849 continue; 10850 10851 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 10852 if (!Conv->isExplicit()) { 10853 // Strip the reference type (if any) and then the pointer type (if 10854 // any) to get down to what might be a function type. 10855 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 10856 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10857 ConvType = ConvPtrType->getPointeeType(); 10858 10859 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 10860 { 10861 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 10862 Object.get(), llvm::makeArrayRef(Args, NumArgs), 10863 CandidateSet); 10864 } 10865 } 10866 } 10867 10868 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10869 10870 // Perform overload resolution. 10871 OverloadCandidateSet::iterator Best; 10872 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 10873 Best)) { 10874 case OR_Success: 10875 // Overload resolution succeeded; we'll build the appropriate call 10876 // below. 10877 break; 10878 10879 case OR_No_Viable_Function: 10880 if (CandidateSet.empty()) 10881 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 10882 << Object.get()->getType() << /*call*/ 1 10883 << Object.get()->getSourceRange(); 10884 else 10885 Diag(Object.get()->getLocStart(), 10886 diag::err_ovl_no_viable_object_call) 10887 << Object.get()->getType() << Object.get()->getSourceRange(); 10888 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10889 llvm::makeArrayRef(Args, NumArgs)); 10890 break; 10891 10892 case OR_Ambiguous: 10893 Diag(Object.get()->getLocStart(), 10894 diag::err_ovl_ambiguous_object_call) 10895 << Object.get()->getType() << Object.get()->getSourceRange(); 10896 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10897 llvm::makeArrayRef(Args, NumArgs)); 10898 break; 10899 10900 case OR_Deleted: 10901 Diag(Object.get()->getLocStart(), 10902 diag::err_ovl_deleted_object_call) 10903 << Best->Function->isDeleted() 10904 << Object.get()->getType() 10905 << getDeletedOrUnavailableSuffix(Best->Function) 10906 << Object.get()->getSourceRange(); 10907 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10908 llvm::makeArrayRef(Args, NumArgs)); 10909 break; 10910 } 10911 10912 if (Best == CandidateSet.end()) 10913 return true; 10914 10915 UnbridgedCasts.restore(); 10916 10917 if (Best->Function == 0) { 10918 // Since there is no function declaration, this is one of the 10919 // surrogate candidates. Dig out the conversion function. 10920 CXXConversionDecl *Conv 10921 = cast<CXXConversionDecl>( 10922 Best->Conversions[0].UserDefined.ConversionFunction); 10923 10924 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10925 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10926 10927 // We selected one of the surrogate functions that converts the 10928 // object parameter to a function pointer. Perform the conversion 10929 // on the object argument, then let ActOnCallExpr finish the job. 10930 10931 // Create an implicit member expr to refer to the conversion operator. 10932 // and then call it. 10933 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 10934 Conv, HadMultipleCandidates); 10935 if (Call.isInvalid()) 10936 return ExprError(); 10937 // Record usage of conversion in an implicit cast. 10938 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 10939 CK_UserDefinedConversion, 10940 Call.get(), 0, VK_RValue)); 10941 10942 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 10943 RParenLoc); 10944 } 10945 10946 MarkFunctionReferenced(LParenLoc, Best->Function); 10947 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10948 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10949 10950 // We found an overloaded operator(). Build a CXXOperatorCallExpr 10951 // that calls this method, using Object for the implicit object 10952 // parameter and passing along the remaining arguments. 10953 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10954 const FunctionProtoType *Proto = 10955 Method->getType()->getAs<FunctionProtoType>(); 10956 10957 unsigned NumArgsInProto = Proto->getNumArgs(); 10958 unsigned NumArgsToCheck = NumArgs; 10959 10960 // Build the full argument list for the method call (the 10961 // implicit object parameter is placed at the beginning of the 10962 // list). 10963 Expr **MethodArgs; 10964 if (NumArgs < NumArgsInProto) { 10965 NumArgsToCheck = NumArgsInProto; 10966 MethodArgs = new Expr*[NumArgsInProto + 1]; 10967 } else { 10968 MethodArgs = new Expr*[NumArgs + 1]; 10969 } 10970 MethodArgs[0] = Object.get(); 10971 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 10972 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 10973 10974 DeclarationNameInfo OpLocInfo( 10975 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 10976 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 10977 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, 10978 HadMultipleCandidates, 10979 OpLocInfo.getLoc(), 10980 OpLocInfo.getInfo()); 10981 if (NewFn.isInvalid()) 10982 return true; 10983 10984 // Once we've built TheCall, all of the expressions are properly 10985 // owned. 10986 QualType ResultTy = Method->getResultType(); 10987 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10988 ResultTy = ResultTy.getNonLValueExprType(Context); 10989 10990 CXXOperatorCallExpr *TheCall = 10991 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 10992 llvm::makeArrayRef(MethodArgs, NumArgs+1), 10993 ResultTy, VK, RParenLoc); 10994 delete [] MethodArgs; 10995 10996 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 10997 Method)) 10998 return true; 10999 11000 // We may have default arguments. If so, we need to allocate more 11001 // slots in the call for them. 11002 if (NumArgs < NumArgsInProto) 11003 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11004 else if (NumArgs > NumArgsInProto) 11005 NumArgsToCheck = NumArgsInProto; 11006 11007 bool IsError = false; 11008 11009 // Initialize the implicit object parameter. 11010 ExprResult ObjRes = 11011 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11012 Best->FoundDecl, Method); 11013 if (ObjRes.isInvalid()) 11014 IsError = true; 11015 else 11016 Object = ObjRes; 11017 TheCall->setArg(0, Object.take()); 11018 11019 // Check the argument types. 11020 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11021 Expr *Arg; 11022 if (i < NumArgs) { 11023 Arg = Args[i]; 11024 11025 // Pass the argument. 11026 11027 ExprResult InputInit 11028 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11029 Context, 11030 Method->getParamDecl(i)), 11031 SourceLocation(), Arg); 11032 11033 IsError |= InputInit.isInvalid(); 11034 Arg = InputInit.takeAs<Expr>(); 11035 } else { 11036 ExprResult DefArg 11037 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11038 if (DefArg.isInvalid()) { 11039 IsError = true; 11040 break; 11041 } 11042 11043 Arg = DefArg.takeAs<Expr>(); 11044 } 11045 11046 TheCall->setArg(i + 1, Arg); 11047 } 11048 11049 // If this is a variadic call, handle args passed through "...". 11050 if (Proto->isVariadic()) { 11051 // Promote the arguments (C99 6.5.2.2p7). 11052 for (unsigned i = NumArgsInProto; i < NumArgs; i++) { 11053 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11054 IsError |= Arg.isInvalid(); 11055 TheCall->setArg(i + 1, Arg.take()); 11056 } 11057 } 11058 11059 if (IsError) return true; 11060 11061 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 11062 11063 if (CheckFunctionCall(Method, TheCall, Proto)) 11064 return true; 11065 11066 return MaybeBindToTemporary(TheCall); 11067} 11068 11069/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11070/// (if one exists), where @c Base is an expression of class type and 11071/// @c Member is the name of the member we're trying to find. 11072ExprResult 11073Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11074 assert(Base->getType()->isRecordType() && 11075 "left-hand side must have class type"); 11076 11077 if (checkPlaceholderForOverload(*this, Base)) 11078 return ExprError(); 11079 11080 SourceLocation Loc = Base->getExprLoc(); 11081 11082 // C++ [over.ref]p1: 11083 // 11084 // [...] An expression x->m is interpreted as (x.operator->())->m 11085 // for a class object x of type T if T::operator->() exists and if 11086 // the operator is selected as the best match function by the 11087 // overload resolution mechanism (13.3). 11088 DeclarationName OpName = 11089 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11090 OverloadCandidateSet CandidateSet(Loc); 11091 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11092 11093 if (RequireCompleteType(Loc, Base->getType(), 11094 diag::err_typecheck_incomplete_tag, Base)) 11095 return ExprError(); 11096 11097 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11098 LookupQualifiedName(R, BaseRecord->getDecl()); 11099 R.suppressDiagnostics(); 11100 11101 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11102 Oper != OperEnd; ++Oper) { 11103 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11104 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 11105 } 11106 11107 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11108 11109 // Perform overload resolution. 11110 OverloadCandidateSet::iterator Best; 11111 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11112 case OR_Success: 11113 // Overload resolution succeeded; we'll build the call below. 11114 break; 11115 11116 case OR_No_Viable_Function: 11117 if (CandidateSet.empty()) 11118 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11119 << Base->getType() << Base->getSourceRange(); 11120 else 11121 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11122 << "operator->" << Base->getSourceRange(); 11123 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11124 return ExprError(); 11125 11126 case OR_Ambiguous: 11127 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11128 << "->" << Base->getType() << Base->getSourceRange(); 11129 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11130 return ExprError(); 11131 11132 case OR_Deleted: 11133 Diag(OpLoc, diag::err_ovl_deleted_oper) 11134 << Best->Function->isDeleted() 11135 << "->" 11136 << getDeletedOrUnavailableSuffix(Best->Function) 11137 << Base->getSourceRange(); 11138 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11139 return ExprError(); 11140 } 11141 11142 MarkFunctionReferenced(OpLoc, Best->Function); 11143 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11144 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 11145 11146 // Convert the object parameter. 11147 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11148 ExprResult BaseResult = 11149 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11150 Best->FoundDecl, Method); 11151 if (BaseResult.isInvalid()) 11152 return ExprError(); 11153 Base = BaseResult.take(); 11154 11155 // Build the operator call. 11156 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, 11157 HadMultipleCandidates, OpLoc); 11158 if (FnExpr.isInvalid()) 11159 return ExprError(); 11160 11161 QualType ResultTy = Method->getResultType(); 11162 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11163 ResultTy = ResultTy.getNonLValueExprType(Context); 11164 CXXOperatorCallExpr *TheCall = 11165 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11166 Base, ResultTy, VK, OpLoc); 11167 11168 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11169 Method)) 11170 return ExprError(); 11171 11172 return MaybeBindToTemporary(TheCall); 11173} 11174 11175/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11176/// a literal operator described by the provided lookup results. 11177ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11178 DeclarationNameInfo &SuffixInfo, 11179 ArrayRef<Expr*> Args, 11180 SourceLocation LitEndLoc, 11181 TemplateArgumentListInfo *TemplateArgs) { 11182 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11183 11184 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11185 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11186 TemplateArgs); 11187 11188 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11189 11190 // Perform overload resolution. This will usually be trivial, but might need 11191 // to perform substitutions for a literal operator template. 11192 OverloadCandidateSet::iterator Best; 11193 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11194 case OR_Success: 11195 case OR_Deleted: 11196 break; 11197 11198 case OR_No_Viable_Function: 11199 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11200 << R.getLookupName(); 11201 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11202 return ExprError(); 11203 11204 case OR_Ambiguous: 11205 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11206 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11207 return ExprError(); 11208 } 11209 11210 FunctionDecl *FD = Best->Function; 11211 MarkFunctionReferenced(UDSuffixLoc, FD); 11212 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc); 11213 11214 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates, 11215 SuffixInfo.getLoc(), 11216 SuffixInfo.getInfo()); 11217 if (Fn.isInvalid()) 11218 return true; 11219 11220 // Check the argument types. This should almost always be a no-op, except 11221 // that array-to-pointer decay is applied to string literals. 11222 Expr *ConvArgs[2]; 11223 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 11224 ExprResult InputInit = PerformCopyInitialization( 11225 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11226 SourceLocation(), Args[ArgIdx]); 11227 if (InputInit.isInvalid()) 11228 return true; 11229 ConvArgs[ArgIdx] = InputInit.take(); 11230 } 11231 11232 QualType ResultTy = FD->getResultType(); 11233 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11234 ResultTy = ResultTy.getNonLValueExprType(Context); 11235 11236 UserDefinedLiteral *UDL = 11237 new (Context) UserDefinedLiteral(Context, Fn.take(), 11238 llvm::makeArrayRef(ConvArgs, Args.size()), 11239 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11240 11241 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11242 return ExprError(); 11243 11244 if (CheckFunctionCall(FD, UDL, NULL)) 11245 return ExprError(); 11246 11247 return MaybeBindToTemporary(UDL); 11248} 11249 11250/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11251/// given LookupResult is non-empty, it is assumed to describe a member which 11252/// will be invoked. Otherwise, the function will be found via argument 11253/// dependent lookup. 11254/// CallExpr is set to a valid expression and FRS_Success returned on success, 11255/// otherwise CallExpr is set to ExprError() and some non-success value 11256/// is returned. 11257Sema::ForRangeStatus 11258Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11259 SourceLocation RangeLoc, VarDecl *Decl, 11260 BeginEndFunction BEF, 11261 const DeclarationNameInfo &NameInfo, 11262 LookupResult &MemberLookup, 11263 OverloadCandidateSet *CandidateSet, 11264 Expr *Range, ExprResult *CallExpr) { 11265 CandidateSet->clear(); 11266 if (!MemberLookup.empty()) { 11267 ExprResult MemberRef = 11268 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11269 /*IsPtr=*/false, CXXScopeSpec(), 11270 /*TemplateKWLoc=*/SourceLocation(), 11271 /*FirstQualifierInScope=*/0, 11272 MemberLookup, 11273 /*TemplateArgs=*/0); 11274 if (MemberRef.isInvalid()) { 11275 *CallExpr = ExprError(); 11276 Diag(Range->getLocStart(), diag::note_in_for_range) 11277 << RangeLoc << BEF << Range->getType(); 11278 return FRS_DiagnosticIssued; 11279 } 11280 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0); 11281 if (CallExpr->isInvalid()) { 11282 *CallExpr = ExprError(); 11283 Diag(Range->getLocStart(), diag::note_in_for_range) 11284 << RangeLoc << BEF << Range->getType(); 11285 return FRS_DiagnosticIssued; 11286 } 11287 } else { 11288 UnresolvedSet<0> FoundNames; 11289 // C++11 [stmt.ranged]p1: For the purposes of this name lookup, namespace 11290 // std is an associated namespace. 11291 UnresolvedLookupExpr *Fn = 11292 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11293 NestedNameSpecifierLoc(), NameInfo, 11294 /*NeedsADL=*/true, /*Overloaded=*/false, 11295 FoundNames.begin(), FoundNames.end(), 11296 /*LookInStdNamespace=*/true); 11297 11298 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc, 11299 CandidateSet, CallExpr); 11300 if (CandidateSet->empty() || CandidateSetError) { 11301 *CallExpr = ExprError(); 11302 return FRS_NoViableFunction; 11303 } 11304 OverloadCandidateSet::iterator Best; 11305 OverloadingResult OverloadResult = 11306 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11307 11308 if (OverloadResult == OR_No_Viable_Function) { 11309 *CallExpr = ExprError(); 11310 return FRS_NoViableFunction; 11311 } 11312 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1, 11313 Loc, 0, CandidateSet, &Best, 11314 OverloadResult, 11315 /*AllowTypoCorrection=*/false); 11316 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11317 *CallExpr = ExprError(); 11318 Diag(Range->getLocStart(), diag::note_in_for_range) 11319 << RangeLoc << BEF << Range->getType(); 11320 return FRS_DiagnosticIssued; 11321 } 11322 } 11323 return FRS_Success; 11324} 11325 11326 11327/// FixOverloadedFunctionReference - E is an expression that refers to 11328/// a C++ overloaded function (possibly with some parentheses and 11329/// perhaps a '&' around it). We have resolved the overloaded function 11330/// to the function declaration Fn, so patch up the expression E to 11331/// refer (possibly indirectly) to Fn. Returns the new expr. 11332Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11333 FunctionDecl *Fn) { 11334 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11335 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11336 Found, Fn); 11337 if (SubExpr == PE->getSubExpr()) 11338 return PE; 11339 11340 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11341 } 11342 11343 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11344 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11345 Found, Fn); 11346 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11347 SubExpr->getType()) && 11348 "Implicit cast type cannot be determined from overload"); 11349 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11350 if (SubExpr == ICE->getSubExpr()) 11351 return ICE; 11352 11353 return ImplicitCastExpr::Create(Context, ICE->getType(), 11354 ICE->getCastKind(), 11355 SubExpr, 0, 11356 ICE->getValueKind()); 11357 } 11358 11359 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11360 assert(UnOp->getOpcode() == UO_AddrOf && 11361 "Can only take the address of an overloaded function"); 11362 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11363 if (Method->isStatic()) { 11364 // Do nothing: static member functions aren't any different 11365 // from non-member functions. 11366 } else { 11367 // Fix the sub expression, which really has to be an 11368 // UnresolvedLookupExpr holding an overloaded member function 11369 // or template. 11370 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11371 Found, Fn); 11372 if (SubExpr == UnOp->getSubExpr()) 11373 return UnOp; 11374 11375 assert(isa<DeclRefExpr>(SubExpr) 11376 && "fixed to something other than a decl ref"); 11377 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11378 && "fixed to a member ref with no nested name qualifier"); 11379 11380 // We have taken the address of a pointer to member 11381 // function. Perform the computation here so that we get the 11382 // appropriate pointer to member type. 11383 QualType ClassType 11384 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11385 QualType MemPtrType 11386 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11387 11388 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11389 VK_RValue, OK_Ordinary, 11390 UnOp->getOperatorLoc()); 11391 } 11392 } 11393 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11394 Found, Fn); 11395 if (SubExpr == UnOp->getSubExpr()) 11396 return UnOp; 11397 11398 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11399 Context.getPointerType(SubExpr->getType()), 11400 VK_RValue, OK_Ordinary, 11401 UnOp->getOperatorLoc()); 11402 } 11403 11404 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11405 // FIXME: avoid copy. 11406 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11407 if (ULE->hasExplicitTemplateArgs()) { 11408 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11409 TemplateArgs = &TemplateArgsBuffer; 11410 } 11411 11412 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11413 ULE->getQualifierLoc(), 11414 ULE->getTemplateKeywordLoc(), 11415 Fn, 11416 /*enclosing*/ false, // FIXME? 11417 ULE->getNameLoc(), 11418 Fn->getType(), 11419 VK_LValue, 11420 Found.getDecl(), 11421 TemplateArgs); 11422 MarkDeclRefReferenced(DRE); 11423 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11424 return DRE; 11425 } 11426 11427 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11428 // FIXME: avoid copy. 11429 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11430 if (MemExpr->hasExplicitTemplateArgs()) { 11431 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11432 TemplateArgs = &TemplateArgsBuffer; 11433 } 11434 11435 Expr *Base; 11436 11437 // If we're filling in a static method where we used to have an 11438 // implicit member access, rewrite to a simple decl ref. 11439 if (MemExpr->isImplicitAccess()) { 11440 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11441 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11442 MemExpr->getQualifierLoc(), 11443 MemExpr->getTemplateKeywordLoc(), 11444 Fn, 11445 /*enclosing*/ false, 11446 MemExpr->getMemberLoc(), 11447 Fn->getType(), 11448 VK_LValue, 11449 Found.getDecl(), 11450 TemplateArgs); 11451 MarkDeclRefReferenced(DRE); 11452 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11453 return DRE; 11454 } else { 11455 SourceLocation Loc = MemExpr->getMemberLoc(); 11456 if (MemExpr->getQualifier()) 11457 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11458 CheckCXXThisCapture(Loc); 11459 Base = new (Context) CXXThisExpr(Loc, 11460 MemExpr->getBaseType(), 11461 /*isImplicit=*/true); 11462 } 11463 } else 11464 Base = MemExpr->getBase(); 11465 11466 ExprValueKind valueKind; 11467 QualType type; 11468 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11469 valueKind = VK_LValue; 11470 type = Fn->getType(); 11471 } else { 11472 valueKind = VK_RValue; 11473 type = Context.BoundMemberTy; 11474 } 11475 11476 MemberExpr *ME = MemberExpr::Create(Context, Base, 11477 MemExpr->isArrow(), 11478 MemExpr->getQualifierLoc(), 11479 MemExpr->getTemplateKeywordLoc(), 11480 Fn, 11481 Found, 11482 MemExpr->getMemberNameInfo(), 11483 TemplateArgs, 11484 type, valueKind, OK_Ordinary); 11485 ME->setHadMultipleCandidates(true); 11486 return ME; 11487 } 11488 11489 llvm_unreachable("Invalid reference to overloaded function"); 11490} 11491 11492ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11493 DeclAccessPair Found, 11494 FunctionDecl *Fn) { 11495 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11496} 11497 11498} // end namespace clang 11499