SemaOverload.cpp revision 6d09da00bf5b5841380eae76571798ced6697f4c
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/TypeOrdering.h" 27#include "clang/Basic/PartialDiagnostic.h" 28#include "llvm/ADT/DenseSet.h" 29#include "llvm/ADT/SmallPtrSet.h" 30#include "llvm/ADT/STLExtras.h" 31#include <algorithm> 32 33namespace clang { 34using namespace sema; 35 36static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 37 bool InOverloadResolution, 38 StandardConversionSequence &SCS); 39static OverloadingResult 40IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 41 UserDefinedConversionSequence& User, 42 OverloadCandidateSet& Conversions, 43 bool AllowExplicit); 44 45 46static ImplicitConversionSequence::CompareKind 47CompareStandardConversionSequences(Sema &S, 48 const StandardConversionSequence& SCS1, 49 const StandardConversionSequence& SCS2); 50 51static ImplicitConversionSequence::CompareKind 52CompareQualificationConversions(Sema &S, 53 const StandardConversionSequence& SCS1, 54 const StandardConversionSequence& SCS2); 55 56static ImplicitConversionSequence::CompareKind 57CompareDerivedToBaseConversions(Sema &S, 58 const StandardConversionSequence& SCS1, 59 const StandardConversionSequence& SCS2); 60 61 62 63/// GetConversionCategory - Retrieve the implicit conversion 64/// category corresponding to the given implicit conversion kind. 65ImplicitConversionCategory 66GetConversionCategory(ImplicitConversionKind Kind) { 67 static const ImplicitConversionCategory 68 Category[(int)ICK_Num_Conversion_Kinds] = { 69 ICC_Identity, 70 ICC_Lvalue_Transformation, 71 ICC_Lvalue_Transformation, 72 ICC_Lvalue_Transformation, 73 ICC_Identity, 74 ICC_Qualification_Adjustment, 75 ICC_Promotion, 76 ICC_Promotion, 77 ICC_Promotion, 78 ICC_Conversion, 79 ICC_Conversion, 80 ICC_Conversion, 81 ICC_Conversion, 82 ICC_Conversion, 83 ICC_Conversion, 84 ICC_Conversion, 85 ICC_Conversion, 86 ICC_Conversion, 87 ICC_Conversion, 88 ICC_Conversion, 89 ICC_Conversion 90 }; 91 return Category[(int)Kind]; 92} 93 94/// GetConversionRank - Retrieve the implicit conversion rank 95/// corresponding to the given implicit conversion kind. 96ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 97 static const ImplicitConversionRank 98 Rank[(int)ICK_Num_Conversion_Kinds] = { 99 ICR_Exact_Match, 100 ICR_Exact_Match, 101 ICR_Exact_Match, 102 ICR_Exact_Match, 103 ICR_Exact_Match, 104 ICR_Exact_Match, 105 ICR_Promotion, 106 ICR_Promotion, 107 ICR_Promotion, 108 ICR_Conversion, 109 ICR_Conversion, 110 ICR_Conversion, 111 ICR_Conversion, 112 ICR_Conversion, 113 ICR_Conversion, 114 ICR_Conversion, 115 ICR_Conversion, 116 ICR_Conversion, 117 ICR_Conversion, 118 ICR_Conversion, 119 ICR_Complex_Real_Conversion 120 }; 121 return Rank[(int)Kind]; 122} 123 124/// GetImplicitConversionName - Return the name of this kind of 125/// implicit conversion. 126const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 127 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 128 "No conversion", 129 "Lvalue-to-rvalue", 130 "Array-to-pointer", 131 "Function-to-pointer", 132 "Noreturn adjustment", 133 "Qualification", 134 "Integral promotion", 135 "Floating point promotion", 136 "Complex promotion", 137 "Integral conversion", 138 "Floating conversion", 139 "Complex conversion", 140 "Floating-integral conversion", 141 "Pointer conversion", 142 "Pointer-to-member conversion", 143 "Boolean conversion", 144 "Compatible-types conversion", 145 "Derived-to-base conversion", 146 "Vector conversion", 147 "Vector splat", 148 "Complex-real conversion" 149 }; 150 return Name[Kind]; 151} 152 153/// StandardConversionSequence - Set the standard conversion 154/// sequence to the identity conversion. 155void StandardConversionSequence::setAsIdentityConversion() { 156 First = ICK_Identity; 157 Second = ICK_Identity; 158 Third = ICK_Identity; 159 DeprecatedStringLiteralToCharPtr = false; 160 ReferenceBinding = false; 161 DirectBinding = false; 162 RRefBinding = false; 163 CopyConstructor = 0; 164} 165 166/// getRank - Retrieve the rank of this standard conversion sequence 167/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 168/// implicit conversions. 169ImplicitConversionRank StandardConversionSequence::getRank() const { 170 ImplicitConversionRank Rank = ICR_Exact_Match; 171 if (GetConversionRank(First) > Rank) 172 Rank = GetConversionRank(First); 173 if (GetConversionRank(Second) > Rank) 174 Rank = GetConversionRank(Second); 175 if (GetConversionRank(Third) > Rank) 176 Rank = GetConversionRank(Third); 177 return Rank; 178} 179 180/// isPointerConversionToBool - Determines whether this conversion is 181/// a conversion of a pointer or pointer-to-member to bool. This is 182/// used as part of the ranking of standard conversion sequences 183/// (C++ 13.3.3.2p4). 184bool StandardConversionSequence::isPointerConversionToBool() const { 185 // Note that FromType has not necessarily been transformed by the 186 // array-to-pointer or function-to-pointer implicit conversions, so 187 // check for their presence as well as checking whether FromType is 188 // a pointer. 189 if (getToType(1)->isBooleanType() && 190 (getFromType()->isPointerType() || 191 getFromType()->isObjCObjectPointerType() || 192 getFromType()->isBlockPointerType() || 193 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 194 return true; 195 196 return false; 197} 198 199/// isPointerConversionToVoidPointer - Determines whether this 200/// conversion is a conversion of a pointer to a void pointer. This is 201/// used as part of the ranking of standard conversion sequences (C++ 202/// 13.3.3.2p4). 203/// 204/// Note that we treat conversions of Objective-C pointers to 205/// unqualified 'id' as having this same rank. 206bool 207StandardConversionSequence:: 208isPointerConversionToVoidPointer(ASTContext& Context) const { 209 QualType FromType = getFromType(); 210 QualType ToType = getToType(1); 211 212 // Note that FromType has not necessarily been transformed by the 213 // array-to-pointer implicit conversion, so check for its presence 214 // and redo the conversion to get a pointer. 215 if (First == ICK_Array_To_Pointer) 216 FromType = Context.getArrayDecayedType(FromType); 217 218 if (Second == ICK_Pointer_Conversion && FromType->isPointerType()) { 219 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 220 return ToPtrType->getPointeeType()->isVoidType(); 221 } else if (Second == ICK_Pointer_Conversion && 222 FromType->isObjCObjectPointerType()) { 223 if (const ObjCObjectPointerType *ToPtrType = 224 ToType->getAs<ObjCObjectPointerType>()) 225 return ToPtrType->isObjCIdType(); 226 } 227 228 return false; 229} 230 231/// DebugPrint - Print this standard conversion sequence to standard 232/// error. Useful for debugging overloading issues. 233void StandardConversionSequence::DebugPrint() const { 234 llvm::raw_ostream &OS = llvm::errs(); 235 bool PrintedSomething = false; 236 if (First != ICK_Identity) { 237 OS << GetImplicitConversionName(First); 238 PrintedSomething = true; 239 } 240 241 if (Second != ICK_Identity) { 242 if (PrintedSomething) { 243 OS << " -> "; 244 } 245 OS << GetImplicitConversionName(Second); 246 247 if (CopyConstructor) { 248 OS << " (by copy constructor)"; 249 } else if (DirectBinding) { 250 OS << " (direct reference binding)"; 251 } else if (ReferenceBinding) { 252 OS << " (reference binding)"; 253 } 254 PrintedSomething = true; 255 } 256 257 if (Third != ICK_Identity) { 258 if (PrintedSomething) { 259 OS << " -> "; 260 } 261 OS << GetImplicitConversionName(Third); 262 PrintedSomething = true; 263 } 264 265 if (!PrintedSomething) { 266 OS << "No conversions required"; 267 } 268} 269 270/// DebugPrint - Print this user-defined conversion sequence to standard 271/// error. Useful for debugging overloading issues. 272void UserDefinedConversionSequence::DebugPrint() const { 273 llvm::raw_ostream &OS = llvm::errs(); 274 if (Before.First || Before.Second || Before.Third) { 275 Before.DebugPrint(); 276 OS << " -> "; 277 } 278 OS << '\'' << ConversionFunction << '\''; 279 if (After.First || After.Second || After.Third) { 280 OS << " -> "; 281 After.DebugPrint(); 282 } 283} 284 285/// DebugPrint - Print this implicit conversion sequence to standard 286/// error. Useful for debugging overloading issues. 287void ImplicitConversionSequence::DebugPrint() const { 288 llvm::raw_ostream &OS = llvm::errs(); 289 switch (ConversionKind) { 290 case StandardConversion: 291 OS << "Standard conversion: "; 292 Standard.DebugPrint(); 293 break; 294 case UserDefinedConversion: 295 OS << "User-defined conversion: "; 296 UserDefined.DebugPrint(); 297 break; 298 case EllipsisConversion: 299 OS << "Ellipsis conversion"; 300 break; 301 case AmbiguousConversion: 302 OS << "Ambiguous conversion"; 303 break; 304 case BadConversion: 305 OS << "Bad conversion"; 306 break; 307 } 308 309 OS << "\n"; 310} 311 312void AmbiguousConversionSequence::construct() { 313 new (&conversions()) ConversionSet(); 314} 315 316void AmbiguousConversionSequence::destruct() { 317 conversions().~ConversionSet(); 318} 319 320void 321AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 322 FromTypePtr = O.FromTypePtr; 323 ToTypePtr = O.ToTypePtr; 324 new (&conversions()) ConversionSet(O.conversions()); 325} 326 327namespace { 328 // Structure used by OverloadCandidate::DeductionFailureInfo to store 329 // template parameter and template argument information. 330 struct DFIParamWithArguments { 331 TemplateParameter Param; 332 TemplateArgument FirstArg; 333 TemplateArgument SecondArg; 334 }; 335} 336 337/// \brief Convert from Sema's representation of template deduction information 338/// to the form used in overload-candidate information. 339OverloadCandidate::DeductionFailureInfo 340static MakeDeductionFailureInfo(ASTContext &Context, 341 Sema::TemplateDeductionResult TDK, 342 TemplateDeductionInfo &Info) { 343 OverloadCandidate::DeductionFailureInfo Result; 344 Result.Result = static_cast<unsigned>(TDK); 345 Result.Data = 0; 346 switch (TDK) { 347 case Sema::TDK_Success: 348 case Sema::TDK_InstantiationDepth: 349 case Sema::TDK_TooManyArguments: 350 case Sema::TDK_TooFewArguments: 351 break; 352 353 case Sema::TDK_Incomplete: 354 case Sema::TDK_InvalidExplicitArguments: 355 Result.Data = Info.Param.getOpaqueValue(); 356 break; 357 358 case Sema::TDK_Inconsistent: 359 case Sema::TDK_Underqualified: { 360 // FIXME: Should allocate from normal heap so that we can free this later. 361 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 362 Saved->Param = Info.Param; 363 Saved->FirstArg = Info.FirstArg; 364 Saved->SecondArg = Info.SecondArg; 365 Result.Data = Saved; 366 break; 367 } 368 369 case Sema::TDK_SubstitutionFailure: 370 Result.Data = Info.take(); 371 break; 372 373 case Sema::TDK_NonDeducedMismatch: 374 case Sema::TDK_FailedOverloadResolution: 375 break; 376 } 377 378 return Result; 379} 380 381void OverloadCandidate::DeductionFailureInfo::Destroy() { 382 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 383 case Sema::TDK_Success: 384 case Sema::TDK_InstantiationDepth: 385 case Sema::TDK_Incomplete: 386 case Sema::TDK_TooManyArguments: 387 case Sema::TDK_TooFewArguments: 388 case Sema::TDK_InvalidExplicitArguments: 389 break; 390 391 case Sema::TDK_Inconsistent: 392 case Sema::TDK_Underqualified: 393 // FIXME: Destroy the data? 394 Data = 0; 395 break; 396 397 case Sema::TDK_SubstitutionFailure: 398 // FIXME: Destroy the template arugment list? 399 Data = 0; 400 break; 401 402 // Unhandled 403 case Sema::TDK_NonDeducedMismatch: 404 case Sema::TDK_FailedOverloadResolution: 405 break; 406 } 407} 408 409TemplateParameter 410OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 411 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 412 case Sema::TDK_Success: 413 case Sema::TDK_InstantiationDepth: 414 case Sema::TDK_TooManyArguments: 415 case Sema::TDK_TooFewArguments: 416 case Sema::TDK_SubstitutionFailure: 417 return TemplateParameter(); 418 419 case Sema::TDK_Incomplete: 420 case Sema::TDK_InvalidExplicitArguments: 421 return TemplateParameter::getFromOpaqueValue(Data); 422 423 case Sema::TDK_Inconsistent: 424 case Sema::TDK_Underqualified: 425 return static_cast<DFIParamWithArguments*>(Data)->Param; 426 427 // Unhandled 428 case Sema::TDK_NonDeducedMismatch: 429 case Sema::TDK_FailedOverloadResolution: 430 break; 431 } 432 433 return TemplateParameter(); 434} 435 436TemplateArgumentList * 437OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 438 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 439 case Sema::TDK_Success: 440 case Sema::TDK_InstantiationDepth: 441 case Sema::TDK_TooManyArguments: 442 case Sema::TDK_TooFewArguments: 443 case Sema::TDK_Incomplete: 444 case Sema::TDK_InvalidExplicitArguments: 445 case Sema::TDK_Inconsistent: 446 case Sema::TDK_Underqualified: 447 return 0; 448 449 case Sema::TDK_SubstitutionFailure: 450 return static_cast<TemplateArgumentList*>(Data); 451 452 // Unhandled 453 case Sema::TDK_NonDeducedMismatch: 454 case Sema::TDK_FailedOverloadResolution: 455 break; 456 } 457 458 return 0; 459} 460 461const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 462 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 463 case Sema::TDK_Success: 464 case Sema::TDK_InstantiationDepth: 465 case Sema::TDK_Incomplete: 466 case Sema::TDK_TooManyArguments: 467 case Sema::TDK_TooFewArguments: 468 case Sema::TDK_InvalidExplicitArguments: 469 case Sema::TDK_SubstitutionFailure: 470 return 0; 471 472 case Sema::TDK_Inconsistent: 473 case Sema::TDK_Underqualified: 474 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 475 476 // Unhandled 477 case Sema::TDK_NonDeducedMismatch: 478 case Sema::TDK_FailedOverloadResolution: 479 break; 480 } 481 482 return 0; 483} 484 485const TemplateArgument * 486OverloadCandidate::DeductionFailureInfo::getSecondArg() { 487 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 488 case Sema::TDK_Success: 489 case Sema::TDK_InstantiationDepth: 490 case Sema::TDK_Incomplete: 491 case Sema::TDK_TooManyArguments: 492 case Sema::TDK_TooFewArguments: 493 case Sema::TDK_InvalidExplicitArguments: 494 case Sema::TDK_SubstitutionFailure: 495 return 0; 496 497 case Sema::TDK_Inconsistent: 498 case Sema::TDK_Underqualified: 499 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 500 501 // Unhandled 502 case Sema::TDK_NonDeducedMismatch: 503 case Sema::TDK_FailedOverloadResolution: 504 break; 505 } 506 507 return 0; 508} 509 510void OverloadCandidateSet::clear() { 511 inherited::clear(); 512 Functions.clear(); 513} 514 515// IsOverload - Determine whether the given New declaration is an 516// overload of the declarations in Old. This routine returns false if 517// New and Old cannot be overloaded, e.g., if New has the same 518// signature as some function in Old (C++ 1.3.10) or if the Old 519// declarations aren't functions (or function templates) at all. When 520// it does return false, MatchedDecl will point to the decl that New 521// cannot be overloaded with. This decl may be a UsingShadowDecl on 522// top of the underlying declaration. 523// 524// Example: Given the following input: 525// 526// void f(int, float); // #1 527// void f(int, int); // #2 528// int f(int, int); // #3 529// 530// When we process #1, there is no previous declaration of "f", 531// so IsOverload will not be used. 532// 533// When we process #2, Old contains only the FunctionDecl for #1. By 534// comparing the parameter types, we see that #1 and #2 are overloaded 535// (since they have different signatures), so this routine returns 536// false; MatchedDecl is unchanged. 537// 538// When we process #3, Old is an overload set containing #1 and #2. We 539// compare the signatures of #3 to #1 (they're overloaded, so we do 540// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 541// identical (return types of functions are not part of the 542// signature), IsOverload returns false and MatchedDecl will be set to 543// point to the FunctionDecl for #2. 544// 545// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 546// into a class by a using declaration. The rules for whether to hide 547// shadow declarations ignore some properties which otherwise figure 548// into a function template's signature. 549Sema::OverloadKind 550Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 551 NamedDecl *&Match, bool NewIsUsingDecl) { 552 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 553 I != E; ++I) { 554 NamedDecl *OldD = *I; 555 556 bool OldIsUsingDecl = false; 557 if (isa<UsingShadowDecl>(OldD)) { 558 OldIsUsingDecl = true; 559 560 // We can always introduce two using declarations into the same 561 // context, even if they have identical signatures. 562 if (NewIsUsingDecl) continue; 563 564 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 565 } 566 567 // If either declaration was introduced by a using declaration, 568 // we'll need to use slightly different rules for matching. 569 // Essentially, these rules are the normal rules, except that 570 // function templates hide function templates with different 571 // return types or template parameter lists. 572 bool UseMemberUsingDeclRules = 573 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 574 575 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 576 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 577 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 578 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 579 continue; 580 } 581 582 Match = *I; 583 return Ovl_Match; 584 } 585 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 586 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 587 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 588 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 589 continue; 590 } 591 592 Match = *I; 593 return Ovl_Match; 594 } 595 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) { 596 // We can overload with these, which can show up when doing 597 // redeclaration checks for UsingDecls. 598 assert(Old.getLookupKind() == LookupUsingDeclName); 599 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 600 // Optimistically assume that an unresolved using decl will 601 // overload; if it doesn't, we'll have to diagnose during 602 // template instantiation. 603 } else { 604 // (C++ 13p1): 605 // Only function declarations can be overloaded; object and type 606 // declarations cannot be overloaded. 607 Match = *I; 608 return Ovl_NonFunction; 609 } 610 } 611 612 return Ovl_Overload; 613} 614 615bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 616 bool UseUsingDeclRules) { 617 // If both of the functions are extern "C", then they are not 618 // overloads. 619 if (Old->isExternC() && New->isExternC()) 620 return false; 621 622 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 623 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 624 625 // C++ [temp.fct]p2: 626 // A function template can be overloaded with other function templates 627 // and with normal (non-template) functions. 628 if ((OldTemplate == 0) != (NewTemplate == 0)) 629 return true; 630 631 // Is the function New an overload of the function Old? 632 QualType OldQType = Context.getCanonicalType(Old->getType()); 633 QualType NewQType = Context.getCanonicalType(New->getType()); 634 635 // Compare the signatures (C++ 1.3.10) of the two functions to 636 // determine whether they are overloads. If we find any mismatch 637 // in the signature, they are overloads. 638 639 // If either of these functions is a K&R-style function (no 640 // prototype), then we consider them to have matching signatures. 641 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 642 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 643 return false; 644 645 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 646 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 647 648 // The signature of a function includes the types of its 649 // parameters (C++ 1.3.10), which includes the presence or absence 650 // of the ellipsis; see C++ DR 357). 651 if (OldQType != NewQType && 652 (OldType->getNumArgs() != NewType->getNumArgs() || 653 OldType->isVariadic() != NewType->isVariadic() || 654 !FunctionArgTypesAreEqual(OldType, NewType))) 655 return true; 656 657 // C++ [temp.over.link]p4: 658 // The signature of a function template consists of its function 659 // signature, its return type and its template parameter list. The names 660 // of the template parameters are significant only for establishing the 661 // relationship between the template parameters and the rest of the 662 // signature. 663 // 664 // We check the return type and template parameter lists for function 665 // templates first; the remaining checks follow. 666 // 667 // However, we don't consider either of these when deciding whether 668 // a member introduced by a shadow declaration is hidden. 669 if (!UseUsingDeclRules && NewTemplate && 670 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 671 OldTemplate->getTemplateParameters(), 672 false, TPL_TemplateMatch) || 673 OldType->getResultType() != NewType->getResultType())) 674 return true; 675 676 // If the function is a class member, its signature includes the 677 // cv-qualifiers (if any) on the function itself. 678 // 679 // As part of this, also check whether one of the member functions 680 // is static, in which case they are not overloads (C++ 681 // 13.1p2). While not part of the definition of the signature, 682 // this check is important to determine whether these functions 683 // can be overloaded. 684 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 685 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 686 if (OldMethod && NewMethod && 687 !OldMethod->isStatic() && !NewMethod->isStatic() && 688 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers()) 689 return true; 690 691 // The signatures match; this is not an overload. 692 return false; 693} 694 695/// TryImplicitConversion - Attempt to perform an implicit conversion 696/// from the given expression (Expr) to the given type (ToType). This 697/// function returns an implicit conversion sequence that can be used 698/// to perform the initialization. Given 699/// 700/// void f(float f); 701/// void g(int i) { f(i); } 702/// 703/// this routine would produce an implicit conversion sequence to 704/// describe the initialization of f from i, which will be a standard 705/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 706/// 4.1) followed by a floating-integral conversion (C++ 4.9). 707// 708/// Note that this routine only determines how the conversion can be 709/// performed; it does not actually perform the conversion. As such, 710/// it will not produce any diagnostics if no conversion is available, 711/// but will instead return an implicit conversion sequence of kind 712/// "BadConversion". 713/// 714/// If @p SuppressUserConversions, then user-defined conversions are 715/// not permitted. 716/// If @p AllowExplicit, then explicit user-defined conversions are 717/// permitted. 718static ImplicitConversionSequence 719TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 720 bool SuppressUserConversions, 721 bool AllowExplicit, 722 bool InOverloadResolution) { 723 ImplicitConversionSequence ICS; 724 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 725 ICS.Standard)) { 726 ICS.setStandard(); 727 return ICS; 728 } 729 730 if (!S.getLangOptions().CPlusPlus) { 731 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 732 return ICS; 733 } 734 735 // C++ [over.ics.user]p4: 736 // A conversion of an expression of class type to the same class 737 // type is given Exact Match rank, and a conversion of an 738 // expression of class type to a base class of that type is 739 // given Conversion rank, in spite of the fact that a copy/move 740 // constructor (i.e., a user-defined conversion function) is 741 // called for those cases. 742 QualType FromType = From->getType(); 743 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 744 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 745 S.IsDerivedFrom(FromType, ToType))) { 746 ICS.setStandard(); 747 ICS.Standard.setAsIdentityConversion(); 748 ICS.Standard.setFromType(FromType); 749 ICS.Standard.setAllToTypes(ToType); 750 751 // We don't actually check at this point whether there is a valid 752 // copy/move constructor, since overloading just assumes that it 753 // exists. When we actually perform initialization, we'll find the 754 // appropriate constructor to copy the returned object, if needed. 755 ICS.Standard.CopyConstructor = 0; 756 757 // Determine whether this is considered a derived-to-base conversion. 758 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 759 ICS.Standard.Second = ICK_Derived_To_Base; 760 761 return ICS; 762 } 763 764 if (SuppressUserConversions) { 765 // We're not in the case above, so there is no conversion that 766 // we can perform. 767 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 768 return ICS; 769 } 770 771 // Attempt user-defined conversion. 772 OverloadCandidateSet Conversions(From->getExprLoc()); 773 OverloadingResult UserDefResult 774 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 775 AllowExplicit); 776 777 if (UserDefResult == OR_Success) { 778 ICS.setUserDefined(); 779 // C++ [over.ics.user]p4: 780 // A conversion of an expression of class type to the same class 781 // type is given Exact Match rank, and a conversion of an 782 // expression of class type to a base class of that type is 783 // given Conversion rank, in spite of the fact that a copy 784 // constructor (i.e., a user-defined conversion function) is 785 // called for those cases. 786 if (CXXConstructorDecl *Constructor 787 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 788 QualType FromCanon 789 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 790 QualType ToCanon 791 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 792 if (Constructor->isCopyConstructor() && 793 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 794 // Turn this into a "standard" conversion sequence, so that it 795 // gets ranked with standard conversion sequences. 796 ICS.setStandard(); 797 ICS.Standard.setAsIdentityConversion(); 798 ICS.Standard.setFromType(From->getType()); 799 ICS.Standard.setAllToTypes(ToType); 800 ICS.Standard.CopyConstructor = Constructor; 801 if (ToCanon != FromCanon) 802 ICS.Standard.Second = ICK_Derived_To_Base; 803 } 804 } 805 806 // C++ [over.best.ics]p4: 807 // However, when considering the argument of a user-defined 808 // conversion function that is a candidate by 13.3.1.3 when 809 // invoked for the copying of the temporary in the second step 810 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 811 // 13.3.1.6 in all cases, only standard conversion sequences and 812 // ellipsis conversion sequences are allowed. 813 if (SuppressUserConversions && ICS.isUserDefined()) { 814 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 815 } 816 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 817 ICS.setAmbiguous(); 818 ICS.Ambiguous.setFromType(From->getType()); 819 ICS.Ambiguous.setToType(ToType); 820 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 821 Cand != Conversions.end(); ++Cand) 822 if (Cand->Viable) 823 ICS.Ambiguous.addConversion(Cand->Function); 824 } else { 825 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 826 } 827 828 return ICS; 829} 830 831bool Sema::TryImplicitConversion(InitializationSequence &Sequence, 832 const InitializedEntity &Entity, 833 Expr *Initializer, 834 bool SuppressUserConversions, 835 bool AllowExplicitConversions, 836 bool InOverloadResolution) { 837 ImplicitConversionSequence ICS 838 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(), 839 SuppressUserConversions, 840 AllowExplicitConversions, 841 InOverloadResolution); 842 if (ICS.isBad()) return true; 843 844 // Perform the actual conversion. 845 Sequence.AddConversionSequenceStep(ICS, Entity.getType()); 846 return false; 847} 848 849/// PerformImplicitConversion - Perform an implicit conversion of the 850/// expression From to the type ToType. Returns true if there was an 851/// error, false otherwise. The expression From is replaced with the 852/// converted expression. Flavor is the kind of conversion we're 853/// performing, used in the error message. If @p AllowExplicit, 854/// explicit user-defined conversions are permitted. 855bool 856Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 857 AssignmentAction Action, bool AllowExplicit) { 858 ImplicitConversionSequence ICS; 859 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 860} 861 862bool 863Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 864 AssignmentAction Action, bool AllowExplicit, 865 ImplicitConversionSequence& ICS) { 866 ICS = clang::TryImplicitConversion(*this, From, ToType, 867 /*SuppressUserConversions=*/false, 868 AllowExplicit, 869 /*InOverloadResolution=*/false); 870 return PerformImplicitConversion(From, ToType, ICS, Action); 871} 872 873/// \brief Determine whether the conversion from FromType to ToType is a valid 874/// conversion that strips "noreturn" off the nested function type. 875static bool IsNoReturnConversion(ASTContext &Context, QualType FromType, 876 QualType ToType, QualType &ResultTy) { 877 if (Context.hasSameUnqualifiedType(FromType, ToType)) 878 return false; 879 880 // Strip the noreturn off the type we're converting from; noreturn can 881 // safely be removed. 882 FromType = Context.getNoReturnType(FromType, false); 883 if (!Context.hasSameUnqualifiedType(FromType, ToType)) 884 return false; 885 886 ResultTy = FromType; 887 return true; 888} 889 890/// \brief Determine whether the conversion from FromType to ToType is a valid 891/// vector conversion. 892/// 893/// \param ICK Will be set to the vector conversion kind, if this is a vector 894/// conversion. 895static bool IsVectorConversion(ASTContext &Context, QualType FromType, 896 QualType ToType, ImplicitConversionKind &ICK) { 897 // We need at least one of these types to be a vector type to have a vector 898 // conversion. 899 if (!ToType->isVectorType() && !FromType->isVectorType()) 900 return false; 901 902 // Identical types require no conversions. 903 if (Context.hasSameUnqualifiedType(FromType, ToType)) 904 return false; 905 906 // There are no conversions between extended vector types, only identity. 907 if (ToType->isExtVectorType()) { 908 // There are no conversions between extended vector types other than the 909 // identity conversion. 910 if (FromType->isExtVectorType()) 911 return false; 912 913 // Vector splat from any arithmetic type to a vector. 914 if (FromType->isArithmeticType()) { 915 ICK = ICK_Vector_Splat; 916 return true; 917 } 918 } 919 920 // We can perform the conversion between vector types in the following cases: 921 // 1)vector types are equivalent AltiVec and GCC vector types 922 // 2)lax vector conversions are permitted and the vector types are of the 923 // same size 924 if (ToType->isVectorType() && FromType->isVectorType()) { 925 if (Context.areCompatibleVectorTypes(FromType, ToType) || 926 (Context.getLangOptions().LaxVectorConversions && 927 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 928 ICK = ICK_Vector_Conversion; 929 return true; 930 } 931 } 932 933 return false; 934} 935 936/// IsStandardConversion - Determines whether there is a standard 937/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 938/// expression From to the type ToType. Standard conversion sequences 939/// only consider non-class types; for conversions that involve class 940/// types, use TryImplicitConversion. If a conversion exists, SCS will 941/// contain the standard conversion sequence required to perform this 942/// conversion and this routine will return true. Otherwise, this 943/// routine will return false and the value of SCS is unspecified. 944static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 945 bool InOverloadResolution, 946 StandardConversionSequence &SCS) { 947 QualType FromType = From->getType(); 948 949 // Standard conversions (C++ [conv]) 950 SCS.setAsIdentityConversion(); 951 SCS.DeprecatedStringLiteralToCharPtr = false; 952 SCS.IncompatibleObjC = false; 953 SCS.setFromType(FromType); 954 SCS.CopyConstructor = 0; 955 956 // There are no standard conversions for class types in C++, so 957 // abort early. When overloading in C, however, we do permit 958 if (FromType->isRecordType() || ToType->isRecordType()) { 959 if (S.getLangOptions().CPlusPlus) 960 return false; 961 962 // When we're overloading in C, we allow, as standard conversions, 963 } 964 965 // The first conversion can be an lvalue-to-rvalue conversion, 966 // array-to-pointer conversion, or function-to-pointer conversion 967 // (C++ 4p1). 968 969 if (FromType == S.Context.OverloadTy) { 970 DeclAccessPair AccessPair; 971 if (FunctionDecl *Fn 972 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 973 AccessPair)) { 974 // We were able to resolve the address of the overloaded function, 975 // so we can convert to the type of that function. 976 FromType = Fn->getType(); 977 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 978 if (!Method->isStatic()) { 979 Type *ClassType 980 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 981 FromType = S.Context.getMemberPointerType(FromType, ClassType); 982 } 983 } 984 985 // If the "from" expression takes the address of the overloaded 986 // function, update the type of the resulting expression accordingly. 987 if (FromType->getAs<FunctionType>()) 988 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens())) 989 if (UnOp->getOpcode() == UO_AddrOf) 990 FromType = S.Context.getPointerType(FromType); 991 992 // Check that we've computed the proper type after overload resolution. 993 assert(S.Context.hasSameType(FromType, 994 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 995 } else { 996 return false; 997 } 998 } 999 // Lvalue-to-rvalue conversion (C++ 4.1): 1000 // An lvalue (3.10) of a non-function, non-array type T can be 1001 // converted to an rvalue. 1002 Expr::isLvalueResult argIsLvalue = From->isLvalue(S.Context); 1003 if (argIsLvalue == Expr::LV_Valid && 1004 !FromType->isFunctionType() && !FromType->isArrayType() && 1005 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1006 SCS.First = ICK_Lvalue_To_Rvalue; 1007 1008 // If T is a non-class type, the type of the rvalue is the 1009 // cv-unqualified version of T. Otherwise, the type of the rvalue 1010 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1011 // just strip the qualifiers because they don't matter. 1012 FromType = FromType.getUnqualifiedType(); 1013 } else if (FromType->isArrayType()) { 1014 // Array-to-pointer conversion (C++ 4.2) 1015 SCS.First = ICK_Array_To_Pointer; 1016 1017 // An lvalue or rvalue of type "array of N T" or "array of unknown 1018 // bound of T" can be converted to an rvalue of type "pointer to 1019 // T" (C++ 4.2p1). 1020 FromType = S.Context.getArrayDecayedType(FromType); 1021 1022 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1023 // This conversion is deprecated. (C++ D.4). 1024 SCS.DeprecatedStringLiteralToCharPtr = true; 1025 1026 // For the purpose of ranking in overload resolution 1027 // (13.3.3.1.1), this conversion is considered an 1028 // array-to-pointer conversion followed by a qualification 1029 // conversion (4.4). (C++ 4.2p2) 1030 SCS.Second = ICK_Identity; 1031 SCS.Third = ICK_Qualification; 1032 SCS.setAllToTypes(FromType); 1033 return true; 1034 } 1035 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) { 1036 // Function-to-pointer conversion (C++ 4.3). 1037 SCS.First = ICK_Function_To_Pointer; 1038 1039 // An lvalue of function type T can be converted to an rvalue of 1040 // type "pointer to T." The result is a pointer to the 1041 // function. (C++ 4.3p1). 1042 FromType = S.Context.getPointerType(FromType); 1043 } else { 1044 // We don't require any conversions for the first step. 1045 SCS.First = ICK_Identity; 1046 } 1047 SCS.setToType(0, FromType); 1048 1049 // The second conversion can be an integral promotion, floating 1050 // point promotion, integral conversion, floating point conversion, 1051 // floating-integral conversion, pointer conversion, 1052 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1053 // For overloading in C, this can also be a "compatible-type" 1054 // conversion. 1055 bool IncompatibleObjC = false; 1056 ImplicitConversionKind SecondICK = ICK_Identity; 1057 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1058 // The unqualified versions of the types are the same: there's no 1059 // conversion to do. 1060 SCS.Second = ICK_Identity; 1061 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1062 // Integral promotion (C++ 4.5). 1063 SCS.Second = ICK_Integral_Promotion; 1064 FromType = ToType.getUnqualifiedType(); 1065 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1066 // Floating point promotion (C++ 4.6). 1067 SCS.Second = ICK_Floating_Promotion; 1068 FromType = ToType.getUnqualifiedType(); 1069 } else if (S.IsComplexPromotion(FromType, ToType)) { 1070 // Complex promotion (Clang extension) 1071 SCS.Second = ICK_Complex_Promotion; 1072 FromType = ToType.getUnqualifiedType(); 1073 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1074 ToType->isIntegralType(S.Context)) { 1075 // Integral conversions (C++ 4.7). 1076 SCS.Second = ICK_Integral_Conversion; 1077 FromType = ToType.getUnqualifiedType(); 1078 } else if (FromType->isComplexType() && ToType->isComplexType()) { 1079 // Complex conversions (C99 6.3.1.6) 1080 SCS.Second = ICK_Complex_Conversion; 1081 FromType = ToType.getUnqualifiedType(); 1082 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) || 1083 (ToType->isComplexType() && FromType->isArithmeticType())) { 1084 // Complex-real conversions (C99 6.3.1.7) 1085 SCS.Second = ICK_Complex_Real; 1086 FromType = ToType.getUnqualifiedType(); 1087 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1088 // Floating point conversions (C++ 4.8). 1089 SCS.Second = ICK_Floating_Conversion; 1090 FromType = ToType.getUnqualifiedType(); 1091 } else if ((FromType->isRealFloatingType() && 1092 ToType->isIntegralType(S.Context) && !ToType->isBooleanType()) || 1093 (FromType->isIntegralOrUnscopedEnumerationType() && 1094 ToType->isRealFloatingType())) { 1095 // Floating-integral conversions (C++ 4.9). 1096 SCS.Second = ICK_Floating_Integral; 1097 FromType = ToType.getUnqualifiedType(); 1098 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1099 FromType, IncompatibleObjC)) { 1100 // Pointer conversions (C++ 4.10). 1101 SCS.Second = ICK_Pointer_Conversion; 1102 SCS.IncompatibleObjC = IncompatibleObjC; 1103 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1104 InOverloadResolution, FromType)) { 1105 // Pointer to member conversions (4.11). 1106 SCS.Second = ICK_Pointer_Member; 1107 } else if (ToType->isBooleanType() && 1108 (FromType->isArithmeticType() || 1109 FromType->isAnyPointerType() || 1110 FromType->isBlockPointerType() || 1111 FromType->isMemberPointerType() || 1112 FromType->isNullPtrType())) { 1113 // Boolean conversions (C++ 4.12). 1114 SCS.Second = ICK_Boolean_Conversion; 1115 FromType = S.Context.BoolTy; 1116 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1117 SCS.Second = SecondICK; 1118 FromType = ToType.getUnqualifiedType(); 1119 } else if (!S.getLangOptions().CPlusPlus && 1120 S.Context.typesAreCompatible(ToType, FromType)) { 1121 // Compatible conversions (Clang extension for C function overloading) 1122 SCS.Second = ICK_Compatible_Conversion; 1123 FromType = ToType.getUnqualifiedType(); 1124 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) { 1125 // Treat a conversion that strips "noreturn" as an identity conversion. 1126 SCS.Second = ICK_NoReturn_Adjustment; 1127 } else { 1128 // No second conversion required. 1129 SCS.Second = ICK_Identity; 1130 } 1131 SCS.setToType(1, FromType); 1132 1133 QualType CanonFrom; 1134 QualType CanonTo; 1135 // The third conversion can be a qualification conversion (C++ 4p1). 1136 if (S.IsQualificationConversion(FromType, ToType)) { 1137 SCS.Third = ICK_Qualification; 1138 FromType = ToType; 1139 CanonFrom = S.Context.getCanonicalType(FromType); 1140 CanonTo = S.Context.getCanonicalType(ToType); 1141 } else { 1142 // No conversion required 1143 SCS.Third = ICK_Identity; 1144 1145 // C++ [over.best.ics]p6: 1146 // [...] Any difference in top-level cv-qualification is 1147 // subsumed by the initialization itself and does not constitute 1148 // a conversion. [...] 1149 CanonFrom = S.Context.getCanonicalType(FromType); 1150 CanonTo = S.Context.getCanonicalType(ToType); 1151 if (CanonFrom.getLocalUnqualifiedType() 1152 == CanonTo.getLocalUnqualifiedType() && 1153 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1154 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) { 1155 FromType = ToType; 1156 CanonFrom = CanonTo; 1157 } 1158 } 1159 SCS.setToType(2, FromType); 1160 1161 // If we have not converted the argument type to the parameter type, 1162 // this is a bad conversion sequence. 1163 if (CanonFrom != CanonTo) 1164 return false; 1165 1166 return true; 1167} 1168 1169/// IsIntegralPromotion - Determines whether the conversion from the 1170/// expression From (whose potentially-adjusted type is FromType) to 1171/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1172/// sets PromotedType to the promoted type. 1173bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1174 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1175 // All integers are built-in. 1176 if (!To) { 1177 return false; 1178 } 1179 1180 // An rvalue of type char, signed char, unsigned char, short int, or 1181 // unsigned short int can be converted to an rvalue of type int if 1182 // int can represent all the values of the source type; otherwise, 1183 // the source rvalue can be converted to an rvalue of type unsigned 1184 // int (C++ 4.5p1). 1185 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1186 !FromType->isEnumeralType()) { 1187 if (// We can promote any signed, promotable integer type to an int 1188 (FromType->isSignedIntegerType() || 1189 // We can promote any unsigned integer type whose size is 1190 // less than int to an int. 1191 (!FromType->isSignedIntegerType() && 1192 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1193 return To->getKind() == BuiltinType::Int; 1194 } 1195 1196 return To->getKind() == BuiltinType::UInt; 1197 } 1198 1199 // C++0x [conv.prom]p3: 1200 // A prvalue of an unscoped enumeration type whose underlying type is not 1201 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1202 // following types that can represent all the values of the enumeration 1203 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1204 // unsigned int, long int, unsigned long int, long long int, or unsigned 1205 // long long int. If none of the types in that list can represent all the 1206 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1207 // type can be converted to an rvalue a prvalue of the extended integer type 1208 // with lowest integer conversion rank (4.13) greater than the rank of long 1209 // long in which all the values of the enumeration can be represented. If 1210 // there are two such extended types, the signed one is chosen. 1211 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1212 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1213 // provided for a scoped enumeration. 1214 if (FromEnumType->getDecl()->isScoped()) 1215 return false; 1216 1217 // We have already pre-calculated the promotion type, so this is trivial. 1218 if (ToType->isIntegerType() && 1219 !RequireCompleteType(From->getLocStart(), FromType, PDiag())) 1220 return Context.hasSameUnqualifiedType(ToType, 1221 FromEnumType->getDecl()->getPromotionType()); 1222 } 1223 1224 // C++0x [conv.prom]p2: 1225 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1226 // to an rvalue a prvalue of the first of the following types that can 1227 // represent all the values of its underlying type: int, unsigned int, 1228 // long int, unsigned long int, long long int, or unsigned long long int. 1229 // If none of the types in that list can represent all the values of its 1230 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1231 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1232 // type. 1233 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1234 ToType->isIntegerType()) { 1235 // Determine whether the type we're converting from is signed or 1236 // unsigned. 1237 bool FromIsSigned; 1238 uint64_t FromSize = Context.getTypeSize(FromType); 1239 1240 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now. 1241 FromIsSigned = true; 1242 1243 // The types we'll try to promote to, in the appropriate 1244 // order. Try each of these types. 1245 QualType PromoteTypes[6] = { 1246 Context.IntTy, Context.UnsignedIntTy, 1247 Context.LongTy, Context.UnsignedLongTy , 1248 Context.LongLongTy, Context.UnsignedLongLongTy 1249 }; 1250 for (int Idx = 0; Idx < 6; ++Idx) { 1251 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1252 if (FromSize < ToSize || 1253 (FromSize == ToSize && 1254 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1255 // We found the type that we can promote to. If this is the 1256 // type we wanted, we have a promotion. Otherwise, no 1257 // promotion. 1258 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1259 } 1260 } 1261 } 1262 1263 // An rvalue for an integral bit-field (9.6) can be converted to an 1264 // rvalue of type int if int can represent all the values of the 1265 // bit-field; otherwise, it can be converted to unsigned int if 1266 // unsigned int can represent all the values of the bit-field. If 1267 // the bit-field is larger yet, no integral promotion applies to 1268 // it. If the bit-field has an enumerated type, it is treated as any 1269 // other value of that type for promotion purposes (C++ 4.5p3). 1270 // FIXME: We should delay checking of bit-fields until we actually perform the 1271 // conversion. 1272 using llvm::APSInt; 1273 if (From) 1274 if (FieldDecl *MemberDecl = From->getBitField()) { 1275 APSInt BitWidth; 1276 if (FromType->isIntegralType(Context) && 1277 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1278 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1279 ToSize = Context.getTypeSize(ToType); 1280 1281 // Are we promoting to an int from a bitfield that fits in an int? 1282 if (BitWidth < ToSize || 1283 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1284 return To->getKind() == BuiltinType::Int; 1285 } 1286 1287 // Are we promoting to an unsigned int from an unsigned bitfield 1288 // that fits into an unsigned int? 1289 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1290 return To->getKind() == BuiltinType::UInt; 1291 } 1292 1293 return false; 1294 } 1295 } 1296 1297 // An rvalue of type bool can be converted to an rvalue of type int, 1298 // with false becoming zero and true becoming one (C++ 4.5p4). 1299 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1300 return true; 1301 } 1302 1303 return false; 1304} 1305 1306/// IsFloatingPointPromotion - Determines whether the conversion from 1307/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1308/// returns true and sets PromotedType to the promoted type. 1309bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1310 /// An rvalue of type float can be converted to an rvalue of type 1311 /// double. (C++ 4.6p1). 1312 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1313 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1314 if (FromBuiltin->getKind() == BuiltinType::Float && 1315 ToBuiltin->getKind() == BuiltinType::Double) 1316 return true; 1317 1318 // C99 6.3.1.5p1: 1319 // When a float is promoted to double or long double, or a 1320 // double is promoted to long double [...]. 1321 if (!getLangOptions().CPlusPlus && 1322 (FromBuiltin->getKind() == BuiltinType::Float || 1323 FromBuiltin->getKind() == BuiltinType::Double) && 1324 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1325 return true; 1326 } 1327 1328 return false; 1329} 1330 1331/// \brief Determine if a conversion is a complex promotion. 1332/// 1333/// A complex promotion is defined as a complex -> complex conversion 1334/// where the conversion between the underlying real types is a 1335/// floating-point or integral promotion. 1336bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1337 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1338 if (!FromComplex) 1339 return false; 1340 1341 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1342 if (!ToComplex) 1343 return false; 1344 1345 return IsFloatingPointPromotion(FromComplex->getElementType(), 1346 ToComplex->getElementType()) || 1347 IsIntegralPromotion(0, FromComplex->getElementType(), 1348 ToComplex->getElementType()); 1349} 1350 1351/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1352/// the pointer type FromPtr to a pointer to type ToPointee, with the 1353/// same type qualifiers as FromPtr has on its pointee type. ToType, 1354/// if non-empty, will be a pointer to ToType that may or may not have 1355/// the right set of qualifiers on its pointee. 1356static QualType 1357BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr, 1358 QualType ToPointee, QualType ToType, 1359 ASTContext &Context) { 1360 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType()); 1361 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1362 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1363 1364 // Exact qualifier match -> return the pointer type we're converting to. 1365 if (CanonToPointee.getLocalQualifiers() == Quals) { 1366 // ToType is exactly what we need. Return it. 1367 if (!ToType.isNull()) 1368 return ToType.getUnqualifiedType(); 1369 1370 // Build a pointer to ToPointee. It has the right qualifiers 1371 // already. 1372 return Context.getPointerType(ToPointee); 1373 } 1374 1375 // Just build a canonical type that has the right qualifiers. 1376 return Context.getPointerType( 1377 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), 1378 Quals)); 1379} 1380 1381/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from 1382/// the FromType, which is an objective-c pointer, to ToType, which may or may 1383/// not have the right set of qualifiers. 1384static QualType 1385BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType, 1386 QualType ToType, 1387 ASTContext &Context) { 1388 QualType CanonFromType = Context.getCanonicalType(FromType); 1389 QualType CanonToType = Context.getCanonicalType(ToType); 1390 Qualifiers Quals = CanonFromType.getQualifiers(); 1391 1392 // Exact qualifier match -> return the pointer type we're converting to. 1393 if (CanonToType.getLocalQualifiers() == Quals) 1394 return ToType; 1395 1396 // Just build a canonical type that has the right qualifiers. 1397 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals); 1398} 1399 1400static bool isNullPointerConstantForConversion(Expr *Expr, 1401 bool InOverloadResolution, 1402 ASTContext &Context) { 1403 // Handle value-dependent integral null pointer constants correctly. 1404 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1405 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1406 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1407 return !InOverloadResolution; 1408 1409 return Expr->isNullPointerConstant(Context, 1410 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1411 : Expr::NPC_ValueDependentIsNull); 1412} 1413 1414/// IsPointerConversion - Determines whether the conversion of the 1415/// expression From, which has the (possibly adjusted) type FromType, 1416/// can be converted to the type ToType via a pointer conversion (C++ 1417/// 4.10). If so, returns true and places the converted type (that 1418/// might differ from ToType in its cv-qualifiers at some level) into 1419/// ConvertedType. 1420/// 1421/// This routine also supports conversions to and from block pointers 1422/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1423/// pointers to interfaces. FIXME: Once we've determined the 1424/// appropriate overloading rules for Objective-C, we may want to 1425/// split the Objective-C checks into a different routine; however, 1426/// GCC seems to consider all of these conversions to be pointer 1427/// conversions, so for now they live here. IncompatibleObjC will be 1428/// set if the conversion is an allowed Objective-C conversion that 1429/// should result in a warning. 1430bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1431 bool InOverloadResolution, 1432 QualType& ConvertedType, 1433 bool &IncompatibleObjC) { 1434 IncompatibleObjC = false; 1435 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC)) 1436 return true; 1437 1438 // Conversion from a null pointer constant to any Objective-C pointer type. 1439 if (ToType->isObjCObjectPointerType() && 1440 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1441 ConvertedType = ToType; 1442 return true; 1443 } 1444 1445 // Blocks: Block pointers can be converted to void*. 1446 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1447 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1448 ConvertedType = ToType; 1449 return true; 1450 } 1451 // Blocks: A null pointer constant can be converted to a block 1452 // pointer type. 1453 if (ToType->isBlockPointerType() && 1454 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1455 ConvertedType = ToType; 1456 return true; 1457 } 1458 1459 // If the left-hand-side is nullptr_t, the right side can be a null 1460 // pointer constant. 1461 if (ToType->isNullPtrType() && 1462 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1463 ConvertedType = ToType; 1464 return true; 1465 } 1466 1467 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 1468 if (!ToTypePtr) 1469 return false; 1470 1471 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 1472 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1473 ConvertedType = ToType; 1474 return true; 1475 } 1476 1477 // Beyond this point, both types need to be pointers 1478 // , including objective-c pointers. 1479 QualType ToPointeeType = ToTypePtr->getPointeeType(); 1480 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) { 1481 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType, 1482 ToType, Context); 1483 return true; 1484 1485 } 1486 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 1487 if (!FromTypePtr) 1488 return false; 1489 1490 QualType FromPointeeType = FromTypePtr->getPointeeType(); 1491 1492 // If the unqualified pointee types are the same, this can't be a 1493 // pointer conversion, so don't do all of the work below. 1494 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 1495 return false; 1496 1497 // An rvalue of type "pointer to cv T," where T is an object type, 1498 // can be converted to an rvalue of type "pointer to cv void" (C++ 1499 // 4.10p2). 1500 if (FromPointeeType->isIncompleteOrObjectType() && 1501 ToPointeeType->isVoidType()) { 1502 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1503 ToPointeeType, 1504 ToType, Context); 1505 return true; 1506 } 1507 1508 // When we're overloading in C, we allow a special kind of pointer 1509 // conversion for compatible-but-not-identical pointee types. 1510 if (!getLangOptions().CPlusPlus && 1511 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 1512 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1513 ToPointeeType, 1514 ToType, Context); 1515 return true; 1516 } 1517 1518 // C++ [conv.ptr]p3: 1519 // 1520 // An rvalue of type "pointer to cv D," where D is a class type, 1521 // can be converted to an rvalue of type "pointer to cv B," where 1522 // B is a base class (clause 10) of D. If B is an inaccessible 1523 // (clause 11) or ambiguous (10.2) base class of D, a program that 1524 // necessitates this conversion is ill-formed. The result of the 1525 // conversion is a pointer to the base class sub-object of the 1526 // derived class object. The null pointer value is converted to 1527 // the null pointer value of the destination type. 1528 // 1529 // Note that we do not check for ambiguity or inaccessibility 1530 // here. That is handled by CheckPointerConversion. 1531 if (getLangOptions().CPlusPlus && 1532 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 1533 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 1534 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) && 1535 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 1536 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1537 ToPointeeType, 1538 ToType, Context); 1539 return true; 1540 } 1541 1542 return false; 1543} 1544 1545/// isObjCPointerConversion - Determines whether this is an 1546/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 1547/// with the same arguments and return values. 1548bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 1549 QualType& ConvertedType, 1550 bool &IncompatibleObjC) { 1551 if (!getLangOptions().ObjC1) 1552 return false; 1553 1554 // First, we handle all conversions on ObjC object pointer types. 1555 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>(); 1556 const ObjCObjectPointerType *FromObjCPtr = 1557 FromType->getAs<ObjCObjectPointerType>(); 1558 1559 if (ToObjCPtr && FromObjCPtr) { 1560 // Objective C++: We're able to convert between "id" or "Class" and a 1561 // pointer to any interface (in both directions). 1562 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 1563 ConvertedType = ToType; 1564 return true; 1565 } 1566 // Conversions with Objective-C's id<...>. 1567 if ((FromObjCPtr->isObjCQualifiedIdType() || 1568 ToObjCPtr->isObjCQualifiedIdType()) && 1569 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 1570 /*compare=*/false)) { 1571 ConvertedType = ToType; 1572 return true; 1573 } 1574 // Objective C++: We're able to convert from a pointer to an 1575 // interface to a pointer to a different interface. 1576 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 1577 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 1578 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 1579 if (getLangOptions().CPlusPlus && LHS && RHS && 1580 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 1581 FromObjCPtr->getPointeeType())) 1582 return false; 1583 ConvertedType = ToType; 1584 return true; 1585 } 1586 1587 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 1588 // Okay: this is some kind of implicit downcast of Objective-C 1589 // interfaces, which is permitted. However, we're going to 1590 // complain about it. 1591 IncompatibleObjC = true; 1592 ConvertedType = FromType; 1593 return true; 1594 } 1595 } 1596 // Beyond this point, both types need to be C pointers or block pointers. 1597 QualType ToPointeeType; 1598 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 1599 ToPointeeType = ToCPtr->getPointeeType(); 1600 else if (const BlockPointerType *ToBlockPtr = 1601 ToType->getAs<BlockPointerType>()) { 1602 // Objective C++: We're able to convert from a pointer to any object 1603 // to a block pointer type. 1604 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 1605 ConvertedType = ToType; 1606 return true; 1607 } 1608 ToPointeeType = ToBlockPtr->getPointeeType(); 1609 } 1610 else if (FromType->getAs<BlockPointerType>() && 1611 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 1612 // Objective C++: We're able to convert from a block pointer type to a 1613 // pointer to any object. 1614 ConvertedType = ToType; 1615 return true; 1616 } 1617 else 1618 return false; 1619 1620 QualType FromPointeeType; 1621 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 1622 FromPointeeType = FromCPtr->getPointeeType(); 1623 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>()) 1624 FromPointeeType = FromBlockPtr->getPointeeType(); 1625 else 1626 return false; 1627 1628 // If we have pointers to pointers, recursively check whether this 1629 // is an Objective-C conversion. 1630 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 1631 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 1632 IncompatibleObjC)) { 1633 // We always complain about this conversion. 1634 IncompatibleObjC = true; 1635 ConvertedType = ToType; 1636 return true; 1637 } 1638 // Allow conversion of pointee being objective-c pointer to another one; 1639 // as in I* to id. 1640 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 1641 ToPointeeType->getAs<ObjCObjectPointerType>() && 1642 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 1643 IncompatibleObjC)) { 1644 ConvertedType = ToType; 1645 return true; 1646 } 1647 1648 // If we have pointers to functions or blocks, check whether the only 1649 // differences in the argument and result types are in Objective-C 1650 // pointer conversions. If so, we permit the conversion (but 1651 // complain about it). 1652 const FunctionProtoType *FromFunctionType 1653 = FromPointeeType->getAs<FunctionProtoType>(); 1654 const FunctionProtoType *ToFunctionType 1655 = ToPointeeType->getAs<FunctionProtoType>(); 1656 if (FromFunctionType && ToFunctionType) { 1657 // If the function types are exactly the same, this isn't an 1658 // Objective-C pointer conversion. 1659 if (Context.getCanonicalType(FromPointeeType) 1660 == Context.getCanonicalType(ToPointeeType)) 1661 return false; 1662 1663 // Perform the quick checks that will tell us whether these 1664 // function types are obviously different. 1665 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 1666 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 1667 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 1668 return false; 1669 1670 bool HasObjCConversion = false; 1671 if (Context.getCanonicalType(FromFunctionType->getResultType()) 1672 == Context.getCanonicalType(ToFunctionType->getResultType())) { 1673 // Okay, the types match exactly. Nothing to do. 1674 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 1675 ToFunctionType->getResultType(), 1676 ConvertedType, IncompatibleObjC)) { 1677 // Okay, we have an Objective-C pointer conversion. 1678 HasObjCConversion = true; 1679 } else { 1680 // Function types are too different. Abort. 1681 return false; 1682 } 1683 1684 // Check argument types. 1685 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 1686 ArgIdx != NumArgs; ++ArgIdx) { 1687 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 1688 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 1689 if (Context.getCanonicalType(FromArgType) 1690 == Context.getCanonicalType(ToArgType)) { 1691 // Okay, the types match exactly. Nothing to do. 1692 } else if (isObjCPointerConversion(FromArgType, ToArgType, 1693 ConvertedType, IncompatibleObjC)) { 1694 // Okay, we have an Objective-C pointer conversion. 1695 HasObjCConversion = true; 1696 } else { 1697 // Argument types are too different. Abort. 1698 return false; 1699 } 1700 } 1701 1702 if (HasObjCConversion) { 1703 // We had an Objective-C conversion. Allow this pointer 1704 // conversion, but complain about it. 1705 ConvertedType = ToType; 1706 IncompatibleObjC = true; 1707 return true; 1708 } 1709 } 1710 1711 return false; 1712} 1713 1714/// FunctionArgTypesAreEqual - This routine checks two function proto types 1715/// for equlity of their argument types. Caller has already checked that 1716/// they have same number of arguments. This routine assumes that Objective-C 1717/// pointer types which only differ in their protocol qualifiers are equal. 1718bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType, 1719 FunctionProtoType* NewType){ 1720 if (!getLangOptions().ObjC1) 1721 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(), 1722 NewType->arg_type_begin()); 1723 1724 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 1725 N = NewType->arg_type_begin(), 1726 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 1727 QualType ToType = (*O); 1728 QualType FromType = (*N); 1729 if (ToType != FromType) { 1730 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 1731 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 1732 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 1733 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 1734 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 1735 PTFr->getPointeeType()->isObjCQualifiedClassType())) 1736 continue; 1737 } 1738 else if (const ObjCObjectPointerType *PTTo = 1739 ToType->getAs<ObjCObjectPointerType>()) { 1740 if (const ObjCObjectPointerType *PTFr = 1741 FromType->getAs<ObjCObjectPointerType>()) 1742 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl()) 1743 continue; 1744 } 1745 return false; 1746 } 1747 } 1748 return true; 1749} 1750 1751/// CheckPointerConversion - Check the pointer conversion from the 1752/// expression From to the type ToType. This routine checks for 1753/// ambiguous or inaccessible derived-to-base pointer 1754/// conversions for which IsPointerConversion has already returned 1755/// true. It returns true and produces a diagnostic if there was an 1756/// error, or returns false otherwise. 1757bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 1758 CastKind &Kind, 1759 CXXCastPath& BasePath, 1760 bool IgnoreBaseAccess) { 1761 QualType FromType = From->getType(); 1762 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 1763 1764 if (CXXBoolLiteralExpr* LitBool 1765 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens())) 1766 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false) 1767 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false) 1768 << ToType; 1769 1770 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) 1771 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 1772 QualType FromPointeeType = FromPtrType->getPointeeType(), 1773 ToPointeeType = ToPtrType->getPointeeType(); 1774 1775 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 1776 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 1777 // We must have a derived-to-base conversion. Check an 1778 // ambiguous or inaccessible conversion. 1779 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 1780 From->getExprLoc(), 1781 From->getSourceRange(), &BasePath, 1782 IgnoreBaseAccess)) 1783 return true; 1784 1785 // The conversion was successful. 1786 Kind = CK_DerivedToBase; 1787 } 1788 } 1789 if (const ObjCObjectPointerType *FromPtrType = 1790 FromType->getAs<ObjCObjectPointerType>()) 1791 if (const ObjCObjectPointerType *ToPtrType = 1792 ToType->getAs<ObjCObjectPointerType>()) { 1793 // Objective-C++ conversions are always okay. 1794 // FIXME: We should have a different class of conversions for the 1795 // Objective-C++ implicit conversions. 1796 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 1797 return false; 1798 1799 } 1800 return false; 1801} 1802 1803/// IsMemberPointerConversion - Determines whether the conversion of the 1804/// expression From, which has the (possibly adjusted) type FromType, can be 1805/// converted to the type ToType via a member pointer conversion (C++ 4.11). 1806/// If so, returns true and places the converted type (that might differ from 1807/// ToType in its cv-qualifiers at some level) into ConvertedType. 1808bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 1809 QualType ToType, 1810 bool InOverloadResolution, 1811 QualType &ConvertedType) { 1812 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 1813 if (!ToTypePtr) 1814 return false; 1815 1816 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 1817 if (From->isNullPointerConstant(Context, 1818 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1819 : Expr::NPC_ValueDependentIsNull)) { 1820 ConvertedType = ToType; 1821 return true; 1822 } 1823 1824 // Otherwise, both types have to be member pointers. 1825 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 1826 if (!FromTypePtr) 1827 return false; 1828 1829 // A pointer to member of B can be converted to a pointer to member of D, 1830 // where D is derived from B (C++ 4.11p2). 1831 QualType FromClass(FromTypePtr->getClass(), 0); 1832 QualType ToClass(ToTypePtr->getClass(), 0); 1833 // FIXME: What happens when these are dependent? Is this function even called? 1834 1835 if (IsDerivedFrom(ToClass, FromClass)) { 1836 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 1837 ToClass.getTypePtr()); 1838 return true; 1839 } 1840 1841 return false; 1842} 1843 1844/// CheckMemberPointerConversion - Check the member pointer conversion from the 1845/// expression From to the type ToType. This routine checks for ambiguous or 1846/// virtual or inaccessible base-to-derived member pointer conversions 1847/// for which IsMemberPointerConversion has already returned true. It returns 1848/// true and produces a diagnostic if there was an error, or returns false 1849/// otherwise. 1850bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 1851 CastKind &Kind, 1852 CXXCastPath &BasePath, 1853 bool IgnoreBaseAccess) { 1854 QualType FromType = From->getType(); 1855 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 1856 if (!FromPtrType) { 1857 // This must be a null pointer to member pointer conversion 1858 assert(From->isNullPointerConstant(Context, 1859 Expr::NPC_ValueDependentIsNull) && 1860 "Expr must be null pointer constant!"); 1861 Kind = CK_NullToMemberPointer; 1862 return false; 1863 } 1864 1865 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 1866 assert(ToPtrType && "No member pointer cast has a target type " 1867 "that is not a member pointer."); 1868 1869 QualType FromClass = QualType(FromPtrType->getClass(), 0); 1870 QualType ToClass = QualType(ToPtrType->getClass(), 0); 1871 1872 // FIXME: What about dependent types? 1873 assert(FromClass->isRecordType() && "Pointer into non-class."); 1874 assert(ToClass->isRecordType() && "Pointer into non-class."); 1875 1876 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1877 /*DetectVirtual=*/true); 1878 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 1879 assert(DerivationOkay && 1880 "Should not have been called if derivation isn't OK."); 1881 (void)DerivationOkay; 1882 1883 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 1884 getUnqualifiedType())) { 1885 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1886 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 1887 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 1888 return true; 1889 } 1890 1891 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 1892 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 1893 << FromClass << ToClass << QualType(VBase, 0) 1894 << From->getSourceRange(); 1895 return true; 1896 } 1897 1898 if (!IgnoreBaseAccess) 1899 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 1900 Paths.front(), 1901 diag::err_downcast_from_inaccessible_base); 1902 1903 // Must be a base to derived member conversion. 1904 BuildBasePathArray(Paths, BasePath); 1905 Kind = CK_BaseToDerivedMemberPointer; 1906 return false; 1907} 1908 1909/// IsQualificationConversion - Determines whether the conversion from 1910/// an rvalue of type FromType to ToType is a qualification conversion 1911/// (C++ 4.4). 1912bool 1913Sema::IsQualificationConversion(QualType FromType, QualType ToType) { 1914 FromType = Context.getCanonicalType(FromType); 1915 ToType = Context.getCanonicalType(ToType); 1916 1917 // If FromType and ToType are the same type, this is not a 1918 // qualification conversion. 1919 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 1920 return false; 1921 1922 // (C++ 4.4p4): 1923 // A conversion can add cv-qualifiers at levels other than the first 1924 // in multi-level pointers, subject to the following rules: [...] 1925 bool PreviousToQualsIncludeConst = true; 1926 bool UnwrappedAnyPointer = false; 1927 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 1928 // Within each iteration of the loop, we check the qualifiers to 1929 // determine if this still looks like a qualification 1930 // conversion. Then, if all is well, we unwrap one more level of 1931 // pointers or pointers-to-members and do it all again 1932 // until there are no more pointers or pointers-to-members left to 1933 // unwrap. 1934 UnwrappedAnyPointer = true; 1935 1936 // -- for every j > 0, if const is in cv 1,j then const is in cv 1937 // 2,j, and similarly for volatile. 1938 if (!ToType.isAtLeastAsQualifiedAs(FromType)) 1939 return false; 1940 1941 // -- if the cv 1,j and cv 2,j are different, then const is in 1942 // every cv for 0 < k < j. 1943 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers() 1944 && !PreviousToQualsIncludeConst) 1945 return false; 1946 1947 // Keep track of whether all prior cv-qualifiers in the "to" type 1948 // include const. 1949 PreviousToQualsIncludeConst 1950 = PreviousToQualsIncludeConst && ToType.isConstQualified(); 1951 } 1952 1953 // We are left with FromType and ToType being the pointee types 1954 // after unwrapping the original FromType and ToType the same number 1955 // of types. If we unwrapped any pointers, and if FromType and 1956 // ToType have the same unqualified type (since we checked 1957 // qualifiers above), then this is a qualification conversion. 1958 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 1959} 1960 1961/// Determines whether there is a user-defined conversion sequence 1962/// (C++ [over.ics.user]) that converts expression From to the type 1963/// ToType. If such a conversion exists, User will contain the 1964/// user-defined conversion sequence that performs such a conversion 1965/// and this routine will return true. Otherwise, this routine returns 1966/// false and User is unspecified. 1967/// 1968/// \param AllowExplicit true if the conversion should consider C++0x 1969/// "explicit" conversion functions as well as non-explicit conversion 1970/// functions (C++0x [class.conv.fct]p2). 1971static OverloadingResult 1972IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1973 UserDefinedConversionSequence& User, 1974 OverloadCandidateSet& CandidateSet, 1975 bool AllowExplicit) { 1976 // Whether we will only visit constructors. 1977 bool ConstructorsOnly = false; 1978 1979 // If the type we are conversion to is a class type, enumerate its 1980 // constructors. 1981 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 1982 // C++ [over.match.ctor]p1: 1983 // When objects of class type are direct-initialized (8.5), or 1984 // copy-initialized from an expression of the same or a 1985 // derived class type (8.5), overload resolution selects the 1986 // constructor. [...] For copy-initialization, the candidate 1987 // functions are all the converting constructors (12.3.1) of 1988 // that class. The argument list is the expression-list within 1989 // the parentheses of the initializer. 1990 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 1991 (From->getType()->getAs<RecordType>() && 1992 S.IsDerivedFrom(From->getType(), ToType))) 1993 ConstructorsOnly = true; 1994 1995 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) { 1996 // We're not going to find any constructors. 1997 } else if (CXXRecordDecl *ToRecordDecl 1998 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 1999 DeclContext::lookup_iterator Con, ConEnd; 2000 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl); 2001 Con != ConEnd; ++Con) { 2002 NamedDecl *D = *Con; 2003 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2004 2005 // Find the constructor (which may be a template). 2006 CXXConstructorDecl *Constructor = 0; 2007 FunctionTemplateDecl *ConstructorTmpl 2008 = dyn_cast<FunctionTemplateDecl>(D); 2009 if (ConstructorTmpl) 2010 Constructor 2011 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2012 else 2013 Constructor = cast<CXXConstructorDecl>(D); 2014 2015 if (!Constructor->isInvalidDecl() && 2016 Constructor->isConvertingConstructor(AllowExplicit)) { 2017 if (ConstructorTmpl) 2018 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2019 /*ExplicitArgs*/ 0, 2020 &From, 1, CandidateSet, 2021 /*SuppressUserConversions=*/ 2022 !ConstructorsOnly); 2023 else 2024 // Allow one user-defined conversion when user specifies a 2025 // From->ToType conversion via an static cast (c-style, etc). 2026 S.AddOverloadCandidate(Constructor, FoundDecl, 2027 &From, 1, CandidateSet, 2028 /*SuppressUserConversions=*/ 2029 !ConstructorsOnly); 2030 } 2031 } 2032 } 2033 } 2034 2035 // Enumerate conversion functions, if we're allowed to. 2036 if (ConstructorsOnly) { 2037 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 2038 S.PDiag(0) << From->getSourceRange())) { 2039 // No conversion functions from incomplete types. 2040 } else if (const RecordType *FromRecordType 2041 = From->getType()->getAs<RecordType>()) { 2042 if (CXXRecordDecl *FromRecordDecl 2043 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 2044 // Add all of the conversion functions as candidates. 2045 const UnresolvedSetImpl *Conversions 2046 = FromRecordDecl->getVisibleConversionFunctions(); 2047 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 2048 E = Conversions->end(); I != E; ++I) { 2049 DeclAccessPair FoundDecl = I.getPair(); 2050 NamedDecl *D = FoundDecl.getDecl(); 2051 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 2052 if (isa<UsingShadowDecl>(D)) 2053 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2054 2055 CXXConversionDecl *Conv; 2056 FunctionTemplateDecl *ConvTemplate; 2057 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 2058 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2059 else 2060 Conv = cast<CXXConversionDecl>(D); 2061 2062 if (AllowExplicit || !Conv->isExplicit()) { 2063 if (ConvTemplate) 2064 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 2065 ActingContext, From, ToType, 2066 CandidateSet); 2067 else 2068 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 2069 From, ToType, CandidateSet); 2070 } 2071 } 2072 } 2073 } 2074 2075 OverloadCandidateSet::iterator Best; 2076 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2077 case OR_Success: 2078 // Record the standard conversion we used and the conversion function. 2079 if (CXXConstructorDecl *Constructor 2080 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 2081 // C++ [over.ics.user]p1: 2082 // If the user-defined conversion is specified by a 2083 // constructor (12.3.1), the initial standard conversion 2084 // sequence converts the source type to the type required by 2085 // the argument of the constructor. 2086 // 2087 QualType ThisType = Constructor->getThisType(S.Context); 2088 if (Best->Conversions[0].isEllipsis()) 2089 User.EllipsisConversion = true; 2090 else { 2091 User.Before = Best->Conversions[0].Standard; 2092 User.EllipsisConversion = false; 2093 } 2094 User.ConversionFunction = Constructor; 2095 User.After.setAsIdentityConversion(); 2096 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2097 User.After.setAllToTypes(ToType); 2098 return OR_Success; 2099 } else if (CXXConversionDecl *Conversion 2100 = dyn_cast<CXXConversionDecl>(Best->Function)) { 2101 // C++ [over.ics.user]p1: 2102 // 2103 // [...] If the user-defined conversion is specified by a 2104 // conversion function (12.3.2), the initial standard 2105 // conversion sequence converts the source type to the 2106 // implicit object parameter of the conversion function. 2107 User.Before = Best->Conversions[0].Standard; 2108 User.ConversionFunction = Conversion; 2109 User.EllipsisConversion = false; 2110 2111 // C++ [over.ics.user]p2: 2112 // The second standard conversion sequence converts the 2113 // result of the user-defined conversion to the target type 2114 // for the sequence. Since an implicit conversion sequence 2115 // is an initialization, the special rules for 2116 // initialization by user-defined conversion apply when 2117 // selecting the best user-defined conversion for a 2118 // user-defined conversion sequence (see 13.3.3 and 2119 // 13.3.3.1). 2120 User.After = Best->FinalConversion; 2121 return OR_Success; 2122 } else { 2123 llvm_unreachable("Not a constructor or conversion function?"); 2124 return OR_No_Viable_Function; 2125 } 2126 2127 case OR_No_Viable_Function: 2128 return OR_No_Viable_Function; 2129 case OR_Deleted: 2130 // No conversion here! We're done. 2131 return OR_Deleted; 2132 2133 case OR_Ambiguous: 2134 return OR_Ambiguous; 2135 } 2136 2137 return OR_No_Viable_Function; 2138} 2139 2140bool 2141Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 2142 ImplicitConversionSequence ICS; 2143 OverloadCandidateSet CandidateSet(From->getExprLoc()); 2144 OverloadingResult OvResult = 2145 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 2146 CandidateSet, false); 2147 if (OvResult == OR_Ambiguous) 2148 Diag(From->getSourceRange().getBegin(), 2149 diag::err_typecheck_ambiguous_condition) 2150 << From->getType() << ToType << From->getSourceRange(); 2151 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 2152 Diag(From->getSourceRange().getBegin(), 2153 diag::err_typecheck_nonviable_condition) 2154 << From->getType() << ToType << From->getSourceRange(); 2155 else 2156 return false; 2157 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1); 2158 return true; 2159} 2160 2161/// CompareImplicitConversionSequences - Compare two implicit 2162/// conversion sequences to determine whether one is better than the 2163/// other or if they are indistinguishable (C++ 13.3.3.2). 2164static ImplicitConversionSequence::CompareKind 2165CompareImplicitConversionSequences(Sema &S, 2166 const ImplicitConversionSequence& ICS1, 2167 const ImplicitConversionSequence& ICS2) 2168{ 2169 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 2170 // conversion sequences (as defined in 13.3.3.1) 2171 // -- a standard conversion sequence (13.3.3.1.1) is a better 2172 // conversion sequence than a user-defined conversion sequence or 2173 // an ellipsis conversion sequence, and 2174 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 2175 // conversion sequence than an ellipsis conversion sequence 2176 // (13.3.3.1.3). 2177 // 2178 // C++0x [over.best.ics]p10: 2179 // For the purpose of ranking implicit conversion sequences as 2180 // described in 13.3.3.2, the ambiguous conversion sequence is 2181 // treated as a user-defined sequence that is indistinguishable 2182 // from any other user-defined conversion sequence. 2183 if (ICS1.getKindRank() < ICS2.getKindRank()) 2184 return ImplicitConversionSequence::Better; 2185 else if (ICS2.getKindRank() < ICS1.getKindRank()) 2186 return ImplicitConversionSequence::Worse; 2187 2188 // The following checks require both conversion sequences to be of 2189 // the same kind. 2190 if (ICS1.getKind() != ICS2.getKind()) 2191 return ImplicitConversionSequence::Indistinguishable; 2192 2193 // Two implicit conversion sequences of the same form are 2194 // indistinguishable conversion sequences unless one of the 2195 // following rules apply: (C++ 13.3.3.2p3): 2196 if (ICS1.isStandard()) 2197 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard); 2198 else if (ICS1.isUserDefined()) { 2199 // User-defined conversion sequence U1 is a better conversion 2200 // sequence than another user-defined conversion sequence U2 if 2201 // they contain the same user-defined conversion function or 2202 // constructor and if the second standard conversion sequence of 2203 // U1 is better than the second standard conversion sequence of 2204 // U2 (C++ 13.3.3.2p3). 2205 if (ICS1.UserDefined.ConversionFunction == 2206 ICS2.UserDefined.ConversionFunction) 2207 return CompareStandardConversionSequences(S, 2208 ICS1.UserDefined.After, 2209 ICS2.UserDefined.After); 2210 } 2211 2212 return ImplicitConversionSequence::Indistinguishable; 2213} 2214 2215static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 2216 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 2217 Qualifiers Quals; 2218 T1 = Context.getUnqualifiedArrayType(T1, Quals); 2219 T2 = Context.getUnqualifiedArrayType(T2, Quals); 2220 } 2221 2222 return Context.hasSameUnqualifiedType(T1, T2); 2223} 2224 2225// Per 13.3.3.2p3, compare the given standard conversion sequences to 2226// determine if one is a proper subset of the other. 2227static ImplicitConversionSequence::CompareKind 2228compareStandardConversionSubsets(ASTContext &Context, 2229 const StandardConversionSequence& SCS1, 2230 const StandardConversionSequence& SCS2) { 2231 ImplicitConversionSequence::CompareKind Result 2232 = ImplicitConversionSequence::Indistinguishable; 2233 2234 // the identity conversion sequence is considered to be a subsequence of 2235 // any non-identity conversion sequence 2236 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) { 2237 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 2238 return ImplicitConversionSequence::Better; 2239 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 2240 return ImplicitConversionSequence::Worse; 2241 } 2242 2243 if (SCS1.Second != SCS2.Second) { 2244 if (SCS1.Second == ICK_Identity) 2245 Result = ImplicitConversionSequence::Better; 2246 else if (SCS2.Second == ICK_Identity) 2247 Result = ImplicitConversionSequence::Worse; 2248 else 2249 return ImplicitConversionSequence::Indistinguishable; 2250 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 2251 return ImplicitConversionSequence::Indistinguishable; 2252 2253 if (SCS1.Third == SCS2.Third) { 2254 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 2255 : ImplicitConversionSequence::Indistinguishable; 2256 } 2257 2258 if (SCS1.Third == ICK_Identity) 2259 return Result == ImplicitConversionSequence::Worse 2260 ? ImplicitConversionSequence::Indistinguishable 2261 : ImplicitConversionSequence::Better; 2262 2263 if (SCS2.Third == ICK_Identity) 2264 return Result == ImplicitConversionSequence::Better 2265 ? ImplicitConversionSequence::Indistinguishable 2266 : ImplicitConversionSequence::Worse; 2267 2268 return ImplicitConversionSequence::Indistinguishable; 2269} 2270 2271/// CompareStandardConversionSequences - Compare two standard 2272/// conversion sequences to determine whether one is better than the 2273/// other or if they are indistinguishable (C++ 13.3.3.2p3). 2274static ImplicitConversionSequence::CompareKind 2275CompareStandardConversionSequences(Sema &S, 2276 const StandardConversionSequence& SCS1, 2277 const StandardConversionSequence& SCS2) 2278{ 2279 // Standard conversion sequence S1 is a better conversion sequence 2280 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 2281 2282 // -- S1 is a proper subsequence of S2 (comparing the conversion 2283 // sequences in the canonical form defined by 13.3.3.1.1, 2284 // excluding any Lvalue Transformation; the identity conversion 2285 // sequence is considered to be a subsequence of any 2286 // non-identity conversion sequence) or, if not that, 2287 if (ImplicitConversionSequence::CompareKind CK 2288 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 2289 return CK; 2290 2291 // -- the rank of S1 is better than the rank of S2 (by the rules 2292 // defined below), or, if not that, 2293 ImplicitConversionRank Rank1 = SCS1.getRank(); 2294 ImplicitConversionRank Rank2 = SCS2.getRank(); 2295 if (Rank1 < Rank2) 2296 return ImplicitConversionSequence::Better; 2297 else if (Rank2 < Rank1) 2298 return ImplicitConversionSequence::Worse; 2299 2300 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 2301 // are indistinguishable unless one of the following rules 2302 // applies: 2303 2304 // A conversion that is not a conversion of a pointer, or 2305 // pointer to member, to bool is better than another conversion 2306 // that is such a conversion. 2307 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 2308 return SCS2.isPointerConversionToBool() 2309 ? ImplicitConversionSequence::Better 2310 : ImplicitConversionSequence::Worse; 2311 2312 // C++ [over.ics.rank]p4b2: 2313 // 2314 // If class B is derived directly or indirectly from class A, 2315 // conversion of B* to A* is better than conversion of B* to 2316 // void*, and conversion of A* to void* is better than conversion 2317 // of B* to void*. 2318 bool SCS1ConvertsToVoid 2319 = SCS1.isPointerConversionToVoidPointer(S.Context); 2320 bool SCS2ConvertsToVoid 2321 = SCS2.isPointerConversionToVoidPointer(S.Context); 2322 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 2323 // Exactly one of the conversion sequences is a conversion to 2324 // a void pointer; it's the worse conversion. 2325 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 2326 : ImplicitConversionSequence::Worse; 2327 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 2328 // Neither conversion sequence converts to a void pointer; compare 2329 // their derived-to-base conversions. 2330 if (ImplicitConversionSequence::CompareKind DerivedCK 2331 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 2332 return DerivedCK; 2333 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) { 2334 // Both conversion sequences are conversions to void 2335 // pointers. Compare the source types to determine if there's an 2336 // inheritance relationship in their sources. 2337 QualType FromType1 = SCS1.getFromType(); 2338 QualType FromType2 = SCS2.getFromType(); 2339 2340 // Adjust the types we're converting from via the array-to-pointer 2341 // conversion, if we need to. 2342 if (SCS1.First == ICK_Array_To_Pointer) 2343 FromType1 = S.Context.getArrayDecayedType(FromType1); 2344 if (SCS2.First == ICK_Array_To_Pointer) 2345 FromType2 = S.Context.getArrayDecayedType(FromType2); 2346 2347 QualType FromPointee1 2348 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2349 QualType FromPointee2 2350 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2351 2352 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 2353 return ImplicitConversionSequence::Better; 2354 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 2355 return ImplicitConversionSequence::Worse; 2356 2357 // Objective-C++: If one interface is more specific than the 2358 // other, it is the better one. 2359 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>(); 2360 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>(); 2361 if (FromIface1 && FromIface1) { 2362 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 2363 return ImplicitConversionSequence::Better; 2364 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 2365 return ImplicitConversionSequence::Worse; 2366 } 2367 } 2368 2369 // Compare based on qualification conversions (C++ 13.3.3.2p3, 2370 // bullet 3). 2371 if (ImplicitConversionSequence::CompareKind QualCK 2372 = CompareQualificationConversions(S, SCS1, SCS2)) 2373 return QualCK; 2374 2375 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 2376 // C++0x [over.ics.rank]p3b4: 2377 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 2378 // implicit object parameter of a non-static member function declared 2379 // without a ref-qualifier, and S1 binds an rvalue reference to an 2380 // rvalue and S2 binds an lvalue reference. 2381 // FIXME: We don't know if we're dealing with the implicit object parameter, 2382 // or if the member function in this case has a ref qualifier. 2383 // (Of course, we don't have ref qualifiers yet.) 2384 if (SCS1.RRefBinding != SCS2.RRefBinding) 2385 return SCS1.RRefBinding ? ImplicitConversionSequence::Better 2386 : ImplicitConversionSequence::Worse; 2387 2388 // C++ [over.ics.rank]p3b4: 2389 // -- S1 and S2 are reference bindings (8.5.3), and the types to 2390 // which the references refer are the same type except for 2391 // top-level cv-qualifiers, and the type to which the reference 2392 // initialized by S2 refers is more cv-qualified than the type 2393 // to which the reference initialized by S1 refers. 2394 QualType T1 = SCS1.getToType(2); 2395 QualType T2 = SCS2.getToType(2); 2396 T1 = S.Context.getCanonicalType(T1); 2397 T2 = S.Context.getCanonicalType(T2); 2398 Qualifiers T1Quals, T2Quals; 2399 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 2400 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 2401 if (UnqualT1 == UnqualT2) { 2402 // If the type is an array type, promote the element qualifiers to the type 2403 // for comparison. 2404 if (isa<ArrayType>(T1) && T1Quals) 2405 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 2406 if (isa<ArrayType>(T2) && T2Quals) 2407 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 2408 if (T2.isMoreQualifiedThan(T1)) 2409 return ImplicitConversionSequence::Better; 2410 else if (T1.isMoreQualifiedThan(T2)) 2411 return ImplicitConversionSequence::Worse; 2412 } 2413 } 2414 2415 return ImplicitConversionSequence::Indistinguishable; 2416} 2417 2418/// CompareQualificationConversions - Compares two standard conversion 2419/// sequences to determine whether they can be ranked based on their 2420/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 2421ImplicitConversionSequence::CompareKind 2422CompareQualificationConversions(Sema &S, 2423 const StandardConversionSequence& SCS1, 2424 const StandardConversionSequence& SCS2) { 2425 // C++ 13.3.3.2p3: 2426 // -- S1 and S2 differ only in their qualification conversion and 2427 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 2428 // cv-qualification signature of type T1 is a proper subset of 2429 // the cv-qualification signature of type T2, and S1 is not the 2430 // deprecated string literal array-to-pointer conversion (4.2). 2431 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 2432 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 2433 return ImplicitConversionSequence::Indistinguishable; 2434 2435 // FIXME: the example in the standard doesn't use a qualification 2436 // conversion (!) 2437 QualType T1 = SCS1.getToType(2); 2438 QualType T2 = SCS2.getToType(2); 2439 T1 = S.Context.getCanonicalType(T1); 2440 T2 = S.Context.getCanonicalType(T2); 2441 Qualifiers T1Quals, T2Quals; 2442 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 2443 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 2444 2445 // If the types are the same, we won't learn anything by unwrapped 2446 // them. 2447 if (UnqualT1 == UnqualT2) 2448 return ImplicitConversionSequence::Indistinguishable; 2449 2450 // If the type is an array type, promote the element qualifiers to the type 2451 // for comparison. 2452 if (isa<ArrayType>(T1) && T1Quals) 2453 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 2454 if (isa<ArrayType>(T2) && T2Quals) 2455 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 2456 2457 ImplicitConversionSequence::CompareKind Result 2458 = ImplicitConversionSequence::Indistinguishable; 2459 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 2460 // Within each iteration of the loop, we check the qualifiers to 2461 // determine if this still looks like a qualification 2462 // conversion. Then, if all is well, we unwrap one more level of 2463 // pointers or pointers-to-members and do it all again 2464 // until there are no more pointers or pointers-to-members left 2465 // to unwrap. This essentially mimics what 2466 // IsQualificationConversion does, but here we're checking for a 2467 // strict subset of qualifiers. 2468 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 2469 // The qualifiers are the same, so this doesn't tell us anything 2470 // about how the sequences rank. 2471 ; 2472 else if (T2.isMoreQualifiedThan(T1)) { 2473 // T1 has fewer qualifiers, so it could be the better sequence. 2474 if (Result == ImplicitConversionSequence::Worse) 2475 // Neither has qualifiers that are a subset of the other's 2476 // qualifiers. 2477 return ImplicitConversionSequence::Indistinguishable; 2478 2479 Result = ImplicitConversionSequence::Better; 2480 } else if (T1.isMoreQualifiedThan(T2)) { 2481 // T2 has fewer qualifiers, so it could be the better sequence. 2482 if (Result == ImplicitConversionSequence::Better) 2483 // Neither has qualifiers that are a subset of the other's 2484 // qualifiers. 2485 return ImplicitConversionSequence::Indistinguishable; 2486 2487 Result = ImplicitConversionSequence::Worse; 2488 } else { 2489 // Qualifiers are disjoint. 2490 return ImplicitConversionSequence::Indistinguishable; 2491 } 2492 2493 // If the types after this point are equivalent, we're done. 2494 if (S.Context.hasSameUnqualifiedType(T1, T2)) 2495 break; 2496 } 2497 2498 // Check that the winning standard conversion sequence isn't using 2499 // the deprecated string literal array to pointer conversion. 2500 switch (Result) { 2501 case ImplicitConversionSequence::Better: 2502 if (SCS1.DeprecatedStringLiteralToCharPtr) 2503 Result = ImplicitConversionSequence::Indistinguishable; 2504 break; 2505 2506 case ImplicitConversionSequence::Indistinguishable: 2507 break; 2508 2509 case ImplicitConversionSequence::Worse: 2510 if (SCS2.DeprecatedStringLiteralToCharPtr) 2511 Result = ImplicitConversionSequence::Indistinguishable; 2512 break; 2513 } 2514 2515 return Result; 2516} 2517 2518/// CompareDerivedToBaseConversions - Compares two standard conversion 2519/// sequences to determine whether they can be ranked based on their 2520/// various kinds of derived-to-base conversions (C++ 2521/// [over.ics.rank]p4b3). As part of these checks, we also look at 2522/// conversions between Objective-C interface types. 2523ImplicitConversionSequence::CompareKind 2524CompareDerivedToBaseConversions(Sema &S, 2525 const StandardConversionSequence& SCS1, 2526 const StandardConversionSequence& SCS2) { 2527 QualType FromType1 = SCS1.getFromType(); 2528 QualType ToType1 = SCS1.getToType(1); 2529 QualType FromType2 = SCS2.getFromType(); 2530 QualType ToType2 = SCS2.getToType(1); 2531 2532 // Adjust the types we're converting from via the array-to-pointer 2533 // conversion, if we need to. 2534 if (SCS1.First == ICK_Array_To_Pointer) 2535 FromType1 = S.Context.getArrayDecayedType(FromType1); 2536 if (SCS2.First == ICK_Array_To_Pointer) 2537 FromType2 = S.Context.getArrayDecayedType(FromType2); 2538 2539 // Canonicalize all of the types. 2540 FromType1 = S.Context.getCanonicalType(FromType1); 2541 ToType1 = S.Context.getCanonicalType(ToType1); 2542 FromType2 = S.Context.getCanonicalType(FromType2); 2543 ToType2 = S.Context.getCanonicalType(ToType2); 2544 2545 // C++ [over.ics.rank]p4b3: 2546 // 2547 // If class B is derived directly or indirectly from class A and 2548 // class C is derived directly or indirectly from B, 2549 // 2550 // For Objective-C, we let A, B, and C also be Objective-C 2551 // interfaces. 2552 2553 // Compare based on pointer conversions. 2554 if (SCS1.Second == ICK_Pointer_Conversion && 2555 SCS2.Second == ICK_Pointer_Conversion && 2556 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 2557 FromType1->isPointerType() && FromType2->isPointerType() && 2558 ToType1->isPointerType() && ToType2->isPointerType()) { 2559 QualType FromPointee1 2560 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2561 QualType ToPointee1 2562 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2563 QualType FromPointee2 2564 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2565 QualType ToPointee2 2566 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2567 2568 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>(); 2569 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>(); 2570 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>(); 2571 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>(); 2572 2573 // -- conversion of C* to B* is better than conversion of C* to A*, 2574 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 2575 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 2576 return ImplicitConversionSequence::Better; 2577 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 2578 return ImplicitConversionSequence::Worse; 2579 2580 if (ToIface1 && ToIface2) { 2581 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1)) 2582 return ImplicitConversionSequence::Better; 2583 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2)) 2584 return ImplicitConversionSequence::Worse; 2585 } 2586 } 2587 2588 // -- conversion of B* to A* is better than conversion of C* to A*, 2589 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 2590 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 2591 return ImplicitConversionSequence::Better; 2592 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 2593 return ImplicitConversionSequence::Worse; 2594 2595 if (FromIface1 && FromIface2) { 2596 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 2597 return ImplicitConversionSequence::Better; 2598 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 2599 return ImplicitConversionSequence::Worse; 2600 } 2601 } 2602 } 2603 2604 // Ranking of member-pointer types. 2605 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 2606 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 2607 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 2608 const MemberPointerType * FromMemPointer1 = 2609 FromType1->getAs<MemberPointerType>(); 2610 const MemberPointerType * ToMemPointer1 = 2611 ToType1->getAs<MemberPointerType>(); 2612 const MemberPointerType * FromMemPointer2 = 2613 FromType2->getAs<MemberPointerType>(); 2614 const MemberPointerType * ToMemPointer2 = 2615 ToType2->getAs<MemberPointerType>(); 2616 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 2617 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 2618 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 2619 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 2620 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 2621 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 2622 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 2623 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 2624 // conversion of A::* to B::* is better than conversion of A::* to C::*, 2625 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 2626 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 2627 return ImplicitConversionSequence::Worse; 2628 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 2629 return ImplicitConversionSequence::Better; 2630 } 2631 // conversion of B::* to C::* is better than conversion of A::* to C::* 2632 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 2633 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 2634 return ImplicitConversionSequence::Better; 2635 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 2636 return ImplicitConversionSequence::Worse; 2637 } 2638 } 2639 2640 if (SCS1.Second == ICK_Derived_To_Base) { 2641 // -- conversion of C to B is better than conversion of C to A, 2642 // -- binding of an expression of type C to a reference of type 2643 // B& is better than binding an expression of type C to a 2644 // reference of type A&, 2645 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 2646 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 2647 if (S.IsDerivedFrom(ToType1, ToType2)) 2648 return ImplicitConversionSequence::Better; 2649 else if (S.IsDerivedFrom(ToType2, ToType1)) 2650 return ImplicitConversionSequence::Worse; 2651 } 2652 2653 // -- conversion of B to A is better than conversion of C to A. 2654 // -- binding of an expression of type B to a reference of type 2655 // A& is better than binding an expression of type C to a 2656 // reference of type A&, 2657 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 2658 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 2659 if (S.IsDerivedFrom(FromType2, FromType1)) 2660 return ImplicitConversionSequence::Better; 2661 else if (S.IsDerivedFrom(FromType1, FromType2)) 2662 return ImplicitConversionSequence::Worse; 2663 } 2664 } 2665 2666 return ImplicitConversionSequence::Indistinguishable; 2667} 2668 2669/// CompareReferenceRelationship - Compare the two types T1 and T2 to 2670/// determine whether they are reference-related, 2671/// reference-compatible, reference-compatible with added 2672/// qualification, or incompatible, for use in C++ initialization by 2673/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 2674/// type, and the first type (T1) is the pointee type of the reference 2675/// type being initialized. 2676Sema::ReferenceCompareResult 2677Sema::CompareReferenceRelationship(SourceLocation Loc, 2678 QualType OrigT1, QualType OrigT2, 2679 bool &DerivedToBase, 2680 bool &ObjCConversion) { 2681 assert(!OrigT1->isReferenceType() && 2682 "T1 must be the pointee type of the reference type"); 2683 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 2684 2685 QualType T1 = Context.getCanonicalType(OrigT1); 2686 QualType T2 = Context.getCanonicalType(OrigT2); 2687 Qualifiers T1Quals, T2Quals; 2688 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 2689 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 2690 2691 // C++ [dcl.init.ref]p4: 2692 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 2693 // reference-related to "cv2 T2" if T1 is the same type as T2, or 2694 // T1 is a base class of T2. 2695 DerivedToBase = false; 2696 ObjCConversion = false; 2697 if (UnqualT1 == UnqualT2) { 2698 // Nothing to do. 2699 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) && 2700 IsDerivedFrom(UnqualT2, UnqualT1)) 2701 DerivedToBase = true; 2702 else if (UnqualT1->isObjCObjectOrInterfaceType() && 2703 UnqualT2->isObjCObjectOrInterfaceType() && 2704 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 2705 ObjCConversion = true; 2706 else 2707 return Ref_Incompatible; 2708 2709 // At this point, we know that T1 and T2 are reference-related (at 2710 // least). 2711 2712 // If the type is an array type, promote the element qualifiers to the type 2713 // for comparison. 2714 if (isa<ArrayType>(T1) && T1Quals) 2715 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 2716 if (isa<ArrayType>(T2) && T2Quals) 2717 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 2718 2719 // C++ [dcl.init.ref]p4: 2720 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 2721 // reference-related to T2 and cv1 is the same cv-qualification 2722 // as, or greater cv-qualification than, cv2. For purposes of 2723 // overload resolution, cases for which cv1 is greater 2724 // cv-qualification than cv2 are identified as 2725 // reference-compatible with added qualification (see 13.3.3.2). 2726 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers()) 2727 return Ref_Compatible; 2728 else if (T1.isMoreQualifiedThan(T2)) 2729 return Ref_Compatible_With_Added_Qualification; 2730 else 2731 return Ref_Related; 2732} 2733 2734/// \brief Look for a user-defined conversion to an value reference-compatible 2735/// with DeclType. Return true if something definite is found. 2736static bool 2737FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 2738 QualType DeclType, SourceLocation DeclLoc, 2739 Expr *Init, QualType T2, bool AllowRvalues, 2740 bool AllowExplicit) { 2741 assert(T2->isRecordType() && "Can only find conversions of record types."); 2742 CXXRecordDecl *T2RecordDecl 2743 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 2744 2745 QualType ToType 2746 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType() 2747 : DeclType; 2748 2749 OverloadCandidateSet CandidateSet(DeclLoc); 2750 const UnresolvedSetImpl *Conversions 2751 = T2RecordDecl->getVisibleConversionFunctions(); 2752 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 2753 E = Conversions->end(); I != E; ++I) { 2754 NamedDecl *D = *I; 2755 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 2756 if (isa<UsingShadowDecl>(D)) 2757 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2758 2759 FunctionTemplateDecl *ConvTemplate 2760 = dyn_cast<FunctionTemplateDecl>(D); 2761 CXXConversionDecl *Conv; 2762 if (ConvTemplate) 2763 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2764 else 2765 Conv = cast<CXXConversionDecl>(D); 2766 2767 // If this is an explicit conversion, and we're not allowed to consider 2768 // explicit conversions, skip it. 2769 if (!AllowExplicit && Conv->isExplicit()) 2770 continue; 2771 2772 if (AllowRvalues) { 2773 bool DerivedToBase = false; 2774 bool ObjCConversion = false; 2775 if (!ConvTemplate && 2776 S.CompareReferenceRelationship(DeclLoc, 2777 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(), 2778 DeclType.getNonReferenceType().getUnqualifiedType(), 2779 DerivedToBase, ObjCConversion) 2780 == Sema::Ref_Incompatible) 2781 continue; 2782 } else { 2783 // If the conversion function doesn't return a reference type, 2784 // it can't be considered for this conversion. An rvalue reference 2785 // is only acceptable if its referencee is a function type. 2786 2787 const ReferenceType *RefType = 2788 Conv->getConversionType()->getAs<ReferenceType>(); 2789 if (!RefType || 2790 (!RefType->isLValueReferenceType() && 2791 !RefType->getPointeeType()->isFunctionType())) 2792 continue; 2793 } 2794 2795 if (ConvTemplate) 2796 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 2797 Init, ToType, CandidateSet); 2798 else 2799 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 2800 ToType, CandidateSet); 2801 } 2802 2803 OverloadCandidateSet::iterator Best; 2804 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 2805 case OR_Success: 2806 // C++ [over.ics.ref]p1: 2807 // 2808 // [...] If the parameter binds directly to the result of 2809 // applying a conversion function to the argument 2810 // expression, the implicit conversion sequence is a 2811 // user-defined conversion sequence (13.3.3.1.2), with the 2812 // second standard conversion sequence either an identity 2813 // conversion or, if the conversion function returns an 2814 // entity of a type that is a derived class of the parameter 2815 // type, a derived-to-base Conversion. 2816 if (!Best->FinalConversion.DirectBinding) 2817 return false; 2818 2819 ICS.setUserDefined(); 2820 ICS.UserDefined.Before = Best->Conversions[0].Standard; 2821 ICS.UserDefined.After = Best->FinalConversion; 2822 ICS.UserDefined.ConversionFunction = Best->Function; 2823 ICS.UserDefined.EllipsisConversion = false; 2824 assert(ICS.UserDefined.After.ReferenceBinding && 2825 ICS.UserDefined.After.DirectBinding && 2826 "Expected a direct reference binding!"); 2827 return true; 2828 2829 case OR_Ambiguous: 2830 ICS.setAmbiguous(); 2831 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 2832 Cand != CandidateSet.end(); ++Cand) 2833 if (Cand->Viable) 2834 ICS.Ambiguous.addConversion(Cand->Function); 2835 return true; 2836 2837 case OR_No_Viable_Function: 2838 case OR_Deleted: 2839 // There was no suitable conversion, or we found a deleted 2840 // conversion; continue with other checks. 2841 return false; 2842 } 2843 2844 return false; 2845} 2846 2847/// \brief Compute an implicit conversion sequence for reference 2848/// initialization. 2849static ImplicitConversionSequence 2850TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType, 2851 SourceLocation DeclLoc, 2852 bool SuppressUserConversions, 2853 bool AllowExplicit) { 2854 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 2855 2856 // Most paths end in a failed conversion. 2857 ImplicitConversionSequence ICS; 2858 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 2859 2860 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 2861 QualType T2 = Init->getType(); 2862 2863 // If the initializer is the address of an overloaded function, try 2864 // to resolve the overloaded function. If all goes well, T2 is the 2865 // type of the resulting function. 2866 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 2867 DeclAccessPair Found; 2868 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 2869 false, Found)) 2870 T2 = Fn->getType(); 2871 } 2872 2873 // Compute some basic properties of the types and the initializer. 2874 bool isRValRef = DeclType->isRValueReferenceType(); 2875 bool DerivedToBase = false; 2876 bool ObjCConversion = false; 2877 Expr::Classification InitCategory = Init->Classify(S.Context); 2878 Sema::ReferenceCompareResult RefRelationship 2879 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 2880 ObjCConversion); 2881 2882 2883 // C++0x [dcl.init.ref]p5: 2884 // A reference to type "cv1 T1" is initialized by an expression 2885 // of type "cv2 T2" as follows: 2886 2887 // -- If reference is an lvalue reference and the initializer expression 2888 // The next bullet point (T1 is a function) is pretty much equivalent to this 2889 // one, so it's handled here. 2890 if (!isRValRef || T1->isFunctionType()) { 2891 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 2892 // reference-compatible with "cv2 T2," or 2893 // 2894 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 2895 if (InitCategory.isLValue() && 2896 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 2897 // C++ [over.ics.ref]p1: 2898 // When a parameter of reference type binds directly (8.5.3) 2899 // to an argument expression, the implicit conversion sequence 2900 // is the identity conversion, unless the argument expression 2901 // has a type that is a derived class of the parameter type, 2902 // in which case the implicit conversion sequence is a 2903 // derived-to-base Conversion (13.3.3.1). 2904 ICS.setStandard(); 2905 ICS.Standard.First = ICK_Identity; 2906 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 2907 : ObjCConversion? ICK_Compatible_Conversion 2908 : ICK_Identity; 2909 ICS.Standard.Third = ICK_Identity; 2910 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 2911 ICS.Standard.setToType(0, T2); 2912 ICS.Standard.setToType(1, T1); 2913 ICS.Standard.setToType(2, T1); 2914 ICS.Standard.ReferenceBinding = true; 2915 ICS.Standard.DirectBinding = true; 2916 ICS.Standard.RRefBinding = isRValRef; 2917 ICS.Standard.CopyConstructor = 0; 2918 2919 // Nothing more to do: the inaccessibility/ambiguity check for 2920 // derived-to-base conversions is suppressed when we're 2921 // computing the implicit conversion sequence (C++ 2922 // [over.best.ics]p2). 2923 return ICS; 2924 } 2925 2926 // -- has a class type (i.e., T2 is a class type), where T1 is 2927 // not reference-related to T2, and can be implicitly 2928 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 2929 // is reference-compatible with "cv3 T3" 92) (this 2930 // conversion is selected by enumerating the applicable 2931 // conversion functions (13.3.1.6) and choosing the best 2932 // one through overload resolution (13.3)), 2933 if (!SuppressUserConversions && T2->isRecordType() && 2934 !S.RequireCompleteType(DeclLoc, T2, 0) && 2935 RefRelationship == Sema::Ref_Incompatible) { 2936 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 2937 Init, T2, /*AllowRvalues=*/false, 2938 AllowExplicit)) 2939 return ICS; 2940 } 2941 } 2942 2943 // -- Otherwise, the reference shall be an lvalue reference to a 2944 // non-volatile const type (i.e., cv1 shall be const), or the reference 2945 // shall be an rvalue reference and the initializer expression shall be 2946 // an rvalue or have a function type. 2947 // 2948 // We actually handle one oddity of C++ [over.ics.ref] at this 2949 // point, which is that, due to p2 (which short-circuits reference 2950 // binding by only attempting a simple conversion for non-direct 2951 // bindings) and p3's strange wording, we allow a const volatile 2952 // reference to bind to an rvalue. Hence the check for the presence 2953 // of "const" rather than checking for "const" being the only 2954 // qualifier. 2955 // This is also the point where rvalue references and lvalue inits no longer 2956 // go together. 2957 if ((!isRValRef && !T1.isConstQualified()) || 2958 (isRValRef && InitCategory.isLValue())) 2959 return ICS; 2960 2961 // -- If T1 is a function type, then 2962 // -- if T2 is the same type as T1, the reference is bound to the 2963 // initializer expression lvalue; 2964 // -- if T2 is a class type and the initializer expression can be 2965 // implicitly converted to an lvalue of type T1 [...], the 2966 // reference is bound to the function lvalue that is the result 2967 // of the conversion; 2968 // This is the same as for the lvalue case above, so it was handled there. 2969 // -- otherwise, the program is ill-formed. 2970 // This is the one difference to the lvalue case. 2971 if (T1->isFunctionType()) 2972 return ICS; 2973 2974 // -- Otherwise, if T2 is a class type and 2975 // -- the initializer expression is an rvalue and "cv1 T1" 2976 // is reference-compatible with "cv2 T2," or 2977 // 2978 // -- T1 is not reference-related to T2 and the initializer 2979 // expression can be implicitly converted to an rvalue 2980 // of type "cv3 T3" (this conversion is selected by 2981 // enumerating the applicable conversion functions 2982 // (13.3.1.6) and choosing the best one through overload 2983 // resolution (13.3)), 2984 // 2985 // then the reference is bound to the initializer 2986 // expression rvalue in the first case and to the object 2987 // that is the result of the conversion in the second case 2988 // (or, in either case, to the appropriate base class 2989 // subobject of the object). 2990 if (T2->isRecordType()) { 2991 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a 2992 // direct binding in C++0x but not in C++03. 2993 if (InitCategory.isRValue() && 2994 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 2995 ICS.setStandard(); 2996 ICS.Standard.First = ICK_Identity; 2997 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 2998 : ObjCConversion? ICK_Compatible_Conversion 2999 : ICK_Identity; 3000 ICS.Standard.Third = ICK_Identity; 3001 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 3002 ICS.Standard.setToType(0, T2); 3003 ICS.Standard.setToType(1, T1); 3004 ICS.Standard.setToType(2, T1); 3005 ICS.Standard.ReferenceBinding = true; 3006 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x; 3007 ICS.Standard.RRefBinding = isRValRef; 3008 ICS.Standard.CopyConstructor = 0; 3009 return ICS; 3010 } 3011 3012 // Second case: not reference-related. 3013 if (RefRelationship == Sema::Ref_Incompatible && 3014 !S.RequireCompleteType(DeclLoc, T2, 0) && 3015 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 3016 Init, T2, /*AllowRvalues=*/true, 3017 AllowExplicit)) 3018 return ICS; 3019 } 3020 3021 // -- Otherwise, a temporary of type "cv1 T1" is created and 3022 // initialized from the initializer expression using the 3023 // rules for a non-reference copy initialization (8.5). The 3024 // reference is then bound to the temporary. If T1 is 3025 // reference-related to T2, cv1 must be the same 3026 // cv-qualification as, or greater cv-qualification than, 3027 // cv2; otherwise, the program is ill-formed. 3028 if (RefRelationship == Sema::Ref_Related) { 3029 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 3030 // we would be reference-compatible or reference-compatible with 3031 // added qualification. But that wasn't the case, so the reference 3032 // initialization fails. 3033 return ICS; 3034 } 3035 3036 // If at least one of the types is a class type, the types are not 3037 // related, and we aren't allowed any user conversions, the 3038 // reference binding fails. This case is important for breaking 3039 // recursion, since TryImplicitConversion below will attempt to 3040 // create a temporary through the use of a copy constructor. 3041 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 3042 (T1->isRecordType() || T2->isRecordType())) 3043 return ICS; 3044 3045 // C++ [over.ics.ref]p2: 3046 // When a parameter of reference type is not bound directly to 3047 // an argument expression, the conversion sequence is the one 3048 // required to convert the argument expression to the 3049 // underlying type of the reference according to 3050 // 13.3.3.1. Conceptually, this conversion sequence corresponds 3051 // to copy-initializing a temporary of the underlying type with 3052 // the argument expression. Any difference in top-level 3053 // cv-qualification is subsumed by the initialization itself 3054 // and does not constitute a conversion. 3055 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 3056 /*AllowExplicit=*/false, 3057 /*InOverloadResolution=*/false); 3058 3059 // Of course, that's still a reference binding. 3060 if (ICS.isStandard()) { 3061 ICS.Standard.ReferenceBinding = true; 3062 ICS.Standard.RRefBinding = isRValRef; 3063 } else if (ICS.isUserDefined()) { 3064 ICS.UserDefined.After.ReferenceBinding = true; 3065 ICS.UserDefined.After.RRefBinding = isRValRef; 3066 } 3067 return ICS; 3068} 3069 3070/// TryCopyInitialization - Try to copy-initialize a value of type 3071/// ToType from the expression From. Return the implicit conversion 3072/// sequence required to pass this argument, which may be a bad 3073/// conversion sequence (meaning that the argument cannot be passed to 3074/// a parameter of this type). If @p SuppressUserConversions, then we 3075/// do not permit any user-defined conversion sequences. 3076static ImplicitConversionSequence 3077TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 3078 bool SuppressUserConversions, 3079 bool InOverloadResolution) { 3080 if (ToType->isReferenceType()) 3081 return TryReferenceInit(S, From, ToType, 3082 /*FIXME:*/From->getLocStart(), 3083 SuppressUserConversions, 3084 /*AllowExplicit=*/false); 3085 3086 return TryImplicitConversion(S, From, ToType, 3087 SuppressUserConversions, 3088 /*AllowExplicit=*/false, 3089 InOverloadResolution); 3090} 3091 3092/// TryObjectArgumentInitialization - Try to initialize the object 3093/// parameter of the given member function (@c Method) from the 3094/// expression @p From. 3095static ImplicitConversionSequence 3096TryObjectArgumentInitialization(Sema &S, QualType OrigFromType, 3097 CXXMethodDecl *Method, 3098 CXXRecordDecl *ActingContext) { 3099 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 3100 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 3101 // const volatile object. 3102 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 3103 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 3104 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 3105 3106 // Set up the conversion sequence as a "bad" conversion, to allow us 3107 // to exit early. 3108 ImplicitConversionSequence ICS; 3109 3110 // We need to have an object of class type. 3111 QualType FromType = OrigFromType; 3112 if (const PointerType *PT = FromType->getAs<PointerType>()) 3113 FromType = PT->getPointeeType(); 3114 3115 assert(FromType->isRecordType()); 3116 3117 // The implicit object parameter is has the type "reference to cv X", 3118 // where X is the class of which the function is a member 3119 // (C++ [over.match.funcs]p4). However, when finding an implicit 3120 // conversion sequence for the argument, we are not allowed to 3121 // create temporaries or perform user-defined conversions 3122 // (C++ [over.match.funcs]p5). We perform a simplified version of 3123 // reference binding here, that allows class rvalues to bind to 3124 // non-constant references. 3125 3126 // First check the qualifiers. We don't care about lvalue-vs-rvalue 3127 // with the implicit object parameter (C++ [over.match.funcs]p5). 3128 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 3129 if (ImplicitParamType.getCVRQualifiers() 3130 != FromTypeCanon.getLocalCVRQualifiers() && 3131 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 3132 ICS.setBad(BadConversionSequence::bad_qualifiers, 3133 OrigFromType, ImplicitParamType); 3134 return ICS; 3135 } 3136 3137 // Check that we have either the same type or a derived type. It 3138 // affects the conversion rank. 3139 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 3140 ImplicitConversionKind SecondKind; 3141 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 3142 SecondKind = ICK_Identity; 3143 } else if (S.IsDerivedFrom(FromType, ClassType)) 3144 SecondKind = ICK_Derived_To_Base; 3145 else { 3146 ICS.setBad(BadConversionSequence::unrelated_class, 3147 FromType, ImplicitParamType); 3148 return ICS; 3149 } 3150 3151 // Success. Mark this as a reference binding. 3152 ICS.setStandard(); 3153 ICS.Standard.setAsIdentityConversion(); 3154 ICS.Standard.Second = SecondKind; 3155 ICS.Standard.setFromType(FromType); 3156 ICS.Standard.setAllToTypes(ImplicitParamType); 3157 ICS.Standard.ReferenceBinding = true; 3158 ICS.Standard.DirectBinding = true; 3159 ICS.Standard.RRefBinding = false; 3160 return ICS; 3161} 3162 3163/// PerformObjectArgumentInitialization - Perform initialization of 3164/// the implicit object parameter for the given Method with the given 3165/// expression. 3166bool 3167Sema::PerformObjectArgumentInitialization(Expr *&From, 3168 NestedNameSpecifier *Qualifier, 3169 NamedDecl *FoundDecl, 3170 CXXMethodDecl *Method) { 3171 QualType FromRecordType, DestType; 3172 QualType ImplicitParamRecordType = 3173 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 3174 3175 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 3176 FromRecordType = PT->getPointeeType(); 3177 DestType = Method->getThisType(Context); 3178 } else { 3179 FromRecordType = From->getType(); 3180 DestType = ImplicitParamRecordType; 3181 } 3182 3183 // Note that we always use the true parent context when performing 3184 // the actual argument initialization. 3185 ImplicitConversionSequence ICS 3186 = TryObjectArgumentInitialization(*this, From->getType(), Method, 3187 Method->getParent()); 3188 if (ICS.isBad()) 3189 return Diag(From->getSourceRange().getBegin(), 3190 diag::err_implicit_object_parameter_init) 3191 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 3192 3193 if (ICS.Standard.Second == ICK_Derived_To_Base) 3194 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 3195 3196 if (!Context.hasSameType(From->getType(), DestType)) 3197 ImpCastExprToType(From, DestType, CK_NoOp, 3198 From->getType()->isPointerType() ? VK_RValue : VK_LValue); 3199 return false; 3200} 3201 3202/// TryContextuallyConvertToBool - Attempt to contextually convert the 3203/// expression From to bool (C++0x [conv]p3). 3204static ImplicitConversionSequence 3205TryContextuallyConvertToBool(Sema &S, Expr *From) { 3206 // FIXME: This is pretty broken. 3207 return TryImplicitConversion(S, From, S.Context.BoolTy, 3208 // FIXME: Are these flags correct? 3209 /*SuppressUserConversions=*/false, 3210 /*AllowExplicit=*/true, 3211 /*InOverloadResolution=*/false); 3212} 3213 3214/// PerformContextuallyConvertToBool - Perform a contextual conversion 3215/// of the expression From to bool (C++0x [conv]p3). 3216bool Sema::PerformContextuallyConvertToBool(Expr *&From) { 3217 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 3218 if (!ICS.isBad()) 3219 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 3220 3221 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 3222 return Diag(From->getSourceRange().getBegin(), 3223 diag::err_typecheck_bool_condition) 3224 << From->getType() << From->getSourceRange(); 3225 return true; 3226} 3227 3228/// TryContextuallyConvertToObjCId - Attempt to contextually convert the 3229/// expression From to 'id'. 3230static ImplicitConversionSequence 3231TryContextuallyConvertToObjCId(Sema &S, Expr *From) { 3232 QualType Ty = S.Context.getObjCIdType(); 3233 return TryImplicitConversion(S, From, Ty, 3234 // FIXME: Are these flags correct? 3235 /*SuppressUserConversions=*/false, 3236 /*AllowExplicit=*/true, 3237 /*InOverloadResolution=*/false); 3238} 3239 3240/// PerformContextuallyConvertToObjCId - Perform a contextual conversion 3241/// of the expression From to 'id'. 3242bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) { 3243 QualType Ty = Context.getObjCIdType(); 3244 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From); 3245 if (!ICS.isBad()) 3246 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 3247 return true; 3248} 3249 3250/// \brief Attempt to convert the given expression to an integral or 3251/// enumeration type. 3252/// 3253/// This routine will attempt to convert an expression of class type to an 3254/// integral or enumeration type, if that class type only has a single 3255/// conversion to an integral or enumeration type. 3256/// 3257/// \param Loc The source location of the construct that requires the 3258/// conversion. 3259/// 3260/// \param FromE The expression we're converting from. 3261/// 3262/// \param NotIntDiag The diagnostic to be emitted if the expression does not 3263/// have integral or enumeration type. 3264/// 3265/// \param IncompleteDiag The diagnostic to be emitted if the expression has 3266/// incomplete class type. 3267/// 3268/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an 3269/// explicit conversion function (because no implicit conversion functions 3270/// were available). This is a recovery mode. 3271/// 3272/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag, 3273/// showing which conversion was picked. 3274/// 3275/// \param AmbigDiag The diagnostic to be emitted if there is more than one 3276/// conversion function that could convert to integral or enumeration type. 3277/// 3278/// \param AmbigNote The note to be emitted with \p AmbigDiag for each 3279/// usable conversion function. 3280/// 3281/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion 3282/// function, which may be an extension in this case. 3283/// 3284/// \returns The expression, converted to an integral or enumeration type if 3285/// successful. 3286ExprResult 3287Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 3288 const PartialDiagnostic &NotIntDiag, 3289 const PartialDiagnostic &IncompleteDiag, 3290 const PartialDiagnostic &ExplicitConvDiag, 3291 const PartialDiagnostic &ExplicitConvNote, 3292 const PartialDiagnostic &AmbigDiag, 3293 const PartialDiagnostic &AmbigNote, 3294 const PartialDiagnostic &ConvDiag) { 3295 // We can't perform any more checking for type-dependent expressions. 3296 if (From->isTypeDependent()) 3297 return Owned(From); 3298 3299 // If the expression already has integral or enumeration type, we're golden. 3300 QualType T = From->getType(); 3301 if (T->isIntegralOrEnumerationType()) 3302 return Owned(From); 3303 3304 // FIXME: Check for missing '()' if T is a function type? 3305 3306 // If we don't have a class type in C++, there's no way we can get an 3307 // expression of integral or enumeration type. 3308 const RecordType *RecordTy = T->getAs<RecordType>(); 3309 if (!RecordTy || !getLangOptions().CPlusPlus) { 3310 Diag(Loc, NotIntDiag) 3311 << T << From->getSourceRange(); 3312 return Owned(From); 3313 } 3314 3315 // We must have a complete class type. 3316 if (RequireCompleteType(Loc, T, IncompleteDiag)) 3317 return Owned(From); 3318 3319 // Look for a conversion to an integral or enumeration type. 3320 UnresolvedSet<4> ViableConversions; 3321 UnresolvedSet<4> ExplicitConversions; 3322 const UnresolvedSetImpl *Conversions 3323 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 3324 3325 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3326 E = Conversions->end(); 3327 I != E; 3328 ++I) { 3329 if (CXXConversionDecl *Conversion 3330 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) 3331 if (Conversion->getConversionType().getNonReferenceType() 3332 ->isIntegralOrEnumerationType()) { 3333 if (Conversion->isExplicit()) 3334 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 3335 else 3336 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 3337 } 3338 } 3339 3340 switch (ViableConversions.size()) { 3341 case 0: 3342 if (ExplicitConversions.size() == 1) { 3343 DeclAccessPair Found = ExplicitConversions[0]; 3344 CXXConversionDecl *Conversion 3345 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 3346 3347 // The user probably meant to invoke the given explicit 3348 // conversion; use it. 3349 QualType ConvTy 3350 = Conversion->getConversionType().getNonReferenceType(); 3351 std::string TypeStr; 3352 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy); 3353 3354 Diag(Loc, ExplicitConvDiag) 3355 << T << ConvTy 3356 << FixItHint::CreateInsertion(From->getLocStart(), 3357 "static_cast<" + TypeStr + ">(") 3358 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 3359 ")"); 3360 Diag(Conversion->getLocation(), ExplicitConvNote) 3361 << ConvTy->isEnumeralType() << ConvTy; 3362 3363 // If we aren't in a SFINAE context, build a call to the 3364 // explicit conversion function. 3365 if (isSFINAEContext()) 3366 return ExprError(); 3367 3368 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 3369 From = BuildCXXMemberCallExpr(From, Found, Conversion); 3370 } 3371 3372 // We'll complain below about a non-integral condition type. 3373 break; 3374 3375 case 1: { 3376 // Apply this conversion. 3377 DeclAccessPair Found = ViableConversions[0]; 3378 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 3379 3380 CXXConversionDecl *Conversion 3381 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 3382 QualType ConvTy 3383 = Conversion->getConversionType().getNonReferenceType(); 3384 if (ConvDiag.getDiagID()) { 3385 if (isSFINAEContext()) 3386 return ExprError(); 3387 3388 Diag(Loc, ConvDiag) 3389 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange(); 3390 } 3391 3392 From = BuildCXXMemberCallExpr(From, Found, 3393 cast<CXXConversionDecl>(Found->getUnderlyingDecl())); 3394 break; 3395 } 3396 3397 default: 3398 Diag(Loc, AmbigDiag) 3399 << T << From->getSourceRange(); 3400 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 3401 CXXConversionDecl *Conv 3402 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 3403 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 3404 Diag(Conv->getLocation(), AmbigNote) 3405 << ConvTy->isEnumeralType() << ConvTy; 3406 } 3407 return Owned(From); 3408 } 3409 3410 if (!From->getType()->isIntegralOrEnumerationType()) 3411 Diag(Loc, NotIntDiag) 3412 << From->getType() << From->getSourceRange(); 3413 3414 return Owned(From); 3415} 3416 3417/// AddOverloadCandidate - Adds the given function to the set of 3418/// candidate functions, using the given function call arguments. If 3419/// @p SuppressUserConversions, then don't allow user-defined 3420/// conversions via constructors or conversion operators. 3421/// 3422/// \para PartialOverloading true if we are performing "partial" overloading 3423/// based on an incomplete set of function arguments. This feature is used by 3424/// code completion. 3425void 3426Sema::AddOverloadCandidate(FunctionDecl *Function, 3427 DeclAccessPair FoundDecl, 3428 Expr **Args, unsigned NumArgs, 3429 OverloadCandidateSet& CandidateSet, 3430 bool SuppressUserConversions, 3431 bool PartialOverloading) { 3432 const FunctionProtoType* Proto 3433 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 3434 assert(Proto && "Functions without a prototype cannot be overloaded"); 3435 assert(!Function->getDescribedFunctionTemplate() && 3436 "Use AddTemplateOverloadCandidate for function templates"); 3437 3438 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 3439 if (!isa<CXXConstructorDecl>(Method)) { 3440 // If we get here, it's because we're calling a member function 3441 // that is named without a member access expression (e.g., 3442 // "this->f") that was either written explicitly or created 3443 // implicitly. This can happen with a qualified call to a member 3444 // function, e.g., X::f(). We use an empty type for the implied 3445 // object argument (C++ [over.call.func]p3), and the acting context 3446 // is irrelevant. 3447 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 3448 QualType(), Args, NumArgs, CandidateSet, 3449 SuppressUserConversions); 3450 return; 3451 } 3452 // We treat a constructor like a non-member function, since its object 3453 // argument doesn't participate in overload resolution. 3454 } 3455 3456 if (!CandidateSet.isNewCandidate(Function)) 3457 return; 3458 3459 // Overload resolution is always an unevaluated context. 3460 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 3461 3462 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 3463 // C++ [class.copy]p3: 3464 // A member function template is never instantiated to perform the copy 3465 // of a class object to an object of its class type. 3466 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 3467 if (NumArgs == 1 && 3468 Constructor->isCopyConstructorLikeSpecialization() && 3469 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 3470 IsDerivedFrom(Args[0]->getType(), ClassType))) 3471 return; 3472 } 3473 3474 // Add this candidate 3475 CandidateSet.push_back(OverloadCandidate()); 3476 OverloadCandidate& Candidate = CandidateSet.back(); 3477 Candidate.FoundDecl = FoundDecl; 3478 Candidate.Function = Function; 3479 Candidate.Viable = true; 3480 Candidate.IsSurrogate = false; 3481 Candidate.IgnoreObjectArgument = false; 3482 3483 unsigned NumArgsInProto = Proto->getNumArgs(); 3484 3485 // (C++ 13.3.2p2): A candidate function having fewer than m 3486 // parameters is viable only if it has an ellipsis in its parameter 3487 // list (8.3.5). 3488 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto && 3489 !Proto->isVariadic()) { 3490 Candidate.Viable = false; 3491 Candidate.FailureKind = ovl_fail_too_many_arguments; 3492 return; 3493 } 3494 3495 // (C++ 13.3.2p2): A candidate function having more than m parameters 3496 // is viable only if the (m+1)st parameter has a default argument 3497 // (8.3.6). For the purposes of overload resolution, the 3498 // parameter list is truncated on the right, so that there are 3499 // exactly m parameters. 3500 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 3501 if (NumArgs < MinRequiredArgs && !PartialOverloading) { 3502 // Not enough arguments. 3503 Candidate.Viable = false; 3504 Candidate.FailureKind = ovl_fail_too_few_arguments; 3505 return; 3506 } 3507 3508 // Determine the implicit conversion sequences for each of the 3509 // arguments. 3510 Candidate.Conversions.resize(NumArgs); 3511 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 3512 if (ArgIdx < NumArgsInProto) { 3513 // (C++ 13.3.2p3): for F to be a viable function, there shall 3514 // exist for each argument an implicit conversion sequence 3515 // (13.3.3.1) that converts that argument to the corresponding 3516 // parameter of F. 3517 QualType ParamType = Proto->getArgType(ArgIdx); 3518 Candidate.Conversions[ArgIdx] 3519 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 3520 SuppressUserConversions, 3521 /*InOverloadResolution=*/true); 3522 if (Candidate.Conversions[ArgIdx].isBad()) { 3523 Candidate.Viable = false; 3524 Candidate.FailureKind = ovl_fail_bad_conversion; 3525 break; 3526 } 3527 } else { 3528 // (C++ 13.3.2p2): For the purposes of overload resolution, any 3529 // argument for which there is no corresponding parameter is 3530 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 3531 Candidate.Conversions[ArgIdx].setEllipsis(); 3532 } 3533 } 3534} 3535 3536/// \brief Add all of the function declarations in the given function set to 3537/// the overload canddiate set. 3538void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 3539 Expr **Args, unsigned NumArgs, 3540 OverloadCandidateSet& CandidateSet, 3541 bool SuppressUserConversions) { 3542 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 3543 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 3544 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 3545 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 3546 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 3547 cast<CXXMethodDecl>(FD)->getParent(), 3548 Args[0]->getType(), Args + 1, NumArgs - 1, 3549 CandidateSet, SuppressUserConversions); 3550 else 3551 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet, 3552 SuppressUserConversions); 3553 } else { 3554 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 3555 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 3556 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 3557 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 3558 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 3559 /*FIXME: explicit args */ 0, 3560 Args[0]->getType(), Args + 1, NumArgs - 1, 3561 CandidateSet, 3562 SuppressUserConversions); 3563 else 3564 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 3565 /*FIXME: explicit args */ 0, 3566 Args, NumArgs, CandidateSet, 3567 SuppressUserConversions); 3568 } 3569 } 3570} 3571 3572/// AddMethodCandidate - Adds a named decl (which is some kind of 3573/// method) as a method candidate to the given overload set. 3574void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 3575 QualType ObjectType, 3576 Expr **Args, unsigned NumArgs, 3577 OverloadCandidateSet& CandidateSet, 3578 bool SuppressUserConversions) { 3579 NamedDecl *Decl = FoundDecl.getDecl(); 3580 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 3581 3582 if (isa<UsingShadowDecl>(Decl)) 3583 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 3584 3585 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 3586 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 3587 "Expected a member function template"); 3588 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 3589 /*ExplicitArgs*/ 0, 3590 ObjectType, Args, NumArgs, 3591 CandidateSet, 3592 SuppressUserConversions); 3593 } else { 3594 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 3595 ObjectType, Args, NumArgs, 3596 CandidateSet, SuppressUserConversions); 3597 } 3598} 3599 3600/// AddMethodCandidate - Adds the given C++ member function to the set 3601/// of candidate functions, using the given function call arguments 3602/// and the object argument (@c Object). For example, in a call 3603/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 3604/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 3605/// allow user-defined conversions via constructors or conversion 3606/// operators. 3607void 3608Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 3609 CXXRecordDecl *ActingContext, QualType ObjectType, 3610 Expr **Args, unsigned NumArgs, 3611 OverloadCandidateSet& CandidateSet, 3612 bool SuppressUserConversions) { 3613 const FunctionProtoType* Proto 3614 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 3615 assert(Proto && "Methods without a prototype cannot be overloaded"); 3616 assert(!isa<CXXConstructorDecl>(Method) && 3617 "Use AddOverloadCandidate for constructors"); 3618 3619 if (!CandidateSet.isNewCandidate(Method)) 3620 return; 3621 3622 // Overload resolution is always an unevaluated context. 3623 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 3624 3625 // Add this candidate 3626 CandidateSet.push_back(OverloadCandidate()); 3627 OverloadCandidate& Candidate = CandidateSet.back(); 3628 Candidate.FoundDecl = FoundDecl; 3629 Candidate.Function = Method; 3630 Candidate.IsSurrogate = false; 3631 Candidate.IgnoreObjectArgument = false; 3632 3633 unsigned NumArgsInProto = Proto->getNumArgs(); 3634 3635 // (C++ 13.3.2p2): A candidate function having fewer than m 3636 // parameters is viable only if it has an ellipsis in its parameter 3637 // list (8.3.5). 3638 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 3639 Candidate.Viable = false; 3640 Candidate.FailureKind = ovl_fail_too_many_arguments; 3641 return; 3642 } 3643 3644 // (C++ 13.3.2p2): A candidate function having more than m parameters 3645 // is viable only if the (m+1)st parameter has a default argument 3646 // (8.3.6). For the purposes of overload resolution, the 3647 // parameter list is truncated on the right, so that there are 3648 // exactly m parameters. 3649 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 3650 if (NumArgs < MinRequiredArgs) { 3651 // Not enough arguments. 3652 Candidate.Viable = false; 3653 Candidate.FailureKind = ovl_fail_too_few_arguments; 3654 return; 3655 } 3656 3657 Candidate.Viable = true; 3658 Candidate.Conversions.resize(NumArgs + 1); 3659 3660 if (Method->isStatic() || ObjectType.isNull()) 3661 // The implicit object argument is ignored. 3662 Candidate.IgnoreObjectArgument = true; 3663 else { 3664 // Determine the implicit conversion sequence for the object 3665 // parameter. 3666 Candidate.Conversions[0] 3667 = TryObjectArgumentInitialization(*this, ObjectType, Method, 3668 ActingContext); 3669 if (Candidate.Conversions[0].isBad()) { 3670 Candidate.Viable = false; 3671 Candidate.FailureKind = ovl_fail_bad_conversion; 3672 return; 3673 } 3674 } 3675 3676 // Determine the implicit conversion sequences for each of the 3677 // arguments. 3678 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 3679 if (ArgIdx < NumArgsInProto) { 3680 // (C++ 13.3.2p3): for F to be a viable function, there shall 3681 // exist for each argument an implicit conversion sequence 3682 // (13.3.3.1) that converts that argument to the corresponding 3683 // parameter of F. 3684 QualType ParamType = Proto->getArgType(ArgIdx); 3685 Candidate.Conversions[ArgIdx + 1] 3686 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 3687 SuppressUserConversions, 3688 /*InOverloadResolution=*/true); 3689 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 3690 Candidate.Viable = false; 3691 Candidate.FailureKind = ovl_fail_bad_conversion; 3692 break; 3693 } 3694 } else { 3695 // (C++ 13.3.2p2): For the purposes of overload resolution, any 3696 // argument for which there is no corresponding parameter is 3697 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 3698 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 3699 } 3700 } 3701} 3702 3703/// \brief Add a C++ member function template as a candidate to the candidate 3704/// set, using template argument deduction to produce an appropriate member 3705/// function template specialization. 3706void 3707Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 3708 DeclAccessPair FoundDecl, 3709 CXXRecordDecl *ActingContext, 3710 const TemplateArgumentListInfo *ExplicitTemplateArgs, 3711 QualType ObjectType, 3712 Expr **Args, unsigned NumArgs, 3713 OverloadCandidateSet& CandidateSet, 3714 bool SuppressUserConversions) { 3715 if (!CandidateSet.isNewCandidate(MethodTmpl)) 3716 return; 3717 3718 // C++ [over.match.funcs]p7: 3719 // In each case where a candidate is a function template, candidate 3720 // function template specializations are generated using template argument 3721 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 3722 // candidate functions in the usual way.113) A given name can refer to one 3723 // or more function templates and also to a set of overloaded non-template 3724 // functions. In such a case, the candidate functions generated from each 3725 // function template are combined with the set of non-template candidate 3726 // functions. 3727 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 3728 FunctionDecl *Specialization = 0; 3729 if (TemplateDeductionResult Result 3730 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, 3731 Args, NumArgs, Specialization, Info)) { 3732 CandidateSet.push_back(OverloadCandidate()); 3733 OverloadCandidate &Candidate = CandidateSet.back(); 3734 Candidate.FoundDecl = FoundDecl; 3735 Candidate.Function = MethodTmpl->getTemplatedDecl(); 3736 Candidate.Viable = false; 3737 Candidate.FailureKind = ovl_fail_bad_deduction; 3738 Candidate.IsSurrogate = false; 3739 Candidate.IgnoreObjectArgument = false; 3740 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 3741 Info); 3742 return; 3743 } 3744 3745 // Add the function template specialization produced by template argument 3746 // deduction as a candidate. 3747 assert(Specialization && "Missing member function template specialization?"); 3748 assert(isa<CXXMethodDecl>(Specialization) && 3749 "Specialization is not a member function?"); 3750 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 3751 ActingContext, ObjectType, Args, NumArgs, 3752 CandidateSet, SuppressUserConversions); 3753} 3754 3755/// \brief Add a C++ function template specialization as a candidate 3756/// in the candidate set, using template argument deduction to produce 3757/// an appropriate function template specialization. 3758void 3759Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 3760 DeclAccessPair FoundDecl, 3761 const TemplateArgumentListInfo *ExplicitTemplateArgs, 3762 Expr **Args, unsigned NumArgs, 3763 OverloadCandidateSet& CandidateSet, 3764 bool SuppressUserConversions) { 3765 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 3766 return; 3767 3768 // C++ [over.match.funcs]p7: 3769 // In each case where a candidate is a function template, candidate 3770 // function template specializations are generated using template argument 3771 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 3772 // candidate functions in the usual way.113) A given name can refer to one 3773 // or more function templates and also to a set of overloaded non-template 3774 // functions. In such a case, the candidate functions generated from each 3775 // function template are combined with the set of non-template candidate 3776 // functions. 3777 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 3778 FunctionDecl *Specialization = 0; 3779 if (TemplateDeductionResult Result 3780 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 3781 Args, NumArgs, Specialization, Info)) { 3782 CandidateSet.push_back(OverloadCandidate()); 3783 OverloadCandidate &Candidate = CandidateSet.back(); 3784 Candidate.FoundDecl = FoundDecl; 3785 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 3786 Candidate.Viable = false; 3787 Candidate.FailureKind = ovl_fail_bad_deduction; 3788 Candidate.IsSurrogate = false; 3789 Candidate.IgnoreObjectArgument = false; 3790 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 3791 Info); 3792 return; 3793 } 3794 3795 // Add the function template specialization produced by template argument 3796 // deduction as a candidate. 3797 assert(Specialization && "Missing function template specialization?"); 3798 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet, 3799 SuppressUserConversions); 3800} 3801 3802/// AddConversionCandidate - Add a C++ conversion function as a 3803/// candidate in the candidate set (C++ [over.match.conv], 3804/// C++ [over.match.copy]). From is the expression we're converting from, 3805/// and ToType is the type that we're eventually trying to convert to 3806/// (which may or may not be the same type as the type that the 3807/// conversion function produces). 3808void 3809Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 3810 DeclAccessPair FoundDecl, 3811 CXXRecordDecl *ActingContext, 3812 Expr *From, QualType ToType, 3813 OverloadCandidateSet& CandidateSet) { 3814 assert(!Conversion->getDescribedFunctionTemplate() && 3815 "Conversion function templates use AddTemplateConversionCandidate"); 3816 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 3817 if (!CandidateSet.isNewCandidate(Conversion)) 3818 return; 3819 3820 // Overload resolution is always an unevaluated context. 3821 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 3822 3823 // Add this candidate 3824 CandidateSet.push_back(OverloadCandidate()); 3825 OverloadCandidate& Candidate = CandidateSet.back(); 3826 Candidate.FoundDecl = FoundDecl; 3827 Candidate.Function = Conversion; 3828 Candidate.IsSurrogate = false; 3829 Candidate.IgnoreObjectArgument = false; 3830 Candidate.FinalConversion.setAsIdentityConversion(); 3831 Candidate.FinalConversion.setFromType(ConvType); 3832 Candidate.FinalConversion.setAllToTypes(ToType); 3833 Candidate.Viable = true; 3834 Candidate.Conversions.resize(1); 3835 3836 // C++ [over.match.funcs]p4: 3837 // For conversion functions, the function is considered to be a member of 3838 // the class of the implicit implied object argument for the purpose of 3839 // defining the type of the implicit object parameter. 3840 // 3841 // Determine the implicit conversion sequence for the implicit 3842 // object parameter. 3843 QualType ImplicitParamType = From->getType(); 3844 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 3845 ImplicitParamType = FromPtrType->getPointeeType(); 3846 CXXRecordDecl *ConversionContext 3847 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 3848 3849 Candidate.Conversions[0] 3850 = TryObjectArgumentInitialization(*this, From->getType(), Conversion, 3851 ConversionContext); 3852 3853 if (Candidate.Conversions[0].isBad()) { 3854 Candidate.Viable = false; 3855 Candidate.FailureKind = ovl_fail_bad_conversion; 3856 return; 3857 } 3858 3859 // We won't go through a user-define type conversion function to convert a 3860 // derived to base as such conversions are given Conversion Rank. They only 3861 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 3862 QualType FromCanon 3863 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 3864 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 3865 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 3866 Candidate.Viable = false; 3867 Candidate.FailureKind = ovl_fail_trivial_conversion; 3868 return; 3869 } 3870 3871 // To determine what the conversion from the result of calling the 3872 // conversion function to the type we're eventually trying to 3873 // convert to (ToType), we need to synthesize a call to the 3874 // conversion function and attempt copy initialization from it. This 3875 // makes sure that we get the right semantics with respect to 3876 // lvalues/rvalues and the type. Fortunately, we can allocate this 3877 // call on the stack and we don't need its arguments to be 3878 // well-formed. 3879 DeclRefExpr ConversionRef(Conversion, Conversion->getType(), 3880 From->getLocStart()); 3881 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 3882 Context.getPointerType(Conversion->getType()), 3883 CK_FunctionToPointerDecay, 3884 &ConversionRef, VK_RValue); 3885 3886 // Note that it is safe to allocate CallExpr on the stack here because 3887 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 3888 // allocator). 3889 CallExpr Call(Context, &ConversionFn, 0, 0, 3890 Conversion->getConversionType().getNonLValueExprType(Context), 3891 From->getLocStart()); 3892 ImplicitConversionSequence ICS = 3893 TryCopyInitialization(*this, &Call, ToType, 3894 /*SuppressUserConversions=*/true, 3895 /*InOverloadResolution=*/false); 3896 3897 switch (ICS.getKind()) { 3898 case ImplicitConversionSequence::StandardConversion: 3899 Candidate.FinalConversion = ICS.Standard; 3900 3901 // C++ [over.ics.user]p3: 3902 // If the user-defined conversion is specified by a specialization of a 3903 // conversion function template, the second standard conversion sequence 3904 // shall have exact match rank. 3905 if (Conversion->getPrimaryTemplate() && 3906 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 3907 Candidate.Viable = false; 3908 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 3909 } 3910 3911 break; 3912 3913 case ImplicitConversionSequence::BadConversion: 3914 Candidate.Viable = false; 3915 Candidate.FailureKind = ovl_fail_bad_final_conversion; 3916 break; 3917 3918 default: 3919 assert(false && 3920 "Can only end up with a standard conversion sequence or failure"); 3921 } 3922} 3923 3924/// \brief Adds a conversion function template specialization 3925/// candidate to the overload set, using template argument deduction 3926/// to deduce the template arguments of the conversion function 3927/// template from the type that we are converting to (C++ 3928/// [temp.deduct.conv]). 3929void 3930Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 3931 DeclAccessPair FoundDecl, 3932 CXXRecordDecl *ActingDC, 3933 Expr *From, QualType ToType, 3934 OverloadCandidateSet &CandidateSet) { 3935 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 3936 "Only conversion function templates permitted here"); 3937 3938 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 3939 return; 3940 3941 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 3942 CXXConversionDecl *Specialization = 0; 3943 if (TemplateDeductionResult Result 3944 = DeduceTemplateArguments(FunctionTemplate, ToType, 3945 Specialization, Info)) { 3946 CandidateSet.push_back(OverloadCandidate()); 3947 OverloadCandidate &Candidate = CandidateSet.back(); 3948 Candidate.FoundDecl = FoundDecl; 3949 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 3950 Candidate.Viable = false; 3951 Candidate.FailureKind = ovl_fail_bad_deduction; 3952 Candidate.IsSurrogate = false; 3953 Candidate.IgnoreObjectArgument = false; 3954 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 3955 Info); 3956 return; 3957 } 3958 3959 // Add the conversion function template specialization produced by 3960 // template argument deduction as a candidate. 3961 assert(Specialization && "Missing function template specialization?"); 3962 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 3963 CandidateSet); 3964} 3965 3966/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 3967/// converts the given @c Object to a function pointer via the 3968/// conversion function @c Conversion, and then attempts to call it 3969/// with the given arguments (C++ [over.call.object]p2-4). Proto is 3970/// the type of function that we'll eventually be calling. 3971void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 3972 DeclAccessPair FoundDecl, 3973 CXXRecordDecl *ActingContext, 3974 const FunctionProtoType *Proto, 3975 QualType ObjectType, 3976 Expr **Args, unsigned NumArgs, 3977 OverloadCandidateSet& CandidateSet) { 3978 if (!CandidateSet.isNewCandidate(Conversion)) 3979 return; 3980 3981 // Overload resolution is always an unevaluated context. 3982 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 3983 3984 CandidateSet.push_back(OverloadCandidate()); 3985 OverloadCandidate& Candidate = CandidateSet.back(); 3986 Candidate.FoundDecl = FoundDecl; 3987 Candidate.Function = 0; 3988 Candidate.Surrogate = Conversion; 3989 Candidate.Viable = true; 3990 Candidate.IsSurrogate = true; 3991 Candidate.IgnoreObjectArgument = false; 3992 Candidate.Conversions.resize(NumArgs + 1); 3993 3994 // Determine the implicit conversion sequence for the implicit 3995 // object parameter. 3996 ImplicitConversionSequence ObjectInit 3997 = TryObjectArgumentInitialization(*this, ObjectType, Conversion, 3998 ActingContext); 3999 if (ObjectInit.isBad()) { 4000 Candidate.Viable = false; 4001 Candidate.FailureKind = ovl_fail_bad_conversion; 4002 Candidate.Conversions[0] = ObjectInit; 4003 return; 4004 } 4005 4006 // The first conversion is actually a user-defined conversion whose 4007 // first conversion is ObjectInit's standard conversion (which is 4008 // effectively a reference binding). Record it as such. 4009 Candidate.Conversions[0].setUserDefined(); 4010 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 4011 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 4012 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 4013 Candidate.Conversions[0].UserDefined.After 4014 = Candidate.Conversions[0].UserDefined.Before; 4015 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 4016 4017 // Find the 4018 unsigned NumArgsInProto = Proto->getNumArgs(); 4019 4020 // (C++ 13.3.2p2): A candidate function having fewer than m 4021 // parameters is viable only if it has an ellipsis in its parameter 4022 // list (8.3.5). 4023 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 4024 Candidate.Viable = false; 4025 Candidate.FailureKind = ovl_fail_too_many_arguments; 4026 return; 4027 } 4028 4029 // Function types don't have any default arguments, so just check if 4030 // we have enough arguments. 4031 if (NumArgs < NumArgsInProto) { 4032 // Not enough arguments. 4033 Candidate.Viable = false; 4034 Candidate.FailureKind = ovl_fail_too_few_arguments; 4035 return; 4036 } 4037 4038 // Determine the implicit conversion sequences for each of the 4039 // arguments. 4040 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4041 if (ArgIdx < NumArgsInProto) { 4042 // (C++ 13.3.2p3): for F to be a viable function, there shall 4043 // exist for each argument an implicit conversion sequence 4044 // (13.3.3.1) that converts that argument to the corresponding 4045 // parameter of F. 4046 QualType ParamType = Proto->getArgType(ArgIdx); 4047 Candidate.Conversions[ArgIdx + 1] 4048 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 4049 /*SuppressUserConversions=*/false, 4050 /*InOverloadResolution=*/false); 4051 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 4052 Candidate.Viable = false; 4053 Candidate.FailureKind = ovl_fail_bad_conversion; 4054 break; 4055 } 4056 } else { 4057 // (C++ 13.3.2p2): For the purposes of overload resolution, any 4058 // argument for which there is no corresponding parameter is 4059 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 4060 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 4061 } 4062 } 4063} 4064 4065/// \brief Add overload candidates for overloaded operators that are 4066/// member functions. 4067/// 4068/// Add the overloaded operator candidates that are member functions 4069/// for the operator Op that was used in an operator expression such 4070/// as "x Op y". , Args/NumArgs provides the operator arguments, and 4071/// CandidateSet will store the added overload candidates. (C++ 4072/// [over.match.oper]). 4073void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 4074 SourceLocation OpLoc, 4075 Expr **Args, unsigned NumArgs, 4076 OverloadCandidateSet& CandidateSet, 4077 SourceRange OpRange) { 4078 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 4079 4080 // C++ [over.match.oper]p3: 4081 // For a unary operator @ with an operand of a type whose 4082 // cv-unqualified version is T1, and for a binary operator @ with 4083 // a left operand of a type whose cv-unqualified version is T1 and 4084 // a right operand of a type whose cv-unqualified version is T2, 4085 // three sets of candidate functions, designated member 4086 // candidates, non-member candidates and built-in candidates, are 4087 // constructed as follows: 4088 QualType T1 = Args[0]->getType(); 4089 4090 // -- If T1 is a class type, the set of member candidates is the 4091 // result of the qualified lookup of T1::operator@ 4092 // (13.3.1.1.1); otherwise, the set of member candidates is 4093 // empty. 4094 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 4095 // Complete the type if it can be completed. Otherwise, we're done. 4096 if (RequireCompleteType(OpLoc, T1, PDiag())) 4097 return; 4098 4099 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 4100 LookupQualifiedName(Operators, T1Rec->getDecl()); 4101 Operators.suppressDiagnostics(); 4102 4103 for (LookupResult::iterator Oper = Operators.begin(), 4104 OperEnd = Operators.end(); 4105 Oper != OperEnd; 4106 ++Oper) 4107 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 4108 Args + 1, NumArgs - 1, CandidateSet, 4109 /* SuppressUserConversions = */ false); 4110 } 4111} 4112 4113/// AddBuiltinCandidate - Add a candidate for a built-in 4114/// operator. ResultTy and ParamTys are the result and parameter types 4115/// of the built-in candidate, respectively. Args and NumArgs are the 4116/// arguments being passed to the candidate. IsAssignmentOperator 4117/// should be true when this built-in candidate is an assignment 4118/// operator. NumContextualBoolArguments is the number of arguments 4119/// (at the beginning of the argument list) that will be contextually 4120/// converted to bool. 4121void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 4122 Expr **Args, unsigned NumArgs, 4123 OverloadCandidateSet& CandidateSet, 4124 bool IsAssignmentOperator, 4125 unsigned NumContextualBoolArguments) { 4126 // Overload resolution is always an unevaluated context. 4127 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 4128 4129 // Add this candidate 4130 CandidateSet.push_back(OverloadCandidate()); 4131 OverloadCandidate& Candidate = CandidateSet.back(); 4132 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 4133 Candidate.Function = 0; 4134 Candidate.IsSurrogate = false; 4135 Candidate.IgnoreObjectArgument = false; 4136 Candidate.BuiltinTypes.ResultTy = ResultTy; 4137 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 4138 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 4139 4140 // Determine the implicit conversion sequences for each of the 4141 // arguments. 4142 Candidate.Viable = true; 4143 Candidate.Conversions.resize(NumArgs); 4144 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4145 // C++ [over.match.oper]p4: 4146 // For the built-in assignment operators, conversions of the 4147 // left operand are restricted as follows: 4148 // -- no temporaries are introduced to hold the left operand, and 4149 // -- no user-defined conversions are applied to the left 4150 // operand to achieve a type match with the left-most 4151 // parameter of a built-in candidate. 4152 // 4153 // We block these conversions by turning off user-defined 4154 // conversions, since that is the only way that initialization of 4155 // a reference to a non-class type can occur from something that 4156 // is not of the same type. 4157 if (ArgIdx < NumContextualBoolArguments) { 4158 assert(ParamTys[ArgIdx] == Context.BoolTy && 4159 "Contextual conversion to bool requires bool type"); 4160 Candidate.Conversions[ArgIdx] 4161 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 4162 } else { 4163 Candidate.Conversions[ArgIdx] 4164 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 4165 ArgIdx == 0 && IsAssignmentOperator, 4166 /*InOverloadResolution=*/false); 4167 } 4168 if (Candidate.Conversions[ArgIdx].isBad()) { 4169 Candidate.Viable = false; 4170 Candidate.FailureKind = ovl_fail_bad_conversion; 4171 break; 4172 } 4173 } 4174} 4175 4176/// BuiltinCandidateTypeSet - A set of types that will be used for the 4177/// candidate operator functions for built-in operators (C++ 4178/// [over.built]). The types are separated into pointer types and 4179/// enumeration types. 4180class BuiltinCandidateTypeSet { 4181 /// TypeSet - A set of types. 4182 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 4183 4184 /// PointerTypes - The set of pointer types that will be used in the 4185 /// built-in candidates. 4186 TypeSet PointerTypes; 4187 4188 /// MemberPointerTypes - The set of member pointer types that will be 4189 /// used in the built-in candidates. 4190 TypeSet MemberPointerTypes; 4191 4192 /// EnumerationTypes - The set of enumeration types that will be 4193 /// used in the built-in candidates. 4194 TypeSet EnumerationTypes; 4195 4196 /// \brief The set of vector types that will be used in the built-in 4197 /// candidates. 4198 TypeSet VectorTypes; 4199 4200 /// Sema - The semantic analysis instance where we are building the 4201 /// candidate type set. 4202 Sema &SemaRef; 4203 4204 /// Context - The AST context in which we will build the type sets. 4205 ASTContext &Context; 4206 4207 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 4208 const Qualifiers &VisibleQuals); 4209 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 4210 4211public: 4212 /// iterator - Iterates through the types that are part of the set. 4213 typedef TypeSet::iterator iterator; 4214 4215 BuiltinCandidateTypeSet(Sema &SemaRef) 4216 : SemaRef(SemaRef), Context(SemaRef.Context) { } 4217 4218 void AddTypesConvertedFrom(QualType Ty, 4219 SourceLocation Loc, 4220 bool AllowUserConversions, 4221 bool AllowExplicitConversions, 4222 const Qualifiers &VisibleTypeConversionsQuals); 4223 4224 /// pointer_begin - First pointer type found; 4225 iterator pointer_begin() { return PointerTypes.begin(); } 4226 4227 /// pointer_end - Past the last pointer type found; 4228 iterator pointer_end() { return PointerTypes.end(); } 4229 4230 /// member_pointer_begin - First member pointer type found; 4231 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 4232 4233 /// member_pointer_end - Past the last member pointer type found; 4234 iterator member_pointer_end() { return MemberPointerTypes.end(); } 4235 4236 /// enumeration_begin - First enumeration type found; 4237 iterator enumeration_begin() { return EnumerationTypes.begin(); } 4238 4239 /// enumeration_end - Past the last enumeration type found; 4240 iterator enumeration_end() { return EnumerationTypes.end(); } 4241 4242 iterator vector_begin() { return VectorTypes.begin(); } 4243 iterator vector_end() { return VectorTypes.end(); } 4244}; 4245 4246/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 4247/// the set of pointer types along with any more-qualified variants of 4248/// that type. For example, if @p Ty is "int const *", this routine 4249/// will add "int const *", "int const volatile *", "int const 4250/// restrict *", and "int const volatile restrict *" to the set of 4251/// pointer types. Returns true if the add of @p Ty itself succeeded, 4252/// false otherwise. 4253/// 4254/// FIXME: what to do about extended qualifiers? 4255bool 4256BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 4257 const Qualifiers &VisibleQuals) { 4258 4259 // Insert this type. 4260 if (!PointerTypes.insert(Ty)) 4261 return false; 4262 4263 QualType PointeeTy; 4264 const PointerType *PointerTy = Ty->getAs<PointerType>(); 4265 bool buildObjCPtr = false; 4266 if (!PointerTy) { 4267 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) { 4268 PointeeTy = PTy->getPointeeType(); 4269 buildObjCPtr = true; 4270 } 4271 else 4272 assert(false && "type was not a pointer type!"); 4273 } 4274 else 4275 PointeeTy = PointerTy->getPointeeType(); 4276 4277 // Don't add qualified variants of arrays. For one, they're not allowed 4278 // (the qualifier would sink to the element type), and for another, the 4279 // only overload situation where it matters is subscript or pointer +- int, 4280 // and those shouldn't have qualifier variants anyway. 4281 if (PointeeTy->isArrayType()) 4282 return true; 4283 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 4284 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy)) 4285 BaseCVR = Array->getElementType().getCVRQualifiers(); 4286 bool hasVolatile = VisibleQuals.hasVolatile(); 4287 bool hasRestrict = VisibleQuals.hasRestrict(); 4288 4289 // Iterate through all strict supersets of BaseCVR. 4290 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 4291 if ((CVR | BaseCVR) != CVR) continue; 4292 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere 4293 // in the types. 4294 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 4295 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue; 4296 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 4297 if (!buildObjCPtr) 4298 PointerTypes.insert(Context.getPointerType(QPointeeTy)); 4299 else 4300 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy)); 4301 } 4302 4303 return true; 4304} 4305 4306/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 4307/// to the set of pointer types along with any more-qualified variants of 4308/// that type. For example, if @p Ty is "int const *", this routine 4309/// will add "int const *", "int const volatile *", "int const 4310/// restrict *", and "int const volatile restrict *" to the set of 4311/// pointer types. Returns true if the add of @p Ty itself succeeded, 4312/// false otherwise. 4313/// 4314/// FIXME: what to do about extended qualifiers? 4315bool 4316BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 4317 QualType Ty) { 4318 // Insert this type. 4319 if (!MemberPointerTypes.insert(Ty)) 4320 return false; 4321 4322 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 4323 assert(PointerTy && "type was not a member pointer type!"); 4324 4325 QualType PointeeTy = PointerTy->getPointeeType(); 4326 // Don't add qualified variants of arrays. For one, they're not allowed 4327 // (the qualifier would sink to the element type), and for another, the 4328 // only overload situation where it matters is subscript or pointer +- int, 4329 // and those shouldn't have qualifier variants anyway. 4330 if (PointeeTy->isArrayType()) 4331 return true; 4332 const Type *ClassTy = PointerTy->getClass(); 4333 4334 // Iterate through all strict supersets of the pointee type's CVR 4335 // qualifiers. 4336 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 4337 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 4338 if ((CVR | BaseCVR) != CVR) continue; 4339 4340 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 4341 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy)); 4342 } 4343 4344 return true; 4345} 4346 4347/// AddTypesConvertedFrom - Add each of the types to which the type @p 4348/// Ty can be implicit converted to the given set of @p Types. We're 4349/// primarily interested in pointer types and enumeration types. We also 4350/// take member pointer types, for the conditional operator. 4351/// AllowUserConversions is true if we should look at the conversion 4352/// functions of a class type, and AllowExplicitConversions if we 4353/// should also include the explicit conversion functions of a class 4354/// type. 4355void 4356BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 4357 SourceLocation Loc, 4358 bool AllowUserConversions, 4359 bool AllowExplicitConversions, 4360 const Qualifiers &VisibleQuals) { 4361 // Only deal with canonical types. 4362 Ty = Context.getCanonicalType(Ty); 4363 4364 // Look through reference types; they aren't part of the type of an 4365 // expression for the purposes of conversions. 4366 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 4367 Ty = RefTy->getPointeeType(); 4368 4369 // We don't care about qualifiers on the type. 4370 Ty = Ty.getLocalUnqualifiedType(); 4371 4372 // If we're dealing with an array type, decay to the pointer. 4373 if (Ty->isArrayType()) 4374 Ty = SemaRef.Context.getArrayDecayedType(Ty); 4375 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 4376 PointerTypes.insert(Ty); 4377 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 4378 // Insert our type, and its more-qualified variants, into the set 4379 // of types. 4380 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 4381 return; 4382 } else if (Ty->isMemberPointerType()) { 4383 // Member pointers are far easier, since the pointee can't be converted. 4384 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 4385 return; 4386 } else if (Ty->isEnumeralType()) { 4387 EnumerationTypes.insert(Ty); 4388 } else if (Ty->isVectorType()) { 4389 VectorTypes.insert(Ty); 4390 } else if (AllowUserConversions) { 4391 if (const RecordType *TyRec = Ty->getAs<RecordType>()) { 4392 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) { 4393 // No conversion functions in incomplete types. 4394 return; 4395 } 4396 4397 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 4398 const UnresolvedSetImpl *Conversions 4399 = ClassDecl->getVisibleConversionFunctions(); 4400 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 4401 E = Conversions->end(); I != E; ++I) { 4402 NamedDecl *D = I.getDecl(); 4403 if (isa<UsingShadowDecl>(D)) 4404 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4405 4406 // Skip conversion function templates; they don't tell us anything 4407 // about which builtin types we can convert to. 4408 if (isa<FunctionTemplateDecl>(D)) 4409 continue; 4410 4411 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 4412 if (AllowExplicitConversions || !Conv->isExplicit()) { 4413 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 4414 VisibleQuals); 4415 } 4416 } 4417 } 4418 } 4419} 4420 4421/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 4422/// the volatile- and non-volatile-qualified assignment operators for the 4423/// given type to the candidate set. 4424static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 4425 QualType T, 4426 Expr **Args, 4427 unsigned NumArgs, 4428 OverloadCandidateSet &CandidateSet) { 4429 QualType ParamTypes[2]; 4430 4431 // T& operator=(T&, T) 4432 ParamTypes[0] = S.Context.getLValueReferenceType(T); 4433 ParamTypes[1] = T; 4434 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 4435 /*IsAssignmentOperator=*/true); 4436 4437 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 4438 // volatile T& operator=(volatile T&, T) 4439 ParamTypes[0] 4440 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 4441 ParamTypes[1] = T; 4442 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 4443 /*IsAssignmentOperator=*/true); 4444 } 4445} 4446 4447/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 4448/// if any, found in visible type conversion functions found in ArgExpr's type. 4449static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 4450 Qualifiers VRQuals; 4451 const RecordType *TyRec; 4452 if (const MemberPointerType *RHSMPType = 4453 ArgExpr->getType()->getAs<MemberPointerType>()) 4454 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 4455 else 4456 TyRec = ArgExpr->getType()->getAs<RecordType>(); 4457 if (!TyRec) { 4458 // Just to be safe, assume the worst case. 4459 VRQuals.addVolatile(); 4460 VRQuals.addRestrict(); 4461 return VRQuals; 4462 } 4463 4464 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 4465 if (!ClassDecl->hasDefinition()) 4466 return VRQuals; 4467 4468 const UnresolvedSetImpl *Conversions = 4469 ClassDecl->getVisibleConversionFunctions(); 4470 4471 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 4472 E = Conversions->end(); I != E; ++I) { 4473 NamedDecl *D = I.getDecl(); 4474 if (isa<UsingShadowDecl>(D)) 4475 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4476 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 4477 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 4478 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 4479 CanTy = ResTypeRef->getPointeeType(); 4480 // Need to go down the pointer/mempointer chain and add qualifiers 4481 // as see them. 4482 bool done = false; 4483 while (!done) { 4484 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 4485 CanTy = ResTypePtr->getPointeeType(); 4486 else if (const MemberPointerType *ResTypeMPtr = 4487 CanTy->getAs<MemberPointerType>()) 4488 CanTy = ResTypeMPtr->getPointeeType(); 4489 else 4490 done = true; 4491 if (CanTy.isVolatileQualified()) 4492 VRQuals.addVolatile(); 4493 if (CanTy.isRestrictQualified()) 4494 VRQuals.addRestrict(); 4495 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 4496 return VRQuals; 4497 } 4498 } 4499 } 4500 return VRQuals; 4501} 4502 4503/// AddBuiltinOperatorCandidates - Add the appropriate built-in 4504/// operator overloads to the candidate set (C++ [over.built]), based 4505/// on the operator @p Op and the arguments given. For example, if the 4506/// operator is a binary '+', this routine might add "int 4507/// operator+(int, int)" to cover integer addition. 4508void 4509Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 4510 SourceLocation OpLoc, 4511 Expr **Args, unsigned NumArgs, 4512 OverloadCandidateSet& CandidateSet) { 4513 // The set of "promoted arithmetic types", which are the arithmetic 4514 // types are that preserved by promotion (C++ [over.built]p2). Note 4515 // that the first few of these types are the promoted integral 4516 // types; these types need to be first. 4517 // FIXME: What about complex? 4518 const unsigned FirstIntegralType = 0; 4519 const unsigned LastIntegralType = 15; 4520 const unsigned FirstPromotedIntegralType = 9, 4521 LastPromotedIntegralType = 15; 4522 const unsigned FirstPromotedArithmeticType = 9, 4523 LastPromotedArithmeticType = 18; 4524 const unsigned NumArithmeticTypes = 18; 4525 QualType ArithmeticTypes[NumArithmeticTypes] = { 4526 Context.BoolTy, Context.CharTy, Context.WCharTy, 4527 Context.Char16Ty, Context.Char32Ty, 4528 Context.SignedCharTy, Context.ShortTy, 4529 Context.UnsignedCharTy, Context.UnsignedShortTy, 4530 Context.IntTy, Context.LongTy, Context.LongLongTy, 4531 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy, 4532 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy 4533 }; 4534 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy && 4535 "Invalid first promoted integral type"); 4536 assert(ArithmeticTypes[LastPromotedIntegralType - 1] 4537 == Context.UnsignedLongLongTy && 4538 "Invalid last promoted integral type"); 4539 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy && 4540 "Invalid first promoted arithmetic type"); 4541 assert(ArithmeticTypes[LastPromotedArithmeticType - 1] 4542 == Context.LongDoubleTy && 4543 "Invalid last promoted arithmetic type"); 4544 4545 // Find all of the types that the arguments can convert to, but only 4546 // if the operator we're looking at has built-in operator candidates 4547 // that make use of these types. 4548 Qualifiers VisibleTypeConversionsQuals; 4549 VisibleTypeConversionsQuals.addConst(); 4550 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 4551 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 4552 4553 BuiltinCandidateTypeSet CandidateTypes(*this); 4554 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 4555 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(), 4556 OpLoc, 4557 true, 4558 (Op == OO_Exclaim || 4559 Op == OO_AmpAmp || 4560 Op == OO_PipePipe), 4561 VisibleTypeConversionsQuals); 4562 4563 // C++ [over.built]p1: 4564 // If there is a user-written candidate with the same name and parameter 4565 // types as a built-in candidate operator function, the built-in operator 4566 // function is hidden and is not included in the set of candidate functions. 4567 // 4568 // The text is actually in a note, but if we don't implement it then we end 4569 // up with ambiguities when the user provides an overloaded operator for 4570 // an enumeration type. Note that only enumeration types have this problem, 4571 // so we track which enumeration types we've seen operators for. 4572 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 4573 UserDefinedBinaryOperators; 4574 4575 if (CandidateTypes.enumeration_begin() != CandidateTypes.enumeration_end()) { 4576 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 4577 CEnd = CandidateSet.end(); 4578 C != CEnd; ++C) { 4579 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 4580 continue; 4581 4582 // Check if the first parameter is of enumeration type. 4583 QualType FirstParamType 4584 = C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 4585 if (!FirstParamType->isEnumeralType()) 4586 continue; 4587 4588 // Check if the second parameter is of enumeration type. 4589 QualType SecondParamType 4590 = C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 4591 if (!SecondParamType->isEnumeralType()) 4592 continue; 4593 4594 // Add this operator to the set of known user-defined operators. 4595 UserDefinedBinaryOperators.insert( 4596 std::make_pair(Context.getCanonicalType(FirstParamType), 4597 Context.getCanonicalType(SecondParamType))); 4598 } 4599 } 4600 4601 bool isComparison = false; 4602 switch (Op) { 4603 case OO_None: 4604 case NUM_OVERLOADED_OPERATORS: 4605 assert(false && "Expected an overloaded operator"); 4606 break; 4607 4608 case OO_Star: // '*' is either unary or binary 4609 if (NumArgs == 1) 4610 goto UnaryStar; 4611 else 4612 goto BinaryStar; 4613 break; 4614 4615 case OO_Plus: // '+' is either unary or binary 4616 if (NumArgs == 1) 4617 goto UnaryPlus; 4618 else 4619 goto BinaryPlus; 4620 break; 4621 4622 case OO_Minus: // '-' is either unary or binary 4623 if (NumArgs == 1) 4624 goto UnaryMinus; 4625 else 4626 goto BinaryMinus; 4627 break; 4628 4629 case OO_Amp: // '&' is either unary or binary 4630 if (NumArgs == 1) 4631 goto UnaryAmp; 4632 else 4633 goto BinaryAmp; 4634 4635 case OO_PlusPlus: 4636 case OO_MinusMinus: 4637 // C++ [over.built]p3: 4638 // 4639 // For every pair (T, VQ), where T is an arithmetic type, and VQ 4640 // is either volatile or empty, there exist candidate operator 4641 // functions of the form 4642 // 4643 // VQ T& operator++(VQ T&); 4644 // T operator++(VQ T&, int); 4645 // 4646 // C++ [over.built]p4: 4647 // 4648 // For every pair (T, VQ), where T is an arithmetic type other 4649 // than bool, and VQ is either volatile or empty, there exist 4650 // candidate operator functions of the form 4651 // 4652 // VQ T& operator--(VQ T&); 4653 // T operator--(VQ T&, int); 4654 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 4655 Arith < NumArithmeticTypes; ++Arith) { 4656 QualType ArithTy = ArithmeticTypes[Arith]; 4657 QualType ParamTypes[2] 4658 = { Context.getLValueReferenceType(ArithTy), Context.IntTy }; 4659 4660 // Non-volatile version. 4661 if (NumArgs == 1) 4662 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 4663 else 4664 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 4665 // heuristic to reduce number of builtin candidates in the set. 4666 // Add volatile version only if there are conversions to a volatile type. 4667 if (VisibleTypeConversionsQuals.hasVolatile()) { 4668 // Volatile version 4669 ParamTypes[0] 4670 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy)); 4671 if (NumArgs == 1) 4672 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 4673 else 4674 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 4675 } 4676 } 4677 4678 // C++ [over.built]p5: 4679 // 4680 // For every pair (T, VQ), where T is a cv-qualified or 4681 // cv-unqualified object type, and VQ is either volatile or 4682 // empty, there exist candidate operator functions of the form 4683 // 4684 // T*VQ& operator++(T*VQ&); 4685 // T*VQ& operator--(T*VQ&); 4686 // T* operator++(T*VQ&, int); 4687 // T* operator--(T*VQ&, int); 4688 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 4689 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 4690 // Skip pointer types that aren't pointers to object types. 4691 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType()) 4692 continue; 4693 4694 QualType ParamTypes[2] = { 4695 Context.getLValueReferenceType(*Ptr), Context.IntTy 4696 }; 4697 4698 // Without volatile 4699 if (NumArgs == 1) 4700 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 4701 else 4702 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 4703 4704 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() && 4705 VisibleTypeConversionsQuals.hasVolatile()) { 4706 // With volatile 4707 ParamTypes[0] 4708 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr)); 4709 if (NumArgs == 1) 4710 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 4711 else 4712 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 4713 } 4714 } 4715 break; 4716 4717 UnaryStar: 4718 // C++ [over.built]p6: 4719 // For every cv-qualified or cv-unqualified object type T, there 4720 // exist candidate operator functions of the form 4721 // 4722 // T& operator*(T*); 4723 // 4724 // C++ [over.built]p7: 4725 // For every function type T, there exist candidate operator 4726 // functions of the form 4727 // T& operator*(T*); 4728 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 4729 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 4730 QualType ParamTy = *Ptr; 4731 QualType PointeeTy = ParamTy->getPointeeType(); 4732 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy), 4733 &ParamTy, Args, 1, CandidateSet); 4734 } 4735 break; 4736 4737 UnaryPlus: 4738 // C++ [over.built]p8: 4739 // For every type T, there exist candidate operator functions of 4740 // the form 4741 // 4742 // T* operator+(T*); 4743 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 4744 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 4745 QualType ParamTy = *Ptr; 4746 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 4747 } 4748 4749 // Fall through 4750 4751 UnaryMinus: 4752 // C++ [over.built]p9: 4753 // For every promoted arithmetic type T, there exist candidate 4754 // operator functions of the form 4755 // 4756 // T operator+(T); 4757 // T operator-(T); 4758 for (unsigned Arith = FirstPromotedArithmeticType; 4759 Arith < LastPromotedArithmeticType; ++Arith) { 4760 QualType ArithTy = ArithmeticTypes[Arith]; 4761 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 4762 } 4763 4764 // Extension: We also add these operators for vector types. 4765 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(), 4766 VecEnd = CandidateTypes.vector_end(); 4767 Vec != VecEnd; ++Vec) { 4768 QualType VecTy = *Vec; 4769 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 4770 } 4771 break; 4772 4773 case OO_Tilde: 4774 // C++ [over.built]p10: 4775 // For every promoted integral type T, there exist candidate 4776 // operator functions of the form 4777 // 4778 // T operator~(T); 4779 for (unsigned Int = FirstPromotedIntegralType; 4780 Int < LastPromotedIntegralType; ++Int) { 4781 QualType IntTy = ArithmeticTypes[Int]; 4782 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 4783 } 4784 4785 // Extension: We also add this operator for vector types. 4786 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(), 4787 VecEnd = CandidateTypes.vector_end(); 4788 Vec != VecEnd; ++Vec) { 4789 QualType VecTy = *Vec; 4790 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 4791 } 4792 break; 4793 4794 case OO_New: 4795 case OO_Delete: 4796 case OO_Array_New: 4797 case OO_Array_Delete: 4798 case OO_Call: 4799 assert(false && "Special operators don't use AddBuiltinOperatorCandidates"); 4800 break; 4801 4802 case OO_Comma: 4803 UnaryAmp: 4804 case OO_Arrow: 4805 // C++ [over.match.oper]p3: 4806 // -- For the operator ',', the unary operator '&', or the 4807 // operator '->', the built-in candidates set is empty. 4808 break; 4809 4810 case OO_EqualEqual: 4811 case OO_ExclaimEqual: 4812 // C++ [over.match.oper]p16: 4813 // For every pointer to member type T, there exist candidate operator 4814 // functions of the form 4815 // 4816 // bool operator==(T,T); 4817 // bool operator!=(T,T); 4818 for (BuiltinCandidateTypeSet::iterator 4819 MemPtr = CandidateTypes.member_pointer_begin(), 4820 MemPtrEnd = CandidateTypes.member_pointer_end(); 4821 MemPtr != MemPtrEnd; 4822 ++MemPtr) { 4823 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 4824 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 4825 } 4826 4827 // Fall through 4828 4829 case OO_Less: 4830 case OO_Greater: 4831 case OO_LessEqual: 4832 case OO_GreaterEqual: 4833 // C++ [over.built]p15: 4834 // 4835 // For every pointer or enumeration type T, there exist 4836 // candidate operator functions of the form 4837 // 4838 // bool operator<(T, T); 4839 // bool operator>(T, T); 4840 // bool operator<=(T, T); 4841 // bool operator>=(T, T); 4842 // bool operator==(T, T); 4843 // bool operator!=(T, T); 4844 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 4845 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 4846 QualType ParamTypes[2] = { *Ptr, *Ptr }; 4847 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 4848 } 4849 for (BuiltinCandidateTypeSet::iterator Enum 4850 = CandidateTypes.enumeration_begin(); 4851 Enum != CandidateTypes.enumeration_end(); ++Enum) { 4852 QualType ParamTypes[2] = { *Enum, *Enum }; 4853 CanQualType CanonType = Context.getCanonicalType(*Enum); 4854 if (!UserDefinedBinaryOperators.count( 4855 std::make_pair(CanonType, CanonType))) 4856 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 4857 } 4858 4859 // Fall through. 4860 isComparison = true; 4861 4862 BinaryPlus: 4863 BinaryMinus: 4864 if (!isComparison) { 4865 // We didn't fall through, so we must have OO_Plus or OO_Minus. 4866 4867 // C++ [over.built]p13: 4868 // 4869 // For every cv-qualified or cv-unqualified object type T 4870 // there exist candidate operator functions of the form 4871 // 4872 // T* operator+(T*, ptrdiff_t); 4873 // T& operator[](T*, ptrdiff_t); [BELOW] 4874 // T* operator-(T*, ptrdiff_t); 4875 // T* operator+(ptrdiff_t, T*); 4876 // T& operator[](ptrdiff_t, T*); [BELOW] 4877 // 4878 // C++ [over.built]p14: 4879 // 4880 // For every T, where T is a pointer to object type, there 4881 // exist candidate operator functions of the form 4882 // 4883 // ptrdiff_t operator-(T, T); 4884 for (BuiltinCandidateTypeSet::iterator Ptr 4885 = CandidateTypes.pointer_begin(); 4886 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 4887 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 4888 4889 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 4890 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 4891 4892 if (Op == OO_Plus) { 4893 // T* operator+(ptrdiff_t, T*); 4894 ParamTypes[0] = ParamTypes[1]; 4895 ParamTypes[1] = *Ptr; 4896 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 4897 } else { 4898 // ptrdiff_t operator-(T, T); 4899 ParamTypes[1] = *Ptr; 4900 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes, 4901 Args, 2, CandidateSet); 4902 } 4903 } 4904 } 4905 // Fall through 4906 4907 case OO_Slash: 4908 BinaryStar: 4909 Conditional: 4910 // C++ [over.built]p12: 4911 // 4912 // For every pair of promoted arithmetic types L and R, there 4913 // exist candidate operator functions of the form 4914 // 4915 // LR operator*(L, R); 4916 // LR operator/(L, R); 4917 // LR operator+(L, R); 4918 // LR operator-(L, R); 4919 // bool operator<(L, R); 4920 // bool operator>(L, R); 4921 // bool operator<=(L, R); 4922 // bool operator>=(L, R); 4923 // bool operator==(L, R); 4924 // bool operator!=(L, R); 4925 // 4926 // where LR is the result of the usual arithmetic conversions 4927 // between types L and R. 4928 // 4929 // C++ [over.built]p24: 4930 // 4931 // For every pair of promoted arithmetic types L and R, there exist 4932 // candidate operator functions of the form 4933 // 4934 // LR operator?(bool, L, R); 4935 // 4936 // where LR is the result of the usual arithmetic conversions 4937 // between types L and R. 4938 // Our candidates ignore the first parameter. 4939 for (unsigned Left = FirstPromotedArithmeticType; 4940 Left < LastPromotedArithmeticType; ++Left) { 4941 for (unsigned Right = FirstPromotedArithmeticType; 4942 Right < LastPromotedArithmeticType; ++Right) { 4943 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 4944 QualType Result 4945 = isComparison 4946 ? Context.BoolTy 4947 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]); 4948 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 4949 } 4950 } 4951 4952 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 4953 // conditional operator for vector types. 4954 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(), 4955 Vec1End = CandidateTypes.vector_end(); 4956 Vec1 != Vec1End; ++Vec1) 4957 for (BuiltinCandidateTypeSet::iterator 4958 Vec2 = CandidateTypes.vector_begin(), 4959 Vec2End = CandidateTypes.vector_end(); 4960 Vec2 != Vec2End; ++Vec2) { 4961 QualType LandR[2] = { *Vec1, *Vec2 }; 4962 QualType Result; 4963 if (isComparison) 4964 Result = Context.BoolTy; 4965 else { 4966 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 4967 Result = *Vec1; 4968 else 4969 Result = *Vec2; 4970 } 4971 4972 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 4973 } 4974 4975 break; 4976 4977 case OO_Percent: 4978 BinaryAmp: 4979 case OO_Caret: 4980 case OO_Pipe: 4981 case OO_LessLess: 4982 case OO_GreaterGreater: 4983 // C++ [over.built]p17: 4984 // 4985 // For every pair of promoted integral types L and R, there 4986 // exist candidate operator functions of the form 4987 // 4988 // LR operator%(L, R); 4989 // LR operator&(L, R); 4990 // LR operator^(L, R); 4991 // LR operator|(L, R); 4992 // L operator<<(L, R); 4993 // L operator>>(L, R); 4994 // 4995 // where LR is the result of the usual arithmetic conversions 4996 // between types L and R. 4997 for (unsigned Left = FirstPromotedIntegralType; 4998 Left < LastPromotedIntegralType; ++Left) { 4999 for (unsigned Right = FirstPromotedIntegralType; 5000 Right < LastPromotedIntegralType; ++Right) { 5001 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 5002 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 5003 ? LandR[0] 5004 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]); 5005 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 5006 } 5007 } 5008 break; 5009 5010 case OO_Equal: 5011 // C++ [over.built]p20: 5012 // 5013 // For every pair (T, VQ), where T is an enumeration or 5014 // pointer to member type and VQ is either volatile or 5015 // empty, there exist candidate operator functions of the form 5016 // 5017 // VQ T& operator=(VQ T&, T); 5018 for (BuiltinCandidateTypeSet::iterator 5019 Enum = CandidateTypes.enumeration_begin(), 5020 EnumEnd = CandidateTypes.enumeration_end(); 5021 Enum != EnumEnd; ++Enum) 5022 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2, 5023 CandidateSet); 5024 for (BuiltinCandidateTypeSet::iterator 5025 MemPtr = CandidateTypes.member_pointer_begin(), 5026 MemPtrEnd = CandidateTypes.member_pointer_end(); 5027 MemPtr != MemPtrEnd; ++MemPtr) 5028 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2, 5029 CandidateSet); 5030 5031 // Fall through. 5032 5033 case OO_PlusEqual: 5034 case OO_MinusEqual: 5035 // C++ [over.built]p19: 5036 // 5037 // For every pair (T, VQ), where T is any type and VQ is either 5038 // volatile or empty, there exist candidate operator functions 5039 // of the form 5040 // 5041 // T*VQ& operator=(T*VQ&, T*); 5042 // 5043 // C++ [over.built]p21: 5044 // 5045 // For every pair (T, VQ), where T is a cv-qualified or 5046 // cv-unqualified object type and VQ is either volatile or 5047 // empty, there exist candidate operator functions of the form 5048 // 5049 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 5050 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 5051 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 5052 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 5053 QualType ParamTypes[2]; 5054 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType(); 5055 5056 // non-volatile version 5057 ParamTypes[0] = Context.getLValueReferenceType(*Ptr); 5058 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5059 /*IsAssigmentOperator=*/Op == OO_Equal); 5060 5061 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() && 5062 VisibleTypeConversionsQuals.hasVolatile()) { 5063 // volatile version 5064 ParamTypes[0] 5065 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr)); 5066 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5067 /*IsAssigmentOperator=*/Op == OO_Equal); 5068 } 5069 } 5070 // Fall through. 5071 5072 case OO_StarEqual: 5073 case OO_SlashEqual: 5074 // C++ [over.built]p18: 5075 // 5076 // For every triple (L, VQ, R), where L is an arithmetic type, 5077 // VQ is either volatile or empty, and R is a promoted 5078 // arithmetic type, there exist candidate operator functions of 5079 // the form 5080 // 5081 // VQ L& operator=(VQ L&, R); 5082 // VQ L& operator*=(VQ L&, R); 5083 // VQ L& operator/=(VQ L&, R); 5084 // VQ L& operator+=(VQ L&, R); 5085 // VQ L& operator-=(VQ L&, R); 5086 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 5087 for (unsigned Right = FirstPromotedArithmeticType; 5088 Right < LastPromotedArithmeticType; ++Right) { 5089 QualType ParamTypes[2]; 5090 ParamTypes[1] = ArithmeticTypes[Right]; 5091 5092 // Add this built-in operator as a candidate (VQ is empty). 5093 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]); 5094 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5095 /*IsAssigmentOperator=*/Op == OO_Equal); 5096 5097 // Add this built-in operator as a candidate (VQ is 'volatile'). 5098 if (VisibleTypeConversionsQuals.hasVolatile()) { 5099 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]); 5100 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]); 5101 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5102 /*IsAssigmentOperator=*/Op == OO_Equal); 5103 } 5104 } 5105 } 5106 5107 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 5108 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(), 5109 Vec1End = CandidateTypes.vector_end(); 5110 Vec1 != Vec1End; ++Vec1) 5111 for (BuiltinCandidateTypeSet::iterator 5112 Vec2 = CandidateTypes.vector_begin(), 5113 Vec2End = CandidateTypes.vector_end(); 5114 Vec2 != Vec2End; ++Vec2) { 5115 QualType ParamTypes[2]; 5116 ParamTypes[1] = *Vec2; 5117 // Add this built-in operator as a candidate (VQ is empty). 5118 ParamTypes[0] = Context.getLValueReferenceType(*Vec1); 5119 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5120 /*IsAssigmentOperator=*/Op == OO_Equal); 5121 5122 // Add this built-in operator as a candidate (VQ is 'volatile'). 5123 if (VisibleTypeConversionsQuals.hasVolatile()) { 5124 ParamTypes[0] = Context.getVolatileType(*Vec1); 5125 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]); 5126 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5127 /*IsAssigmentOperator=*/Op == OO_Equal); 5128 } 5129 } 5130 break; 5131 5132 case OO_PercentEqual: 5133 case OO_LessLessEqual: 5134 case OO_GreaterGreaterEqual: 5135 case OO_AmpEqual: 5136 case OO_CaretEqual: 5137 case OO_PipeEqual: 5138 // C++ [over.built]p22: 5139 // 5140 // For every triple (L, VQ, R), where L is an integral type, VQ 5141 // is either volatile or empty, and R is a promoted integral 5142 // type, there exist candidate operator functions of the form 5143 // 5144 // VQ L& operator%=(VQ L&, R); 5145 // VQ L& operator<<=(VQ L&, R); 5146 // VQ L& operator>>=(VQ L&, R); 5147 // VQ L& operator&=(VQ L&, R); 5148 // VQ L& operator^=(VQ L&, R); 5149 // VQ L& operator|=(VQ L&, R); 5150 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 5151 for (unsigned Right = FirstPromotedIntegralType; 5152 Right < LastPromotedIntegralType; ++Right) { 5153 QualType ParamTypes[2]; 5154 ParamTypes[1] = ArithmeticTypes[Right]; 5155 5156 // Add this built-in operator as a candidate (VQ is empty). 5157 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]); 5158 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 5159 if (VisibleTypeConversionsQuals.hasVolatile()) { 5160 // Add this built-in operator as a candidate (VQ is 'volatile'). 5161 ParamTypes[0] = ArithmeticTypes[Left]; 5162 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]); 5163 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]); 5164 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 5165 } 5166 } 5167 } 5168 break; 5169 5170 case OO_Exclaim: { 5171 // C++ [over.operator]p23: 5172 // 5173 // There also exist candidate operator functions of the form 5174 // 5175 // bool operator!(bool); 5176 // bool operator&&(bool, bool); [BELOW] 5177 // bool operator||(bool, bool); [BELOW] 5178 QualType ParamTy = Context.BoolTy; 5179 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 5180 /*IsAssignmentOperator=*/false, 5181 /*NumContextualBoolArguments=*/1); 5182 break; 5183 } 5184 5185 case OO_AmpAmp: 5186 case OO_PipePipe: { 5187 // C++ [over.operator]p23: 5188 // 5189 // There also exist candidate operator functions of the form 5190 // 5191 // bool operator!(bool); [ABOVE] 5192 // bool operator&&(bool, bool); 5193 // bool operator||(bool, bool); 5194 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy }; 5195 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 5196 /*IsAssignmentOperator=*/false, 5197 /*NumContextualBoolArguments=*/2); 5198 break; 5199 } 5200 5201 case OO_Subscript: 5202 // C++ [over.built]p13: 5203 // 5204 // For every cv-qualified or cv-unqualified object type T there 5205 // exist candidate operator functions of the form 5206 // 5207 // T* operator+(T*, ptrdiff_t); [ABOVE] 5208 // T& operator[](T*, ptrdiff_t); 5209 // T* operator-(T*, ptrdiff_t); [ABOVE] 5210 // T* operator+(ptrdiff_t, T*); [ABOVE] 5211 // T& operator[](ptrdiff_t, T*); 5212 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 5213 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 5214 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 5215 QualType PointeeType = (*Ptr)->getPointeeType(); 5216 QualType ResultTy = Context.getLValueReferenceType(PointeeType); 5217 5218 // T& operator[](T*, ptrdiff_t) 5219 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 5220 5221 // T& operator[](ptrdiff_t, T*); 5222 ParamTypes[0] = ParamTypes[1]; 5223 ParamTypes[1] = *Ptr; 5224 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 5225 } 5226 break; 5227 5228 case OO_ArrowStar: 5229 // C++ [over.built]p11: 5230 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 5231 // C1 is the same type as C2 or is a derived class of C2, T is an object 5232 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 5233 // there exist candidate operator functions of the form 5234 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 5235 // where CV12 is the union of CV1 and CV2. 5236 { 5237 for (BuiltinCandidateTypeSet::iterator Ptr = 5238 CandidateTypes.pointer_begin(); 5239 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 5240 QualType C1Ty = (*Ptr); 5241 QualType C1; 5242 QualifierCollector Q1; 5243 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 5244 if (!isa<RecordType>(C1)) 5245 continue; 5246 // heuristic to reduce number of builtin candidates in the set. 5247 // Add volatile/restrict version only if there are conversions to a 5248 // volatile/restrict type. 5249 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 5250 continue; 5251 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 5252 continue; 5253 for (BuiltinCandidateTypeSet::iterator 5254 MemPtr = CandidateTypes.member_pointer_begin(), 5255 MemPtrEnd = CandidateTypes.member_pointer_end(); 5256 MemPtr != MemPtrEnd; ++MemPtr) { 5257 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 5258 QualType C2 = QualType(mptr->getClass(), 0); 5259 C2 = C2.getUnqualifiedType(); 5260 if (C1 != C2 && !IsDerivedFrom(C1, C2)) 5261 break; 5262 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 5263 // build CV12 T& 5264 QualType T = mptr->getPointeeType(); 5265 if (!VisibleTypeConversionsQuals.hasVolatile() && 5266 T.isVolatileQualified()) 5267 continue; 5268 if (!VisibleTypeConversionsQuals.hasRestrict() && 5269 T.isRestrictQualified()) 5270 continue; 5271 T = Q1.apply(T); 5272 QualType ResultTy = Context.getLValueReferenceType(T); 5273 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 5274 } 5275 } 5276 } 5277 break; 5278 5279 case OO_Conditional: 5280 // Note that we don't consider the first argument, since it has been 5281 // contextually converted to bool long ago. The candidates below are 5282 // therefore added as binary. 5283 // 5284 // C++ [over.built]p25: 5285 // For every type T, where T is a pointer, pointer-to-member, or scoped 5286 // enumeration type, there exist candidate operator functions of the form 5287 // 5288 // T operator?(bool, T, T); 5289 // 5290 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(), 5291 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) { 5292 QualType ParamTypes[2] = { *Ptr, *Ptr }; 5293 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 5294 } 5295 for (BuiltinCandidateTypeSet::iterator Ptr = 5296 CandidateTypes.member_pointer_begin(), 5297 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) { 5298 QualType ParamTypes[2] = { *Ptr, *Ptr }; 5299 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 5300 } 5301 if (getLangOptions().CPlusPlus0x) 5302 for (BuiltinCandidateTypeSet::iterator Enum = 5303 CandidateTypes.enumeration_begin(), 5304 E = CandidateTypes.enumeration_end(); Enum != E; ++Enum) { 5305 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 5306 continue; 5307 QualType ParamTypes[2] = { *Enum, *Enum }; 5308 AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 5309 } 5310 goto Conditional; 5311 } 5312} 5313 5314/// \brief Add function candidates found via argument-dependent lookup 5315/// to the set of overloading candidates. 5316/// 5317/// This routine performs argument-dependent name lookup based on the 5318/// given function name (which may also be an operator name) and adds 5319/// all of the overload candidates found by ADL to the overload 5320/// candidate set (C++ [basic.lookup.argdep]). 5321void 5322Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 5323 bool Operator, 5324 Expr **Args, unsigned NumArgs, 5325 const TemplateArgumentListInfo *ExplicitTemplateArgs, 5326 OverloadCandidateSet& CandidateSet, 5327 bool PartialOverloading) { 5328 ADLResult Fns; 5329 5330 // FIXME: This approach for uniquing ADL results (and removing 5331 // redundant candidates from the set) relies on pointer-equality, 5332 // which means we need to key off the canonical decl. However, 5333 // always going back to the canonical decl might not get us the 5334 // right set of default arguments. What default arguments are 5335 // we supposed to consider on ADL candidates, anyway? 5336 5337 // FIXME: Pass in the explicit template arguments? 5338 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns); 5339 5340 // Erase all of the candidates we already knew about. 5341 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 5342 CandEnd = CandidateSet.end(); 5343 Cand != CandEnd; ++Cand) 5344 if (Cand->Function) { 5345 Fns.erase(Cand->Function); 5346 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 5347 Fns.erase(FunTmpl); 5348 } 5349 5350 // For each of the ADL candidates we found, add it to the overload 5351 // set. 5352 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 5353 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 5354 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 5355 if (ExplicitTemplateArgs) 5356 continue; 5357 5358 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet, 5359 false, PartialOverloading); 5360 } else 5361 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 5362 FoundDecl, ExplicitTemplateArgs, 5363 Args, NumArgs, CandidateSet); 5364 } 5365} 5366 5367/// isBetterOverloadCandidate - Determines whether the first overload 5368/// candidate is a better candidate than the second (C++ 13.3.3p1). 5369bool 5370isBetterOverloadCandidate(Sema &S, 5371 const OverloadCandidate& Cand1, 5372 const OverloadCandidate& Cand2, 5373 SourceLocation Loc, 5374 bool UserDefinedConversion) { 5375 // Define viable functions to be better candidates than non-viable 5376 // functions. 5377 if (!Cand2.Viable) 5378 return Cand1.Viable; 5379 else if (!Cand1.Viable) 5380 return false; 5381 5382 // C++ [over.match.best]p1: 5383 // 5384 // -- if F is a static member function, ICS1(F) is defined such 5385 // that ICS1(F) is neither better nor worse than ICS1(G) for 5386 // any function G, and, symmetrically, ICS1(G) is neither 5387 // better nor worse than ICS1(F). 5388 unsigned StartArg = 0; 5389 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 5390 StartArg = 1; 5391 5392 // C++ [over.match.best]p1: 5393 // A viable function F1 is defined to be a better function than another 5394 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 5395 // conversion sequence than ICSi(F2), and then... 5396 unsigned NumArgs = Cand1.Conversions.size(); 5397 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 5398 bool HasBetterConversion = false; 5399 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 5400 switch (CompareImplicitConversionSequences(S, 5401 Cand1.Conversions[ArgIdx], 5402 Cand2.Conversions[ArgIdx])) { 5403 case ImplicitConversionSequence::Better: 5404 // Cand1 has a better conversion sequence. 5405 HasBetterConversion = true; 5406 break; 5407 5408 case ImplicitConversionSequence::Worse: 5409 // Cand1 can't be better than Cand2. 5410 return false; 5411 5412 case ImplicitConversionSequence::Indistinguishable: 5413 // Do nothing. 5414 break; 5415 } 5416 } 5417 5418 // -- for some argument j, ICSj(F1) is a better conversion sequence than 5419 // ICSj(F2), or, if not that, 5420 if (HasBetterConversion) 5421 return true; 5422 5423 // - F1 is a non-template function and F2 is a function template 5424 // specialization, or, if not that, 5425 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 5426 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 5427 return true; 5428 5429 // -- F1 and F2 are function template specializations, and the function 5430 // template for F1 is more specialized than the template for F2 5431 // according to the partial ordering rules described in 14.5.5.2, or, 5432 // if not that, 5433 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 5434 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 5435 if (FunctionTemplateDecl *BetterTemplate 5436 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 5437 Cand2.Function->getPrimaryTemplate(), 5438 Loc, 5439 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 5440 : TPOC_Call)) 5441 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 5442 5443 // -- the context is an initialization by user-defined conversion 5444 // (see 8.5, 13.3.1.5) and the standard conversion sequence 5445 // from the return type of F1 to the destination type (i.e., 5446 // the type of the entity being initialized) is a better 5447 // conversion sequence than the standard conversion sequence 5448 // from the return type of F2 to the destination type. 5449 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 5450 isa<CXXConversionDecl>(Cand1.Function) && 5451 isa<CXXConversionDecl>(Cand2.Function)) { 5452 switch (CompareStandardConversionSequences(S, 5453 Cand1.FinalConversion, 5454 Cand2.FinalConversion)) { 5455 case ImplicitConversionSequence::Better: 5456 // Cand1 has a better conversion sequence. 5457 return true; 5458 5459 case ImplicitConversionSequence::Worse: 5460 // Cand1 can't be better than Cand2. 5461 return false; 5462 5463 case ImplicitConversionSequence::Indistinguishable: 5464 // Do nothing 5465 break; 5466 } 5467 } 5468 5469 return false; 5470} 5471 5472/// \brief Computes the best viable function (C++ 13.3.3) 5473/// within an overload candidate set. 5474/// 5475/// \param CandidateSet the set of candidate functions. 5476/// 5477/// \param Loc the location of the function name (or operator symbol) for 5478/// which overload resolution occurs. 5479/// 5480/// \param Best f overload resolution was successful or found a deleted 5481/// function, Best points to the candidate function found. 5482/// 5483/// \returns The result of overload resolution. 5484OverloadingResult 5485OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 5486 iterator& Best, 5487 bool UserDefinedConversion) { 5488 // Find the best viable function. 5489 Best = end(); 5490 for (iterator Cand = begin(); Cand != end(); ++Cand) { 5491 if (Cand->Viable) 5492 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 5493 UserDefinedConversion)) 5494 Best = Cand; 5495 } 5496 5497 // If we didn't find any viable functions, abort. 5498 if (Best == end()) 5499 return OR_No_Viable_Function; 5500 5501 // Make sure that this function is better than every other viable 5502 // function. If not, we have an ambiguity. 5503 for (iterator Cand = begin(); Cand != end(); ++Cand) { 5504 if (Cand->Viable && 5505 Cand != Best && 5506 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 5507 UserDefinedConversion)) { 5508 Best = end(); 5509 return OR_Ambiguous; 5510 } 5511 } 5512 5513 // Best is the best viable function. 5514 if (Best->Function && 5515 (Best->Function->isDeleted() || 5516 Best->Function->getAttr<UnavailableAttr>())) 5517 return OR_Deleted; 5518 5519 // C++ [basic.def.odr]p2: 5520 // An overloaded function is used if it is selected by overload resolution 5521 // when referred to from a potentially-evaluated expression. [Note: this 5522 // covers calls to named functions (5.2.2), operator overloading 5523 // (clause 13), user-defined conversions (12.3.2), allocation function for 5524 // placement new (5.3.4), as well as non-default initialization (8.5). 5525 if (Best->Function) 5526 S.MarkDeclarationReferenced(Loc, Best->Function); 5527 5528 return OR_Success; 5529} 5530 5531namespace { 5532 5533enum OverloadCandidateKind { 5534 oc_function, 5535 oc_method, 5536 oc_constructor, 5537 oc_function_template, 5538 oc_method_template, 5539 oc_constructor_template, 5540 oc_implicit_default_constructor, 5541 oc_implicit_copy_constructor, 5542 oc_implicit_copy_assignment 5543}; 5544 5545OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 5546 FunctionDecl *Fn, 5547 std::string &Description) { 5548 bool isTemplate = false; 5549 5550 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 5551 isTemplate = true; 5552 Description = S.getTemplateArgumentBindingsText( 5553 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 5554 } 5555 5556 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 5557 if (!Ctor->isImplicit()) 5558 return isTemplate ? oc_constructor_template : oc_constructor; 5559 5560 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor 5561 : oc_implicit_default_constructor; 5562 } 5563 5564 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 5565 // This actually gets spelled 'candidate function' for now, but 5566 // it doesn't hurt to split it out. 5567 if (!Meth->isImplicit()) 5568 return isTemplate ? oc_method_template : oc_method; 5569 5570 assert(Meth->isCopyAssignmentOperator() 5571 && "implicit method is not copy assignment operator?"); 5572 return oc_implicit_copy_assignment; 5573 } 5574 5575 return isTemplate ? oc_function_template : oc_function; 5576} 5577 5578} // end anonymous namespace 5579 5580// Notes the location of an overload candidate. 5581void Sema::NoteOverloadCandidate(FunctionDecl *Fn) { 5582 std::string FnDesc; 5583 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 5584 Diag(Fn->getLocation(), diag::note_ovl_candidate) 5585 << (unsigned) K << FnDesc; 5586} 5587 5588/// Diagnoses an ambiguous conversion. The partial diagnostic is the 5589/// "lead" diagnostic; it will be given two arguments, the source and 5590/// target types of the conversion. 5591void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 5592 Sema &S, 5593 SourceLocation CaretLoc, 5594 const PartialDiagnostic &PDiag) const { 5595 S.Diag(CaretLoc, PDiag) 5596 << Ambiguous.getFromType() << Ambiguous.getToType(); 5597 for (AmbiguousConversionSequence::const_iterator 5598 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 5599 S.NoteOverloadCandidate(*I); 5600 } 5601} 5602 5603namespace { 5604 5605void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 5606 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 5607 assert(Conv.isBad()); 5608 assert(Cand->Function && "for now, candidate must be a function"); 5609 FunctionDecl *Fn = Cand->Function; 5610 5611 // There's a conversion slot for the object argument if this is a 5612 // non-constructor method. Note that 'I' corresponds the 5613 // conversion-slot index. 5614 bool isObjectArgument = false; 5615 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 5616 if (I == 0) 5617 isObjectArgument = true; 5618 else 5619 I--; 5620 } 5621 5622 std::string FnDesc; 5623 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 5624 5625 Expr *FromExpr = Conv.Bad.FromExpr; 5626 QualType FromTy = Conv.Bad.getFromType(); 5627 QualType ToTy = Conv.Bad.getToType(); 5628 5629 if (FromTy == S.Context.OverloadTy) { 5630 assert(FromExpr && "overload set argument came from implicit argument?"); 5631 Expr *E = FromExpr->IgnoreParens(); 5632 if (isa<UnaryOperator>(E)) 5633 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 5634 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 5635 5636 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 5637 << (unsigned) FnKind << FnDesc 5638 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5639 << ToTy << Name << I+1; 5640 return; 5641 } 5642 5643 // Do some hand-waving analysis to see if the non-viability is due 5644 // to a qualifier mismatch. 5645 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 5646 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 5647 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 5648 CToTy = RT->getPointeeType(); 5649 else { 5650 // TODO: detect and diagnose the full richness of const mismatches. 5651 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 5652 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 5653 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 5654 } 5655 5656 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 5657 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 5658 // It is dumb that we have to do this here. 5659 while (isa<ArrayType>(CFromTy)) 5660 CFromTy = CFromTy->getAs<ArrayType>()->getElementType(); 5661 while (isa<ArrayType>(CToTy)) 5662 CToTy = CFromTy->getAs<ArrayType>()->getElementType(); 5663 5664 Qualifiers FromQs = CFromTy.getQualifiers(); 5665 Qualifiers ToQs = CToTy.getQualifiers(); 5666 5667 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 5668 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 5669 << (unsigned) FnKind << FnDesc 5670 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5671 << FromTy 5672 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 5673 << (unsigned) isObjectArgument << I+1; 5674 return; 5675 } 5676 5677 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5678 assert(CVR && "unexpected qualifiers mismatch"); 5679 5680 if (isObjectArgument) { 5681 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 5682 << (unsigned) FnKind << FnDesc 5683 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5684 << FromTy << (CVR - 1); 5685 } else { 5686 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 5687 << (unsigned) FnKind << FnDesc 5688 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5689 << FromTy << (CVR - 1) << I+1; 5690 } 5691 return; 5692 } 5693 5694 // Diagnose references or pointers to incomplete types differently, 5695 // since it's far from impossible that the incompleteness triggered 5696 // the failure. 5697 QualType TempFromTy = FromTy.getNonReferenceType(); 5698 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 5699 TempFromTy = PTy->getPointeeType(); 5700 if (TempFromTy->isIncompleteType()) { 5701 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 5702 << (unsigned) FnKind << FnDesc 5703 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5704 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 5705 return; 5706 } 5707 5708 // Diagnose base -> derived pointer conversions. 5709 unsigned BaseToDerivedConversion = 0; 5710 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 5711 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 5712 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 5713 FromPtrTy->getPointeeType()) && 5714 !FromPtrTy->getPointeeType()->isIncompleteType() && 5715 !ToPtrTy->getPointeeType()->isIncompleteType() && 5716 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 5717 FromPtrTy->getPointeeType())) 5718 BaseToDerivedConversion = 1; 5719 } 5720 } else if (const ObjCObjectPointerType *FromPtrTy 5721 = FromTy->getAs<ObjCObjectPointerType>()) { 5722 if (const ObjCObjectPointerType *ToPtrTy 5723 = ToTy->getAs<ObjCObjectPointerType>()) 5724 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 5725 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 5726 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 5727 FromPtrTy->getPointeeType()) && 5728 FromIface->isSuperClassOf(ToIface)) 5729 BaseToDerivedConversion = 2; 5730 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 5731 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 5732 !FromTy->isIncompleteType() && 5733 !ToRefTy->getPointeeType()->isIncompleteType() && 5734 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) 5735 BaseToDerivedConversion = 3; 5736 } 5737 5738 if (BaseToDerivedConversion) { 5739 S.Diag(Fn->getLocation(), 5740 diag::note_ovl_candidate_bad_base_to_derived_conv) 5741 << (unsigned) FnKind << FnDesc 5742 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5743 << (BaseToDerivedConversion - 1) 5744 << FromTy << ToTy << I+1; 5745 return; 5746 } 5747 5748 // TODO: specialize more based on the kind of mismatch 5749 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv) 5750 << (unsigned) FnKind << FnDesc 5751 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 5752 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 5753} 5754 5755void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 5756 unsigned NumFormalArgs) { 5757 // TODO: treat calls to a missing default constructor as a special case 5758 5759 FunctionDecl *Fn = Cand->Function; 5760 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 5761 5762 unsigned MinParams = Fn->getMinRequiredArguments(); 5763 5764 // at least / at most / exactly 5765 // FIXME: variadic templates "at most" should account for parameter packs 5766 unsigned mode, modeCount; 5767 if (NumFormalArgs < MinParams) { 5768 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 5769 (Cand->FailureKind == ovl_fail_bad_deduction && 5770 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 5771 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic()) 5772 mode = 0; // "at least" 5773 else 5774 mode = 2; // "exactly" 5775 modeCount = MinParams; 5776 } else { 5777 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 5778 (Cand->FailureKind == ovl_fail_bad_deduction && 5779 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 5780 if (MinParams != FnTy->getNumArgs()) 5781 mode = 1; // "at most" 5782 else 5783 mode = 2; // "exactly" 5784 modeCount = FnTy->getNumArgs(); 5785 } 5786 5787 std::string Description; 5788 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 5789 5790 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 5791 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 5792 << modeCount << NumFormalArgs; 5793} 5794 5795/// Diagnose a failed template-argument deduction. 5796void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 5797 Expr **Args, unsigned NumArgs) { 5798 FunctionDecl *Fn = Cand->Function; // pattern 5799 5800 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 5801 NamedDecl *ParamD; 5802 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 5803 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 5804 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 5805 switch (Cand->DeductionFailure.Result) { 5806 case Sema::TDK_Success: 5807 llvm_unreachable("TDK_success while diagnosing bad deduction"); 5808 5809 case Sema::TDK_Incomplete: { 5810 assert(ParamD && "no parameter found for incomplete deduction result"); 5811 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 5812 << ParamD->getDeclName(); 5813 return; 5814 } 5815 5816 case Sema::TDK_Underqualified: { 5817 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 5818 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 5819 5820 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 5821 5822 // Param will have been canonicalized, but it should just be a 5823 // qualified version of ParamD, so move the qualifiers to that. 5824 QualifierCollector Qs(S.Context); 5825 Qs.strip(Param); 5826 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl()); 5827 assert(S.Context.hasSameType(Param, NonCanonParam)); 5828 5829 // Arg has also been canonicalized, but there's nothing we can do 5830 // about that. It also doesn't matter as much, because it won't 5831 // have any template parameters in it (because deduction isn't 5832 // done on dependent types). 5833 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 5834 5835 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 5836 << ParamD->getDeclName() << Arg << NonCanonParam; 5837 return; 5838 } 5839 5840 case Sema::TDK_Inconsistent: { 5841 assert(ParamD && "no parameter found for inconsistent deduction result"); 5842 int which = 0; 5843 if (isa<TemplateTypeParmDecl>(ParamD)) 5844 which = 0; 5845 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 5846 which = 1; 5847 else { 5848 which = 2; 5849 } 5850 5851 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 5852 << which << ParamD->getDeclName() 5853 << *Cand->DeductionFailure.getFirstArg() 5854 << *Cand->DeductionFailure.getSecondArg(); 5855 return; 5856 } 5857 5858 case Sema::TDK_InvalidExplicitArguments: 5859 assert(ParamD && "no parameter found for invalid explicit arguments"); 5860 if (ParamD->getDeclName()) 5861 S.Diag(Fn->getLocation(), 5862 diag::note_ovl_candidate_explicit_arg_mismatch_named) 5863 << ParamD->getDeclName(); 5864 else { 5865 int index = 0; 5866 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 5867 index = TTP->getIndex(); 5868 else if (NonTypeTemplateParmDecl *NTTP 5869 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 5870 index = NTTP->getIndex(); 5871 else 5872 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 5873 S.Diag(Fn->getLocation(), 5874 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 5875 << (index + 1); 5876 } 5877 return; 5878 5879 case Sema::TDK_TooManyArguments: 5880 case Sema::TDK_TooFewArguments: 5881 DiagnoseArityMismatch(S, Cand, NumArgs); 5882 return; 5883 5884 case Sema::TDK_InstantiationDepth: 5885 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 5886 return; 5887 5888 case Sema::TDK_SubstitutionFailure: { 5889 std::string ArgString; 5890 if (TemplateArgumentList *Args 5891 = Cand->DeductionFailure.getTemplateArgumentList()) 5892 ArgString = S.getTemplateArgumentBindingsText( 5893 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), 5894 *Args); 5895 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 5896 << ArgString; 5897 return; 5898 } 5899 5900 // TODO: diagnose these individually, then kill off 5901 // note_ovl_candidate_bad_deduction, which is uselessly vague. 5902 case Sema::TDK_NonDeducedMismatch: 5903 case Sema::TDK_FailedOverloadResolution: 5904 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 5905 return; 5906 } 5907} 5908 5909/// Generates a 'note' diagnostic for an overload candidate. We've 5910/// already generated a primary error at the call site. 5911/// 5912/// It really does need to be a single diagnostic with its caret 5913/// pointed at the candidate declaration. Yes, this creates some 5914/// major challenges of technical writing. Yes, this makes pointing 5915/// out problems with specific arguments quite awkward. It's still 5916/// better than generating twenty screens of text for every failed 5917/// overload. 5918/// 5919/// It would be great to be able to express per-candidate problems 5920/// more richly for those diagnostic clients that cared, but we'd 5921/// still have to be just as careful with the default diagnostics. 5922void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 5923 Expr **Args, unsigned NumArgs) { 5924 FunctionDecl *Fn = Cand->Function; 5925 5926 // Note deleted candidates, but only if they're viable. 5927 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) { 5928 std::string FnDesc; 5929 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 5930 5931 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 5932 << FnKind << FnDesc << Fn->isDeleted(); 5933 return; 5934 } 5935 5936 // We don't really have anything else to say about viable candidates. 5937 if (Cand->Viable) { 5938 S.NoteOverloadCandidate(Fn); 5939 return; 5940 } 5941 5942 switch (Cand->FailureKind) { 5943 case ovl_fail_too_many_arguments: 5944 case ovl_fail_too_few_arguments: 5945 return DiagnoseArityMismatch(S, Cand, NumArgs); 5946 5947 case ovl_fail_bad_deduction: 5948 return DiagnoseBadDeduction(S, Cand, Args, NumArgs); 5949 5950 case ovl_fail_trivial_conversion: 5951 case ovl_fail_bad_final_conversion: 5952 case ovl_fail_final_conversion_not_exact: 5953 return S.NoteOverloadCandidate(Fn); 5954 5955 case ovl_fail_bad_conversion: { 5956 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 5957 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 5958 if (Cand->Conversions[I].isBad()) 5959 return DiagnoseBadConversion(S, Cand, I); 5960 5961 // FIXME: this currently happens when we're called from SemaInit 5962 // when user-conversion overload fails. Figure out how to handle 5963 // those conditions and diagnose them well. 5964 return S.NoteOverloadCandidate(Fn); 5965 } 5966 } 5967} 5968 5969void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 5970 // Desugar the type of the surrogate down to a function type, 5971 // retaining as many typedefs as possible while still showing 5972 // the function type (and, therefore, its parameter types). 5973 QualType FnType = Cand->Surrogate->getConversionType(); 5974 bool isLValueReference = false; 5975 bool isRValueReference = false; 5976 bool isPointer = false; 5977 if (const LValueReferenceType *FnTypeRef = 5978 FnType->getAs<LValueReferenceType>()) { 5979 FnType = FnTypeRef->getPointeeType(); 5980 isLValueReference = true; 5981 } else if (const RValueReferenceType *FnTypeRef = 5982 FnType->getAs<RValueReferenceType>()) { 5983 FnType = FnTypeRef->getPointeeType(); 5984 isRValueReference = true; 5985 } 5986 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 5987 FnType = FnTypePtr->getPointeeType(); 5988 isPointer = true; 5989 } 5990 // Desugar down to a function type. 5991 FnType = QualType(FnType->getAs<FunctionType>(), 0); 5992 // Reconstruct the pointer/reference as appropriate. 5993 if (isPointer) FnType = S.Context.getPointerType(FnType); 5994 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 5995 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 5996 5997 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 5998 << FnType; 5999} 6000 6001void NoteBuiltinOperatorCandidate(Sema &S, 6002 const char *Opc, 6003 SourceLocation OpLoc, 6004 OverloadCandidate *Cand) { 6005 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 6006 std::string TypeStr("operator"); 6007 TypeStr += Opc; 6008 TypeStr += "("; 6009 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 6010 if (Cand->Conversions.size() == 1) { 6011 TypeStr += ")"; 6012 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 6013 } else { 6014 TypeStr += ", "; 6015 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 6016 TypeStr += ")"; 6017 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 6018 } 6019} 6020 6021void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 6022 OverloadCandidate *Cand) { 6023 unsigned NoOperands = Cand->Conversions.size(); 6024 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 6025 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 6026 if (ICS.isBad()) break; // all meaningless after first invalid 6027 if (!ICS.isAmbiguous()) continue; 6028 6029 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 6030 S.PDiag(diag::note_ambiguous_type_conversion)); 6031 } 6032} 6033 6034SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 6035 if (Cand->Function) 6036 return Cand->Function->getLocation(); 6037 if (Cand->IsSurrogate) 6038 return Cand->Surrogate->getLocation(); 6039 return SourceLocation(); 6040} 6041 6042struct CompareOverloadCandidatesForDisplay { 6043 Sema &S; 6044 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 6045 6046 bool operator()(const OverloadCandidate *L, 6047 const OverloadCandidate *R) { 6048 // Fast-path this check. 6049 if (L == R) return false; 6050 6051 // Order first by viability. 6052 if (L->Viable) { 6053 if (!R->Viable) return true; 6054 6055 // TODO: introduce a tri-valued comparison for overload 6056 // candidates. Would be more worthwhile if we had a sort 6057 // that could exploit it. 6058 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 6059 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 6060 } else if (R->Viable) 6061 return false; 6062 6063 assert(L->Viable == R->Viable); 6064 6065 // Criteria by which we can sort non-viable candidates: 6066 if (!L->Viable) { 6067 // 1. Arity mismatches come after other candidates. 6068 if (L->FailureKind == ovl_fail_too_many_arguments || 6069 L->FailureKind == ovl_fail_too_few_arguments) 6070 return false; 6071 if (R->FailureKind == ovl_fail_too_many_arguments || 6072 R->FailureKind == ovl_fail_too_few_arguments) 6073 return true; 6074 6075 // 2. Bad conversions come first and are ordered by the number 6076 // of bad conversions and quality of good conversions. 6077 if (L->FailureKind == ovl_fail_bad_conversion) { 6078 if (R->FailureKind != ovl_fail_bad_conversion) 6079 return true; 6080 6081 // If there's any ordering between the defined conversions... 6082 // FIXME: this might not be transitive. 6083 assert(L->Conversions.size() == R->Conversions.size()); 6084 6085 int leftBetter = 0; 6086 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 6087 for (unsigned E = L->Conversions.size(); I != E; ++I) { 6088 switch (CompareImplicitConversionSequences(S, 6089 L->Conversions[I], 6090 R->Conversions[I])) { 6091 case ImplicitConversionSequence::Better: 6092 leftBetter++; 6093 break; 6094 6095 case ImplicitConversionSequence::Worse: 6096 leftBetter--; 6097 break; 6098 6099 case ImplicitConversionSequence::Indistinguishable: 6100 break; 6101 } 6102 } 6103 if (leftBetter > 0) return true; 6104 if (leftBetter < 0) return false; 6105 6106 } else if (R->FailureKind == ovl_fail_bad_conversion) 6107 return false; 6108 6109 // TODO: others? 6110 } 6111 6112 // Sort everything else by location. 6113 SourceLocation LLoc = GetLocationForCandidate(L); 6114 SourceLocation RLoc = GetLocationForCandidate(R); 6115 6116 // Put candidates without locations (e.g. builtins) at the end. 6117 if (LLoc.isInvalid()) return false; 6118 if (RLoc.isInvalid()) return true; 6119 6120 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 6121 } 6122}; 6123 6124/// CompleteNonViableCandidate - Normally, overload resolution only 6125/// computes up to the first 6126void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 6127 Expr **Args, unsigned NumArgs) { 6128 assert(!Cand->Viable); 6129 6130 // Don't do anything on failures other than bad conversion. 6131 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 6132 6133 // Skip forward to the first bad conversion. 6134 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 6135 unsigned ConvCount = Cand->Conversions.size(); 6136 while (true) { 6137 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 6138 ConvIdx++; 6139 if (Cand->Conversions[ConvIdx - 1].isBad()) 6140 break; 6141 } 6142 6143 if (ConvIdx == ConvCount) 6144 return; 6145 6146 assert(!Cand->Conversions[ConvIdx].isInitialized() && 6147 "remaining conversion is initialized?"); 6148 6149 // FIXME: this should probably be preserved from the overload 6150 // operation somehow. 6151 bool SuppressUserConversions = false; 6152 6153 const FunctionProtoType* Proto; 6154 unsigned ArgIdx = ConvIdx; 6155 6156 if (Cand->IsSurrogate) { 6157 QualType ConvType 6158 = Cand->Surrogate->getConversionType().getNonReferenceType(); 6159 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 6160 ConvType = ConvPtrType->getPointeeType(); 6161 Proto = ConvType->getAs<FunctionProtoType>(); 6162 ArgIdx--; 6163 } else if (Cand->Function) { 6164 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 6165 if (isa<CXXMethodDecl>(Cand->Function) && 6166 !isa<CXXConstructorDecl>(Cand->Function)) 6167 ArgIdx--; 6168 } else { 6169 // Builtin binary operator with a bad first conversion. 6170 assert(ConvCount <= 3); 6171 for (; ConvIdx != ConvCount; ++ConvIdx) 6172 Cand->Conversions[ConvIdx] 6173 = TryCopyInitialization(S, Args[ConvIdx], 6174 Cand->BuiltinTypes.ParamTypes[ConvIdx], 6175 SuppressUserConversions, 6176 /*InOverloadResolution*/ true); 6177 return; 6178 } 6179 6180 // Fill in the rest of the conversions. 6181 unsigned NumArgsInProto = Proto->getNumArgs(); 6182 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 6183 if (ArgIdx < NumArgsInProto) 6184 Cand->Conversions[ConvIdx] 6185 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 6186 SuppressUserConversions, 6187 /*InOverloadResolution=*/true); 6188 else 6189 Cand->Conversions[ConvIdx].setEllipsis(); 6190 } 6191} 6192 6193} // end anonymous namespace 6194 6195/// PrintOverloadCandidates - When overload resolution fails, prints 6196/// diagnostic messages containing the candidates in the candidate 6197/// set. 6198void OverloadCandidateSet::NoteCandidates(Sema &S, 6199 OverloadCandidateDisplayKind OCD, 6200 Expr **Args, unsigned NumArgs, 6201 const char *Opc, 6202 SourceLocation OpLoc) { 6203 // Sort the candidates by viability and position. Sorting directly would 6204 // be prohibitive, so we make a set of pointers and sort those. 6205 llvm::SmallVector<OverloadCandidate*, 32> Cands; 6206 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 6207 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 6208 if (Cand->Viable) 6209 Cands.push_back(Cand); 6210 else if (OCD == OCD_AllCandidates) { 6211 CompleteNonViableCandidate(S, Cand, Args, NumArgs); 6212 if (Cand->Function || Cand->IsSurrogate) 6213 Cands.push_back(Cand); 6214 // Otherwise, this a non-viable builtin candidate. We do not, in general, 6215 // want to list every possible builtin candidate. 6216 } 6217 } 6218 6219 std::sort(Cands.begin(), Cands.end(), 6220 CompareOverloadCandidatesForDisplay(S)); 6221 6222 bool ReportedAmbiguousConversions = false; 6223 6224 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E; 6225 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 6226 unsigned CandsShown = 0; 6227 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 6228 OverloadCandidate *Cand = *I; 6229 6230 // Set an arbitrary limit on the number of candidate functions we'll spam 6231 // the user with. FIXME: This limit should depend on details of the 6232 // candidate list. 6233 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) { 6234 break; 6235 } 6236 ++CandsShown; 6237 6238 if (Cand->Function) 6239 NoteFunctionCandidate(S, Cand, Args, NumArgs); 6240 else if (Cand->IsSurrogate) 6241 NoteSurrogateCandidate(S, Cand); 6242 else { 6243 assert(Cand->Viable && 6244 "Non-viable built-in candidates are not added to Cands."); 6245 // Generally we only see ambiguities including viable builtin 6246 // operators if overload resolution got screwed up by an 6247 // ambiguous user-defined conversion. 6248 // 6249 // FIXME: It's quite possible for different conversions to see 6250 // different ambiguities, though. 6251 if (!ReportedAmbiguousConversions) { 6252 NoteAmbiguousUserConversions(S, OpLoc, Cand); 6253 ReportedAmbiguousConversions = true; 6254 } 6255 6256 // If this is a viable builtin, print it. 6257 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 6258 } 6259 } 6260 6261 if (I != E) 6262 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 6263} 6264 6265static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) { 6266 if (isa<UnresolvedLookupExpr>(E)) 6267 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D); 6268 6269 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D); 6270} 6271 6272/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 6273/// an overloaded function (C++ [over.over]), where @p From is an 6274/// expression with overloaded function type and @p ToType is the type 6275/// we're trying to resolve to. For example: 6276/// 6277/// @code 6278/// int f(double); 6279/// int f(int); 6280/// 6281/// int (*pfd)(double) = f; // selects f(double) 6282/// @endcode 6283/// 6284/// This routine returns the resulting FunctionDecl if it could be 6285/// resolved, and NULL otherwise. When @p Complain is true, this 6286/// routine will emit diagnostics if there is an error. 6287FunctionDecl * 6288Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType, 6289 bool Complain, 6290 DeclAccessPair &FoundResult) { 6291 QualType FunctionType = ToType; 6292 bool IsMember = false; 6293 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>()) 6294 FunctionType = ToTypePtr->getPointeeType(); 6295 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>()) 6296 FunctionType = ToTypeRef->getPointeeType(); 6297 else if (const MemberPointerType *MemTypePtr = 6298 ToType->getAs<MemberPointerType>()) { 6299 FunctionType = MemTypePtr->getPointeeType(); 6300 IsMember = true; 6301 } 6302 6303 // C++ [over.over]p1: 6304 // [...] [Note: any redundant set of parentheses surrounding the 6305 // overloaded function name is ignored (5.1). ] 6306 // C++ [over.over]p1: 6307 // [...] The overloaded function name can be preceded by the & 6308 // operator. 6309 // However, remember whether the expression has member-pointer form: 6310 // C++ [expr.unary.op]p4: 6311 // A pointer to member is only formed when an explicit & is used 6312 // and its operand is a qualified-id not enclosed in 6313 // parentheses. 6314 OverloadExpr::FindResult Ovl = OverloadExpr::find(From); 6315 OverloadExpr *OvlExpr = Ovl.Expression; 6316 6317 // We expect a pointer or reference to function, or a function pointer. 6318 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType(); 6319 if (!FunctionType->isFunctionType()) { 6320 if (Complain) 6321 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 6322 << OvlExpr->getName() << ToType; 6323 6324 return 0; 6325 } 6326 6327 // If the overload expression doesn't have the form of a pointer to 6328 // member, don't try to convert it to a pointer-to-member type. 6329 if (IsMember && !Ovl.HasFormOfMemberPointer) { 6330 if (!Complain) return 0; 6331 6332 // TODO: Should we condition this on whether any functions might 6333 // have matched, or is it more appropriate to do that in callers? 6334 // TODO: a fixit wouldn't hurt. 6335 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 6336 << ToType << OvlExpr->getSourceRange(); 6337 return 0; 6338 } 6339 6340 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0; 6341 if (OvlExpr->hasExplicitTemplateArgs()) { 6342 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer); 6343 ExplicitTemplateArgs = &ETABuffer; 6344 } 6345 6346 assert(From->getType() == Context.OverloadTy); 6347 6348 // Look through all of the overloaded functions, searching for one 6349 // whose type matches exactly. 6350 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 6351 llvm::SmallVector<FunctionDecl *, 4> NonMatches; 6352 6353 bool FoundNonTemplateFunction = false; 6354 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 6355 E = OvlExpr->decls_end(); I != E; ++I) { 6356 // Look through any using declarations to find the underlying function. 6357 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 6358 6359 // C++ [over.over]p3: 6360 // Non-member functions and static member functions match 6361 // targets of type "pointer-to-function" or "reference-to-function." 6362 // Nonstatic member functions match targets of 6363 // type "pointer-to-member-function." 6364 // Note that according to DR 247, the containing class does not matter. 6365 6366 if (FunctionTemplateDecl *FunctionTemplate 6367 = dyn_cast<FunctionTemplateDecl>(Fn)) { 6368 if (CXXMethodDecl *Method 6369 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 6370 // Skip non-static function templates when converting to pointer, and 6371 // static when converting to member pointer. 6372 if (Method->isStatic() == IsMember) 6373 continue; 6374 } else if (IsMember) 6375 continue; 6376 6377 // C++ [over.over]p2: 6378 // If the name is a function template, template argument deduction is 6379 // done (14.8.2.2), and if the argument deduction succeeds, the 6380 // resulting template argument list is used to generate a single 6381 // function template specialization, which is added to the set of 6382 // overloaded functions considered. 6383 FunctionDecl *Specialization = 0; 6384 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 6385 if (TemplateDeductionResult Result 6386 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 6387 FunctionType, Specialization, Info)) { 6388 // FIXME: make a note of the failed deduction for diagnostics. 6389 (void)Result; 6390 } else { 6391 // Template argument deduction ensures that we have an exact match. 6392 // This function template specicalization works. 6393 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 6394 assert(FunctionType 6395 == Context.getCanonicalType(Specialization->getType())); 6396 Matches.push_back(std::make_pair(I.getPair(), Specialization)); 6397 } 6398 6399 continue; 6400 } 6401 6402 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 6403 // Skip non-static functions when converting to pointer, and static 6404 // when converting to member pointer. 6405 if (Method->isStatic() == IsMember) 6406 continue; 6407 6408 // If we have explicit template arguments, skip non-templates. 6409 if (OvlExpr->hasExplicitTemplateArgs()) 6410 continue; 6411 } else if (IsMember) 6412 continue; 6413 6414 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 6415 QualType ResultTy; 6416 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) || 6417 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType, 6418 ResultTy)) { 6419 Matches.push_back(std::make_pair(I.getPair(), 6420 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 6421 FoundNonTemplateFunction = true; 6422 } 6423 } 6424 } 6425 6426 // If there were 0 or 1 matches, we're done. 6427 if (Matches.empty()) { 6428 if (Complain) { 6429 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable) 6430 << OvlExpr->getName() << FunctionType; 6431 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 6432 E = OvlExpr->decls_end(); 6433 I != E; ++I) 6434 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 6435 NoteOverloadCandidate(F); 6436 } 6437 6438 return 0; 6439 } else if (Matches.size() == 1) { 6440 FunctionDecl *Result = Matches[0].second; 6441 FoundResult = Matches[0].first; 6442 MarkDeclarationReferenced(From->getLocStart(), Result); 6443 if (Complain) { 6444 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first); 6445 } 6446 return Result; 6447 } 6448 6449 // C++ [over.over]p4: 6450 // If more than one function is selected, [...] 6451 if (!FoundNonTemplateFunction) { 6452 // [...] and any given function template specialization F1 is 6453 // eliminated if the set contains a second function template 6454 // specialization whose function template is more specialized 6455 // than the function template of F1 according to the partial 6456 // ordering rules of 14.5.5.2. 6457 6458 // The algorithm specified above is quadratic. We instead use a 6459 // two-pass algorithm (similar to the one used to identify the 6460 // best viable function in an overload set) that identifies the 6461 // best function template (if it exists). 6462 6463 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 6464 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 6465 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 6466 6467 UnresolvedSetIterator Result = 6468 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 6469 TPOC_Other, From->getLocStart(), 6470 PDiag(), 6471 PDiag(diag::err_addr_ovl_ambiguous) 6472 << Matches[0].second->getDeclName(), 6473 PDiag(diag::note_ovl_candidate) 6474 << (unsigned) oc_function_template); 6475 if (Result == MatchesCopy.end()) 6476 return 0; 6477 6478 MarkDeclarationReferenced(From->getLocStart(), *Result); 6479 FoundResult = Matches[Result - MatchesCopy.begin()].first; 6480 if (Complain) 6481 CheckUnresolvedAccess(*this, OvlExpr, FoundResult); 6482 return cast<FunctionDecl>(*Result); 6483 } 6484 6485 // [...] any function template specializations in the set are 6486 // eliminated if the set also contains a non-template function, [...] 6487 for (unsigned I = 0, N = Matches.size(); I != N; ) { 6488 if (Matches[I].second->getPrimaryTemplate() == 0) 6489 ++I; 6490 else { 6491 Matches[I] = Matches[--N]; 6492 Matches.set_size(N); 6493 } 6494 } 6495 6496 // [...] After such eliminations, if any, there shall remain exactly one 6497 // selected function. 6498 if (Matches.size() == 1) { 6499 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second); 6500 FoundResult = Matches[0].first; 6501 if (Complain) 6502 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first); 6503 return cast<FunctionDecl>(Matches[0].second); 6504 } 6505 6506 // FIXME: We should probably return the same thing that BestViableFunction 6507 // returns (even if we issue the diagnostics here). 6508 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous) 6509 << Matches[0].second->getDeclName(); 6510 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 6511 NoteOverloadCandidate(Matches[I].second); 6512 return 0; 6513} 6514 6515/// \brief Given an expression that refers to an overloaded function, try to 6516/// resolve that overloaded function expression down to a single function. 6517/// 6518/// This routine can only resolve template-ids that refer to a single function 6519/// template, where that template-id refers to a single template whose template 6520/// arguments are either provided by the template-id or have defaults, 6521/// as described in C++0x [temp.arg.explicit]p3. 6522FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) { 6523 // C++ [over.over]p1: 6524 // [...] [Note: any redundant set of parentheses surrounding the 6525 // overloaded function name is ignored (5.1). ] 6526 // C++ [over.over]p1: 6527 // [...] The overloaded function name can be preceded by the & 6528 // operator. 6529 6530 if (From->getType() != Context.OverloadTy) 6531 return 0; 6532 6533 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression; 6534 6535 // If we didn't actually find any template-ids, we're done. 6536 if (!OvlExpr->hasExplicitTemplateArgs()) 6537 return 0; 6538 6539 TemplateArgumentListInfo ExplicitTemplateArgs; 6540 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 6541 6542 // Look through all of the overloaded functions, searching for one 6543 // whose type matches exactly. 6544 FunctionDecl *Matched = 0; 6545 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 6546 E = OvlExpr->decls_end(); I != E; ++I) { 6547 // C++0x [temp.arg.explicit]p3: 6548 // [...] In contexts where deduction is done and fails, or in contexts 6549 // where deduction is not done, if a template argument list is 6550 // specified and it, along with any default template arguments, 6551 // identifies a single function template specialization, then the 6552 // template-id is an lvalue for the function template specialization. 6553 FunctionTemplateDecl *FunctionTemplate 6554 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 6555 6556 // C++ [over.over]p2: 6557 // If the name is a function template, template argument deduction is 6558 // done (14.8.2.2), and if the argument deduction succeeds, the 6559 // resulting template argument list is used to generate a single 6560 // function template specialization, which is added to the set of 6561 // overloaded functions considered. 6562 FunctionDecl *Specialization = 0; 6563 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 6564 if (TemplateDeductionResult Result 6565 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 6566 Specialization, Info)) { 6567 // FIXME: make a note of the failed deduction for diagnostics. 6568 (void)Result; 6569 continue; 6570 } 6571 6572 // Multiple matches; we can't resolve to a single declaration. 6573 if (Matched) 6574 return 0; 6575 6576 Matched = Specialization; 6577 } 6578 6579 return Matched; 6580} 6581 6582/// \brief Add a single candidate to the overload set. 6583static void AddOverloadedCallCandidate(Sema &S, 6584 DeclAccessPair FoundDecl, 6585 const TemplateArgumentListInfo *ExplicitTemplateArgs, 6586 Expr **Args, unsigned NumArgs, 6587 OverloadCandidateSet &CandidateSet, 6588 bool PartialOverloading) { 6589 NamedDecl *Callee = FoundDecl.getDecl(); 6590 if (isa<UsingShadowDecl>(Callee)) 6591 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 6592 6593 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 6594 assert(!ExplicitTemplateArgs && "Explicit template arguments?"); 6595 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet, 6596 false, PartialOverloading); 6597 return; 6598 } 6599 6600 if (FunctionTemplateDecl *FuncTemplate 6601 = dyn_cast<FunctionTemplateDecl>(Callee)) { 6602 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 6603 ExplicitTemplateArgs, 6604 Args, NumArgs, CandidateSet); 6605 return; 6606 } 6607 6608 assert(false && "unhandled case in overloaded call candidate"); 6609 6610 // do nothing? 6611} 6612 6613/// \brief Add the overload candidates named by callee and/or found by argument 6614/// dependent lookup to the given overload set. 6615void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 6616 Expr **Args, unsigned NumArgs, 6617 OverloadCandidateSet &CandidateSet, 6618 bool PartialOverloading) { 6619 6620#ifndef NDEBUG 6621 // Verify that ArgumentDependentLookup is consistent with the rules 6622 // in C++0x [basic.lookup.argdep]p3: 6623 // 6624 // Let X be the lookup set produced by unqualified lookup (3.4.1) 6625 // and let Y be the lookup set produced by argument dependent 6626 // lookup (defined as follows). If X contains 6627 // 6628 // -- a declaration of a class member, or 6629 // 6630 // -- a block-scope function declaration that is not a 6631 // using-declaration, or 6632 // 6633 // -- a declaration that is neither a function or a function 6634 // template 6635 // 6636 // then Y is empty. 6637 6638 if (ULE->requiresADL()) { 6639 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 6640 E = ULE->decls_end(); I != E; ++I) { 6641 assert(!(*I)->getDeclContext()->isRecord()); 6642 assert(isa<UsingShadowDecl>(*I) || 6643 !(*I)->getDeclContext()->isFunctionOrMethod()); 6644 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 6645 } 6646 } 6647#endif 6648 6649 // It would be nice to avoid this copy. 6650 TemplateArgumentListInfo TABuffer; 6651 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 6652 if (ULE->hasExplicitTemplateArgs()) { 6653 ULE->copyTemplateArgumentsInto(TABuffer); 6654 ExplicitTemplateArgs = &TABuffer; 6655 } 6656 6657 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 6658 E = ULE->decls_end(); I != E; ++I) 6659 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, 6660 Args, NumArgs, CandidateSet, 6661 PartialOverloading); 6662 6663 if (ULE->requiresADL()) 6664 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 6665 Args, NumArgs, 6666 ExplicitTemplateArgs, 6667 CandidateSet, 6668 PartialOverloading); 6669} 6670 6671/// Attempts to recover from a call where no functions were found. 6672/// 6673/// Returns true if new candidates were found. 6674static ExprResult 6675BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 6676 UnresolvedLookupExpr *ULE, 6677 SourceLocation LParenLoc, 6678 Expr **Args, unsigned NumArgs, 6679 SourceLocation RParenLoc) { 6680 6681 CXXScopeSpec SS; 6682 if (ULE->getQualifier()) { 6683 SS.setScopeRep(ULE->getQualifier()); 6684 SS.setRange(ULE->getQualifierRange()); 6685 } 6686 6687 TemplateArgumentListInfo TABuffer; 6688 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 6689 if (ULE->hasExplicitTemplateArgs()) { 6690 ULE->copyTemplateArgumentsInto(TABuffer); 6691 ExplicitTemplateArgs = &TABuffer; 6692 } 6693 6694 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 6695 Sema::LookupOrdinaryName); 6696 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression)) 6697 return ExprError(); 6698 6699 assert(!R.empty() && "lookup results empty despite recovery"); 6700 6701 // Build an implicit member call if appropriate. Just drop the 6702 // casts and such from the call, we don't really care. 6703 ExprResult NewFn = ExprError(); 6704 if ((*R.begin())->isCXXClassMember()) 6705 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs); 6706 else if (ExplicitTemplateArgs) 6707 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs); 6708 else 6709 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 6710 6711 if (NewFn.isInvalid()) 6712 return ExprError(); 6713 6714 // This shouldn't cause an infinite loop because we're giving it 6715 // an expression with non-empty lookup results, which should never 6716 // end up here. 6717 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 6718 MultiExprArg(Args, NumArgs), RParenLoc); 6719} 6720 6721/// ResolveOverloadedCallFn - Given the call expression that calls Fn 6722/// (which eventually refers to the declaration Func) and the call 6723/// arguments Args/NumArgs, attempt to resolve the function call down 6724/// to a specific function. If overload resolution succeeds, returns 6725/// the function declaration produced by overload 6726/// resolution. Otherwise, emits diagnostics, deletes all of the 6727/// arguments and Fn, and returns NULL. 6728ExprResult 6729Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 6730 SourceLocation LParenLoc, 6731 Expr **Args, unsigned NumArgs, 6732 SourceLocation RParenLoc) { 6733#ifndef NDEBUG 6734 if (ULE->requiresADL()) { 6735 // To do ADL, we must have found an unqualified name. 6736 assert(!ULE->getQualifier() && "qualified name with ADL"); 6737 6738 // We don't perform ADL for implicit declarations of builtins. 6739 // Verify that this was correctly set up. 6740 FunctionDecl *F; 6741 if (ULE->decls_begin() + 1 == ULE->decls_end() && 6742 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 6743 F->getBuiltinID() && F->isImplicit()) 6744 assert(0 && "performing ADL for builtin"); 6745 6746 // We don't perform ADL in C. 6747 assert(getLangOptions().CPlusPlus && "ADL enabled in C"); 6748 } 6749#endif 6750 6751 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 6752 6753 // Add the functions denoted by the callee to the set of candidate 6754 // functions, including those from argument-dependent lookup. 6755 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet); 6756 6757 // If we found nothing, try to recover. 6758 // AddRecoveryCallCandidates diagnoses the error itself, so we just 6759 // bailout out if it fails. 6760 if (CandidateSet.empty()) 6761 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 6762 RParenLoc); 6763 6764 OverloadCandidateSet::iterator Best; 6765 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) { 6766 case OR_Success: { 6767 FunctionDecl *FDecl = Best->Function; 6768 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl); 6769 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), ULE->getNameLoc()); 6770 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl); 6771 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc); 6772 } 6773 6774 case OR_No_Viable_Function: 6775 Diag(Fn->getSourceRange().getBegin(), 6776 diag::err_ovl_no_viable_function_in_call) 6777 << ULE->getName() << Fn->getSourceRange(); 6778 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 6779 break; 6780 6781 case OR_Ambiguous: 6782 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 6783 << ULE->getName() << Fn->getSourceRange(); 6784 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); 6785 break; 6786 6787 case OR_Deleted: 6788 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call) 6789 << Best->Function->isDeleted() 6790 << ULE->getName() 6791 << Fn->getSourceRange(); 6792 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 6793 break; 6794 } 6795 6796 // Overload resolution failed. 6797 return ExprError(); 6798} 6799 6800static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 6801 return Functions.size() > 1 || 6802 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 6803} 6804 6805/// \brief Create a unary operation that may resolve to an overloaded 6806/// operator. 6807/// 6808/// \param OpLoc The location of the operator itself (e.g., '*'). 6809/// 6810/// \param OpcIn The UnaryOperator::Opcode that describes this 6811/// operator. 6812/// 6813/// \param Functions The set of non-member functions that will be 6814/// considered by overload resolution. The caller needs to build this 6815/// set based on the context using, e.g., 6816/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 6817/// set should not contain any member functions; those will be added 6818/// by CreateOverloadedUnaryOp(). 6819/// 6820/// \param input The input argument. 6821ExprResult 6822Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 6823 const UnresolvedSetImpl &Fns, 6824 Expr *Input) { 6825 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 6826 6827 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 6828 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 6829 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6830 // TODO: provide better source location info. 6831 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 6832 6833 Expr *Args[2] = { Input, 0 }; 6834 unsigned NumArgs = 1; 6835 6836 // For post-increment and post-decrement, add the implicit '0' as 6837 // the second argument, so that we know this is a post-increment or 6838 // post-decrement. 6839 if (Opc == UO_PostInc || Opc == UO_PostDec) { 6840 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 6841 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 6842 SourceLocation()); 6843 NumArgs = 2; 6844 } 6845 6846 if (Input->isTypeDependent()) { 6847 if (Fns.empty()) 6848 return Owned(new (Context) UnaryOperator(Input, 6849 Opc, 6850 Context.DependentTy, 6851 OpLoc)); 6852 6853 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 6854 UnresolvedLookupExpr *Fn 6855 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass, 6856 0, SourceRange(), OpNameInfo, 6857 /*ADL*/ true, IsOverloaded(Fns), 6858 Fns.begin(), Fns.end()); 6859 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 6860 &Args[0], NumArgs, 6861 Context.DependentTy, 6862 OpLoc)); 6863 } 6864 6865 // Build an empty overload set. 6866 OverloadCandidateSet CandidateSet(OpLoc); 6867 6868 // Add the candidates from the given function set. 6869 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false); 6870 6871 // Add operator candidates that are member functions. 6872 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 6873 6874 // Add candidates from ADL. 6875 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 6876 Args, NumArgs, 6877 /*ExplicitTemplateArgs*/ 0, 6878 CandidateSet); 6879 6880 // Add builtin operator candidates. 6881 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 6882 6883 // Perform overload resolution. 6884 OverloadCandidateSet::iterator Best; 6885 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 6886 case OR_Success: { 6887 // We found a built-in operator or an overloaded operator. 6888 FunctionDecl *FnDecl = Best->Function; 6889 6890 if (FnDecl) { 6891 // We matched an overloaded operator. Build a call to that 6892 // operator. 6893 6894 // Convert the arguments. 6895 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 6896 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 6897 6898 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 6899 Best->FoundDecl, Method)) 6900 return ExprError(); 6901 } else { 6902 // Convert the arguments. 6903 ExprResult InputInit 6904 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 6905 Context, 6906 FnDecl->getParamDecl(0)), 6907 SourceLocation(), 6908 Input); 6909 if (InputInit.isInvalid()) 6910 return ExprError(); 6911 Input = InputInit.take(); 6912 } 6913 6914 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 6915 6916 // Determine the result type 6917 QualType ResultTy = FnDecl->getCallResultType(); 6918 6919 // Build the actual expression node. 6920 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 6921 SourceLocation()); 6922 UsualUnaryConversions(FnExpr); 6923 6924 Args[0] = Input; 6925 CallExpr *TheCall = 6926 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr, 6927 Args, NumArgs, ResultTy, OpLoc); 6928 6929 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 6930 FnDecl)) 6931 return ExprError(); 6932 6933 return MaybeBindToTemporary(TheCall); 6934 } else { 6935 // We matched a built-in operator. Convert the arguments, then 6936 // break out so that we will build the appropriate built-in 6937 // operator node. 6938 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 6939 Best->Conversions[0], AA_Passing)) 6940 return ExprError(); 6941 6942 break; 6943 } 6944 } 6945 6946 case OR_No_Viable_Function: 6947 // No viable function; fall through to handling this as a 6948 // built-in operator, which will produce an error message for us. 6949 break; 6950 6951 case OR_Ambiguous: 6952 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 6953 << UnaryOperator::getOpcodeStr(Opc) 6954 << Input->getSourceRange(); 6955 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 6956 Args, NumArgs, 6957 UnaryOperator::getOpcodeStr(Opc), OpLoc); 6958 return ExprError(); 6959 6960 case OR_Deleted: 6961 Diag(OpLoc, diag::err_ovl_deleted_oper) 6962 << Best->Function->isDeleted() 6963 << UnaryOperator::getOpcodeStr(Opc) 6964 << Input->getSourceRange(); 6965 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 6966 return ExprError(); 6967 } 6968 6969 // Either we found no viable overloaded operator or we matched a 6970 // built-in operator. In either case, fall through to trying to 6971 // build a built-in operation. 6972 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 6973} 6974 6975/// \brief Create a binary operation that may resolve to an overloaded 6976/// operator. 6977/// 6978/// \param OpLoc The location of the operator itself (e.g., '+'). 6979/// 6980/// \param OpcIn The BinaryOperator::Opcode that describes this 6981/// operator. 6982/// 6983/// \param Functions The set of non-member functions that will be 6984/// considered by overload resolution. The caller needs to build this 6985/// set based on the context using, e.g., 6986/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 6987/// set should not contain any member functions; those will be added 6988/// by CreateOverloadedBinOp(). 6989/// 6990/// \param LHS Left-hand argument. 6991/// \param RHS Right-hand argument. 6992ExprResult 6993Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 6994 unsigned OpcIn, 6995 const UnresolvedSetImpl &Fns, 6996 Expr *LHS, Expr *RHS) { 6997 Expr *Args[2] = { LHS, RHS }; 6998 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 6999 7000 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 7001 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 7002 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7003 7004 // If either side is type-dependent, create an appropriate dependent 7005 // expression. 7006 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 7007 if (Fns.empty()) { 7008 // If there are no functions to store, just build a dependent 7009 // BinaryOperator or CompoundAssignment. 7010 if (Opc <= BO_Assign || Opc > BO_OrAssign) 7011 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 7012 Context.DependentTy, OpLoc)); 7013 7014 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 7015 Context.DependentTy, 7016 Context.DependentTy, 7017 Context.DependentTy, 7018 OpLoc)); 7019 } 7020 7021 // FIXME: save results of ADL from here? 7022 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 7023 // TODO: provide better source location info in DNLoc component. 7024 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 7025 UnresolvedLookupExpr *Fn 7026 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass, 7027 0, SourceRange(), OpNameInfo, 7028 /*ADL*/ true, IsOverloaded(Fns), 7029 Fns.begin(), Fns.end()); 7030 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 7031 Args, 2, 7032 Context.DependentTy, 7033 OpLoc)); 7034 } 7035 7036 // If this is the .* operator, which is not overloadable, just 7037 // create a built-in binary operator. 7038 if (Opc == BO_PtrMemD) 7039 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 7040 7041 // If this is the assignment operator, we only perform overload resolution 7042 // if the left-hand side is a class or enumeration type. This is actually 7043 // a hack. The standard requires that we do overload resolution between the 7044 // various built-in candidates, but as DR507 points out, this can lead to 7045 // problems. So we do it this way, which pretty much follows what GCC does. 7046 // Note that we go the traditional code path for compound assignment forms. 7047 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 7048 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 7049 7050 // Build an empty overload set. 7051 OverloadCandidateSet CandidateSet(OpLoc); 7052 7053 // Add the candidates from the given function set. 7054 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false); 7055 7056 // Add operator candidates that are member functions. 7057 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 7058 7059 // Add candidates from ADL. 7060 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 7061 Args, 2, 7062 /*ExplicitTemplateArgs*/ 0, 7063 CandidateSet); 7064 7065 // Add builtin operator candidates. 7066 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 7067 7068 // Perform overload resolution. 7069 OverloadCandidateSet::iterator Best; 7070 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 7071 case OR_Success: { 7072 // We found a built-in operator or an overloaded operator. 7073 FunctionDecl *FnDecl = Best->Function; 7074 7075 if (FnDecl) { 7076 // We matched an overloaded operator. Build a call to that 7077 // operator. 7078 7079 // Convert the arguments. 7080 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 7081 // Best->Access is only meaningful for class members. 7082 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 7083 7084 ExprResult Arg1 7085 = PerformCopyInitialization( 7086 InitializedEntity::InitializeParameter( 7087 Context, 7088 FnDecl->getParamDecl(0)), 7089 SourceLocation(), 7090 Owned(Args[1])); 7091 if (Arg1.isInvalid()) 7092 return ExprError(); 7093 7094 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 7095 Best->FoundDecl, Method)) 7096 return ExprError(); 7097 7098 Args[1] = RHS = Arg1.takeAs<Expr>(); 7099 } else { 7100 // Convert the arguments. 7101 ExprResult Arg0 7102 = PerformCopyInitialization( 7103 InitializedEntity::InitializeParameter( 7104 Context, 7105 FnDecl->getParamDecl(0)), 7106 SourceLocation(), 7107 Owned(Args[0])); 7108 if (Arg0.isInvalid()) 7109 return ExprError(); 7110 7111 ExprResult Arg1 7112 = PerformCopyInitialization( 7113 InitializedEntity::InitializeParameter( 7114 Context, 7115 FnDecl->getParamDecl(1)), 7116 SourceLocation(), 7117 Owned(Args[1])); 7118 if (Arg1.isInvalid()) 7119 return ExprError(); 7120 Args[0] = LHS = Arg0.takeAs<Expr>(); 7121 Args[1] = RHS = Arg1.takeAs<Expr>(); 7122 } 7123 7124 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 7125 7126 // Determine the result type 7127 QualType ResultTy 7128 = FnDecl->getType()->getAs<FunctionType>() 7129 ->getCallResultType(Context); 7130 7131 // Build the actual expression node. 7132 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 7133 OpLoc); 7134 UsualUnaryConversions(FnExpr); 7135 7136 CXXOperatorCallExpr *TheCall = 7137 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr, 7138 Args, 2, ResultTy, OpLoc); 7139 7140 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 7141 FnDecl)) 7142 return ExprError(); 7143 7144 return MaybeBindToTemporary(TheCall); 7145 } else { 7146 // We matched a built-in operator. Convert the arguments, then 7147 // break out so that we will build the appropriate built-in 7148 // operator node. 7149 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 7150 Best->Conversions[0], AA_Passing) || 7151 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 7152 Best->Conversions[1], AA_Passing)) 7153 return ExprError(); 7154 7155 break; 7156 } 7157 } 7158 7159 case OR_No_Viable_Function: { 7160 // C++ [over.match.oper]p9: 7161 // If the operator is the operator , [...] and there are no 7162 // viable functions, then the operator is assumed to be the 7163 // built-in operator and interpreted according to clause 5. 7164 if (Opc == BO_Comma) 7165 break; 7166 7167 // For class as left operand for assignment or compound assigment operator 7168 // do not fall through to handling in built-in, but report that no overloaded 7169 // assignment operator found 7170 ExprResult Result = ExprError(); 7171 if (Args[0]->getType()->isRecordType() && 7172 Opc >= BO_Assign && Opc <= BO_OrAssign) { 7173 Diag(OpLoc, diag::err_ovl_no_viable_oper) 7174 << BinaryOperator::getOpcodeStr(Opc) 7175 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7176 } else { 7177 // No viable function; try to create a built-in operation, which will 7178 // produce an error. Then, show the non-viable candidates. 7179 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 7180 } 7181 assert(Result.isInvalid() && 7182 "C++ binary operator overloading is missing candidates!"); 7183 if (Result.isInvalid()) 7184 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2, 7185 BinaryOperator::getOpcodeStr(Opc), OpLoc); 7186 return move(Result); 7187 } 7188 7189 case OR_Ambiguous: 7190 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 7191 << BinaryOperator::getOpcodeStr(Opc) 7192 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7193 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2, 7194 BinaryOperator::getOpcodeStr(Opc), OpLoc); 7195 return ExprError(); 7196 7197 case OR_Deleted: 7198 Diag(OpLoc, diag::err_ovl_deleted_oper) 7199 << Best->Function->isDeleted() 7200 << BinaryOperator::getOpcodeStr(Opc) 7201 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7202 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2); 7203 return ExprError(); 7204 } 7205 7206 // We matched a built-in operator; build it. 7207 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 7208} 7209 7210ExprResult 7211Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 7212 SourceLocation RLoc, 7213 Expr *Base, Expr *Idx) { 7214 Expr *Args[2] = { Base, Idx }; 7215 DeclarationName OpName = 7216 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 7217 7218 // If either side is type-dependent, create an appropriate dependent 7219 // expression. 7220 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 7221 7222 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 7223 // CHECKME: no 'operator' keyword? 7224 DeclarationNameInfo OpNameInfo(OpName, LLoc); 7225 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 7226 UnresolvedLookupExpr *Fn 7227 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass, 7228 0, SourceRange(), OpNameInfo, 7229 /*ADL*/ true, /*Overloaded*/ false, 7230 UnresolvedSetIterator(), 7231 UnresolvedSetIterator()); 7232 // Can't add any actual overloads yet 7233 7234 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 7235 Args, 2, 7236 Context.DependentTy, 7237 RLoc)); 7238 } 7239 7240 // Build an empty overload set. 7241 OverloadCandidateSet CandidateSet(LLoc); 7242 7243 // Subscript can only be overloaded as a member function. 7244 7245 // Add operator candidates that are member functions. 7246 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 7247 7248 // Add builtin operator candidates. 7249 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 7250 7251 // Perform overload resolution. 7252 OverloadCandidateSet::iterator Best; 7253 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 7254 case OR_Success: { 7255 // We found a built-in operator or an overloaded operator. 7256 FunctionDecl *FnDecl = Best->Function; 7257 7258 if (FnDecl) { 7259 // We matched an overloaded operator. Build a call to that 7260 // operator. 7261 7262 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 7263 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 7264 7265 // Convert the arguments. 7266 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 7267 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 7268 Best->FoundDecl, Method)) 7269 return ExprError(); 7270 7271 // Convert the arguments. 7272 ExprResult InputInit 7273 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 7274 Context, 7275 FnDecl->getParamDecl(0)), 7276 SourceLocation(), 7277 Owned(Args[1])); 7278 if (InputInit.isInvalid()) 7279 return ExprError(); 7280 7281 Args[1] = InputInit.takeAs<Expr>(); 7282 7283 // Determine the result type 7284 QualType ResultTy 7285 = FnDecl->getType()->getAs<FunctionType>() 7286 ->getCallResultType(Context); 7287 7288 // Build the actual expression node. 7289 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 7290 LLoc); 7291 UsualUnaryConversions(FnExpr); 7292 7293 CXXOperatorCallExpr *TheCall = 7294 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 7295 FnExpr, Args, 2, 7296 ResultTy, RLoc); 7297 7298 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 7299 FnDecl)) 7300 return ExprError(); 7301 7302 return MaybeBindToTemporary(TheCall); 7303 } else { 7304 // We matched a built-in operator. Convert the arguments, then 7305 // break out so that we will build the appropriate built-in 7306 // operator node. 7307 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 7308 Best->Conversions[0], AA_Passing) || 7309 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 7310 Best->Conversions[1], AA_Passing)) 7311 return ExprError(); 7312 7313 break; 7314 } 7315 } 7316 7317 case OR_No_Viable_Function: { 7318 if (CandidateSet.empty()) 7319 Diag(LLoc, diag::err_ovl_no_oper) 7320 << Args[0]->getType() << /*subscript*/ 0 7321 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7322 else 7323 Diag(LLoc, diag::err_ovl_no_viable_subscript) 7324 << Args[0]->getType() 7325 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7326 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2, 7327 "[]", LLoc); 7328 return ExprError(); 7329 } 7330 7331 case OR_Ambiguous: 7332 Diag(LLoc, diag::err_ovl_ambiguous_oper) 7333 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7334 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2, 7335 "[]", LLoc); 7336 return ExprError(); 7337 7338 case OR_Deleted: 7339 Diag(LLoc, diag::err_ovl_deleted_oper) 7340 << Best->Function->isDeleted() << "[]" 7341 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7342 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2, 7343 "[]", LLoc); 7344 return ExprError(); 7345 } 7346 7347 // We matched a built-in operator; build it. 7348 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 7349} 7350 7351/// BuildCallToMemberFunction - Build a call to a member 7352/// function. MemExpr is the expression that refers to the member 7353/// function (and includes the object parameter), Args/NumArgs are the 7354/// arguments to the function call (not including the object 7355/// parameter). The caller needs to validate that the member 7356/// expression refers to a member function or an overloaded member 7357/// function. 7358ExprResult 7359Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 7360 SourceLocation LParenLoc, Expr **Args, 7361 unsigned NumArgs, SourceLocation RParenLoc) { 7362 // Dig out the member expression. This holds both the object 7363 // argument and the member function we're referring to. 7364 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 7365 7366 MemberExpr *MemExpr; 7367 CXXMethodDecl *Method = 0; 7368 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 7369 NestedNameSpecifier *Qualifier = 0; 7370 if (isa<MemberExpr>(NakedMemExpr)) { 7371 MemExpr = cast<MemberExpr>(NakedMemExpr); 7372 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 7373 FoundDecl = MemExpr->getFoundDecl(); 7374 Qualifier = MemExpr->getQualifier(); 7375 } else { 7376 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 7377 Qualifier = UnresExpr->getQualifier(); 7378 7379 QualType ObjectType = UnresExpr->getBaseType(); 7380 7381 // Add overload candidates 7382 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 7383 7384 // FIXME: avoid copy. 7385 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 7386 if (UnresExpr->hasExplicitTemplateArgs()) { 7387 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 7388 TemplateArgs = &TemplateArgsBuffer; 7389 } 7390 7391 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 7392 E = UnresExpr->decls_end(); I != E; ++I) { 7393 7394 NamedDecl *Func = *I; 7395 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 7396 if (isa<UsingShadowDecl>(Func)) 7397 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 7398 7399 if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 7400 // If explicit template arguments were provided, we can't call a 7401 // non-template member function. 7402 if (TemplateArgs) 7403 continue; 7404 7405 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 7406 Args, NumArgs, 7407 CandidateSet, /*SuppressUserConversions=*/false); 7408 } else { 7409 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 7410 I.getPair(), ActingDC, TemplateArgs, 7411 ObjectType, Args, NumArgs, 7412 CandidateSet, 7413 /*SuppressUsedConversions=*/false); 7414 } 7415 } 7416 7417 DeclarationName DeclName = UnresExpr->getMemberName(); 7418 7419 OverloadCandidateSet::iterator Best; 7420 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 7421 Best)) { 7422 case OR_Success: 7423 Method = cast<CXXMethodDecl>(Best->Function); 7424 FoundDecl = Best->FoundDecl; 7425 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 7426 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 7427 break; 7428 7429 case OR_No_Viable_Function: 7430 Diag(UnresExpr->getMemberLoc(), 7431 diag::err_ovl_no_viable_member_function_in_call) 7432 << DeclName << MemExprE->getSourceRange(); 7433 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 7434 // FIXME: Leaking incoming expressions! 7435 return ExprError(); 7436 7437 case OR_Ambiguous: 7438 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 7439 << DeclName << MemExprE->getSourceRange(); 7440 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 7441 // FIXME: Leaking incoming expressions! 7442 return ExprError(); 7443 7444 case OR_Deleted: 7445 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 7446 << Best->Function->isDeleted() 7447 << DeclName << MemExprE->getSourceRange(); 7448 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 7449 // FIXME: Leaking incoming expressions! 7450 return ExprError(); 7451 } 7452 7453 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 7454 7455 // If overload resolution picked a static member, build a 7456 // non-member call based on that function. 7457 if (Method->isStatic()) { 7458 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 7459 Args, NumArgs, RParenLoc); 7460 } 7461 7462 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 7463 } 7464 7465 assert(Method && "Member call to something that isn't a method?"); 7466 CXXMemberCallExpr *TheCall = 7467 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs, 7468 Method->getCallResultType(), 7469 RParenLoc); 7470 7471 // Check for a valid return type. 7472 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 7473 TheCall, Method)) 7474 return ExprError(); 7475 7476 // Convert the object argument (for a non-static member function call). 7477 // We only need to do this if there was actually an overload; otherwise 7478 // it was done at lookup. 7479 Expr *ObjectArg = MemExpr->getBase(); 7480 if (!Method->isStatic() && 7481 PerformObjectArgumentInitialization(ObjectArg, Qualifier, 7482 FoundDecl, Method)) 7483 return ExprError(); 7484 MemExpr->setBase(ObjectArg); 7485 7486 // Convert the rest of the arguments 7487 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>(); 7488 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 7489 RParenLoc)) 7490 return ExprError(); 7491 7492 if (CheckFunctionCall(Method, TheCall)) 7493 return ExprError(); 7494 7495 return MaybeBindToTemporary(TheCall); 7496} 7497 7498/// BuildCallToObjectOfClassType - Build a call to an object of class 7499/// type (C++ [over.call.object]), which can end up invoking an 7500/// overloaded function call operator (@c operator()) or performing a 7501/// user-defined conversion on the object argument. 7502ExprResult 7503Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object, 7504 SourceLocation LParenLoc, 7505 Expr **Args, unsigned NumArgs, 7506 SourceLocation RParenLoc) { 7507 assert(Object->getType()->isRecordType() && "Requires object type argument"); 7508 const RecordType *Record = Object->getType()->getAs<RecordType>(); 7509 7510 // C++ [over.call.object]p1: 7511 // If the primary-expression E in the function call syntax 7512 // evaluates to a class object of type "cv T", then the set of 7513 // candidate functions includes at least the function call 7514 // operators of T. The function call operators of T are obtained by 7515 // ordinary lookup of the name operator() in the context of 7516 // (E).operator(). 7517 OverloadCandidateSet CandidateSet(LParenLoc); 7518 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 7519 7520 if (RequireCompleteType(LParenLoc, Object->getType(), 7521 PDiag(diag::err_incomplete_object_call) 7522 << Object->getSourceRange())) 7523 return true; 7524 7525 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 7526 LookupQualifiedName(R, Record->getDecl()); 7527 R.suppressDiagnostics(); 7528 7529 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 7530 Oper != OperEnd; ++Oper) { 7531 AddMethodCandidate(Oper.getPair(), Object->getType(), 7532 Args, NumArgs, CandidateSet, 7533 /*SuppressUserConversions=*/ false); 7534 } 7535 7536 // C++ [over.call.object]p2: 7537 // In addition, for each conversion function declared in T of the 7538 // form 7539 // 7540 // operator conversion-type-id () cv-qualifier; 7541 // 7542 // where cv-qualifier is the same cv-qualification as, or a 7543 // greater cv-qualification than, cv, and where conversion-type-id 7544 // denotes the type "pointer to function of (P1,...,Pn) returning 7545 // R", or the type "reference to pointer to function of 7546 // (P1,...,Pn) returning R", or the type "reference to function 7547 // of (P1,...,Pn) returning R", a surrogate call function [...] 7548 // is also considered as a candidate function. Similarly, 7549 // surrogate call functions are added to the set of candidate 7550 // functions for each conversion function declared in an 7551 // accessible base class provided the function is not hidden 7552 // within T by another intervening declaration. 7553 const UnresolvedSetImpl *Conversions 7554 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 7555 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 7556 E = Conversions->end(); I != E; ++I) { 7557 NamedDecl *D = *I; 7558 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 7559 if (isa<UsingShadowDecl>(D)) 7560 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7561 7562 // Skip over templated conversion functions; they aren't 7563 // surrogates. 7564 if (isa<FunctionTemplateDecl>(D)) 7565 continue; 7566 7567 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7568 7569 // Strip the reference type (if any) and then the pointer type (if 7570 // any) to get down to what might be a function type. 7571 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 7572 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 7573 ConvType = ConvPtrType->getPointeeType(); 7574 7575 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 7576 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 7577 Object->getType(), Args, NumArgs, 7578 CandidateSet); 7579 } 7580 7581 // Perform overload resolution. 7582 OverloadCandidateSet::iterator Best; 7583 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(), 7584 Best)) { 7585 case OR_Success: 7586 // Overload resolution succeeded; we'll build the appropriate call 7587 // below. 7588 break; 7589 7590 case OR_No_Viable_Function: 7591 if (CandidateSet.empty()) 7592 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper) 7593 << Object->getType() << /*call*/ 1 7594 << Object->getSourceRange(); 7595 else 7596 Diag(Object->getSourceRange().getBegin(), 7597 diag::err_ovl_no_viable_object_call) 7598 << Object->getType() << Object->getSourceRange(); 7599 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 7600 break; 7601 7602 case OR_Ambiguous: 7603 Diag(Object->getSourceRange().getBegin(), 7604 diag::err_ovl_ambiguous_object_call) 7605 << Object->getType() << Object->getSourceRange(); 7606 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); 7607 break; 7608 7609 case OR_Deleted: 7610 Diag(Object->getSourceRange().getBegin(), 7611 diag::err_ovl_deleted_object_call) 7612 << Best->Function->isDeleted() 7613 << Object->getType() << Object->getSourceRange(); 7614 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 7615 break; 7616 } 7617 7618 if (Best == CandidateSet.end()) 7619 return true; 7620 7621 if (Best->Function == 0) { 7622 // Since there is no function declaration, this is one of the 7623 // surrogate candidates. Dig out the conversion function. 7624 CXXConversionDecl *Conv 7625 = cast<CXXConversionDecl>( 7626 Best->Conversions[0].UserDefined.ConversionFunction); 7627 7628 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl); 7629 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 7630 7631 // We selected one of the surrogate functions that converts the 7632 // object parameter to a function pointer. Perform the conversion 7633 // on the object argument, then let ActOnCallExpr finish the job. 7634 7635 // Create an implicit member expr to refer to the conversion operator. 7636 // and then call it. 7637 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl, 7638 Conv); 7639 7640 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs), 7641 RParenLoc); 7642 } 7643 7644 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl); 7645 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 7646 7647 // We found an overloaded operator(). Build a CXXOperatorCallExpr 7648 // that calls this method, using Object for the implicit object 7649 // parameter and passing along the remaining arguments. 7650 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 7651 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>(); 7652 7653 unsigned NumArgsInProto = Proto->getNumArgs(); 7654 unsigned NumArgsToCheck = NumArgs; 7655 7656 // Build the full argument list for the method call (the 7657 // implicit object parameter is placed at the beginning of the 7658 // list). 7659 Expr **MethodArgs; 7660 if (NumArgs < NumArgsInProto) { 7661 NumArgsToCheck = NumArgsInProto; 7662 MethodArgs = new Expr*[NumArgsInProto + 1]; 7663 } else { 7664 MethodArgs = new Expr*[NumArgs + 1]; 7665 } 7666 MethodArgs[0] = Object; 7667 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7668 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 7669 7670 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(), 7671 SourceLocation()); 7672 UsualUnaryConversions(NewFn); 7673 7674 // Once we've built TheCall, all of the expressions are properly 7675 // owned. 7676 QualType ResultTy = Method->getCallResultType(); 7677 CXXOperatorCallExpr *TheCall = 7678 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn, 7679 MethodArgs, NumArgs + 1, 7680 ResultTy, RParenLoc); 7681 delete [] MethodArgs; 7682 7683 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 7684 Method)) 7685 return true; 7686 7687 // We may have default arguments. If so, we need to allocate more 7688 // slots in the call for them. 7689 if (NumArgs < NumArgsInProto) 7690 TheCall->setNumArgs(Context, NumArgsInProto + 1); 7691 else if (NumArgs > NumArgsInProto) 7692 NumArgsToCheck = NumArgsInProto; 7693 7694 bool IsError = false; 7695 7696 // Initialize the implicit object parameter. 7697 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0, 7698 Best->FoundDecl, Method); 7699 TheCall->setArg(0, Object); 7700 7701 7702 // Check the argument types. 7703 for (unsigned i = 0; i != NumArgsToCheck; i++) { 7704 Expr *Arg; 7705 if (i < NumArgs) { 7706 Arg = Args[i]; 7707 7708 // Pass the argument. 7709 7710 ExprResult InputInit 7711 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 7712 Context, 7713 Method->getParamDecl(i)), 7714 SourceLocation(), Arg); 7715 7716 IsError |= InputInit.isInvalid(); 7717 Arg = InputInit.takeAs<Expr>(); 7718 } else { 7719 ExprResult DefArg 7720 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 7721 if (DefArg.isInvalid()) { 7722 IsError = true; 7723 break; 7724 } 7725 7726 Arg = DefArg.takeAs<Expr>(); 7727 } 7728 7729 TheCall->setArg(i + 1, Arg); 7730 } 7731 7732 // If this is a variadic call, handle args passed through "...". 7733 if (Proto->isVariadic()) { 7734 // Promote the arguments (C99 6.5.2.2p7). 7735 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 7736 Expr *Arg = Args[i]; 7737 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0); 7738 TheCall->setArg(i + 1, Arg); 7739 } 7740 } 7741 7742 if (IsError) return true; 7743 7744 if (CheckFunctionCall(Method, TheCall)) 7745 return true; 7746 7747 return MaybeBindToTemporary(TheCall); 7748} 7749 7750/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 7751/// (if one exists), where @c Base is an expression of class type and 7752/// @c Member is the name of the member we're trying to find. 7753ExprResult 7754Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 7755 assert(Base->getType()->isRecordType() && "left-hand side must have class type"); 7756 7757 SourceLocation Loc = Base->getExprLoc(); 7758 7759 // C++ [over.ref]p1: 7760 // 7761 // [...] An expression x->m is interpreted as (x.operator->())->m 7762 // for a class object x of type T if T::operator->() exists and if 7763 // the operator is selected as the best match function by the 7764 // overload resolution mechanism (13.3). 7765 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 7766 OverloadCandidateSet CandidateSet(Loc); 7767 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 7768 7769 if (RequireCompleteType(Loc, Base->getType(), 7770 PDiag(diag::err_typecheck_incomplete_tag) 7771 << Base->getSourceRange())) 7772 return ExprError(); 7773 7774 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 7775 LookupQualifiedName(R, BaseRecord->getDecl()); 7776 R.suppressDiagnostics(); 7777 7778 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 7779 Oper != OperEnd; ++Oper) { 7780 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet, 7781 /*SuppressUserConversions=*/false); 7782 } 7783 7784 // Perform overload resolution. 7785 OverloadCandidateSet::iterator Best; 7786 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 7787 case OR_Success: 7788 // Overload resolution succeeded; we'll build the call below. 7789 break; 7790 7791 case OR_No_Viable_Function: 7792 if (CandidateSet.empty()) 7793 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 7794 << Base->getType() << Base->getSourceRange(); 7795 else 7796 Diag(OpLoc, diag::err_ovl_no_viable_oper) 7797 << "operator->" << Base->getSourceRange(); 7798 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1); 7799 return ExprError(); 7800 7801 case OR_Ambiguous: 7802 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 7803 << "->" << Base->getSourceRange(); 7804 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1); 7805 return ExprError(); 7806 7807 case OR_Deleted: 7808 Diag(OpLoc, diag::err_ovl_deleted_oper) 7809 << Best->Function->isDeleted() 7810 << "->" << Base->getSourceRange(); 7811 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1); 7812 return ExprError(); 7813 } 7814 7815 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 7816 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 7817 7818 // Convert the object parameter. 7819 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 7820 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 7821 Best->FoundDecl, Method)) 7822 return ExprError(); 7823 7824 // Build the operator call. 7825 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(), 7826 SourceLocation()); 7827 UsualUnaryConversions(FnExpr); 7828 7829 QualType ResultTy = Method->getCallResultType(); 7830 CXXOperatorCallExpr *TheCall = 7831 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, 7832 &Base, 1, ResultTy, OpLoc); 7833 7834 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 7835 Method)) 7836 return ExprError(); 7837 return Owned(TheCall); 7838} 7839 7840/// FixOverloadedFunctionReference - E is an expression that refers to 7841/// a C++ overloaded function (possibly with some parentheses and 7842/// perhaps a '&' around it). We have resolved the overloaded function 7843/// to the function declaration Fn, so patch up the expression E to 7844/// refer (possibly indirectly) to Fn. Returns the new expr. 7845Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 7846 FunctionDecl *Fn) { 7847 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 7848 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 7849 Found, Fn); 7850 if (SubExpr == PE->getSubExpr()) 7851 return PE->Retain(); 7852 7853 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 7854 } 7855 7856 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7857 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 7858 Found, Fn); 7859 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 7860 SubExpr->getType()) && 7861 "Implicit cast type cannot be determined from overload"); 7862 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 7863 if (SubExpr == ICE->getSubExpr()) 7864 return ICE->Retain(); 7865 7866 return ImplicitCastExpr::Create(Context, ICE->getType(), 7867 ICE->getCastKind(), 7868 SubExpr, 0, 7869 ICE->getValueKind()); 7870 } 7871 7872 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 7873 assert(UnOp->getOpcode() == UO_AddrOf && 7874 "Can only take the address of an overloaded function"); 7875 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 7876 if (Method->isStatic()) { 7877 // Do nothing: static member functions aren't any different 7878 // from non-member functions. 7879 } else { 7880 // Fix the sub expression, which really has to be an 7881 // UnresolvedLookupExpr holding an overloaded member function 7882 // or template. 7883 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 7884 Found, Fn); 7885 if (SubExpr == UnOp->getSubExpr()) 7886 return UnOp->Retain(); 7887 7888 assert(isa<DeclRefExpr>(SubExpr) 7889 && "fixed to something other than a decl ref"); 7890 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 7891 && "fixed to a member ref with no nested name qualifier"); 7892 7893 // We have taken the address of a pointer to member 7894 // function. Perform the computation here so that we get the 7895 // appropriate pointer to member type. 7896 QualType ClassType 7897 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 7898 QualType MemPtrType 7899 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 7900 7901 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 7902 MemPtrType, UnOp->getOperatorLoc()); 7903 } 7904 } 7905 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 7906 Found, Fn); 7907 if (SubExpr == UnOp->getSubExpr()) 7908 return UnOp->Retain(); 7909 7910 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 7911 Context.getPointerType(SubExpr->getType()), 7912 UnOp->getOperatorLoc()); 7913 } 7914 7915 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 7916 // FIXME: avoid copy. 7917 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 7918 if (ULE->hasExplicitTemplateArgs()) { 7919 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 7920 TemplateArgs = &TemplateArgsBuffer; 7921 } 7922 7923 return DeclRefExpr::Create(Context, 7924 ULE->getQualifier(), 7925 ULE->getQualifierRange(), 7926 Fn, 7927 ULE->getNameLoc(), 7928 Fn->getType(), 7929 TemplateArgs); 7930 } 7931 7932 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 7933 // FIXME: avoid copy. 7934 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 7935 if (MemExpr->hasExplicitTemplateArgs()) { 7936 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 7937 TemplateArgs = &TemplateArgsBuffer; 7938 } 7939 7940 Expr *Base; 7941 7942 // If we're filling in 7943 if (MemExpr->isImplicitAccess()) { 7944 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 7945 return DeclRefExpr::Create(Context, 7946 MemExpr->getQualifier(), 7947 MemExpr->getQualifierRange(), 7948 Fn, 7949 MemExpr->getMemberLoc(), 7950 Fn->getType(), 7951 TemplateArgs); 7952 } else { 7953 SourceLocation Loc = MemExpr->getMemberLoc(); 7954 if (MemExpr->getQualifier()) 7955 Loc = MemExpr->getQualifierRange().getBegin(); 7956 Base = new (Context) CXXThisExpr(Loc, 7957 MemExpr->getBaseType(), 7958 /*isImplicit=*/true); 7959 } 7960 } else 7961 Base = MemExpr->getBase()->Retain(); 7962 7963 return MemberExpr::Create(Context, Base, 7964 MemExpr->isArrow(), 7965 MemExpr->getQualifier(), 7966 MemExpr->getQualifierRange(), 7967 Fn, 7968 Found, 7969 MemExpr->getMemberNameInfo(), 7970 TemplateArgs, 7971 Fn->getType()); 7972 } 7973 7974 assert(false && "Invalid reference to overloaded function"); 7975 return E->Retain(); 7976} 7977 7978ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 7979 DeclAccessPair Found, 7980 FunctionDecl *Fn) { 7981 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 7982} 7983 7984} // end namespace clang 7985