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