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