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