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