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