SemaOverload.cpp revision ceb07622bacde3184b19caf0957f5eeba5cb6784
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_InstantiationDepth: 559 case Sema::TDK_TooManyArguments: 560 case Sema::TDK_TooFewArguments: 561 break; 562 563 case Sema::TDK_Incomplete: 564 case Sema::TDK_InvalidExplicitArguments: 565 Result.Data = Info.Param.getOpaqueValue(); 566 break; 567 568 case Sema::TDK_Inconsistent: 569 case Sema::TDK_Underqualified: { 570 // FIXME: Should allocate from normal heap so that we can free this later. 571 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 572 Saved->Param = Info.Param; 573 Saved->FirstArg = Info.FirstArg; 574 Saved->SecondArg = Info.SecondArg; 575 Result.Data = Saved; 576 break; 577 } 578 579 case Sema::TDK_SubstitutionFailure: 580 Result.Data = Info.take(); 581 if (Info.hasSFINAEDiagnostic()) { 582 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 583 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 584 Info.takeSFINAEDiagnostic(*Diag); 585 Result.HasDiagnostic = true; 586 } 587 break; 588 589 case Sema::TDK_NonDeducedMismatch: 590 case Sema::TDK_FailedOverloadResolution: 591 break; 592 } 593 594 return Result; 595} 596 597void OverloadCandidate::DeductionFailureInfo::Destroy() { 598 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 599 case Sema::TDK_Success: 600 case Sema::TDK_InstantiationDepth: 601 case Sema::TDK_Incomplete: 602 case Sema::TDK_TooManyArguments: 603 case Sema::TDK_TooFewArguments: 604 case Sema::TDK_InvalidExplicitArguments: 605 break; 606 607 case Sema::TDK_Inconsistent: 608 case Sema::TDK_Underqualified: 609 // FIXME: Destroy the data? 610 Data = 0; 611 break; 612 613 case Sema::TDK_SubstitutionFailure: 614 // FIXME: Destroy the template argument list? 615 Data = 0; 616 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 617 Diag->~PartialDiagnosticAt(); 618 HasDiagnostic = false; 619 } 620 break; 621 622 // Unhandled 623 case Sema::TDK_NonDeducedMismatch: 624 case Sema::TDK_FailedOverloadResolution: 625 break; 626 } 627} 628 629PartialDiagnosticAt * 630OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 631 if (HasDiagnostic) 632 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 633 return 0; 634} 635 636TemplateParameter 637OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 638 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 639 case Sema::TDK_Success: 640 case Sema::TDK_InstantiationDepth: 641 case Sema::TDK_TooManyArguments: 642 case Sema::TDK_TooFewArguments: 643 case Sema::TDK_SubstitutionFailure: 644 return TemplateParameter(); 645 646 case Sema::TDK_Incomplete: 647 case Sema::TDK_InvalidExplicitArguments: 648 return TemplateParameter::getFromOpaqueValue(Data); 649 650 case Sema::TDK_Inconsistent: 651 case Sema::TDK_Underqualified: 652 return static_cast<DFIParamWithArguments*>(Data)->Param; 653 654 // Unhandled 655 case Sema::TDK_NonDeducedMismatch: 656 case Sema::TDK_FailedOverloadResolution: 657 break; 658 } 659 660 return TemplateParameter(); 661} 662 663TemplateArgumentList * 664OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 665 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 666 case Sema::TDK_Success: 667 case Sema::TDK_InstantiationDepth: 668 case Sema::TDK_TooManyArguments: 669 case Sema::TDK_TooFewArguments: 670 case Sema::TDK_Incomplete: 671 case Sema::TDK_InvalidExplicitArguments: 672 case Sema::TDK_Inconsistent: 673 case Sema::TDK_Underqualified: 674 return 0; 675 676 case Sema::TDK_SubstitutionFailure: 677 return static_cast<TemplateArgumentList*>(Data); 678 679 // Unhandled 680 case Sema::TDK_NonDeducedMismatch: 681 case Sema::TDK_FailedOverloadResolution: 682 break; 683 } 684 685 return 0; 686} 687 688const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 689 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 690 case Sema::TDK_Success: 691 case Sema::TDK_InstantiationDepth: 692 case Sema::TDK_Incomplete: 693 case Sema::TDK_TooManyArguments: 694 case Sema::TDK_TooFewArguments: 695 case Sema::TDK_InvalidExplicitArguments: 696 case Sema::TDK_SubstitutionFailure: 697 return 0; 698 699 case Sema::TDK_Inconsistent: 700 case Sema::TDK_Underqualified: 701 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 702 703 // Unhandled 704 case Sema::TDK_NonDeducedMismatch: 705 case Sema::TDK_FailedOverloadResolution: 706 break; 707 } 708 709 return 0; 710} 711 712const TemplateArgument * 713OverloadCandidate::DeductionFailureInfo::getSecondArg() { 714 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 715 case Sema::TDK_Success: 716 case Sema::TDK_InstantiationDepth: 717 case Sema::TDK_Incomplete: 718 case Sema::TDK_TooManyArguments: 719 case Sema::TDK_TooFewArguments: 720 case Sema::TDK_InvalidExplicitArguments: 721 case Sema::TDK_SubstitutionFailure: 722 return 0; 723 724 case Sema::TDK_Inconsistent: 725 case Sema::TDK_Underqualified: 726 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 727 728 // Unhandled 729 case Sema::TDK_NonDeducedMismatch: 730 case Sema::TDK_FailedOverloadResolution: 731 break; 732 } 733 734 return 0; 735} 736 737void OverloadCandidateSet::clear() { 738 for (iterator i = begin(), e = end(); i != e; ++i) { 739 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 740 i->Conversions[ii].~ImplicitConversionSequence(); 741 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 742 i->DeductionFailure.Destroy(); 743 } 744 NumInlineSequences = 0; 745 Candidates.clear(); 746 Functions.clear(); 747} 748 749namespace { 750 class UnbridgedCastsSet { 751 struct Entry { 752 Expr **Addr; 753 Expr *Saved; 754 }; 755 SmallVector<Entry, 2> Entries; 756 757 public: 758 void save(Sema &S, Expr *&E) { 759 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 760 Entry entry = { &E, E }; 761 Entries.push_back(entry); 762 E = S.stripARCUnbridgedCast(E); 763 } 764 765 void restore() { 766 for (SmallVectorImpl<Entry>::iterator 767 i = Entries.begin(), e = Entries.end(); i != e; ++i) 768 *i->Addr = i->Saved; 769 } 770 }; 771} 772 773/// checkPlaceholderForOverload - Do any interesting placeholder-like 774/// preprocessing on the given expression. 775/// 776/// \param unbridgedCasts a collection to which to add unbridged casts; 777/// without this, they will be immediately diagnosed as errors 778/// 779/// Return true on unrecoverable error. 780static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 781 UnbridgedCastsSet *unbridgedCasts = 0) { 782 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 783 // We can't handle overloaded expressions here because overload 784 // resolution might reasonably tweak them. 785 if (placeholder->getKind() == BuiltinType::Overload) return false; 786 787 // If the context potentially accepts unbridged ARC casts, strip 788 // the unbridged cast and add it to the collection for later restoration. 789 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 790 unbridgedCasts) { 791 unbridgedCasts->save(S, E); 792 return false; 793 } 794 795 // Go ahead and check everything else. 796 ExprResult result = S.CheckPlaceholderExpr(E); 797 if (result.isInvalid()) 798 return true; 799 800 E = result.take(); 801 return false; 802 } 803 804 // Nothing to do. 805 return false; 806} 807 808/// checkArgPlaceholdersForOverload - Check a set of call operands for 809/// placeholders. 810static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args, 811 unsigned numArgs, 812 UnbridgedCastsSet &unbridged) { 813 for (unsigned i = 0; i != numArgs; ++i) 814 if (checkPlaceholderForOverload(S, args[i], &unbridged)) 815 return true; 816 817 return false; 818} 819 820// IsOverload - Determine whether the given New declaration is an 821// overload of the declarations in Old. This routine returns false if 822// New and Old cannot be overloaded, e.g., if New has the same 823// signature as some function in Old (C++ 1.3.10) or if the Old 824// declarations aren't functions (or function templates) at all. When 825// it does return false, MatchedDecl will point to the decl that New 826// cannot be overloaded with. This decl may be a UsingShadowDecl on 827// top of the underlying declaration. 828// 829// Example: Given the following input: 830// 831// void f(int, float); // #1 832// void f(int, int); // #2 833// int f(int, int); // #3 834// 835// When we process #1, there is no previous declaration of "f", 836// so IsOverload will not be used. 837// 838// When we process #2, Old contains only the FunctionDecl for #1. By 839// comparing the parameter types, we see that #1 and #2 are overloaded 840// (since they have different signatures), so this routine returns 841// false; MatchedDecl is unchanged. 842// 843// When we process #3, Old is an overload set containing #1 and #2. We 844// compare the signatures of #3 to #1 (they're overloaded, so we do 845// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 846// identical (return types of functions are not part of the 847// signature), IsOverload returns false and MatchedDecl will be set to 848// point to the FunctionDecl for #2. 849// 850// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 851// into a class by a using declaration. The rules for whether to hide 852// shadow declarations ignore some properties which otherwise figure 853// into a function template's signature. 854Sema::OverloadKind 855Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 856 NamedDecl *&Match, bool NewIsUsingDecl) { 857 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 858 I != E; ++I) { 859 NamedDecl *OldD = *I; 860 861 bool OldIsUsingDecl = false; 862 if (isa<UsingShadowDecl>(OldD)) { 863 OldIsUsingDecl = true; 864 865 // We can always introduce two using declarations into the same 866 // context, even if they have identical signatures. 867 if (NewIsUsingDecl) continue; 868 869 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 870 } 871 872 // If either declaration was introduced by a using declaration, 873 // we'll need to use slightly different rules for matching. 874 // Essentially, these rules are the normal rules, except that 875 // function templates hide function templates with different 876 // return types or template parameter lists. 877 bool UseMemberUsingDeclRules = 878 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 879 880 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 881 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 882 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 883 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 884 continue; 885 } 886 887 Match = *I; 888 return Ovl_Match; 889 } 890 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 891 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 892 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 893 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 894 continue; 895 } 896 897 Match = *I; 898 return Ovl_Match; 899 } 900 } else if (isa<UsingDecl>(OldD)) { 901 // We can overload with these, which can show up when doing 902 // redeclaration checks for UsingDecls. 903 assert(Old.getLookupKind() == LookupUsingDeclName); 904 } else if (isa<TagDecl>(OldD)) { 905 // We can always overload with tags by hiding them. 906 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 907 // Optimistically assume that an unresolved using decl will 908 // overload; if it doesn't, we'll have to diagnose during 909 // template instantiation. 910 } else { 911 // (C++ 13p1): 912 // Only function declarations can be overloaded; object and type 913 // declarations cannot be overloaded. 914 Match = *I; 915 return Ovl_NonFunction; 916 } 917 } 918 919 return Ovl_Overload; 920} 921 922bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 923 bool UseUsingDeclRules) { 924 // If both of the functions are extern "C", then they are not 925 // overloads. 926 if (Old->isExternC() && New->isExternC()) 927 return false; 928 929 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 930 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 931 932 // C++ [temp.fct]p2: 933 // A function template can be overloaded with other function templates 934 // and with normal (non-template) functions. 935 if ((OldTemplate == 0) != (NewTemplate == 0)) 936 return true; 937 938 // Is the function New an overload of the function Old? 939 QualType OldQType = Context.getCanonicalType(Old->getType()); 940 QualType NewQType = Context.getCanonicalType(New->getType()); 941 942 // Compare the signatures (C++ 1.3.10) of the two functions to 943 // determine whether they are overloads. If we find any mismatch 944 // in the signature, they are overloads. 945 946 // If either of these functions is a K&R-style function (no 947 // prototype), then we consider them to have matching signatures. 948 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 949 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 950 return false; 951 952 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 953 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 954 955 // The signature of a function includes the types of its 956 // parameters (C++ 1.3.10), which includes the presence or absence 957 // of the ellipsis; see C++ DR 357). 958 if (OldQType != NewQType && 959 (OldType->getNumArgs() != NewType->getNumArgs() || 960 OldType->isVariadic() != NewType->isVariadic() || 961 !FunctionArgTypesAreEqual(OldType, NewType))) 962 return true; 963 964 // C++ [temp.over.link]p4: 965 // The signature of a function template consists of its function 966 // signature, its return type and its template parameter list. The names 967 // of the template parameters are significant only for establishing the 968 // relationship between the template parameters and the rest of the 969 // signature. 970 // 971 // We check the return type and template parameter lists for function 972 // templates first; the remaining checks follow. 973 // 974 // However, we don't consider either of these when deciding whether 975 // a member introduced by a shadow declaration is hidden. 976 if (!UseUsingDeclRules && NewTemplate && 977 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 978 OldTemplate->getTemplateParameters(), 979 false, TPL_TemplateMatch) || 980 OldType->getResultType() != NewType->getResultType())) 981 return true; 982 983 // If the function is a class member, its signature includes the 984 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 985 // 986 // As part of this, also check whether one of the member functions 987 // is static, in which case they are not overloads (C++ 988 // 13.1p2). While not part of the definition of the signature, 989 // this check is important to determine whether these functions 990 // can be overloaded. 991 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 992 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 993 if (OldMethod && NewMethod && 994 !OldMethod->isStatic() && !NewMethod->isStatic() && 995 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() || 996 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) { 997 if (!UseUsingDeclRules && 998 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() && 999 (OldMethod->getRefQualifier() == RQ_None || 1000 NewMethod->getRefQualifier() == RQ_None)) { 1001 // C++0x [over.load]p2: 1002 // - Member function declarations with the same name and the same 1003 // parameter-type-list as well as member function template 1004 // declarations with the same name, the same parameter-type-list, and 1005 // the same template parameter lists cannot be overloaded if any of 1006 // them, but not all, have a ref-qualifier (8.3.5). 1007 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1008 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1009 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1010 } 1011 1012 return true; 1013 } 1014 1015 // The signatures match; this is not an overload. 1016 return false; 1017} 1018 1019/// \brief Checks availability of the function depending on the current 1020/// function context. Inside an unavailable function, unavailability is ignored. 1021/// 1022/// \returns true if \arg FD is unavailable and current context is inside 1023/// an available function, false otherwise. 1024bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1025 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1026} 1027 1028/// \brief Tries a user-defined conversion from From to ToType. 1029/// 1030/// Produces an implicit conversion sequence for when a standard conversion 1031/// is not an option. See TryImplicitConversion for more information. 1032static ImplicitConversionSequence 1033TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1034 bool SuppressUserConversions, 1035 bool AllowExplicit, 1036 bool InOverloadResolution, 1037 bool CStyle, 1038 bool AllowObjCWritebackConversion) { 1039 ImplicitConversionSequence ICS; 1040 1041 if (SuppressUserConversions) { 1042 // We're not in the case above, so there is no conversion that 1043 // we can perform. 1044 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1045 return ICS; 1046 } 1047 1048 // Attempt user-defined conversion. 1049 OverloadCandidateSet Conversions(From->getExprLoc()); 1050 OverloadingResult UserDefResult 1051 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1052 AllowExplicit); 1053 1054 if (UserDefResult == OR_Success) { 1055 ICS.setUserDefined(); 1056 // C++ [over.ics.user]p4: 1057 // A conversion of an expression of class type to the same class 1058 // type is given Exact Match rank, and a conversion of an 1059 // expression of class type to a base class of that type is 1060 // given Conversion rank, in spite of the fact that a copy 1061 // constructor (i.e., a user-defined conversion function) is 1062 // called for those cases. 1063 if (CXXConstructorDecl *Constructor 1064 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1065 QualType FromCanon 1066 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1067 QualType ToCanon 1068 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1069 if (Constructor->isCopyConstructor() && 1070 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1071 // Turn this into a "standard" conversion sequence, so that it 1072 // gets ranked with standard conversion sequences. 1073 ICS.setStandard(); 1074 ICS.Standard.setAsIdentityConversion(); 1075 ICS.Standard.setFromType(From->getType()); 1076 ICS.Standard.setAllToTypes(ToType); 1077 ICS.Standard.CopyConstructor = Constructor; 1078 if (ToCanon != FromCanon) 1079 ICS.Standard.Second = ICK_Derived_To_Base; 1080 } 1081 } 1082 1083 // C++ [over.best.ics]p4: 1084 // However, when considering the argument of a user-defined 1085 // conversion function that is a candidate by 13.3.1.3 when 1086 // invoked for the copying of the temporary in the second step 1087 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1088 // 13.3.1.6 in all cases, only standard conversion sequences and 1089 // ellipsis conversion sequences are allowed. 1090 if (SuppressUserConversions && ICS.isUserDefined()) { 1091 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1092 } 1093 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1094 ICS.setAmbiguous(); 1095 ICS.Ambiguous.setFromType(From->getType()); 1096 ICS.Ambiguous.setToType(ToType); 1097 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1098 Cand != Conversions.end(); ++Cand) 1099 if (Cand->Viable) 1100 ICS.Ambiguous.addConversion(Cand->Function); 1101 } else { 1102 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1103 } 1104 1105 return ICS; 1106} 1107 1108/// TryImplicitConversion - Attempt to perform an implicit conversion 1109/// from the given expression (Expr) to the given type (ToType). This 1110/// function returns an implicit conversion sequence that can be used 1111/// to perform the initialization. Given 1112/// 1113/// void f(float f); 1114/// void g(int i) { f(i); } 1115/// 1116/// this routine would produce an implicit conversion sequence to 1117/// describe the initialization of f from i, which will be a standard 1118/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1119/// 4.1) followed by a floating-integral conversion (C++ 4.9). 1120// 1121/// Note that this routine only determines how the conversion can be 1122/// performed; it does not actually perform the conversion. As such, 1123/// it will not produce any diagnostics if no conversion is available, 1124/// but will instead return an implicit conversion sequence of kind 1125/// "BadConversion". 1126/// 1127/// If @p SuppressUserConversions, then user-defined conversions are 1128/// not permitted. 1129/// If @p AllowExplicit, then explicit user-defined conversions are 1130/// permitted. 1131/// 1132/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1133/// writeback conversion, which allows __autoreleasing id* parameters to 1134/// be initialized with __strong id* or __weak id* arguments. 1135static ImplicitConversionSequence 1136TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1137 bool SuppressUserConversions, 1138 bool AllowExplicit, 1139 bool InOverloadResolution, 1140 bool CStyle, 1141 bool AllowObjCWritebackConversion) { 1142 ImplicitConversionSequence ICS; 1143 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1144 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1145 ICS.setStandard(); 1146 return ICS; 1147 } 1148 1149 if (!S.getLangOpts().CPlusPlus) { 1150 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1151 return ICS; 1152 } 1153 1154 // C++ [over.ics.user]p4: 1155 // A conversion of an expression of class type to the same class 1156 // type is given Exact Match rank, and a conversion of an 1157 // expression of class type to a base class of that type is 1158 // given Conversion rank, in spite of the fact that a copy/move 1159 // constructor (i.e., a user-defined conversion function) is 1160 // called for those cases. 1161 QualType FromType = From->getType(); 1162 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1163 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1164 S.IsDerivedFrom(FromType, ToType))) { 1165 ICS.setStandard(); 1166 ICS.Standard.setAsIdentityConversion(); 1167 ICS.Standard.setFromType(FromType); 1168 ICS.Standard.setAllToTypes(ToType); 1169 1170 // We don't actually check at this point whether there is a valid 1171 // copy/move constructor, since overloading just assumes that it 1172 // exists. When we actually perform initialization, we'll find the 1173 // appropriate constructor to copy the returned object, if needed. 1174 ICS.Standard.CopyConstructor = 0; 1175 1176 // Determine whether this is considered a derived-to-base conversion. 1177 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1178 ICS.Standard.Second = ICK_Derived_To_Base; 1179 1180 return ICS; 1181 } 1182 1183 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1184 AllowExplicit, InOverloadResolution, CStyle, 1185 AllowObjCWritebackConversion); 1186} 1187 1188ImplicitConversionSequence 1189Sema::TryImplicitConversion(Expr *From, QualType ToType, 1190 bool SuppressUserConversions, 1191 bool AllowExplicit, 1192 bool InOverloadResolution, 1193 bool CStyle, 1194 bool AllowObjCWritebackConversion) { 1195 return clang::TryImplicitConversion(*this, From, ToType, 1196 SuppressUserConversions, AllowExplicit, 1197 InOverloadResolution, CStyle, 1198 AllowObjCWritebackConversion); 1199} 1200 1201/// PerformImplicitConversion - Perform an implicit conversion of the 1202/// expression From to the type ToType. Returns the 1203/// converted expression. Flavor is the kind of conversion we're 1204/// performing, used in the error message. If @p AllowExplicit, 1205/// explicit user-defined conversions are permitted. 1206ExprResult 1207Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1208 AssignmentAction Action, bool AllowExplicit) { 1209 ImplicitConversionSequence ICS; 1210 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1211} 1212 1213ExprResult 1214Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1215 AssignmentAction Action, bool AllowExplicit, 1216 ImplicitConversionSequence& ICS) { 1217 if (checkPlaceholderForOverload(*this, From)) 1218 return ExprError(); 1219 1220 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1221 bool AllowObjCWritebackConversion 1222 = getLangOpts().ObjCAutoRefCount && 1223 (Action == AA_Passing || Action == AA_Sending); 1224 1225 ICS = clang::TryImplicitConversion(*this, From, ToType, 1226 /*SuppressUserConversions=*/false, 1227 AllowExplicit, 1228 /*InOverloadResolution=*/false, 1229 /*CStyle=*/false, 1230 AllowObjCWritebackConversion); 1231 return PerformImplicitConversion(From, ToType, ICS, Action); 1232} 1233 1234/// \brief Determine whether the conversion from FromType to ToType is a valid 1235/// conversion that strips "noreturn" off the nested function type. 1236bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1237 QualType &ResultTy) { 1238 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1239 return false; 1240 1241 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1242 // where F adds one of the following at most once: 1243 // - a pointer 1244 // - a member pointer 1245 // - a block pointer 1246 CanQualType CanTo = Context.getCanonicalType(ToType); 1247 CanQualType CanFrom = Context.getCanonicalType(FromType); 1248 Type::TypeClass TyClass = CanTo->getTypeClass(); 1249 if (TyClass != CanFrom->getTypeClass()) return false; 1250 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1251 if (TyClass == Type::Pointer) { 1252 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1253 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1254 } else if (TyClass == Type::BlockPointer) { 1255 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1256 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1257 } else if (TyClass == Type::MemberPointer) { 1258 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1259 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1260 } else { 1261 return false; 1262 } 1263 1264 TyClass = CanTo->getTypeClass(); 1265 if (TyClass != CanFrom->getTypeClass()) return false; 1266 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1267 return false; 1268 } 1269 1270 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1271 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1272 if (!EInfo.getNoReturn()) return false; 1273 1274 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1275 assert(QualType(FromFn, 0).isCanonical()); 1276 if (QualType(FromFn, 0) != CanTo) return false; 1277 1278 ResultTy = ToType; 1279 return true; 1280} 1281 1282/// \brief Determine whether the conversion from FromType to ToType is a valid 1283/// vector conversion. 1284/// 1285/// \param ICK Will be set to the vector conversion kind, if this is a vector 1286/// conversion. 1287static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1288 QualType ToType, ImplicitConversionKind &ICK) { 1289 // We need at least one of these types to be a vector type to have a vector 1290 // conversion. 1291 if (!ToType->isVectorType() && !FromType->isVectorType()) 1292 return false; 1293 1294 // Identical types require no conversions. 1295 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1296 return false; 1297 1298 // There are no conversions between extended vector types, only identity. 1299 if (ToType->isExtVectorType()) { 1300 // There are no conversions between extended vector types other than the 1301 // identity conversion. 1302 if (FromType->isExtVectorType()) 1303 return false; 1304 1305 // Vector splat from any arithmetic type to a vector. 1306 if (FromType->isArithmeticType()) { 1307 ICK = ICK_Vector_Splat; 1308 return true; 1309 } 1310 } 1311 1312 // We can perform the conversion between vector types in the following cases: 1313 // 1)vector types are equivalent AltiVec and GCC vector types 1314 // 2)lax vector conversions are permitted and the vector types are of the 1315 // same size 1316 if (ToType->isVectorType() && FromType->isVectorType()) { 1317 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1318 (Context.getLangOpts().LaxVectorConversions && 1319 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1320 ICK = ICK_Vector_Conversion; 1321 return true; 1322 } 1323 } 1324 1325 return false; 1326} 1327 1328static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1329 bool InOverloadResolution, 1330 StandardConversionSequence &SCS, 1331 bool CStyle); 1332 1333/// IsStandardConversion - Determines whether there is a standard 1334/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1335/// expression From to the type ToType. Standard conversion sequences 1336/// only consider non-class types; for conversions that involve class 1337/// types, use TryImplicitConversion. If a conversion exists, SCS will 1338/// contain the standard conversion sequence required to perform this 1339/// conversion and this routine will return true. Otherwise, this 1340/// routine will return false and the value of SCS is unspecified. 1341static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1342 bool InOverloadResolution, 1343 StandardConversionSequence &SCS, 1344 bool CStyle, 1345 bool AllowObjCWritebackConversion) { 1346 QualType FromType = From->getType(); 1347 1348 // Standard conversions (C++ [conv]) 1349 SCS.setAsIdentityConversion(); 1350 SCS.DeprecatedStringLiteralToCharPtr = false; 1351 SCS.IncompatibleObjC = false; 1352 SCS.setFromType(FromType); 1353 SCS.CopyConstructor = 0; 1354 1355 // There are no standard conversions for class types in C++, so 1356 // abort early. When overloading in C, however, we do permit 1357 if (FromType->isRecordType() || ToType->isRecordType()) { 1358 if (S.getLangOpts().CPlusPlus) 1359 return false; 1360 1361 // When we're overloading in C, we allow, as standard conversions, 1362 } 1363 1364 // The first conversion can be an lvalue-to-rvalue conversion, 1365 // array-to-pointer conversion, or function-to-pointer conversion 1366 // (C++ 4p1). 1367 1368 if (FromType == S.Context.OverloadTy) { 1369 DeclAccessPair AccessPair; 1370 if (FunctionDecl *Fn 1371 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1372 AccessPair)) { 1373 // We were able to resolve the address of the overloaded function, 1374 // so we can convert to the type of that function. 1375 FromType = Fn->getType(); 1376 1377 // we can sometimes resolve &foo<int> regardless of ToType, so check 1378 // if the type matches (identity) or we are converting to bool 1379 if (!S.Context.hasSameUnqualifiedType( 1380 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1381 QualType resultTy; 1382 // if the function type matches except for [[noreturn]], it's ok 1383 if (!S.IsNoReturnConversion(FromType, 1384 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1385 // otherwise, only a boolean conversion is standard 1386 if (!ToType->isBooleanType()) 1387 return false; 1388 } 1389 1390 // Check if the "from" expression is taking the address of an overloaded 1391 // function and recompute the FromType accordingly. Take advantage of the 1392 // fact that non-static member functions *must* have such an address-of 1393 // expression. 1394 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1395 if (Method && !Method->isStatic()) { 1396 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1397 "Non-unary operator on non-static member address"); 1398 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1399 == UO_AddrOf && 1400 "Non-address-of operator on non-static member address"); 1401 const Type *ClassType 1402 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1403 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1404 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1405 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1406 UO_AddrOf && 1407 "Non-address-of operator for overloaded function expression"); 1408 FromType = S.Context.getPointerType(FromType); 1409 } 1410 1411 // Check that we've computed the proper type after overload resolution. 1412 assert(S.Context.hasSameType( 1413 FromType, 1414 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1415 } else { 1416 return false; 1417 } 1418 } 1419 // Lvalue-to-rvalue conversion (C++11 4.1): 1420 // A glvalue (3.10) of a non-function, non-array type T can 1421 // be converted to a prvalue. 1422 bool argIsLValue = From->isGLValue(); 1423 if (argIsLValue && 1424 !FromType->isFunctionType() && !FromType->isArrayType() && 1425 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1426 SCS.First = ICK_Lvalue_To_Rvalue; 1427 1428 // C11 6.3.2.1p2: 1429 // ... if the lvalue has atomic type, the value has the non-atomic version 1430 // of the type of the lvalue ... 1431 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1432 FromType = Atomic->getValueType(); 1433 1434 // If T is a non-class type, the type of the rvalue is the 1435 // cv-unqualified version of T. Otherwise, the type of the rvalue 1436 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1437 // just strip the qualifiers because they don't matter. 1438 FromType = FromType.getUnqualifiedType(); 1439 } else if (FromType->isArrayType()) { 1440 // Array-to-pointer conversion (C++ 4.2) 1441 SCS.First = ICK_Array_To_Pointer; 1442 1443 // An lvalue or rvalue of type "array of N T" or "array of unknown 1444 // bound of T" can be converted to an rvalue of type "pointer to 1445 // T" (C++ 4.2p1). 1446 FromType = S.Context.getArrayDecayedType(FromType); 1447 1448 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1449 // This conversion is deprecated. (C++ D.4). 1450 SCS.DeprecatedStringLiteralToCharPtr = true; 1451 1452 // For the purpose of ranking in overload resolution 1453 // (13.3.3.1.1), this conversion is considered an 1454 // array-to-pointer conversion followed by a qualification 1455 // conversion (4.4). (C++ 4.2p2) 1456 SCS.Second = ICK_Identity; 1457 SCS.Third = ICK_Qualification; 1458 SCS.QualificationIncludesObjCLifetime = false; 1459 SCS.setAllToTypes(FromType); 1460 return true; 1461 } 1462 } else if (FromType->isFunctionType() && argIsLValue) { 1463 // Function-to-pointer conversion (C++ 4.3). 1464 SCS.First = ICK_Function_To_Pointer; 1465 1466 // An lvalue of function type T can be converted to an rvalue of 1467 // type "pointer to T." The result is a pointer to the 1468 // function. (C++ 4.3p1). 1469 FromType = S.Context.getPointerType(FromType); 1470 } else { 1471 // We don't require any conversions for the first step. 1472 SCS.First = ICK_Identity; 1473 } 1474 SCS.setToType(0, FromType); 1475 1476 // The second conversion can be an integral promotion, floating 1477 // point promotion, integral conversion, floating point conversion, 1478 // floating-integral conversion, pointer conversion, 1479 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1480 // For overloading in C, this can also be a "compatible-type" 1481 // conversion. 1482 bool IncompatibleObjC = false; 1483 ImplicitConversionKind SecondICK = ICK_Identity; 1484 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1485 // The unqualified versions of the types are the same: there's no 1486 // conversion to do. 1487 SCS.Second = ICK_Identity; 1488 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1489 // Integral promotion (C++ 4.5). 1490 SCS.Second = ICK_Integral_Promotion; 1491 FromType = ToType.getUnqualifiedType(); 1492 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1493 // Floating point promotion (C++ 4.6). 1494 SCS.Second = ICK_Floating_Promotion; 1495 FromType = ToType.getUnqualifiedType(); 1496 } else if (S.IsComplexPromotion(FromType, ToType)) { 1497 // Complex promotion (Clang extension) 1498 SCS.Second = ICK_Complex_Promotion; 1499 FromType = ToType.getUnqualifiedType(); 1500 } else if (ToType->isBooleanType() && 1501 (FromType->isArithmeticType() || 1502 FromType->isAnyPointerType() || 1503 FromType->isBlockPointerType() || 1504 FromType->isMemberPointerType() || 1505 FromType->isNullPtrType())) { 1506 // Boolean conversions (C++ 4.12). 1507 SCS.Second = ICK_Boolean_Conversion; 1508 FromType = S.Context.BoolTy; 1509 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1510 ToType->isIntegralType(S.Context)) { 1511 // Integral conversions (C++ 4.7). 1512 SCS.Second = ICK_Integral_Conversion; 1513 FromType = ToType.getUnqualifiedType(); 1514 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1515 // Complex conversions (C99 6.3.1.6) 1516 SCS.Second = ICK_Complex_Conversion; 1517 FromType = ToType.getUnqualifiedType(); 1518 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1519 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1520 // Complex-real conversions (C99 6.3.1.7) 1521 SCS.Second = ICK_Complex_Real; 1522 FromType = ToType.getUnqualifiedType(); 1523 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1524 // Floating point conversions (C++ 4.8). 1525 SCS.Second = ICK_Floating_Conversion; 1526 FromType = ToType.getUnqualifiedType(); 1527 } else if ((FromType->isRealFloatingType() && 1528 ToType->isIntegralType(S.Context)) || 1529 (FromType->isIntegralOrUnscopedEnumerationType() && 1530 ToType->isRealFloatingType())) { 1531 // Floating-integral conversions (C++ 4.9). 1532 SCS.Second = ICK_Floating_Integral; 1533 FromType = ToType.getUnqualifiedType(); 1534 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1535 SCS.Second = ICK_Block_Pointer_Conversion; 1536 } else if (AllowObjCWritebackConversion && 1537 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1538 SCS.Second = ICK_Writeback_Conversion; 1539 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1540 FromType, IncompatibleObjC)) { 1541 // Pointer conversions (C++ 4.10). 1542 SCS.Second = ICK_Pointer_Conversion; 1543 SCS.IncompatibleObjC = IncompatibleObjC; 1544 FromType = FromType.getUnqualifiedType(); 1545 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1546 InOverloadResolution, FromType)) { 1547 // Pointer to member conversions (4.11). 1548 SCS.Second = ICK_Pointer_Member; 1549 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1550 SCS.Second = SecondICK; 1551 FromType = ToType.getUnqualifiedType(); 1552 } else if (!S.getLangOpts().CPlusPlus && 1553 S.Context.typesAreCompatible(ToType, FromType)) { 1554 // Compatible conversions (Clang extension for C function overloading) 1555 SCS.Second = ICK_Compatible_Conversion; 1556 FromType = ToType.getUnqualifiedType(); 1557 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1558 // Treat a conversion that strips "noreturn" as an identity conversion. 1559 SCS.Second = ICK_NoReturn_Adjustment; 1560 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1561 InOverloadResolution, 1562 SCS, CStyle)) { 1563 SCS.Second = ICK_TransparentUnionConversion; 1564 FromType = ToType; 1565 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1566 CStyle)) { 1567 // tryAtomicConversion has updated the standard conversion sequence 1568 // appropriately. 1569 return true; 1570 } else { 1571 // No second conversion required. 1572 SCS.Second = ICK_Identity; 1573 } 1574 SCS.setToType(1, FromType); 1575 1576 QualType CanonFrom; 1577 QualType CanonTo; 1578 // The third conversion can be a qualification conversion (C++ 4p1). 1579 bool ObjCLifetimeConversion; 1580 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1581 ObjCLifetimeConversion)) { 1582 SCS.Third = ICK_Qualification; 1583 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1584 FromType = ToType; 1585 CanonFrom = S.Context.getCanonicalType(FromType); 1586 CanonTo = S.Context.getCanonicalType(ToType); 1587 } else { 1588 // No conversion required 1589 SCS.Third = ICK_Identity; 1590 1591 // C++ [over.best.ics]p6: 1592 // [...] Any difference in top-level cv-qualification is 1593 // subsumed by the initialization itself and does not constitute 1594 // a conversion. [...] 1595 CanonFrom = S.Context.getCanonicalType(FromType); 1596 CanonTo = S.Context.getCanonicalType(ToType); 1597 if (CanonFrom.getLocalUnqualifiedType() 1598 == CanonTo.getLocalUnqualifiedType() && 1599 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1600 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr() 1601 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) { 1602 FromType = ToType; 1603 CanonFrom = CanonTo; 1604 } 1605 } 1606 SCS.setToType(2, FromType); 1607 1608 // If we have not converted the argument type to the parameter type, 1609 // this is a bad conversion sequence. 1610 if (CanonFrom != CanonTo) 1611 return false; 1612 1613 return true; 1614} 1615 1616static bool 1617IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1618 QualType &ToType, 1619 bool InOverloadResolution, 1620 StandardConversionSequence &SCS, 1621 bool CStyle) { 1622 1623 const RecordType *UT = ToType->getAsUnionType(); 1624 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1625 return false; 1626 // The field to initialize within the transparent union. 1627 RecordDecl *UD = UT->getDecl(); 1628 // It's compatible if the expression matches any of the fields. 1629 for (RecordDecl::field_iterator it = UD->field_begin(), 1630 itend = UD->field_end(); 1631 it != itend; ++it) { 1632 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1633 CStyle, /*ObjCWritebackConversion=*/false)) { 1634 ToType = it->getType(); 1635 return true; 1636 } 1637 } 1638 return false; 1639} 1640 1641/// IsIntegralPromotion - Determines whether the conversion from the 1642/// expression From (whose potentially-adjusted type is FromType) to 1643/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1644/// sets PromotedType to the promoted type. 1645bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1646 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1647 // All integers are built-in. 1648 if (!To) { 1649 return false; 1650 } 1651 1652 // An rvalue of type char, signed char, unsigned char, short int, or 1653 // unsigned short int can be converted to an rvalue of type int if 1654 // int can represent all the values of the source type; otherwise, 1655 // the source rvalue can be converted to an rvalue of type unsigned 1656 // int (C++ 4.5p1). 1657 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1658 !FromType->isEnumeralType()) { 1659 if (// We can promote any signed, promotable integer type to an int 1660 (FromType->isSignedIntegerType() || 1661 // We can promote any unsigned integer type whose size is 1662 // less than int to an int. 1663 (!FromType->isSignedIntegerType() && 1664 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1665 return To->getKind() == BuiltinType::Int; 1666 } 1667 1668 return To->getKind() == BuiltinType::UInt; 1669 } 1670 1671 // C++0x [conv.prom]p3: 1672 // A prvalue of an unscoped enumeration type whose underlying type is not 1673 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1674 // following types that can represent all the values of the enumeration 1675 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1676 // unsigned int, long int, unsigned long int, long long int, or unsigned 1677 // long long int. If none of the types in that list can represent all the 1678 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1679 // type can be converted to an rvalue a prvalue of the extended integer type 1680 // with lowest integer conversion rank (4.13) greater than the rank of long 1681 // long in which all the values of the enumeration can be represented. If 1682 // there are two such extended types, the signed one is chosen. 1683 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1684 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1685 // provided for a scoped enumeration. 1686 if (FromEnumType->getDecl()->isScoped()) 1687 return false; 1688 1689 // We have already pre-calculated the promotion type, so this is trivial. 1690 if (ToType->isIntegerType() && 1691 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1692 return Context.hasSameUnqualifiedType(ToType, 1693 FromEnumType->getDecl()->getPromotionType()); 1694 } 1695 1696 // C++0x [conv.prom]p2: 1697 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1698 // to an rvalue a prvalue of the first of the following types that can 1699 // represent all the values of its underlying type: int, unsigned int, 1700 // long int, unsigned long int, long long int, or unsigned long long int. 1701 // If none of the types in that list can represent all the values of its 1702 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1703 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1704 // type. 1705 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1706 ToType->isIntegerType()) { 1707 // Determine whether the type we're converting from is signed or 1708 // unsigned. 1709 bool FromIsSigned = FromType->isSignedIntegerType(); 1710 uint64_t FromSize = Context.getTypeSize(FromType); 1711 1712 // The types we'll try to promote to, in the appropriate 1713 // order. Try each of these types. 1714 QualType PromoteTypes[6] = { 1715 Context.IntTy, Context.UnsignedIntTy, 1716 Context.LongTy, Context.UnsignedLongTy , 1717 Context.LongLongTy, Context.UnsignedLongLongTy 1718 }; 1719 for (int Idx = 0; Idx < 6; ++Idx) { 1720 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1721 if (FromSize < ToSize || 1722 (FromSize == ToSize && 1723 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1724 // We found the type that we can promote to. If this is the 1725 // type we wanted, we have a promotion. Otherwise, no 1726 // promotion. 1727 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1728 } 1729 } 1730 } 1731 1732 // An rvalue for an integral bit-field (9.6) can be converted to an 1733 // rvalue of type int if int can represent all the values of the 1734 // bit-field; otherwise, it can be converted to unsigned int if 1735 // unsigned int can represent all the values of the bit-field. If 1736 // the bit-field is larger yet, no integral promotion applies to 1737 // it. If the bit-field has an enumerated type, it is treated as any 1738 // other value of that type for promotion purposes (C++ 4.5p3). 1739 // FIXME: We should delay checking of bit-fields until we actually perform the 1740 // conversion. 1741 using llvm::APSInt; 1742 if (From) 1743 if (FieldDecl *MemberDecl = From->getBitField()) { 1744 APSInt BitWidth; 1745 if (FromType->isIntegralType(Context) && 1746 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1747 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1748 ToSize = Context.getTypeSize(ToType); 1749 1750 // Are we promoting to an int from a bitfield that fits in an int? 1751 if (BitWidth < ToSize || 1752 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1753 return To->getKind() == BuiltinType::Int; 1754 } 1755 1756 // Are we promoting to an unsigned int from an unsigned bitfield 1757 // that fits into an unsigned int? 1758 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1759 return To->getKind() == BuiltinType::UInt; 1760 } 1761 1762 return false; 1763 } 1764 } 1765 1766 // An rvalue of type bool can be converted to an rvalue of type int, 1767 // with false becoming zero and true becoming one (C++ 4.5p4). 1768 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1769 return true; 1770 } 1771 1772 return false; 1773} 1774 1775/// IsFloatingPointPromotion - Determines whether the conversion from 1776/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1777/// returns true and sets PromotedType to the promoted type. 1778bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1779 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1780 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1781 /// An rvalue of type float can be converted to an rvalue of type 1782 /// double. (C++ 4.6p1). 1783 if (FromBuiltin->getKind() == BuiltinType::Float && 1784 ToBuiltin->getKind() == BuiltinType::Double) 1785 return true; 1786 1787 // C99 6.3.1.5p1: 1788 // When a float is promoted to double or long double, or a 1789 // double is promoted to long double [...]. 1790 if (!getLangOpts().CPlusPlus && 1791 (FromBuiltin->getKind() == BuiltinType::Float || 1792 FromBuiltin->getKind() == BuiltinType::Double) && 1793 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1794 return true; 1795 1796 // Half can be promoted to float. 1797 if (FromBuiltin->getKind() == BuiltinType::Half && 1798 ToBuiltin->getKind() == BuiltinType::Float) 1799 return true; 1800 } 1801 1802 return false; 1803} 1804 1805/// \brief Determine if a conversion is a complex promotion. 1806/// 1807/// A complex promotion is defined as a complex -> complex conversion 1808/// where the conversion between the underlying real types is a 1809/// floating-point or integral promotion. 1810bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1811 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1812 if (!FromComplex) 1813 return false; 1814 1815 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1816 if (!ToComplex) 1817 return false; 1818 1819 return IsFloatingPointPromotion(FromComplex->getElementType(), 1820 ToComplex->getElementType()) || 1821 IsIntegralPromotion(0, FromComplex->getElementType(), 1822 ToComplex->getElementType()); 1823} 1824 1825/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1826/// the pointer type FromPtr to a pointer to type ToPointee, with the 1827/// same type qualifiers as FromPtr has on its pointee type. ToType, 1828/// if non-empty, will be a pointer to ToType that may or may not have 1829/// the right set of qualifiers on its pointee. 1830/// 1831static QualType 1832BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1833 QualType ToPointee, QualType ToType, 1834 ASTContext &Context, 1835 bool StripObjCLifetime = false) { 1836 assert((FromPtr->getTypeClass() == Type::Pointer || 1837 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1838 "Invalid similarly-qualified pointer type"); 1839 1840 /// Conversions to 'id' subsume cv-qualifier conversions. 1841 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1842 return ToType.getUnqualifiedType(); 1843 1844 QualType CanonFromPointee 1845 = Context.getCanonicalType(FromPtr->getPointeeType()); 1846 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1847 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1848 1849 if (StripObjCLifetime) 1850 Quals.removeObjCLifetime(); 1851 1852 // Exact qualifier match -> return the pointer type we're converting to. 1853 if (CanonToPointee.getLocalQualifiers() == Quals) { 1854 // ToType is exactly what we need. Return it. 1855 if (!ToType.isNull()) 1856 return ToType.getUnqualifiedType(); 1857 1858 // Build a pointer to ToPointee. It has the right qualifiers 1859 // already. 1860 if (isa<ObjCObjectPointerType>(ToType)) 1861 return Context.getObjCObjectPointerType(ToPointee); 1862 return Context.getPointerType(ToPointee); 1863 } 1864 1865 // Just build a canonical type that has the right qualifiers. 1866 QualType QualifiedCanonToPointee 1867 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1868 1869 if (isa<ObjCObjectPointerType>(ToType)) 1870 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1871 return Context.getPointerType(QualifiedCanonToPointee); 1872} 1873 1874static bool isNullPointerConstantForConversion(Expr *Expr, 1875 bool InOverloadResolution, 1876 ASTContext &Context) { 1877 // Handle value-dependent integral null pointer constants correctly. 1878 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1879 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1880 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1881 return !InOverloadResolution; 1882 1883 return Expr->isNullPointerConstant(Context, 1884 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1885 : Expr::NPC_ValueDependentIsNull); 1886} 1887 1888/// IsPointerConversion - Determines whether the conversion of the 1889/// expression From, which has the (possibly adjusted) type FromType, 1890/// can be converted to the type ToType via a pointer conversion (C++ 1891/// 4.10). If so, returns true and places the converted type (that 1892/// might differ from ToType in its cv-qualifiers at some level) into 1893/// ConvertedType. 1894/// 1895/// This routine also supports conversions to and from block pointers 1896/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1897/// pointers to interfaces. FIXME: Once we've determined the 1898/// appropriate overloading rules for Objective-C, we may want to 1899/// split the Objective-C checks into a different routine; however, 1900/// GCC seems to consider all of these conversions to be pointer 1901/// conversions, so for now they live here. IncompatibleObjC will be 1902/// set if the conversion is an allowed Objective-C conversion that 1903/// should result in a warning. 1904bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1905 bool InOverloadResolution, 1906 QualType& ConvertedType, 1907 bool &IncompatibleObjC) { 1908 IncompatibleObjC = false; 1909 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1910 IncompatibleObjC)) 1911 return true; 1912 1913 // Conversion from a null pointer constant to any Objective-C pointer type. 1914 if (ToType->isObjCObjectPointerType() && 1915 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1916 ConvertedType = ToType; 1917 return true; 1918 } 1919 1920 // Blocks: Block pointers can be converted to void*. 1921 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1922 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1923 ConvertedType = ToType; 1924 return true; 1925 } 1926 // Blocks: A null pointer constant can be converted to a block 1927 // pointer type. 1928 if (ToType->isBlockPointerType() && 1929 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1930 ConvertedType = ToType; 1931 return true; 1932 } 1933 1934 // If the left-hand-side is nullptr_t, the right side can be a null 1935 // pointer constant. 1936 if (ToType->isNullPtrType() && 1937 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1938 ConvertedType = ToType; 1939 return true; 1940 } 1941 1942 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 1943 if (!ToTypePtr) 1944 return false; 1945 1946 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 1947 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1948 ConvertedType = ToType; 1949 return true; 1950 } 1951 1952 // Beyond this point, both types need to be pointers 1953 // , including objective-c pointers. 1954 QualType ToPointeeType = ToTypePtr->getPointeeType(); 1955 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 1956 !getLangOpts().ObjCAutoRefCount) { 1957 ConvertedType = BuildSimilarlyQualifiedPointerType( 1958 FromType->getAs<ObjCObjectPointerType>(), 1959 ToPointeeType, 1960 ToType, Context); 1961 return true; 1962 } 1963 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 1964 if (!FromTypePtr) 1965 return false; 1966 1967 QualType FromPointeeType = FromTypePtr->getPointeeType(); 1968 1969 // If the unqualified pointee types are the same, this can't be a 1970 // pointer conversion, so don't do all of the work below. 1971 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 1972 return false; 1973 1974 // An rvalue of type "pointer to cv T," where T is an object type, 1975 // can be converted to an rvalue of type "pointer to cv void" (C++ 1976 // 4.10p2). 1977 if (FromPointeeType->isIncompleteOrObjectType() && 1978 ToPointeeType->isVoidType()) { 1979 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1980 ToPointeeType, 1981 ToType, Context, 1982 /*StripObjCLifetime=*/true); 1983 return true; 1984 } 1985 1986 // MSVC allows implicit function to void* type conversion. 1987 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 1988 ToPointeeType->isVoidType()) { 1989 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1990 ToPointeeType, 1991 ToType, Context); 1992 return true; 1993 } 1994 1995 // When we're overloading in C, we allow a special kind of pointer 1996 // conversion for compatible-but-not-identical pointee types. 1997 if (!getLangOpts().CPlusPlus && 1998 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 1999 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2000 ToPointeeType, 2001 ToType, Context); 2002 return true; 2003 } 2004 2005 // C++ [conv.ptr]p3: 2006 // 2007 // An rvalue of type "pointer to cv D," where D is a class type, 2008 // can be converted to an rvalue of type "pointer to cv B," where 2009 // B is a base class (clause 10) of D. If B is an inaccessible 2010 // (clause 11) or ambiguous (10.2) base class of D, a program that 2011 // necessitates this conversion is ill-formed. The result of the 2012 // conversion is a pointer to the base class sub-object of the 2013 // derived class object. The null pointer value is converted to 2014 // the null pointer value of the destination type. 2015 // 2016 // Note that we do not check for ambiguity or inaccessibility 2017 // here. That is handled by CheckPointerConversion. 2018 if (getLangOpts().CPlusPlus && 2019 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2020 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2021 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2022 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2023 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2024 ToPointeeType, 2025 ToType, Context); 2026 return true; 2027 } 2028 2029 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2030 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2031 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2032 ToPointeeType, 2033 ToType, Context); 2034 return true; 2035 } 2036 2037 return false; 2038} 2039 2040/// \brief Adopt the given qualifiers for the given type. 2041static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2042 Qualifiers TQs = T.getQualifiers(); 2043 2044 // Check whether qualifiers already match. 2045 if (TQs == Qs) 2046 return T; 2047 2048 if (Qs.compatiblyIncludes(TQs)) 2049 return Context.getQualifiedType(T, Qs); 2050 2051 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2052} 2053 2054/// isObjCPointerConversion - Determines whether this is an 2055/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2056/// with the same arguments and return values. 2057bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2058 QualType& ConvertedType, 2059 bool &IncompatibleObjC) { 2060 if (!getLangOpts().ObjC1) 2061 return false; 2062 2063 // The set of qualifiers on the type we're converting from. 2064 Qualifiers FromQualifiers = FromType.getQualifiers(); 2065 2066 // First, we handle all conversions on ObjC object pointer types. 2067 const ObjCObjectPointerType* ToObjCPtr = 2068 ToType->getAs<ObjCObjectPointerType>(); 2069 const ObjCObjectPointerType *FromObjCPtr = 2070 FromType->getAs<ObjCObjectPointerType>(); 2071 2072 if (ToObjCPtr && FromObjCPtr) { 2073 // If the pointee types are the same (ignoring qualifications), 2074 // then this is not a pointer conversion. 2075 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2076 FromObjCPtr->getPointeeType())) 2077 return false; 2078 2079 // Check for compatible 2080 // Objective C++: We're able to convert between "id" or "Class" and a 2081 // pointer to any interface (in both directions). 2082 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2083 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2084 return true; 2085 } 2086 // Conversions with Objective-C's id<...>. 2087 if ((FromObjCPtr->isObjCQualifiedIdType() || 2088 ToObjCPtr->isObjCQualifiedIdType()) && 2089 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2090 /*compare=*/false)) { 2091 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2092 return true; 2093 } 2094 // Objective C++: We're able to convert from a pointer to an 2095 // interface to a pointer to a different interface. 2096 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2097 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2098 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2099 if (getLangOpts().CPlusPlus && LHS && RHS && 2100 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2101 FromObjCPtr->getPointeeType())) 2102 return false; 2103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2104 ToObjCPtr->getPointeeType(), 2105 ToType, Context); 2106 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2107 return true; 2108 } 2109 2110 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2111 // Okay: this is some kind of implicit downcast of Objective-C 2112 // interfaces, which is permitted. However, we're going to 2113 // complain about it. 2114 IncompatibleObjC = true; 2115 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2116 ToObjCPtr->getPointeeType(), 2117 ToType, Context); 2118 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2119 return true; 2120 } 2121 } 2122 // Beyond this point, both types need to be C pointers or block pointers. 2123 QualType ToPointeeType; 2124 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2125 ToPointeeType = ToCPtr->getPointeeType(); 2126 else if (const BlockPointerType *ToBlockPtr = 2127 ToType->getAs<BlockPointerType>()) { 2128 // Objective C++: We're able to convert from a pointer to any object 2129 // to a block pointer type. 2130 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2131 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2132 return true; 2133 } 2134 ToPointeeType = ToBlockPtr->getPointeeType(); 2135 } 2136 else if (FromType->getAs<BlockPointerType>() && 2137 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2138 // Objective C++: We're able to convert from a block pointer type to a 2139 // pointer to any object. 2140 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2141 return true; 2142 } 2143 else 2144 return false; 2145 2146 QualType FromPointeeType; 2147 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2148 FromPointeeType = FromCPtr->getPointeeType(); 2149 else if (const BlockPointerType *FromBlockPtr = 2150 FromType->getAs<BlockPointerType>()) 2151 FromPointeeType = FromBlockPtr->getPointeeType(); 2152 else 2153 return false; 2154 2155 // If we have pointers to pointers, recursively check whether this 2156 // is an Objective-C conversion. 2157 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2158 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2159 IncompatibleObjC)) { 2160 // We always complain about this conversion. 2161 IncompatibleObjC = true; 2162 ConvertedType = Context.getPointerType(ConvertedType); 2163 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2164 return true; 2165 } 2166 // Allow conversion of pointee being objective-c pointer to another one; 2167 // as in I* to id. 2168 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2169 ToPointeeType->getAs<ObjCObjectPointerType>() && 2170 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2171 IncompatibleObjC)) { 2172 2173 ConvertedType = Context.getPointerType(ConvertedType); 2174 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2175 return true; 2176 } 2177 2178 // If we have pointers to functions or blocks, check whether the only 2179 // differences in the argument and result types are in Objective-C 2180 // pointer conversions. If so, we permit the conversion (but 2181 // complain about it). 2182 const FunctionProtoType *FromFunctionType 2183 = FromPointeeType->getAs<FunctionProtoType>(); 2184 const FunctionProtoType *ToFunctionType 2185 = ToPointeeType->getAs<FunctionProtoType>(); 2186 if (FromFunctionType && ToFunctionType) { 2187 // If the function types are exactly the same, this isn't an 2188 // Objective-C pointer conversion. 2189 if (Context.getCanonicalType(FromPointeeType) 2190 == Context.getCanonicalType(ToPointeeType)) 2191 return false; 2192 2193 // Perform the quick checks that will tell us whether these 2194 // function types are obviously different. 2195 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2196 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2197 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2198 return false; 2199 2200 bool HasObjCConversion = false; 2201 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2202 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2203 // Okay, the types match exactly. Nothing to do. 2204 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2205 ToFunctionType->getResultType(), 2206 ConvertedType, IncompatibleObjC)) { 2207 // Okay, we have an Objective-C pointer conversion. 2208 HasObjCConversion = true; 2209 } else { 2210 // Function types are too different. Abort. 2211 return false; 2212 } 2213 2214 // Check argument types. 2215 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2216 ArgIdx != NumArgs; ++ArgIdx) { 2217 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2218 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2219 if (Context.getCanonicalType(FromArgType) 2220 == Context.getCanonicalType(ToArgType)) { 2221 // Okay, the types match exactly. Nothing to do. 2222 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2223 ConvertedType, IncompatibleObjC)) { 2224 // Okay, we have an Objective-C pointer conversion. 2225 HasObjCConversion = true; 2226 } else { 2227 // Argument types are too different. Abort. 2228 return false; 2229 } 2230 } 2231 2232 if (HasObjCConversion) { 2233 // We had an Objective-C conversion. Allow this pointer 2234 // conversion, but complain about it. 2235 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2236 IncompatibleObjC = true; 2237 return true; 2238 } 2239 } 2240 2241 return false; 2242} 2243 2244/// \brief Determine whether this is an Objective-C writeback conversion, 2245/// used for parameter passing when performing automatic reference counting. 2246/// 2247/// \param FromType The type we're converting form. 2248/// 2249/// \param ToType The type we're converting to. 2250/// 2251/// \param ConvertedType The type that will be produced after applying 2252/// this conversion. 2253bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2254 QualType &ConvertedType) { 2255 if (!getLangOpts().ObjCAutoRefCount || 2256 Context.hasSameUnqualifiedType(FromType, ToType)) 2257 return false; 2258 2259 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2260 QualType ToPointee; 2261 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2262 ToPointee = ToPointer->getPointeeType(); 2263 else 2264 return false; 2265 2266 Qualifiers ToQuals = ToPointee.getQualifiers(); 2267 if (!ToPointee->isObjCLifetimeType() || 2268 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2269 !ToQuals.withoutObjCLifetime().empty()) 2270 return false; 2271 2272 // Argument must be a pointer to __strong to __weak. 2273 QualType FromPointee; 2274 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2275 FromPointee = FromPointer->getPointeeType(); 2276 else 2277 return false; 2278 2279 Qualifiers FromQuals = FromPointee.getQualifiers(); 2280 if (!FromPointee->isObjCLifetimeType() || 2281 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2282 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2283 return false; 2284 2285 // Make sure that we have compatible qualifiers. 2286 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2287 if (!ToQuals.compatiblyIncludes(FromQuals)) 2288 return false; 2289 2290 // Remove qualifiers from the pointee type we're converting from; they 2291 // aren't used in the compatibility check belong, and we'll be adding back 2292 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2293 FromPointee = FromPointee.getUnqualifiedType(); 2294 2295 // The unqualified form of the pointee types must be compatible. 2296 ToPointee = ToPointee.getUnqualifiedType(); 2297 bool IncompatibleObjC; 2298 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2299 FromPointee = ToPointee; 2300 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2301 IncompatibleObjC)) 2302 return false; 2303 2304 /// \brief Construct the type we're converting to, which is a pointer to 2305 /// __autoreleasing pointee. 2306 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2307 ConvertedType = Context.getPointerType(FromPointee); 2308 return true; 2309} 2310 2311bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2312 QualType& ConvertedType) { 2313 QualType ToPointeeType; 2314 if (const BlockPointerType *ToBlockPtr = 2315 ToType->getAs<BlockPointerType>()) 2316 ToPointeeType = ToBlockPtr->getPointeeType(); 2317 else 2318 return false; 2319 2320 QualType FromPointeeType; 2321 if (const BlockPointerType *FromBlockPtr = 2322 FromType->getAs<BlockPointerType>()) 2323 FromPointeeType = FromBlockPtr->getPointeeType(); 2324 else 2325 return false; 2326 // We have pointer to blocks, check whether the only 2327 // differences in the argument and result types are in Objective-C 2328 // pointer conversions. If so, we permit the conversion. 2329 2330 const FunctionProtoType *FromFunctionType 2331 = FromPointeeType->getAs<FunctionProtoType>(); 2332 const FunctionProtoType *ToFunctionType 2333 = ToPointeeType->getAs<FunctionProtoType>(); 2334 2335 if (!FromFunctionType || !ToFunctionType) 2336 return false; 2337 2338 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2339 return true; 2340 2341 // Perform the quick checks that will tell us whether these 2342 // function types are obviously different. 2343 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2344 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2345 return false; 2346 2347 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2348 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2349 if (FromEInfo != ToEInfo) 2350 return false; 2351 2352 bool IncompatibleObjC = false; 2353 if (Context.hasSameType(FromFunctionType->getResultType(), 2354 ToFunctionType->getResultType())) { 2355 // Okay, the types match exactly. Nothing to do. 2356 } else { 2357 QualType RHS = FromFunctionType->getResultType(); 2358 QualType LHS = ToFunctionType->getResultType(); 2359 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2360 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2361 LHS = LHS.getUnqualifiedType(); 2362 2363 if (Context.hasSameType(RHS,LHS)) { 2364 // OK exact match. 2365 } else if (isObjCPointerConversion(RHS, LHS, 2366 ConvertedType, IncompatibleObjC)) { 2367 if (IncompatibleObjC) 2368 return false; 2369 // Okay, we have an Objective-C pointer conversion. 2370 } 2371 else 2372 return false; 2373 } 2374 2375 // Check argument types. 2376 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2377 ArgIdx != NumArgs; ++ArgIdx) { 2378 IncompatibleObjC = false; 2379 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2380 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2381 if (Context.hasSameType(FromArgType, ToArgType)) { 2382 // Okay, the types match exactly. Nothing to do. 2383 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2384 ConvertedType, IncompatibleObjC)) { 2385 if (IncompatibleObjC) 2386 return false; 2387 // Okay, we have an Objective-C pointer conversion. 2388 } else 2389 // Argument types are too different. Abort. 2390 return false; 2391 } 2392 if (LangOpts.ObjCAutoRefCount && 2393 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2394 ToFunctionType)) 2395 return false; 2396 2397 ConvertedType = ToType; 2398 return true; 2399} 2400 2401enum { 2402 ft_default, 2403 ft_different_class, 2404 ft_parameter_arity, 2405 ft_parameter_mismatch, 2406 ft_return_type, 2407 ft_qualifer_mismatch 2408}; 2409 2410/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2411/// function types. Catches different number of parameter, mismatch in 2412/// parameter types, and different return types. 2413void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2414 QualType FromType, QualType ToType) { 2415 // If either type is not valid, include no extra info. 2416 if (FromType.isNull() || ToType.isNull()) { 2417 PDiag << ft_default; 2418 return; 2419 } 2420 2421 // Get the function type from the pointers. 2422 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2423 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2424 *ToMember = ToType->getAs<MemberPointerType>(); 2425 if (FromMember->getClass() != ToMember->getClass()) { 2426 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2427 << QualType(FromMember->getClass(), 0); 2428 return; 2429 } 2430 FromType = FromMember->getPointeeType(); 2431 ToType = ToMember->getPointeeType(); 2432 } 2433 2434 if (FromType->isPointerType()) 2435 FromType = FromType->getPointeeType(); 2436 if (ToType->isPointerType()) 2437 ToType = ToType->getPointeeType(); 2438 2439 // Remove references. 2440 FromType = FromType.getNonReferenceType(); 2441 ToType = ToType.getNonReferenceType(); 2442 2443 // Don't print extra info for non-specialized template functions. 2444 if (FromType->isInstantiationDependentType() && 2445 !FromType->getAs<TemplateSpecializationType>()) { 2446 PDiag << ft_default; 2447 return; 2448 } 2449 2450 // No extra info for same types. 2451 if (Context.hasSameType(FromType, ToType)) { 2452 PDiag << ft_default; 2453 return; 2454 } 2455 2456 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2457 *ToFunction = ToType->getAs<FunctionProtoType>(); 2458 2459 // Both types need to be function types. 2460 if (!FromFunction || !ToFunction) { 2461 PDiag << ft_default; 2462 return; 2463 } 2464 2465 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2466 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2467 << FromFunction->getNumArgs(); 2468 return; 2469 } 2470 2471 // Handle different parameter types. 2472 unsigned ArgPos; 2473 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2474 PDiag << ft_parameter_mismatch << ArgPos + 1 2475 << ToFunction->getArgType(ArgPos) 2476 << FromFunction->getArgType(ArgPos); 2477 return; 2478 } 2479 2480 // Handle different return type. 2481 if (!Context.hasSameType(FromFunction->getResultType(), 2482 ToFunction->getResultType())) { 2483 PDiag << ft_return_type << ToFunction->getResultType() 2484 << FromFunction->getResultType(); 2485 return; 2486 } 2487 2488 unsigned FromQuals = FromFunction->getTypeQuals(), 2489 ToQuals = ToFunction->getTypeQuals(); 2490 if (FromQuals != ToQuals) { 2491 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2492 return; 2493 } 2494 2495 // Unable to find a difference, so add no extra info. 2496 PDiag << ft_default; 2497} 2498 2499/// FunctionArgTypesAreEqual - This routine checks two function proto types 2500/// for equality of their argument types. Caller has already checked that 2501/// they have same number of arguments. This routine assumes that Objective-C 2502/// pointer types which only differ in their protocol qualifiers are equal. 2503/// If the parameters are different, ArgPos will have the parameter index 2504/// of the first different parameter. 2505bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2506 const FunctionProtoType *NewType, 2507 unsigned *ArgPos) { 2508 if (!getLangOpts().ObjC1) { 2509 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2510 N = NewType->arg_type_begin(), 2511 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2512 if (!Context.hasSameType(*O, *N)) { 2513 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2514 return false; 2515 } 2516 } 2517 return true; 2518 } 2519 2520 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2521 N = NewType->arg_type_begin(), 2522 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2523 QualType ToType = (*O); 2524 QualType FromType = (*N); 2525 if (!Context.hasSameType(ToType, FromType)) { 2526 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2527 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2528 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2529 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2530 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2531 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2532 continue; 2533 } 2534 else if (const ObjCObjectPointerType *PTTo = 2535 ToType->getAs<ObjCObjectPointerType>()) { 2536 if (const ObjCObjectPointerType *PTFr = 2537 FromType->getAs<ObjCObjectPointerType>()) 2538 if (Context.hasSameUnqualifiedType( 2539 PTTo->getObjectType()->getBaseType(), 2540 PTFr->getObjectType()->getBaseType())) 2541 continue; 2542 } 2543 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2544 return false; 2545 } 2546 } 2547 return true; 2548} 2549 2550/// CheckPointerConversion - Check the pointer conversion from the 2551/// expression From to the type ToType. This routine checks for 2552/// ambiguous or inaccessible derived-to-base pointer 2553/// conversions for which IsPointerConversion has already returned 2554/// true. It returns true and produces a diagnostic if there was an 2555/// error, or returns false otherwise. 2556bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2557 CastKind &Kind, 2558 CXXCastPath& BasePath, 2559 bool IgnoreBaseAccess) { 2560 QualType FromType = From->getType(); 2561 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2562 2563 Kind = CK_BitCast; 2564 2565 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2566 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2567 Expr::NPCK_ZeroExpression) { 2568 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2569 DiagRuntimeBehavior(From->getExprLoc(), From, 2570 PDiag(diag::warn_impcast_bool_to_null_pointer) 2571 << ToType << From->getSourceRange()); 2572 else if (!isUnevaluatedContext()) 2573 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2574 << ToType << From->getSourceRange(); 2575 } 2576 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2577 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2578 QualType FromPointeeType = FromPtrType->getPointeeType(), 2579 ToPointeeType = ToPtrType->getPointeeType(); 2580 2581 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2582 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2583 // We must have a derived-to-base conversion. Check an 2584 // ambiguous or inaccessible conversion. 2585 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2586 From->getExprLoc(), 2587 From->getSourceRange(), &BasePath, 2588 IgnoreBaseAccess)) 2589 return true; 2590 2591 // The conversion was successful. 2592 Kind = CK_DerivedToBase; 2593 } 2594 } 2595 } else if (const ObjCObjectPointerType *ToPtrType = 2596 ToType->getAs<ObjCObjectPointerType>()) { 2597 if (const ObjCObjectPointerType *FromPtrType = 2598 FromType->getAs<ObjCObjectPointerType>()) { 2599 // Objective-C++ conversions are always okay. 2600 // FIXME: We should have a different class of conversions for the 2601 // Objective-C++ implicit conversions. 2602 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2603 return false; 2604 } else if (FromType->isBlockPointerType()) { 2605 Kind = CK_BlockPointerToObjCPointerCast; 2606 } else { 2607 Kind = CK_CPointerToObjCPointerCast; 2608 } 2609 } else if (ToType->isBlockPointerType()) { 2610 if (!FromType->isBlockPointerType()) 2611 Kind = CK_AnyPointerToBlockPointerCast; 2612 } 2613 2614 // We shouldn't fall into this case unless it's valid for other 2615 // reasons. 2616 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2617 Kind = CK_NullToPointer; 2618 2619 return false; 2620} 2621 2622/// IsMemberPointerConversion - Determines whether the conversion of the 2623/// expression From, which has the (possibly adjusted) type FromType, can be 2624/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2625/// If so, returns true and places the converted type (that might differ from 2626/// ToType in its cv-qualifiers at some level) into ConvertedType. 2627bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2628 QualType ToType, 2629 bool InOverloadResolution, 2630 QualType &ConvertedType) { 2631 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2632 if (!ToTypePtr) 2633 return false; 2634 2635 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2636 if (From->isNullPointerConstant(Context, 2637 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2638 : Expr::NPC_ValueDependentIsNull)) { 2639 ConvertedType = ToType; 2640 return true; 2641 } 2642 2643 // Otherwise, both types have to be member pointers. 2644 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2645 if (!FromTypePtr) 2646 return false; 2647 2648 // A pointer to member of B can be converted to a pointer to member of D, 2649 // where D is derived from B (C++ 4.11p2). 2650 QualType FromClass(FromTypePtr->getClass(), 0); 2651 QualType ToClass(ToTypePtr->getClass(), 0); 2652 2653 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2654 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2655 IsDerivedFrom(ToClass, FromClass)) { 2656 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2657 ToClass.getTypePtr()); 2658 return true; 2659 } 2660 2661 return false; 2662} 2663 2664/// CheckMemberPointerConversion - Check the member pointer conversion from the 2665/// expression From to the type ToType. This routine checks for ambiguous or 2666/// virtual or inaccessible base-to-derived member pointer conversions 2667/// for which IsMemberPointerConversion has already returned true. It returns 2668/// true and produces a diagnostic if there was an error, or returns false 2669/// otherwise. 2670bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2671 CastKind &Kind, 2672 CXXCastPath &BasePath, 2673 bool IgnoreBaseAccess) { 2674 QualType FromType = From->getType(); 2675 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2676 if (!FromPtrType) { 2677 // This must be a null pointer to member pointer conversion 2678 assert(From->isNullPointerConstant(Context, 2679 Expr::NPC_ValueDependentIsNull) && 2680 "Expr must be null pointer constant!"); 2681 Kind = CK_NullToMemberPointer; 2682 return false; 2683 } 2684 2685 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2686 assert(ToPtrType && "No member pointer cast has a target type " 2687 "that is not a member pointer."); 2688 2689 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2690 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2691 2692 // FIXME: What about dependent types? 2693 assert(FromClass->isRecordType() && "Pointer into non-class."); 2694 assert(ToClass->isRecordType() && "Pointer into non-class."); 2695 2696 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2697 /*DetectVirtual=*/true); 2698 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2699 assert(DerivationOkay && 2700 "Should not have been called if derivation isn't OK."); 2701 (void)DerivationOkay; 2702 2703 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2704 getUnqualifiedType())) { 2705 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2706 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2707 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2708 return true; 2709 } 2710 2711 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2712 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2713 << FromClass << ToClass << QualType(VBase, 0) 2714 << From->getSourceRange(); 2715 return true; 2716 } 2717 2718 if (!IgnoreBaseAccess) 2719 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2720 Paths.front(), 2721 diag::err_downcast_from_inaccessible_base); 2722 2723 // Must be a base to derived member conversion. 2724 BuildBasePathArray(Paths, BasePath); 2725 Kind = CK_BaseToDerivedMemberPointer; 2726 return false; 2727} 2728 2729/// IsQualificationConversion - Determines whether the conversion from 2730/// an rvalue of type FromType to ToType is a qualification conversion 2731/// (C++ 4.4). 2732/// 2733/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2734/// when the qualification conversion involves a change in the Objective-C 2735/// object lifetime. 2736bool 2737Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2738 bool CStyle, bool &ObjCLifetimeConversion) { 2739 FromType = Context.getCanonicalType(FromType); 2740 ToType = Context.getCanonicalType(ToType); 2741 ObjCLifetimeConversion = false; 2742 2743 // If FromType and ToType are the same type, this is not a 2744 // qualification conversion. 2745 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2746 return false; 2747 2748 // (C++ 4.4p4): 2749 // A conversion can add cv-qualifiers at levels other than the first 2750 // in multi-level pointers, subject to the following rules: [...] 2751 bool PreviousToQualsIncludeConst = true; 2752 bool UnwrappedAnyPointer = false; 2753 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2754 // Within each iteration of the loop, we check the qualifiers to 2755 // determine if this still looks like a qualification 2756 // conversion. Then, if all is well, we unwrap one more level of 2757 // pointers or pointers-to-members and do it all again 2758 // until there are no more pointers or pointers-to-members left to 2759 // unwrap. 2760 UnwrappedAnyPointer = true; 2761 2762 Qualifiers FromQuals = FromType.getQualifiers(); 2763 Qualifiers ToQuals = ToType.getQualifiers(); 2764 2765 // Objective-C ARC: 2766 // Check Objective-C lifetime conversions. 2767 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2768 UnwrappedAnyPointer) { 2769 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2770 ObjCLifetimeConversion = true; 2771 FromQuals.removeObjCLifetime(); 2772 ToQuals.removeObjCLifetime(); 2773 } else { 2774 // Qualification conversions cannot cast between different 2775 // Objective-C lifetime qualifiers. 2776 return false; 2777 } 2778 } 2779 2780 // Allow addition/removal of GC attributes but not changing GC attributes. 2781 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2782 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2783 FromQuals.removeObjCGCAttr(); 2784 ToQuals.removeObjCGCAttr(); 2785 } 2786 2787 // -- for every j > 0, if const is in cv 1,j then const is in cv 2788 // 2,j, and similarly for volatile. 2789 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2790 return false; 2791 2792 // -- if the cv 1,j and cv 2,j are different, then const is in 2793 // every cv for 0 < k < j. 2794 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2795 && !PreviousToQualsIncludeConst) 2796 return false; 2797 2798 // Keep track of whether all prior cv-qualifiers in the "to" type 2799 // include const. 2800 PreviousToQualsIncludeConst 2801 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2802 } 2803 2804 // We are left with FromType and ToType being the pointee types 2805 // after unwrapping the original FromType and ToType the same number 2806 // of types. If we unwrapped any pointers, and if FromType and 2807 // ToType have the same unqualified type (since we checked 2808 // qualifiers above), then this is a qualification conversion. 2809 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2810} 2811 2812/// \brief - Determine whether this is a conversion from a scalar type to an 2813/// atomic type. 2814/// 2815/// If successful, updates \c SCS's second and third steps in the conversion 2816/// sequence to finish the conversion. 2817static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2818 bool InOverloadResolution, 2819 StandardConversionSequence &SCS, 2820 bool CStyle) { 2821 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2822 if (!ToAtomic) 2823 return false; 2824 2825 StandardConversionSequence InnerSCS; 2826 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2827 InOverloadResolution, InnerSCS, 2828 CStyle, /*AllowObjCWritebackConversion=*/false)) 2829 return false; 2830 2831 SCS.Second = InnerSCS.Second; 2832 SCS.setToType(1, InnerSCS.getToType(1)); 2833 SCS.Third = InnerSCS.Third; 2834 SCS.QualificationIncludesObjCLifetime 2835 = InnerSCS.QualificationIncludesObjCLifetime; 2836 SCS.setToType(2, InnerSCS.getToType(2)); 2837 return true; 2838} 2839 2840static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2841 CXXConstructorDecl *Constructor, 2842 QualType Type) { 2843 const FunctionProtoType *CtorType = 2844 Constructor->getType()->getAs<FunctionProtoType>(); 2845 if (CtorType->getNumArgs() > 0) { 2846 QualType FirstArg = CtorType->getArgType(0); 2847 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2848 return true; 2849 } 2850 return false; 2851} 2852 2853static OverloadingResult 2854IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2855 CXXRecordDecl *To, 2856 UserDefinedConversionSequence &User, 2857 OverloadCandidateSet &CandidateSet, 2858 bool AllowExplicit) { 2859 DeclContext::lookup_iterator Con, ConEnd; 2860 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To); 2861 Con != ConEnd; ++Con) { 2862 NamedDecl *D = *Con; 2863 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2864 2865 // Find the constructor (which may be a template). 2866 CXXConstructorDecl *Constructor = 0; 2867 FunctionTemplateDecl *ConstructorTmpl 2868 = dyn_cast<FunctionTemplateDecl>(D); 2869 if (ConstructorTmpl) 2870 Constructor 2871 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2872 else 2873 Constructor = cast<CXXConstructorDecl>(D); 2874 2875 bool Usable = !Constructor->isInvalidDecl() && 2876 S.isInitListConstructor(Constructor) && 2877 (AllowExplicit || !Constructor->isExplicit()); 2878 if (Usable) { 2879 // If the first argument is (a reference to) the target type, 2880 // suppress conversions. 2881 bool SuppressUserConversions = 2882 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2883 if (ConstructorTmpl) 2884 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2885 /*ExplicitArgs*/ 0, 2886 From, CandidateSet, 2887 SuppressUserConversions); 2888 else 2889 S.AddOverloadCandidate(Constructor, FoundDecl, 2890 From, CandidateSet, 2891 SuppressUserConversions); 2892 } 2893 } 2894 2895 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2896 2897 OverloadCandidateSet::iterator Best; 2898 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2899 case OR_Success: { 2900 // Record the standard conversion we used and the conversion function. 2901 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2902 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 2903 2904 QualType ThisType = Constructor->getThisType(S.Context); 2905 // Initializer lists don't have conversions as such. 2906 User.Before.setAsIdentityConversion(); 2907 User.HadMultipleCandidates = HadMultipleCandidates; 2908 User.ConversionFunction = Constructor; 2909 User.FoundConversionFunction = Best->FoundDecl; 2910 User.After.setAsIdentityConversion(); 2911 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2912 User.After.setAllToTypes(ToType); 2913 return OR_Success; 2914 } 2915 2916 case OR_No_Viable_Function: 2917 return OR_No_Viable_Function; 2918 case OR_Deleted: 2919 return OR_Deleted; 2920 case OR_Ambiguous: 2921 return OR_Ambiguous; 2922 } 2923 2924 llvm_unreachable("Invalid OverloadResult!"); 2925} 2926 2927/// Determines whether there is a user-defined conversion sequence 2928/// (C++ [over.ics.user]) that converts expression From to the type 2929/// ToType. If such a conversion exists, User will contain the 2930/// user-defined conversion sequence that performs such a conversion 2931/// and this routine will return true. Otherwise, this routine returns 2932/// false and User is unspecified. 2933/// 2934/// \param AllowExplicit true if the conversion should consider C++0x 2935/// "explicit" conversion functions as well as non-explicit conversion 2936/// functions (C++0x [class.conv.fct]p2). 2937static OverloadingResult 2938IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2939 UserDefinedConversionSequence &User, 2940 OverloadCandidateSet &CandidateSet, 2941 bool AllowExplicit) { 2942 // Whether we will only visit constructors. 2943 bool ConstructorsOnly = false; 2944 2945 // If the type we are conversion to is a class type, enumerate its 2946 // constructors. 2947 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2948 // C++ [over.match.ctor]p1: 2949 // When objects of class type are direct-initialized (8.5), or 2950 // copy-initialized from an expression of the same or a 2951 // derived class type (8.5), overload resolution selects the 2952 // constructor. [...] For copy-initialization, the candidate 2953 // functions are all the converting constructors (12.3.1) of 2954 // that class. The argument list is the expression-list within 2955 // the parentheses of the initializer. 2956 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 2957 (From->getType()->getAs<RecordType>() && 2958 S.IsDerivedFrom(From->getType(), ToType))) 2959 ConstructorsOnly = true; 2960 2961 S.RequireCompleteType(From->getLocStart(), ToType, 0); 2962 // RequireCompleteType may have returned true due to some invalid decl 2963 // during template instantiation, but ToType may be complete enough now 2964 // to try to recover. 2965 if (ToType->isIncompleteType()) { 2966 // We're not going to find any constructors. 2967 } else if (CXXRecordDecl *ToRecordDecl 2968 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 2969 2970 Expr **Args = &From; 2971 unsigned NumArgs = 1; 2972 bool ListInitializing = false; 2973 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 2974 // But first, see if there is an init-list-contructor that will work. 2975 OverloadingResult Result = IsInitializerListConstructorConversion( 2976 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 2977 if (Result != OR_No_Viable_Function) 2978 return Result; 2979 // Never mind. 2980 CandidateSet.clear(); 2981 2982 // If we're list-initializing, we pass the individual elements as 2983 // arguments, not the entire list. 2984 Args = InitList->getInits(); 2985 NumArgs = InitList->getNumInits(); 2986 ListInitializing = true; 2987 } 2988 2989 DeclContext::lookup_iterator Con, ConEnd; 2990 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl); 2991 Con != ConEnd; ++Con) { 2992 NamedDecl *D = *Con; 2993 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2994 2995 // Find the constructor (which may be a template). 2996 CXXConstructorDecl *Constructor = 0; 2997 FunctionTemplateDecl *ConstructorTmpl 2998 = dyn_cast<FunctionTemplateDecl>(D); 2999 if (ConstructorTmpl) 3000 Constructor 3001 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3002 else 3003 Constructor = cast<CXXConstructorDecl>(D); 3004 3005 bool Usable = !Constructor->isInvalidDecl(); 3006 if (ListInitializing) 3007 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3008 else 3009 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3010 if (Usable) { 3011 bool SuppressUserConversions = !ConstructorsOnly; 3012 if (SuppressUserConversions && ListInitializing) { 3013 SuppressUserConversions = false; 3014 if (NumArgs == 1) { 3015 // If the first argument is (a reference to) the target type, 3016 // suppress conversions. 3017 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3018 S.Context, Constructor, ToType); 3019 } 3020 } 3021 if (ConstructorTmpl) 3022 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3023 /*ExplicitArgs*/ 0, 3024 llvm::makeArrayRef(Args, NumArgs), 3025 CandidateSet, SuppressUserConversions); 3026 else 3027 // Allow one user-defined conversion when user specifies a 3028 // From->ToType conversion via an static cast (c-style, etc). 3029 S.AddOverloadCandidate(Constructor, FoundDecl, 3030 llvm::makeArrayRef(Args, NumArgs), 3031 CandidateSet, SuppressUserConversions); 3032 } 3033 } 3034 } 3035 } 3036 3037 // Enumerate conversion functions, if we're allowed to. 3038 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3039 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3040 // No conversion functions from incomplete types. 3041 } else if (const RecordType *FromRecordType 3042 = From->getType()->getAs<RecordType>()) { 3043 if (CXXRecordDecl *FromRecordDecl 3044 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3045 // Add all of the conversion functions as candidates. 3046 const UnresolvedSetImpl *Conversions 3047 = FromRecordDecl->getVisibleConversionFunctions(); 3048 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3049 E = Conversions->end(); I != E; ++I) { 3050 DeclAccessPair FoundDecl = I.getPair(); 3051 NamedDecl *D = FoundDecl.getDecl(); 3052 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3053 if (isa<UsingShadowDecl>(D)) 3054 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3055 3056 CXXConversionDecl *Conv; 3057 FunctionTemplateDecl *ConvTemplate; 3058 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3059 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3060 else 3061 Conv = cast<CXXConversionDecl>(D); 3062 3063 if (AllowExplicit || !Conv->isExplicit()) { 3064 if (ConvTemplate) 3065 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3066 ActingContext, From, ToType, 3067 CandidateSet); 3068 else 3069 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3070 From, ToType, CandidateSet); 3071 } 3072 } 3073 } 3074 } 3075 3076 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3077 3078 OverloadCandidateSet::iterator Best; 3079 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3080 case OR_Success: 3081 // Record the standard conversion we used and the conversion function. 3082 if (CXXConstructorDecl *Constructor 3083 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3084 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 3085 3086 // C++ [over.ics.user]p1: 3087 // If the user-defined conversion is specified by a 3088 // constructor (12.3.1), the initial standard conversion 3089 // sequence converts the source type to the type required by 3090 // the argument of the constructor. 3091 // 3092 QualType ThisType = Constructor->getThisType(S.Context); 3093 if (isa<InitListExpr>(From)) { 3094 // Initializer lists don't have conversions as such. 3095 User.Before.setAsIdentityConversion(); 3096 } else { 3097 if (Best->Conversions[0].isEllipsis()) 3098 User.EllipsisConversion = true; 3099 else { 3100 User.Before = Best->Conversions[0].Standard; 3101 User.EllipsisConversion = false; 3102 } 3103 } 3104 User.HadMultipleCandidates = HadMultipleCandidates; 3105 User.ConversionFunction = Constructor; 3106 User.FoundConversionFunction = Best->FoundDecl; 3107 User.After.setAsIdentityConversion(); 3108 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3109 User.After.setAllToTypes(ToType); 3110 return OR_Success; 3111 } 3112 if (CXXConversionDecl *Conversion 3113 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3114 S.MarkFunctionReferenced(From->getLocStart(), Conversion); 3115 3116 // C++ [over.ics.user]p1: 3117 // 3118 // [...] If the user-defined conversion is specified by a 3119 // conversion function (12.3.2), the initial standard 3120 // conversion sequence converts the source type to the 3121 // implicit object parameter of the conversion function. 3122 User.Before = Best->Conversions[0].Standard; 3123 User.HadMultipleCandidates = HadMultipleCandidates; 3124 User.ConversionFunction = Conversion; 3125 User.FoundConversionFunction = Best->FoundDecl; 3126 User.EllipsisConversion = false; 3127 3128 // C++ [over.ics.user]p2: 3129 // The second standard conversion sequence converts the 3130 // result of the user-defined conversion to the target type 3131 // for the sequence. Since an implicit conversion sequence 3132 // is an initialization, the special rules for 3133 // initialization by user-defined conversion apply when 3134 // selecting the best user-defined conversion for a 3135 // user-defined conversion sequence (see 13.3.3 and 3136 // 13.3.3.1). 3137 User.After = Best->FinalConversion; 3138 return OR_Success; 3139 } 3140 llvm_unreachable("Not a constructor or conversion function?"); 3141 3142 case OR_No_Viable_Function: 3143 return OR_No_Viable_Function; 3144 case OR_Deleted: 3145 // No conversion here! We're done. 3146 return OR_Deleted; 3147 3148 case OR_Ambiguous: 3149 return OR_Ambiguous; 3150 } 3151 3152 llvm_unreachable("Invalid OverloadResult!"); 3153} 3154 3155bool 3156Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3157 ImplicitConversionSequence ICS; 3158 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3159 OverloadingResult OvResult = 3160 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3161 CandidateSet, false); 3162 if (OvResult == OR_Ambiguous) 3163 Diag(From->getLocStart(), 3164 diag::err_typecheck_ambiguous_condition) 3165 << From->getType() << ToType << From->getSourceRange(); 3166 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3167 Diag(From->getLocStart(), 3168 diag::err_typecheck_nonviable_condition) 3169 << From->getType() << ToType << From->getSourceRange(); 3170 else 3171 return false; 3172 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3173 return true; 3174} 3175 3176/// \brief Compare the user-defined conversion functions or constructors 3177/// of two user-defined conversion sequences to determine whether any ordering 3178/// is possible. 3179static ImplicitConversionSequence::CompareKind 3180compareConversionFunctions(Sema &S, 3181 FunctionDecl *Function1, 3182 FunctionDecl *Function2) { 3183 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x) 3184 return ImplicitConversionSequence::Indistinguishable; 3185 3186 // Objective-C++: 3187 // If both conversion functions are implicitly-declared conversions from 3188 // a lambda closure type to a function pointer and a block pointer, 3189 // respectively, always prefer the conversion to a function pointer, 3190 // because the function pointer is more lightweight and is more likely 3191 // to keep code working. 3192 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3193 if (!Conv1) 3194 return ImplicitConversionSequence::Indistinguishable; 3195 3196 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3197 if (!Conv2) 3198 return ImplicitConversionSequence::Indistinguishable; 3199 3200 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3201 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3202 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3203 if (Block1 != Block2) 3204 return Block1? ImplicitConversionSequence::Worse 3205 : ImplicitConversionSequence::Better; 3206 } 3207 3208 return ImplicitConversionSequence::Indistinguishable; 3209} 3210 3211/// CompareImplicitConversionSequences - Compare two implicit 3212/// conversion sequences to determine whether one is better than the 3213/// other or if they are indistinguishable (C++ 13.3.3.2). 3214static ImplicitConversionSequence::CompareKind 3215CompareImplicitConversionSequences(Sema &S, 3216 const ImplicitConversionSequence& ICS1, 3217 const ImplicitConversionSequence& ICS2) 3218{ 3219 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3220 // conversion sequences (as defined in 13.3.3.1) 3221 // -- a standard conversion sequence (13.3.3.1.1) is a better 3222 // conversion sequence than a user-defined conversion sequence or 3223 // an ellipsis conversion sequence, and 3224 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3225 // conversion sequence than an ellipsis conversion sequence 3226 // (13.3.3.1.3). 3227 // 3228 // C++0x [over.best.ics]p10: 3229 // For the purpose of ranking implicit conversion sequences as 3230 // described in 13.3.3.2, the ambiguous conversion sequence is 3231 // treated as a user-defined sequence that is indistinguishable 3232 // from any other user-defined conversion sequence. 3233 if (ICS1.getKindRank() < ICS2.getKindRank()) 3234 return ImplicitConversionSequence::Better; 3235 if (ICS2.getKindRank() < ICS1.getKindRank()) 3236 return ImplicitConversionSequence::Worse; 3237 3238 // The following checks require both conversion sequences to be of 3239 // the same kind. 3240 if (ICS1.getKind() != ICS2.getKind()) 3241 return ImplicitConversionSequence::Indistinguishable; 3242 3243 ImplicitConversionSequence::CompareKind Result = 3244 ImplicitConversionSequence::Indistinguishable; 3245 3246 // Two implicit conversion sequences of the same form are 3247 // indistinguishable conversion sequences unless one of the 3248 // following rules apply: (C++ 13.3.3.2p3): 3249 if (ICS1.isStandard()) 3250 Result = CompareStandardConversionSequences(S, 3251 ICS1.Standard, ICS2.Standard); 3252 else if (ICS1.isUserDefined()) { 3253 // User-defined conversion sequence U1 is a better conversion 3254 // sequence than another user-defined conversion sequence U2 if 3255 // they contain the same user-defined conversion function or 3256 // constructor and if the second standard conversion sequence of 3257 // U1 is better than the second standard conversion sequence of 3258 // U2 (C++ 13.3.3.2p3). 3259 if (ICS1.UserDefined.ConversionFunction == 3260 ICS2.UserDefined.ConversionFunction) 3261 Result = CompareStandardConversionSequences(S, 3262 ICS1.UserDefined.After, 3263 ICS2.UserDefined.After); 3264 else 3265 Result = compareConversionFunctions(S, 3266 ICS1.UserDefined.ConversionFunction, 3267 ICS2.UserDefined.ConversionFunction); 3268 } 3269 3270 // List-initialization sequence L1 is a better conversion sequence than 3271 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3272 // for some X and L2 does not. 3273 if (Result == ImplicitConversionSequence::Indistinguishable && 3274 !ICS1.isBad() && 3275 ICS1.isListInitializationSequence() && 3276 ICS2.isListInitializationSequence()) { 3277 if (ICS1.isStdInitializerListElement() && 3278 !ICS2.isStdInitializerListElement()) 3279 return ImplicitConversionSequence::Better; 3280 if (!ICS1.isStdInitializerListElement() && 3281 ICS2.isStdInitializerListElement()) 3282 return ImplicitConversionSequence::Worse; 3283 } 3284 3285 return Result; 3286} 3287 3288static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3289 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3290 Qualifiers Quals; 3291 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3292 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3293 } 3294 3295 return Context.hasSameUnqualifiedType(T1, T2); 3296} 3297 3298// Per 13.3.3.2p3, compare the given standard conversion sequences to 3299// determine if one is a proper subset of the other. 3300static ImplicitConversionSequence::CompareKind 3301compareStandardConversionSubsets(ASTContext &Context, 3302 const StandardConversionSequence& SCS1, 3303 const StandardConversionSequence& SCS2) { 3304 ImplicitConversionSequence::CompareKind Result 3305 = ImplicitConversionSequence::Indistinguishable; 3306 3307 // the identity conversion sequence is considered to be a subsequence of 3308 // any non-identity conversion sequence 3309 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3310 return ImplicitConversionSequence::Better; 3311 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3312 return ImplicitConversionSequence::Worse; 3313 3314 if (SCS1.Second != SCS2.Second) { 3315 if (SCS1.Second == ICK_Identity) 3316 Result = ImplicitConversionSequence::Better; 3317 else if (SCS2.Second == ICK_Identity) 3318 Result = ImplicitConversionSequence::Worse; 3319 else 3320 return ImplicitConversionSequence::Indistinguishable; 3321 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3322 return ImplicitConversionSequence::Indistinguishable; 3323 3324 if (SCS1.Third == SCS2.Third) { 3325 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3326 : ImplicitConversionSequence::Indistinguishable; 3327 } 3328 3329 if (SCS1.Third == ICK_Identity) 3330 return Result == ImplicitConversionSequence::Worse 3331 ? ImplicitConversionSequence::Indistinguishable 3332 : ImplicitConversionSequence::Better; 3333 3334 if (SCS2.Third == ICK_Identity) 3335 return Result == ImplicitConversionSequence::Better 3336 ? ImplicitConversionSequence::Indistinguishable 3337 : ImplicitConversionSequence::Worse; 3338 3339 return ImplicitConversionSequence::Indistinguishable; 3340} 3341 3342/// \brief Determine whether one of the given reference bindings is better 3343/// than the other based on what kind of bindings they are. 3344static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3345 const StandardConversionSequence &SCS2) { 3346 // C++0x [over.ics.rank]p3b4: 3347 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3348 // implicit object parameter of a non-static member function declared 3349 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3350 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3351 // lvalue reference to a function lvalue and S2 binds an rvalue 3352 // reference*. 3353 // 3354 // FIXME: Rvalue references. We're going rogue with the above edits, 3355 // because the semantics in the current C++0x working paper (N3225 at the 3356 // time of this writing) break the standard definition of std::forward 3357 // and std::reference_wrapper when dealing with references to functions. 3358 // Proposed wording changes submitted to CWG for consideration. 3359 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3360 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3361 return false; 3362 3363 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3364 SCS2.IsLvalueReference) || 3365 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3366 !SCS2.IsLvalueReference); 3367} 3368 3369/// CompareStandardConversionSequences - Compare two standard 3370/// conversion sequences to determine whether one is better than the 3371/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3372static ImplicitConversionSequence::CompareKind 3373CompareStandardConversionSequences(Sema &S, 3374 const StandardConversionSequence& SCS1, 3375 const StandardConversionSequence& SCS2) 3376{ 3377 // Standard conversion sequence S1 is a better conversion sequence 3378 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3379 3380 // -- S1 is a proper subsequence of S2 (comparing the conversion 3381 // sequences in the canonical form defined by 13.3.3.1.1, 3382 // excluding any Lvalue Transformation; the identity conversion 3383 // sequence is considered to be a subsequence of any 3384 // non-identity conversion sequence) or, if not that, 3385 if (ImplicitConversionSequence::CompareKind CK 3386 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3387 return CK; 3388 3389 // -- the rank of S1 is better than the rank of S2 (by the rules 3390 // defined below), or, if not that, 3391 ImplicitConversionRank Rank1 = SCS1.getRank(); 3392 ImplicitConversionRank Rank2 = SCS2.getRank(); 3393 if (Rank1 < Rank2) 3394 return ImplicitConversionSequence::Better; 3395 else if (Rank2 < Rank1) 3396 return ImplicitConversionSequence::Worse; 3397 3398 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3399 // are indistinguishable unless one of the following rules 3400 // applies: 3401 3402 // A conversion that is not a conversion of a pointer, or 3403 // pointer to member, to bool is better than another conversion 3404 // that is such a conversion. 3405 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3406 return SCS2.isPointerConversionToBool() 3407 ? ImplicitConversionSequence::Better 3408 : ImplicitConversionSequence::Worse; 3409 3410 // C++ [over.ics.rank]p4b2: 3411 // 3412 // If class B is derived directly or indirectly from class A, 3413 // conversion of B* to A* is better than conversion of B* to 3414 // void*, and conversion of A* to void* is better than conversion 3415 // of B* to void*. 3416 bool SCS1ConvertsToVoid 3417 = SCS1.isPointerConversionToVoidPointer(S.Context); 3418 bool SCS2ConvertsToVoid 3419 = SCS2.isPointerConversionToVoidPointer(S.Context); 3420 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3421 // Exactly one of the conversion sequences is a conversion to 3422 // a void pointer; it's the worse conversion. 3423 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3424 : ImplicitConversionSequence::Worse; 3425 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3426 // Neither conversion sequence converts to a void pointer; compare 3427 // their derived-to-base conversions. 3428 if (ImplicitConversionSequence::CompareKind DerivedCK 3429 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3430 return DerivedCK; 3431 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3432 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3433 // Both conversion sequences are conversions to void 3434 // pointers. Compare the source types to determine if there's an 3435 // inheritance relationship in their sources. 3436 QualType FromType1 = SCS1.getFromType(); 3437 QualType FromType2 = SCS2.getFromType(); 3438 3439 // Adjust the types we're converting from via the array-to-pointer 3440 // conversion, if we need to. 3441 if (SCS1.First == ICK_Array_To_Pointer) 3442 FromType1 = S.Context.getArrayDecayedType(FromType1); 3443 if (SCS2.First == ICK_Array_To_Pointer) 3444 FromType2 = S.Context.getArrayDecayedType(FromType2); 3445 3446 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3447 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3448 3449 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3450 return ImplicitConversionSequence::Better; 3451 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3452 return ImplicitConversionSequence::Worse; 3453 3454 // Objective-C++: If one interface is more specific than the 3455 // other, it is the better one. 3456 const ObjCObjectPointerType* FromObjCPtr1 3457 = FromType1->getAs<ObjCObjectPointerType>(); 3458 const ObjCObjectPointerType* FromObjCPtr2 3459 = FromType2->getAs<ObjCObjectPointerType>(); 3460 if (FromObjCPtr1 && FromObjCPtr2) { 3461 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3462 FromObjCPtr2); 3463 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3464 FromObjCPtr1); 3465 if (AssignLeft != AssignRight) { 3466 return AssignLeft? ImplicitConversionSequence::Better 3467 : ImplicitConversionSequence::Worse; 3468 } 3469 } 3470 } 3471 3472 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3473 // bullet 3). 3474 if (ImplicitConversionSequence::CompareKind QualCK 3475 = CompareQualificationConversions(S, SCS1, SCS2)) 3476 return QualCK; 3477 3478 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3479 // Check for a better reference binding based on the kind of bindings. 3480 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3481 return ImplicitConversionSequence::Better; 3482 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3483 return ImplicitConversionSequence::Worse; 3484 3485 // C++ [over.ics.rank]p3b4: 3486 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3487 // which the references refer are the same type except for 3488 // top-level cv-qualifiers, and the type to which the reference 3489 // initialized by S2 refers is more cv-qualified than the type 3490 // to which the reference initialized by S1 refers. 3491 QualType T1 = SCS1.getToType(2); 3492 QualType T2 = SCS2.getToType(2); 3493 T1 = S.Context.getCanonicalType(T1); 3494 T2 = S.Context.getCanonicalType(T2); 3495 Qualifiers T1Quals, T2Quals; 3496 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3497 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3498 if (UnqualT1 == UnqualT2) { 3499 // Objective-C++ ARC: If the references refer to objects with different 3500 // lifetimes, prefer bindings that don't change lifetime. 3501 if (SCS1.ObjCLifetimeConversionBinding != 3502 SCS2.ObjCLifetimeConversionBinding) { 3503 return SCS1.ObjCLifetimeConversionBinding 3504 ? ImplicitConversionSequence::Worse 3505 : ImplicitConversionSequence::Better; 3506 } 3507 3508 // If the type is an array type, promote the element qualifiers to the 3509 // type for comparison. 3510 if (isa<ArrayType>(T1) && T1Quals) 3511 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3512 if (isa<ArrayType>(T2) && T2Quals) 3513 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3514 if (T2.isMoreQualifiedThan(T1)) 3515 return ImplicitConversionSequence::Better; 3516 else if (T1.isMoreQualifiedThan(T2)) 3517 return ImplicitConversionSequence::Worse; 3518 } 3519 } 3520 3521 // In Microsoft mode, prefer an integral conversion to a 3522 // floating-to-integral conversion if the integral conversion 3523 // is between types of the same size. 3524 // For example: 3525 // void f(float); 3526 // void f(int); 3527 // int main { 3528 // long a; 3529 // f(a); 3530 // } 3531 // Here, MSVC will call f(int) instead of generating a compile error 3532 // as clang will do in standard mode. 3533 if (S.getLangOpts().MicrosoftMode && 3534 SCS1.Second == ICK_Integral_Conversion && 3535 SCS2.Second == ICK_Floating_Integral && 3536 S.Context.getTypeSize(SCS1.getFromType()) == 3537 S.Context.getTypeSize(SCS1.getToType(2))) 3538 return ImplicitConversionSequence::Better; 3539 3540 return ImplicitConversionSequence::Indistinguishable; 3541} 3542 3543/// CompareQualificationConversions - Compares two standard conversion 3544/// sequences to determine whether they can be ranked based on their 3545/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3546ImplicitConversionSequence::CompareKind 3547CompareQualificationConversions(Sema &S, 3548 const StandardConversionSequence& SCS1, 3549 const StandardConversionSequence& SCS2) { 3550 // C++ 13.3.3.2p3: 3551 // -- S1 and S2 differ only in their qualification conversion and 3552 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3553 // cv-qualification signature of type T1 is a proper subset of 3554 // the cv-qualification signature of type T2, and S1 is not the 3555 // deprecated string literal array-to-pointer conversion (4.2). 3556 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3557 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3558 return ImplicitConversionSequence::Indistinguishable; 3559 3560 // FIXME: the example in the standard doesn't use a qualification 3561 // conversion (!) 3562 QualType T1 = SCS1.getToType(2); 3563 QualType T2 = SCS2.getToType(2); 3564 T1 = S.Context.getCanonicalType(T1); 3565 T2 = S.Context.getCanonicalType(T2); 3566 Qualifiers T1Quals, T2Quals; 3567 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3568 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3569 3570 // If the types are the same, we won't learn anything by unwrapped 3571 // them. 3572 if (UnqualT1 == UnqualT2) 3573 return ImplicitConversionSequence::Indistinguishable; 3574 3575 // If the type is an array type, promote the element qualifiers to the type 3576 // for comparison. 3577 if (isa<ArrayType>(T1) && T1Quals) 3578 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3579 if (isa<ArrayType>(T2) && T2Quals) 3580 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3581 3582 ImplicitConversionSequence::CompareKind Result 3583 = ImplicitConversionSequence::Indistinguishable; 3584 3585 // Objective-C++ ARC: 3586 // Prefer qualification conversions not involving a change in lifetime 3587 // to qualification conversions that do not change lifetime. 3588 if (SCS1.QualificationIncludesObjCLifetime != 3589 SCS2.QualificationIncludesObjCLifetime) { 3590 Result = SCS1.QualificationIncludesObjCLifetime 3591 ? ImplicitConversionSequence::Worse 3592 : ImplicitConversionSequence::Better; 3593 } 3594 3595 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3596 // Within each iteration of the loop, we check the qualifiers to 3597 // determine if this still looks like a qualification 3598 // conversion. Then, if all is well, we unwrap one more level of 3599 // pointers or pointers-to-members and do it all again 3600 // until there are no more pointers or pointers-to-members left 3601 // to unwrap. This essentially mimics what 3602 // IsQualificationConversion does, but here we're checking for a 3603 // strict subset of qualifiers. 3604 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3605 // The qualifiers are the same, so this doesn't tell us anything 3606 // about how the sequences rank. 3607 ; 3608 else if (T2.isMoreQualifiedThan(T1)) { 3609 // T1 has fewer qualifiers, so it could be the better sequence. 3610 if (Result == ImplicitConversionSequence::Worse) 3611 // Neither has qualifiers that are a subset of the other's 3612 // qualifiers. 3613 return ImplicitConversionSequence::Indistinguishable; 3614 3615 Result = ImplicitConversionSequence::Better; 3616 } else if (T1.isMoreQualifiedThan(T2)) { 3617 // T2 has fewer qualifiers, so it could be the better sequence. 3618 if (Result == ImplicitConversionSequence::Better) 3619 // Neither has qualifiers that are a subset of the other's 3620 // qualifiers. 3621 return ImplicitConversionSequence::Indistinguishable; 3622 3623 Result = ImplicitConversionSequence::Worse; 3624 } else { 3625 // Qualifiers are disjoint. 3626 return ImplicitConversionSequence::Indistinguishable; 3627 } 3628 3629 // If the types after this point are equivalent, we're done. 3630 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3631 break; 3632 } 3633 3634 // Check that the winning standard conversion sequence isn't using 3635 // the deprecated string literal array to pointer conversion. 3636 switch (Result) { 3637 case ImplicitConversionSequence::Better: 3638 if (SCS1.DeprecatedStringLiteralToCharPtr) 3639 Result = ImplicitConversionSequence::Indistinguishable; 3640 break; 3641 3642 case ImplicitConversionSequence::Indistinguishable: 3643 break; 3644 3645 case ImplicitConversionSequence::Worse: 3646 if (SCS2.DeprecatedStringLiteralToCharPtr) 3647 Result = ImplicitConversionSequence::Indistinguishable; 3648 break; 3649 } 3650 3651 return Result; 3652} 3653 3654/// CompareDerivedToBaseConversions - Compares two standard conversion 3655/// sequences to determine whether they can be ranked based on their 3656/// various kinds of derived-to-base conversions (C++ 3657/// [over.ics.rank]p4b3). As part of these checks, we also look at 3658/// conversions between Objective-C interface types. 3659ImplicitConversionSequence::CompareKind 3660CompareDerivedToBaseConversions(Sema &S, 3661 const StandardConversionSequence& SCS1, 3662 const StandardConversionSequence& SCS2) { 3663 QualType FromType1 = SCS1.getFromType(); 3664 QualType ToType1 = SCS1.getToType(1); 3665 QualType FromType2 = SCS2.getFromType(); 3666 QualType ToType2 = SCS2.getToType(1); 3667 3668 // Adjust the types we're converting from via the array-to-pointer 3669 // conversion, if we need to. 3670 if (SCS1.First == ICK_Array_To_Pointer) 3671 FromType1 = S.Context.getArrayDecayedType(FromType1); 3672 if (SCS2.First == ICK_Array_To_Pointer) 3673 FromType2 = S.Context.getArrayDecayedType(FromType2); 3674 3675 // Canonicalize all of the types. 3676 FromType1 = S.Context.getCanonicalType(FromType1); 3677 ToType1 = S.Context.getCanonicalType(ToType1); 3678 FromType2 = S.Context.getCanonicalType(FromType2); 3679 ToType2 = S.Context.getCanonicalType(ToType2); 3680 3681 // C++ [over.ics.rank]p4b3: 3682 // 3683 // If class B is derived directly or indirectly from class A and 3684 // class C is derived directly or indirectly from B, 3685 // 3686 // Compare based on pointer conversions. 3687 if (SCS1.Second == ICK_Pointer_Conversion && 3688 SCS2.Second == ICK_Pointer_Conversion && 3689 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3690 FromType1->isPointerType() && FromType2->isPointerType() && 3691 ToType1->isPointerType() && ToType2->isPointerType()) { 3692 QualType FromPointee1 3693 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3694 QualType ToPointee1 3695 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3696 QualType FromPointee2 3697 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3698 QualType ToPointee2 3699 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3700 3701 // -- conversion of C* to B* is better than conversion of C* to A*, 3702 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3703 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3704 return ImplicitConversionSequence::Better; 3705 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3706 return ImplicitConversionSequence::Worse; 3707 } 3708 3709 // -- conversion of B* to A* is better than conversion of C* to A*, 3710 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3711 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3712 return ImplicitConversionSequence::Better; 3713 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3714 return ImplicitConversionSequence::Worse; 3715 } 3716 } else if (SCS1.Second == ICK_Pointer_Conversion && 3717 SCS2.Second == ICK_Pointer_Conversion) { 3718 const ObjCObjectPointerType *FromPtr1 3719 = FromType1->getAs<ObjCObjectPointerType>(); 3720 const ObjCObjectPointerType *FromPtr2 3721 = FromType2->getAs<ObjCObjectPointerType>(); 3722 const ObjCObjectPointerType *ToPtr1 3723 = ToType1->getAs<ObjCObjectPointerType>(); 3724 const ObjCObjectPointerType *ToPtr2 3725 = ToType2->getAs<ObjCObjectPointerType>(); 3726 3727 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3728 // Apply the same conversion ranking rules for Objective-C pointer types 3729 // that we do for C++ pointers to class types. However, we employ the 3730 // Objective-C pseudo-subtyping relationship used for assignment of 3731 // Objective-C pointer types. 3732 bool FromAssignLeft 3733 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3734 bool FromAssignRight 3735 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3736 bool ToAssignLeft 3737 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3738 bool ToAssignRight 3739 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3740 3741 // A conversion to an a non-id object pointer type or qualified 'id' 3742 // type is better than a conversion to 'id'. 3743 if (ToPtr1->isObjCIdType() && 3744 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3745 return ImplicitConversionSequence::Worse; 3746 if (ToPtr2->isObjCIdType() && 3747 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3748 return ImplicitConversionSequence::Better; 3749 3750 // A conversion to a non-id object pointer type is better than a 3751 // conversion to a qualified 'id' type 3752 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3753 return ImplicitConversionSequence::Worse; 3754 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3755 return ImplicitConversionSequence::Better; 3756 3757 // A conversion to an a non-Class object pointer type or qualified 'Class' 3758 // type is better than a conversion to 'Class'. 3759 if (ToPtr1->isObjCClassType() && 3760 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3761 return ImplicitConversionSequence::Worse; 3762 if (ToPtr2->isObjCClassType() && 3763 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3764 return ImplicitConversionSequence::Better; 3765 3766 // A conversion to a non-Class object pointer type is better than a 3767 // conversion to a qualified 'Class' type. 3768 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3769 return ImplicitConversionSequence::Worse; 3770 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3771 return ImplicitConversionSequence::Better; 3772 3773 // -- "conversion of C* to B* is better than conversion of C* to A*," 3774 if (S.Context.hasSameType(FromType1, FromType2) && 3775 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3776 (ToAssignLeft != ToAssignRight)) 3777 return ToAssignLeft? ImplicitConversionSequence::Worse 3778 : ImplicitConversionSequence::Better; 3779 3780 // -- "conversion of B* to A* is better than conversion of C* to A*," 3781 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3782 (FromAssignLeft != FromAssignRight)) 3783 return FromAssignLeft? ImplicitConversionSequence::Better 3784 : ImplicitConversionSequence::Worse; 3785 } 3786 } 3787 3788 // Ranking of member-pointer types. 3789 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3790 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3791 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3792 const MemberPointerType * FromMemPointer1 = 3793 FromType1->getAs<MemberPointerType>(); 3794 const MemberPointerType * ToMemPointer1 = 3795 ToType1->getAs<MemberPointerType>(); 3796 const MemberPointerType * FromMemPointer2 = 3797 FromType2->getAs<MemberPointerType>(); 3798 const MemberPointerType * ToMemPointer2 = 3799 ToType2->getAs<MemberPointerType>(); 3800 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3801 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3802 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3803 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3804 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3805 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3806 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3807 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3808 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3809 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3810 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3811 return ImplicitConversionSequence::Worse; 3812 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3813 return ImplicitConversionSequence::Better; 3814 } 3815 // conversion of B::* to C::* is better than conversion of A::* to C::* 3816 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3817 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3818 return ImplicitConversionSequence::Better; 3819 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3820 return ImplicitConversionSequence::Worse; 3821 } 3822 } 3823 3824 if (SCS1.Second == ICK_Derived_To_Base) { 3825 // -- conversion of C to B is better than conversion of C to A, 3826 // -- binding of an expression of type C to a reference of type 3827 // B& is better than binding an expression of type C to a 3828 // reference of type A&, 3829 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3830 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3831 if (S.IsDerivedFrom(ToType1, ToType2)) 3832 return ImplicitConversionSequence::Better; 3833 else if (S.IsDerivedFrom(ToType2, ToType1)) 3834 return ImplicitConversionSequence::Worse; 3835 } 3836 3837 // -- conversion of B to A is better than conversion of C to A. 3838 // -- binding of an expression of type B to a reference of type 3839 // A& is better than binding an expression of type C to a 3840 // reference of type A&, 3841 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3842 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3843 if (S.IsDerivedFrom(FromType2, FromType1)) 3844 return ImplicitConversionSequence::Better; 3845 else if (S.IsDerivedFrom(FromType1, FromType2)) 3846 return ImplicitConversionSequence::Worse; 3847 } 3848 } 3849 3850 return ImplicitConversionSequence::Indistinguishable; 3851} 3852 3853/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3854/// determine whether they are reference-related, 3855/// reference-compatible, reference-compatible with added 3856/// qualification, or incompatible, for use in C++ initialization by 3857/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3858/// type, and the first type (T1) is the pointee type of the reference 3859/// type being initialized. 3860Sema::ReferenceCompareResult 3861Sema::CompareReferenceRelationship(SourceLocation Loc, 3862 QualType OrigT1, QualType OrigT2, 3863 bool &DerivedToBase, 3864 bool &ObjCConversion, 3865 bool &ObjCLifetimeConversion) { 3866 assert(!OrigT1->isReferenceType() && 3867 "T1 must be the pointee type of the reference type"); 3868 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3869 3870 QualType T1 = Context.getCanonicalType(OrigT1); 3871 QualType T2 = Context.getCanonicalType(OrigT2); 3872 Qualifiers T1Quals, T2Quals; 3873 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3874 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3875 3876 // C++ [dcl.init.ref]p4: 3877 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3878 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3879 // T1 is a base class of T2. 3880 DerivedToBase = false; 3881 ObjCConversion = false; 3882 ObjCLifetimeConversion = false; 3883 if (UnqualT1 == UnqualT2) { 3884 // Nothing to do. 3885 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3886 IsDerivedFrom(UnqualT2, UnqualT1)) 3887 DerivedToBase = true; 3888 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3889 UnqualT2->isObjCObjectOrInterfaceType() && 3890 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3891 ObjCConversion = true; 3892 else 3893 return Ref_Incompatible; 3894 3895 // At this point, we know that T1 and T2 are reference-related (at 3896 // least). 3897 3898 // If the type is an array type, promote the element qualifiers to the type 3899 // for comparison. 3900 if (isa<ArrayType>(T1) && T1Quals) 3901 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3902 if (isa<ArrayType>(T2) && T2Quals) 3903 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3904 3905 // C++ [dcl.init.ref]p4: 3906 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3907 // reference-related to T2 and cv1 is the same cv-qualification 3908 // as, or greater cv-qualification than, cv2. For purposes of 3909 // overload resolution, cases for which cv1 is greater 3910 // cv-qualification than cv2 are identified as 3911 // reference-compatible with added qualification (see 13.3.3.2). 3912 // 3913 // Note that we also require equivalence of Objective-C GC and address-space 3914 // qualifiers when performing these computations, so that e.g., an int in 3915 // address space 1 is not reference-compatible with an int in address 3916 // space 2. 3917 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3918 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3919 T1Quals.removeObjCLifetime(); 3920 T2Quals.removeObjCLifetime(); 3921 ObjCLifetimeConversion = true; 3922 } 3923 3924 if (T1Quals == T2Quals) 3925 return Ref_Compatible; 3926 else if (T1Quals.compatiblyIncludes(T2Quals)) 3927 return Ref_Compatible_With_Added_Qualification; 3928 else 3929 return Ref_Related; 3930} 3931 3932/// \brief Look for a user-defined conversion to an value reference-compatible 3933/// with DeclType. Return true if something definite is found. 3934static bool 3935FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3936 QualType DeclType, SourceLocation DeclLoc, 3937 Expr *Init, QualType T2, bool AllowRvalues, 3938 bool AllowExplicit) { 3939 assert(T2->isRecordType() && "Can only find conversions of record types."); 3940 CXXRecordDecl *T2RecordDecl 3941 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3942 3943 OverloadCandidateSet CandidateSet(DeclLoc); 3944 const UnresolvedSetImpl *Conversions 3945 = T2RecordDecl->getVisibleConversionFunctions(); 3946 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3947 E = Conversions->end(); I != E; ++I) { 3948 NamedDecl *D = *I; 3949 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3950 if (isa<UsingShadowDecl>(D)) 3951 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3952 3953 FunctionTemplateDecl *ConvTemplate 3954 = dyn_cast<FunctionTemplateDecl>(D); 3955 CXXConversionDecl *Conv; 3956 if (ConvTemplate) 3957 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3958 else 3959 Conv = cast<CXXConversionDecl>(D); 3960 3961 // If this is an explicit conversion, and we're not allowed to consider 3962 // explicit conversions, skip it. 3963 if (!AllowExplicit && Conv->isExplicit()) 3964 continue; 3965 3966 if (AllowRvalues) { 3967 bool DerivedToBase = false; 3968 bool ObjCConversion = false; 3969 bool ObjCLifetimeConversion = false; 3970 3971 // If we are initializing an rvalue reference, don't permit conversion 3972 // functions that return lvalues. 3973 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 3974 const ReferenceType *RefType 3975 = Conv->getConversionType()->getAs<LValueReferenceType>(); 3976 if (RefType && !RefType->getPointeeType()->isFunctionType()) 3977 continue; 3978 } 3979 3980 if (!ConvTemplate && 3981 S.CompareReferenceRelationship( 3982 DeclLoc, 3983 Conv->getConversionType().getNonReferenceType() 3984 .getUnqualifiedType(), 3985 DeclType.getNonReferenceType().getUnqualifiedType(), 3986 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 3987 Sema::Ref_Incompatible) 3988 continue; 3989 } else { 3990 // If the conversion function doesn't return a reference type, 3991 // it can't be considered for this conversion. An rvalue reference 3992 // is only acceptable if its referencee is a function type. 3993 3994 const ReferenceType *RefType = 3995 Conv->getConversionType()->getAs<ReferenceType>(); 3996 if (!RefType || 3997 (!RefType->isLValueReferenceType() && 3998 !RefType->getPointeeType()->isFunctionType())) 3999 continue; 4000 } 4001 4002 if (ConvTemplate) 4003 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4004 Init, DeclType, CandidateSet); 4005 else 4006 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4007 DeclType, CandidateSet); 4008 } 4009 4010 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4011 4012 OverloadCandidateSet::iterator Best; 4013 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4014 case OR_Success: 4015 // C++ [over.ics.ref]p1: 4016 // 4017 // [...] If the parameter binds directly to the result of 4018 // applying a conversion function to the argument 4019 // expression, the implicit conversion sequence is a 4020 // user-defined conversion sequence (13.3.3.1.2), with the 4021 // second standard conversion sequence either an identity 4022 // conversion or, if the conversion function returns an 4023 // entity of a type that is a derived class of the parameter 4024 // type, a derived-to-base Conversion. 4025 if (!Best->FinalConversion.DirectBinding) 4026 return false; 4027 4028 if (Best->Function) 4029 S.MarkFunctionReferenced(DeclLoc, Best->Function); 4030 ICS.setUserDefined(); 4031 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4032 ICS.UserDefined.After = Best->FinalConversion; 4033 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4034 ICS.UserDefined.ConversionFunction = Best->Function; 4035 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4036 ICS.UserDefined.EllipsisConversion = false; 4037 assert(ICS.UserDefined.After.ReferenceBinding && 4038 ICS.UserDefined.After.DirectBinding && 4039 "Expected a direct reference binding!"); 4040 return true; 4041 4042 case OR_Ambiguous: 4043 ICS.setAmbiguous(); 4044 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4045 Cand != CandidateSet.end(); ++Cand) 4046 if (Cand->Viable) 4047 ICS.Ambiguous.addConversion(Cand->Function); 4048 return true; 4049 4050 case OR_No_Viable_Function: 4051 case OR_Deleted: 4052 // There was no suitable conversion, or we found a deleted 4053 // conversion; continue with other checks. 4054 return false; 4055 } 4056 4057 llvm_unreachable("Invalid OverloadResult!"); 4058} 4059 4060/// \brief Compute an implicit conversion sequence for reference 4061/// initialization. 4062static ImplicitConversionSequence 4063TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4064 SourceLocation DeclLoc, 4065 bool SuppressUserConversions, 4066 bool AllowExplicit) { 4067 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4068 4069 // Most paths end in a failed conversion. 4070 ImplicitConversionSequence ICS; 4071 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4072 4073 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4074 QualType T2 = Init->getType(); 4075 4076 // If the initializer is the address of an overloaded function, try 4077 // to resolve the overloaded function. If all goes well, T2 is the 4078 // type of the resulting function. 4079 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4080 DeclAccessPair Found; 4081 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4082 false, Found)) 4083 T2 = Fn->getType(); 4084 } 4085 4086 // Compute some basic properties of the types and the initializer. 4087 bool isRValRef = DeclType->isRValueReferenceType(); 4088 bool DerivedToBase = false; 4089 bool ObjCConversion = false; 4090 bool ObjCLifetimeConversion = false; 4091 Expr::Classification InitCategory = Init->Classify(S.Context); 4092 Sema::ReferenceCompareResult RefRelationship 4093 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4094 ObjCConversion, ObjCLifetimeConversion); 4095 4096 4097 // C++0x [dcl.init.ref]p5: 4098 // A reference to type "cv1 T1" is initialized by an expression 4099 // of type "cv2 T2" as follows: 4100 4101 // -- If reference is an lvalue reference and the initializer expression 4102 if (!isRValRef) { 4103 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4104 // reference-compatible with "cv2 T2," or 4105 // 4106 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4107 if (InitCategory.isLValue() && 4108 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4109 // C++ [over.ics.ref]p1: 4110 // When a parameter of reference type binds directly (8.5.3) 4111 // to an argument expression, the implicit conversion sequence 4112 // is the identity conversion, unless the argument expression 4113 // has a type that is a derived class of the parameter type, 4114 // in which case the implicit conversion sequence is a 4115 // derived-to-base Conversion (13.3.3.1). 4116 ICS.setStandard(); 4117 ICS.Standard.First = ICK_Identity; 4118 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4119 : ObjCConversion? ICK_Compatible_Conversion 4120 : ICK_Identity; 4121 ICS.Standard.Third = ICK_Identity; 4122 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4123 ICS.Standard.setToType(0, T2); 4124 ICS.Standard.setToType(1, T1); 4125 ICS.Standard.setToType(2, T1); 4126 ICS.Standard.ReferenceBinding = true; 4127 ICS.Standard.DirectBinding = true; 4128 ICS.Standard.IsLvalueReference = !isRValRef; 4129 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4130 ICS.Standard.BindsToRvalue = false; 4131 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4132 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4133 ICS.Standard.CopyConstructor = 0; 4134 4135 // Nothing more to do: the inaccessibility/ambiguity check for 4136 // derived-to-base conversions is suppressed when we're 4137 // computing the implicit conversion sequence (C++ 4138 // [over.best.ics]p2). 4139 return ICS; 4140 } 4141 4142 // -- has a class type (i.e., T2 is a class type), where T1 is 4143 // not reference-related to T2, and can be implicitly 4144 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4145 // is reference-compatible with "cv3 T3" 92) (this 4146 // conversion is selected by enumerating the applicable 4147 // conversion functions (13.3.1.6) and choosing the best 4148 // one through overload resolution (13.3)), 4149 if (!SuppressUserConversions && T2->isRecordType() && 4150 !S.RequireCompleteType(DeclLoc, T2, 0) && 4151 RefRelationship == Sema::Ref_Incompatible) { 4152 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4153 Init, T2, /*AllowRvalues=*/false, 4154 AllowExplicit)) 4155 return ICS; 4156 } 4157 } 4158 4159 // -- Otherwise, the reference shall be an lvalue reference to a 4160 // non-volatile const type (i.e., cv1 shall be const), or the reference 4161 // shall be an rvalue reference. 4162 // 4163 // We actually handle one oddity of C++ [over.ics.ref] at this 4164 // point, which is that, due to p2 (which short-circuits reference 4165 // binding by only attempting a simple conversion for non-direct 4166 // bindings) and p3's strange wording, we allow a const volatile 4167 // reference to bind to an rvalue. Hence the check for the presence 4168 // of "const" rather than checking for "const" being the only 4169 // qualifier. 4170 // This is also the point where rvalue references and lvalue inits no longer 4171 // go together. 4172 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4173 return ICS; 4174 4175 // -- If the initializer expression 4176 // 4177 // -- is an xvalue, class prvalue, array prvalue or function 4178 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4179 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4180 (InitCategory.isXValue() || 4181 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4182 (InitCategory.isLValue() && T2->isFunctionType()))) { 4183 ICS.setStandard(); 4184 ICS.Standard.First = ICK_Identity; 4185 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4186 : ObjCConversion? ICK_Compatible_Conversion 4187 : ICK_Identity; 4188 ICS.Standard.Third = ICK_Identity; 4189 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4190 ICS.Standard.setToType(0, T2); 4191 ICS.Standard.setToType(1, T1); 4192 ICS.Standard.setToType(2, T1); 4193 ICS.Standard.ReferenceBinding = true; 4194 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4195 // binding unless we're binding to a class prvalue. 4196 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4197 // allow the use of rvalue references in C++98/03 for the benefit of 4198 // standard library implementors; therefore, we need the xvalue check here. 4199 ICS.Standard.DirectBinding = 4200 S.getLangOpts().CPlusPlus0x || 4201 (InitCategory.isPRValue() && !T2->isRecordType()); 4202 ICS.Standard.IsLvalueReference = !isRValRef; 4203 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4204 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4205 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4206 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4207 ICS.Standard.CopyConstructor = 0; 4208 return ICS; 4209 } 4210 4211 // -- has a class type (i.e., T2 is a class type), where T1 is not 4212 // reference-related to T2, and can be implicitly converted to 4213 // an xvalue, class prvalue, or function lvalue of type 4214 // "cv3 T3", where "cv1 T1" is reference-compatible with 4215 // "cv3 T3", 4216 // 4217 // then the reference is bound to the value of the initializer 4218 // expression in the first case and to the result of the conversion 4219 // in the second case (or, in either case, to an appropriate base 4220 // class subobject). 4221 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4222 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4223 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4224 Init, T2, /*AllowRvalues=*/true, 4225 AllowExplicit)) { 4226 // In the second case, if the reference is an rvalue reference 4227 // and the second standard conversion sequence of the 4228 // user-defined conversion sequence includes an lvalue-to-rvalue 4229 // conversion, the program is ill-formed. 4230 if (ICS.isUserDefined() && isRValRef && 4231 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4232 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4233 4234 return ICS; 4235 } 4236 4237 // -- Otherwise, a temporary of type "cv1 T1" is created and 4238 // initialized from the initializer expression using the 4239 // rules for a non-reference copy initialization (8.5). The 4240 // reference is then bound to the temporary. If T1 is 4241 // reference-related to T2, cv1 must be the same 4242 // cv-qualification as, or greater cv-qualification than, 4243 // cv2; otherwise, the program is ill-formed. 4244 if (RefRelationship == Sema::Ref_Related) { 4245 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4246 // we would be reference-compatible or reference-compatible with 4247 // added qualification. But that wasn't the case, so the reference 4248 // initialization fails. 4249 // 4250 // Note that we only want to check address spaces and cvr-qualifiers here. 4251 // ObjC GC and lifetime qualifiers aren't important. 4252 Qualifiers T1Quals = T1.getQualifiers(); 4253 Qualifiers T2Quals = T2.getQualifiers(); 4254 T1Quals.removeObjCGCAttr(); 4255 T1Quals.removeObjCLifetime(); 4256 T2Quals.removeObjCGCAttr(); 4257 T2Quals.removeObjCLifetime(); 4258 if (!T1Quals.compatiblyIncludes(T2Quals)) 4259 return ICS; 4260 } 4261 4262 // If at least one of the types is a class type, the types are not 4263 // related, and we aren't allowed any user conversions, the 4264 // reference binding fails. This case is important for breaking 4265 // recursion, since TryImplicitConversion below will attempt to 4266 // create a temporary through the use of a copy constructor. 4267 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4268 (T1->isRecordType() || T2->isRecordType())) 4269 return ICS; 4270 4271 // If T1 is reference-related to T2 and the reference is an rvalue 4272 // reference, the initializer expression shall not be an lvalue. 4273 if (RefRelationship >= Sema::Ref_Related && 4274 isRValRef && Init->Classify(S.Context).isLValue()) 4275 return ICS; 4276 4277 // C++ [over.ics.ref]p2: 4278 // When a parameter of reference type is not bound directly to 4279 // an argument expression, the conversion sequence is the one 4280 // required to convert the argument expression to the 4281 // underlying type of the reference according to 4282 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4283 // to copy-initializing a temporary of the underlying type with 4284 // the argument expression. Any difference in top-level 4285 // cv-qualification is subsumed by the initialization itself 4286 // and does not constitute a conversion. 4287 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4288 /*AllowExplicit=*/false, 4289 /*InOverloadResolution=*/false, 4290 /*CStyle=*/false, 4291 /*AllowObjCWritebackConversion=*/false); 4292 4293 // Of course, that's still a reference binding. 4294 if (ICS.isStandard()) { 4295 ICS.Standard.ReferenceBinding = true; 4296 ICS.Standard.IsLvalueReference = !isRValRef; 4297 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4298 ICS.Standard.BindsToRvalue = true; 4299 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4300 ICS.Standard.ObjCLifetimeConversionBinding = false; 4301 } else if (ICS.isUserDefined()) { 4302 // Don't allow rvalue references to bind to lvalues. 4303 if (DeclType->isRValueReferenceType()) { 4304 if (const ReferenceType *RefType 4305 = ICS.UserDefined.ConversionFunction->getResultType() 4306 ->getAs<LValueReferenceType>()) { 4307 if (!RefType->getPointeeType()->isFunctionType()) { 4308 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4309 DeclType); 4310 return ICS; 4311 } 4312 } 4313 } 4314 4315 ICS.UserDefined.After.ReferenceBinding = true; 4316 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4317 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4318 ICS.UserDefined.After.BindsToRvalue = true; 4319 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4320 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4321 } 4322 4323 return ICS; 4324} 4325 4326static ImplicitConversionSequence 4327TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4328 bool SuppressUserConversions, 4329 bool InOverloadResolution, 4330 bool AllowObjCWritebackConversion, 4331 bool AllowExplicit = false); 4332 4333/// TryListConversion - Try to copy-initialize a value of type ToType from the 4334/// initializer list From. 4335static ImplicitConversionSequence 4336TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4337 bool SuppressUserConversions, 4338 bool InOverloadResolution, 4339 bool AllowObjCWritebackConversion) { 4340 // C++11 [over.ics.list]p1: 4341 // When an argument is an initializer list, it is not an expression and 4342 // special rules apply for converting it to a parameter type. 4343 4344 ImplicitConversionSequence Result; 4345 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4346 Result.setListInitializationSequence(); 4347 4348 // We need a complete type for what follows. Incomplete types can never be 4349 // initialized from init lists. 4350 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4351 return Result; 4352 4353 // C++11 [over.ics.list]p2: 4354 // If the parameter type is std::initializer_list<X> or "array of X" and 4355 // all the elements can be implicitly converted to X, the implicit 4356 // conversion sequence is the worst conversion necessary to convert an 4357 // element of the list to X. 4358 bool toStdInitializerList = false; 4359 QualType X; 4360 if (ToType->isArrayType()) 4361 X = S.Context.getBaseElementType(ToType); 4362 else 4363 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4364 if (!X.isNull()) { 4365 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4366 Expr *Init = From->getInit(i); 4367 ImplicitConversionSequence ICS = 4368 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4369 InOverloadResolution, 4370 AllowObjCWritebackConversion); 4371 // If a single element isn't convertible, fail. 4372 if (ICS.isBad()) { 4373 Result = ICS; 4374 break; 4375 } 4376 // Otherwise, look for the worst conversion. 4377 if (Result.isBad() || 4378 CompareImplicitConversionSequences(S, ICS, Result) == 4379 ImplicitConversionSequence::Worse) 4380 Result = ICS; 4381 } 4382 4383 // For an empty list, we won't have computed any conversion sequence. 4384 // Introduce the identity conversion sequence. 4385 if (From->getNumInits() == 0) { 4386 Result.setStandard(); 4387 Result.Standard.setAsIdentityConversion(); 4388 Result.Standard.setFromType(ToType); 4389 Result.Standard.setAllToTypes(ToType); 4390 } 4391 4392 Result.setListInitializationSequence(); 4393 Result.setStdInitializerListElement(toStdInitializerList); 4394 return Result; 4395 } 4396 4397 // C++11 [over.ics.list]p3: 4398 // Otherwise, if the parameter is a non-aggregate class X and overload 4399 // resolution chooses a single best constructor [...] the implicit 4400 // conversion sequence is a user-defined conversion sequence. If multiple 4401 // constructors are viable but none is better than the others, the 4402 // implicit conversion sequence is a user-defined conversion sequence. 4403 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4404 // This function can deal with initializer lists. 4405 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4406 /*AllowExplicit=*/false, 4407 InOverloadResolution, /*CStyle=*/false, 4408 AllowObjCWritebackConversion); 4409 Result.setListInitializationSequence(); 4410 return Result; 4411 } 4412 4413 // C++11 [over.ics.list]p4: 4414 // Otherwise, if the parameter has an aggregate type which can be 4415 // initialized from the initializer list [...] the implicit conversion 4416 // sequence is a user-defined conversion sequence. 4417 if (ToType->isAggregateType()) { 4418 // Type is an aggregate, argument is an init list. At this point it comes 4419 // down to checking whether the initialization works. 4420 // FIXME: Find out whether this parameter is consumed or not. 4421 InitializedEntity Entity = 4422 InitializedEntity::InitializeParameter(S.Context, ToType, 4423 /*Consumed=*/false); 4424 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4425 Result.setUserDefined(); 4426 Result.UserDefined.Before.setAsIdentityConversion(); 4427 // Initializer lists don't have a type. 4428 Result.UserDefined.Before.setFromType(QualType()); 4429 Result.UserDefined.Before.setAllToTypes(QualType()); 4430 4431 Result.UserDefined.After.setAsIdentityConversion(); 4432 Result.UserDefined.After.setFromType(ToType); 4433 Result.UserDefined.After.setAllToTypes(ToType); 4434 Result.UserDefined.ConversionFunction = 0; 4435 } 4436 return Result; 4437 } 4438 4439 // C++11 [over.ics.list]p5: 4440 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4441 if (ToType->isReferenceType()) { 4442 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4443 // mention initializer lists in any way. So we go by what list- 4444 // initialization would do and try to extrapolate from that. 4445 4446 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4447 4448 // If the initializer list has a single element that is reference-related 4449 // to the parameter type, we initialize the reference from that. 4450 if (From->getNumInits() == 1) { 4451 Expr *Init = From->getInit(0); 4452 4453 QualType T2 = Init->getType(); 4454 4455 // If the initializer is the address of an overloaded function, try 4456 // to resolve the overloaded function. If all goes well, T2 is the 4457 // type of the resulting function. 4458 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4459 DeclAccessPair Found; 4460 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4461 Init, ToType, false, Found)) 4462 T2 = Fn->getType(); 4463 } 4464 4465 // Compute some basic properties of the types and the initializer. 4466 bool dummy1 = false; 4467 bool dummy2 = false; 4468 bool dummy3 = false; 4469 Sema::ReferenceCompareResult RefRelationship 4470 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4471 dummy2, dummy3); 4472 4473 if (RefRelationship >= Sema::Ref_Related) 4474 return TryReferenceInit(S, Init, ToType, 4475 /*FIXME:*/From->getLocStart(), 4476 SuppressUserConversions, 4477 /*AllowExplicit=*/false); 4478 } 4479 4480 // Otherwise, we bind the reference to a temporary created from the 4481 // initializer list. 4482 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4483 InOverloadResolution, 4484 AllowObjCWritebackConversion); 4485 if (Result.isFailure()) 4486 return Result; 4487 assert(!Result.isEllipsis() && 4488 "Sub-initialization cannot result in ellipsis conversion."); 4489 4490 // Can we even bind to a temporary? 4491 if (ToType->isRValueReferenceType() || 4492 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4493 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4494 Result.UserDefined.After; 4495 SCS.ReferenceBinding = true; 4496 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4497 SCS.BindsToRvalue = true; 4498 SCS.BindsToFunctionLvalue = false; 4499 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4500 SCS.ObjCLifetimeConversionBinding = false; 4501 } else 4502 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4503 From, ToType); 4504 return Result; 4505 } 4506 4507 // C++11 [over.ics.list]p6: 4508 // Otherwise, if the parameter type is not a class: 4509 if (!ToType->isRecordType()) { 4510 // - if the initializer list has one element, the implicit conversion 4511 // sequence is the one required to convert the element to the 4512 // parameter type. 4513 unsigned NumInits = From->getNumInits(); 4514 if (NumInits == 1) 4515 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4516 SuppressUserConversions, 4517 InOverloadResolution, 4518 AllowObjCWritebackConversion); 4519 // - if the initializer list has no elements, the implicit conversion 4520 // sequence is the identity conversion. 4521 else if (NumInits == 0) { 4522 Result.setStandard(); 4523 Result.Standard.setAsIdentityConversion(); 4524 Result.Standard.setFromType(ToType); 4525 Result.Standard.setAllToTypes(ToType); 4526 } 4527 Result.setListInitializationSequence(); 4528 return Result; 4529 } 4530 4531 // C++11 [over.ics.list]p7: 4532 // In all cases other than those enumerated above, no conversion is possible 4533 return Result; 4534} 4535 4536/// TryCopyInitialization - Try to copy-initialize a value of type 4537/// ToType from the expression From. Return the implicit conversion 4538/// sequence required to pass this argument, which may be a bad 4539/// conversion sequence (meaning that the argument cannot be passed to 4540/// a parameter of this type). If @p SuppressUserConversions, then we 4541/// do not permit any user-defined conversion sequences. 4542static ImplicitConversionSequence 4543TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4544 bool SuppressUserConversions, 4545 bool InOverloadResolution, 4546 bool AllowObjCWritebackConversion, 4547 bool AllowExplicit) { 4548 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4549 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4550 InOverloadResolution,AllowObjCWritebackConversion); 4551 4552 if (ToType->isReferenceType()) 4553 return TryReferenceInit(S, From, ToType, 4554 /*FIXME:*/From->getLocStart(), 4555 SuppressUserConversions, 4556 AllowExplicit); 4557 4558 return TryImplicitConversion(S, From, ToType, 4559 SuppressUserConversions, 4560 /*AllowExplicit=*/false, 4561 InOverloadResolution, 4562 /*CStyle=*/false, 4563 AllowObjCWritebackConversion); 4564} 4565 4566static bool TryCopyInitialization(const CanQualType FromQTy, 4567 const CanQualType ToQTy, 4568 Sema &S, 4569 SourceLocation Loc, 4570 ExprValueKind FromVK) { 4571 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4572 ImplicitConversionSequence ICS = 4573 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4574 4575 return !ICS.isBad(); 4576} 4577 4578/// TryObjectArgumentInitialization - Try to initialize the object 4579/// parameter of the given member function (@c Method) from the 4580/// expression @p From. 4581static ImplicitConversionSequence 4582TryObjectArgumentInitialization(Sema &S, QualType OrigFromType, 4583 Expr::Classification FromClassification, 4584 CXXMethodDecl *Method, 4585 CXXRecordDecl *ActingContext) { 4586 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4587 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4588 // const volatile object. 4589 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4590 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4591 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4592 4593 // Set up the conversion sequence as a "bad" conversion, to allow us 4594 // to exit early. 4595 ImplicitConversionSequence ICS; 4596 4597 // We need to have an object of class type. 4598 QualType FromType = OrigFromType; 4599 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4600 FromType = PT->getPointeeType(); 4601 4602 // When we had a pointer, it's implicitly dereferenced, so we 4603 // better have an lvalue. 4604 assert(FromClassification.isLValue()); 4605 } 4606 4607 assert(FromType->isRecordType()); 4608 4609 // C++0x [over.match.funcs]p4: 4610 // For non-static member functions, the type of the implicit object 4611 // parameter is 4612 // 4613 // - "lvalue reference to cv X" for functions declared without a 4614 // ref-qualifier or with the & ref-qualifier 4615 // - "rvalue reference to cv X" for functions declared with the && 4616 // ref-qualifier 4617 // 4618 // where X is the class of which the function is a member and cv is the 4619 // cv-qualification on the member function declaration. 4620 // 4621 // However, when finding an implicit conversion sequence for the argument, we 4622 // are not allowed to create temporaries or perform user-defined conversions 4623 // (C++ [over.match.funcs]p5). We perform a simplified version of 4624 // reference binding here, that allows class rvalues to bind to 4625 // non-constant references. 4626 4627 // First check the qualifiers. 4628 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4629 if (ImplicitParamType.getCVRQualifiers() 4630 != FromTypeCanon.getLocalCVRQualifiers() && 4631 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4632 ICS.setBad(BadConversionSequence::bad_qualifiers, 4633 OrigFromType, ImplicitParamType); 4634 return ICS; 4635 } 4636 4637 // Check that we have either the same type or a derived type. It 4638 // affects the conversion rank. 4639 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4640 ImplicitConversionKind SecondKind; 4641 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4642 SecondKind = ICK_Identity; 4643 } else if (S.IsDerivedFrom(FromType, ClassType)) 4644 SecondKind = ICK_Derived_To_Base; 4645 else { 4646 ICS.setBad(BadConversionSequence::unrelated_class, 4647 FromType, ImplicitParamType); 4648 return ICS; 4649 } 4650 4651 // Check the ref-qualifier. 4652 switch (Method->getRefQualifier()) { 4653 case RQ_None: 4654 // Do nothing; we don't care about lvalueness or rvalueness. 4655 break; 4656 4657 case RQ_LValue: 4658 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4659 // non-const lvalue reference cannot bind to an rvalue 4660 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4661 ImplicitParamType); 4662 return ICS; 4663 } 4664 break; 4665 4666 case RQ_RValue: 4667 if (!FromClassification.isRValue()) { 4668 // rvalue reference cannot bind to an lvalue 4669 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4670 ImplicitParamType); 4671 return ICS; 4672 } 4673 break; 4674 } 4675 4676 // Success. Mark this as a reference binding. 4677 ICS.setStandard(); 4678 ICS.Standard.setAsIdentityConversion(); 4679 ICS.Standard.Second = SecondKind; 4680 ICS.Standard.setFromType(FromType); 4681 ICS.Standard.setAllToTypes(ImplicitParamType); 4682 ICS.Standard.ReferenceBinding = true; 4683 ICS.Standard.DirectBinding = true; 4684 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4685 ICS.Standard.BindsToFunctionLvalue = false; 4686 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4687 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4688 = (Method->getRefQualifier() == RQ_None); 4689 return ICS; 4690} 4691 4692/// PerformObjectArgumentInitialization - Perform initialization of 4693/// the implicit object parameter for the given Method with the given 4694/// expression. 4695ExprResult 4696Sema::PerformObjectArgumentInitialization(Expr *From, 4697 NestedNameSpecifier *Qualifier, 4698 NamedDecl *FoundDecl, 4699 CXXMethodDecl *Method) { 4700 QualType FromRecordType, DestType; 4701 QualType ImplicitParamRecordType = 4702 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4703 4704 Expr::Classification FromClassification; 4705 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4706 FromRecordType = PT->getPointeeType(); 4707 DestType = Method->getThisType(Context); 4708 FromClassification = Expr::Classification::makeSimpleLValue(); 4709 } else { 4710 FromRecordType = From->getType(); 4711 DestType = ImplicitParamRecordType; 4712 FromClassification = From->Classify(Context); 4713 } 4714 4715 // Note that we always use the true parent context when performing 4716 // the actual argument initialization. 4717 ImplicitConversionSequence ICS 4718 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4719 Method, Method->getParent()); 4720 if (ICS.isBad()) { 4721 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4722 Qualifiers FromQs = FromRecordType.getQualifiers(); 4723 Qualifiers ToQs = DestType.getQualifiers(); 4724 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4725 if (CVR) { 4726 Diag(From->getLocStart(), 4727 diag::err_member_function_call_bad_cvr) 4728 << Method->getDeclName() << FromRecordType << (CVR - 1) 4729 << From->getSourceRange(); 4730 Diag(Method->getLocation(), diag::note_previous_decl) 4731 << Method->getDeclName(); 4732 return ExprError(); 4733 } 4734 } 4735 4736 return Diag(From->getLocStart(), 4737 diag::err_implicit_object_parameter_init) 4738 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4739 } 4740 4741 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4742 ExprResult FromRes = 4743 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4744 if (FromRes.isInvalid()) 4745 return ExprError(); 4746 From = FromRes.take(); 4747 } 4748 4749 if (!Context.hasSameType(From->getType(), DestType)) 4750 From = ImpCastExprToType(From, DestType, CK_NoOp, 4751 From->getValueKind()).take(); 4752 return Owned(From); 4753} 4754 4755/// TryContextuallyConvertToBool - Attempt to contextually convert the 4756/// expression From to bool (C++0x [conv]p3). 4757static ImplicitConversionSequence 4758TryContextuallyConvertToBool(Sema &S, Expr *From) { 4759 // FIXME: This is pretty broken. 4760 return TryImplicitConversion(S, From, S.Context.BoolTy, 4761 // FIXME: Are these flags correct? 4762 /*SuppressUserConversions=*/false, 4763 /*AllowExplicit=*/true, 4764 /*InOverloadResolution=*/false, 4765 /*CStyle=*/false, 4766 /*AllowObjCWritebackConversion=*/false); 4767} 4768 4769/// PerformContextuallyConvertToBool - Perform a contextual conversion 4770/// of the expression From to bool (C++0x [conv]p3). 4771ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4772 if (checkPlaceholderForOverload(*this, From)) 4773 return ExprError(); 4774 4775 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4776 if (!ICS.isBad()) 4777 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4778 4779 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4780 return Diag(From->getLocStart(), 4781 diag::err_typecheck_bool_condition) 4782 << From->getType() << From->getSourceRange(); 4783 return ExprError(); 4784} 4785 4786/// Check that the specified conversion is permitted in a converted constant 4787/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4788/// is acceptable. 4789static bool CheckConvertedConstantConversions(Sema &S, 4790 StandardConversionSequence &SCS) { 4791 // Since we know that the target type is an integral or unscoped enumeration 4792 // type, most conversion kinds are impossible. All possible First and Third 4793 // conversions are fine. 4794 switch (SCS.Second) { 4795 case ICK_Identity: 4796 case ICK_Integral_Promotion: 4797 case ICK_Integral_Conversion: 4798 return true; 4799 4800 case ICK_Boolean_Conversion: 4801 case ICK_Floating_Integral: 4802 case ICK_Complex_Real: 4803 return false; 4804 4805 case ICK_Lvalue_To_Rvalue: 4806 case ICK_Array_To_Pointer: 4807 case ICK_Function_To_Pointer: 4808 case ICK_NoReturn_Adjustment: 4809 case ICK_Qualification: 4810 case ICK_Compatible_Conversion: 4811 case ICK_Vector_Conversion: 4812 case ICK_Vector_Splat: 4813 case ICK_Derived_To_Base: 4814 case ICK_Pointer_Conversion: 4815 case ICK_Pointer_Member: 4816 case ICK_Block_Pointer_Conversion: 4817 case ICK_Writeback_Conversion: 4818 case ICK_Floating_Promotion: 4819 case ICK_Complex_Promotion: 4820 case ICK_Complex_Conversion: 4821 case ICK_Floating_Conversion: 4822 case ICK_TransparentUnionConversion: 4823 llvm_unreachable("unexpected second conversion kind"); 4824 4825 case ICK_Num_Conversion_Kinds: 4826 break; 4827 } 4828 4829 llvm_unreachable("unknown conversion kind"); 4830} 4831 4832/// CheckConvertedConstantExpression - Check that the expression From is a 4833/// converted constant expression of type T, perform the conversion and produce 4834/// the converted expression, per C++11 [expr.const]p3. 4835ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4836 llvm::APSInt &Value, 4837 CCEKind CCE) { 4838 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11"); 4839 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4840 4841 if (checkPlaceholderForOverload(*this, From)) 4842 return ExprError(); 4843 4844 // C++11 [expr.const]p3 with proposed wording fixes: 4845 // A converted constant expression of type T is a core constant expression, 4846 // implicitly converted to a prvalue of type T, where the converted 4847 // expression is a literal constant expression and the implicit conversion 4848 // sequence contains only user-defined conversions, lvalue-to-rvalue 4849 // conversions, integral promotions, and integral conversions other than 4850 // narrowing conversions. 4851 ImplicitConversionSequence ICS = 4852 TryImplicitConversion(From, T, 4853 /*SuppressUserConversions=*/false, 4854 /*AllowExplicit=*/false, 4855 /*InOverloadResolution=*/false, 4856 /*CStyle=*/false, 4857 /*AllowObjcWritebackConversion=*/false); 4858 StandardConversionSequence *SCS = 0; 4859 switch (ICS.getKind()) { 4860 case ImplicitConversionSequence::StandardConversion: 4861 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4862 return Diag(From->getLocStart(), 4863 diag::err_typecheck_converted_constant_expression_disallowed) 4864 << From->getType() << From->getSourceRange() << T; 4865 SCS = &ICS.Standard; 4866 break; 4867 case ImplicitConversionSequence::UserDefinedConversion: 4868 // We are converting from class type to an integral or enumeration type, so 4869 // the Before sequence must be trivial. 4870 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4871 return Diag(From->getLocStart(), 4872 diag::err_typecheck_converted_constant_expression_disallowed) 4873 << From->getType() << From->getSourceRange() << T; 4874 SCS = &ICS.UserDefined.After; 4875 break; 4876 case ImplicitConversionSequence::AmbiguousConversion: 4877 case ImplicitConversionSequence::BadConversion: 4878 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4879 return Diag(From->getLocStart(), 4880 diag::err_typecheck_converted_constant_expression) 4881 << From->getType() << From->getSourceRange() << T; 4882 return ExprError(); 4883 4884 case ImplicitConversionSequence::EllipsisConversion: 4885 llvm_unreachable("ellipsis conversion in converted constant expression"); 4886 } 4887 4888 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4889 if (Result.isInvalid()) 4890 return Result; 4891 4892 // Check for a narrowing implicit conversion. 4893 APValue PreNarrowingValue; 4894 QualType PreNarrowingType; 4895 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4896 PreNarrowingType)) { 4897 case NK_Variable_Narrowing: 4898 // Implicit conversion to a narrower type, and the value is not a constant 4899 // expression. We'll diagnose this in a moment. 4900 case NK_Not_Narrowing: 4901 break; 4902 4903 case NK_Constant_Narrowing: 4904 Diag(From->getLocStart(), 4905 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4906 diag::err_cce_narrowing) 4907 << CCE << /*Constant*/1 4908 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4909 break; 4910 4911 case NK_Type_Narrowing: 4912 Diag(From->getLocStart(), 4913 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4914 diag::err_cce_narrowing) 4915 << CCE << /*Constant*/0 << From->getType() << T; 4916 break; 4917 } 4918 4919 // Check the expression is a constant expression. 4920 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 4921 Expr::EvalResult Eval; 4922 Eval.Diag = &Notes; 4923 4924 if (!Result.get()->EvaluateAsRValue(Eval, Context)) { 4925 // The expression can't be folded, so we can't keep it at this position in 4926 // the AST. 4927 Result = ExprError(); 4928 } else { 4929 Value = Eval.Val.getInt(); 4930 4931 if (Notes.empty()) { 4932 // It's a constant expression. 4933 return Result; 4934 } 4935 } 4936 4937 // It's not a constant expression. Produce an appropriate diagnostic. 4938 if (Notes.size() == 1 && 4939 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 4940 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 4941 else { 4942 Diag(From->getLocStart(), diag::err_expr_not_cce) 4943 << CCE << From->getSourceRange(); 4944 for (unsigned I = 0; I < Notes.size(); ++I) 4945 Diag(Notes[I].first, Notes[I].second); 4946 } 4947 return Result; 4948} 4949 4950/// dropPointerConversions - If the given standard conversion sequence 4951/// involves any pointer conversions, remove them. This may change 4952/// the result type of the conversion sequence. 4953static void dropPointerConversion(StandardConversionSequence &SCS) { 4954 if (SCS.Second == ICK_Pointer_Conversion) { 4955 SCS.Second = ICK_Identity; 4956 SCS.Third = ICK_Identity; 4957 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 4958 } 4959} 4960 4961/// TryContextuallyConvertToObjCPointer - Attempt to contextually 4962/// convert the expression From to an Objective-C pointer type. 4963static ImplicitConversionSequence 4964TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 4965 // Do an implicit conversion to 'id'. 4966 QualType Ty = S.Context.getObjCIdType(); 4967 ImplicitConversionSequence ICS 4968 = TryImplicitConversion(S, From, Ty, 4969 // FIXME: Are these flags correct? 4970 /*SuppressUserConversions=*/false, 4971 /*AllowExplicit=*/true, 4972 /*InOverloadResolution=*/false, 4973 /*CStyle=*/false, 4974 /*AllowObjCWritebackConversion=*/false); 4975 4976 // Strip off any final conversions to 'id'. 4977 switch (ICS.getKind()) { 4978 case ImplicitConversionSequence::BadConversion: 4979 case ImplicitConversionSequence::AmbiguousConversion: 4980 case ImplicitConversionSequence::EllipsisConversion: 4981 break; 4982 4983 case ImplicitConversionSequence::UserDefinedConversion: 4984 dropPointerConversion(ICS.UserDefined.After); 4985 break; 4986 4987 case ImplicitConversionSequence::StandardConversion: 4988 dropPointerConversion(ICS.Standard); 4989 break; 4990 } 4991 4992 return ICS; 4993} 4994 4995/// PerformContextuallyConvertToObjCPointer - Perform a contextual 4996/// conversion of the expression From to an Objective-C pointer type. 4997ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 4998 if (checkPlaceholderForOverload(*this, From)) 4999 return ExprError(); 5000 5001 QualType Ty = Context.getObjCIdType(); 5002 ImplicitConversionSequence ICS = 5003 TryContextuallyConvertToObjCPointer(*this, From); 5004 if (!ICS.isBad()) 5005 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5006 return ExprError(); 5007} 5008 5009/// Determine whether the provided type is an integral type, or an enumeration 5010/// type of a permitted flavor. 5011static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) { 5012 return AllowScopedEnum ? T->isIntegralOrEnumerationType() 5013 : T->isIntegralOrUnscopedEnumerationType(); 5014} 5015 5016/// \brief Attempt to convert the given expression to an integral or 5017/// enumeration type. 5018/// 5019/// This routine will attempt to convert an expression of class type to an 5020/// integral or enumeration type, if that class type only has a single 5021/// conversion to an integral or enumeration type. 5022/// 5023/// \param Loc The source location of the construct that requires the 5024/// conversion. 5025/// 5026/// \param From The expression we're converting from. 5027/// 5028/// \param Diagnoser Used to output any diagnostics. 5029/// 5030/// \param AllowScopedEnumerations Specifies whether conversions to scoped 5031/// enumerations should be considered. 5032/// 5033/// \returns The expression, converted to an integral or enumeration type if 5034/// successful. 5035ExprResult 5036Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 5037 ICEConvertDiagnoser &Diagnoser, 5038 bool AllowScopedEnumerations) { 5039 // We can't perform any more checking for type-dependent expressions. 5040 if (From->isTypeDependent()) 5041 return Owned(From); 5042 5043 // Process placeholders immediately. 5044 if (From->hasPlaceholderType()) { 5045 ExprResult result = CheckPlaceholderExpr(From); 5046 if (result.isInvalid()) return result; 5047 From = result.take(); 5048 } 5049 5050 // If the expression already has integral or enumeration type, we're golden. 5051 QualType T = From->getType(); 5052 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations)) 5053 return DefaultLvalueConversion(From); 5054 5055 // FIXME: Check for missing '()' if T is a function type? 5056 5057 // If we don't have a class type in C++, there's no way we can get an 5058 // expression of integral or enumeration type. 5059 const RecordType *RecordTy = T->getAs<RecordType>(); 5060 if (!RecordTy || !getLangOpts().CPlusPlus) { 5061 if (!Diagnoser.Suppress) 5062 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange(); 5063 return Owned(From); 5064 } 5065 5066 // We must have a complete class type. 5067 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5068 ICEConvertDiagnoser &Diagnoser; 5069 Expr *From; 5070 5071 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From) 5072 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {} 5073 5074 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5075 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5076 } 5077 } IncompleteDiagnoser(Diagnoser, From); 5078 5079 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5080 return Owned(From); 5081 5082 // Look for a conversion to an integral or enumeration type. 5083 UnresolvedSet<4> ViableConversions; 5084 UnresolvedSet<4> ExplicitConversions; 5085 const UnresolvedSetImpl *Conversions 5086 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5087 5088 bool HadMultipleCandidates = (Conversions->size() > 1); 5089 5090 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 5091 E = Conversions->end(); 5092 I != E; 5093 ++I) { 5094 if (CXXConversionDecl *Conversion 5095 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 5096 if (isIntegralOrEnumerationType( 5097 Conversion->getConversionType().getNonReferenceType(), 5098 AllowScopedEnumerations)) { 5099 if (Conversion->isExplicit()) 5100 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5101 else 5102 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5103 } 5104 } 5105 } 5106 5107 switch (ViableConversions.size()) { 5108 case 0: 5109 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) { 5110 DeclAccessPair Found = ExplicitConversions[0]; 5111 CXXConversionDecl *Conversion 5112 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5113 5114 // The user probably meant to invoke the given explicit 5115 // conversion; use it. 5116 QualType ConvTy 5117 = Conversion->getConversionType().getNonReferenceType(); 5118 std::string TypeStr; 5119 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy()); 5120 5121 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy) 5122 << FixItHint::CreateInsertion(From->getLocStart(), 5123 "static_cast<" + TypeStr + ">(") 5124 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 5125 ")"); 5126 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy); 5127 5128 // If we aren't in a SFINAE context, build a call to the 5129 // explicit conversion function. 5130 if (isSFINAEContext()) 5131 return ExprError(); 5132 5133 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5134 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5135 HadMultipleCandidates); 5136 if (Result.isInvalid()) 5137 return ExprError(); 5138 // Record usage of conversion in an implicit cast. 5139 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5140 CK_UserDefinedConversion, 5141 Result.get(), 0, 5142 Result.get()->getValueKind()); 5143 } 5144 5145 // We'll complain below about a non-integral condition type. 5146 break; 5147 5148 case 1: { 5149 // Apply this conversion. 5150 DeclAccessPair Found = ViableConversions[0]; 5151 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5152 5153 CXXConversionDecl *Conversion 5154 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5155 QualType ConvTy 5156 = Conversion->getConversionType().getNonReferenceType(); 5157 if (!Diagnoser.SuppressConversion) { 5158 if (isSFINAEContext()) 5159 return ExprError(); 5160 5161 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy) 5162 << From->getSourceRange(); 5163 } 5164 5165 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5166 HadMultipleCandidates); 5167 if (Result.isInvalid()) 5168 return ExprError(); 5169 // Record usage of conversion in an implicit cast. 5170 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5171 CK_UserDefinedConversion, 5172 Result.get(), 0, 5173 Result.get()->getValueKind()); 5174 break; 5175 } 5176 5177 default: 5178 if (Diagnoser.Suppress) 5179 return ExprError(); 5180 5181 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange(); 5182 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5183 CXXConversionDecl *Conv 5184 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5185 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5186 Diagnoser.noteAmbiguous(*this, Conv, ConvTy); 5187 } 5188 return Owned(From); 5189 } 5190 5191 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) && 5192 !Diagnoser.Suppress) { 5193 Diagnoser.diagnoseNotInt(*this, Loc, From->getType()) 5194 << From->getSourceRange(); 5195 } 5196 5197 return DefaultLvalueConversion(From); 5198} 5199 5200/// AddOverloadCandidate - Adds the given function to the set of 5201/// candidate functions, using the given function call arguments. If 5202/// @p SuppressUserConversions, then don't allow user-defined 5203/// conversions via constructors or conversion operators. 5204/// 5205/// \param PartialOverloading true if we are performing "partial" overloading 5206/// based on an incomplete set of function arguments. This feature is used by 5207/// code completion. 5208void 5209Sema::AddOverloadCandidate(FunctionDecl *Function, 5210 DeclAccessPair FoundDecl, 5211 llvm::ArrayRef<Expr *> Args, 5212 OverloadCandidateSet& CandidateSet, 5213 bool SuppressUserConversions, 5214 bool PartialOverloading, 5215 bool AllowExplicit) { 5216 const FunctionProtoType* Proto 5217 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5218 assert(Proto && "Functions without a prototype cannot be overloaded"); 5219 assert(!Function->getDescribedFunctionTemplate() && 5220 "Use AddTemplateOverloadCandidate for function templates"); 5221 5222 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5223 if (!isa<CXXConstructorDecl>(Method)) { 5224 // If we get here, it's because we're calling a member function 5225 // that is named without a member access expression (e.g., 5226 // "this->f") that was either written explicitly or created 5227 // implicitly. This can happen with a qualified call to a member 5228 // function, e.g., X::f(). We use an empty type for the implied 5229 // object argument (C++ [over.call.func]p3), and the acting context 5230 // is irrelevant. 5231 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5232 QualType(), Expr::Classification::makeSimpleLValue(), 5233 Args, CandidateSet, SuppressUserConversions); 5234 return; 5235 } 5236 // We treat a constructor like a non-member function, since its object 5237 // argument doesn't participate in overload resolution. 5238 } 5239 5240 if (!CandidateSet.isNewCandidate(Function)) 5241 return; 5242 5243 // Overload resolution is always an unevaluated context. 5244 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5245 5246 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5247 // C++ [class.copy]p3: 5248 // A member function template is never instantiated to perform the copy 5249 // of a class object to an object of its class type. 5250 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5251 if (Args.size() == 1 && 5252 Constructor->isSpecializationCopyingObject() && 5253 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5254 IsDerivedFrom(Args[0]->getType(), ClassType))) 5255 return; 5256 } 5257 5258 // Add this candidate 5259 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5260 Candidate.FoundDecl = FoundDecl; 5261 Candidate.Function = Function; 5262 Candidate.Viable = true; 5263 Candidate.IsSurrogate = false; 5264 Candidate.IgnoreObjectArgument = false; 5265 Candidate.ExplicitCallArguments = Args.size(); 5266 5267 unsigned NumArgsInProto = Proto->getNumArgs(); 5268 5269 // (C++ 13.3.2p2): A candidate function having fewer than m 5270 // parameters is viable only if it has an ellipsis in its parameter 5271 // list (8.3.5). 5272 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5273 !Proto->isVariadic()) { 5274 Candidate.Viable = false; 5275 Candidate.FailureKind = ovl_fail_too_many_arguments; 5276 return; 5277 } 5278 5279 // (C++ 13.3.2p2): A candidate function having more than m parameters 5280 // is viable only if the (m+1)st parameter has a default argument 5281 // (8.3.6). For the purposes of overload resolution, the 5282 // parameter list is truncated on the right, so that there are 5283 // exactly m parameters. 5284 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5285 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5286 // Not enough arguments. 5287 Candidate.Viable = false; 5288 Candidate.FailureKind = ovl_fail_too_few_arguments; 5289 return; 5290 } 5291 5292 // (CUDA B.1): Check for invalid calls between targets. 5293 if (getLangOpts().CUDA) 5294 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5295 if (CheckCUDATarget(Caller, Function)) { 5296 Candidate.Viable = false; 5297 Candidate.FailureKind = ovl_fail_bad_target; 5298 return; 5299 } 5300 5301 // Determine the implicit conversion sequences for each of the 5302 // arguments. 5303 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5304 if (ArgIdx < NumArgsInProto) { 5305 // (C++ 13.3.2p3): for F to be a viable function, there shall 5306 // exist for each argument an implicit conversion sequence 5307 // (13.3.3.1) that converts that argument to the corresponding 5308 // parameter of F. 5309 QualType ParamType = Proto->getArgType(ArgIdx); 5310 Candidate.Conversions[ArgIdx] 5311 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5312 SuppressUserConversions, 5313 /*InOverloadResolution=*/true, 5314 /*AllowObjCWritebackConversion=*/ 5315 getLangOpts().ObjCAutoRefCount, 5316 AllowExplicit); 5317 if (Candidate.Conversions[ArgIdx].isBad()) { 5318 Candidate.Viable = false; 5319 Candidate.FailureKind = ovl_fail_bad_conversion; 5320 break; 5321 } 5322 } else { 5323 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5324 // argument for which there is no corresponding parameter is 5325 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5326 Candidate.Conversions[ArgIdx].setEllipsis(); 5327 } 5328 } 5329} 5330 5331/// \brief Add all of the function declarations in the given function set to 5332/// the overload canddiate set. 5333void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5334 llvm::ArrayRef<Expr *> Args, 5335 OverloadCandidateSet& CandidateSet, 5336 bool SuppressUserConversions, 5337 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5338 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5339 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5340 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5341 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5342 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5343 cast<CXXMethodDecl>(FD)->getParent(), 5344 Args[0]->getType(), Args[0]->Classify(Context), 5345 Args.slice(1), CandidateSet, 5346 SuppressUserConversions); 5347 else 5348 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5349 SuppressUserConversions); 5350 } else { 5351 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5352 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5353 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5354 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5355 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5356 ExplicitTemplateArgs, 5357 Args[0]->getType(), 5358 Args[0]->Classify(Context), Args.slice(1), 5359 CandidateSet, SuppressUserConversions); 5360 else 5361 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5362 ExplicitTemplateArgs, Args, 5363 CandidateSet, SuppressUserConversions); 5364 } 5365 } 5366} 5367 5368/// AddMethodCandidate - Adds a named decl (which is some kind of 5369/// method) as a method candidate to the given overload set. 5370void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5371 QualType ObjectType, 5372 Expr::Classification ObjectClassification, 5373 Expr **Args, unsigned NumArgs, 5374 OverloadCandidateSet& CandidateSet, 5375 bool SuppressUserConversions) { 5376 NamedDecl *Decl = FoundDecl.getDecl(); 5377 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5378 5379 if (isa<UsingShadowDecl>(Decl)) 5380 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5381 5382 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5383 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5384 "Expected a member function template"); 5385 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5386 /*ExplicitArgs*/ 0, 5387 ObjectType, ObjectClassification, 5388 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 5389 SuppressUserConversions); 5390 } else { 5391 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5392 ObjectType, ObjectClassification, 5393 llvm::makeArrayRef(Args, NumArgs), 5394 CandidateSet, SuppressUserConversions); 5395 } 5396} 5397 5398/// AddMethodCandidate - Adds the given C++ member function to the set 5399/// of candidate functions, using the given function call arguments 5400/// and the object argument (@c Object). For example, in a call 5401/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5402/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5403/// allow user-defined conversions via constructors or conversion 5404/// operators. 5405void 5406Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5407 CXXRecordDecl *ActingContext, QualType ObjectType, 5408 Expr::Classification ObjectClassification, 5409 llvm::ArrayRef<Expr *> Args, 5410 OverloadCandidateSet& CandidateSet, 5411 bool SuppressUserConversions) { 5412 const FunctionProtoType* Proto 5413 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5414 assert(Proto && "Methods without a prototype cannot be overloaded"); 5415 assert(!isa<CXXConstructorDecl>(Method) && 5416 "Use AddOverloadCandidate for constructors"); 5417 5418 if (!CandidateSet.isNewCandidate(Method)) 5419 return; 5420 5421 // Overload resolution is always an unevaluated context. 5422 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5423 5424 // Add this candidate 5425 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5426 Candidate.FoundDecl = FoundDecl; 5427 Candidate.Function = Method; 5428 Candidate.IsSurrogate = false; 5429 Candidate.IgnoreObjectArgument = false; 5430 Candidate.ExplicitCallArguments = Args.size(); 5431 5432 unsigned NumArgsInProto = Proto->getNumArgs(); 5433 5434 // (C++ 13.3.2p2): A candidate function having fewer than m 5435 // parameters is viable only if it has an ellipsis in its parameter 5436 // list (8.3.5). 5437 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5438 Candidate.Viable = false; 5439 Candidate.FailureKind = ovl_fail_too_many_arguments; 5440 return; 5441 } 5442 5443 // (C++ 13.3.2p2): A candidate function having more than m parameters 5444 // is viable only if the (m+1)st parameter has a default argument 5445 // (8.3.6). For the purposes of overload resolution, the 5446 // parameter list is truncated on the right, so that there are 5447 // exactly m parameters. 5448 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5449 if (Args.size() < MinRequiredArgs) { 5450 // Not enough arguments. 5451 Candidate.Viable = false; 5452 Candidate.FailureKind = ovl_fail_too_few_arguments; 5453 return; 5454 } 5455 5456 Candidate.Viable = true; 5457 5458 if (Method->isStatic() || ObjectType.isNull()) 5459 // The implicit object argument is ignored. 5460 Candidate.IgnoreObjectArgument = true; 5461 else { 5462 // Determine the implicit conversion sequence for the object 5463 // parameter. 5464 Candidate.Conversions[0] 5465 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5466 Method, ActingContext); 5467 if (Candidate.Conversions[0].isBad()) { 5468 Candidate.Viable = false; 5469 Candidate.FailureKind = ovl_fail_bad_conversion; 5470 return; 5471 } 5472 } 5473 5474 // Determine the implicit conversion sequences for each of the 5475 // arguments. 5476 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5477 if (ArgIdx < NumArgsInProto) { 5478 // (C++ 13.3.2p3): for F to be a viable function, there shall 5479 // exist for each argument an implicit conversion sequence 5480 // (13.3.3.1) that converts that argument to the corresponding 5481 // parameter of F. 5482 QualType ParamType = Proto->getArgType(ArgIdx); 5483 Candidate.Conversions[ArgIdx + 1] 5484 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5485 SuppressUserConversions, 5486 /*InOverloadResolution=*/true, 5487 /*AllowObjCWritebackConversion=*/ 5488 getLangOpts().ObjCAutoRefCount); 5489 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5490 Candidate.Viable = false; 5491 Candidate.FailureKind = ovl_fail_bad_conversion; 5492 break; 5493 } 5494 } else { 5495 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5496 // argument for which there is no corresponding parameter is 5497 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5498 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5499 } 5500 } 5501} 5502 5503/// \brief Add a C++ member function template as a candidate to the candidate 5504/// set, using template argument deduction to produce an appropriate member 5505/// function template specialization. 5506void 5507Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5508 DeclAccessPair FoundDecl, 5509 CXXRecordDecl *ActingContext, 5510 TemplateArgumentListInfo *ExplicitTemplateArgs, 5511 QualType ObjectType, 5512 Expr::Classification ObjectClassification, 5513 llvm::ArrayRef<Expr *> Args, 5514 OverloadCandidateSet& CandidateSet, 5515 bool SuppressUserConversions) { 5516 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5517 return; 5518 5519 // C++ [over.match.funcs]p7: 5520 // In each case where a candidate is a function template, candidate 5521 // function template specializations are generated using template argument 5522 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5523 // candidate functions in the usual way.113) A given name can refer to one 5524 // or more function templates and also to a set of overloaded non-template 5525 // functions. In such a case, the candidate functions generated from each 5526 // function template are combined with the set of non-template candidate 5527 // functions. 5528 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5529 FunctionDecl *Specialization = 0; 5530 if (TemplateDeductionResult Result 5531 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5532 Specialization, Info)) { 5533 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5534 Candidate.FoundDecl = FoundDecl; 5535 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5536 Candidate.Viable = false; 5537 Candidate.FailureKind = ovl_fail_bad_deduction; 5538 Candidate.IsSurrogate = false; 5539 Candidate.IgnoreObjectArgument = false; 5540 Candidate.ExplicitCallArguments = Args.size(); 5541 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5542 Info); 5543 return; 5544 } 5545 5546 // Add the function template specialization produced by template argument 5547 // deduction as a candidate. 5548 assert(Specialization && "Missing member function template specialization?"); 5549 assert(isa<CXXMethodDecl>(Specialization) && 5550 "Specialization is not a member function?"); 5551 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5552 ActingContext, ObjectType, ObjectClassification, Args, 5553 CandidateSet, SuppressUserConversions); 5554} 5555 5556/// \brief Add a C++ function template specialization as a candidate 5557/// in the candidate set, using template argument deduction to produce 5558/// an appropriate function template specialization. 5559void 5560Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5561 DeclAccessPair FoundDecl, 5562 TemplateArgumentListInfo *ExplicitTemplateArgs, 5563 llvm::ArrayRef<Expr *> Args, 5564 OverloadCandidateSet& CandidateSet, 5565 bool SuppressUserConversions) { 5566 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5567 return; 5568 5569 // C++ [over.match.funcs]p7: 5570 // In each case where a candidate is a function template, candidate 5571 // function template specializations are generated using template argument 5572 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5573 // candidate functions in the usual way.113) A given name can refer to one 5574 // or more function templates and also to a set of overloaded non-template 5575 // functions. In such a case, the candidate functions generated from each 5576 // function template are combined with the set of non-template candidate 5577 // functions. 5578 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5579 FunctionDecl *Specialization = 0; 5580 if (TemplateDeductionResult Result 5581 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5582 Specialization, Info)) { 5583 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5584 Candidate.FoundDecl = FoundDecl; 5585 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5586 Candidate.Viable = false; 5587 Candidate.FailureKind = ovl_fail_bad_deduction; 5588 Candidate.IsSurrogate = false; 5589 Candidate.IgnoreObjectArgument = false; 5590 Candidate.ExplicitCallArguments = Args.size(); 5591 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5592 Info); 5593 return; 5594 } 5595 5596 // Add the function template specialization produced by template argument 5597 // deduction as a candidate. 5598 assert(Specialization && "Missing function template specialization?"); 5599 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5600 SuppressUserConversions); 5601} 5602 5603/// AddConversionCandidate - Add a C++ conversion function as a 5604/// candidate in the candidate set (C++ [over.match.conv], 5605/// C++ [over.match.copy]). From is the expression we're converting from, 5606/// and ToType is the type that we're eventually trying to convert to 5607/// (which may or may not be the same type as the type that the 5608/// conversion function produces). 5609void 5610Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5611 DeclAccessPair FoundDecl, 5612 CXXRecordDecl *ActingContext, 5613 Expr *From, QualType ToType, 5614 OverloadCandidateSet& CandidateSet) { 5615 assert(!Conversion->getDescribedFunctionTemplate() && 5616 "Conversion function templates use AddTemplateConversionCandidate"); 5617 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5618 if (!CandidateSet.isNewCandidate(Conversion)) 5619 return; 5620 5621 // Overload resolution is always an unevaluated context. 5622 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5623 5624 // Add this candidate 5625 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5626 Candidate.FoundDecl = FoundDecl; 5627 Candidate.Function = Conversion; 5628 Candidate.IsSurrogate = false; 5629 Candidate.IgnoreObjectArgument = false; 5630 Candidate.FinalConversion.setAsIdentityConversion(); 5631 Candidate.FinalConversion.setFromType(ConvType); 5632 Candidate.FinalConversion.setAllToTypes(ToType); 5633 Candidate.Viable = true; 5634 Candidate.ExplicitCallArguments = 1; 5635 5636 // C++ [over.match.funcs]p4: 5637 // For conversion functions, the function is considered to be a member of 5638 // the class of the implicit implied object argument for the purpose of 5639 // defining the type of the implicit object parameter. 5640 // 5641 // Determine the implicit conversion sequence for the implicit 5642 // object parameter. 5643 QualType ImplicitParamType = From->getType(); 5644 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5645 ImplicitParamType = FromPtrType->getPointeeType(); 5646 CXXRecordDecl *ConversionContext 5647 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5648 5649 Candidate.Conversions[0] 5650 = TryObjectArgumentInitialization(*this, From->getType(), 5651 From->Classify(Context), 5652 Conversion, ConversionContext); 5653 5654 if (Candidate.Conversions[0].isBad()) { 5655 Candidate.Viable = false; 5656 Candidate.FailureKind = ovl_fail_bad_conversion; 5657 return; 5658 } 5659 5660 // We won't go through a user-define type conversion function to convert a 5661 // derived to base as such conversions are given Conversion Rank. They only 5662 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5663 QualType FromCanon 5664 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5665 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5666 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5667 Candidate.Viable = false; 5668 Candidate.FailureKind = ovl_fail_trivial_conversion; 5669 return; 5670 } 5671 5672 // To determine what the conversion from the result of calling the 5673 // conversion function to the type we're eventually trying to 5674 // convert to (ToType), we need to synthesize a call to the 5675 // conversion function and attempt copy initialization from it. This 5676 // makes sure that we get the right semantics with respect to 5677 // lvalues/rvalues and the type. Fortunately, we can allocate this 5678 // call on the stack and we don't need its arguments to be 5679 // well-formed. 5680 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5681 VK_LValue, From->getLocStart()); 5682 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5683 Context.getPointerType(Conversion->getType()), 5684 CK_FunctionToPointerDecay, 5685 &ConversionRef, VK_RValue); 5686 5687 QualType ConversionType = Conversion->getConversionType(); 5688 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5689 Candidate.Viable = false; 5690 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5691 return; 5692 } 5693 5694 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5695 5696 // Note that it is safe to allocate CallExpr on the stack here because 5697 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5698 // allocator). 5699 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5700 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK, 5701 From->getLocStart()); 5702 ImplicitConversionSequence ICS = 5703 TryCopyInitialization(*this, &Call, ToType, 5704 /*SuppressUserConversions=*/true, 5705 /*InOverloadResolution=*/false, 5706 /*AllowObjCWritebackConversion=*/false); 5707 5708 switch (ICS.getKind()) { 5709 case ImplicitConversionSequence::StandardConversion: 5710 Candidate.FinalConversion = ICS.Standard; 5711 5712 // C++ [over.ics.user]p3: 5713 // If the user-defined conversion is specified by a specialization of a 5714 // conversion function template, the second standard conversion sequence 5715 // shall have exact match rank. 5716 if (Conversion->getPrimaryTemplate() && 5717 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5718 Candidate.Viable = false; 5719 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5720 } 5721 5722 // C++0x [dcl.init.ref]p5: 5723 // In the second case, if the reference is an rvalue reference and 5724 // the second standard conversion sequence of the user-defined 5725 // conversion sequence includes an lvalue-to-rvalue conversion, the 5726 // program is ill-formed. 5727 if (ToType->isRValueReferenceType() && 5728 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5729 Candidate.Viable = false; 5730 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5731 } 5732 break; 5733 5734 case ImplicitConversionSequence::BadConversion: 5735 Candidate.Viable = false; 5736 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5737 break; 5738 5739 default: 5740 llvm_unreachable( 5741 "Can only end up with a standard conversion sequence or failure"); 5742 } 5743} 5744 5745/// \brief Adds a conversion function template specialization 5746/// candidate to the overload set, using template argument deduction 5747/// to deduce the template arguments of the conversion function 5748/// template from the type that we are converting to (C++ 5749/// [temp.deduct.conv]). 5750void 5751Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5752 DeclAccessPair FoundDecl, 5753 CXXRecordDecl *ActingDC, 5754 Expr *From, QualType ToType, 5755 OverloadCandidateSet &CandidateSet) { 5756 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5757 "Only conversion function templates permitted here"); 5758 5759 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5760 return; 5761 5762 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5763 CXXConversionDecl *Specialization = 0; 5764 if (TemplateDeductionResult Result 5765 = DeduceTemplateArguments(FunctionTemplate, ToType, 5766 Specialization, Info)) { 5767 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5768 Candidate.FoundDecl = FoundDecl; 5769 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5770 Candidate.Viable = false; 5771 Candidate.FailureKind = ovl_fail_bad_deduction; 5772 Candidate.IsSurrogate = false; 5773 Candidate.IgnoreObjectArgument = false; 5774 Candidate.ExplicitCallArguments = 1; 5775 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5776 Info); 5777 return; 5778 } 5779 5780 // Add the conversion function template specialization produced by 5781 // template argument deduction as a candidate. 5782 assert(Specialization && "Missing function template specialization?"); 5783 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5784 CandidateSet); 5785} 5786 5787/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5788/// converts the given @c Object to a function pointer via the 5789/// conversion function @c Conversion, and then attempts to call it 5790/// with the given arguments (C++ [over.call.object]p2-4). Proto is 5791/// the type of function that we'll eventually be calling. 5792void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5793 DeclAccessPair FoundDecl, 5794 CXXRecordDecl *ActingContext, 5795 const FunctionProtoType *Proto, 5796 Expr *Object, 5797 llvm::ArrayRef<Expr *> Args, 5798 OverloadCandidateSet& CandidateSet) { 5799 if (!CandidateSet.isNewCandidate(Conversion)) 5800 return; 5801 5802 // Overload resolution is always an unevaluated context. 5803 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5804 5805 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5806 Candidate.FoundDecl = FoundDecl; 5807 Candidate.Function = 0; 5808 Candidate.Surrogate = Conversion; 5809 Candidate.Viable = true; 5810 Candidate.IsSurrogate = true; 5811 Candidate.IgnoreObjectArgument = false; 5812 Candidate.ExplicitCallArguments = Args.size(); 5813 5814 // Determine the implicit conversion sequence for the implicit 5815 // object parameter. 5816 ImplicitConversionSequence ObjectInit 5817 = TryObjectArgumentInitialization(*this, Object->getType(), 5818 Object->Classify(Context), 5819 Conversion, ActingContext); 5820 if (ObjectInit.isBad()) { 5821 Candidate.Viable = false; 5822 Candidate.FailureKind = ovl_fail_bad_conversion; 5823 Candidate.Conversions[0] = ObjectInit; 5824 return; 5825 } 5826 5827 // The first conversion is actually a user-defined conversion whose 5828 // first conversion is ObjectInit's standard conversion (which is 5829 // effectively a reference binding). Record it as such. 5830 Candidate.Conversions[0].setUserDefined(); 5831 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 5832 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 5833 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 5834 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 5835 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 5836 Candidate.Conversions[0].UserDefined.After 5837 = Candidate.Conversions[0].UserDefined.Before; 5838 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 5839 5840 // Find the 5841 unsigned NumArgsInProto = Proto->getNumArgs(); 5842 5843 // (C++ 13.3.2p2): A candidate function having fewer than m 5844 // parameters is viable only if it has an ellipsis in its parameter 5845 // list (8.3.5). 5846 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5847 Candidate.Viable = false; 5848 Candidate.FailureKind = ovl_fail_too_many_arguments; 5849 return; 5850 } 5851 5852 // Function types don't have any default arguments, so just check if 5853 // we have enough arguments. 5854 if (Args.size() < NumArgsInProto) { 5855 // Not enough arguments. 5856 Candidate.Viable = false; 5857 Candidate.FailureKind = ovl_fail_too_few_arguments; 5858 return; 5859 } 5860 5861 // Determine the implicit conversion sequences for each of the 5862 // arguments. 5863 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5864 if (ArgIdx < NumArgsInProto) { 5865 // (C++ 13.3.2p3): for F to be a viable function, there shall 5866 // exist for each argument an implicit conversion sequence 5867 // (13.3.3.1) that converts that argument to the corresponding 5868 // parameter of F. 5869 QualType ParamType = Proto->getArgType(ArgIdx); 5870 Candidate.Conversions[ArgIdx + 1] 5871 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5872 /*SuppressUserConversions=*/false, 5873 /*InOverloadResolution=*/false, 5874 /*AllowObjCWritebackConversion=*/ 5875 getLangOpts().ObjCAutoRefCount); 5876 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5877 Candidate.Viable = false; 5878 Candidate.FailureKind = ovl_fail_bad_conversion; 5879 break; 5880 } 5881 } else { 5882 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5883 // argument for which there is no corresponding parameter is 5884 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5885 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5886 } 5887 } 5888} 5889 5890/// \brief Add overload candidates for overloaded operators that are 5891/// member functions. 5892/// 5893/// Add the overloaded operator candidates that are member functions 5894/// for the operator Op that was used in an operator expression such 5895/// as "x Op y". , Args/NumArgs provides the operator arguments, and 5896/// CandidateSet will store the added overload candidates. (C++ 5897/// [over.match.oper]). 5898void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 5899 SourceLocation OpLoc, 5900 Expr **Args, unsigned NumArgs, 5901 OverloadCandidateSet& CandidateSet, 5902 SourceRange OpRange) { 5903 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 5904 5905 // C++ [over.match.oper]p3: 5906 // For a unary operator @ with an operand of a type whose 5907 // cv-unqualified version is T1, and for a binary operator @ with 5908 // a left operand of a type whose cv-unqualified version is T1 and 5909 // a right operand of a type whose cv-unqualified version is T2, 5910 // three sets of candidate functions, designated member 5911 // candidates, non-member candidates and built-in candidates, are 5912 // constructed as follows: 5913 QualType T1 = Args[0]->getType(); 5914 5915 // -- If T1 is a class type, the set of member candidates is the 5916 // result of the qualified lookup of T1::operator@ 5917 // (13.3.1.1.1); otherwise, the set of member candidates is 5918 // empty. 5919 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 5920 // Complete the type if it can be completed. Otherwise, we're done. 5921 if (RequireCompleteType(OpLoc, T1, 0)) 5922 return; 5923 5924 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 5925 LookupQualifiedName(Operators, T1Rec->getDecl()); 5926 Operators.suppressDiagnostics(); 5927 5928 for (LookupResult::iterator Oper = Operators.begin(), 5929 OperEnd = Operators.end(); 5930 Oper != OperEnd; 5931 ++Oper) 5932 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 5933 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 5934 CandidateSet, 5935 /* SuppressUserConversions = */ false); 5936 } 5937} 5938 5939/// AddBuiltinCandidate - Add a candidate for a built-in 5940/// operator. ResultTy and ParamTys are the result and parameter types 5941/// of the built-in candidate, respectively. Args and NumArgs are the 5942/// arguments being passed to the candidate. IsAssignmentOperator 5943/// should be true when this built-in candidate is an assignment 5944/// operator. NumContextualBoolArguments is the number of arguments 5945/// (at the beginning of the argument list) that will be contextually 5946/// converted to bool. 5947void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 5948 Expr **Args, unsigned NumArgs, 5949 OverloadCandidateSet& CandidateSet, 5950 bool IsAssignmentOperator, 5951 unsigned NumContextualBoolArguments) { 5952 // Overload resolution is always an unevaluated context. 5953 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5954 5955 // Add this candidate 5956 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs); 5957 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 5958 Candidate.Function = 0; 5959 Candidate.IsSurrogate = false; 5960 Candidate.IgnoreObjectArgument = false; 5961 Candidate.BuiltinTypes.ResultTy = ResultTy; 5962 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 5963 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 5964 5965 // Determine the implicit conversion sequences for each of the 5966 // arguments. 5967 Candidate.Viable = true; 5968 Candidate.ExplicitCallArguments = NumArgs; 5969 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5970 // C++ [over.match.oper]p4: 5971 // For the built-in assignment operators, conversions of the 5972 // left operand are restricted as follows: 5973 // -- no temporaries are introduced to hold the left operand, and 5974 // -- no user-defined conversions are applied to the left 5975 // operand to achieve a type match with the left-most 5976 // parameter of a built-in candidate. 5977 // 5978 // We block these conversions by turning off user-defined 5979 // conversions, since that is the only way that initialization of 5980 // a reference to a non-class type can occur from something that 5981 // is not of the same type. 5982 if (ArgIdx < NumContextualBoolArguments) { 5983 assert(ParamTys[ArgIdx] == Context.BoolTy && 5984 "Contextual conversion to bool requires bool type"); 5985 Candidate.Conversions[ArgIdx] 5986 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 5987 } else { 5988 Candidate.Conversions[ArgIdx] 5989 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 5990 ArgIdx == 0 && IsAssignmentOperator, 5991 /*InOverloadResolution=*/false, 5992 /*AllowObjCWritebackConversion=*/ 5993 getLangOpts().ObjCAutoRefCount); 5994 } 5995 if (Candidate.Conversions[ArgIdx].isBad()) { 5996 Candidate.Viable = false; 5997 Candidate.FailureKind = ovl_fail_bad_conversion; 5998 break; 5999 } 6000 } 6001} 6002 6003/// BuiltinCandidateTypeSet - A set of types that will be used for the 6004/// candidate operator functions for built-in operators (C++ 6005/// [over.built]). The types are separated into pointer types and 6006/// enumeration types. 6007class BuiltinCandidateTypeSet { 6008 /// TypeSet - A set of types. 6009 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6010 6011 /// PointerTypes - The set of pointer types that will be used in the 6012 /// built-in candidates. 6013 TypeSet PointerTypes; 6014 6015 /// MemberPointerTypes - The set of member pointer types that will be 6016 /// used in the built-in candidates. 6017 TypeSet MemberPointerTypes; 6018 6019 /// EnumerationTypes - The set of enumeration types that will be 6020 /// used in the built-in candidates. 6021 TypeSet EnumerationTypes; 6022 6023 /// \brief The set of vector types that will be used in the built-in 6024 /// candidates. 6025 TypeSet VectorTypes; 6026 6027 /// \brief A flag indicating non-record types are viable candidates 6028 bool HasNonRecordTypes; 6029 6030 /// \brief A flag indicating whether either arithmetic or enumeration types 6031 /// were present in the candidate set. 6032 bool HasArithmeticOrEnumeralTypes; 6033 6034 /// \brief A flag indicating whether the nullptr type was present in the 6035 /// candidate set. 6036 bool HasNullPtrType; 6037 6038 /// Sema - The semantic analysis instance where we are building the 6039 /// candidate type set. 6040 Sema &SemaRef; 6041 6042 /// Context - The AST context in which we will build the type sets. 6043 ASTContext &Context; 6044 6045 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6046 const Qualifiers &VisibleQuals); 6047 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6048 6049public: 6050 /// iterator - Iterates through the types that are part of the set. 6051 typedef TypeSet::iterator iterator; 6052 6053 BuiltinCandidateTypeSet(Sema &SemaRef) 6054 : HasNonRecordTypes(false), 6055 HasArithmeticOrEnumeralTypes(false), 6056 HasNullPtrType(false), 6057 SemaRef(SemaRef), 6058 Context(SemaRef.Context) { } 6059 6060 void AddTypesConvertedFrom(QualType Ty, 6061 SourceLocation Loc, 6062 bool AllowUserConversions, 6063 bool AllowExplicitConversions, 6064 const Qualifiers &VisibleTypeConversionsQuals); 6065 6066 /// pointer_begin - First pointer type found; 6067 iterator pointer_begin() { return PointerTypes.begin(); } 6068 6069 /// pointer_end - Past the last pointer type found; 6070 iterator pointer_end() { return PointerTypes.end(); } 6071 6072 /// member_pointer_begin - First member pointer type found; 6073 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6074 6075 /// member_pointer_end - Past the last member pointer type found; 6076 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6077 6078 /// enumeration_begin - First enumeration type found; 6079 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6080 6081 /// enumeration_end - Past the last enumeration type found; 6082 iterator enumeration_end() { return EnumerationTypes.end(); } 6083 6084 iterator vector_begin() { return VectorTypes.begin(); } 6085 iterator vector_end() { return VectorTypes.end(); } 6086 6087 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6088 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6089 bool hasNullPtrType() const { return HasNullPtrType; } 6090}; 6091 6092/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6093/// the set of pointer types along with any more-qualified variants of 6094/// that type. For example, if @p Ty is "int const *", this routine 6095/// will add "int const *", "int const volatile *", "int const 6096/// restrict *", and "int const volatile restrict *" to the set of 6097/// pointer types. Returns true if the add of @p Ty itself succeeded, 6098/// false otherwise. 6099/// 6100/// FIXME: what to do about extended qualifiers? 6101bool 6102BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6103 const Qualifiers &VisibleQuals) { 6104 6105 // Insert this type. 6106 if (!PointerTypes.insert(Ty)) 6107 return false; 6108 6109 QualType PointeeTy; 6110 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6111 bool buildObjCPtr = false; 6112 if (!PointerTy) { 6113 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6114 PointeeTy = PTy->getPointeeType(); 6115 buildObjCPtr = true; 6116 } else { 6117 PointeeTy = PointerTy->getPointeeType(); 6118 } 6119 6120 // Don't add qualified variants of arrays. For one, they're not allowed 6121 // (the qualifier would sink to the element type), and for another, the 6122 // only overload situation where it matters is subscript or pointer +- int, 6123 // and those shouldn't have qualifier variants anyway. 6124 if (PointeeTy->isArrayType()) 6125 return true; 6126 6127 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6128 bool hasVolatile = VisibleQuals.hasVolatile(); 6129 bool hasRestrict = VisibleQuals.hasRestrict(); 6130 6131 // Iterate through all strict supersets of BaseCVR. 6132 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6133 if ((CVR | BaseCVR) != CVR) continue; 6134 // Skip over volatile if no volatile found anywhere in the types. 6135 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6136 6137 // Skip over restrict if no restrict found anywhere in the types, or if 6138 // the type cannot be restrict-qualified. 6139 if ((CVR & Qualifiers::Restrict) && 6140 (!hasRestrict || 6141 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6142 continue; 6143 6144 // Build qualified pointee type. 6145 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6146 6147 // Build qualified pointer type. 6148 QualType QPointerTy; 6149 if (!buildObjCPtr) 6150 QPointerTy = Context.getPointerType(QPointeeTy); 6151 else 6152 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6153 6154 // Insert qualified pointer type. 6155 PointerTypes.insert(QPointerTy); 6156 } 6157 6158 return true; 6159} 6160 6161/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6162/// to the set of pointer types along with any more-qualified variants of 6163/// that type. For example, if @p Ty is "int const *", this routine 6164/// will add "int const *", "int const volatile *", "int const 6165/// restrict *", and "int const volatile restrict *" to the set of 6166/// pointer types. Returns true if the add of @p Ty itself succeeded, 6167/// false otherwise. 6168/// 6169/// FIXME: what to do about extended qualifiers? 6170bool 6171BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6172 QualType Ty) { 6173 // Insert this type. 6174 if (!MemberPointerTypes.insert(Ty)) 6175 return false; 6176 6177 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6178 assert(PointerTy && "type was not a member pointer type!"); 6179 6180 QualType PointeeTy = PointerTy->getPointeeType(); 6181 // Don't add qualified variants of arrays. For one, they're not allowed 6182 // (the qualifier would sink to the element type), and for another, the 6183 // only overload situation where it matters is subscript or pointer +- int, 6184 // and those shouldn't have qualifier variants anyway. 6185 if (PointeeTy->isArrayType()) 6186 return true; 6187 const Type *ClassTy = PointerTy->getClass(); 6188 6189 // Iterate through all strict supersets of the pointee type's CVR 6190 // qualifiers. 6191 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6192 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6193 if ((CVR | BaseCVR) != CVR) continue; 6194 6195 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6196 MemberPointerTypes.insert( 6197 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6198 } 6199 6200 return true; 6201} 6202 6203/// AddTypesConvertedFrom - Add each of the types to which the type @p 6204/// Ty can be implicit converted to the given set of @p Types. We're 6205/// primarily interested in pointer types and enumeration types. We also 6206/// take member pointer types, for the conditional operator. 6207/// AllowUserConversions is true if we should look at the conversion 6208/// functions of a class type, and AllowExplicitConversions if we 6209/// should also include the explicit conversion functions of a class 6210/// type. 6211void 6212BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6213 SourceLocation Loc, 6214 bool AllowUserConversions, 6215 bool AllowExplicitConversions, 6216 const Qualifiers &VisibleQuals) { 6217 // Only deal with canonical types. 6218 Ty = Context.getCanonicalType(Ty); 6219 6220 // Look through reference types; they aren't part of the type of an 6221 // expression for the purposes of conversions. 6222 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6223 Ty = RefTy->getPointeeType(); 6224 6225 // If we're dealing with an array type, decay to the pointer. 6226 if (Ty->isArrayType()) 6227 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6228 6229 // Otherwise, we don't care about qualifiers on the type. 6230 Ty = Ty.getLocalUnqualifiedType(); 6231 6232 // Flag if we ever add a non-record type. 6233 const RecordType *TyRec = Ty->getAs<RecordType>(); 6234 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6235 6236 // Flag if we encounter an arithmetic type. 6237 HasArithmeticOrEnumeralTypes = 6238 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6239 6240 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6241 PointerTypes.insert(Ty); 6242 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6243 // Insert our type, and its more-qualified variants, into the set 6244 // of types. 6245 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6246 return; 6247 } else if (Ty->isMemberPointerType()) { 6248 // Member pointers are far easier, since the pointee can't be converted. 6249 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6250 return; 6251 } else if (Ty->isEnumeralType()) { 6252 HasArithmeticOrEnumeralTypes = true; 6253 EnumerationTypes.insert(Ty); 6254 } else if (Ty->isVectorType()) { 6255 // We treat vector types as arithmetic types in many contexts as an 6256 // extension. 6257 HasArithmeticOrEnumeralTypes = true; 6258 VectorTypes.insert(Ty); 6259 } else if (Ty->isNullPtrType()) { 6260 HasNullPtrType = true; 6261 } else if (AllowUserConversions && TyRec) { 6262 // No conversion functions in incomplete types. 6263 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6264 return; 6265 6266 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6267 const UnresolvedSetImpl *Conversions 6268 = ClassDecl->getVisibleConversionFunctions(); 6269 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6270 E = Conversions->end(); I != E; ++I) { 6271 NamedDecl *D = I.getDecl(); 6272 if (isa<UsingShadowDecl>(D)) 6273 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6274 6275 // Skip conversion function templates; they don't tell us anything 6276 // about which builtin types we can convert to. 6277 if (isa<FunctionTemplateDecl>(D)) 6278 continue; 6279 6280 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6281 if (AllowExplicitConversions || !Conv->isExplicit()) { 6282 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6283 VisibleQuals); 6284 } 6285 } 6286 } 6287} 6288 6289/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6290/// the volatile- and non-volatile-qualified assignment operators for the 6291/// given type to the candidate set. 6292static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6293 QualType T, 6294 Expr **Args, 6295 unsigned NumArgs, 6296 OverloadCandidateSet &CandidateSet) { 6297 QualType ParamTypes[2]; 6298 6299 // T& operator=(T&, T) 6300 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6301 ParamTypes[1] = T; 6302 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6303 /*IsAssignmentOperator=*/true); 6304 6305 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6306 // volatile T& operator=(volatile T&, T) 6307 ParamTypes[0] 6308 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6309 ParamTypes[1] = T; 6310 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6311 /*IsAssignmentOperator=*/true); 6312 } 6313} 6314 6315/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6316/// if any, found in visible type conversion functions found in ArgExpr's type. 6317static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6318 Qualifiers VRQuals; 6319 const RecordType *TyRec; 6320 if (const MemberPointerType *RHSMPType = 6321 ArgExpr->getType()->getAs<MemberPointerType>()) 6322 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6323 else 6324 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6325 if (!TyRec) { 6326 // Just to be safe, assume the worst case. 6327 VRQuals.addVolatile(); 6328 VRQuals.addRestrict(); 6329 return VRQuals; 6330 } 6331 6332 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6333 if (!ClassDecl->hasDefinition()) 6334 return VRQuals; 6335 6336 const UnresolvedSetImpl *Conversions = 6337 ClassDecl->getVisibleConversionFunctions(); 6338 6339 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6340 E = Conversions->end(); I != E; ++I) { 6341 NamedDecl *D = I.getDecl(); 6342 if (isa<UsingShadowDecl>(D)) 6343 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6344 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6345 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6346 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6347 CanTy = ResTypeRef->getPointeeType(); 6348 // Need to go down the pointer/mempointer chain and add qualifiers 6349 // as see them. 6350 bool done = false; 6351 while (!done) { 6352 if (CanTy.isRestrictQualified()) 6353 VRQuals.addRestrict(); 6354 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6355 CanTy = ResTypePtr->getPointeeType(); 6356 else if (const MemberPointerType *ResTypeMPtr = 6357 CanTy->getAs<MemberPointerType>()) 6358 CanTy = ResTypeMPtr->getPointeeType(); 6359 else 6360 done = true; 6361 if (CanTy.isVolatileQualified()) 6362 VRQuals.addVolatile(); 6363 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6364 return VRQuals; 6365 } 6366 } 6367 } 6368 return VRQuals; 6369} 6370 6371namespace { 6372 6373/// \brief Helper class to manage the addition of builtin operator overload 6374/// candidates. It provides shared state and utility methods used throughout 6375/// the process, as well as a helper method to add each group of builtin 6376/// operator overloads from the standard to a candidate set. 6377class BuiltinOperatorOverloadBuilder { 6378 // Common instance state available to all overload candidate addition methods. 6379 Sema &S; 6380 Expr **Args; 6381 unsigned NumArgs; 6382 Qualifiers VisibleTypeConversionsQuals; 6383 bool HasArithmeticOrEnumeralCandidateType; 6384 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6385 OverloadCandidateSet &CandidateSet; 6386 6387 // Define some constants used to index and iterate over the arithemetic types 6388 // provided via the getArithmeticType() method below. 6389 // The "promoted arithmetic types" are the arithmetic 6390 // types are that preserved by promotion (C++ [over.built]p2). 6391 static const unsigned FirstIntegralType = 3; 6392 static const unsigned LastIntegralType = 20; 6393 static const unsigned FirstPromotedIntegralType = 3, 6394 LastPromotedIntegralType = 11; 6395 static const unsigned FirstPromotedArithmeticType = 0, 6396 LastPromotedArithmeticType = 11; 6397 static const unsigned NumArithmeticTypes = 20; 6398 6399 /// \brief Get the canonical type for a given arithmetic type index. 6400 CanQualType getArithmeticType(unsigned index) { 6401 assert(index < NumArithmeticTypes); 6402 static CanQualType ASTContext::* const 6403 ArithmeticTypes[NumArithmeticTypes] = { 6404 // Start of promoted types. 6405 &ASTContext::FloatTy, 6406 &ASTContext::DoubleTy, 6407 &ASTContext::LongDoubleTy, 6408 6409 // Start of integral types. 6410 &ASTContext::IntTy, 6411 &ASTContext::LongTy, 6412 &ASTContext::LongLongTy, 6413 &ASTContext::Int128Ty, 6414 &ASTContext::UnsignedIntTy, 6415 &ASTContext::UnsignedLongTy, 6416 &ASTContext::UnsignedLongLongTy, 6417 &ASTContext::UnsignedInt128Ty, 6418 // End of promoted types. 6419 6420 &ASTContext::BoolTy, 6421 &ASTContext::CharTy, 6422 &ASTContext::WCharTy, 6423 &ASTContext::Char16Ty, 6424 &ASTContext::Char32Ty, 6425 &ASTContext::SignedCharTy, 6426 &ASTContext::ShortTy, 6427 &ASTContext::UnsignedCharTy, 6428 &ASTContext::UnsignedShortTy, 6429 // End of integral types. 6430 // FIXME: What about complex? What about half? 6431 }; 6432 return S.Context.*ArithmeticTypes[index]; 6433 } 6434 6435 /// \brief Gets the canonical type resulting from the usual arithemetic 6436 /// converions for the given arithmetic types. 6437 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6438 // Accelerator table for performing the usual arithmetic conversions. 6439 // The rules are basically: 6440 // - if either is floating-point, use the wider floating-point 6441 // - if same signedness, use the higher rank 6442 // - if same size, use unsigned of the higher rank 6443 // - use the larger type 6444 // These rules, together with the axiom that higher ranks are 6445 // never smaller, are sufficient to precompute all of these results 6446 // *except* when dealing with signed types of higher rank. 6447 // (we could precompute SLL x UI for all known platforms, but it's 6448 // better not to make any assumptions). 6449 // We assume that int128 has a higher rank than long long on all platforms. 6450 enum PromotedType { 6451 Dep=-1, 6452 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6453 }; 6454 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6455 [LastPromotedArithmeticType] = { 6456/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6457/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6458/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6459/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6460/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6461/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6462/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6463/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6464/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6465/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6466/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6467 }; 6468 6469 assert(L < LastPromotedArithmeticType); 6470 assert(R < LastPromotedArithmeticType); 6471 int Idx = ConversionsTable[L][R]; 6472 6473 // Fast path: the table gives us a concrete answer. 6474 if (Idx != Dep) return getArithmeticType(Idx); 6475 6476 // Slow path: we need to compare widths. 6477 // An invariant is that the signed type has higher rank. 6478 CanQualType LT = getArithmeticType(L), 6479 RT = getArithmeticType(R); 6480 unsigned LW = S.Context.getIntWidth(LT), 6481 RW = S.Context.getIntWidth(RT); 6482 6483 // If they're different widths, use the signed type. 6484 if (LW > RW) return LT; 6485 else if (LW < RW) return RT; 6486 6487 // Otherwise, use the unsigned type of the signed type's rank. 6488 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6489 assert(L == SLL || R == SLL); 6490 return S.Context.UnsignedLongLongTy; 6491 } 6492 6493 /// \brief Helper method to factor out the common pattern of adding overloads 6494 /// for '++' and '--' builtin operators. 6495 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6496 bool HasVolatile, 6497 bool HasRestrict) { 6498 QualType ParamTypes[2] = { 6499 S.Context.getLValueReferenceType(CandidateTy), 6500 S.Context.IntTy 6501 }; 6502 6503 // Non-volatile version. 6504 if (NumArgs == 1) 6505 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6506 else 6507 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6508 6509 // Use a heuristic to reduce number of builtin candidates in the set: 6510 // add volatile version only if there are conversions to a volatile type. 6511 if (HasVolatile) { 6512 ParamTypes[0] = 6513 S.Context.getLValueReferenceType( 6514 S.Context.getVolatileType(CandidateTy)); 6515 if (NumArgs == 1) 6516 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6517 else 6518 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6519 } 6520 6521 // Add restrict version only if there are conversions to a restrict type 6522 // and our candidate type is a non-restrict-qualified pointer. 6523 if (HasRestrict && CandidateTy->isAnyPointerType() && 6524 !CandidateTy.isRestrictQualified()) { 6525 ParamTypes[0] 6526 = S.Context.getLValueReferenceType( 6527 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6528 if (NumArgs == 1) 6529 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6530 else 6531 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6532 6533 if (HasVolatile) { 6534 ParamTypes[0] 6535 = S.Context.getLValueReferenceType( 6536 S.Context.getCVRQualifiedType(CandidateTy, 6537 (Qualifiers::Volatile | 6538 Qualifiers::Restrict))); 6539 if (NumArgs == 1) 6540 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, 6541 CandidateSet); 6542 else 6543 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6544 } 6545 } 6546 6547 } 6548 6549public: 6550 BuiltinOperatorOverloadBuilder( 6551 Sema &S, Expr **Args, unsigned NumArgs, 6552 Qualifiers VisibleTypeConversionsQuals, 6553 bool HasArithmeticOrEnumeralCandidateType, 6554 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6555 OverloadCandidateSet &CandidateSet) 6556 : S(S), Args(Args), NumArgs(NumArgs), 6557 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6558 HasArithmeticOrEnumeralCandidateType( 6559 HasArithmeticOrEnumeralCandidateType), 6560 CandidateTypes(CandidateTypes), 6561 CandidateSet(CandidateSet) { 6562 // Validate some of our static helper constants in debug builds. 6563 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6564 "Invalid first promoted integral type"); 6565 assert(getArithmeticType(LastPromotedIntegralType - 1) 6566 == S.Context.UnsignedInt128Ty && 6567 "Invalid last promoted integral type"); 6568 assert(getArithmeticType(FirstPromotedArithmeticType) 6569 == S.Context.FloatTy && 6570 "Invalid first promoted arithmetic type"); 6571 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6572 == S.Context.UnsignedInt128Ty && 6573 "Invalid last promoted arithmetic type"); 6574 } 6575 6576 // C++ [over.built]p3: 6577 // 6578 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6579 // is either volatile or empty, there exist candidate operator 6580 // functions of the form 6581 // 6582 // VQ T& operator++(VQ T&); 6583 // T operator++(VQ T&, int); 6584 // 6585 // C++ [over.built]p4: 6586 // 6587 // For every pair (T, VQ), where T is an arithmetic type other 6588 // than bool, and VQ is either volatile or empty, there exist 6589 // candidate operator functions of the form 6590 // 6591 // VQ T& operator--(VQ T&); 6592 // T operator--(VQ T&, int); 6593 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6594 if (!HasArithmeticOrEnumeralCandidateType) 6595 return; 6596 6597 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6598 Arith < NumArithmeticTypes; ++Arith) { 6599 addPlusPlusMinusMinusStyleOverloads( 6600 getArithmeticType(Arith), 6601 VisibleTypeConversionsQuals.hasVolatile(), 6602 VisibleTypeConversionsQuals.hasRestrict()); 6603 } 6604 } 6605 6606 // C++ [over.built]p5: 6607 // 6608 // For every pair (T, VQ), where T is a cv-qualified or 6609 // cv-unqualified object type, and VQ is either volatile or 6610 // empty, there exist candidate operator functions of the form 6611 // 6612 // T*VQ& operator++(T*VQ&); 6613 // T*VQ& operator--(T*VQ&); 6614 // T* operator++(T*VQ&, int); 6615 // T* operator--(T*VQ&, int); 6616 void addPlusPlusMinusMinusPointerOverloads() { 6617 for (BuiltinCandidateTypeSet::iterator 6618 Ptr = CandidateTypes[0].pointer_begin(), 6619 PtrEnd = CandidateTypes[0].pointer_end(); 6620 Ptr != PtrEnd; ++Ptr) { 6621 // Skip pointer types that aren't pointers to object types. 6622 if (!(*Ptr)->getPointeeType()->isObjectType()) 6623 continue; 6624 6625 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6626 (!(*Ptr).isVolatileQualified() && 6627 VisibleTypeConversionsQuals.hasVolatile()), 6628 (!(*Ptr).isRestrictQualified() && 6629 VisibleTypeConversionsQuals.hasRestrict())); 6630 } 6631 } 6632 6633 // C++ [over.built]p6: 6634 // For every cv-qualified or cv-unqualified object type T, there 6635 // exist candidate operator functions of the form 6636 // 6637 // T& operator*(T*); 6638 // 6639 // C++ [over.built]p7: 6640 // For every function type T that does not have cv-qualifiers or a 6641 // ref-qualifier, there exist candidate operator functions of the form 6642 // T& operator*(T*); 6643 void addUnaryStarPointerOverloads() { 6644 for (BuiltinCandidateTypeSet::iterator 6645 Ptr = CandidateTypes[0].pointer_begin(), 6646 PtrEnd = CandidateTypes[0].pointer_end(); 6647 Ptr != PtrEnd; ++Ptr) { 6648 QualType ParamTy = *Ptr; 6649 QualType PointeeTy = ParamTy->getPointeeType(); 6650 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6651 continue; 6652 6653 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6654 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6655 continue; 6656 6657 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6658 &ParamTy, Args, 1, CandidateSet); 6659 } 6660 } 6661 6662 // C++ [over.built]p9: 6663 // For every promoted arithmetic type T, there exist candidate 6664 // operator functions of the form 6665 // 6666 // T operator+(T); 6667 // T operator-(T); 6668 void addUnaryPlusOrMinusArithmeticOverloads() { 6669 if (!HasArithmeticOrEnumeralCandidateType) 6670 return; 6671 6672 for (unsigned Arith = FirstPromotedArithmeticType; 6673 Arith < LastPromotedArithmeticType; ++Arith) { 6674 QualType ArithTy = getArithmeticType(Arith); 6675 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 6676 } 6677 6678 // Extension: We also add these operators for vector types. 6679 for (BuiltinCandidateTypeSet::iterator 6680 Vec = CandidateTypes[0].vector_begin(), 6681 VecEnd = CandidateTypes[0].vector_end(); 6682 Vec != VecEnd; ++Vec) { 6683 QualType VecTy = *Vec; 6684 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6685 } 6686 } 6687 6688 // C++ [over.built]p8: 6689 // For every type T, there exist candidate operator functions of 6690 // the form 6691 // 6692 // T* operator+(T*); 6693 void addUnaryPlusPointerOverloads() { 6694 for (BuiltinCandidateTypeSet::iterator 6695 Ptr = CandidateTypes[0].pointer_begin(), 6696 PtrEnd = CandidateTypes[0].pointer_end(); 6697 Ptr != PtrEnd; ++Ptr) { 6698 QualType ParamTy = *Ptr; 6699 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 6700 } 6701 } 6702 6703 // C++ [over.built]p10: 6704 // For every promoted integral type T, there exist candidate 6705 // operator functions of the form 6706 // 6707 // T operator~(T); 6708 void addUnaryTildePromotedIntegralOverloads() { 6709 if (!HasArithmeticOrEnumeralCandidateType) 6710 return; 6711 6712 for (unsigned Int = FirstPromotedIntegralType; 6713 Int < LastPromotedIntegralType; ++Int) { 6714 QualType IntTy = getArithmeticType(Int); 6715 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 6716 } 6717 6718 // Extension: We also add this operator for vector types. 6719 for (BuiltinCandidateTypeSet::iterator 6720 Vec = CandidateTypes[0].vector_begin(), 6721 VecEnd = CandidateTypes[0].vector_end(); 6722 Vec != VecEnd; ++Vec) { 6723 QualType VecTy = *Vec; 6724 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6725 } 6726 } 6727 6728 // C++ [over.match.oper]p16: 6729 // For every pointer to member type T, there exist candidate operator 6730 // functions of the form 6731 // 6732 // bool operator==(T,T); 6733 // bool operator!=(T,T); 6734 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6735 /// Set of (canonical) types that we've already handled. 6736 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6737 6738 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6739 for (BuiltinCandidateTypeSet::iterator 6740 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6741 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6742 MemPtr != MemPtrEnd; 6743 ++MemPtr) { 6744 // Don't add the same builtin candidate twice. 6745 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6746 continue; 6747 6748 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6749 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6750 CandidateSet); 6751 } 6752 } 6753 } 6754 6755 // C++ [over.built]p15: 6756 // 6757 // For every T, where T is an enumeration type, a pointer type, or 6758 // std::nullptr_t, there exist candidate operator functions of the form 6759 // 6760 // bool operator<(T, T); 6761 // bool operator>(T, T); 6762 // bool operator<=(T, T); 6763 // bool operator>=(T, T); 6764 // bool operator==(T, T); 6765 // bool operator!=(T, T); 6766 void addRelationalPointerOrEnumeralOverloads() { 6767 // C++ [over.built]p1: 6768 // If there is a user-written candidate with the same name and parameter 6769 // types as a built-in candidate operator function, the built-in operator 6770 // function is hidden and is not included in the set of candidate 6771 // functions. 6772 // 6773 // The text is actually in a note, but if we don't implement it then we end 6774 // up with ambiguities when the user provides an overloaded operator for 6775 // an enumeration type. Note that only enumeration types have this problem, 6776 // so we track which enumeration types we've seen operators for. Also, the 6777 // only other overloaded operator with enumeration argumenst, operator=, 6778 // cannot be overloaded for enumeration types, so this is the only place 6779 // where we must suppress candidates like this. 6780 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6781 UserDefinedBinaryOperators; 6782 6783 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6784 if (CandidateTypes[ArgIdx].enumeration_begin() != 6785 CandidateTypes[ArgIdx].enumeration_end()) { 6786 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6787 CEnd = CandidateSet.end(); 6788 C != CEnd; ++C) { 6789 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 6790 continue; 6791 6792 QualType FirstParamType = 6793 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 6794 QualType SecondParamType = 6795 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 6796 6797 // Skip if either parameter isn't of enumeral type. 6798 if (!FirstParamType->isEnumeralType() || 6799 !SecondParamType->isEnumeralType()) 6800 continue; 6801 6802 // Add this operator to the set of known user-defined operators. 6803 UserDefinedBinaryOperators.insert( 6804 std::make_pair(S.Context.getCanonicalType(FirstParamType), 6805 S.Context.getCanonicalType(SecondParamType))); 6806 } 6807 } 6808 } 6809 6810 /// Set of (canonical) types that we've already handled. 6811 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6812 6813 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6814 for (BuiltinCandidateTypeSet::iterator 6815 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6816 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6817 Ptr != PtrEnd; ++Ptr) { 6818 // Don't add the same builtin candidate twice. 6819 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6820 continue; 6821 6822 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6823 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6824 CandidateSet); 6825 } 6826 for (BuiltinCandidateTypeSet::iterator 6827 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6828 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6829 Enum != EnumEnd; ++Enum) { 6830 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 6831 6832 // Don't add the same builtin candidate twice, or if a user defined 6833 // candidate exists. 6834 if (!AddedTypes.insert(CanonType) || 6835 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 6836 CanonType))) 6837 continue; 6838 6839 QualType ParamTypes[2] = { *Enum, *Enum }; 6840 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6841 CandidateSet); 6842 } 6843 6844 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 6845 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 6846 if (AddedTypes.insert(NullPtrTy) && 6847 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 6848 NullPtrTy))) { 6849 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 6850 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6851 CandidateSet); 6852 } 6853 } 6854 } 6855 } 6856 6857 // C++ [over.built]p13: 6858 // 6859 // For every cv-qualified or cv-unqualified object type T 6860 // there exist candidate operator functions of the form 6861 // 6862 // T* operator+(T*, ptrdiff_t); 6863 // T& operator[](T*, ptrdiff_t); [BELOW] 6864 // T* operator-(T*, ptrdiff_t); 6865 // T* operator+(ptrdiff_t, T*); 6866 // T& operator[](ptrdiff_t, T*); [BELOW] 6867 // 6868 // C++ [over.built]p14: 6869 // 6870 // For every T, where T is a pointer to object type, there 6871 // exist candidate operator functions of the form 6872 // 6873 // ptrdiff_t operator-(T, T); 6874 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 6875 /// Set of (canonical) types that we've already handled. 6876 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6877 6878 for (int Arg = 0; Arg < 2; ++Arg) { 6879 QualType AsymetricParamTypes[2] = { 6880 S.Context.getPointerDiffType(), 6881 S.Context.getPointerDiffType(), 6882 }; 6883 for (BuiltinCandidateTypeSet::iterator 6884 Ptr = CandidateTypes[Arg].pointer_begin(), 6885 PtrEnd = CandidateTypes[Arg].pointer_end(); 6886 Ptr != PtrEnd; ++Ptr) { 6887 QualType PointeeTy = (*Ptr)->getPointeeType(); 6888 if (!PointeeTy->isObjectType()) 6889 continue; 6890 6891 AsymetricParamTypes[Arg] = *Ptr; 6892 if (Arg == 0 || Op == OO_Plus) { 6893 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 6894 // T* operator+(ptrdiff_t, T*); 6895 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 6896 CandidateSet); 6897 } 6898 if (Op == OO_Minus) { 6899 // ptrdiff_t operator-(T, T); 6900 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6901 continue; 6902 6903 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6904 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 6905 Args, 2, CandidateSet); 6906 } 6907 } 6908 } 6909 } 6910 6911 // C++ [over.built]p12: 6912 // 6913 // For every pair of promoted arithmetic types L and R, there 6914 // exist candidate operator functions of the form 6915 // 6916 // LR operator*(L, R); 6917 // LR operator/(L, R); 6918 // LR operator+(L, R); 6919 // LR operator-(L, R); 6920 // bool operator<(L, R); 6921 // bool operator>(L, R); 6922 // bool operator<=(L, R); 6923 // bool operator>=(L, R); 6924 // bool operator==(L, R); 6925 // bool operator!=(L, R); 6926 // 6927 // where LR is the result of the usual arithmetic conversions 6928 // between types L and R. 6929 // 6930 // C++ [over.built]p24: 6931 // 6932 // For every pair of promoted arithmetic types L and R, there exist 6933 // candidate operator functions of the form 6934 // 6935 // LR operator?(bool, L, R); 6936 // 6937 // where LR is the result of the usual arithmetic conversions 6938 // between types L and R. 6939 // Our candidates ignore the first parameter. 6940 void addGenericBinaryArithmeticOverloads(bool isComparison) { 6941 if (!HasArithmeticOrEnumeralCandidateType) 6942 return; 6943 6944 for (unsigned Left = FirstPromotedArithmeticType; 6945 Left < LastPromotedArithmeticType; ++Left) { 6946 for (unsigned Right = FirstPromotedArithmeticType; 6947 Right < LastPromotedArithmeticType; ++Right) { 6948 QualType LandR[2] = { getArithmeticType(Left), 6949 getArithmeticType(Right) }; 6950 QualType Result = 6951 isComparison ? S.Context.BoolTy 6952 : getUsualArithmeticConversions(Left, Right); 6953 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 6954 } 6955 } 6956 6957 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 6958 // conditional operator for vector types. 6959 for (BuiltinCandidateTypeSet::iterator 6960 Vec1 = CandidateTypes[0].vector_begin(), 6961 Vec1End = CandidateTypes[0].vector_end(); 6962 Vec1 != Vec1End; ++Vec1) { 6963 for (BuiltinCandidateTypeSet::iterator 6964 Vec2 = CandidateTypes[1].vector_begin(), 6965 Vec2End = CandidateTypes[1].vector_end(); 6966 Vec2 != Vec2End; ++Vec2) { 6967 QualType LandR[2] = { *Vec1, *Vec2 }; 6968 QualType Result = S.Context.BoolTy; 6969 if (!isComparison) { 6970 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 6971 Result = *Vec1; 6972 else 6973 Result = *Vec2; 6974 } 6975 6976 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 6977 } 6978 } 6979 } 6980 6981 // C++ [over.built]p17: 6982 // 6983 // For every pair of promoted integral types L and R, there 6984 // exist candidate operator functions of the form 6985 // 6986 // LR operator%(L, R); 6987 // LR operator&(L, R); 6988 // LR operator^(L, R); 6989 // LR operator|(L, R); 6990 // L operator<<(L, R); 6991 // L operator>>(L, R); 6992 // 6993 // where LR is the result of the usual arithmetic conversions 6994 // between types L and R. 6995 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 6996 if (!HasArithmeticOrEnumeralCandidateType) 6997 return; 6998 6999 for (unsigned Left = FirstPromotedIntegralType; 7000 Left < LastPromotedIntegralType; ++Left) { 7001 for (unsigned Right = FirstPromotedIntegralType; 7002 Right < LastPromotedIntegralType; ++Right) { 7003 QualType LandR[2] = { getArithmeticType(Left), 7004 getArithmeticType(Right) }; 7005 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7006 ? LandR[0] 7007 : getUsualArithmeticConversions(Left, Right); 7008 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7009 } 7010 } 7011 } 7012 7013 // C++ [over.built]p20: 7014 // 7015 // For every pair (T, VQ), where T is an enumeration or 7016 // pointer to member type and VQ is either volatile or 7017 // empty, there exist candidate operator functions of the form 7018 // 7019 // VQ T& operator=(VQ T&, T); 7020 void addAssignmentMemberPointerOrEnumeralOverloads() { 7021 /// Set of (canonical) types that we've already handled. 7022 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7023 7024 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7025 for (BuiltinCandidateTypeSet::iterator 7026 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7027 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7028 Enum != EnumEnd; ++Enum) { 7029 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7030 continue; 7031 7032 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 7033 CandidateSet); 7034 } 7035 7036 for (BuiltinCandidateTypeSet::iterator 7037 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7038 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7039 MemPtr != MemPtrEnd; ++MemPtr) { 7040 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7041 continue; 7042 7043 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 7044 CandidateSet); 7045 } 7046 } 7047 } 7048 7049 // C++ [over.built]p19: 7050 // 7051 // For every pair (T, VQ), where T is any type and VQ is either 7052 // volatile or empty, there exist candidate operator functions 7053 // of the form 7054 // 7055 // T*VQ& operator=(T*VQ&, T*); 7056 // 7057 // C++ [over.built]p21: 7058 // 7059 // For every pair (T, VQ), where T is a cv-qualified or 7060 // cv-unqualified object type and VQ is either volatile or 7061 // empty, there exist candidate operator functions of the form 7062 // 7063 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7064 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7065 void addAssignmentPointerOverloads(bool isEqualOp) { 7066 /// Set of (canonical) types that we've already handled. 7067 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7068 7069 for (BuiltinCandidateTypeSet::iterator 7070 Ptr = CandidateTypes[0].pointer_begin(), 7071 PtrEnd = CandidateTypes[0].pointer_end(); 7072 Ptr != PtrEnd; ++Ptr) { 7073 // If this is operator=, keep track of the builtin candidates we added. 7074 if (isEqualOp) 7075 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7076 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7077 continue; 7078 7079 // non-volatile version 7080 QualType ParamTypes[2] = { 7081 S.Context.getLValueReferenceType(*Ptr), 7082 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7083 }; 7084 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7085 /*IsAssigmentOperator=*/ isEqualOp); 7086 7087 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7088 VisibleTypeConversionsQuals.hasVolatile(); 7089 if (NeedVolatile) { 7090 // volatile version 7091 ParamTypes[0] = 7092 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7093 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7094 /*IsAssigmentOperator=*/isEqualOp); 7095 } 7096 7097 if (!(*Ptr).isRestrictQualified() && 7098 VisibleTypeConversionsQuals.hasRestrict()) { 7099 // restrict version 7100 ParamTypes[0] 7101 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7102 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7103 /*IsAssigmentOperator=*/isEqualOp); 7104 7105 if (NeedVolatile) { 7106 // volatile restrict version 7107 ParamTypes[0] 7108 = S.Context.getLValueReferenceType( 7109 S.Context.getCVRQualifiedType(*Ptr, 7110 (Qualifiers::Volatile | 7111 Qualifiers::Restrict))); 7112 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7113 CandidateSet, 7114 /*IsAssigmentOperator=*/isEqualOp); 7115 } 7116 } 7117 } 7118 7119 if (isEqualOp) { 7120 for (BuiltinCandidateTypeSet::iterator 7121 Ptr = CandidateTypes[1].pointer_begin(), 7122 PtrEnd = CandidateTypes[1].pointer_end(); 7123 Ptr != PtrEnd; ++Ptr) { 7124 // Make sure we don't add the same candidate twice. 7125 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7126 continue; 7127 7128 QualType ParamTypes[2] = { 7129 S.Context.getLValueReferenceType(*Ptr), 7130 *Ptr, 7131 }; 7132 7133 // non-volatile version 7134 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7135 /*IsAssigmentOperator=*/true); 7136 7137 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7138 VisibleTypeConversionsQuals.hasVolatile(); 7139 if (NeedVolatile) { 7140 // volatile version 7141 ParamTypes[0] = 7142 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7143 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7144 CandidateSet, /*IsAssigmentOperator=*/true); 7145 } 7146 7147 if (!(*Ptr).isRestrictQualified() && 7148 VisibleTypeConversionsQuals.hasRestrict()) { 7149 // restrict version 7150 ParamTypes[0] 7151 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7152 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7153 CandidateSet, /*IsAssigmentOperator=*/true); 7154 7155 if (NeedVolatile) { 7156 // volatile restrict version 7157 ParamTypes[0] 7158 = S.Context.getLValueReferenceType( 7159 S.Context.getCVRQualifiedType(*Ptr, 7160 (Qualifiers::Volatile | 7161 Qualifiers::Restrict))); 7162 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7163 CandidateSet, /*IsAssigmentOperator=*/true); 7164 7165 } 7166 } 7167 } 7168 } 7169 } 7170 7171 // C++ [over.built]p18: 7172 // 7173 // For every triple (L, VQ, R), where L is an arithmetic type, 7174 // VQ is either volatile or empty, and R is a promoted 7175 // arithmetic type, there exist candidate operator functions of 7176 // the form 7177 // 7178 // VQ L& operator=(VQ L&, R); 7179 // VQ L& operator*=(VQ L&, R); 7180 // VQ L& operator/=(VQ L&, R); 7181 // VQ L& operator+=(VQ L&, R); 7182 // VQ L& operator-=(VQ L&, R); 7183 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7184 if (!HasArithmeticOrEnumeralCandidateType) 7185 return; 7186 7187 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7188 for (unsigned Right = FirstPromotedArithmeticType; 7189 Right < LastPromotedArithmeticType; ++Right) { 7190 QualType ParamTypes[2]; 7191 ParamTypes[1] = getArithmeticType(Right); 7192 7193 // Add this built-in operator as a candidate (VQ is empty). 7194 ParamTypes[0] = 7195 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7196 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7197 /*IsAssigmentOperator=*/isEqualOp); 7198 7199 // Add this built-in operator as a candidate (VQ is 'volatile'). 7200 if (VisibleTypeConversionsQuals.hasVolatile()) { 7201 ParamTypes[0] = 7202 S.Context.getVolatileType(getArithmeticType(Left)); 7203 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7204 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7205 CandidateSet, 7206 /*IsAssigmentOperator=*/isEqualOp); 7207 } 7208 } 7209 } 7210 7211 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7212 for (BuiltinCandidateTypeSet::iterator 7213 Vec1 = CandidateTypes[0].vector_begin(), 7214 Vec1End = CandidateTypes[0].vector_end(); 7215 Vec1 != Vec1End; ++Vec1) { 7216 for (BuiltinCandidateTypeSet::iterator 7217 Vec2 = CandidateTypes[1].vector_begin(), 7218 Vec2End = CandidateTypes[1].vector_end(); 7219 Vec2 != Vec2End; ++Vec2) { 7220 QualType ParamTypes[2]; 7221 ParamTypes[1] = *Vec2; 7222 // Add this built-in operator as a candidate (VQ is empty). 7223 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7224 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7225 /*IsAssigmentOperator=*/isEqualOp); 7226 7227 // Add this built-in operator as a candidate (VQ is 'volatile'). 7228 if (VisibleTypeConversionsQuals.hasVolatile()) { 7229 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7230 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7231 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7232 CandidateSet, 7233 /*IsAssigmentOperator=*/isEqualOp); 7234 } 7235 } 7236 } 7237 } 7238 7239 // C++ [over.built]p22: 7240 // 7241 // For every triple (L, VQ, R), where L is an integral type, VQ 7242 // is either volatile or empty, and R is a promoted integral 7243 // type, there exist candidate operator functions of the form 7244 // 7245 // VQ L& operator%=(VQ L&, R); 7246 // VQ L& operator<<=(VQ L&, R); 7247 // VQ L& operator>>=(VQ L&, R); 7248 // VQ L& operator&=(VQ L&, R); 7249 // VQ L& operator^=(VQ L&, R); 7250 // VQ L& operator|=(VQ L&, R); 7251 void addAssignmentIntegralOverloads() { 7252 if (!HasArithmeticOrEnumeralCandidateType) 7253 return; 7254 7255 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7256 for (unsigned Right = FirstPromotedIntegralType; 7257 Right < LastPromotedIntegralType; ++Right) { 7258 QualType ParamTypes[2]; 7259 ParamTypes[1] = getArithmeticType(Right); 7260 7261 // Add this built-in operator as a candidate (VQ is empty). 7262 ParamTypes[0] = 7263 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7264 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 7265 if (VisibleTypeConversionsQuals.hasVolatile()) { 7266 // Add this built-in operator as a candidate (VQ is 'volatile'). 7267 ParamTypes[0] = getArithmeticType(Left); 7268 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7269 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7270 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7271 CandidateSet); 7272 } 7273 } 7274 } 7275 } 7276 7277 // C++ [over.operator]p23: 7278 // 7279 // There also exist candidate operator functions of the form 7280 // 7281 // bool operator!(bool); 7282 // bool operator&&(bool, bool); 7283 // bool operator||(bool, bool); 7284 void addExclaimOverload() { 7285 QualType ParamTy = S.Context.BoolTy; 7286 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 7287 /*IsAssignmentOperator=*/false, 7288 /*NumContextualBoolArguments=*/1); 7289 } 7290 void addAmpAmpOrPipePipeOverload() { 7291 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7292 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 7293 /*IsAssignmentOperator=*/false, 7294 /*NumContextualBoolArguments=*/2); 7295 } 7296 7297 // C++ [over.built]p13: 7298 // 7299 // For every cv-qualified or cv-unqualified object type T there 7300 // exist candidate operator functions of the form 7301 // 7302 // T* operator+(T*, ptrdiff_t); [ABOVE] 7303 // T& operator[](T*, ptrdiff_t); 7304 // T* operator-(T*, ptrdiff_t); [ABOVE] 7305 // T* operator+(ptrdiff_t, T*); [ABOVE] 7306 // T& operator[](ptrdiff_t, T*); 7307 void addSubscriptOverloads() { 7308 for (BuiltinCandidateTypeSet::iterator 7309 Ptr = CandidateTypes[0].pointer_begin(), 7310 PtrEnd = CandidateTypes[0].pointer_end(); 7311 Ptr != PtrEnd; ++Ptr) { 7312 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7313 QualType PointeeType = (*Ptr)->getPointeeType(); 7314 if (!PointeeType->isObjectType()) 7315 continue; 7316 7317 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7318 7319 // T& operator[](T*, ptrdiff_t) 7320 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7321 } 7322 7323 for (BuiltinCandidateTypeSet::iterator 7324 Ptr = CandidateTypes[1].pointer_begin(), 7325 PtrEnd = CandidateTypes[1].pointer_end(); 7326 Ptr != PtrEnd; ++Ptr) { 7327 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7328 QualType PointeeType = (*Ptr)->getPointeeType(); 7329 if (!PointeeType->isObjectType()) 7330 continue; 7331 7332 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7333 7334 // T& operator[](ptrdiff_t, T*) 7335 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7336 } 7337 } 7338 7339 // C++ [over.built]p11: 7340 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7341 // C1 is the same type as C2 or is a derived class of C2, T is an object 7342 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7343 // there exist candidate operator functions of the form 7344 // 7345 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7346 // 7347 // where CV12 is the union of CV1 and CV2. 7348 void addArrowStarOverloads() { 7349 for (BuiltinCandidateTypeSet::iterator 7350 Ptr = CandidateTypes[0].pointer_begin(), 7351 PtrEnd = CandidateTypes[0].pointer_end(); 7352 Ptr != PtrEnd; ++Ptr) { 7353 QualType C1Ty = (*Ptr); 7354 QualType C1; 7355 QualifierCollector Q1; 7356 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7357 if (!isa<RecordType>(C1)) 7358 continue; 7359 // heuristic to reduce number of builtin candidates in the set. 7360 // Add volatile/restrict version only if there are conversions to a 7361 // volatile/restrict type. 7362 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7363 continue; 7364 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7365 continue; 7366 for (BuiltinCandidateTypeSet::iterator 7367 MemPtr = CandidateTypes[1].member_pointer_begin(), 7368 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7369 MemPtr != MemPtrEnd; ++MemPtr) { 7370 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7371 QualType C2 = QualType(mptr->getClass(), 0); 7372 C2 = C2.getUnqualifiedType(); 7373 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7374 break; 7375 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7376 // build CV12 T& 7377 QualType T = mptr->getPointeeType(); 7378 if (!VisibleTypeConversionsQuals.hasVolatile() && 7379 T.isVolatileQualified()) 7380 continue; 7381 if (!VisibleTypeConversionsQuals.hasRestrict() && 7382 T.isRestrictQualified()) 7383 continue; 7384 T = Q1.apply(S.Context, T); 7385 QualType ResultTy = S.Context.getLValueReferenceType(T); 7386 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7387 } 7388 } 7389 } 7390 7391 // Note that we don't consider the first argument, since it has been 7392 // contextually converted to bool long ago. The candidates below are 7393 // therefore added as binary. 7394 // 7395 // C++ [over.built]p25: 7396 // For every type T, where T is a pointer, pointer-to-member, or scoped 7397 // enumeration type, there exist candidate operator functions of the form 7398 // 7399 // T operator?(bool, T, T); 7400 // 7401 void addConditionalOperatorOverloads() { 7402 /// Set of (canonical) types that we've already handled. 7403 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7404 7405 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7406 for (BuiltinCandidateTypeSet::iterator 7407 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7408 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7409 Ptr != PtrEnd; ++Ptr) { 7410 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7411 continue; 7412 7413 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7414 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 7415 } 7416 7417 for (BuiltinCandidateTypeSet::iterator 7418 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7419 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7420 MemPtr != MemPtrEnd; ++MemPtr) { 7421 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7422 continue; 7423 7424 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7425 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 7426 } 7427 7428 if (S.getLangOpts().CPlusPlus0x) { 7429 for (BuiltinCandidateTypeSet::iterator 7430 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7431 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7432 Enum != EnumEnd; ++Enum) { 7433 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7434 continue; 7435 7436 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7437 continue; 7438 7439 QualType ParamTypes[2] = { *Enum, *Enum }; 7440 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 7441 } 7442 } 7443 } 7444 } 7445}; 7446 7447} // end anonymous namespace 7448 7449/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7450/// operator overloads to the candidate set (C++ [over.built]), based 7451/// on the operator @p Op and the arguments given. For example, if the 7452/// operator is a binary '+', this routine might add "int 7453/// operator+(int, int)" to cover integer addition. 7454void 7455Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7456 SourceLocation OpLoc, 7457 Expr **Args, unsigned NumArgs, 7458 OverloadCandidateSet& CandidateSet) { 7459 // Find all of the types that the arguments can convert to, but only 7460 // if the operator we're looking at has built-in operator candidates 7461 // that make use of these types. Also record whether we encounter non-record 7462 // candidate types or either arithmetic or enumeral candidate types. 7463 Qualifiers VisibleTypeConversionsQuals; 7464 VisibleTypeConversionsQuals.addConst(); 7465 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7466 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7467 7468 bool HasNonRecordCandidateType = false; 7469 bool HasArithmeticOrEnumeralCandidateType = false; 7470 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7471 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 7472 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7473 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7474 OpLoc, 7475 true, 7476 (Op == OO_Exclaim || 7477 Op == OO_AmpAmp || 7478 Op == OO_PipePipe), 7479 VisibleTypeConversionsQuals); 7480 HasNonRecordCandidateType = HasNonRecordCandidateType || 7481 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7482 HasArithmeticOrEnumeralCandidateType = 7483 HasArithmeticOrEnumeralCandidateType || 7484 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7485 } 7486 7487 // Exit early when no non-record types have been added to the candidate set 7488 // for any of the arguments to the operator. 7489 // 7490 // We can't exit early for !, ||, or &&, since there we have always have 7491 // 'bool' overloads. 7492 if (!HasNonRecordCandidateType && 7493 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7494 return; 7495 7496 // Setup an object to manage the common state for building overloads. 7497 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 7498 VisibleTypeConversionsQuals, 7499 HasArithmeticOrEnumeralCandidateType, 7500 CandidateTypes, CandidateSet); 7501 7502 // Dispatch over the operation to add in only those overloads which apply. 7503 switch (Op) { 7504 case OO_None: 7505 case NUM_OVERLOADED_OPERATORS: 7506 llvm_unreachable("Expected an overloaded operator"); 7507 7508 case OO_New: 7509 case OO_Delete: 7510 case OO_Array_New: 7511 case OO_Array_Delete: 7512 case OO_Call: 7513 llvm_unreachable( 7514 "Special operators don't use AddBuiltinOperatorCandidates"); 7515 7516 case OO_Comma: 7517 case OO_Arrow: 7518 // C++ [over.match.oper]p3: 7519 // -- For the operator ',', the unary operator '&', or the 7520 // operator '->', the built-in candidates set is empty. 7521 break; 7522 7523 case OO_Plus: // '+' is either unary or binary 7524 if (NumArgs == 1) 7525 OpBuilder.addUnaryPlusPointerOverloads(); 7526 // Fall through. 7527 7528 case OO_Minus: // '-' is either unary or binary 7529 if (NumArgs == 1) { 7530 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7531 } else { 7532 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7533 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7534 } 7535 break; 7536 7537 case OO_Star: // '*' is either unary or binary 7538 if (NumArgs == 1) 7539 OpBuilder.addUnaryStarPointerOverloads(); 7540 else 7541 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7542 break; 7543 7544 case OO_Slash: 7545 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7546 break; 7547 7548 case OO_PlusPlus: 7549 case OO_MinusMinus: 7550 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7551 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7552 break; 7553 7554 case OO_EqualEqual: 7555 case OO_ExclaimEqual: 7556 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7557 // Fall through. 7558 7559 case OO_Less: 7560 case OO_Greater: 7561 case OO_LessEqual: 7562 case OO_GreaterEqual: 7563 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7564 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7565 break; 7566 7567 case OO_Percent: 7568 case OO_Caret: 7569 case OO_Pipe: 7570 case OO_LessLess: 7571 case OO_GreaterGreater: 7572 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7573 break; 7574 7575 case OO_Amp: // '&' is either unary or binary 7576 if (NumArgs == 1) 7577 // C++ [over.match.oper]p3: 7578 // -- For the operator ',', the unary operator '&', or the 7579 // operator '->', the built-in candidates set is empty. 7580 break; 7581 7582 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7583 break; 7584 7585 case OO_Tilde: 7586 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7587 break; 7588 7589 case OO_Equal: 7590 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7591 // Fall through. 7592 7593 case OO_PlusEqual: 7594 case OO_MinusEqual: 7595 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7596 // Fall through. 7597 7598 case OO_StarEqual: 7599 case OO_SlashEqual: 7600 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7601 break; 7602 7603 case OO_PercentEqual: 7604 case OO_LessLessEqual: 7605 case OO_GreaterGreaterEqual: 7606 case OO_AmpEqual: 7607 case OO_CaretEqual: 7608 case OO_PipeEqual: 7609 OpBuilder.addAssignmentIntegralOverloads(); 7610 break; 7611 7612 case OO_Exclaim: 7613 OpBuilder.addExclaimOverload(); 7614 break; 7615 7616 case OO_AmpAmp: 7617 case OO_PipePipe: 7618 OpBuilder.addAmpAmpOrPipePipeOverload(); 7619 break; 7620 7621 case OO_Subscript: 7622 OpBuilder.addSubscriptOverloads(); 7623 break; 7624 7625 case OO_ArrowStar: 7626 OpBuilder.addArrowStarOverloads(); 7627 break; 7628 7629 case OO_Conditional: 7630 OpBuilder.addConditionalOperatorOverloads(); 7631 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7632 break; 7633 } 7634} 7635 7636/// \brief Add function candidates found via argument-dependent lookup 7637/// to the set of overloading candidates. 7638/// 7639/// This routine performs argument-dependent name lookup based on the 7640/// given function name (which may also be an operator name) and adds 7641/// all of the overload candidates found by ADL to the overload 7642/// candidate set (C++ [basic.lookup.argdep]). 7643void 7644Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7645 bool Operator, SourceLocation Loc, 7646 llvm::ArrayRef<Expr *> Args, 7647 TemplateArgumentListInfo *ExplicitTemplateArgs, 7648 OverloadCandidateSet& CandidateSet, 7649 bool PartialOverloading, 7650 bool StdNamespaceIsAssociated) { 7651 ADLResult Fns; 7652 7653 // FIXME: This approach for uniquing ADL results (and removing 7654 // redundant candidates from the set) relies on pointer-equality, 7655 // which means we need to key off the canonical decl. However, 7656 // always going back to the canonical decl might not get us the 7657 // right set of default arguments. What default arguments are 7658 // we supposed to consider on ADL candidates, anyway? 7659 7660 // FIXME: Pass in the explicit template arguments? 7661 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns, 7662 StdNamespaceIsAssociated); 7663 7664 // Erase all of the candidates we already knew about. 7665 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7666 CandEnd = CandidateSet.end(); 7667 Cand != CandEnd; ++Cand) 7668 if (Cand->Function) { 7669 Fns.erase(Cand->Function); 7670 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7671 Fns.erase(FunTmpl); 7672 } 7673 7674 // For each of the ADL candidates we found, add it to the overload 7675 // set. 7676 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7677 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7678 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7679 if (ExplicitTemplateArgs) 7680 continue; 7681 7682 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7683 PartialOverloading); 7684 } else 7685 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7686 FoundDecl, ExplicitTemplateArgs, 7687 Args, CandidateSet); 7688 } 7689} 7690 7691/// isBetterOverloadCandidate - Determines whether the first overload 7692/// candidate is a better candidate than the second (C++ 13.3.3p1). 7693bool 7694isBetterOverloadCandidate(Sema &S, 7695 const OverloadCandidate &Cand1, 7696 const OverloadCandidate &Cand2, 7697 SourceLocation Loc, 7698 bool UserDefinedConversion) { 7699 // Define viable functions to be better candidates than non-viable 7700 // functions. 7701 if (!Cand2.Viable) 7702 return Cand1.Viable; 7703 else if (!Cand1.Viable) 7704 return false; 7705 7706 // C++ [over.match.best]p1: 7707 // 7708 // -- if F is a static member function, ICS1(F) is defined such 7709 // that ICS1(F) is neither better nor worse than ICS1(G) for 7710 // any function G, and, symmetrically, ICS1(G) is neither 7711 // better nor worse than ICS1(F). 7712 unsigned StartArg = 0; 7713 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7714 StartArg = 1; 7715 7716 // C++ [over.match.best]p1: 7717 // A viable function F1 is defined to be a better function than another 7718 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7719 // conversion sequence than ICSi(F2), and then... 7720 unsigned NumArgs = Cand1.NumConversions; 7721 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7722 bool HasBetterConversion = false; 7723 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7724 switch (CompareImplicitConversionSequences(S, 7725 Cand1.Conversions[ArgIdx], 7726 Cand2.Conversions[ArgIdx])) { 7727 case ImplicitConversionSequence::Better: 7728 // Cand1 has a better conversion sequence. 7729 HasBetterConversion = true; 7730 break; 7731 7732 case ImplicitConversionSequence::Worse: 7733 // Cand1 can't be better than Cand2. 7734 return false; 7735 7736 case ImplicitConversionSequence::Indistinguishable: 7737 // Do nothing. 7738 break; 7739 } 7740 } 7741 7742 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7743 // ICSj(F2), or, if not that, 7744 if (HasBetterConversion) 7745 return true; 7746 7747 // - F1 is a non-template function and F2 is a function template 7748 // specialization, or, if not that, 7749 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7750 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7751 return true; 7752 7753 // -- F1 and F2 are function template specializations, and the function 7754 // template for F1 is more specialized than the template for F2 7755 // according to the partial ordering rules described in 14.5.5.2, or, 7756 // if not that, 7757 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7758 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7759 if (FunctionTemplateDecl *BetterTemplate 7760 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7761 Cand2.Function->getPrimaryTemplate(), 7762 Loc, 7763 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7764 : TPOC_Call, 7765 Cand1.ExplicitCallArguments)) 7766 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7767 } 7768 7769 // -- the context is an initialization by user-defined conversion 7770 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7771 // from the return type of F1 to the destination type (i.e., 7772 // the type of the entity being initialized) is a better 7773 // conversion sequence than the standard conversion sequence 7774 // from the return type of F2 to the destination type. 7775 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7776 isa<CXXConversionDecl>(Cand1.Function) && 7777 isa<CXXConversionDecl>(Cand2.Function)) { 7778 // First check whether we prefer one of the conversion functions over the 7779 // other. This only distinguishes the results in non-standard, extension 7780 // cases such as the conversion from a lambda closure type to a function 7781 // pointer or block. 7782 ImplicitConversionSequence::CompareKind FuncResult 7783 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7784 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7785 return FuncResult; 7786 7787 switch (CompareStandardConversionSequences(S, 7788 Cand1.FinalConversion, 7789 Cand2.FinalConversion)) { 7790 case ImplicitConversionSequence::Better: 7791 // Cand1 has a better conversion sequence. 7792 return true; 7793 7794 case ImplicitConversionSequence::Worse: 7795 // Cand1 can't be better than Cand2. 7796 return false; 7797 7798 case ImplicitConversionSequence::Indistinguishable: 7799 // Do nothing 7800 break; 7801 } 7802 } 7803 7804 return false; 7805} 7806 7807/// \brief Computes the best viable function (C++ 13.3.3) 7808/// within an overload candidate set. 7809/// 7810/// \param Loc The location of the function name (or operator symbol) for 7811/// which overload resolution occurs. 7812/// 7813/// \param Best If overload resolution was successful or found a deleted 7814/// function, \p Best points to the candidate function found. 7815/// 7816/// \returns The result of overload resolution. 7817OverloadingResult 7818OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 7819 iterator &Best, 7820 bool UserDefinedConversion) { 7821 // Find the best viable function. 7822 Best = end(); 7823 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7824 if (Cand->Viable) 7825 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 7826 UserDefinedConversion)) 7827 Best = Cand; 7828 } 7829 7830 // If we didn't find any viable functions, abort. 7831 if (Best == end()) 7832 return OR_No_Viable_Function; 7833 7834 // Make sure that this function is better than every other viable 7835 // function. If not, we have an ambiguity. 7836 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7837 if (Cand->Viable && 7838 Cand != Best && 7839 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 7840 UserDefinedConversion)) { 7841 Best = end(); 7842 return OR_Ambiguous; 7843 } 7844 } 7845 7846 // Best is the best viable function. 7847 if (Best->Function && 7848 (Best->Function->isDeleted() || 7849 S.isFunctionConsideredUnavailable(Best->Function))) 7850 return OR_Deleted; 7851 7852 return OR_Success; 7853} 7854 7855namespace { 7856 7857enum OverloadCandidateKind { 7858 oc_function, 7859 oc_method, 7860 oc_constructor, 7861 oc_function_template, 7862 oc_method_template, 7863 oc_constructor_template, 7864 oc_implicit_default_constructor, 7865 oc_implicit_copy_constructor, 7866 oc_implicit_move_constructor, 7867 oc_implicit_copy_assignment, 7868 oc_implicit_move_assignment, 7869 oc_implicit_inherited_constructor 7870}; 7871 7872OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 7873 FunctionDecl *Fn, 7874 std::string &Description) { 7875 bool isTemplate = false; 7876 7877 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 7878 isTemplate = true; 7879 Description = S.getTemplateArgumentBindingsText( 7880 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 7881 } 7882 7883 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 7884 if (!Ctor->isImplicit()) 7885 return isTemplate ? oc_constructor_template : oc_constructor; 7886 7887 if (Ctor->getInheritedConstructor()) 7888 return oc_implicit_inherited_constructor; 7889 7890 if (Ctor->isDefaultConstructor()) 7891 return oc_implicit_default_constructor; 7892 7893 if (Ctor->isMoveConstructor()) 7894 return oc_implicit_move_constructor; 7895 7896 assert(Ctor->isCopyConstructor() && 7897 "unexpected sort of implicit constructor"); 7898 return oc_implicit_copy_constructor; 7899 } 7900 7901 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 7902 // This actually gets spelled 'candidate function' for now, but 7903 // it doesn't hurt to split it out. 7904 if (!Meth->isImplicit()) 7905 return isTemplate ? oc_method_template : oc_method; 7906 7907 if (Meth->isMoveAssignmentOperator()) 7908 return oc_implicit_move_assignment; 7909 7910 if (Meth->isCopyAssignmentOperator()) 7911 return oc_implicit_copy_assignment; 7912 7913 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 7914 return oc_method; 7915 } 7916 7917 return isTemplate ? oc_function_template : oc_function; 7918} 7919 7920void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 7921 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 7922 if (!Ctor) return; 7923 7924 Ctor = Ctor->getInheritedConstructor(); 7925 if (!Ctor) return; 7926 7927 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 7928} 7929 7930} // end anonymous namespace 7931 7932// Notes the location of an overload candidate. 7933void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 7934 std::string FnDesc; 7935 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 7936 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 7937 << (unsigned) K << FnDesc; 7938 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 7939 Diag(Fn->getLocation(), PD); 7940 MaybeEmitInheritedConstructorNote(*this, Fn); 7941} 7942 7943//Notes the location of all overload candidates designated through 7944// OverloadedExpr 7945void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 7946 assert(OverloadedExpr->getType() == Context.OverloadTy); 7947 7948 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 7949 OverloadExpr *OvlExpr = Ovl.Expression; 7950 7951 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 7952 IEnd = OvlExpr->decls_end(); 7953 I != IEnd; ++I) { 7954 if (FunctionTemplateDecl *FunTmpl = 7955 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 7956 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 7957 } else if (FunctionDecl *Fun 7958 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 7959 NoteOverloadCandidate(Fun, DestType); 7960 } 7961 } 7962} 7963 7964/// Diagnoses an ambiguous conversion. The partial diagnostic is the 7965/// "lead" diagnostic; it will be given two arguments, the source and 7966/// target types of the conversion. 7967void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 7968 Sema &S, 7969 SourceLocation CaretLoc, 7970 const PartialDiagnostic &PDiag) const { 7971 S.Diag(CaretLoc, PDiag) 7972 << Ambiguous.getFromType() << Ambiguous.getToType(); 7973 for (AmbiguousConversionSequence::const_iterator 7974 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 7975 S.NoteOverloadCandidate(*I); 7976 } 7977} 7978 7979namespace { 7980 7981void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 7982 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 7983 assert(Conv.isBad()); 7984 assert(Cand->Function && "for now, candidate must be a function"); 7985 FunctionDecl *Fn = Cand->Function; 7986 7987 // There's a conversion slot for the object argument if this is a 7988 // non-constructor method. Note that 'I' corresponds the 7989 // conversion-slot index. 7990 bool isObjectArgument = false; 7991 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 7992 if (I == 0) 7993 isObjectArgument = true; 7994 else 7995 I--; 7996 } 7997 7998 std::string FnDesc; 7999 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8000 8001 Expr *FromExpr = Conv.Bad.FromExpr; 8002 QualType FromTy = Conv.Bad.getFromType(); 8003 QualType ToTy = Conv.Bad.getToType(); 8004 8005 if (FromTy == S.Context.OverloadTy) { 8006 assert(FromExpr && "overload set argument came from implicit argument?"); 8007 Expr *E = FromExpr->IgnoreParens(); 8008 if (isa<UnaryOperator>(E)) 8009 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8010 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8011 8012 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8013 << (unsigned) FnKind << FnDesc 8014 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8015 << ToTy << Name << I+1; 8016 MaybeEmitInheritedConstructorNote(S, Fn); 8017 return; 8018 } 8019 8020 // Do some hand-waving analysis to see if the non-viability is due 8021 // to a qualifier mismatch. 8022 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8023 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8024 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8025 CToTy = RT->getPointeeType(); 8026 else { 8027 // TODO: detect and diagnose the full richness of const mismatches. 8028 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8029 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8030 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8031 } 8032 8033 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8034 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8035 Qualifiers FromQs = CFromTy.getQualifiers(); 8036 Qualifiers ToQs = CToTy.getQualifiers(); 8037 8038 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8039 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8040 << (unsigned) FnKind << FnDesc 8041 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8042 << FromTy 8043 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8044 << (unsigned) isObjectArgument << I+1; 8045 MaybeEmitInheritedConstructorNote(S, Fn); 8046 return; 8047 } 8048 8049 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8050 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8051 << (unsigned) FnKind << FnDesc 8052 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8053 << FromTy 8054 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8055 << (unsigned) isObjectArgument << I+1; 8056 MaybeEmitInheritedConstructorNote(S, Fn); 8057 return; 8058 } 8059 8060 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8061 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8062 << (unsigned) FnKind << FnDesc 8063 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8064 << FromTy 8065 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8066 << (unsigned) isObjectArgument << I+1; 8067 MaybeEmitInheritedConstructorNote(S, Fn); 8068 return; 8069 } 8070 8071 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8072 assert(CVR && "unexpected qualifiers mismatch"); 8073 8074 if (isObjectArgument) { 8075 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8076 << (unsigned) FnKind << FnDesc 8077 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8078 << FromTy << (CVR - 1); 8079 } else { 8080 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8081 << (unsigned) FnKind << FnDesc 8082 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8083 << FromTy << (CVR - 1) << I+1; 8084 } 8085 MaybeEmitInheritedConstructorNote(S, Fn); 8086 return; 8087 } 8088 8089 // Special diagnostic for failure to convert an initializer list, since 8090 // telling the user that it has type void is not useful. 8091 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8092 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8093 << (unsigned) FnKind << FnDesc 8094 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8095 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8096 MaybeEmitInheritedConstructorNote(S, Fn); 8097 return; 8098 } 8099 8100 // Diagnose references or pointers to incomplete types differently, 8101 // since it's far from impossible that the incompleteness triggered 8102 // the failure. 8103 QualType TempFromTy = FromTy.getNonReferenceType(); 8104 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8105 TempFromTy = PTy->getPointeeType(); 8106 if (TempFromTy->isIncompleteType()) { 8107 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8108 << (unsigned) FnKind << FnDesc 8109 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8110 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8111 MaybeEmitInheritedConstructorNote(S, Fn); 8112 return; 8113 } 8114 8115 // Diagnose base -> derived pointer conversions. 8116 unsigned BaseToDerivedConversion = 0; 8117 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8118 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8119 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8120 FromPtrTy->getPointeeType()) && 8121 !FromPtrTy->getPointeeType()->isIncompleteType() && 8122 !ToPtrTy->getPointeeType()->isIncompleteType() && 8123 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8124 FromPtrTy->getPointeeType())) 8125 BaseToDerivedConversion = 1; 8126 } 8127 } else if (const ObjCObjectPointerType *FromPtrTy 8128 = FromTy->getAs<ObjCObjectPointerType>()) { 8129 if (const ObjCObjectPointerType *ToPtrTy 8130 = ToTy->getAs<ObjCObjectPointerType>()) 8131 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8132 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8133 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8134 FromPtrTy->getPointeeType()) && 8135 FromIface->isSuperClassOf(ToIface)) 8136 BaseToDerivedConversion = 2; 8137 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8138 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8139 !FromTy->isIncompleteType() && 8140 !ToRefTy->getPointeeType()->isIncompleteType() && 8141 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8142 BaseToDerivedConversion = 3; 8143 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8144 ToTy.getNonReferenceType().getCanonicalType() == 8145 FromTy.getNonReferenceType().getCanonicalType()) { 8146 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8147 << (unsigned) FnKind << FnDesc 8148 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8149 << (unsigned) isObjectArgument << I + 1; 8150 MaybeEmitInheritedConstructorNote(S, Fn); 8151 return; 8152 } 8153 } 8154 8155 if (BaseToDerivedConversion) { 8156 S.Diag(Fn->getLocation(), 8157 diag::note_ovl_candidate_bad_base_to_derived_conv) 8158 << (unsigned) FnKind << FnDesc 8159 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8160 << (BaseToDerivedConversion - 1) 8161 << FromTy << ToTy << I+1; 8162 MaybeEmitInheritedConstructorNote(S, Fn); 8163 return; 8164 } 8165 8166 if (isa<ObjCObjectPointerType>(CFromTy) && 8167 isa<PointerType>(CToTy)) { 8168 Qualifiers FromQs = CFromTy.getQualifiers(); 8169 Qualifiers ToQs = CToTy.getQualifiers(); 8170 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8171 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8172 << (unsigned) FnKind << FnDesc 8173 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8174 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8175 MaybeEmitInheritedConstructorNote(S, Fn); 8176 return; 8177 } 8178 } 8179 8180 // Emit the generic diagnostic and, optionally, add the hints to it. 8181 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8182 FDiag << (unsigned) FnKind << FnDesc 8183 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8184 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8185 << (unsigned) (Cand->Fix.Kind); 8186 8187 // If we can fix the conversion, suggest the FixIts. 8188 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8189 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8190 FDiag << *HI; 8191 S.Diag(Fn->getLocation(), FDiag); 8192 8193 MaybeEmitInheritedConstructorNote(S, Fn); 8194} 8195 8196void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8197 unsigned NumFormalArgs) { 8198 // TODO: treat calls to a missing default constructor as a special case 8199 8200 FunctionDecl *Fn = Cand->Function; 8201 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8202 8203 unsigned MinParams = Fn->getMinRequiredArguments(); 8204 8205 // With invalid overloaded operators, it's possible that we think we 8206 // have an arity mismatch when it fact it looks like we have the 8207 // right number of arguments, because only overloaded operators have 8208 // the weird behavior of overloading member and non-member functions. 8209 // Just don't report anything. 8210 if (Fn->isInvalidDecl() && 8211 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8212 return; 8213 8214 // at least / at most / exactly 8215 unsigned mode, modeCount; 8216 if (NumFormalArgs < MinParams) { 8217 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8218 (Cand->FailureKind == ovl_fail_bad_deduction && 8219 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8220 if (MinParams != FnTy->getNumArgs() || 8221 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8222 mode = 0; // "at least" 8223 else 8224 mode = 2; // "exactly" 8225 modeCount = MinParams; 8226 } else { 8227 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8228 (Cand->FailureKind == ovl_fail_bad_deduction && 8229 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8230 if (MinParams != FnTy->getNumArgs()) 8231 mode = 1; // "at most" 8232 else 8233 mode = 2; // "exactly" 8234 modeCount = FnTy->getNumArgs(); 8235 } 8236 8237 std::string Description; 8238 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8239 8240 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8241 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8242 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8243 << Fn->getParamDecl(0) << NumFormalArgs; 8244 else 8245 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8246 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8247 << modeCount << NumFormalArgs; 8248 MaybeEmitInheritedConstructorNote(S, Fn); 8249} 8250 8251/// Diagnose a failed template-argument deduction. 8252void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8253 unsigned NumArgs) { 8254 FunctionDecl *Fn = Cand->Function; // pattern 8255 8256 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8257 NamedDecl *ParamD; 8258 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8259 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8260 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8261 switch (Cand->DeductionFailure.Result) { 8262 case Sema::TDK_Success: 8263 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8264 8265 case Sema::TDK_Incomplete: { 8266 assert(ParamD && "no parameter found for incomplete deduction result"); 8267 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8268 << ParamD->getDeclName(); 8269 MaybeEmitInheritedConstructorNote(S, Fn); 8270 return; 8271 } 8272 8273 case Sema::TDK_Underqualified: { 8274 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8275 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8276 8277 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8278 8279 // Param will have been canonicalized, but it should just be a 8280 // qualified version of ParamD, so move the qualifiers to that. 8281 QualifierCollector Qs; 8282 Qs.strip(Param); 8283 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8284 assert(S.Context.hasSameType(Param, NonCanonParam)); 8285 8286 // Arg has also been canonicalized, but there's nothing we can do 8287 // about that. It also doesn't matter as much, because it won't 8288 // have any template parameters in it (because deduction isn't 8289 // done on dependent types). 8290 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8291 8292 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8293 << ParamD->getDeclName() << Arg << NonCanonParam; 8294 MaybeEmitInheritedConstructorNote(S, Fn); 8295 return; 8296 } 8297 8298 case Sema::TDK_Inconsistent: { 8299 assert(ParamD && "no parameter found for inconsistent deduction result"); 8300 int which = 0; 8301 if (isa<TemplateTypeParmDecl>(ParamD)) 8302 which = 0; 8303 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8304 which = 1; 8305 else { 8306 which = 2; 8307 } 8308 8309 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8310 << which << ParamD->getDeclName() 8311 << *Cand->DeductionFailure.getFirstArg() 8312 << *Cand->DeductionFailure.getSecondArg(); 8313 MaybeEmitInheritedConstructorNote(S, Fn); 8314 return; 8315 } 8316 8317 case Sema::TDK_InvalidExplicitArguments: 8318 assert(ParamD && "no parameter found for invalid explicit arguments"); 8319 if (ParamD->getDeclName()) 8320 S.Diag(Fn->getLocation(), 8321 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8322 << ParamD->getDeclName(); 8323 else { 8324 int index = 0; 8325 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8326 index = TTP->getIndex(); 8327 else if (NonTypeTemplateParmDecl *NTTP 8328 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8329 index = NTTP->getIndex(); 8330 else 8331 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8332 S.Diag(Fn->getLocation(), 8333 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8334 << (index + 1); 8335 } 8336 MaybeEmitInheritedConstructorNote(S, Fn); 8337 return; 8338 8339 case Sema::TDK_TooManyArguments: 8340 case Sema::TDK_TooFewArguments: 8341 DiagnoseArityMismatch(S, Cand, NumArgs); 8342 return; 8343 8344 case Sema::TDK_InstantiationDepth: 8345 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8346 MaybeEmitInheritedConstructorNote(S, Fn); 8347 return; 8348 8349 case Sema::TDK_SubstitutionFailure: { 8350 // Format the template argument list into the argument string. 8351 llvm::SmallString<128> TemplateArgString; 8352 if (TemplateArgumentList *Args = 8353 Cand->DeductionFailure.getTemplateArgumentList()) { 8354 TemplateArgString = " "; 8355 TemplateArgString += S.getTemplateArgumentBindingsText( 8356 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8357 } 8358 8359 // If this candidate was disabled by enable_if, say so. 8360 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8361 if (PDiag && PDiag->second.getDiagID() == 8362 diag::err_typename_nested_not_found_enable_if) { 8363 // FIXME: Use the source range of the condition, and the fully-qualified 8364 // name of the enable_if template. These are both present in PDiag. 8365 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8366 << "'enable_if'" << TemplateArgString; 8367 return; 8368 } 8369 8370 // Format the SFINAE diagnostic into the argument string. 8371 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8372 // formatted message in another diagnostic. 8373 llvm::SmallString<128> SFINAEArgString; 8374 SourceRange R; 8375 if (PDiag) { 8376 SFINAEArgString = ": "; 8377 R = SourceRange(PDiag->first, PDiag->first); 8378 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8379 } 8380 8381 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8382 << TemplateArgString << SFINAEArgString << R; 8383 MaybeEmitInheritedConstructorNote(S, Fn); 8384 return; 8385 } 8386 8387 // TODO: diagnose these individually, then kill off 8388 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8389 case Sema::TDK_NonDeducedMismatch: 8390 case Sema::TDK_FailedOverloadResolution: 8391 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8392 MaybeEmitInheritedConstructorNote(S, Fn); 8393 return; 8394 } 8395} 8396 8397/// CUDA: diagnose an invalid call across targets. 8398void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8399 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8400 FunctionDecl *Callee = Cand->Function; 8401 8402 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8403 CalleeTarget = S.IdentifyCUDATarget(Callee); 8404 8405 std::string FnDesc; 8406 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8407 8408 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8409 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8410} 8411 8412/// Generates a 'note' diagnostic for an overload candidate. We've 8413/// already generated a primary error at the call site. 8414/// 8415/// It really does need to be a single diagnostic with its caret 8416/// pointed at the candidate declaration. Yes, this creates some 8417/// major challenges of technical writing. Yes, this makes pointing 8418/// out problems with specific arguments quite awkward. It's still 8419/// better than generating twenty screens of text for every failed 8420/// overload. 8421/// 8422/// It would be great to be able to express per-candidate problems 8423/// more richly for those diagnostic clients that cared, but we'd 8424/// still have to be just as careful with the default diagnostics. 8425void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8426 unsigned NumArgs) { 8427 FunctionDecl *Fn = Cand->Function; 8428 8429 // Note deleted candidates, but only if they're viable. 8430 if (Cand->Viable && (Fn->isDeleted() || 8431 S.isFunctionConsideredUnavailable(Fn))) { 8432 std::string FnDesc; 8433 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8434 8435 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8436 << FnKind << FnDesc 8437 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8438 MaybeEmitInheritedConstructorNote(S, Fn); 8439 return; 8440 } 8441 8442 // We don't really have anything else to say about viable candidates. 8443 if (Cand->Viable) { 8444 S.NoteOverloadCandidate(Fn); 8445 return; 8446 } 8447 8448 switch (Cand->FailureKind) { 8449 case ovl_fail_too_many_arguments: 8450 case ovl_fail_too_few_arguments: 8451 return DiagnoseArityMismatch(S, Cand, NumArgs); 8452 8453 case ovl_fail_bad_deduction: 8454 return DiagnoseBadDeduction(S, Cand, NumArgs); 8455 8456 case ovl_fail_trivial_conversion: 8457 case ovl_fail_bad_final_conversion: 8458 case ovl_fail_final_conversion_not_exact: 8459 return S.NoteOverloadCandidate(Fn); 8460 8461 case ovl_fail_bad_conversion: { 8462 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8463 for (unsigned N = Cand->NumConversions; I != N; ++I) 8464 if (Cand->Conversions[I].isBad()) 8465 return DiagnoseBadConversion(S, Cand, I); 8466 8467 // FIXME: this currently happens when we're called from SemaInit 8468 // when user-conversion overload fails. Figure out how to handle 8469 // those conditions and diagnose them well. 8470 return S.NoteOverloadCandidate(Fn); 8471 } 8472 8473 case ovl_fail_bad_target: 8474 return DiagnoseBadTarget(S, Cand); 8475 } 8476} 8477 8478void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8479 // Desugar the type of the surrogate down to a function type, 8480 // retaining as many typedefs as possible while still showing 8481 // the function type (and, therefore, its parameter types). 8482 QualType FnType = Cand->Surrogate->getConversionType(); 8483 bool isLValueReference = false; 8484 bool isRValueReference = false; 8485 bool isPointer = false; 8486 if (const LValueReferenceType *FnTypeRef = 8487 FnType->getAs<LValueReferenceType>()) { 8488 FnType = FnTypeRef->getPointeeType(); 8489 isLValueReference = true; 8490 } else if (const RValueReferenceType *FnTypeRef = 8491 FnType->getAs<RValueReferenceType>()) { 8492 FnType = FnTypeRef->getPointeeType(); 8493 isRValueReference = true; 8494 } 8495 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8496 FnType = FnTypePtr->getPointeeType(); 8497 isPointer = true; 8498 } 8499 // Desugar down to a function type. 8500 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8501 // Reconstruct the pointer/reference as appropriate. 8502 if (isPointer) FnType = S.Context.getPointerType(FnType); 8503 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8504 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8505 8506 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8507 << FnType; 8508 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8509} 8510 8511void NoteBuiltinOperatorCandidate(Sema &S, 8512 const char *Opc, 8513 SourceLocation OpLoc, 8514 OverloadCandidate *Cand) { 8515 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8516 std::string TypeStr("operator"); 8517 TypeStr += Opc; 8518 TypeStr += "("; 8519 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8520 if (Cand->NumConversions == 1) { 8521 TypeStr += ")"; 8522 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8523 } else { 8524 TypeStr += ", "; 8525 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8526 TypeStr += ")"; 8527 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8528 } 8529} 8530 8531void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8532 OverloadCandidate *Cand) { 8533 unsigned NoOperands = Cand->NumConversions; 8534 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8535 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8536 if (ICS.isBad()) break; // all meaningless after first invalid 8537 if (!ICS.isAmbiguous()) continue; 8538 8539 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8540 S.PDiag(diag::note_ambiguous_type_conversion)); 8541 } 8542} 8543 8544SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8545 if (Cand->Function) 8546 return Cand->Function->getLocation(); 8547 if (Cand->IsSurrogate) 8548 return Cand->Surrogate->getLocation(); 8549 return SourceLocation(); 8550} 8551 8552static unsigned 8553RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8554 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8555 case Sema::TDK_Success: 8556 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8557 8558 case Sema::TDK_Incomplete: 8559 return 1; 8560 8561 case Sema::TDK_Underqualified: 8562 case Sema::TDK_Inconsistent: 8563 return 2; 8564 8565 case Sema::TDK_SubstitutionFailure: 8566 case Sema::TDK_NonDeducedMismatch: 8567 return 3; 8568 8569 case Sema::TDK_InstantiationDepth: 8570 case Sema::TDK_FailedOverloadResolution: 8571 return 4; 8572 8573 case Sema::TDK_InvalidExplicitArguments: 8574 return 5; 8575 8576 case Sema::TDK_TooManyArguments: 8577 case Sema::TDK_TooFewArguments: 8578 return 6; 8579 } 8580 llvm_unreachable("Unhandled deduction result"); 8581} 8582 8583struct CompareOverloadCandidatesForDisplay { 8584 Sema &S; 8585 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8586 8587 bool operator()(const OverloadCandidate *L, 8588 const OverloadCandidate *R) { 8589 // Fast-path this check. 8590 if (L == R) return false; 8591 8592 // Order first by viability. 8593 if (L->Viable) { 8594 if (!R->Viable) return true; 8595 8596 // TODO: introduce a tri-valued comparison for overload 8597 // candidates. Would be more worthwhile if we had a sort 8598 // that could exploit it. 8599 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8600 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8601 } else if (R->Viable) 8602 return false; 8603 8604 assert(L->Viable == R->Viable); 8605 8606 // Criteria by which we can sort non-viable candidates: 8607 if (!L->Viable) { 8608 // 1. Arity mismatches come after other candidates. 8609 if (L->FailureKind == ovl_fail_too_many_arguments || 8610 L->FailureKind == ovl_fail_too_few_arguments) 8611 return false; 8612 if (R->FailureKind == ovl_fail_too_many_arguments || 8613 R->FailureKind == ovl_fail_too_few_arguments) 8614 return true; 8615 8616 // 2. Bad conversions come first and are ordered by the number 8617 // of bad conversions and quality of good conversions. 8618 if (L->FailureKind == ovl_fail_bad_conversion) { 8619 if (R->FailureKind != ovl_fail_bad_conversion) 8620 return true; 8621 8622 // The conversion that can be fixed with a smaller number of changes, 8623 // comes first. 8624 unsigned numLFixes = L->Fix.NumConversionsFixed; 8625 unsigned numRFixes = R->Fix.NumConversionsFixed; 8626 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8627 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8628 if (numLFixes != numRFixes) { 8629 if (numLFixes < numRFixes) 8630 return true; 8631 else 8632 return false; 8633 } 8634 8635 // If there's any ordering between the defined conversions... 8636 // FIXME: this might not be transitive. 8637 assert(L->NumConversions == R->NumConversions); 8638 8639 int leftBetter = 0; 8640 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8641 for (unsigned E = L->NumConversions; I != E; ++I) { 8642 switch (CompareImplicitConversionSequences(S, 8643 L->Conversions[I], 8644 R->Conversions[I])) { 8645 case ImplicitConversionSequence::Better: 8646 leftBetter++; 8647 break; 8648 8649 case ImplicitConversionSequence::Worse: 8650 leftBetter--; 8651 break; 8652 8653 case ImplicitConversionSequence::Indistinguishable: 8654 break; 8655 } 8656 } 8657 if (leftBetter > 0) return true; 8658 if (leftBetter < 0) return false; 8659 8660 } else if (R->FailureKind == ovl_fail_bad_conversion) 8661 return false; 8662 8663 if (L->FailureKind == ovl_fail_bad_deduction) { 8664 if (R->FailureKind != ovl_fail_bad_deduction) 8665 return true; 8666 8667 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8668 return RankDeductionFailure(L->DeductionFailure) 8669 < RankDeductionFailure(R->DeductionFailure); 8670 } else if (R->FailureKind == ovl_fail_bad_deduction) 8671 return false; 8672 8673 // TODO: others? 8674 } 8675 8676 // Sort everything else by location. 8677 SourceLocation LLoc = GetLocationForCandidate(L); 8678 SourceLocation RLoc = GetLocationForCandidate(R); 8679 8680 // Put candidates without locations (e.g. builtins) at the end. 8681 if (LLoc.isInvalid()) return false; 8682 if (RLoc.isInvalid()) return true; 8683 8684 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8685 } 8686}; 8687 8688/// CompleteNonViableCandidate - Normally, overload resolution only 8689/// computes up to the first. Produces the FixIt set if possible. 8690void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8691 llvm::ArrayRef<Expr *> Args) { 8692 assert(!Cand->Viable); 8693 8694 // Don't do anything on failures other than bad conversion. 8695 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8696 8697 // We only want the FixIts if all the arguments can be corrected. 8698 bool Unfixable = false; 8699 // Use a implicit copy initialization to check conversion fixes. 8700 Cand->Fix.setConversionChecker(TryCopyInitialization); 8701 8702 // Skip forward to the first bad conversion. 8703 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8704 unsigned ConvCount = Cand->NumConversions; 8705 while (true) { 8706 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8707 ConvIdx++; 8708 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8709 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8710 break; 8711 } 8712 } 8713 8714 if (ConvIdx == ConvCount) 8715 return; 8716 8717 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8718 "remaining conversion is initialized?"); 8719 8720 // FIXME: this should probably be preserved from the overload 8721 // operation somehow. 8722 bool SuppressUserConversions = false; 8723 8724 const FunctionProtoType* Proto; 8725 unsigned ArgIdx = ConvIdx; 8726 8727 if (Cand->IsSurrogate) { 8728 QualType ConvType 8729 = Cand->Surrogate->getConversionType().getNonReferenceType(); 8730 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8731 ConvType = ConvPtrType->getPointeeType(); 8732 Proto = ConvType->getAs<FunctionProtoType>(); 8733 ArgIdx--; 8734 } else if (Cand->Function) { 8735 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8736 if (isa<CXXMethodDecl>(Cand->Function) && 8737 !isa<CXXConstructorDecl>(Cand->Function)) 8738 ArgIdx--; 8739 } else { 8740 // Builtin binary operator with a bad first conversion. 8741 assert(ConvCount <= 3); 8742 for (; ConvIdx != ConvCount; ++ConvIdx) 8743 Cand->Conversions[ConvIdx] 8744 = TryCopyInitialization(S, Args[ConvIdx], 8745 Cand->BuiltinTypes.ParamTypes[ConvIdx], 8746 SuppressUserConversions, 8747 /*InOverloadResolution*/ true, 8748 /*AllowObjCWritebackConversion=*/ 8749 S.getLangOpts().ObjCAutoRefCount); 8750 return; 8751 } 8752 8753 // Fill in the rest of the conversions. 8754 unsigned NumArgsInProto = Proto->getNumArgs(); 8755 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 8756 if (ArgIdx < NumArgsInProto) { 8757 Cand->Conversions[ConvIdx] 8758 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 8759 SuppressUserConversions, 8760 /*InOverloadResolution=*/true, 8761 /*AllowObjCWritebackConversion=*/ 8762 S.getLangOpts().ObjCAutoRefCount); 8763 // Store the FixIt in the candidate if it exists. 8764 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 8765 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 8766 } 8767 else 8768 Cand->Conversions[ConvIdx].setEllipsis(); 8769 } 8770} 8771 8772} // end anonymous namespace 8773 8774/// PrintOverloadCandidates - When overload resolution fails, prints 8775/// diagnostic messages containing the candidates in the candidate 8776/// set. 8777void OverloadCandidateSet::NoteCandidates(Sema &S, 8778 OverloadCandidateDisplayKind OCD, 8779 llvm::ArrayRef<Expr *> Args, 8780 const char *Opc, 8781 SourceLocation OpLoc) { 8782 // Sort the candidates by viability and position. Sorting directly would 8783 // be prohibitive, so we make a set of pointers and sort those. 8784 SmallVector<OverloadCandidate*, 32> Cands; 8785 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 8786 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 8787 if (Cand->Viable) 8788 Cands.push_back(Cand); 8789 else if (OCD == OCD_AllCandidates) { 8790 CompleteNonViableCandidate(S, Cand, Args); 8791 if (Cand->Function || Cand->IsSurrogate) 8792 Cands.push_back(Cand); 8793 // Otherwise, this a non-viable builtin candidate. We do not, in general, 8794 // want to list every possible builtin candidate. 8795 } 8796 } 8797 8798 std::sort(Cands.begin(), Cands.end(), 8799 CompareOverloadCandidatesForDisplay(S)); 8800 8801 bool ReportedAmbiguousConversions = false; 8802 8803 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 8804 const DiagnosticsEngine::OverloadsShown ShowOverloads = 8805 S.Diags.getShowOverloads(); 8806 unsigned CandsShown = 0; 8807 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 8808 OverloadCandidate *Cand = *I; 8809 8810 // Set an arbitrary limit on the number of candidate functions we'll spam 8811 // the user with. FIXME: This limit should depend on details of the 8812 // candidate list. 8813 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) { 8814 break; 8815 } 8816 ++CandsShown; 8817 8818 if (Cand->Function) 8819 NoteFunctionCandidate(S, Cand, Args.size()); 8820 else if (Cand->IsSurrogate) 8821 NoteSurrogateCandidate(S, Cand); 8822 else { 8823 assert(Cand->Viable && 8824 "Non-viable built-in candidates are not added to Cands."); 8825 // Generally we only see ambiguities including viable builtin 8826 // operators if overload resolution got screwed up by an 8827 // ambiguous user-defined conversion. 8828 // 8829 // FIXME: It's quite possible for different conversions to see 8830 // different ambiguities, though. 8831 if (!ReportedAmbiguousConversions) { 8832 NoteAmbiguousUserConversions(S, OpLoc, Cand); 8833 ReportedAmbiguousConversions = true; 8834 } 8835 8836 // If this is a viable builtin, print it. 8837 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 8838 } 8839 } 8840 8841 if (I != E) 8842 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 8843} 8844 8845// [PossiblyAFunctionType] --> [Return] 8846// NonFunctionType --> NonFunctionType 8847// R (A) --> R(A) 8848// R (*)(A) --> R (A) 8849// R (&)(A) --> R (A) 8850// R (S::*)(A) --> R (A) 8851QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 8852 QualType Ret = PossiblyAFunctionType; 8853 if (const PointerType *ToTypePtr = 8854 PossiblyAFunctionType->getAs<PointerType>()) 8855 Ret = ToTypePtr->getPointeeType(); 8856 else if (const ReferenceType *ToTypeRef = 8857 PossiblyAFunctionType->getAs<ReferenceType>()) 8858 Ret = ToTypeRef->getPointeeType(); 8859 else if (const MemberPointerType *MemTypePtr = 8860 PossiblyAFunctionType->getAs<MemberPointerType>()) 8861 Ret = MemTypePtr->getPointeeType(); 8862 Ret = 8863 Context.getCanonicalType(Ret).getUnqualifiedType(); 8864 return Ret; 8865} 8866 8867// A helper class to help with address of function resolution 8868// - allows us to avoid passing around all those ugly parameters 8869class AddressOfFunctionResolver 8870{ 8871 Sema& S; 8872 Expr* SourceExpr; 8873 const QualType& TargetType; 8874 QualType TargetFunctionType; // Extracted function type from target type 8875 8876 bool Complain; 8877 //DeclAccessPair& ResultFunctionAccessPair; 8878 ASTContext& Context; 8879 8880 bool TargetTypeIsNonStaticMemberFunction; 8881 bool FoundNonTemplateFunction; 8882 8883 OverloadExpr::FindResult OvlExprInfo; 8884 OverloadExpr *OvlExpr; 8885 TemplateArgumentListInfo OvlExplicitTemplateArgs; 8886 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 8887 8888public: 8889 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 8890 const QualType& TargetType, bool Complain) 8891 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 8892 Complain(Complain), Context(S.getASTContext()), 8893 TargetTypeIsNonStaticMemberFunction( 8894 !!TargetType->getAs<MemberPointerType>()), 8895 FoundNonTemplateFunction(false), 8896 OvlExprInfo(OverloadExpr::find(SourceExpr)), 8897 OvlExpr(OvlExprInfo.Expression) 8898 { 8899 ExtractUnqualifiedFunctionTypeFromTargetType(); 8900 8901 if (!TargetFunctionType->isFunctionType()) { 8902 if (OvlExpr->hasExplicitTemplateArgs()) { 8903 DeclAccessPair dap; 8904 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 8905 OvlExpr, false, &dap) ) { 8906 8907 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 8908 if (!Method->isStatic()) { 8909 // If the target type is a non-function type and the function 8910 // found is a non-static member function, pretend as if that was 8911 // the target, it's the only possible type to end up with. 8912 TargetTypeIsNonStaticMemberFunction = true; 8913 8914 // And skip adding the function if its not in the proper form. 8915 // We'll diagnose this due to an empty set of functions. 8916 if (!OvlExprInfo.HasFormOfMemberPointer) 8917 return; 8918 } 8919 } 8920 8921 Matches.push_back(std::make_pair(dap,Fn)); 8922 } 8923 } 8924 return; 8925 } 8926 8927 if (OvlExpr->hasExplicitTemplateArgs()) 8928 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 8929 8930 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 8931 // C++ [over.over]p4: 8932 // If more than one function is selected, [...] 8933 if (Matches.size() > 1) { 8934 if (FoundNonTemplateFunction) 8935 EliminateAllTemplateMatches(); 8936 else 8937 EliminateAllExceptMostSpecializedTemplate(); 8938 } 8939 } 8940 } 8941 8942private: 8943 bool isTargetTypeAFunction() const { 8944 return TargetFunctionType->isFunctionType(); 8945 } 8946 8947 // [ToType] [Return] 8948 8949 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 8950 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 8951 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 8952 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 8953 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 8954 } 8955 8956 // return true if any matching specializations were found 8957 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 8958 const DeclAccessPair& CurAccessFunPair) { 8959 if (CXXMethodDecl *Method 8960 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 8961 // Skip non-static function templates when converting to pointer, and 8962 // static when converting to member pointer. 8963 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 8964 return false; 8965 } 8966 else if (TargetTypeIsNonStaticMemberFunction) 8967 return false; 8968 8969 // C++ [over.over]p2: 8970 // If the name is a function template, template argument deduction is 8971 // done (14.8.2.2), and if the argument deduction succeeds, the 8972 // resulting template argument list is used to generate a single 8973 // function template specialization, which is added to the set of 8974 // overloaded functions considered. 8975 FunctionDecl *Specialization = 0; 8976 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 8977 if (Sema::TemplateDeductionResult Result 8978 = S.DeduceTemplateArguments(FunctionTemplate, 8979 &OvlExplicitTemplateArgs, 8980 TargetFunctionType, Specialization, 8981 Info)) { 8982 // FIXME: make a note of the failed deduction for diagnostics. 8983 (void)Result; 8984 return false; 8985 } 8986 8987 // Template argument deduction ensures that we have an exact match. 8988 // This function template specicalization works. 8989 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 8990 assert(TargetFunctionType 8991 == Context.getCanonicalType(Specialization->getType())); 8992 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 8993 return true; 8994 } 8995 8996 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 8997 const DeclAccessPair& CurAccessFunPair) { 8998 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 8999 // Skip non-static functions when converting to pointer, and static 9000 // when converting to member pointer. 9001 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9002 return false; 9003 } 9004 else if (TargetTypeIsNonStaticMemberFunction) 9005 return false; 9006 9007 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9008 if (S.getLangOpts().CUDA) 9009 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9010 if (S.CheckCUDATarget(Caller, FunDecl)) 9011 return false; 9012 9013 QualType ResultTy; 9014 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9015 FunDecl->getType()) || 9016 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9017 ResultTy)) { 9018 Matches.push_back(std::make_pair(CurAccessFunPair, 9019 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9020 FoundNonTemplateFunction = true; 9021 return true; 9022 } 9023 } 9024 9025 return false; 9026 } 9027 9028 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9029 bool Ret = false; 9030 9031 // If the overload expression doesn't have the form of a pointer to 9032 // member, don't try to convert it to a pointer-to-member type. 9033 if (IsInvalidFormOfPointerToMemberFunction()) 9034 return false; 9035 9036 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9037 E = OvlExpr->decls_end(); 9038 I != E; ++I) { 9039 // Look through any using declarations to find the underlying function. 9040 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9041 9042 // C++ [over.over]p3: 9043 // Non-member functions and static member functions match 9044 // targets of type "pointer-to-function" or "reference-to-function." 9045 // Nonstatic member functions match targets of 9046 // type "pointer-to-member-function." 9047 // Note that according to DR 247, the containing class does not matter. 9048 if (FunctionTemplateDecl *FunctionTemplate 9049 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9050 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9051 Ret = true; 9052 } 9053 // If we have explicit template arguments supplied, skip non-templates. 9054 else if (!OvlExpr->hasExplicitTemplateArgs() && 9055 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9056 Ret = true; 9057 } 9058 assert(Ret || Matches.empty()); 9059 return Ret; 9060 } 9061 9062 void EliminateAllExceptMostSpecializedTemplate() { 9063 // [...] and any given function template specialization F1 is 9064 // eliminated if the set contains a second function template 9065 // specialization whose function template is more specialized 9066 // than the function template of F1 according to the partial 9067 // ordering rules of 14.5.5.2. 9068 9069 // The algorithm specified above is quadratic. We instead use a 9070 // two-pass algorithm (similar to the one used to identify the 9071 // best viable function in an overload set) that identifies the 9072 // best function template (if it exists). 9073 9074 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9075 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9076 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9077 9078 UnresolvedSetIterator Result = 9079 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9080 TPOC_Other, 0, SourceExpr->getLocStart(), 9081 S.PDiag(), 9082 S.PDiag(diag::err_addr_ovl_ambiguous) 9083 << Matches[0].second->getDeclName(), 9084 S.PDiag(diag::note_ovl_candidate) 9085 << (unsigned) oc_function_template, 9086 Complain, TargetFunctionType); 9087 9088 if (Result != MatchesCopy.end()) { 9089 // Make it the first and only element 9090 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9091 Matches[0].second = cast<FunctionDecl>(*Result); 9092 Matches.resize(1); 9093 } 9094 } 9095 9096 void EliminateAllTemplateMatches() { 9097 // [...] any function template specializations in the set are 9098 // eliminated if the set also contains a non-template function, [...] 9099 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9100 if (Matches[I].second->getPrimaryTemplate() == 0) 9101 ++I; 9102 else { 9103 Matches[I] = Matches[--N]; 9104 Matches.set_size(N); 9105 } 9106 } 9107 } 9108 9109public: 9110 void ComplainNoMatchesFound() const { 9111 assert(Matches.empty()); 9112 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9113 << OvlExpr->getName() << TargetFunctionType 9114 << OvlExpr->getSourceRange(); 9115 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9116 } 9117 9118 bool IsInvalidFormOfPointerToMemberFunction() const { 9119 return TargetTypeIsNonStaticMemberFunction && 9120 !OvlExprInfo.HasFormOfMemberPointer; 9121 } 9122 9123 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9124 // TODO: Should we condition this on whether any functions might 9125 // have matched, or is it more appropriate to do that in callers? 9126 // TODO: a fixit wouldn't hurt. 9127 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9128 << TargetType << OvlExpr->getSourceRange(); 9129 } 9130 9131 void ComplainOfInvalidConversion() const { 9132 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9133 << OvlExpr->getName() << TargetType; 9134 } 9135 9136 void ComplainMultipleMatchesFound() const { 9137 assert(Matches.size() > 1); 9138 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9139 << OvlExpr->getName() 9140 << OvlExpr->getSourceRange(); 9141 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9142 } 9143 9144 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9145 9146 int getNumMatches() const { return Matches.size(); } 9147 9148 FunctionDecl* getMatchingFunctionDecl() const { 9149 if (Matches.size() != 1) return 0; 9150 return Matches[0].second; 9151 } 9152 9153 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9154 if (Matches.size() != 1) return 0; 9155 return &Matches[0].first; 9156 } 9157}; 9158 9159/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9160/// an overloaded function (C++ [over.over]), where @p From is an 9161/// expression with overloaded function type and @p ToType is the type 9162/// we're trying to resolve to. For example: 9163/// 9164/// @code 9165/// int f(double); 9166/// int f(int); 9167/// 9168/// int (*pfd)(double) = f; // selects f(double) 9169/// @endcode 9170/// 9171/// This routine returns the resulting FunctionDecl if it could be 9172/// resolved, and NULL otherwise. When @p Complain is true, this 9173/// routine will emit diagnostics if there is an error. 9174FunctionDecl * 9175Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9176 QualType TargetType, 9177 bool Complain, 9178 DeclAccessPair &FoundResult, 9179 bool *pHadMultipleCandidates) { 9180 assert(AddressOfExpr->getType() == Context.OverloadTy); 9181 9182 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9183 Complain); 9184 int NumMatches = Resolver.getNumMatches(); 9185 FunctionDecl* Fn = 0; 9186 if (NumMatches == 0 && Complain) { 9187 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9188 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9189 else 9190 Resolver.ComplainNoMatchesFound(); 9191 } 9192 else if (NumMatches > 1 && Complain) 9193 Resolver.ComplainMultipleMatchesFound(); 9194 else if (NumMatches == 1) { 9195 Fn = Resolver.getMatchingFunctionDecl(); 9196 assert(Fn); 9197 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9198 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn); 9199 if (Complain) 9200 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9201 } 9202 9203 if (pHadMultipleCandidates) 9204 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9205 return Fn; 9206} 9207 9208/// \brief Given an expression that refers to an overloaded function, try to 9209/// resolve that overloaded function expression down to a single function. 9210/// 9211/// This routine can only resolve template-ids that refer to a single function 9212/// template, where that template-id refers to a single template whose template 9213/// arguments are either provided by the template-id or have defaults, 9214/// as described in C++0x [temp.arg.explicit]p3. 9215FunctionDecl * 9216Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9217 bool Complain, 9218 DeclAccessPair *FoundResult) { 9219 // C++ [over.over]p1: 9220 // [...] [Note: any redundant set of parentheses surrounding the 9221 // overloaded function name is ignored (5.1). ] 9222 // C++ [over.over]p1: 9223 // [...] The overloaded function name can be preceded by the & 9224 // operator. 9225 9226 // If we didn't actually find any template-ids, we're done. 9227 if (!ovl->hasExplicitTemplateArgs()) 9228 return 0; 9229 9230 TemplateArgumentListInfo ExplicitTemplateArgs; 9231 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9232 9233 // Look through all of the overloaded functions, searching for one 9234 // whose type matches exactly. 9235 FunctionDecl *Matched = 0; 9236 for (UnresolvedSetIterator I = ovl->decls_begin(), 9237 E = ovl->decls_end(); I != E; ++I) { 9238 // C++0x [temp.arg.explicit]p3: 9239 // [...] In contexts where deduction is done and fails, or in contexts 9240 // where deduction is not done, if a template argument list is 9241 // specified and it, along with any default template arguments, 9242 // identifies a single function template specialization, then the 9243 // template-id is an lvalue for the function template specialization. 9244 FunctionTemplateDecl *FunctionTemplate 9245 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9246 9247 // C++ [over.over]p2: 9248 // If the name is a function template, template argument deduction is 9249 // done (14.8.2.2), and if the argument deduction succeeds, the 9250 // resulting template argument list is used to generate a single 9251 // function template specialization, which is added to the set of 9252 // overloaded functions considered. 9253 FunctionDecl *Specialization = 0; 9254 TemplateDeductionInfo Info(Context, ovl->getNameLoc()); 9255 if (TemplateDeductionResult Result 9256 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9257 Specialization, Info)) { 9258 // FIXME: make a note of the failed deduction for diagnostics. 9259 (void)Result; 9260 continue; 9261 } 9262 9263 assert(Specialization && "no specialization and no error?"); 9264 9265 // Multiple matches; we can't resolve to a single declaration. 9266 if (Matched) { 9267 if (Complain) { 9268 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9269 << ovl->getName(); 9270 NoteAllOverloadCandidates(ovl); 9271 } 9272 return 0; 9273 } 9274 9275 Matched = Specialization; 9276 if (FoundResult) *FoundResult = I.getPair(); 9277 } 9278 9279 return Matched; 9280} 9281 9282 9283 9284 9285// Resolve and fix an overloaded expression that can be resolved 9286// because it identifies a single function template specialization. 9287// 9288// Last three arguments should only be supplied if Complain = true 9289// 9290// Return true if it was logically possible to so resolve the 9291// expression, regardless of whether or not it succeeded. Always 9292// returns true if 'complain' is set. 9293bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9294 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9295 bool complain, const SourceRange& OpRangeForComplaining, 9296 QualType DestTypeForComplaining, 9297 unsigned DiagIDForComplaining) { 9298 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9299 9300 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9301 9302 DeclAccessPair found; 9303 ExprResult SingleFunctionExpression; 9304 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9305 ovl.Expression, /*complain*/ false, &found)) { 9306 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9307 SrcExpr = ExprError(); 9308 return true; 9309 } 9310 9311 // It is only correct to resolve to an instance method if we're 9312 // resolving a form that's permitted to be a pointer to member. 9313 // Otherwise we'll end up making a bound member expression, which 9314 // is illegal in all the contexts we resolve like this. 9315 if (!ovl.HasFormOfMemberPointer && 9316 isa<CXXMethodDecl>(fn) && 9317 cast<CXXMethodDecl>(fn)->isInstance()) { 9318 if (!complain) return false; 9319 9320 Diag(ovl.Expression->getExprLoc(), 9321 diag::err_bound_member_function) 9322 << 0 << ovl.Expression->getSourceRange(); 9323 9324 // TODO: I believe we only end up here if there's a mix of 9325 // static and non-static candidates (otherwise the expression 9326 // would have 'bound member' type, not 'overload' type). 9327 // Ideally we would note which candidate was chosen and why 9328 // the static candidates were rejected. 9329 SrcExpr = ExprError(); 9330 return true; 9331 } 9332 9333 // Fix the expression to refer to 'fn'. 9334 SingleFunctionExpression = 9335 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9336 9337 // If desired, do function-to-pointer decay. 9338 if (doFunctionPointerConverion) { 9339 SingleFunctionExpression = 9340 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9341 if (SingleFunctionExpression.isInvalid()) { 9342 SrcExpr = ExprError(); 9343 return true; 9344 } 9345 } 9346 } 9347 9348 if (!SingleFunctionExpression.isUsable()) { 9349 if (complain) { 9350 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9351 << ovl.Expression->getName() 9352 << DestTypeForComplaining 9353 << OpRangeForComplaining 9354 << ovl.Expression->getQualifierLoc().getSourceRange(); 9355 NoteAllOverloadCandidates(SrcExpr.get()); 9356 9357 SrcExpr = ExprError(); 9358 return true; 9359 } 9360 9361 return false; 9362 } 9363 9364 SrcExpr = SingleFunctionExpression; 9365 return true; 9366} 9367 9368/// \brief Add a single candidate to the overload set. 9369static void AddOverloadedCallCandidate(Sema &S, 9370 DeclAccessPair FoundDecl, 9371 TemplateArgumentListInfo *ExplicitTemplateArgs, 9372 llvm::ArrayRef<Expr *> Args, 9373 OverloadCandidateSet &CandidateSet, 9374 bool PartialOverloading, 9375 bool KnownValid) { 9376 NamedDecl *Callee = FoundDecl.getDecl(); 9377 if (isa<UsingShadowDecl>(Callee)) 9378 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9379 9380 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9381 if (ExplicitTemplateArgs) { 9382 assert(!KnownValid && "Explicit template arguments?"); 9383 return; 9384 } 9385 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9386 PartialOverloading); 9387 return; 9388 } 9389 9390 if (FunctionTemplateDecl *FuncTemplate 9391 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9392 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9393 ExplicitTemplateArgs, Args, CandidateSet); 9394 return; 9395 } 9396 9397 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9398} 9399 9400/// \brief Add the overload candidates named by callee and/or found by argument 9401/// dependent lookup to the given overload set. 9402void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9403 llvm::ArrayRef<Expr *> Args, 9404 OverloadCandidateSet &CandidateSet, 9405 bool PartialOverloading) { 9406 9407#ifndef NDEBUG 9408 // Verify that ArgumentDependentLookup is consistent with the rules 9409 // in C++0x [basic.lookup.argdep]p3: 9410 // 9411 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9412 // and let Y be the lookup set produced by argument dependent 9413 // lookup (defined as follows). If X contains 9414 // 9415 // -- a declaration of a class member, or 9416 // 9417 // -- a block-scope function declaration that is not a 9418 // using-declaration, or 9419 // 9420 // -- a declaration that is neither a function or a function 9421 // template 9422 // 9423 // then Y is empty. 9424 9425 if (ULE->requiresADL()) { 9426 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9427 E = ULE->decls_end(); I != E; ++I) { 9428 assert(!(*I)->getDeclContext()->isRecord()); 9429 assert(isa<UsingShadowDecl>(*I) || 9430 !(*I)->getDeclContext()->isFunctionOrMethod()); 9431 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9432 } 9433 } 9434#endif 9435 9436 // It would be nice to avoid this copy. 9437 TemplateArgumentListInfo TABuffer; 9438 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9439 if (ULE->hasExplicitTemplateArgs()) { 9440 ULE->copyTemplateArgumentsInto(TABuffer); 9441 ExplicitTemplateArgs = &TABuffer; 9442 } 9443 9444 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9445 E = ULE->decls_end(); I != E; ++I) 9446 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9447 CandidateSet, PartialOverloading, 9448 /*KnownValid*/ true); 9449 9450 if (ULE->requiresADL()) 9451 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9452 ULE->getExprLoc(), 9453 Args, ExplicitTemplateArgs, 9454 CandidateSet, PartialOverloading, 9455 ULE->isStdAssociatedNamespace()); 9456} 9457 9458/// Attempt to recover from an ill-formed use of a non-dependent name in a 9459/// template, where the non-dependent name was declared after the template 9460/// was defined. This is common in code written for a compilers which do not 9461/// correctly implement two-stage name lookup. 9462/// 9463/// Returns true if a viable candidate was found and a diagnostic was issued. 9464static bool 9465DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9466 const CXXScopeSpec &SS, LookupResult &R, 9467 TemplateArgumentListInfo *ExplicitTemplateArgs, 9468 llvm::ArrayRef<Expr *> Args) { 9469 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9470 return false; 9471 9472 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9473 if (DC->isTransparentContext()) 9474 continue; 9475 9476 SemaRef.LookupQualifiedName(R, DC); 9477 9478 if (!R.empty()) { 9479 R.suppressDiagnostics(); 9480 9481 if (isa<CXXRecordDecl>(DC)) { 9482 // Don't diagnose names we find in classes; we get much better 9483 // diagnostics for these from DiagnoseEmptyLookup. 9484 R.clear(); 9485 return false; 9486 } 9487 9488 OverloadCandidateSet Candidates(FnLoc); 9489 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9490 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9491 ExplicitTemplateArgs, Args, 9492 Candidates, false, /*KnownValid*/ false); 9493 9494 OverloadCandidateSet::iterator Best; 9495 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9496 // No viable functions. Don't bother the user with notes for functions 9497 // which don't work and shouldn't be found anyway. 9498 R.clear(); 9499 return false; 9500 } 9501 9502 // Find the namespaces where ADL would have looked, and suggest 9503 // declaring the function there instead. 9504 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9505 Sema::AssociatedClassSet AssociatedClasses; 9506 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9507 AssociatedNamespaces, 9508 AssociatedClasses); 9509 // Never suggest declaring a function within namespace 'std'. 9510 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9511 if (DeclContext *Std = SemaRef.getStdNamespace()) { 9512 for (Sema::AssociatedNamespaceSet::iterator 9513 it = AssociatedNamespaces.begin(), 9514 end = AssociatedNamespaces.end(); it != end; ++it) { 9515 if (!Std->Encloses(*it)) 9516 SuggestedNamespaces.insert(*it); 9517 } 9518 } else { 9519 // Lacking the 'std::' namespace, use all of the associated namespaces. 9520 SuggestedNamespaces = AssociatedNamespaces; 9521 } 9522 9523 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9524 << R.getLookupName(); 9525 if (SuggestedNamespaces.empty()) { 9526 SemaRef.Diag(Best->Function->getLocation(), 9527 diag::note_not_found_by_two_phase_lookup) 9528 << R.getLookupName() << 0; 9529 } else if (SuggestedNamespaces.size() == 1) { 9530 SemaRef.Diag(Best->Function->getLocation(), 9531 diag::note_not_found_by_two_phase_lookup) 9532 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9533 } else { 9534 // FIXME: It would be useful to list the associated namespaces here, 9535 // but the diagnostics infrastructure doesn't provide a way to produce 9536 // a localized representation of a list of items. 9537 SemaRef.Diag(Best->Function->getLocation(), 9538 diag::note_not_found_by_two_phase_lookup) 9539 << R.getLookupName() << 2; 9540 } 9541 9542 // Try to recover by calling this function. 9543 return true; 9544 } 9545 9546 R.clear(); 9547 } 9548 9549 return false; 9550} 9551 9552/// Attempt to recover from ill-formed use of a non-dependent operator in a 9553/// template, where the non-dependent operator was declared after the template 9554/// was defined. 9555/// 9556/// Returns true if a viable candidate was found and a diagnostic was issued. 9557static bool 9558DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9559 SourceLocation OpLoc, 9560 llvm::ArrayRef<Expr *> Args) { 9561 DeclarationName OpName = 9562 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9563 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9564 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9565 /*ExplicitTemplateArgs=*/0, Args); 9566} 9567 9568namespace { 9569// Callback to limit the allowed keywords and to only accept typo corrections 9570// that are keywords or whose decls refer to functions (or template functions) 9571// that accept the given number of arguments. 9572class RecoveryCallCCC : public CorrectionCandidateCallback { 9573 public: 9574 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9575 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9576 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9577 WantRemainingKeywords = false; 9578 } 9579 9580 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9581 if (!candidate.getCorrectionDecl()) 9582 return candidate.isKeyword(); 9583 9584 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9585 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9586 FunctionDecl *FD = 0; 9587 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9588 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9589 FD = FTD->getTemplatedDecl(); 9590 if (!HasExplicitTemplateArgs && !FD) { 9591 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9592 // If the Decl is neither a function nor a template function, 9593 // determine if it is a pointer or reference to a function. If so, 9594 // check against the number of arguments expected for the pointee. 9595 QualType ValType = cast<ValueDecl>(ND)->getType(); 9596 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9597 ValType = ValType->getPointeeType(); 9598 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9599 if (FPT->getNumArgs() == NumArgs) 9600 return true; 9601 } 9602 } 9603 if (FD && FD->getNumParams() >= NumArgs && 9604 FD->getMinRequiredArguments() <= NumArgs) 9605 return true; 9606 } 9607 return false; 9608 } 9609 9610 private: 9611 unsigned NumArgs; 9612 bool HasExplicitTemplateArgs; 9613}; 9614 9615// Callback that effectively disabled typo correction 9616class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9617 public: 9618 NoTypoCorrectionCCC() { 9619 WantTypeSpecifiers = false; 9620 WantExpressionKeywords = false; 9621 WantCXXNamedCasts = false; 9622 WantRemainingKeywords = false; 9623 } 9624 9625 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9626 return false; 9627 } 9628}; 9629} 9630 9631/// Attempts to recover from a call where no functions were found. 9632/// 9633/// Returns true if new candidates were found. 9634static ExprResult 9635BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9636 UnresolvedLookupExpr *ULE, 9637 SourceLocation LParenLoc, 9638 llvm::MutableArrayRef<Expr *> Args, 9639 SourceLocation RParenLoc, 9640 bool EmptyLookup, bool AllowTypoCorrection) { 9641 9642 CXXScopeSpec SS; 9643 SS.Adopt(ULE->getQualifierLoc()); 9644 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9645 9646 TemplateArgumentListInfo TABuffer; 9647 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9648 if (ULE->hasExplicitTemplateArgs()) { 9649 ULE->copyTemplateArgumentsInto(TABuffer); 9650 ExplicitTemplateArgs = &TABuffer; 9651 } 9652 9653 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9654 Sema::LookupOrdinaryName); 9655 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9656 NoTypoCorrectionCCC RejectAll; 9657 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9658 (CorrectionCandidateCallback*)&Validator : 9659 (CorrectionCandidateCallback*)&RejectAll; 9660 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9661 ExplicitTemplateArgs, Args) && 9662 (!EmptyLookup || 9663 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9664 ExplicitTemplateArgs, Args))) 9665 return ExprError(); 9666 9667 assert(!R.empty() && "lookup results empty despite recovery"); 9668 9669 // Build an implicit member call if appropriate. Just drop the 9670 // casts and such from the call, we don't really care. 9671 ExprResult NewFn = ExprError(); 9672 if ((*R.begin())->isCXXClassMember()) 9673 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9674 R, ExplicitTemplateArgs); 9675 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9676 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9677 ExplicitTemplateArgs); 9678 else 9679 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9680 9681 if (NewFn.isInvalid()) 9682 return ExprError(); 9683 9684 // This shouldn't cause an infinite loop because we're giving it 9685 // an expression with viable lookup results, which should never 9686 // end up here. 9687 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9688 MultiExprArg(Args.data(), Args.size()), 9689 RParenLoc); 9690} 9691 9692/// \brief Constructs and populates an OverloadedCandidateSet from 9693/// the given function. 9694/// \returns true when an the ExprResult output parameter has been set. 9695bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 9696 UnresolvedLookupExpr *ULE, 9697 Expr **Args, unsigned NumArgs, 9698 SourceLocation RParenLoc, 9699 OverloadCandidateSet *CandidateSet, 9700 ExprResult *Result) { 9701#ifndef NDEBUG 9702 if (ULE->requiresADL()) { 9703 // To do ADL, we must have found an unqualified name. 9704 assert(!ULE->getQualifier() && "qualified name with ADL"); 9705 9706 // We don't perform ADL for implicit declarations of builtins. 9707 // Verify that this was correctly set up. 9708 FunctionDecl *F; 9709 if (ULE->decls_begin() + 1 == ULE->decls_end() && 9710 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 9711 F->getBuiltinID() && F->isImplicit()) 9712 llvm_unreachable("performing ADL for builtin"); 9713 9714 // We don't perform ADL in C. 9715 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 9716 } else 9717 assert(!ULE->isStdAssociatedNamespace() && 9718 "std is associated namespace but not doing ADL"); 9719#endif 9720 9721 UnbridgedCastsSet UnbridgedCasts; 9722 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) { 9723 *Result = ExprError(); 9724 return true; 9725 } 9726 9727 // Add the functions denoted by the callee to the set of candidate 9728 // functions, including those from argument-dependent lookup. 9729 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs), 9730 *CandidateSet); 9731 9732 // If we found nothing, try to recover. 9733 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 9734 // out if it fails. 9735 if (CandidateSet->empty()) { 9736 // In Microsoft mode, if we are inside a template class member function then 9737 // create a type dependent CallExpr. The goal is to postpone name lookup 9738 // to instantiation time to be able to search into type dependent base 9739 // classes. 9740 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 9741 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 9742 CallExpr *CE = new (Context) CallExpr(Context, Fn, 9743 llvm::makeArrayRef(Args, NumArgs), 9744 Context.DependentTy, VK_RValue, 9745 RParenLoc); 9746 CE->setTypeDependent(true); 9747 *Result = Owned(CE); 9748 return true; 9749 } 9750 return false; 9751 } 9752 9753 UnbridgedCasts.restore(); 9754 return false; 9755} 9756 9757/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 9758/// the completed call expression. If overload resolution fails, emits 9759/// diagnostics and returns ExprError() 9760static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9761 UnresolvedLookupExpr *ULE, 9762 SourceLocation LParenLoc, 9763 Expr **Args, unsigned NumArgs, 9764 SourceLocation RParenLoc, 9765 Expr *ExecConfig, 9766 OverloadCandidateSet *CandidateSet, 9767 OverloadCandidateSet::iterator *Best, 9768 OverloadingResult OverloadResult, 9769 bool AllowTypoCorrection) { 9770 if (CandidateSet->empty()) 9771 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9772 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9773 RParenLoc, /*EmptyLookup=*/true, 9774 AllowTypoCorrection); 9775 9776 switch (OverloadResult) { 9777 case OR_Success: { 9778 FunctionDecl *FDecl = (*Best)->Function; 9779 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl); 9780 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 9781 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()); 9782 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9783 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9784 RParenLoc, ExecConfig); 9785 } 9786 9787 case OR_No_Viable_Function: { 9788 // Try to recover by looking for viable functions which the user might 9789 // have meant to call. 9790 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9791 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9792 RParenLoc, 9793 /*EmptyLookup=*/false, 9794 AllowTypoCorrection); 9795 if (!Recovery.isInvalid()) 9796 return Recovery; 9797 9798 SemaRef.Diag(Fn->getLocStart(), 9799 diag::err_ovl_no_viable_function_in_call) 9800 << ULE->getName() << Fn->getSourceRange(); 9801 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9802 llvm::makeArrayRef(Args, NumArgs)); 9803 break; 9804 } 9805 9806 case OR_Ambiguous: 9807 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 9808 << ULE->getName() << Fn->getSourceRange(); 9809 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, 9810 llvm::makeArrayRef(Args, NumArgs)); 9811 break; 9812 9813 case OR_Deleted: { 9814 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 9815 << (*Best)->Function->isDeleted() 9816 << ULE->getName() 9817 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 9818 << Fn->getSourceRange(); 9819 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9820 llvm::makeArrayRef(Args, NumArgs)); 9821 9822 // We emitted an error for the unvailable/deleted function call but keep 9823 // the call in the AST. 9824 FunctionDecl *FDecl = (*Best)->Function; 9825 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9826 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9827 RParenLoc, ExecConfig); 9828 } 9829 } 9830 9831 // Overload resolution failed. 9832 return ExprError(); 9833} 9834 9835/// BuildOverloadedCallExpr - Given the call expression that calls Fn 9836/// (which eventually refers to the declaration Func) and the call 9837/// arguments Args/NumArgs, attempt to resolve the function call down 9838/// to a specific function. If overload resolution succeeds, returns 9839/// the call expression produced by overload resolution. 9840/// Otherwise, emits diagnostics and returns ExprError. 9841ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 9842 UnresolvedLookupExpr *ULE, 9843 SourceLocation LParenLoc, 9844 Expr **Args, unsigned NumArgs, 9845 SourceLocation RParenLoc, 9846 Expr *ExecConfig, 9847 bool AllowTypoCorrection) { 9848 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 9849 ExprResult result; 9850 9851 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc, 9852 &CandidateSet, &result)) 9853 return result; 9854 9855 OverloadCandidateSet::iterator Best; 9856 OverloadingResult OverloadResult = 9857 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 9858 9859 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 9860 RParenLoc, ExecConfig, &CandidateSet, 9861 &Best, OverloadResult, 9862 AllowTypoCorrection); 9863} 9864 9865static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 9866 return Functions.size() > 1 || 9867 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 9868} 9869 9870/// \brief Create a unary operation that may resolve to an overloaded 9871/// operator. 9872/// 9873/// \param OpLoc The location of the operator itself (e.g., '*'). 9874/// 9875/// \param OpcIn The UnaryOperator::Opcode that describes this 9876/// operator. 9877/// 9878/// \param Fns The set of non-member functions that will be 9879/// considered by overload resolution. The caller needs to build this 9880/// set based on the context using, e.g., 9881/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 9882/// set should not contain any member functions; those will be added 9883/// by CreateOverloadedUnaryOp(). 9884/// 9885/// \param Input The input argument. 9886ExprResult 9887Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 9888 const UnresolvedSetImpl &Fns, 9889 Expr *Input) { 9890 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 9891 9892 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 9893 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 9894 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 9895 // TODO: provide better source location info. 9896 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 9897 9898 if (checkPlaceholderForOverload(*this, Input)) 9899 return ExprError(); 9900 9901 Expr *Args[2] = { Input, 0 }; 9902 unsigned NumArgs = 1; 9903 9904 // For post-increment and post-decrement, add the implicit '0' as 9905 // the second argument, so that we know this is a post-increment or 9906 // post-decrement. 9907 if (Opc == UO_PostInc || Opc == UO_PostDec) { 9908 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 9909 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 9910 SourceLocation()); 9911 NumArgs = 2; 9912 } 9913 9914 if (Input->isTypeDependent()) { 9915 if (Fns.empty()) 9916 return Owned(new (Context) UnaryOperator(Input, 9917 Opc, 9918 Context.DependentTy, 9919 VK_RValue, OK_Ordinary, 9920 OpLoc)); 9921 9922 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 9923 UnresolvedLookupExpr *Fn 9924 = UnresolvedLookupExpr::Create(Context, NamingClass, 9925 NestedNameSpecifierLoc(), OpNameInfo, 9926 /*ADL*/ true, IsOverloaded(Fns), 9927 Fns.begin(), Fns.end()); 9928 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 9929 llvm::makeArrayRef(Args, NumArgs), 9930 Context.DependentTy, 9931 VK_RValue, 9932 OpLoc)); 9933 } 9934 9935 // Build an empty overload set. 9936 OverloadCandidateSet CandidateSet(OpLoc); 9937 9938 // Add the candidates from the given function set. 9939 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet, 9940 false); 9941 9942 // Add operator candidates that are member functions. 9943 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 9944 9945 // Add candidates from ADL. 9946 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 9947 OpLoc, llvm::makeArrayRef(Args, NumArgs), 9948 /*ExplicitTemplateArgs*/ 0, 9949 CandidateSet); 9950 9951 // Add builtin operator candidates. 9952 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 9953 9954 bool HadMultipleCandidates = (CandidateSet.size() > 1); 9955 9956 // Perform overload resolution. 9957 OverloadCandidateSet::iterator Best; 9958 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 9959 case OR_Success: { 9960 // We found a built-in operator or an overloaded operator. 9961 FunctionDecl *FnDecl = Best->Function; 9962 9963 if (FnDecl) { 9964 // We matched an overloaded operator. Build a call to that 9965 // operator. 9966 9967 MarkFunctionReferenced(OpLoc, FnDecl); 9968 9969 // Convert the arguments. 9970 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 9971 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 9972 9973 ExprResult InputRes = 9974 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 9975 Best->FoundDecl, Method); 9976 if (InputRes.isInvalid()) 9977 return ExprError(); 9978 Input = InputRes.take(); 9979 } else { 9980 // Convert the arguments. 9981 ExprResult InputInit 9982 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 9983 Context, 9984 FnDecl->getParamDecl(0)), 9985 SourceLocation(), 9986 Input); 9987 if (InputInit.isInvalid()) 9988 return ExprError(); 9989 Input = InputInit.take(); 9990 } 9991 9992 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 9993 9994 // Determine the result type. 9995 QualType ResultTy = FnDecl->getResultType(); 9996 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 9997 ResultTy = ResultTy.getNonLValueExprType(Context); 9998 9999 // Build the actual expression node. 10000 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10001 HadMultipleCandidates, OpLoc); 10002 if (FnExpr.isInvalid()) 10003 return ExprError(); 10004 10005 Args[0] = Input; 10006 CallExpr *TheCall = 10007 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10008 llvm::makeArrayRef(Args, NumArgs), 10009 ResultTy, VK, OpLoc); 10010 10011 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10012 FnDecl)) 10013 return ExprError(); 10014 10015 return MaybeBindToTemporary(TheCall); 10016 } else { 10017 // We matched a built-in operator. Convert the arguments, then 10018 // break out so that we will build the appropriate built-in 10019 // operator node. 10020 ExprResult InputRes = 10021 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10022 Best->Conversions[0], AA_Passing); 10023 if (InputRes.isInvalid()) 10024 return ExprError(); 10025 Input = InputRes.take(); 10026 break; 10027 } 10028 } 10029 10030 case OR_No_Viable_Function: 10031 // This is an erroneous use of an operator which can be overloaded by 10032 // a non-member function. Check for non-member operators which were 10033 // defined too late to be candidates. 10034 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, 10035 llvm::makeArrayRef(Args, NumArgs))) 10036 // FIXME: Recover by calling the found function. 10037 return ExprError(); 10038 10039 // No viable function; fall through to handling this as a 10040 // built-in operator, which will produce an error message for us. 10041 break; 10042 10043 case OR_Ambiguous: 10044 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10045 << UnaryOperator::getOpcodeStr(Opc) 10046 << Input->getType() 10047 << Input->getSourceRange(); 10048 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10049 llvm::makeArrayRef(Args, NumArgs), 10050 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10051 return ExprError(); 10052 10053 case OR_Deleted: 10054 Diag(OpLoc, diag::err_ovl_deleted_oper) 10055 << Best->Function->isDeleted() 10056 << UnaryOperator::getOpcodeStr(Opc) 10057 << getDeletedOrUnavailableSuffix(Best->Function) 10058 << Input->getSourceRange(); 10059 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10060 llvm::makeArrayRef(Args, NumArgs), 10061 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10062 return ExprError(); 10063 } 10064 10065 // Either we found no viable overloaded operator or we matched a 10066 // built-in operator. In either case, fall through to trying to 10067 // build a built-in operation. 10068 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10069} 10070 10071/// \brief Create a binary operation that may resolve to an overloaded 10072/// operator. 10073/// 10074/// \param OpLoc The location of the operator itself (e.g., '+'). 10075/// 10076/// \param OpcIn The BinaryOperator::Opcode that describes this 10077/// operator. 10078/// 10079/// \param Fns The set of non-member functions that will be 10080/// considered by overload resolution. The caller needs to build this 10081/// set based on the context using, e.g., 10082/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10083/// set should not contain any member functions; those will be added 10084/// by CreateOverloadedBinOp(). 10085/// 10086/// \param LHS Left-hand argument. 10087/// \param RHS Right-hand argument. 10088ExprResult 10089Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10090 unsigned OpcIn, 10091 const UnresolvedSetImpl &Fns, 10092 Expr *LHS, Expr *RHS) { 10093 Expr *Args[2] = { LHS, RHS }; 10094 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10095 10096 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10097 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10098 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10099 10100 // If either side is type-dependent, create an appropriate dependent 10101 // expression. 10102 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10103 if (Fns.empty()) { 10104 // If there are no functions to store, just build a dependent 10105 // BinaryOperator or CompoundAssignment. 10106 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10107 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10108 Context.DependentTy, 10109 VK_RValue, OK_Ordinary, 10110 OpLoc)); 10111 10112 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10113 Context.DependentTy, 10114 VK_LValue, 10115 OK_Ordinary, 10116 Context.DependentTy, 10117 Context.DependentTy, 10118 OpLoc)); 10119 } 10120 10121 // FIXME: save results of ADL from here? 10122 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10123 // TODO: provide better source location info in DNLoc component. 10124 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10125 UnresolvedLookupExpr *Fn 10126 = UnresolvedLookupExpr::Create(Context, NamingClass, 10127 NestedNameSpecifierLoc(), OpNameInfo, 10128 /*ADL*/ true, IsOverloaded(Fns), 10129 Fns.begin(), Fns.end()); 10130 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 10131 Args, 10132 Context.DependentTy, 10133 VK_RValue, 10134 OpLoc)); 10135 } 10136 10137 // Always do placeholder-like conversions on the RHS. 10138 if (checkPlaceholderForOverload(*this, Args[1])) 10139 return ExprError(); 10140 10141 // Do placeholder-like conversion on the LHS; note that we should 10142 // not get here with a PseudoObject LHS. 10143 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10144 if (checkPlaceholderForOverload(*this, Args[0])) 10145 return ExprError(); 10146 10147 // If this is the assignment operator, we only perform overload resolution 10148 // if the left-hand side is a class or enumeration type. This is actually 10149 // a hack. The standard requires that we do overload resolution between the 10150 // various built-in candidates, but as DR507 points out, this can lead to 10151 // problems. So we do it this way, which pretty much follows what GCC does. 10152 // Note that we go the traditional code path for compound assignment forms. 10153 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10154 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10155 10156 // If this is the .* operator, which is not overloadable, just 10157 // create a built-in binary operator. 10158 if (Opc == BO_PtrMemD) 10159 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10160 10161 // Build an empty overload set. 10162 OverloadCandidateSet CandidateSet(OpLoc); 10163 10164 // Add the candidates from the given function set. 10165 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10166 10167 // Add operator candidates that are member functions. 10168 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10169 10170 // Add candidates from ADL. 10171 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10172 OpLoc, Args, 10173 /*ExplicitTemplateArgs*/ 0, 10174 CandidateSet); 10175 10176 // Add builtin operator candidates. 10177 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10178 10179 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10180 10181 // Perform overload resolution. 10182 OverloadCandidateSet::iterator Best; 10183 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10184 case OR_Success: { 10185 // We found a built-in operator or an overloaded operator. 10186 FunctionDecl *FnDecl = Best->Function; 10187 10188 if (FnDecl) { 10189 // We matched an overloaded operator. Build a call to that 10190 // operator. 10191 10192 MarkFunctionReferenced(OpLoc, FnDecl); 10193 10194 // Convert the arguments. 10195 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10196 // Best->Access is only meaningful for class members. 10197 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10198 10199 ExprResult Arg1 = 10200 PerformCopyInitialization( 10201 InitializedEntity::InitializeParameter(Context, 10202 FnDecl->getParamDecl(0)), 10203 SourceLocation(), Owned(Args[1])); 10204 if (Arg1.isInvalid()) 10205 return ExprError(); 10206 10207 ExprResult Arg0 = 10208 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10209 Best->FoundDecl, Method); 10210 if (Arg0.isInvalid()) 10211 return ExprError(); 10212 Args[0] = Arg0.takeAs<Expr>(); 10213 Args[1] = RHS = Arg1.takeAs<Expr>(); 10214 } else { 10215 // Convert the arguments. 10216 ExprResult Arg0 = PerformCopyInitialization( 10217 InitializedEntity::InitializeParameter(Context, 10218 FnDecl->getParamDecl(0)), 10219 SourceLocation(), Owned(Args[0])); 10220 if (Arg0.isInvalid()) 10221 return ExprError(); 10222 10223 ExprResult Arg1 = 10224 PerformCopyInitialization( 10225 InitializedEntity::InitializeParameter(Context, 10226 FnDecl->getParamDecl(1)), 10227 SourceLocation(), Owned(Args[1])); 10228 if (Arg1.isInvalid()) 10229 return ExprError(); 10230 Args[0] = LHS = Arg0.takeAs<Expr>(); 10231 Args[1] = RHS = Arg1.takeAs<Expr>(); 10232 } 10233 10234 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10235 10236 // Determine the result type. 10237 QualType ResultTy = FnDecl->getResultType(); 10238 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10239 ResultTy = ResultTy.getNonLValueExprType(Context); 10240 10241 // Build the actual expression node. 10242 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10243 HadMultipleCandidates, OpLoc); 10244 if (FnExpr.isInvalid()) 10245 return ExprError(); 10246 10247 CXXOperatorCallExpr *TheCall = 10248 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10249 Args, ResultTy, VK, OpLoc); 10250 10251 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10252 FnDecl)) 10253 return ExprError(); 10254 10255 return MaybeBindToTemporary(TheCall); 10256 } else { 10257 // We matched a built-in operator. Convert the arguments, then 10258 // break out so that we will build the appropriate built-in 10259 // operator node. 10260 ExprResult ArgsRes0 = 10261 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10262 Best->Conversions[0], AA_Passing); 10263 if (ArgsRes0.isInvalid()) 10264 return ExprError(); 10265 Args[0] = ArgsRes0.take(); 10266 10267 ExprResult ArgsRes1 = 10268 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10269 Best->Conversions[1], AA_Passing); 10270 if (ArgsRes1.isInvalid()) 10271 return ExprError(); 10272 Args[1] = ArgsRes1.take(); 10273 break; 10274 } 10275 } 10276 10277 case OR_No_Viable_Function: { 10278 // C++ [over.match.oper]p9: 10279 // If the operator is the operator , [...] and there are no 10280 // viable functions, then the operator is assumed to be the 10281 // built-in operator and interpreted according to clause 5. 10282 if (Opc == BO_Comma) 10283 break; 10284 10285 // For class as left operand for assignment or compound assigment 10286 // operator do not fall through to handling in built-in, but report that 10287 // no overloaded assignment operator found 10288 ExprResult Result = ExprError(); 10289 if (Args[0]->getType()->isRecordType() && 10290 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10291 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10292 << BinaryOperator::getOpcodeStr(Opc) 10293 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10294 } else { 10295 // This is an erroneous use of an operator which can be overloaded by 10296 // a non-member function. Check for non-member operators which were 10297 // defined too late to be candidates. 10298 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10299 // FIXME: Recover by calling the found function. 10300 return ExprError(); 10301 10302 // No viable function; try to create a built-in operation, which will 10303 // produce an error. Then, show the non-viable candidates. 10304 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10305 } 10306 assert(Result.isInvalid() && 10307 "C++ binary operator overloading is missing candidates!"); 10308 if (Result.isInvalid()) 10309 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10310 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10311 return Result; 10312 } 10313 10314 case OR_Ambiguous: 10315 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10316 << BinaryOperator::getOpcodeStr(Opc) 10317 << Args[0]->getType() << Args[1]->getType() 10318 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10319 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10320 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10321 return ExprError(); 10322 10323 case OR_Deleted: 10324 if (isImplicitlyDeleted(Best->Function)) { 10325 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10326 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10327 << getSpecialMember(Method) 10328 << BinaryOperator::getOpcodeStr(Opc) 10329 << getDeletedOrUnavailableSuffix(Best->Function); 10330 10331 if (getSpecialMember(Method) != CXXInvalid) { 10332 // The user probably meant to call this special member. Just 10333 // explain why it's deleted. 10334 NoteDeletedFunction(Method); 10335 return ExprError(); 10336 } 10337 } else { 10338 Diag(OpLoc, diag::err_ovl_deleted_oper) 10339 << Best->Function->isDeleted() 10340 << BinaryOperator::getOpcodeStr(Opc) 10341 << getDeletedOrUnavailableSuffix(Best->Function) 10342 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10343 } 10344 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10345 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10346 return ExprError(); 10347 } 10348 10349 // We matched a built-in operator; build it. 10350 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10351} 10352 10353ExprResult 10354Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10355 SourceLocation RLoc, 10356 Expr *Base, Expr *Idx) { 10357 Expr *Args[2] = { Base, Idx }; 10358 DeclarationName OpName = 10359 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10360 10361 // If either side is type-dependent, create an appropriate dependent 10362 // expression. 10363 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10364 10365 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10366 // CHECKME: no 'operator' keyword? 10367 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10368 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10369 UnresolvedLookupExpr *Fn 10370 = UnresolvedLookupExpr::Create(Context, NamingClass, 10371 NestedNameSpecifierLoc(), OpNameInfo, 10372 /*ADL*/ true, /*Overloaded*/ false, 10373 UnresolvedSetIterator(), 10374 UnresolvedSetIterator()); 10375 // Can't add any actual overloads yet 10376 10377 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10378 Args, 10379 Context.DependentTy, 10380 VK_RValue, 10381 RLoc)); 10382 } 10383 10384 // Handle placeholders on both operands. 10385 if (checkPlaceholderForOverload(*this, Args[0])) 10386 return ExprError(); 10387 if (checkPlaceholderForOverload(*this, Args[1])) 10388 return ExprError(); 10389 10390 // Build an empty overload set. 10391 OverloadCandidateSet CandidateSet(LLoc); 10392 10393 // Subscript can only be overloaded as a member function. 10394 10395 // Add operator candidates that are member functions. 10396 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10397 10398 // Add builtin operator candidates. 10399 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10400 10401 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10402 10403 // Perform overload resolution. 10404 OverloadCandidateSet::iterator Best; 10405 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10406 case OR_Success: { 10407 // We found a built-in operator or an overloaded operator. 10408 FunctionDecl *FnDecl = Best->Function; 10409 10410 if (FnDecl) { 10411 // We matched an overloaded operator. Build a call to that 10412 // operator. 10413 10414 MarkFunctionReferenced(LLoc, FnDecl); 10415 10416 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10417 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 10418 10419 // Convert the arguments. 10420 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10421 ExprResult Arg0 = 10422 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10423 Best->FoundDecl, Method); 10424 if (Arg0.isInvalid()) 10425 return ExprError(); 10426 Args[0] = Arg0.take(); 10427 10428 // Convert the arguments. 10429 ExprResult InputInit 10430 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10431 Context, 10432 FnDecl->getParamDecl(0)), 10433 SourceLocation(), 10434 Owned(Args[1])); 10435 if (InputInit.isInvalid()) 10436 return ExprError(); 10437 10438 Args[1] = InputInit.takeAs<Expr>(); 10439 10440 // Determine the result type 10441 QualType ResultTy = FnDecl->getResultType(); 10442 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10443 ResultTy = ResultTy.getNonLValueExprType(Context); 10444 10445 // Build the actual expression node. 10446 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10447 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10448 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10449 HadMultipleCandidates, 10450 OpLocInfo.getLoc(), 10451 OpLocInfo.getInfo()); 10452 if (FnExpr.isInvalid()) 10453 return ExprError(); 10454 10455 CXXOperatorCallExpr *TheCall = 10456 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10457 FnExpr.take(), Args, 10458 ResultTy, VK, RLoc); 10459 10460 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10461 FnDecl)) 10462 return ExprError(); 10463 10464 return MaybeBindToTemporary(TheCall); 10465 } else { 10466 // We matched a built-in operator. Convert the arguments, then 10467 // break out so that we will build the appropriate built-in 10468 // operator node. 10469 ExprResult ArgsRes0 = 10470 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10471 Best->Conversions[0], AA_Passing); 10472 if (ArgsRes0.isInvalid()) 10473 return ExprError(); 10474 Args[0] = ArgsRes0.take(); 10475 10476 ExprResult ArgsRes1 = 10477 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10478 Best->Conversions[1], AA_Passing); 10479 if (ArgsRes1.isInvalid()) 10480 return ExprError(); 10481 Args[1] = ArgsRes1.take(); 10482 10483 break; 10484 } 10485 } 10486 10487 case OR_No_Viable_Function: { 10488 if (CandidateSet.empty()) 10489 Diag(LLoc, diag::err_ovl_no_oper) 10490 << Args[0]->getType() << /*subscript*/ 0 10491 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10492 else 10493 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10494 << Args[0]->getType() 10495 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10496 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10497 "[]", LLoc); 10498 return ExprError(); 10499 } 10500 10501 case OR_Ambiguous: 10502 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10503 << "[]" 10504 << Args[0]->getType() << Args[1]->getType() 10505 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10506 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10507 "[]", LLoc); 10508 return ExprError(); 10509 10510 case OR_Deleted: 10511 Diag(LLoc, diag::err_ovl_deleted_oper) 10512 << Best->Function->isDeleted() << "[]" 10513 << getDeletedOrUnavailableSuffix(Best->Function) 10514 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10515 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10516 "[]", LLoc); 10517 return ExprError(); 10518 } 10519 10520 // We matched a built-in operator; build it. 10521 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10522} 10523 10524/// BuildCallToMemberFunction - Build a call to a member 10525/// function. MemExpr is the expression that refers to the member 10526/// function (and includes the object parameter), Args/NumArgs are the 10527/// arguments to the function call (not including the object 10528/// parameter). The caller needs to validate that the member 10529/// expression refers to a non-static member function or an overloaded 10530/// member function. 10531ExprResult 10532Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10533 SourceLocation LParenLoc, Expr **Args, 10534 unsigned NumArgs, SourceLocation RParenLoc) { 10535 assert(MemExprE->getType() == Context.BoundMemberTy || 10536 MemExprE->getType() == Context.OverloadTy); 10537 10538 // Dig out the member expression. This holds both the object 10539 // argument and the member function we're referring to. 10540 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10541 10542 // Determine whether this is a call to a pointer-to-member function. 10543 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10544 assert(op->getType() == Context.BoundMemberTy); 10545 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10546 10547 QualType fnType = 10548 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10549 10550 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10551 QualType resultType = proto->getCallResultType(Context); 10552 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10553 10554 // Check that the object type isn't more qualified than the 10555 // member function we're calling. 10556 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10557 10558 QualType objectType = op->getLHS()->getType(); 10559 if (op->getOpcode() == BO_PtrMemI) 10560 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10561 Qualifiers objectQuals = objectType.getQualifiers(); 10562 10563 Qualifiers difference = objectQuals - funcQuals; 10564 difference.removeObjCGCAttr(); 10565 difference.removeAddressSpace(); 10566 if (difference) { 10567 std::string qualsString = difference.getAsString(); 10568 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10569 << fnType.getUnqualifiedType() 10570 << qualsString 10571 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10572 } 10573 10574 CXXMemberCallExpr *call 10575 = new (Context) CXXMemberCallExpr(Context, MemExprE, 10576 llvm::makeArrayRef(Args, NumArgs), 10577 resultType, valueKind, RParenLoc); 10578 10579 if (CheckCallReturnType(proto->getResultType(), 10580 op->getRHS()->getLocStart(), 10581 call, 0)) 10582 return ExprError(); 10583 10584 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 10585 return ExprError(); 10586 10587 return MaybeBindToTemporary(call); 10588 } 10589 10590 UnbridgedCastsSet UnbridgedCasts; 10591 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10592 return ExprError(); 10593 10594 MemberExpr *MemExpr; 10595 CXXMethodDecl *Method = 0; 10596 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10597 NestedNameSpecifier *Qualifier = 0; 10598 if (isa<MemberExpr>(NakedMemExpr)) { 10599 MemExpr = cast<MemberExpr>(NakedMemExpr); 10600 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10601 FoundDecl = MemExpr->getFoundDecl(); 10602 Qualifier = MemExpr->getQualifier(); 10603 UnbridgedCasts.restore(); 10604 } else { 10605 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10606 Qualifier = UnresExpr->getQualifier(); 10607 10608 QualType ObjectType = UnresExpr->getBaseType(); 10609 Expr::Classification ObjectClassification 10610 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10611 : UnresExpr->getBase()->Classify(Context); 10612 10613 // Add overload candidates 10614 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10615 10616 // FIXME: avoid copy. 10617 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10618 if (UnresExpr->hasExplicitTemplateArgs()) { 10619 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10620 TemplateArgs = &TemplateArgsBuffer; 10621 } 10622 10623 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10624 E = UnresExpr->decls_end(); I != E; ++I) { 10625 10626 NamedDecl *Func = *I; 10627 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10628 if (isa<UsingShadowDecl>(Func)) 10629 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10630 10631 10632 // Microsoft supports direct constructor calls. 10633 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10634 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10635 llvm::makeArrayRef(Args, NumArgs), CandidateSet); 10636 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10637 // If explicit template arguments were provided, we can't call a 10638 // non-template member function. 10639 if (TemplateArgs) 10640 continue; 10641 10642 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10643 ObjectClassification, 10644 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10645 /*SuppressUserConversions=*/false); 10646 } else { 10647 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10648 I.getPair(), ActingDC, TemplateArgs, 10649 ObjectType, ObjectClassification, 10650 llvm::makeArrayRef(Args, NumArgs), 10651 CandidateSet, 10652 /*SuppressUsedConversions=*/false); 10653 } 10654 } 10655 10656 DeclarationName DeclName = UnresExpr->getMemberName(); 10657 10658 UnbridgedCasts.restore(); 10659 10660 OverloadCandidateSet::iterator Best; 10661 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10662 Best)) { 10663 case OR_Success: 10664 Method = cast<CXXMethodDecl>(Best->Function); 10665 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method); 10666 FoundDecl = Best->FoundDecl; 10667 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10668 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 10669 break; 10670 10671 case OR_No_Viable_Function: 10672 Diag(UnresExpr->getMemberLoc(), 10673 diag::err_ovl_no_viable_member_function_in_call) 10674 << DeclName << MemExprE->getSourceRange(); 10675 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10676 llvm::makeArrayRef(Args, NumArgs)); 10677 // FIXME: Leaking incoming expressions! 10678 return ExprError(); 10679 10680 case OR_Ambiguous: 10681 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10682 << DeclName << MemExprE->getSourceRange(); 10683 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10684 llvm::makeArrayRef(Args, NumArgs)); 10685 // FIXME: Leaking incoming expressions! 10686 return ExprError(); 10687 10688 case OR_Deleted: 10689 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10690 << Best->Function->isDeleted() 10691 << DeclName 10692 << getDeletedOrUnavailableSuffix(Best->Function) 10693 << MemExprE->getSourceRange(); 10694 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10695 llvm::makeArrayRef(Args, NumArgs)); 10696 // FIXME: Leaking incoming expressions! 10697 return ExprError(); 10698 } 10699 10700 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 10701 10702 // If overload resolution picked a static member, build a 10703 // non-member call based on that function. 10704 if (Method->isStatic()) { 10705 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 10706 Args, NumArgs, RParenLoc); 10707 } 10708 10709 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 10710 } 10711 10712 QualType ResultType = Method->getResultType(); 10713 ExprValueKind VK = Expr::getValueKindForType(ResultType); 10714 ResultType = ResultType.getNonLValueExprType(Context); 10715 10716 assert(Method && "Member call to something that isn't a method?"); 10717 CXXMemberCallExpr *TheCall = 10718 new (Context) CXXMemberCallExpr(Context, MemExprE, 10719 llvm::makeArrayRef(Args, NumArgs), 10720 ResultType, VK, RParenLoc); 10721 10722 // Check for a valid return type. 10723 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 10724 TheCall, Method)) 10725 return ExprError(); 10726 10727 // Convert the object argument (for a non-static member function call). 10728 // We only need to do this if there was actually an overload; otherwise 10729 // it was done at lookup. 10730 if (!Method->isStatic()) { 10731 ExprResult ObjectArg = 10732 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 10733 FoundDecl, Method); 10734 if (ObjectArg.isInvalid()) 10735 return ExprError(); 10736 MemExpr->setBase(ObjectArg.take()); 10737 } 10738 10739 // Convert the rest of the arguments 10740 const FunctionProtoType *Proto = 10741 Method->getType()->getAs<FunctionProtoType>(); 10742 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 10743 RParenLoc)) 10744 return ExprError(); 10745 10746 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 10747 10748 if (CheckFunctionCall(Method, TheCall, Proto)) 10749 return ExprError(); 10750 10751 if ((isa<CXXConstructorDecl>(CurContext) || 10752 isa<CXXDestructorDecl>(CurContext)) && 10753 TheCall->getMethodDecl()->isPure()) { 10754 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 10755 10756 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 10757 Diag(MemExpr->getLocStart(), 10758 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 10759 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 10760 << MD->getParent()->getDeclName(); 10761 10762 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 10763 } 10764 } 10765 return MaybeBindToTemporary(TheCall); 10766} 10767 10768/// BuildCallToObjectOfClassType - Build a call to an object of class 10769/// type (C++ [over.call.object]), which can end up invoking an 10770/// overloaded function call operator (@c operator()) or performing a 10771/// user-defined conversion on the object argument. 10772ExprResult 10773Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 10774 SourceLocation LParenLoc, 10775 Expr **Args, unsigned NumArgs, 10776 SourceLocation RParenLoc) { 10777 if (checkPlaceholderForOverload(*this, Obj)) 10778 return ExprError(); 10779 ExprResult Object = Owned(Obj); 10780 10781 UnbridgedCastsSet UnbridgedCasts; 10782 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10783 return ExprError(); 10784 10785 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 10786 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 10787 10788 // C++ [over.call.object]p1: 10789 // If the primary-expression E in the function call syntax 10790 // evaluates to a class object of type "cv T", then the set of 10791 // candidate functions includes at least the function call 10792 // operators of T. The function call operators of T are obtained by 10793 // ordinary lookup of the name operator() in the context of 10794 // (E).operator(). 10795 OverloadCandidateSet CandidateSet(LParenLoc); 10796 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 10797 10798 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 10799 diag::err_incomplete_object_call, Object.get())) 10800 return true; 10801 10802 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 10803 LookupQualifiedName(R, Record->getDecl()); 10804 R.suppressDiagnostics(); 10805 10806 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 10807 Oper != OperEnd; ++Oper) { 10808 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 10809 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 10810 /*SuppressUserConversions=*/ false); 10811 } 10812 10813 // C++ [over.call.object]p2: 10814 // In addition, for each (non-explicit in C++0x) conversion function 10815 // declared in T of the form 10816 // 10817 // operator conversion-type-id () cv-qualifier; 10818 // 10819 // where cv-qualifier is the same cv-qualification as, or a 10820 // greater cv-qualification than, cv, and where conversion-type-id 10821 // denotes the type "pointer to function of (P1,...,Pn) returning 10822 // R", or the type "reference to pointer to function of 10823 // (P1,...,Pn) returning R", or the type "reference to function 10824 // of (P1,...,Pn) returning R", a surrogate call function [...] 10825 // is also considered as a candidate function. Similarly, 10826 // surrogate call functions are added to the set of candidate 10827 // functions for each conversion function declared in an 10828 // accessible base class provided the function is not hidden 10829 // within T by another intervening declaration. 10830 const UnresolvedSetImpl *Conversions 10831 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 10832 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 10833 E = Conversions->end(); I != E; ++I) { 10834 NamedDecl *D = *I; 10835 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 10836 if (isa<UsingShadowDecl>(D)) 10837 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 10838 10839 // Skip over templated conversion functions; they aren't 10840 // surrogates. 10841 if (isa<FunctionTemplateDecl>(D)) 10842 continue; 10843 10844 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 10845 if (!Conv->isExplicit()) { 10846 // Strip the reference type (if any) and then the pointer type (if 10847 // any) to get down to what might be a function type. 10848 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 10849 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10850 ConvType = ConvPtrType->getPointeeType(); 10851 10852 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 10853 { 10854 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 10855 Object.get(), llvm::makeArrayRef(Args, NumArgs), 10856 CandidateSet); 10857 } 10858 } 10859 } 10860 10861 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10862 10863 // Perform overload resolution. 10864 OverloadCandidateSet::iterator Best; 10865 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 10866 Best)) { 10867 case OR_Success: 10868 // Overload resolution succeeded; we'll build the appropriate call 10869 // below. 10870 break; 10871 10872 case OR_No_Viable_Function: 10873 if (CandidateSet.empty()) 10874 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 10875 << Object.get()->getType() << /*call*/ 1 10876 << Object.get()->getSourceRange(); 10877 else 10878 Diag(Object.get()->getLocStart(), 10879 diag::err_ovl_no_viable_object_call) 10880 << Object.get()->getType() << Object.get()->getSourceRange(); 10881 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10882 llvm::makeArrayRef(Args, NumArgs)); 10883 break; 10884 10885 case OR_Ambiguous: 10886 Diag(Object.get()->getLocStart(), 10887 diag::err_ovl_ambiguous_object_call) 10888 << Object.get()->getType() << Object.get()->getSourceRange(); 10889 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10890 llvm::makeArrayRef(Args, NumArgs)); 10891 break; 10892 10893 case OR_Deleted: 10894 Diag(Object.get()->getLocStart(), 10895 diag::err_ovl_deleted_object_call) 10896 << Best->Function->isDeleted() 10897 << Object.get()->getType() 10898 << getDeletedOrUnavailableSuffix(Best->Function) 10899 << Object.get()->getSourceRange(); 10900 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10901 llvm::makeArrayRef(Args, NumArgs)); 10902 break; 10903 } 10904 10905 if (Best == CandidateSet.end()) 10906 return true; 10907 10908 UnbridgedCasts.restore(); 10909 10910 if (Best->Function == 0) { 10911 // Since there is no function declaration, this is one of the 10912 // surrogate candidates. Dig out the conversion function. 10913 CXXConversionDecl *Conv 10914 = cast<CXXConversionDecl>( 10915 Best->Conversions[0].UserDefined.ConversionFunction); 10916 10917 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10918 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10919 10920 // We selected one of the surrogate functions that converts the 10921 // object parameter to a function pointer. Perform the conversion 10922 // on the object argument, then let ActOnCallExpr finish the job. 10923 10924 // Create an implicit member expr to refer to the conversion operator. 10925 // and then call it. 10926 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 10927 Conv, HadMultipleCandidates); 10928 if (Call.isInvalid()) 10929 return ExprError(); 10930 // Record usage of conversion in an implicit cast. 10931 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 10932 CK_UserDefinedConversion, 10933 Call.get(), 0, VK_RValue)); 10934 10935 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 10936 RParenLoc); 10937 } 10938 10939 MarkFunctionReferenced(LParenLoc, Best->Function); 10940 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10941 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10942 10943 // We found an overloaded operator(). Build a CXXOperatorCallExpr 10944 // that calls this method, using Object for the implicit object 10945 // parameter and passing along the remaining arguments. 10946 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10947 const FunctionProtoType *Proto = 10948 Method->getType()->getAs<FunctionProtoType>(); 10949 10950 unsigned NumArgsInProto = Proto->getNumArgs(); 10951 unsigned NumArgsToCheck = NumArgs; 10952 10953 // Build the full argument list for the method call (the 10954 // implicit object parameter is placed at the beginning of the 10955 // list). 10956 Expr **MethodArgs; 10957 if (NumArgs < NumArgsInProto) { 10958 NumArgsToCheck = NumArgsInProto; 10959 MethodArgs = new Expr*[NumArgsInProto + 1]; 10960 } else { 10961 MethodArgs = new Expr*[NumArgs + 1]; 10962 } 10963 MethodArgs[0] = Object.get(); 10964 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 10965 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 10966 10967 DeclarationNameInfo OpLocInfo( 10968 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 10969 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 10970 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, 10971 HadMultipleCandidates, 10972 OpLocInfo.getLoc(), 10973 OpLocInfo.getInfo()); 10974 if (NewFn.isInvalid()) 10975 return true; 10976 10977 // Once we've built TheCall, all of the expressions are properly 10978 // owned. 10979 QualType ResultTy = Method->getResultType(); 10980 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10981 ResultTy = ResultTy.getNonLValueExprType(Context); 10982 10983 CXXOperatorCallExpr *TheCall = 10984 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 10985 llvm::makeArrayRef(MethodArgs, NumArgs+1), 10986 ResultTy, VK, RParenLoc); 10987 delete [] MethodArgs; 10988 10989 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 10990 Method)) 10991 return true; 10992 10993 // We may have default arguments. If so, we need to allocate more 10994 // slots in the call for them. 10995 if (NumArgs < NumArgsInProto) 10996 TheCall->setNumArgs(Context, NumArgsInProto + 1); 10997 else if (NumArgs > NumArgsInProto) 10998 NumArgsToCheck = NumArgsInProto; 10999 11000 bool IsError = false; 11001 11002 // Initialize the implicit object parameter. 11003 ExprResult ObjRes = 11004 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11005 Best->FoundDecl, Method); 11006 if (ObjRes.isInvalid()) 11007 IsError = true; 11008 else 11009 Object = ObjRes; 11010 TheCall->setArg(0, Object.take()); 11011 11012 // Check the argument types. 11013 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11014 Expr *Arg; 11015 if (i < NumArgs) { 11016 Arg = Args[i]; 11017 11018 // Pass the argument. 11019 11020 ExprResult InputInit 11021 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11022 Context, 11023 Method->getParamDecl(i)), 11024 SourceLocation(), Arg); 11025 11026 IsError |= InputInit.isInvalid(); 11027 Arg = InputInit.takeAs<Expr>(); 11028 } else { 11029 ExprResult DefArg 11030 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11031 if (DefArg.isInvalid()) { 11032 IsError = true; 11033 break; 11034 } 11035 11036 Arg = DefArg.takeAs<Expr>(); 11037 } 11038 11039 TheCall->setArg(i + 1, Arg); 11040 } 11041 11042 // If this is a variadic call, handle args passed through "...". 11043 if (Proto->isVariadic()) { 11044 // Promote the arguments (C99 6.5.2.2p7). 11045 for (unsigned i = NumArgsInProto; i < NumArgs; i++) { 11046 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11047 IsError |= Arg.isInvalid(); 11048 TheCall->setArg(i + 1, Arg.take()); 11049 } 11050 } 11051 11052 if (IsError) return true; 11053 11054 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 11055 11056 if (CheckFunctionCall(Method, TheCall, Proto)) 11057 return true; 11058 11059 return MaybeBindToTemporary(TheCall); 11060} 11061 11062/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11063/// (if one exists), where @c Base is an expression of class type and 11064/// @c Member is the name of the member we're trying to find. 11065ExprResult 11066Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11067 assert(Base->getType()->isRecordType() && 11068 "left-hand side must have class type"); 11069 11070 if (checkPlaceholderForOverload(*this, Base)) 11071 return ExprError(); 11072 11073 SourceLocation Loc = Base->getExprLoc(); 11074 11075 // C++ [over.ref]p1: 11076 // 11077 // [...] An expression x->m is interpreted as (x.operator->())->m 11078 // for a class object x of type T if T::operator->() exists and if 11079 // the operator is selected as the best match function by the 11080 // overload resolution mechanism (13.3). 11081 DeclarationName OpName = 11082 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11083 OverloadCandidateSet CandidateSet(Loc); 11084 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11085 11086 if (RequireCompleteType(Loc, Base->getType(), 11087 diag::err_typecheck_incomplete_tag, Base)) 11088 return ExprError(); 11089 11090 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11091 LookupQualifiedName(R, BaseRecord->getDecl()); 11092 R.suppressDiagnostics(); 11093 11094 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11095 Oper != OperEnd; ++Oper) { 11096 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11097 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 11098 } 11099 11100 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11101 11102 // Perform overload resolution. 11103 OverloadCandidateSet::iterator Best; 11104 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11105 case OR_Success: 11106 // Overload resolution succeeded; we'll build the call below. 11107 break; 11108 11109 case OR_No_Viable_Function: 11110 if (CandidateSet.empty()) 11111 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11112 << Base->getType() << Base->getSourceRange(); 11113 else 11114 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11115 << "operator->" << Base->getSourceRange(); 11116 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11117 return ExprError(); 11118 11119 case OR_Ambiguous: 11120 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11121 << "->" << Base->getType() << Base->getSourceRange(); 11122 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11123 return ExprError(); 11124 11125 case OR_Deleted: 11126 Diag(OpLoc, diag::err_ovl_deleted_oper) 11127 << Best->Function->isDeleted() 11128 << "->" 11129 << getDeletedOrUnavailableSuffix(Best->Function) 11130 << Base->getSourceRange(); 11131 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11132 return ExprError(); 11133 } 11134 11135 MarkFunctionReferenced(OpLoc, Best->Function); 11136 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11137 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 11138 11139 // Convert the object parameter. 11140 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11141 ExprResult BaseResult = 11142 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11143 Best->FoundDecl, Method); 11144 if (BaseResult.isInvalid()) 11145 return ExprError(); 11146 Base = BaseResult.take(); 11147 11148 // Build the operator call. 11149 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, 11150 HadMultipleCandidates, OpLoc); 11151 if (FnExpr.isInvalid()) 11152 return ExprError(); 11153 11154 QualType ResultTy = Method->getResultType(); 11155 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11156 ResultTy = ResultTy.getNonLValueExprType(Context); 11157 CXXOperatorCallExpr *TheCall = 11158 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11159 Base, ResultTy, VK, OpLoc); 11160 11161 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11162 Method)) 11163 return ExprError(); 11164 11165 return MaybeBindToTemporary(TheCall); 11166} 11167 11168/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11169/// a literal operator described by the provided lookup results. 11170ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11171 DeclarationNameInfo &SuffixInfo, 11172 ArrayRef<Expr*> Args, 11173 SourceLocation LitEndLoc, 11174 TemplateArgumentListInfo *TemplateArgs) { 11175 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11176 11177 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11178 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11179 TemplateArgs); 11180 11181 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11182 11183 // Perform overload resolution. This will usually be trivial, but might need 11184 // to perform substitutions for a literal operator template. 11185 OverloadCandidateSet::iterator Best; 11186 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11187 case OR_Success: 11188 case OR_Deleted: 11189 break; 11190 11191 case OR_No_Viable_Function: 11192 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11193 << R.getLookupName(); 11194 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11195 return ExprError(); 11196 11197 case OR_Ambiguous: 11198 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11199 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11200 return ExprError(); 11201 } 11202 11203 FunctionDecl *FD = Best->Function; 11204 MarkFunctionReferenced(UDSuffixLoc, FD); 11205 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc); 11206 11207 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates, 11208 SuffixInfo.getLoc(), 11209 SuffixInfo.getInfo()); 11210 if (Fn.isInvalid()) 11211 return true; 11212 11213 // Check the argument types. This should almost always be a no-op, except 11214 // that array-to-pointer decay is applied to string literals. 11215 Expr *ConvArgs[2]; 11216 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 11217 ExprResult InputInit = PerformCopyInitialization( 11218 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11219 SourceLocation(), Args[ArgIdx]); 11220 if (InputInit.isInvalid()) 11221 return true; 11222 ConvArgs[ArgIdx] = InputInit.take(); 11223 } 11224 11225 QualType ResultTy = FD->getResultType(); 11226 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11227 ResultTy = ResultTy.getNonLValueExprType(Context); 11228 11229 UserDefinedLiteral *UDL = 11230 new (Context) UserDefinedLiteral(Context, Fn.take(), 11231 llvm::makeArrayRef(ConvArgs, Args.size()), 11232 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11233 11234 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11235 return ExprError(); 11236 11237 if (CheckFunctionCall(FD, UDL, NULL)) 11238 return ExprError(); 11239 11240 return MaybeBindToTemporary(UDL); 11241} 11242 11243/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11244/// given LookupResult is non-empty, it is assumed to describe a member which 11245/// will be invoked. Otherwise, the function will be found via argument 11246/// dependent lookup. 11247/// CallExpr is set to a valid expression and FRS_Success returned on success, 11248/// otherwise CallExpr is set to ExprError() and some non-success value 11249/// is returned. 11250Sema::ForRangeStatus 11251Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11252 SourceLocation RangeLoc, VarDecl *Decl, 11253 BeginEndFunction BEF, 11254 const DeclarationNameInfo &NameInfo, 11255 LookupResult &MemberLookup, 11256 OverloadCandidateSet *CandidateSet, 11257 Expr *Range, ExprResult *CallExpr) { 11258 CandidateSet->clear(); 11259 if (!MemberLookup.empty()) { 11260 ExprResult MemberRef = 11261 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11262 /*IsPtr=*/false, CXXScopeSpec(), 11263 /*TemplateKWLoc=*/SourceLocation(), 11264 /*FirstQualifierInScope=*/0, 11265 MemberLookup, 11266 /*TemplateArgs=*/0); 11267 if (MemberRef.isInvalid()) { 11268 *CallExpr = ExprError(); 11269 Diag(Range->getLocStart(), diag::note_in_for_range) 11270 << RangeLoc << BEF << Range->getType(); 11271 return FRS_DiagnosticIssued; 11272 } 11273 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0); 11274 if (CallExpr->isInvalid()) { 11275 *CallExpr = ExprError(); 11276 Diag(Range->getLocStart(), diag::note_in_for_range) 11277 << RangeLoc << BEF << Range->getType(); 11278 return FRS_DiagnosticIssued; 11279 } 11280 } else { 11281 UnresolvedSet<0> FoundNames; 11282 // C++11 [stmt.ranged]p1: For the purposes of this name lookup, namespace 11283 // std is an associated namespace. 11284 UnresolvedLookupExpr *Fn = 11285 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11286 NestedNameSpecifierLoc(), NameInfo, 11287 /*NeedsADL=*/true, /*Overloaded=*/false, 11288 FoundNames.begin(), FoundNames.end(), 11289 /*LookInStdNamespace=*/true); 11290 11291 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc, 11292 CandidateSet, CallExpr); 11293 if (CandidateSet->empty() || CandidateSetError) { 11294 *CallExpr = ExprError(); 11295 return FRS_NoViableFunction; 11296 } 11297 OverloadCandidateSet::iterator Best; 11298 OverloadingResult OverloadResult = 11299 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11300 11301 if (OverloadResult == OR_No_Viable_Function) { 11302 *CallExpr = ExprError(); 11303 return FRS_NoViableFunction; 11304 } 11305 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1, 11306 Loc, 0, CandidateSet, &Best, 11307 OverloadResult, 11308 /*AllowTypoCorrection=*/false); 11309 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11310 *CallExpr = ExprError(); 11311 Diag(Range->getLocStart(), diag::note_in_for_range) 11312 << RangeLoc << BEF << Range->getType(); 11313 return FRS_DiagnosticIssued; 11314 } 11315 } 11316 return FRS_Success; 11317} 11318 11319 11320/// FixOverloadedFunctionReference - E is an expression that refers to 11321/// a C++ overloaded function (possibly with some parentheses and 11322/// perhaps a '&' around it). We have resolved the overloaded function 11323/// to the function declaration Fn, so patch up the expression E to 11324/// refer (possibly indirectly) to Fn. Returns the new expr. 11325Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11326 FunctionDecl *Fn) { 11327 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11328 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11329 Found, Fn); 11330 if (SubExpr == PE->getSubExpr()) 11331 return PE; 11332 11333 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11334 } 11335 11336 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11337 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11338 Found, Fn); 11339 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11340 SubExpr->getType()) && 11341 "Implicit cast type cannot be determined from overload"); 11342 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11343 if (SubExpr == ICE->getSubExpr()) 11344 return ICE; 11345 11346 return ImplicitCastExpr::Create(Context, ICE->getType(), 11347 ICE->getCastKind(), 11348 SubExpr, 0, 11349 ICE->getValueKind()); 11350 } 11351 11352 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11353 assert(UnOp->getOpcode() == UO_AddrOf && 11354 "Can only take the address of an overloaded function"); 11355 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11356 if (Method->isStatic()) { 11357 // Do nothing: static member functions aren't any different 11358 // from non-member functions. 11359 } else { 11360 // Fix the sub expression, which really has to be an 11361 // UnresolvedLookupExpr holding an overloaded member function 11362 // or template. 11363 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11364 Found, Fn); 11365 if (SubExpr == UnOp->getSubExpr()) 11366 return UnOp; 11367 11368 assert(isa<DeclRefExpr>(SubExpr) 11369 && "fixed to something other than a decl ref"); 11370 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11371 && "fixed to a member ref with no nested name qualifier"); 11372 11373 // We have taken the address of a pointer to member 11374 // function. Perform the computation here so that we get the 11375 // appropriate pointer to member type. 11376 QualType ClassType 11377 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11378 QualType MemPtrType 11379 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11380 11381 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11382 VK_RValue, OK_Ordinary, 11383 UnOp->getOperatorLoc()); 11384 } 11385 } 11386 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11387 Found, Fn); 11388 if (SubExpr == UnOp->getSubExpr()) 11389 return UnOp; 11390 11391 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11392 Context.getPointerType(SubExpr->getType()), 11393 VK_RValue, OK_Ordinary, 11394 UnOp->getOperatorLoc()); 11395 } 11396 11397 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11398 // FIXME: avoid copy. 11399 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11400 if (ULE->hasExplicitTemplateArgs()) { 11401 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11402 TemplateArgs = &TemplateArgsBuffer; 11403 } 11404 11405 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11406 ULE->getQualifierLoc(), 11407 ULE->getTemplateKeywordLoc(), 11408 Fn, 11409 /*enclosing*/ false, // FIXME? 11410 ULE->getNameLoc(), 11411 Fn->getType(), 11412 VK_LValue, 11413 Found.getDecl(), 11414 TemplateArgs); 11415 MarkDeclRefReferenced(DRE); 11416 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11417 return DRE; 11418 } 11419 11420 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11421 // FIXME: avoid copy. 11422 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11423 if (MemExpr->hasExplicitTemplateArgs()) { 11424 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11425 TemplateArgs = &TemplateArgsBuffer; 11426 } 11427 11428 Expr *Base; 11429 11430 // If we're filling in a static method where we used to have an 11431 // implicit member access, rewrite to a simple decl ref. 11432 if (MemExpr->isImplicitAccess()) { 11433 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11434 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11435 MemExpr->getQualifierLoc(), 11436 MemExpr->getTemplateKeywordLoc(), 11437 Fn, 11438 /*enclosing*/ false, 11439 MemExpr->getMemberLoc(), 11440 Fn->getType(), 11441 VK_LValue, 11442 Found.getDecl(), 11443 TemplateArgs); 11444 MarkDeclRefReferenced(DRE); 11445 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11446 return DRE; 11447 } else { 11448 SourceLocation Loc = MemExpr->getMemberLoc(); 11449 if (MemExpr->getQualifier()) 11450 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11451 CheckCXXThisCapture(Loc); 11452 Base = new (Context) CXXThisExpr(Loc, 11453 MemExpr->getBaseType(), 11454 /*isImplicit=*/true); 11455 } 11456 } else 11457 Base = MemExpr->getBase(); 11458 11459 ExprValueKind valueKind; 11460 QualType type; 11461 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11462 valueKind = VK_LValue; 11463 type = Fn->getType(); 11464 } else { 11465 valueKind = VK_RValue; 11466 type = Context.BoundMemberTy; 11467 } 11468 11469 MemberExpr *ME = MemberExpr::Create(Context, Base, 11470 MemExpr->isArrow(), 11471 MemExpr->getQualifierLoc(), 11472 MemExpr->getTemplateKeywordLoc(), 11473 Fn, 11474 Found, 11475 MemExpr->getMemberNameInfo(), 11476 TemplateArgs, 11477 type, valueKind, OK_Ordinary); 11478 ME->setHadMultipleCandidates(true); 11479 return ME; 11480 } 11481 11482 llvm_unreachable("Invalid reference to overloaded function"); 11483} 11484 11485ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11486 DeclAccessPair Found, 11487 FunctionDecl *Fn) { 11488 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11489} 11490 11491} // end namespace clang 11492