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