SemaOverload.cpp revision 29ecaba4ebe8c9a2627cf405e36473b764cc5cfd
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 NamedDecl *D = *Con; 1529 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 1530 1531 // Find the constructor (which may be a template). 1532 CXXConstructorDecl *Constructor = 0; 1533 FunctionTemplateDecl *ConstructorTmpl 1534 = dyn_cast<FunctionTemplateDecl>(D); 1535 if (ConstructorTmpl) 1536 Constructor 1537 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 1538 else 1539 Constructor = cast<CXXConstructorDecl>(D); 1540 1541 if (!Constructor->isInvalidDecl() && 1542 Constructor->isConvertingConstructor(AllowExplicit)) { 1543 if (ConstructorTmpl) 1544 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 1545 /*ExplicitArgs*/ 0, 1546 &From, 1, CandidateSet, 1547 SuppressUserConversions, ForceRValue); 1548 else 1549 // Allow one user-defined conversion when user specifies a 1550 // From->ToType conversion via an static cast (c-style, etc). 1551 AddOverloadCandidate(Constructor, FoundDecl, 1552 &From, 1, CandidateSet, 1553 SuppressUserConversions, ForceRValue); 1554 } 1555 } 1556 } 1557 } 1558 1559 if (!AllowConversionFunctions) { 1560 // Don't allow any conversion functions to enter the overload set. 1561 } else if (RequireCompleteType(From->getLocStart(), From->getType(), 1562 PDiag(0) 1563 << From->getSourceRange())) { 1564 // No conversion functions from incomplete types. 1565 } else if (const RecordType *FromRecordType 1566 = From->getType()->getAs<RecordType>()) { 1567 if (CXXRecordDecl *FromRecordDecl 1568 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 1569 // Add all of the conversion functions as candidates. 1570 const UnresolvedSetImpl *Conversions 1571 = FromRecordDecl->getVisibleConversionFunctions(); 1572 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 1573 E = Conversions->end(); I != E; ++I) { 1574 DeclAccessPair FoundDecl = I.getPair(); 1575 NamedDecl *D = FoundDecl.getDecl(); 1576 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 1577 if (isa<UsingShadowDecl>(D)) 1578 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1579 1580 CXXConversionDecl *Conv; 1581 FunctionTemplateDecl *ConvTemplate; 1582 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I))) 1583 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 1584 else 1585 Conv = dyn_cast<CXXConversionDecl>(*I); 1586 1587 if (AllowExplicit || !Conv->isExplicit()) { 1588 if (ConvTemplate) 1589 AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 1590 ActingContext, From, ToType, 1591 CandidateSet); 1592 else 1593 AddConversionCandidate(Conv, FoundDecl, ActingContext, 1594 From, ToType, CandidateSet); 1595 } 1596 } 1597 } 1598 } 1599 1600 OverloadCandidateSet::iterator Best; 1601 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) { 1602 case OR_Success: 1603 // Record the standard conversion we used and the conversion function. 1604 if (CXXConstructorDecl *Constructor 1605 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 1606 // C++ [over.ics.user]p1: 1607 // If the user-defined conversion is specified by a 1608 // constructor (12.3.1), the initial standard conversion 1609 // sequence converts the source type to the type required by 1610 // the argument of the constructor. 1611 // 1612 QualType ThisType = Constructor->getThisType(Context); 1613 if (Best->Conversions[0].isEllipsis()) 1614 User.EllipsisConversion = true; 1615 else { 1616 User.Before = Best->Conversions[0].Standard; 1617 User.EllipsisConversion = false; 1618 } 1619 User.ConversionFunction = Constructor; 1620 User.After.setAsIdentityConversion(); 1621 User.After.setFromType( 1622 ThisType->getAs<PointerType>()->getPointeeType()); 1623 User.After.setAllToTypes(ToType); 1624 return OR_Success; 1625 } else if (CXXConversionDecl *Conversion 1626 = dyn_cast<CXXConversionDecl>(Best->Function)) { 1627 // C++ [over.ics.user]p1: 1628 // 1629 // [...] If the user-defined conversion is specified by a 1630 // conversion function (12.3.2), the initial standard 1631 // conversion sequence converts the source type to the 1632 // implicit object parameter of the conversion function. 1633 User.Before = Best->Conversions[0].Standard; 1634 User.ConversionFunction = Conversion; 1635 User.EllipsisConversion = false; 1636 1637 // C++ [over.ics.user]p2: 1638 // The second standard conversion sequence converts the 1639 // result of the user-defined conversion to the target type 1640 // for the sequence. Since an implicit conversion sequence 1641 // is an initialization, the special rules for 1642 // initialization by user-defined conversion apply when 1643 // selecting the best user-defined conversion for a 1644 // user-defined conversion sequence (see 13.3.3 and 1645 // 13.3.3.1). 1646 User.After = Best->FinalConversion; 1647 return OR_Success; 1648 } else { 1649 assert(false && "Not a constructor or conversion function?"); 1650 return OR_No_Viable_Function; 1651 } 1652 1653 case OR_No_Viable_Function: 1654 return OR_No_Viable_Function; 1655 case OR_Deleted: 1656 // No conversion here! We're done. 1657 return OR_Deleted; 1658 1659 case OR_Ambiguous: 1660 return OR_Ambiguous; 1661 } 1662 1663 return OR_No_Viable_Function; 1664} 1665 1666bool 1667Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 1668 ImplicitConversionSequence ICS; 1669 OverloadCandidateSet CandidateSet(From->getExprLoc()); 1670 OverloadingResult OvResult = 1671 IsUserDefinedConversion(From, ToType, ICS.UserDefined, 1672 CandidateSet, true, false, false); 1673 if (OvResult == OR_Ambiguous) 1674 Diag(From->getSourceRange().getBegin(), 1675 diag::err_typecheck_ambiguous_condition) 1676 << From->getType() << ToType << From->getSourceRange(); 1677 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 1678 Diag(From->getSourceRange().getBegin(), 1679 diag::err_typecheck_nonviable_condition) 1680 << From->getType() << ToType << From->getSourceRange(); 1681 else 1682 return false; 1683 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1); 1684 return true; 1685} 1686 1687/// CompareImplicitConversionSequences - Compare two implicit 1688/// conversion sequences to determine whether one is better than the 1689/// other or if they are indistinguishable (C++ 13.3.3.2). 1690ImplicitConversionSequence::CompareKind 1691Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1, 1692 const ImplicitConversionSequence& ICS2) 1693{ 1694 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 1695 // conversion sequences (as defined in 13.3.3.1) 1696 // -- a standard conversion sequence (13.3.3.1.1) is a better 1697 // conversion sequence than a user-defined conversion sequence or 1698 // an ellipsis conversion sequence, and 1699 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 1700 // conversion sequence than an ellipsis conversion sequence 1701 // (13.3.3.1.3). 1702 // 1703 // C++0x [over.best.ics]p10: 1704 // For the purpose of ranking implicit conversion sequences as 1705 // described in 13.3.3.2, the ambiguous conversion sequence is 1706 // treated as a user-defined sequence that is indistinguishable 1707 // from any other user-defined conversion sequence. 1708 if (ICS1.getKind() < ICS2.getKind()) { 1709 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous())) 1710 return ImplicitConversionSequence::Better; 1711 } else if (ICS2.getKind() < ICS1.getKind()) { 1712 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous())) 1713 return ImplicitConversionSequence::Worse; 1714 } 1715 1716 if (ICS1.isAmbiguous() || ICS2.isAmbiguous()) 1717 return ImplicitConversionSequence::Indistinguishable; 1718 1719 // Two implicit conversion sequences of the same form are 1720 // indistinguishable conversion sequences unless one of the 1721 // following rules apply: (C++ 13.3.3.2p3): 1722 if (ICS1.isStandard()) 1723 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard); 1724 else if (ICS1.isUserDefined()) { 1725 // User-defined conversion sequence U1 is a better conversion 1726 // sequence than another user-defined conversion sequence U2 if 1727 // they contain the same user-defined conversion function or 1728 // constructor and if the second standard conversion sequence of 1729 // U1 is better than the second standard conversion sequence of 1730 // U2 (C++ 13.3.3.2p3). 1731 if (ICS1.UserDefined.ConversionFunction == 1732 ICS2.UserDefined.ConversionFunction) 1733 return CompareStandardConversionSequences(ICS1.UserDefined.After, 1734 ICS2.UserDefined.After); 1735 } 1736 1737 return ImplicitConversionSequence::Indistinguishable; 1738} 1739 1740// Per 13.3.3.2p3, compare the given standard conversion sequences to 1741// determine if one is a proper subset of the other. 1742static ImplicitConversionSequence::CompareKind 1743compareStandardConversionSubsets(ASTContext &Context, 1744 const StandardConversionSequence& SCS1, 1745 const StandardConversionSequence& SCS2) { 1746 ImplicitConversionSequence::CompareKind Result 1747 = ImplicitConversionSequence::Indistinguishable; 1748 1749 if (SCS1.Second != SCS2.Second) { 1750 if (SCS1.Second == ICK_Identity) 1751 Result = ImplicitConversionSequence::Better; 1752 else if (SCS2.Second == ICK_Identity) 1753 Result = ImplicitConversionSequence::Worse; 1754 else 1755 return ImplicitConversionSequence::Indistinguishable; 1756 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1))) 1757 return ImplicitConversionSequence::Indistinguishable; 1758 1759 if (SCS1.Third == SCS2.Third) { 1760 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 1761 : ImplicitConversionSequence::Indistinguishable; 1762 } 1763 1764 if (SCS1.Third == ICK_Identity) 1765 return Result == ImplicitConversionSequence::Worse 1766 ? ImplicitConversionSequence::Indistinguishable 1767 : ImplicitConversionSequence::Better; 1768 1769 if (SCS2.Third == ICK_Identity) 1770 return Result == ImplicitConversionSequence::Better 1771 ? ImplicitConversionSequence::Indistinguishable 1772 : ImplicitConversionSequence::Worse; 1773 1774 return ImplicitConversionSequence::Indistinguishable; 1775} 1776 1777/// CompareStandardConversionSequences - Compare two standard 1778/// conversion sequences to determine whether one is better than the 1779/// other or if they are indistinguishable (C++ 13.3.3.2p3). 1780ImplicitConversionSequence::CompareKind 1781Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1, 1782 const StandardConversionSequence& SCS2) 1783{ 1784 // Standard conversion sequence S1 is a better conversion sequence 1785 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 1786 1787 // -- S1 is a proper subsequence of S2 (comparing the conversion 1788 // sequences in the canonical form defined by 13.3.3.1.1, 1789 // excluding any Lvalue Transformation; the identity conversion 1790 // sequence is considered to be a subsequence of any 1791 // non-identity conversion sequence) or, if not that, 1792 if (ImplicitConversionSequence::CompareKind CK 1793 = compareStandardConversionSubsets(Context, SCS1, SCS2)) 1794 return CK; 1795 1796 // -- the rank of S1 is better than the rank of S2 (by the rules 1797 // defined below), or, if not that, 1798 ImplicitConversionRank Rank1 = SCS1.getRank(); 1799 ImplicitConversionRank Rank2 = SCS2.getRank(); 1800 if (Rank1 < Rank2) 1801 return ImplicitConversionSequence::Better; 1802 else if (Rank2 < Rank1) 1803 return ImplicitConversionSequence::Worse; 1804 1805 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 1806 // are indistinguishable unless one of the following rules 1807 // applies: 1808 1809 // A conversion that is not a conversion of a pointer, or 1810 // pointer to member, to bool is better than another conversion 1811 // that is such a conversion. 1812 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 1813 return SCS2.isPointerConversionToBool() 1814 ? ImplicitConversionSequence::Better 1815 : ImplicitConversionSequence::Worse; 1816 1817 // C++ [over.ics.rank]p4b2: 1818 // 1819 // If class B is derived directly or indirectly from class A, 1820 // conversion of B* to A* is better than conversion of B* to 1821 // void*, and conversion of A* to void* is better than conversion 1822 // of B* to void*. 1823 bool SCS1ConvertsToVoid 1824 = SCS1.isPointerConversionToVoidPointer(Context); 1825 bool SCS2ConvertsToVoid 1826 = SCS2.isPointerConversionToVoidPointer(Context); 1827 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 1828 // Exactly one of the conversion sequences is a conversion to 1829 // a void pointer; it's the worse conversion. 1830 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 1831 : ImplicitConversionSequence::Worse; 1832 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 1833 // Neither conversion sequence converts to a void pointer; compare 1834 // their derived-to-base conversions. 1835 if (ImplicitConversionSequence::CompareKind DerivedCK 1836 = CompareDerivedToBaseConversions(SCS1, SCS2)) 1837 return DerivedCK; 1838 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) { 1839 // Both conversion sequences are conversions to void 1840 // pointers. Compare the source types to determine if there's an 1841 // inheritance relationship in their sources. 1842 QualType FromType1 = SCS1.getFromType(); 1843 QualType FromType2 = SCS2.getFromType(); 1844 1845 // Adjust the types we're converting from via the array-to-pointer 1846 // conversion, if we need to. 1847 if (SCS1.First == ICK_Array_To_Pointer) 1848 FromType1 = Context.getArrayDecayedType(FromType1); 1849 if (SCS2.First == ICK_Array_To_Pointer) 1850 FromType2 = Context.getArrayDecayedType(FromType2); 1851 1852 QualType FromPointee1 1853 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 1854 QualType FromPointee2 1855 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 1856 1857 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1858 return ImplicitConversionSequence::Better; 1859 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1860 return ImplicitConversionSequence::Worse; 1861 1862 // Objective-C++: If one interface is more specific than the 1863 // other, it is the better one. 1864 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>(); 1865 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>(); 1866 if (FromIface1 && FromIface1) { 1867 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 1868 return ImplicitConversionSequence::Better; 1869 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 1870 return ImplicitConversionSequence::Worse; 1871 } 1872 } 1873 1874 // Compare based on qualification conversions (C++ 13.3.3.2p3, 1875 // bullet 3). 1876 if (ImplicitConversionSequence::CompareKind QualCK 1877 = CompareQualificationConversions(SCS1, SCS2)) 1878 return QualCK; 1879 1880 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 1881 // C++0x [over.ics.rank]p3b4: 1882 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 1883 // implicit object parameter of a non-static member function declared 1884 // without a ref-qualifier, and S1 binds an rvalue reference to an 1885 // rvalue and S2 binds an lvalue reference. 1886 // FIXME: We don't know if we're dealing with the implicit object parameter, 1887 // or if the member function in this case has a ref qualifier. 1888 // (Of course, we don't have ref qualifiers yet.) 1889 if (SCS1.RRefBinding != SCS2.RRefBinding) 1890 return SCS1.RRefBinding ? ImplicitConversionSequence::Better 1891 : ImplicitConversionSequence::Worse; 1892 1893 // C++ [over.ics.rank]p3b4: 1894 // -- S1 and S2 are reference bindings (8.5.3), and the types to 1895 // which the references refer are the same type except for 1896 // top-level cv-qualifiers, and the type to which the reference 1897 // initialized by S2 refers is more cv-qualified than the type 1898 // to which the reference initialized by S1 refers. 1899 QualType T1 = SCS1.getToType(2); 1900 QualType T2 = SCS2.getToType(2); 1901 T1 = Context.getCanonicalType(T1); 1902 T2 = Context.getCanonicalType(T2); 1903 Qualifiers T1Quals, T2Quals; 1904 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 1905 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 1906 if (UnqualT1 == UnqualT2) { 1907 // If the type is an array type, promote the element qualifiers to the type 1908 // for comparison. 1909 if (isa<ArrayType>(T1) && T1Quals) 1910 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 1911 if (isa<ArrayType>(T2) && T2Quals) 1912 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 1913 if (T2.isMoreQualifiedThan(T1)) 1914 return ImplicitConversionSequence::Better; 1915 else if (T1.isMoreQualifiedThan(T2)) 1916 return ImplicitConversionSequence::Worse; 1917 } 1918 } 1919 1920 return ImplicitConversionSequence::Indistinguishable; 1921} 1922 1923/// CompareQualificationConversions - Compares two standard conversion 1924/// sequences to determine whether they can be ranked based on their 1925/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 1926ImplicitConversionSequence::CompareKind 1927Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1, 1928 const StandardConversionSequence& SCS2) { 1929 // C++ 13.3.3.2p3: 1930 // -- S1 and S2 differ only in their qualification conversion and 1931 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 1932 // cv-qualification signature of type T1 is a proper subset of 1933 // the cv-qualification signature of type T2, and S1 is not the 1934 // deprecated string literal array-to-pointer conversion (4.2). 1935 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 1936 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 1937 return ImplicitConversionSequence::Indistinguishable; 1938 1939 // FIXME: the example in the standard doesn't use a qualification 1940 // conversion (!) 1941 QualType T1 = SCS1.getToType(2); 1942 QualType T2 = SCS2.getToType(2); 1943 T1 = Context.getCanonicalType(T1); 1944 T2 = Context.getCanonicalType(T2); 1945 Qualifiers T1Quals, T2Quals; 1946 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 1947 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 1948 1949 // If the types are the same, we won't learn anything by unwrapped 1950 // them. 1951 if (UnqualT1 == UnqualT2) 1952 return ImplicitConversionSequence::Indistinguishable; 1953 1954 // If the type is an array type, promote the element qualifiers to the type 1955 // for comparison. 1956 if (isa<ArrayType>(T1) && T1Quals) 1957 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 1958 if (isa<ArrayType>(T2) && T2Quals) 1959 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 1960 1961 ImplicitConversionSequence::CompareKind Result 1962 = ImplicitConversionSequence::Indistinguishable; 1963 while (UnwrapSimilarPointerTypes(T1, T2)) { 1964 // Within each iteration of the loop, we check the qualifiers to 1965 // determine if this still looks like a qualification 1966 // conversion. Then, if all is well, we unwrap one more level of 1967 // pointers or pointers-to-members and do it all again 1968 // until there are no more pointers or pointers-to-members left 1969 // to unwrap. This essentially mimics what 1970 // IsQualificationConversion does, but here we're checking for a 1971 // strict subset of qualifiers. 1972 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1973 // The qualifiers are the same, so this doesn't tell us anything 1974 // about how the sequences rank. 1975 ; 1976 else if (T2.isMoreQualifiedThan(T1)) { 1977 // T1 has fewer qualifiers, so it could be the better sequence. 1978 if (Result == ImplicitConversionSequence::Worse) 1979 // Neither has qualifiers that are a subset of the other's 1980 // qualifiers. 1981 return ImplicitConversionSequence::Indistinguishable; 1982 1983 Result = ImplicitConversionSequence::Better; 1984 } else if (T1.isMoreQualifiedThan(T2)) { 1985 // T2 has fewer qualifiers, so it could be the better sequence. 1986 if (Result == ImplicitConversionSequence::Better) 1987 // Neither has qualifiers that are a subset of the other's 1988 // qualifiers. 1989 return ImplicitConversionSequence::Indistinguishable; 1990 1991 Result = ImplicitConversionSequence::Worse; 1992 } else { 1993 // Qualifiers are disjoint. 1994 return ImplicitConversionSequence::Indistinguishable; 1995 } 1996 1997 // If the types after this point are equivalent, we're done. 1998 if (Context.hasSameUnqualifiedType(T1, T2)) 1999 break; 2000 } 2001 2002 // Check that the winning standard conversion sequence isn't using 2003 // the deprecated string literal array to pointer conversion. 2004 switch (Result) { 2005 case ImplicitConversionSequence::Better: 2006 if (SCS1.DeprecatedStringLiteralToCharPtr) 2007 Result = ImplicitConversionSequence::Indistinguishable; 2008 break; 2009 2010 case ImplicitConversionSequence::Indistinguishable: 2011 break; 2012 2013 case ImplicitConversionSequence::Worse: 2014 if (SCS2.DeprecatedStringLiteralToCharPtr) 2015 Result = ImplicitConversionSequence::Indistinguishable; 2016 break; 2017 } 2018 2019 return Result; 2020} 2021 2022/// CompareDerivedToBaseConversions - Compares two standard conversion 2023/// sequences to determine whether they can be ranked based on their 2024/// various kinds of derived-to-base conversions (C++ 2025/// [over.ics.rank]p4b3). As part of these checks, we also look at 2026/// conversions between Objective-C interface types. 2027ImplicitConversionSequence::CompareKind 2028Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1, 2029 const StandardConversionSequence& SCS2) { 2030 QualType FromType1 = SCS1.getFromType(); 2031 QualType ToType1 = SCS1.getToType(1); 2032 QualType FromType2 = SCS2.getFromType(); 2033 QualType ToType2 = SCS2.getToType(1); 2034 2035 // Adjust the types we're converting from via the array-to-pointer 2036 // conversion, if we need to. 2037 if (SCS1.First == ICK_Array_To_Pointer) 2038 FromType1 = Context.getArrayDecayedType(FromType1); 2039 if (SCS2.First == ICK_Array_To_Pointer) 2040 FromType2 = Context.getArrayDecayedType(FromType2); 2041 2042 // Canonicalize all of the types. 2043 FromType1 = Context.getCanonicalType(FromType1); 2044 ToType1 = Context.getCanonicalType(ToType1); 2045 FromType2 = Context.getCanonicalType(FromType2); 2046 ToType2 = Context.getCanonicalType(ToType2); 2047 2048 // C++ [over.ics.rank]p4b3: 2049 // 2050 // If class B is derived directly or indirectly from class A and 2051 // class C is derived directly or indirectly from B, 2052 // 2053 // For Objective-C, we let A, B, and C also be Objective-C 2054 // interfaces. 2055 2056 // Compare based on pointer conversions. 2057 if (SCS1.Second == ICK_Pointer_Conversion && 2058 SCS2.Second == ICK_Pointer_Conversion && 2059 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 2060 FromType1->isPointerType() && FromType2->isPointerType() && 2061 ToType1->isPointerType() && ToType2->isPointerType()) { 2062 QualType FromPointee1 2063 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2064 QualType ToPointee1 2065 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2066 QualType FromPointee2 2067 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2068 QualType ToPointee2 2069 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 2070 2071 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>(); 2072 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>(); 2073 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>(); 2074 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>(); 2075 2076 // -- conversion of C* to B* is better than conversion of C* to A*, 2077 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 2078 if (IsDerivedFrom(ToPointee1, ToPointee2)) 2079 return ImplicitConversionSequence::Better; 2080 else if (IsDerivedFrom(ToPointee2, ToPointee1)) 2081 return ImplicitConversionSequence::Worse; 2082 2083 if (ToIface1 && ToIface2) { 2084 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1)) 2085 return ImplicitConversionSequence::Better; 2086 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2)) 2087 return ImplicitConversionSequence::Worse; 2088 } 2089 } 2090 2091 // -- conversion of B* to A* is better than conversion of C* to A*, 2092 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 2093 if (IsDerivedFrom(FromPointee2, FromPointee1)) 2094 return ImplicitConversionSequence::Better; 2095 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 2096 return ImplicitConversionSequence::Worse; 2097 2098 if (FromIface1 && FromIface2) { 2099 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 2100 return ImplicitConversionSequence::Better; 2101 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 2102 return ImplicitConversionSequence::Worse; 2103 } 2104 } 2105 } 2106 2107 // Ranking of member-pointer types. 2108 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 2109 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 2110 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 2111 const MemberPointerType * FromMemPointer1 = 2112 FromType1->getAs<MemberPointerType>(); 2113 const MemberPointerType * ToMemPointer1 = 2114 ToType1->getAs<MemberPointerType>(); 2115 const MemberPointerType * FromMemPointer2 = 2116 FromType2->getAs<MemberPointerType>(); 2117 const MemberPointerType * ToMemPointer2 = 2118 ToType2->getAs<MemberPointerType>(); 2119 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 2120 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 2121 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 2122 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 2123 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 2124 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 2125 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 2126 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 2127 // conversion of A::* to B::* is better than conversion of A::* to C::*, 2128 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 2129 if (IsDerivedFrom(ToPointee1, ToPointee2)) 2130 return ImplicitConversionSequence::Worse; 2131 else if (IsDerivedFrom(ToPointee2, ToPointee1)) 2132 return ImplicitConversionSequence::Better; 2133 } 2134 // conversion of B::* to C::* is better than conversion of A::* to C::* 2135 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 2136 if (IsDerivedFrom(FromPointee1, FromPointee2)) 2137 return ImplicitConversionSequence::Better; 2138 else if (IsDerivedFrom(FromPointee2, FromPointee1)) 2139 return ImplicitConversionSequence::Worse; 2140 } 2141 } 2142 2143 if ((SCS1.ReferenceBinding || SCS1.CopyConstructor) && 2144 (SCS2.ReferenceBinding || SCS2.CopyConstructor) && 2145 SCS1.Second == ICK_Derived_To_Base) { 2146 // -- conversion of C to B is better than conversion of C to A, 2147 // -- binding of an expression of type C to a reference of type 2148 // B& is better than binding an expression of type C to a 2149 // reference of type A&, 2150 if (Context.hasSameUnqualifiedType(FromType1, FromType2) && 2151 !Context.hasSameUnqualifiedType(ToType1, ToType2)) { 2152 if (IsDerivedFrom(ToType1, ToType2)) 2153 return ImplicitConversionSequence::Better; 2154 else if (IsDerivedFrom(ToType2, ToType1)) 2155 return ImplicitConversionSequence::Worse; 2156 } 2157 2158 // -- conversion of B to A is better than conversion of C to A. 2159 // -- binding of an expression of type B to a reference of type 2160 // A& is better than binding an expression of type C to a 2161 // reference of type A&, 2162 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) && 2163 Context.hasSameUnqualifiedType(ToType1, ToType2)) { 2164 if (IsDerivedFrom(FromType2, FromType1)) 2165 return ImplicitConversionSequence::Better; 2166 else if (IsDerivedFrom(FromType1, FromType2)) 2167 return ImplicitConversionSequence::Worse; 2168 } 2169 } 2170 2171 return ImplicitConversionSequence::Indistinguishable; 2172} 2173 2174/// TryCopyInitialization - Try to copy-initialize a value of type 2175/// ToType from the expression From. Return the implicit conversion 2176/// sequence required to pass this argument, which may be a bad 2177/// conversion sequence (meaning that the argument cannot be passed to 2178/// a parameter of this type). If @p SuppressUserConversions, then we 2179/// do not permit any user-defined conversion sequences. If @p ForceRValue, 2180/// then we treat @p From as an rvalue, even if it is an lvalue. 2181ImplicitConversionSequence 2182Sema::TryCopyInitialization(Expr *From, QualType ToType, 2183 bool SuppressUserConversions, bool ForceRValue, 2184 bool InOverloadResolution) { 2185 if (ToType->isReferenceType()) { 2186 ImplicitConversionSequence ICS; 2187 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 2188 CheckReferenceInit(From, ToType, 2189 /*FIXME:*/From->getLocStart(), 2190 SuppressUserConversions, 2191 /*AllowExplicit=*/false, 2192 ForceRValue, 2193 &ICS); 2194 return ICS; 2195 } else { 2196 return TryImplicitConversion(From, ToType, 2197 SuppressUserConversions, 2198 /*AllowExplicit=*/false, 2199 ForceRValue, 2200 InOverloadResolution); 2201 } 2202} 2203 2204/// TryObjectArgumentInitialization - Try to initialize the object 2205/// parameter of the given member function (@c Method) from the 2206/// expression @p From. 2207ImplicitConversionSequence 2208Sema::TryObjectArgumentInitialization(QualType OrigFromType, 2209 CXXMethodDecl *Method, 2210 CXXRecordDecl *ActingContext) { 2211 QualType ClassType = Context.getTypeDeclType(ActingContext); 2212 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 2213 // const volatile object. 2214 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 2215 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 2216 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals); 2217 2218 // Set up the conversion sequence as a "bad" conversion, to allow us 2219 // to exit early. 2220 ImplicitConversionSequence ICS; 2221 2222 // We need to have an object of class type. 2223 QualType FromType = OrigFromType; 2224 if (const PointerType *PT = FromType->getAs<PointerType>()) 2225 FromType = PT->getPointeeType(); 2226 2227 assert(FromType->isRecordType()); 2228 2229 // The implicit object parameter is has the type "reference to cv X", 2230 // where X is the class of which the function is a member 2231 // (C++ [over.match.funcs]p4). However, when finding an implicit 2232 // conversion sequence for the argument, we are not allowed to 2233 // create temporaries or perform user-defined conversions 2234 // (C++ [over.match.funcs]p5). We perform a simplified version of 2235 // reference binding here, that allows class rvalues to bind to 2236 // non-constant references. 2237 2238 // First check the qualifiers. We don't care about lvalue-vs-rvalue 2239 // with the implicit object parameter (C++ [over.match.funcs]p5). 2240 QualType FromTypeCanon = Context.getCanonicalType(FromType); 2241 if (ImplicitParamType.getCVRQualifiers() 2242 != FromTypeCanon.getLocalCVRQualifiers() && 2243 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 2244 ICS.setBad(BadConversionSequence::bad_qualifiers, 2245 OrigFromType, ImplicitParamType); 2246 return ICS; 2247 } 2248 2249 // Check that we have either the same type or a derived type. It 2250 // affects the conversion rank. 2251 QualType ClassTypeCanon = Context.getCanonicalType(ClassType); 2252 ImplicitConversionKind SecondKind; 2253 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 2254 SecondKind = ICK_Identity; 2255 } else if (IsDerivedFrom(FromType, ClassType)) 2256 SecondKind = ICK_Derived_To_Base; 2257 else { 2258 ICS.setBad(BadConversionSequence::unrelated_class, 2259 FromType, ImplicitParamType); 2260 return ICS; 2261 } 2262 2263 // Success. Mark this as a reference binding. 2264 ICS.setStandard(); 2265 ICS.Standard.setAsIdentityConversion(); 2266 ICS.Standard.Second = SecondKind; 2267 ICS.Standard.setFromType(FromType); 2268 ICS.Standard.setAllToTypes(ImplicitParamType); 2269 ICS.Standard.ReferenceBinding = true; 2270 ICS.Standard.DirectBinding = true; 2271 ICS.Standard.RRefBinding = false; 2272 return ICS; 2273} 2274 2275/// PerformObjectArgumentInitialization - Perform initialization of 2276/// the implicit object parameter for the given Method with the given 2277/// expression. 2278bool 2279Sema::PerformObjectArgumentInitialization(Expr *&From, 2280 NestedNameSpecifier *Qualifier, 2281 CXXMethodDecl *Method) { 2282 QualType FromRecordType, DestType; 2283 QualType ImplicitParamRecordType = 2284 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 2285 2286 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 2287 FromRecordType = PT->getPointeeType(); 2288 DestType = Method->getThisType(Context); 2289 } else { 2290 FromRecordType = From->getType(); 2291 DestType = ImplicitParamRecordType; 2292 } 2293 2294 // Note that we always use the true parent context when performing 2295 // the actual argument initialization. 2296 ImplicitConversionSequence ICS 2297 = TryObjectArgumentInitialization(From->getType(), Method, 2298 Method->getParent()); 2299 if (ICS.isBad()) 2300 return Diag(From->getSourceRange().getBegin(), 2301 diag::err_implicit_object_parameter_init) 2302 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 2303 2304 if (ICS.Standard.Second == ICK_Derived_To_Base) 2305 return PerformObjectMemberConversion(From, Qualifier, Method); 2306 2307 if (!Context.hasSameType(From->getType(), DestType)) 2308 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp, 2309 /*isLvalue=*/!From->getType()->getAs<PointerType>()); 2310 return false; 2311} 2312 2313/// TryContextuallyConvertToBool - Attempt to contextually convert the 2314/// expression From to bool (C++0x [conv]p3). 2315ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) { 2316 return TryImplicitConversion(From, Context.BoolTy, 2317 // FIXME: Are these flags correct? 2318 /*SuppressUserConversions=*/false, 2319 /*AllowExplicit=*/true, 2320 /*ForceRValue=*/false, 2321 /*InOverloadResolution=*/false); 2322} 2323 2324/// PerformContextuallyConvertToBool - Perform a contextual conversion 2325/// of the expression From to bool (C++0x [conv]p3). 2326bool Sema::PerformContextuallyConvertToBool(Expr *&From) { 2327 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From); 2328 if (!ICS.isBad()) 2329 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 2330 2331 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 2332 return Diag(From->getSourceRange().getBegin(), 2333 diag::err_typecheck_bool_condition) 2334 << From->getType() << From->getSourceRange(); 2335 return true; 2336} 2337 2338/// AddOverloadCandidate - Adds the given function to the set of 2339/// candidate functions, using the given function call arguments. If 2340/// @p SuppressUserConversions, then don't allow user-defined 2341/// conversions via constructors or conversion operators. 2342/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly 2343/// hacky way to implement the overloading rules for elidable copy 2344/// initialization in C++0x (C++0x 12.8p15). 2345/// 2346/// \para PartialOverloading true if we are performing "partial" overloading 2347/// based on an incomplete set of function arguments. This feature is used by 2348/// code completion. 2349void 2350Sema::AddOverloadCandidate(FunctionDecl *Function, 2351 DeclAccessPair FoundDecl, 2352 Expr **Args, unsigned NumArgs, 2353 OverloadCandidateSet& CandidateSet, 2354 bool SuppressUserConversions, 2355 bool ForceRValue, 2356 bool PartialOverloading) { 2357 const FunctionProtoType* Proto 2358 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 2359 assert(Proto && "Functions without a prototype cannot be overloaded"); 2360 assert(!Function->getDescribedFunctionTemplate() && 2361 "Use AddTemplateOverloadCandidate for function templates"); 2362 2363 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 2364 if (!isa<CXXConstructorDecl>(Method)) { 2365 // If we get here, it's because we're calling a member function 2366 // that is named without a member access expression (e.g., 2367 // "this->f") that was either written explicitly or created 2368 // implicitly. This can happen with a qualified call to a member 2369 // function, e.g., X::f(). We use an empty type for the implied 2370 // object argument (C++ [over.call.func]p3), and the acting context 2371 // is irrelevant. 2372 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 2373 QualType(), Args, NumArgs, CandidateSet, 2374 SuppressUserConversions, ForceRValue); 2375 return; 2376 } 2377 // We treat a constructor like a non-member function, since its object 2378 // argument doesn't participate in overload resolution. 2379 } 2380 2381 if (!CandidateSet.isNewCandidate(Function)) 2382 return; 2383 2384 // Overload resolution is always an unevaluated context. 2385 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 2386 2387 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 2388 // C++ [class.copy]p3: 2389 // A member function template is never instantiated to perform the copy 2390 // of a class object to an object of its class type. 2391 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 2392 if (NumArgs == 1 && 2393 Constructor->isCopyConstructorLikeSpecialization() && 2394 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 2395 IsDerivedFrom(Args[0]->getType(), ClassType))) 2396 return; 2397 } 2398 2399 // Add this candidate 2400 CandidateSet.push_back(OverloadCandidate()); 2401 OverloadCandidate& Candidate = CandidateSet.back(); 2402 Candidate.FoundDecl = FoundDecl; 2403 Candidate.Function = Function; 2404 Candidate.Viable = true; 2405 Candidate.IsSurrogate = false; 2406 Candidate.IgnoreObjectArgument = false; 2407 2408 unsigned NumArgsInProto = Proto->getNumArgs(); 2409 2410 // (C++ 13.3.2p2): A candidate function having fewer than m 2411 // parameters is viable only if it has an ellipsis in its parameter 2412 // list (8.3.5). 2413 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto && 2414 !Proto->isVariadic()) { 2415 Candidate.Viable = false; 2416 Candidate.FailureKind = ovl_fail_too_many_arguments; 2417 return; 2418 } 2419 2420 // (C++ 13.3.2p2): A candidate function having more than m parameters 2421 // is viable only if the (m+1)st parameter has a default argument 2422 // (8.3.6). For the purposes of overload resolution, the 2423 // parameter list is truncated on the right, so that there are 2424 // exactly m parameters. 2425 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 2426 if (NumArgs < MinRequiredArgs && !PartialOverloading) { 2427 // Not enough arguments. 2428 Candidate.Viable = false; 2429 Candidate.FailureKind = ovl_fail_too_few_arguments; 2430 return; 2431 } 2432 2433 // Determine the implicit conversion sequences for each of the 2434 // arguments. 2435 Candidate.Conversions.resize(NumArgs); 2436 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2437 if (ArgIdx < NumArgsInProto) { 2438 // (C++ 13.3.2p3): for F to be a viable function, there shall 2439 // exist for each argument an implicit conversion sequence 2440 // (13.3.3.1) that converts that argument to the corresponding 2441 // parameter of F. 2442 QualType ParamType = Proto->getArgType(ArgIdx); 2443 Candidate.Conversions[ArgIdx] 2444 = TryCopyInitialization(Args[ArgIdx], ParamType, 2445 SuppressUserConversions, ForceRValue, 2446 /*InOverloadResolution=*/true); 2447 if (Candidate.Conversions[ArgIdx].isBad()) { 2448 Candidate.Viable = false; 2449 Candidate.FailureKind = ovl_fail_bad_conversion; 2450 break; 2451 } 2452 } else { 2453 // (C++ 13.3.2p2): For the purposes of overload resolution, any 2454 // argument for which there is no corresponding parameter is 2455 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 2456 Candidate.Conversions[ArgIdx].setEllipsis(); 2457 } 2458 } 2459} 2460 2461/// \brief Add all of the function declarations in the given function set to 2462/// the overload canddiate set. 2463void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 2464 Expr **Args, unsigned NumArgs, 2465 OverloadCandidateSet& CandidateSet, 2466 bool SuppressUserConversions) { 2467 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 2468 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 2469 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2470 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2471 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 2472 cast<CXXMethodDecl>(FD)->getParent(), 2473 Args[0]->getType(), Args + 1, NumArgs - 1, 2474 CandidateSet, SuppressUserConversions); 2475 else 2476 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet, 2477 SuppressUserConversions); 2478 } else { 2479 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 2480 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 2481 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 2482 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 2483 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 2484 /*FIXME: explicit args */ 0, 2485 Args[0]->getType(), Args + 1, NumArgs - 1, 2486 CandidateSet, 2487 SuppressUserConversions); 2488 else 2489 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 2490 /*FIXME: explicit args */ 0, 2491 Args, NumArgs, CandidateSet, 2492 SuppressUserConversions); 2493 } 2494 } 2495} 2496 2497/// AddMethodCandidate - Adds a named decl (which is some kind of 2498/// method) as a method candidate to the given overload set. 2499void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 2500 QualType ObjectType, 2501 Expr **Args, unsigned NumArgs, 2502 OverloadCandidateSet& CandidateSet, 2503 bool SuppressUserConversions, bool ForceRValue) { 2504 NamedDecl *Decl = FoundDecl.getDecl(); 2505 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 2506 2507 if (isa<UsingShadowDecl>(Decl)) 2508 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 2509 2510 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 2511 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 2512 "Expected a member function template"); 2513 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 2514 /*ExplicitArgs*/ 0, 2515 ObjectType, Args, NumArgs, 2516 CandidateSet, 2517 SuppressUserConversions, 2518 ForceRValue); 2519 } else { 2520 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 2521 ObjectType, Args, NumArgs, 2522 CandidateSet, SuppressUserConversions, ForceRValue); 2523 } 2524} 2525 2526/// AddMethodCandidate - Adds the given C++ member function to the set 2527/// of candidate functions, using the given function call arguments 2528/// and the object argument (@c Object). For example, in a call 2529/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 2530/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 2531/// allow user-defined conversions via constructors or conversion 2532/// operators. If @p ForceRValue, treat all arguments as rvalues. This is 2533/// a slightly hacky way to implement the overloading rules for elidable copy 2534/// initialization in C++0x (C++0x 12.8p15). 2535void 2536Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 2537 CXXRecordDecl *ActingContext, QualType ObjectType, 2538 Expr **Args, unsigned NumArgs, 2539 OverloadCandidateSet& CandidateSet, 2540 bool SuppressUserConversions, bool ForceRValue) { 2541 const FunctionProtoType* Proto 2542 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 2543 assert(Proto && "Methods without a prototype cannot be overloaded"); 2544 assert(!isa<CXXConstructorDecl>(Method) && 2545 "Use AddOverloadCandidate for constructors"); 2546 2547 if (!CandidateSet.isNewCandidate(Method)) 2548 return; 2549 2550 // Overload resolution is always an unevaluated context. 2551 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 2552 2553 // Add this candidate 2554 CandidateSet.push_back(OverloadCandidate()); 2555 OverloadCandidate& Candidate = CandidateSet.back(); 2556 Candidate.FoundDecl = FoundDecl; 2557 Candidate.Function = Method; 2558 Candidate.IsSurrogate = false; 2559 Candidate.IgnoreObjectArgument = false; 2560 2561 unsigned NumArgsInProto = Proto->getNumArgs(); 2562 2563 // (C++ 13.3.2p2): A candidate function having fewer than m 2564 // parameters is viable only if it has an ellipsis in its parameter 2565 // list (8.3.5). 2566 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 2567 Candidate.Viable = false; 2568 Candidate.FailureKind = ovl_fail_too_many_arguments; 2569 return; 2570 } 2571 2572 // (C++ 13.3.2p2): A candidate function having more than m parameters 2573 // is viable only if the (m+1)st parameter has a default argument 2574 // (8.3.6). For the purposes of overload resolution, the 2575 // parameter list is truncated on the right, so that there are 2576 // exactly m parameters. 2577 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 2578 if (NumArgs < MinRequiredArgs) { 2579 // Not enough arguments. 2580 Candidate.Viable = false; 2581 Candidate.FailureKind = ovl_fail_too_few_arguments; 2582 return; 2583 } 2584 2585 Candidate.Viable = true; 2586 Candidate.Conversions.resize(NumArgs + 1); 2587 2588 if (Method->isStatic() || ObjectType.isNull()) 2589 // The implicit object argument is ignored. 2590 Candidate.IgnoreObjectArgument = true; 2591 else { 2592 // Determine the implicit conversion sequence for the object 2593 // parameter. 2594 Candidate.Conversions[0] 2595 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext); 2596 if (Candidate.Conversions[0].isBad()) { 2597 Candidate.Viable = false; 2598 Candidate.FailureKind = ovl_fail_bad_conversion; 2599 return; 2600 } 2601 } 2602 2603 // Determine the implicit conversion sequences for each of the 2604 // arguments. 2605 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2606 if (ArgIdx < NumArgsInProto) { 2607 // (C++ 13.3.2p3): for F to be a viable function, there shall 2608 // exist for each argument an implicit conversion sequence 2609 // (13.3.3.1) that converts that argument to the corresponding 2610 // parameter of F. 2611 QualType ParamType = Proto->getArgType(ArgIdx); 2612 Candidate.Conversions[ArgIdx + 1] 2613 = TryCopyInitialization(Args[ArgIdx], ParamType, 2614 SuppressUserConversions, ForceRValue, 2615 /*InOverloadResolution=*/true); 2616 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 2617 Candidate.Viable = false; 2618 Candidate.FailureKind = ovl_fail_bad_conversion; 2619 break; 2620 } 2621 } else { 2622 // (C++ 13.3.2p2): For the purposes of overload resolution, any 2623 // argument for which there is no corresponding parameter is 2624 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 2625 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 2626 } 2627 } 2628} 2629 2630/// \brief Add a C++ member function template as a candidate to the candidate 2631/// set, using template argument deduction to produce an appropriate member 2632/// function template specialization. 2633void 2634Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 2635 DeclAccessPair FoundDecl, 2636 CXXRecordDecl *ActingContext, 2637 const TemplateArgumentListInfo *ExplicitTemplateArgs, 2638 QualType ObjectType, 2639 Expr **Args, unsigned NumArgs, 2640 OverloadCandidateSet& CandidateSet, 2641 bool SuppressUserConversions, 2642 bool ForceRValue) { 2643 if (!CandidateSet.isNewCandidate(MethodTmpl)) 2644 return; 2645 2646 // C++ [over.match.funcs]p7: 2647 // In each case where a candidate is a function template, candidate 2648 // function template specializations are generated using template argument 2649 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 2650 // candidate functions in the usual way.113) A given name can refer to one 2651 // or more function templates and also to a set of overloaded non-template 2652 // functions. In such a case, the candidate functions generated from each 2653 // function template are combined with the set of non-template candidate 2654 // functions. 2655 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 2656 FunctionDecl *Specialization = 0; 2657 if (TemplateDeductionResult Result 2658 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, 2659 Args, NumArgs, Specialization, Info)) { 2660 // FIXME: Record what happened with template argument deduction, so 2661 // that we can give the user a beautiful diagnostic. 2662 (void)Result; 2663 return; 2664 } 2665 2666 // Add the function template specialization produced by template argument 2667 // deduction as a candidate. 2668 assert(Specialization && "Missing member function template specialization?"); 2669 assert(isa<CXXMethodDecl>(Specialization) && 2670 "Specialization is not a member function?"); 2671 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 2672 ActingContext, ObjectType, Args, NumArgs, 2673 CandidateSet, SuppressUserConversions, ForceRValue); 2674} 2675 2676/// \brief Add a C++ function template specialization as a candidate 2677/// in the candidate set, using template argument deduction to produce 2678/// an appropriate function template specialization. 2679void 2680Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 2681 DeclAccessPair FoundDecl, 2682 const TemplateArgumentListInfo *ExplicitTemplateArgs, 2683 Expr **Args, unsigned NumArgs, 2684 OverloadCandidateSet& CandidateSet, 2685 bool SuppressUserConversions, 2686 bool ForceRValue) { 2687 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 2688 return; 2689 2690 // C++ [over.match.funcs]p7: 2691 // In each case where a candidate is a function template, candidate 2692 // function template specializations are generated using template argument 2693 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 2694 // candidate functions in the usual way.113) A given name can refer to one 2695 // or more function templates and also to a set of overloaded non-template 2696 // functions. In such a case, the candidate functions generated from each 2697 // function template are combined with the set of non-template candidate 2698 // functions. 2699 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 2700 FunctionDecl *Specialization = 0; 2701 if (TemplateDeductionResult Result 2702 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 2703 Args, NumArgs, Specialization, Info)) { 2704 CandidateSet.push_back(OverloadCandidate()); 2705 OverloadCandidate &Candidate = CandidateSet.back(); 2706 Candidate.FoundDecl = FoundDecl; 2707 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 2708 Candidate.Viable = false; 2709 Candidate.FailureKind = ovl_fail_bad_deduction; 2710 Candidate.IsSurrogate = false; 2711 Candidate.IgnoreObjectArgument = false; 2712 2713 // TODO: record more information about failed template arguments 2714 Candidate.DeductionFailure.Result = Result; 2715 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue(); 2716 return; 2717 } 2718 2719 // Add the function template specialization produced by template argument 2720 // deduction as a candidate. 2721 assert(Specialization && "Missing function template specialization?"); 2722 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet, 2723 SuppressUserConversions, ForceRValue); 2724} 2725 2726/// AddConversionCandidate - Add a C++ conversion function as a 2727/// candidate in the candidate set (C++ [over.match.conv], 2728/// C++ [over.match.copy]). From is the expression we're converting from, 2729/// and ToType is the type that we're eventually trying to convert to 2730/// (which may or may not be the same type as the type that the 2731/// conversion function produces). 2732void 2733Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 2734 DeclAccessPair FoundDecl, 2735 CXXRecordDecl *ActingContext, 2736 Expr *From, QualType ToType, 2737 OverloadCandidateSet& CandidateSet) { 2738 assert(!Conversion->getDescribedFunctionTemplate() && 2739 "Conversion function templates use AddTemplateConversionCandidate"); 2740 2741 if (!CandidateSet.isNewCandidate(Conversion)) 2742 return; 2743 2744 // Overload resolution is always an unevaluated context. 2745 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 2746 2747 // Add this candidate 2748 CandidateSet.push_back(OverloadCandidate()); 2749 OverloadCandidate& Candidate = CandidateSet.back(); 2750 Candidate.FoundDecl = FoundDecl; 2751 Candidate.Function = Conversion; 2752 Candidate.IsSurrogate = false; 2753 Candidate.IgnoreObjectArgument = false; 2754 Candidate.FinalConversion.setAsIdentityConversion(); 2755 Candidate.FinalConversion.setFromType(Conversion->getConversionType()); 2756 Candidate.FinalConversion.setAllToTypes(ToType); 2757 2758 // Determine the implicit conversion sequence for the implicit 2759 // object parameter. 2760 Candidate.Viable = true; 2761 Candidate.Conversions.resize(1); 2762 Candidate.Conversions[0] 2763 = TryObjectArgumentInitialization(From->getType(), Conversion, 2764 ActingContext); 2765 // Conversion functions to a different type in the base class is visible in 2766 // the derived class. So, a derived to base conversion should not participate 2767 // in overload resolution. 2768 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base) 2769 Candidate.Conversions[0].Standard.Second = ICK_Identity; 2770 if (Candidate.Conversions[0].isBad()) { 2771 Candidate.Viable = false; 2772 Candidate.FailureKind = ovl_fail_bad_conversion; 2773 return; 2774 } 2775 2776 // We won't go through a user-define type conversion function to convert a 2777 // derived to base as such conversions are given Conversion Rank. They only 2778 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 2779 QualType FromCanon 2780 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 2781 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 2782 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 2783 Candidate.Viable = false; 2784 Candidate.FailureKind = ovl_fail_trivial_conversion; 2785 return; 2786 } 2787 2788 2789 // To determine what the conversion from the result of calling the 2790 // conversion function to the type we're eventually trying to 2791 // convert to (ToType), we need to synthesize a call to the 2792 // conversion function and attempt copy initialization from it. This 2793 // makes sure that we get the right semantics with respect to 2794 // lvalues/rvalues and the type. Fortunately, we can allocate this 2795 // call on the stack and we don't need its arguments to be 2796 // well-formed. 2797 DeclRefExpr ConversionRef(Conversion, Conversion->getType(), 2798 From->getLocStart()); 2799 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()), 2800 CastExpr::CK_FunctionToPointerDecay, 2801 &ConversionRef, false); 2802 2803 // Note that it is safe to allocate CallExpr on the stack here because 2804 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 2805 // allocator). 2806 CallExpr Call(Context, &ConversionFn, 0, 0, 2807 Conversion->getConversionType().getNonReferenceType(), 2808 From->getLocStart()); 2809 ImplicitConversionSequence ICS = 2810 TryCopyInitialization(&Call, ToType, 2811 /*SuppressUserConversions=*/true, 2812 /*ForceRValue=*/false, 2813 /*InOverloadResolution=*/false); 2814 2815 switch (ICS.getKind()) { 2816 case ImplicitConversionSequence::StandardConversion: 2817 Candidate.FinalConversion = ICS.Standard; 2818 break; 2819 2820 case ImplicitConversionSequence::BadConversion: 2821 Candidate.Viable = false; 2822 Candidate.FailureKind = ovl_fail_bad_final_conversion; 2823 break; 2824 2825 default: 2826 assert(false && 2827 "Can only end up with a standard conversion sequence or failure"); 2828 } 2829} 2830 2831/// \brief Adds a conversion function template specialization 2832/// candidate to the overload set, using template argument deduction 2833/// to deduce the template arguments of the conversion function 2834/// template from the type that we are converting to (C++ 2835/// [temp.deduct.conv]). 2836void 2837Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 2838 DeclAccessPair FoundDecl, 2839 CXXRecordDecl *ActingDC, 2840 Expr *From, QualType ToType, 2841 OverloadCandidateSet &CandidateSet) { 2842 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 2843 "Only conversion function templates permitted here"); 2844 2845 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 2846 return; 2847 2848 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 2849 CXXConversionDecl *Specialization = 0; 2850 if (TemplateDeductionResult Result 2851 = DeduceTemplateArguments(FunctionTemplate, ToType, 2852 Specialization, Info)) { 2853 // FIXME: Record what happened with template argument deduction, so 2854 // that we can give the user a beautiful diagnostic. 2855 (void)Result; 2856 return; 2857 } 2858 2859 // Add the conversion function template specialization produced by 2860 // template argument deduction as a candidate. 2861 assert(Specialization && "Missing function template specialization?"); 2862 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 2863 CandidateSet); 2864} 2865 2866/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 2867/// converts the given @c Object to a function pointer via the 2868/// conversion function @c Conversion, and then attempts to call it 2869/// with the given arguments (C++ [over.call.object]p2-4). Proto is 2870/// the type of function that we'll eventually be calling. 2871void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 2872 DeclAccessPair FoundDecl, 2873 CXXRecordDecl *ActingContext, 2874 const FunctionProtoType *Proto, 2875 QualType ObjectType, 2876 Expr **Args, unsigned NumArgs, 2877 OverloadCandidateSet& CandidateSet) { 2878 if (!CandidateSet.isNewCandidate(Conversion)) 2879 return; 2880 2881 // Overload resolution is always an unevaluated context. 2882 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 2883 2884 CandidateSet.push_back(OverloadCandidate()); 2885 OverloadCandidate& Candidate = CandidateSet.back(); 2886 Candidate.FoundDecl = FoundDecl; 2887 Candidate.Function = 0; 2888 Candidate.Surrogate = Conversion; 2889 Candidate.Viable = true; 2890 Candidate.IsSurrogate = true; 2891 Candidate.IgnoreObjectArgument = false; 2892 Candidate.Conversions.resize(NumArgs + 1); 2893 2894 // Determine the implicit conversion sequence for the implicit 2895 // object parameter. 2896 ImplicitConversionSequence ObjectInit 2897 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext); 2898 if (ObjectInit.isBad()) { 2899 Candidate.Viable = false; 2900 Candidate.FailureKind = ovl_fail_bad_conversion; 2901 Candidate.Conversions[0] = ObjectInit; 2902 return; 2903 } 2904 2905 // The first conversion is actually a user-defined conversion whose 2906 // first conversion is ObjectInit's standard conversion (which is 2907 // effectively a reference binding). Record it as such. 2908 Candidate.Conversions[0].setUserDefined(); 2909 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 2910 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 2911 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 2912 Candidate.Conversions[0].UserDefined.After 2913 = Candidate.Conversions[0].UserDefined.Before; 2914 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 2915 2916 // Find the 2917 unsigned NumArgsInProto = Proto->getNumArgs(); 2918 2919 // (C++ 13.3.2p2): A candidate function having fewer than m 2920 // parameters is viable only if it has an ellipsis in its parameter 2921 // list (8.3.5). 2922 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 2923 Candidate.Viable = false; 2924 Candidate.FailureKind = ovl_fail_too_many_arguments; 2925 return; 2926 } 2927 2928 // Function types don't have any default arguments, so just check if 2929 // we have enough arguments. 2930 if (NumArgs < NumArgsInProto) { 2931 // Not enough arguments. 2932 Candidate.Viable = false; 2933 Candidate.FailureKind = ovl_fail_too_few_arguments; 2934 return; 2935 } 2936 2937 // Determine the implicit conversion sequences for each of the 2938 // arguments. 2939 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2940 if (ArgIdx < NumArgsInProto) { 2941 // (C++ 13.3.2p3): for F to be a viable function, there shall 2942 // exist for each argument an implicit conversion sequence 2943 // (13.3.3.1) that converts that argument to the corresponding 2944 // parameter of F. 2945 QualType ParamType = Proto->getArgType(ArgIdx); 2946 Candidate.Conversions[ArgIdx + 1] 2947 = TryCopyInitialization(Args[ArgIdx], ParamType, 2948 /*SuppressUserConversions=*/false, 2949 /*ForceRValue=*/false, 2950 /*InOverloadResolution=*/false); 2951 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 2952 Candidate.Viable = false; 2953 Candidate.FailureKind = ovl_fail_bad_conversion; 2954 break; 2955 } 2956 } else { 2957 // (C++ 13.3.2p2): For the purposes of overload resolution, any 2958 // argument for which there is no corresponding parameter is 2959 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 2960 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 2961 } 2962 } 2963} 2964 2965// FIXME: This will eventually be removed, once we've migrated all of the 2966// operator overloading logic over to the scheme used by binary operators, which 2967// works for template instantiation. 2968void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S, 2969 SourceLocation OpLoc, 2970 Expr **Args, unsigned NumArgs, 2971 OverloadCandidateSet& CandidateSet, 2972 SourceRange OpRange) { 2973 UnresolvedSet<16> Fns; 2974 2975 QualType T1 = Args[0]->getType(); 2976 QualType T2; 2977 if (NumArgs > 1) 2978 T2 = Args[1]->getType(); 2979 2980 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 2981 if (S) 2982 LookupOverloadedOperatorName(Op, S, T1, T2, Fns); 2983 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false); 2984 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0, 2985 CandidateSet); 2986 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange); 2987 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet); 2988} 2989 2990/// \brief Add overload candidates for overloaded operators that are 2991/// member functions. 2992/// 2993/// Add the overloaded operator candidates that are member functions 2994/// for the operator Op that was used in an operator expression such 2995/// as "x Op y". , Args/NumArgs provides the operator arguments, and 2996/// CandidateSet will store the added overload candidates. (C++ 2997/// [over.match.oper]). 2998void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 2999 SourceLocation OpLoc, 3000 Expr **Args, unsigned NumArgs, 3001 OverloadCandidateSet& CandidateSet, 3002 SourceRange OpRange) { 3003 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 3004 3005 // C++ [over.match.oper]p3: 3006 // For a unary operator @ with an operand of a type whose 3007 // cv-unqualified version is T1, and for a binary operator @ with 3008 // a left operand of a type whose cv-unqualified version is T1 and 3009 // a right operand of a type whose cv-unqualified version is T2, 3010 // three sets of candidate functions, designated member 3011 // candidates, non-member candidates and built-in candidates, are 3012 // constructed as follows: 3013 QualType T1 = Args[0]->getType(); 3014 QualType T2; 3015 if (NumArgs > 1) 3016 T2 = Args[1]->getType(); 3017 3018 // -- If T1 is a class type, the set of member candidates is the 3019 // result of the qualified lookup of T1::operator@ 3020 // (13.3.1.1.1); otherwise, the set of member candidates is 3021 // empty. 3022 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 3023 // Complete the type if it can be completed. Otherwise, we're done. 3024 if (RequireCompleteType(OpLoc, T1, PDiag())) 3025 return; 3026 3027 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 3028 LookupQualifiedName(Operators, T1Rec->getDecl()); 3029 Operators.suppressDiagnostics(); 3030 3031 for (LookupResult::iterator Oper = Operators.begin(), 3032 OperEnd = Operators.end(); 3033 Oper != OperEnd; 3034 ++Oper) 3035 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 3036 Args + 1, NumArgs - 1, CandidateSet, 3037 /* SuppressUserConversions = */ false); 3038 } 3039} 3040 3041/// AddBuiltinCandidate - Add a candidate for a built-in 3042/// operator. ResultTy and ParamTys are the result and parameter types 3043/// of the built-in candidate, respectively. Args and NumArgs are the 3044/// arguments being passed to the candidate. IsAssignmentOperator 3045/// should be true when this built-in candidate is an assignment 3046/// operator. NumContextualBoolArguments is the number of arguments 3047/// (at the beginning of the argument list) that will be contextually 3048/// converted to bool. 3049void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 3050 Expr **Args, unsigned NumArgs, 3051 OverloadCandidateSet& CandidateSet, 3052 bool IsAssignmentOperator, 3053 unsigned NumContextualBoolArguments) { 3054 // Overload resolution is always an unevaluated context. 3055 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 3056 3057 // Add this candidate 3058 CandidateSet.push_back(OverloadCandidate()); 3059 OverloadCandidate& Candidate = CandidateSet.back(); 3060 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 3061 Candidate.Function = 0; 3062 Candidate.IsSurrogate = false; 3063 Candidate.IgnoreObjectArgument = false; 3064 Candidate.BuiltinTypes.ResultTy = ResultTy; 3065 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 3066 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 3067 3068 // Determine the implicit conversion sequences for each of the 3069 // arguments. 3070 Candidate.Viable = true; 3071 Candidate.Conversions.resize(NumArgs); 3072 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 3073 // C++ [over.match.oper]p4: 3074 // For the built-in assignment operators, conversions of the 3075 // left operand are restricted as follows: 3076 // -- no temporaries are introduced to hold the left operand, and 3077 // -- no user-defined conversions are applied to the left 3078 // operand to achieve a type match with the left-most 3079 // parameter of a built-in candidate. 3080 // 3081 // We block these conversions by turning off user-defined 3082 // conversions, since that is the only way that initialization of 3083 // a reference to a non-class type can occur from something that 3084 // is not of the same type. 3085 if (ArgIdx < NumContextualBoolArguments) { 3086 assert(ParamTys[ArgIdx] == Context.BoolTy && 3087 "Contextual conversion to bool requires bool type"); 3088 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]); 3089 } else { 3090 Candidate.Conversions[ArgIdx] 3091 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], 3092 ArgIdx == 0 && IsAssignmentOperator, 3093 /*ForceRValue=*/false, 3094 /*InOverloadResolution=*/false); 3095 } 3096 if (Candidate.Conversions[ArgIdx].isBad()) { 3097 Candidate.Viable = false; 3098 Candidate.FailureKind = ovl_fail_bad_conversion; 3099 break; 3100 } 3101 } 3102} 3103 3104/// BuiltinCandidateTypeSet - A set of types that will be used for the 3105/// candidate operator functions for built-in operators (C++ 3106/// [over.built]). The types are separated into pointer types and 3107/// enumeration types. 3108class BuiltinCandidateTypeSet { 3109 /// TypeSet - A set of types. 3110 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 3111 3112 /// PointerTypes - The set of pointer types that will be used in the 3113 /// built-in candidates. 3114 TypeSet PointerTypes; 3115 3116 /// MemberPointerTypes - The set of member pointer types that will be 3117 /// used in the built-in candidates. 3118 TypeSet MemberPointerTypes; 3119 3120 /// EnumerationTypes - The set of enumeration types that will be 3121 /// used in the built-in candidates. 3122 TypeSet EnumerationTypes; 3123 3124 /// Sema - The semantic analysis instance where we are building the 3125 /// candidate type set. 3126 Sema &SemaRef; 3127 3128 /// Context - The AST context in which we will build the type sets. 3129 ASTContext &Context; 3130 3131 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 3132 const Qualifiers &VisibleQuals); 3133 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 3134 3135public: 3136 /// iterator - Iterates through the types that are part of the set. 3137 typedef TypeSet::iterator iterator; 3138 3139 BuiltinCandidateTypeSet(Sema &SemaRef) 3140 : SemaRef(SemaRef), Context(SemaRef.Context) { } 3141 3142 void AddTypesConvertedFrom(QualType Ty, 3143 SourceLocation Loc, 3144 bool AllowUserConversions, 3145 bool AllowExplicitConversions, 3146 const Qualifiers &VisibleTypeConversionsQuals); 3147 3148 /// pointer_begin - First pointer type found; 3149 iterator pointer_begin() { return PointerTypes.begin(); } 3150 3151 /// pointer_end - Past the last pointer type found; 3152 iterator pointer_end() { return PointerTypes.end(); } 3153 3154 /// member_pointer_begin - First member pointer type found; 3155 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 3156 3157 /// member_pointer_end - Past the last member pointer type found; 3158 iterator member_pointer_end() { return MemberPointerTypes.end(); } 3159 3160 /// enumeration_begin - First enumeration type found; 3161 iterator enumeration_begin() { return EnumerationTypes.begin(); } 3162 3163 /// enumeration_end - Past the last enumeration type found; 3164 iterator enumeration_end() { return EnumerationTypes.end(); } 3165}; 3166 3167/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 3168/// the set of pointer types along with any more-qualified variants of 3169/// that type. For example, if @p Ty is "int const *", this routine 3170/// will add "int const *", "int const volatile *", "int const 3171/// restrict *", and "int const volatile restrict *" to the set of 3172/// pointer types. Returns true if the add of @p Ty itself succeeded, 3173/// false otherwise. 3174/// 3175/// FIXME: what to do about extended qualifiers? 3176bool 3177BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 3178 const Qualifiers &VisibleQuals) { 3179 3180 // Insert this type. 3181 if (!PointerTypes.insert(Ty)) 3182 return false; 3183 3184 const PointerType *PointerTy = Ty->getAs<PointerType>(); 3185 assert(PointerTy && "type was not a pointer type!"); 3186 3187 QualType PointeeTy = PointerTy->getPointeeType(); 3188 // Don't add qualified variants of arrays. For one, they're not allowed 3189 // (the qualifier would sink to the element type), and for another, the 3190 // only overload situation where it matters is subscript or pointer +- int, 3191 // and those shouldn't have qualifier variants anyway. 3192 if (PointeeTy->isArrayType()) 3193 return true; 3194 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 3195 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy)) 3196 BaseCVR = Array->getElementType().getCVRQualifiers(); 3197 bool hasVolatile = VisibleQuals.hasVolatile(); 3198 bool hasRestrict = VisibleQuals.hasRestrict(); 3199 3200 // Iterate through all strict supersets of BaseCVR. 3201 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 3202 if ((CVR | BaseCVR) != CVR) continue; 3203 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere 3204 // in the types. 3205 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 3206 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue; 3207 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 3208 PointerTypes.insert(Context.getPointerType(QPointeeTy)); 3209 } 3210 3211 return true; 3212} 3213 3214/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 3215/// to the set of pointer types along with any more-qualified variants of 3216/// that type. For example, if @p Ty is "int const *", this routine 3217/// will add "int const *", "int const volatile *", "int const 3218/// restrict *", and "int const volatile restrict *" to the set of 3219/// pointer types. Returns true if the add of @p Ty itself succeeded, 3220/// false otherwise. 3221/// 3222/// FIXME: what to do about extended qualifiers? 3223bool 3224BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 3225 QualType Ty) { 3226 // Insert this type. 3227 if (!MemberPointerTypes.insert(Ty)) 3228 return false; 3229 3230 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 3231 assert(PointerTy && "type was not a member pointer type!"); 3232 3233 QualType PointeeTy = PointerTy->getPointeeType(); 3234 // Don't add qualified variants of arrays. For one, they're not allowed 3235 // (the qualifier would sink to the element type), and for another, the 3236 // only overload situation where it matters is subscript or pointer +- int, 3237 // and those shouldn't have qualifier variants anyway. 3238 if (PointeeTy->isArrayType()) 3239 return true; 3240 const Type *ClassTy = PointerTy->getClass(); 3241 3242 // Iterate through all strict supersets of the pointee type's CVR 3243 // qualifiers. 3244 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 3245 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 3246 if ((CVR | BaseCVR) != CVR) continue; 3247 3248 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 3249 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy)); 3250 } 3251 3252 return true; 3253} 3254 3255/// AddTypesConvertedFrom - Add each of the types to which the type @p 3256/// Ty can be implicit converted to the given set of @p Types. We're 3257/// primarily interested in pointer types and enumeration types. We also 3258/// take member pointer types, for the conditional operator. 3259/// AllowUserConversions is true if we should look at the conversion 3260/// functions of a class type, and AllowExplicitConversions if we 3261/// should also include the explicit conversion functions of a class 3262/// type. 3263void 3264BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 3265 SourceLocation Loc, 3266 bool AllowUserConversions, 3267 bool AllowExplicitConversions, 3268 const Qualifiers &VisibleQuals) { 3269 // Only deal with canonical types. 3270 Ty = Context.getCanonicalType(Ty); 3271 3272 // Look through reference types; they aren't part of the type of an 3273 // expression for the purposes of conversions. 3274 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 3275 Ty = RefTy->getPointeeType(); 3276 3277 // We don't care about qualifiers on the type. 3278 Ty = Ty.getLocalUnqualifiedType(); 3279 3280 // If we're dealing with an array type, decay to the pointer. 3281 if (Ty->isArrayType()) 3282 Ty = SemaRef.Context.getArrayDecayedType(Ty); 3283 3284 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) { 3285 QualType PointeeTy = PointerTy->getPointeeType(); 3286 3287 // Insert our type, and its more-qualified variants, into the set 3288 // of types. 3289 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 3290 return; 3291 } else if (Ty->isMemberPointerType()) { 3292 // Member pointers are far easier, since the pointee can't be converted. 3293 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 3294 return; 3295 } else if (Ty->isEnumeralType()) { 3296 EnumerationTypes.insert(Ty); 3297 } else if (AllowUserConversions) { 3298 if (const RecordType *TyRec = Ty->getAs<RecordType>()) { 3299 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) { 3300 // No conversion functions in incomplete types. 3301 return; 3302 } 3303 3304 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 3305 const UnresolvedSetImpl *Conversions 3306 = ClassDecl->getVisibleConversionFunctions(); 3307 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3308 E = Conversions->end(); I != E; ++I) { 3309 3310 // Skip conversion function templates; they don't tell us anything 3311 // about which builtin types we can convert to. 3312 if (isa<FunctionTemplateDecl>(*I)) 3313 continue; 3314 3315 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I); 3316 if (AllowExplicitConversions || !Conv->isExplicit()) { 3317 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 3318 VisibleQuals); 3319 } 3320 } 3321 } 3322 } 3323} 3324 3325/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 3326/// the volatile- and non-volatile-qualified assignment operators for the 3327/// given type to the candidate set. 3328static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 3329 QualType T, 3330 Expr **Args, 3331 unsigned NumArgs, 3332 OverloadCandidateSet &CandidateSet) { 3333 QualType ParamTypes[2]; 3334 3335 // T& operator=(T&, T) 3336 ParamTypes[0] = S.Context.getLValueReferenceType(T); 3337 ParamTypes[1] = T; 3338 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3339 /*IsAssignmentOperator=*/true); 3340 3341 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 3342 // volatile T& operator=(volatile T&, T) 3343 ParamTypes[0] 3344 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 3345 ParamTypes[1] = T; 3346 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3347 /*IsAssignmentOperator=*/true); 3348 } 3349} 3350 3351/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 3352/// if any, found in visible type conversion functions found in ArgExpr's type. 3353static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 3354 Qualifiers VRQuals; 3355 const RecordType *TyRec; 3356 if (const MemberPointerType *RHSMPType = 3357 ArgExpr->getType()->getAs<MemberPointerType>()) 3358 TyRec = cast<RecordType>(RHSMPType->getClass()); 3359 else 3360 TyRec = ArgExpr->getType()->getAs<RecordType>(); 3361 if (!TyRec) { 3362 // Just to be safe, assume the worst case. 3363 VRQuals.addVolatile(); 3364 VRQuals.addRestrict(); 3365 return VRQuals; 3366 } 3367 3368 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 3369 if (!ClassDecl->hasDefinition()) 3370 return VRQuals; 3371 3372 const UnresolvedSetImpl *Conversions = 3373 ClassDecl->getVisibleConversionFunctions(); 3374 3375 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3376 E = Conversions->end(); I != E; ++I) { 3377 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) { 3378 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 3379 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 3380 CanTy = ResTypeRef->getPointeeType(); 3381 // Need to go down the pointer/mempointer chain and add qualifiers 3382 // as see them. 3383 bool done = false; 3384 while (!done) { 3385 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 3386 CanTy = ResTypePtr->getPointeeType(); 3387 else if (const MemberPointerType *ResTypeMPtr = 3388 CanTy->getAs<MemberPointerType>()) 3389 CanTy = ResTypeMPtr->getPointeeType(); 3390 else 3391 done = true; 3392 if (CanTy.isVolatileQualified()) 3393 VRQuals.addVolatile(); 3394 if (CanTy.isRestrictQualified()) 3395 VRQuals.addRestrict(); 3396 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 3397 return VRQuals; 3398 } 3399 } 3400 } 3401 return VRQuals; 3402} 3403 3404/// AddBuiltinOperatorCandidates - Add the appropriate built-in 3405/// operator overloads to the candidate set (C++ [over.built]), based 3406/// on the operator @p Op and the arguments given. For example, if the 3407/// operator is a binary '+', this routine might add "int 3408/// operator+(int, int)" to cover integer addition. 3409void 3410Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 3411 SourceLocation OpLoc, 3412 Expr **Args, unsigned NumArgs, 3413 OverloadCandidateSet& CandidateSet) { 3414 // The set of "promoted arithmetic types", which are the arithmetic 3415 // types are that preserved by promotion (C++ [over.built]p2). Note 3416 // that the first few of these types are the promoted integral 3417 // types; these types need to be first. 3418 // FIXME: What about complex? 3419 const unsigned FirstIntegralType = 0; 3420 const unsigned LastIntegralType = 13; 3421 const unsigned FirstPromotedIntegralType = 7, 3422 LastPromotedIntegralType = 13; 3423 const unsigned FirstPromotedArithmeticType = 7, 3424 LastPromotedArithmeticType = 16; 3425 const unsigned NumArithmeticTypes = 16; 3426 QualType ArithmeticTypes[NumArithmeticTypes] = { 3427 Context.BoolTy, Context.CharTy, Context.WCharTy, 3428// FIXME: Context.Char16Ty, Context.Char32Ty, 3429 Context.SignedCharTy, Context.ShortTy, 3430 Context.UnsignedCharTy, Context.UnsignedShortTy, 3431 Context.IntTy, Context.LongTy, Context.LongLongTy, 3432 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy, 3433 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy 3434 }; 3435 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy && 3436 "Invalid first promoted integral type"); 3437 assert(ArithmeticTypes[LastPromotedIntegralType - 1] 3438 == Context.UnsignedLongLongTy && 3439 "Invalid last promoted integral type"); 3440 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy && 3441 "Invalid first promoted arithmetic type"); 3442 assert(ArithmeticTypes[LastPromotedArithmeticType - 1] 3443 == Context.LongDoubleTy && 3444 "Invalid last promoted arithmetic type"); 3445 3446 // Find all of the types that the arguments can convert to, but only 3447 // if the operator we're looking at has built-in operator candidates 3448 // that make use of these types. 3449 Qualifiers VisibleTypeConversionsQuals; 3450 VisibleTypeConversionsQuals.addConst(); 3451 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 3452 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 3453 3454 BuiltinCandidateTypeSet CandidateTypes(*this); 3455 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual || 3456 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual || 3457 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal || 3458 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript || 3459 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus || 3460 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) { 3461 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 3462 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(), 3463 OpLoc, 3464 true, 3465 (Op == OO_Exclaim || 3466 Op == OO_AmpAmp || 3467 Op == OO_PipePipe), 3468 VisibleTypeConversionsQuals); 3469 } 3470 3471 bool isComparison = false; 3472 switch (Op) { 3473 case OO_None: 3474 case NUM_OVERLOADED_OPERATORS: 3475 assert(false && "Expected an overloaded operator"); 3476 break; 3477 3478 case OO_Star: // '*' is either unary or binary 3479 if (NumArgs == 1) 3480 goto UnaryStar; 3481 else 3482 goto BinaryStar; 3483 break; 3484 3485 case OO_Plus: // '+' is either unary or binary 3486 if (NumArgs == 1) 3487 goto UnaryPlus; 3488 else 3489 goto BinaryPlus; 3490 break; 3491 3492 case OO_Minus: // '-' is either unary or binary 3493 if (NumArgs == 1) 3494 goto UnaryMinus; 3495 else 3496 goto BinaryMinus; 3497 break; 3498 3499 case OO_Amp: // '&' is either unary or binary 3500 if (NumArgs == 1) 3501 goto UnaryAmp; 3502 else 3503 goto BinaryAmp; 3504 3505 case OO_PlusPlus: 3506 case OO_MinusMinus: 3507 // C++ [over.built]p3: 3508 // 3509 // For every pair (T, VQ), where T is an arithmetic type, and VQ 3510 // is either volatile or empty, there exist candidate operator 3511 // functions of the form 3512 // 3513 // VQ T& operator++(VQ T&); 3514 // T operator++(VQ T&, int); 3515 // 3516 // C++ [over.built]p4: 3517 // 3518 // For every pair (T, VQ), where T is an arithmetic type other 3519 // than bool, and VQ is either volatile or empty, there exist 3520 // candidate operator functions of the form 3521 // 3522 // VQ T& operator--(VQ T&); 3523 // T operator--(VQ T&, int); 3524 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 3525 Arith < NumArithmeticTypes; ++Arith) { 3526 QualType ArithTy = ArithmeticTypes[Arith]; 3527 QualType ParamTypes[2] 3528 = { Context.getLValueReferenceType(ArithTy), Context.IntTy }; 3529 3530 // Non-volatile version. 3531 if (NumArgs == 1) 3532 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 3533 else 3534 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 3535 // heuristic to reduce number of builtin candidates in the set. 3536 // Add volatile version only if there are conversions to a volatile type. 3537 if (VisibleTypeConversionsQuals.hasVolatile()) { 3538 // Volatile version 3539 ParamTypes[0] 3540 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy)); 3541 if (NumArgs == 1) 3542 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 3543 else 3544 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 3545 } 3546 } 3547 3548 // C++ [over.built]p5: 3549 // 3550 // For every pair (T, VQ), where T is a cv-qualified or 3551 // cv-unqualified object type, and VQ is either volatile or 3552 // empty, there exist candidate operator functions of the form 3553 // 3554 // T*VQ& operator++(T*VQ&); 3555 // T*VQ& operator--(T*VQ&); 3556 // T* operator++(T*VQ&, int); 3557 // T* operator--(T*VQ&, int); 3558 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 3559 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3560 // Skip pointer types that aren't pointers to object types. 3561 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType()) 3562 continue; 3563 3564 QualType ParamTypes[2] = { 3565 Context.getLValueReferenceType(*Ptr), Context.IntTy 3566 }; 3567 3568 // Without volatile 3569 if (NumArgs == 1) 3570 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 3571 else 3572 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 3573 3574 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() && 3575 VisibleTypeConversionsQuals.hasVolatile()) { 3576 // With volatile 3577 ParamTypes[0] 3578 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr)); 3579 if (NumArgs == 1) 3580 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 3581 else 3582 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 3583 } 3584 } 3585 break; 3586 3587 UnaryStar: 3588 // C++ [over.built]p6: 3589 // For every cv-qualified or cv-unqualified object type T, there 3590 // exist candidate operator functions of the form 3591 // 3592 // T& operator*(T*); 3593 // 3594 // C++ [over.built]p7: 3595 // For every function type T, there exist candidate operator 3596 // functions of the form 3597 // T& operator*(T*); 3598 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 3599 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3600 QualType ParamTy = *Ptr; 3601 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType(); 3602 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy), 3603 &ParamTy, Args, 1, CandidateSet); 3604 } 3605 break; 3606 3607 UnaryPlus: 3608 // C++ [over.built]p8: 3609 // For every type T, there exist candidate operator functions of 3610 // the form 3611 // 3612 // T* operator+(T*); 3613 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 3614 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3615 QualType ParamTy = *Ptr; 3616 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 3617 } 3618 3619 // Fall through 3620 3621 UnaryMinus: 3622 // C++ [over.built]p9: 3623 // For every promoted arithmetic type T, there exist candidate 3624 // operator functions of the form 3625 // 3626 // T operator+(T); 3627 // T operator-(T); 3628 for (unsigned Arith = FirstPromotedArithmeticType; 3629 Arith < LastPromotedArithmeticType; ++Arith) { 3630 QualType ArithTy = ArithmeticTypes[Arith]; 3631 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 3632 } 3633 break; 3634 3635 case OO_Tilde: 3636 // C++ [over.built]p10: 3637 // For every promoted integral type T, there exist candidate 3638 // operator functions of the form 3639 // 3640 // T operator~(T); 3641 for (unsigned Int = FirstPromotedIntegralType; 3642 Int < LastPromotedIntegralType; ++Int) { 3643 QualType IntTy = ArithmeticTypes[Int]; 3644 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 3645 } 3646 break; 3647 3648 case OO_New: 3649 case OO_Delete: 3650 case OO_Array_New: 3651 case OO_Array_Delete: 3652 case OO_Call: 3653 assert(false && "Special operators don't use AddBuiltinOperatorCandidates"); 3654 break; 3655 3656 case OO_Comma: 3657 UnaryAmp: 3658 case OO_Arrow: 3659 // C++ [over.match.oper]p3: 3660 // -- For the operator ',', the unary operator '&', or the 3661 // operator '->', the built-in candidates set is empty. 3662 break; 3663 3664 case OO_EqualEqual: 3665 case OO_ExclaimEqual: 3666 // C++ [over.match.oper]p16: 3667 // For every pointer to member type T, there exist candidate operator 3668 // functions of the form 3669 // 3670 // bool operator==(T,T); 3671 // bool operator!=(T,T); 3672 for (BuiltinCandidateTypeSet::iterator 3673 MemPtr = CandidateTypes.member_pointer_begin(), 3674 MemPtrEnd = CandidateTypes.member_pointer_end(); 3675 MemPtr != MemPtrEnd; 3676 ++MemPtr) { 3677 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 3678 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 3679 } 3680 3681 // Fall through 3682 3683 case OO_Less: 3684 case OO_Greater: 3685 case OO_LessEqual: 3686 case OO_GreaterEqual: 3687 // C++ [over.built]p15: 3688 // 3689 // For every pointer or enumeration type T, there exist 3690 // candidate operator functions of the form 3691 // 3692 // bool operator<(T, T); 3693 // bool operator>(T, T); 3694 // bool operator<=(T, T); 3695 // bool operator>=(T, T); 3696 // bool operator==(T, T); 3697 // bool operator!=(T, T); 3698 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 3699 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3700 QualType ParamTypes[2] = { *Ptr, *Ptr }; 3701 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 3702 } 3703 for (BuiltinCandidateTypeSet::iterator Enum 3704 = CandidateTypes.enumeration_begin(); 3705 Enum != CandidateTypes.enumeration_end(); ++Enum) { 3706 QualType ParamTypes[2] = { *Enum, *Enum }; 3707 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 3708 } 3709 3710 // Fall through. 3711 isComparison = true; 3712 3713 BinaryPlus: 3714 BinaryMinus: 3715 if (!isComparison) { 3716 // We didn't fall through, so we must have OO_Plus or OO_Minus. 3717 3718 // C++ [over.built]p13: 3719 // 3720 // For every cv-qualified or cv-unqualified object type T 3721 // there exist candidate operator functions of the form 3722 // 3723 // T* operator+(T*, ptrdiff_t); 3724 // T& operator[](T*, ptrdiff_t); [BELOW] 3725 // T* operator-(T*, ptrdiff_t); 3726 // T* operator+(ptrdiff_t, T*); 3727 // T& operator[](ptrdiff_t, T*); [BELOW] 3728 // 3729 // C++ [over.built]p14: 3730 // 3731 // For every T, where T is a pointer to object type, there 3732 // exist candidate operator functions of the form 3733 // 3734 // ptrdiff_t operator-(T, T); 3735 for (BuiltinCandidateTypeSet::iterator Ptr 3736 = CandidateTypes.pointer_begin(); 3737 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3738 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 3739 3740 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 3741 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 3742 3743 if (Op == OO_Plus) { 3744 // T* operator+(ptrdiff_t, T*); 3745 ParamTypes[0] = ParamTypes[1]; 3746 ParamTypes[1] = *Ptr; 3747 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 3748 } else { 3749 // ptrdiff_t operator-(T, T); 3750 ParamTypes[1] = *Ptr; 3751 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes, 3752 Args, 2, CandidateSet); 3753 } 3754 } 3755 } 3756 // Fall through 3757 3758 case OO_Slash: 3759 BinaryStar: 3760 Conditional: 3761 // C++ [over.built]p12: 3762 // 3763 // For every pair of promoted arithmetic types L and R, there 3764 // exist candidate operator functions of the form 3765 // 3766 // LR operator*(L, R); 3767 // LR operator/(L, R); 3768 // LR operator+(L, R); 3769 // LR operator-(L, R); 3770 // bool operator<(L, R); 3771 // bool operator>(L, R); 3772 // bool operator<=(L, R); 3773 // bool operator>=(L, R); 3774 // bool operator==(L, R); 3775 // bool operator!=(L, R); 3776 // 3777 // where LR is the result of the usual arithmetic conversions 3778 // between types L and R. 3779 // 3780 // C++ [over.built]p24: 3781 // 3782 // For every pair of promoted arithmetic types L and R, there exist 3783 // candidate operator functions of the form 3784 // 3785 // LR operator?(bool, L, R); 3786 // 3787 // where LR is the result of the usual arithmetic conversions 3788 // between types L and R. 3789 // Our candidates ignore the first parameter. 3790 for (unsigned Left = FirstPromotedArithmeticType; 3791 Left < LastPromotedArithmeticType; ++Left) { 3792 for (unsigned Right = FirstPromotedArithmeticType; 3793 Right < LastPromotedArithmeticType; ++Right) { 3794 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 3795 QualType Result 3796 = isComparison 3797 ? Context.BoolTy 3798 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]); 3799 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 3800 } 3801 } 3802 break; 3803 3804 case OO_Percent: 3805 BinaryAmp: 3806 case OO_Caret: 3807 case OO_Pipe: 3808 case OO_LessLess: 3809 case OO_GreaterGreater: 3810 // C++ [over.built]p17: 3811 // 3812 // For every pair of promoted integral types L and R, there 3813 // exist candidate operator functions of the form 3814 // 3815 // LR operator%(L, R); 3816 // LR operator&(L, R); 3817 // LR operator^(L, R); 3818 // LR operator|(L, R); 3819 // L operator<<(L, R); 3820 // L operator>>(L, R); 3821 // 3822 // where LR is the result of the usual arithmetic conversions 3823 // between types L and R. 3824 for (unsigned Left = FirstPromotedIntegralType; 3825 Left < LastPromotedIntegralType; ++Left) { 3826 for (unsigned Right = FirstPromotedIntegralType; 3827 Right < LastPromotedIntegralType; ++Right) { 3828 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 3829 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 3830 ? LandR[0] 3831 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]); 3832 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 3833 } 3834 } 3835 break; 3836 3837 case OO_Equal: 3838 // C++ [over.built]p20: 3839 // 3840 // For every pair (T, VQ), where T is an enumeration or 3841 // pointer to member type and VQ is either volatile or 3842 // empty, there exist candidate operator functions of the form 3843 // 3844 // VQ T& operator=(VQ T&, T); 3845 for (BuiltinCandidateTypeSet::iterator 3846 Enum = CandidateTypes.enumeration_begin(), 3847 EnumEnd = CandidateTypes.enumeration_end(); 3848 Enum != EnumEnd; ++Enum) 3849 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2, 3850 CandidateSet); 3851 for (BuiltinCandidateTypeSet::iterator 3852 MemPtr = CandidateTypes.member_pointer_begin(), 3853 MemPtrEnd = CandidateTypes.member_pointer_end(); 3854 MemPtr != MemPtrEnd; ++MemPtr) 3855 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2, 3856 CandidateSet); 3857 // Fall through. 3858 3859 case OO_PlusEqual: 3860 case OO_MinusEqual: 3861 // C++ [over.built]p19: 3862 // 3863 // For every pair (T, VQ), where T is any type and VQ is either 3864 // volatile or empty, there exist candidate operator functions 3865 // of the form 3866 // 3867 // T*VQ& operator=(T*VQ&, T*); 3868 // 3869 // C++ [over.built]p21: 3870 // 3871 // For every pair (T, VQ), where T is a cv-qualified or 3872 // cv-unqualified object type and VQ is either volatile or 3873 // empty, there exist candidate operator functions of the form 3874 // 3875 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 3876 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 3877 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 3878 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3879 QualType ParamTypes[2]; 3880 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType(); 3881 3882 // non-volatile version 3883 ParamTypes[0] = Context.getLValueReferenceType(*Ptr); 3884 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3885 /*IsAssigmentOperator=*/Op == OO_Equal); 3886 3887 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() && 3888 VisibleTypeConversionsQuals.hasVolatile()) { 3889 // volatile version 3890 ParamTypes[0] 3891 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr)); 3892 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3893 /*IsAssigmentOperator=*/Op == OO_Equal); 3894 } 3895 } 3896 // Fall through. 3897 3898 case OO_StarEqual: 3899 case OO_SlashEqual: 3900 // C++ [over.built]p18: 3901 // 3902 // For every triple (L, VQ, R), where L is an arithmetic type, 3903 // VQ is either volatile or empty, and R is a promoted 3904 // arithmetic type, there exist candidate operator functions of 3905 // the form 3906 // 3907 // VQ L& operator=(VQ L&, R); 3908 // VQ L& operator*=(VQ L&, R); 3909 // VQ L& operator/=(VQ L&, R); 3910 // VQ L& operator+=(VQ L&, R); 3911 // VQ L& operator-=(VQ L&, R); 3912 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 3913 for (unsigned Right = FirstPromotedArithmeticType; 3914 Right < LastPromotedArithmeticType; ++Right) { 3915 QualType ParamTypes[2]; 3916 ParamTypes[1] = ArithmeticTypes[Right]; 3917 3918 // Add this built-in operator as a candidate (VQ is empty). 3919 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]); 3920 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3921 /*IsAssigmentOperator=*/Op == OO_Equal); 3922 3923 // Add this built-in operator as a candidate (VQ is 'volatile'). 3924 if (VisibleTypeConversionsQuals.hasVolatile()) { 3925 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]); 3926 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]); 3927 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3928 /*IsAssigmentOperator=*/Op == OO_Equal); 3929 } 3930 } 3931 } 3932 break; 3933 3934 case OO_PercentEqual: 3935 case OO_LessLessEqual: 3936 case OO_GreaterGreaterEqual: 3937 case OO_AmpEqual: 3938 case OO_CaretEqual: 3939 case OO_PipeEqual: 3940 // C++ [over.built]p22: 3941 // 3942 // For every triple (L, VQ, R), where L is an integral type, VQ 3943 // is either volatile or empty, and R is a promoted integral 3944 // type, there exist candidate operator functions of the form 3945 // 3946 // VQ L& operator%=(VQ L&, R); 3947 // VQ L& operator<<=(VQ L&, R); 3948 // VQ L& operator>>=(VQ L&, R); 3949 // VQ L& operator&=(VQ L&, R); 3950 // VQ L& operator^=(VQ L&, R); 3951 // VQ L& operator|=(VQ L&, R); 3952 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 3953 for (unsigned Right = FirstPromotedIntegralType; 3954 Right < LastPromotedIntegralType; ++Right) { 3955 QualType ParamTypes[2]; 3956 ParamTypes[1] = ArithmeticTypes[Right]; 3957 3958 // Add this built-in operator as a candidate (VQ is empty). 3959 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]); 3960 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 3961 if (VisibleTypeConversionsQuals.hasVolatile()) { 3962 // Add this built-in operator as a candidate (VQ is 'volatile'). 3963 ParamTypes[0] = ArithmeticTypes[Left]; 3964 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]); 3965 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]); 3966 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 3967 } 3968 } 3969 } 3970 break; 3971 3972 case OO_Exclaim: { 3973 // C++ [over.operator]p23: 3974 // 3975 // There also exist candidate operator functions of the form 3976 // 3977 // bool operator!(bool); 3978 // bool operator&&(bool, bool); [BELOW] 3979 // bool operator||(bool, bool); [BELOW] 3980 QualType ParamTy = Context.BoolTy; 3981 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 3982 /*IsAssignmentOperator=*/false, 3983 /*NumContextualBoolArguments=*/1); 3984 break; 3985 } 3986 3987 case OO_AmpAmp: 3988 case OO_PipePipe: { 3989 // C++ [over.operator]p23: 3990 // 3991 // There also exist candidate operator functions of the form 3992 // 3993 // bool operator!(bool); [ABOVE] 3994 // bool operator&&(bool, bool); 3995 // bool operator||(bool, bool); 3996 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy }; 3997 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 3998 /*IsAssignmentOperator=*/false, 3999 /*NumContextualBoolArguments=*/2); 4000 break; 4001 } 4002 4003 case OO_Subscript: 4004 // C++ [over.built]p13: 4005 // 4006 // For every cv-qualified or cv-unqualified object type T there 4007 // exist candidate operator functions of the form 4008 // 4009 // T* operator+(T*, ptrdiff_t); [ABOVE] 4010 // T& operator[](T*, ptrdiff_t); 4011 // T* operator-(T*, ptrdiff_t); [ABOVE] 4012 // T* operator+(ptrdiff_t, T*); [ABOVE] 4013 // T& operator[](ptrdiff_t, T*); 4014 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 4015 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 4016 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 4017 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType(); 4018 QualType ResultTy = Context.getLValueReferenceType(PointeeType); 4019 4020 // T& operator[](T*, ptrdiff_t) 4021 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 4022 4023 // T& operator[](ptrdiff_t, T*); 4024 ParamTypes[0] = ParamTypes[1]; 4025 ParamTypes[1] = *Ptr; 4026 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 4027 } 4028 break; 4029 4030 case OO_ArrowStar: 4031 // C++ [over.built]p11: 4032 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 4033 // C1 is the same type as C2 or is a derived class of C2, T is an object 4034 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 4035 // there exist candidate operator functions of the form 4036 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 4037 // where CV12 is the union of CV1 and CV2. 4038 { 4039 for (BuiltinCandidateTypeSet::iterator Ptr = 4040 CandidateTypes.pointer_begin(); 4041 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 4042 QualType C1Ty = (*Ptr); 4043 QualType C1; 4044 QualifierCollector Q1; 4045 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) { 4046 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0); 4047 if (!isa<RecordType>(C1)) 4048 continue; 4049 // heuristic to reduce number of builtin candidates in the set. 4050 // Add volatile/restrict version only if there are conversions to a 4051 // volatile/restrict type. 4052 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 4053 continue; 4054 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 4055 continue; 4056 } 4057 for (BuiltinCandidateTypeSet::iterator 4058 MemPtr = CandidateTypes.member_pointer_begin(), 4059 MemPtrEnd = CandidateTypes.member_pointer_end(); 4060 MemPtr != MemPtrEnd; ++MemPtr) { 4061 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 4062 QualType C2 = QualType(mptr->getClass(), 0); 4063 C2 = C2.getUnqualifiedType(); 4064 if (C1 != C2 && !IsDerivedFrom(C1, C2)) 4065 break; 4066 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 4067 // build CV12 T& 4068 QualType T = mptr->getPointeeType(); 4069 if (!VisibleTypeConversionsQuals.hasVolatile() && 4070 T.isVolatileQualified()) 4071 continue; 4072 if (!VisibleTypeConversionsQuals.hasRestrict() && 4073 T.isRestrictQualified()) 4074 continue; 4075 T = Q1.apply(T); 4076 QualType ResultTy = Context.getLValueReferenceType(T); 4077 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 4078 } 4079 } 4080 } 4081 break; 4082 4083 case OO_Conditional: 4084 // Note that we don't consider the first argument, since it has been 4085 // contextually converted to bool long ago. The candidates below are 4086 // therefore added as binary. 4087 // 4088 // C++ [over.built]p24: 4089 // For every type T, where T is a pointer or pointer-to-member type, 4090 // there exist candidate operator functions of the form 4091 // 4092 // T operator?(bool, T, T); 4093 // 4094 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(), 4095 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) { 4096 QualType ParamTypes[2] = { *Ptr, *Ptr }; 4097 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 4098 } 4099 for (BuiltinCandidateTypeSet::iterator Ptr = 4100 CandidateTypes.member_pointer_begin(), 4101 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) { 4102 QualType ParamTypes[2] = { *Ptr, *Ptr }; 4103 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 4104 } 4105 goto Conditional; 4106 } 4107} 4108 4109/// \brief Add function candidates found via argument-dependent lookup 4110/// to the set of overloading candidates. 4111/// 4112/// This routine performs argument-dependent name lookup based on the 4113/// given function name (which may also be an operator name) and adds 4114/// all of the overload candidates found by ADL to the overload 4115/// candidate set (C++ [basic.lookup.argdep]). 4116void 4117Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 4118 bool Operator, 4119 Expr **Args, unsigned NumArgs, 4120 const TemplateArgumentListInfo *ExplicitTemplateArgs, 4121 OverloadCandidateSet& CandidateSet, 4122 bool PartialOverloading) { 4123 ADLResult Fns; 4124 4125 // FIXME: This approach for uniquing ADL results (and removing 4126 // redundant candidates from the set) relies on pointer-equality, 4127 // which means we need to key off the canonical decl. However, 4128 // always going back to the canonical decl might not get us the 4129 // right set of default arguments. What default arguments are 4130 // we supposed to consider on ADL candidates, anyway? 4131 4132 // FIXME: Pass in the explicit template arguments? 4133 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns); 4134 4135 // Erase all of the candidates we already knew about. 4136 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 4137 CandEnd = CandidateSet.end(); 4138 Cand != CandEnd; ++Cand) 4139 if (Cand->Function) { 4140 Fns.erase(Cand->Function); 4141 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 4142 Fns.erase(FunTmpl); 4143 } 4144 4145 // For each of the ADL candidates we found, add it to the overload 4146 // set. 4147 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 4148 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 4149 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 4150 if (ExplicitTemplateArgs) 4151 continue; 4152 4153 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet, 4154 false, false, PartialOverloading); 4155 } else 4156 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 4157 FoundDecl, ExplicitTemplateArgs, 4158 Args, NumArgs, CandidateSet); 4159 } 4160} 4161 4162/// isBetterOverloadCandidate - Determines whether the first overload 4163/// candidate is a better candidate than the second (C++ 13.3.3p1). 4164bool 4165Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1, 4166 const OverloadCandidate& Cand2, 4167 SourceLocation Loc) { 4168 // Define viable functions to be better candidates than non-viable 4169 // functions. 4170 if (!Cand2.Viable) 4171 return Cand1.Viable; 4172 else if (!Cand1.Viable) 4173 return false; 4174 4175 // C++ [over.match.best]p1: 4176 // 4177 // -- if F is a static member function, ICS1(F) is defined such 4178 // that ICS1(F) is neither better nor worse than ICS1(G) for 4179 // any function G, and, symmetrically, ICS1(G) is neither 4180 // better nor worse than ICS1(F). 4181 unsigned StartArg = 0; 4182 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 4183 StartArg = 1; 4184 4185 // C++ [over.match.best]p1: 4186 // A viable function F1 is defined to be a better function than another 4187 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 4188 // conversion sequence than ICSi(F2), and then... 4189 unsigned NumArgs = Cand1.Conversions.size(); 4190 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 4191 bool HasBetterConversion = false; 4192 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 4193 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx], 4194 Cand2.Conversions[ArgIdx])) { 4195 case ImplicitConversionSequence::Better: 4196 // Cand1 has a better conversion sequence. 4197 HasBetterConversion = true; 4198 break; 4199 4200 case ImplicitConversionSequence::Worse: 4201 // Cand1 can't be better than Cand2. 4202 return false; 4203 4204 case ImplicitConversionSequence::Indistinguishable: 4205 // Do nothing. 4206 break; 4207 } 4208 } 4209 4210 // -- for some argument j, ICSj(F1) is a better conversion sequence than 4211 // ICSj(F2), or, if not that, 4212 if (HasBetterConversion) 4213 return true; 4214 4215 // - F1 is a non-template function and F2 is a function template 4216 // specialization, or, if not that, 4217 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() && 4218 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 4219 return true; 4220 4221 // -- F1 and F2 are function template specializations, and the function 4222 // template for F1 is more specialized than the template for F2 4223 // according to the partial ordering rules described in 14.5.5.2, or, 4224 // if not that, 4225 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 4226 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 4227 if (FunctionTemplateDecl *BetterTemplate 4228 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 4229 Cand2.Function->getPrimaryTemplate(), 4230 Loc, 4231 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 4232 : TPOC_Call)) 4233 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 4234 4235 // -- the context is an initialization by user-defined conversion 4236 // (see 8.5, 13.3.1.5) and the standard conversion sequence 4237 // from the return type of F1 to the destination type (i.e., 4238 // the type of the entity being initialized) is a better 4239 // conversion sequence than the standard conversion sequence 4240 // from the return type of F2 to the destination type. 4241 if (Cand1.Function && Cand2.Function && 4242 isa<CXXConversionDecl>(Cand1.Function) && 4243 isa<CXXConversionDecl>(Cand2.Function)) { 4244 switch (CompareStandardConversionSequences(Cand1.FinalConversion, 4245 Cand2.FinalConversion)) { 4246 case ImplicitConversionSequence::Better: 4247 // Cand1 has a better conversion sequence. 4248 return true; 4249 4250 case ImplicitConversionSequence::Worse: 4251 // Cand1 can't be better than Cand2. 4252 return false; 4253 4254 case ImplicitConversionSequence::Indistinguishable: 4255 // Do nothing 4256 break; 4257 } 4258 } 4259 4260 return false; 4261} 4262 4263/// \brief Computes the best viable function (C++ 13.3.3) 4264/// within an overload candidate set. 4265/// 4266/// \param CandidateSet the set of candidate functions. 4267/// 4268/// \param Loc the location of the function name (or operator symbol) for 4269/// which overload resolution occurs. 4270/// 4271/// \param Best f overload resolution was successful or found a deleted 4272/// function, Best points to the candidate function found. 4273/// 4274/// \returns The result of overload resolution. 4275OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet, 4276 SourceLocation Loc, 4277 OverloadCandidateSet::iterator& Best) { 4278 // Find the best viable function. 4279 Best = CandidateSet.end(); 4280 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4281 Cand != CandidateSet.end(); ++Cand) { 4282 if (Cand->Viable) { 4283 if (Best == CandidateSet.end() || 4284 isBetterOverloadCandidate(*Cand, *Best, Loc)) 4285 Best = Cand; 4286 } 4287 } 4288 4289 // If we didn't find any viable functions, abort. 4290 if (Best == CandidateSet.end()) 4291 return OR_No_Viable_Function; 4292 4293 // Make sure that this function is better than every other viable 4294 // function. If not, we have an ambiguity. 4295 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4296 Cand != CandidateSet.end(); ++Cand) { 4297 if (Cand->Viable && 4298 Cand != Best && 4299 !isBetterOverloadCandidate(*Best, *Cand, Loc)) { 4300 Best = CandidateSet.end(); 4301 return OR_Ambiguous; 4302 } 4303 } 4304 4305 // Best is the best viable function. 4306 if (Best->Function && 4307 (Best->Function->isDeleted() || 4308 Best->Function->getAttr<UnavailableAttr>())) 4309 return OR_Deleted; 4310 4311 // C++ [basic.def.odr]p2: 4312 // An overloaded function is used if it is selected by overload resolution 4313 // when referred to from a potentially-evaluated expression. [Note: this 4314 // covers calls to named functions (5.2.2), operator overloading 4315 // (clause 13), user-defined conversions (12.3.2), allocation function for 4316 // placement new (5.3.4), as well as non-default initialization (8.5). 4317 if (Best->Function) 4318 MarkDeclarationReferenced(Loc, Best->Function); 4319 return OR_Success; 4320} 4321 4322namespace { 4323 4324enum OverloadCandidateKind { 4325 oc_function, 4326 oc_method, 4327 oc_constructor, 4328 oc_function_template, 4329 oc_method_template, 4330 oc_constructor_template, 4331 oc_implicit_default_constructor, 4332 oc_implicit_copy_constructor, 4333 oc_implicit_copy_assignment 4334}; 4335 4336OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 4337 FunctionDecl *Fn, 4338 std::string &Description) { 4339 bool isTemplate = false; 4340 4341 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 4342 isTemplate = true; 4343 Description = S.getTemplateArgumentBindingsText( 4344 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 4345 } 4346 4347 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 4348 if (!Ctor->isImplicit()) 4349 return isTemplate ? oc_constructor_template : oc_constructor; 4350 4351 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor 4352 : oc_implicit_default_constructor; 4353 } 4354 4355 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 4356 // This actually gets spelled 'candidate function' for now, but 4357 // it doesn't hurt to split it out. 4358 if (!Meth->isImplicit()) 4359 return isTemplate ? oc_method_template : oc_method; 4360 4361 assert(Meth->isCopyAssignment() 4362 && "implicit method is not copy assignment operator?"); 4363 return oc_implicit_copy_assignment; 4364 } 4365 4366 return isTemplate ? oc_function_template : oc_function; 4367} 4368 4369} // end anonymous namespace 4370 4371// Notes the location of an overload candidate. 4372void Sema::NoteOverloadCandidate(FunctionDecl *Fn) { 4373 std::string FnDesc; 4374 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 4375 Diag(Fn->getLocation(), diag::note_ovl_candidate) 4376 << (unsigned) K << FnDesc; 4377} 4378 4379/// Diagnoses an ambiguous conversion. The partial diagnostic is the 4380/// "lead" diagnostic; it will be given two arguments, the source and 4381/// target types of the conversion. 4382void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS, 4383 SourceLocation CaretLoc, 4384 const PartialDiagnostic &PDiag) { 4385 Diag(CaretLoc, PDiag) 4386 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType(); 4387 for (AmbiguousConversionSequence::const_iterator 4388 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) { 4389 NoteOverloadCandidate(*I); 4390 } 4391} 4392 4393namespace { 4394 4395void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 4396 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 4397 assert(Conv.isBad()); 4398 assert(Cand->Function && "for now, candidate must be a function"); 4399 FunctionDecl *Fn = Cand->Function; 4400 4401 // There's a conversion slot for the object argument if this is a 4402 // non-constructor method. Note that 'I' corresponds the 4403 // conversion-slot index. 4404 bool isObjectArgument = false; 4405 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 4406 if (I == 0) 4407 isObjectArgument = true; 4408 else 4409 I--; 4410 } 4411 4412 std::string FnDesc; 4413 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 4414 4415 Expr *FromExpr = Conv.Bad.FromExpr; 4416 QualType FromTy = Conv.Bad.getFromType(); 4417 QualType ToTy = Conv.Bad.getToType(); 4418 4419 if (FromTy == S.Context.OverloadTy) { 4420 assert(FromExpr && "overload set argument came from implicit argument?"); 4421 Expr *E = FromExpr->IgnoreParens(); 4422 if (isa<UnaryOperator>(E)) 4423 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 4424 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 4425 4426 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 4427 << (unsigned) FnKind << FnDesc 4428 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 4429 << ToTy << Name << I+1; 4430 return; 4431 } 4432 4433 // Do some hand-waving analysis to see if the non-viability is due 4434 // to a qualifier mismatch. 4435 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 4436 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 4437 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 4438 CToTy = RT->getPointeeType(); 4439 else { 4440 // TODO: detect and diagnose the full richness of const mismatches. 4441 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 4442 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 4443 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 4444 } 4445 4446 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 4447 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 4448 // It is dumb that we have to do this here. 4449 while (isa<ArrayType>(CFromTy)) 4450 CFromTy = CFromTy->getAs<ArrayType>()->getElementType(); 4451 while (isa<ArrayType>(CToTy)) 4452 CToTy = CFromTy->getAs<ArrayType>()->getElementType(); 4453 4454 Qualifiers FromQs = CFromTy.getQualifiers(); 4455 Qualifiers ToQs = CToTy.getQualifiers(); 4456 4457 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 4458 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 4459 << (unsigned) FnKind << FnDesc 4460 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 4461 << FromTy 4462 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 4463 << (unsigned) isObjectArgument << I+1; 4464 return; 4465 } 4466 4467 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4468 assert(CVR && "unexpected qualifiers mismatch"); 4469 4470 if (isObjectArgument) { 4471 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 4472 << (unsigned) FnKind << FnDesc 4473 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 4474 << FromTy << (CVR - 1); 4475 } else { 4476 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 4477 << (unsigned) FnKind << FnDesc 4478 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 4479 << FromTy << (CVR - 1) << I+1; 4480 } 4481 return; 4482 } 4483 4484 // Diagnose references or pointers to incomplete types differently, 4485 // since it's far from impossible that the incompleteness triggered 4486 // the failure. 4487 QualType TempFromTy = FromTy.getNonReferenceType(); 4488 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 4489 TempFromTy = PTy->getPointeeType(); 4490 if (TempFromTy->isIncompleteType()) { 4491 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 4492 << (unsigned) FnKind << FnDesc 4493 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 4494 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 4495 return; 4496 } 4497 4498 // TODO: specialize more based on the kind of mismatch 4499 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv) 4500 << (unsigned) FnKind << FnDesc 4501 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 4502 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 4503} 4504 4505void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 4506 unsigned NumFormalArgs) { 4507 // TODO: treat calls to a missing default constructor as a special case 4508 4509 FunctionDecl *Fn = Cand->Function; 4510 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 4511 4512 unsigned MinParams = Fn->getMinRequiredArguments(); 4513 4514 // at least / at most / exactly 4515 unsigned mode, modeCount; 4516 if (NumFormalArgs < MinParams) { 4517 assert(Cand->FailureKind == ovl_fail_too_few_arguments); 4518 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic()) 4519 mode = 0; // "at least" 4520 else 4521 mode = 2; // "exactly" 4522 modeCount = MinParams; 4523 } else { 4524 assert(Cand->FailureKind == ovl_fail_too_many_arguments); 4525 if (MinParams != FnTy->getNumArgs()) 4526 mode = 1; // "at most" 4527 else 4528 mode = 2; // "exactly" 4529 modeCount = FnTy->getNumArgs(); 4530 } 4531 4532 std::string Description; 4533 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 4534 4535 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 4536 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs; 4537} 4538 4539/// Diagnose a failed template-argument deduction. 4540void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 4541 Expr **Args, unsigned NumArgs) { 4542 FunctionDecl *Fn = Cand->Function; // pattern 4543 4544 TemplateParameter Param = TemplateParameter::getFromOpaqueValue( 4545 Cand->DeductionFailure.TemplateParameter); 4546 4547 switch (Cand->DeductionFailure.Result) { 4548 case Sema::TDK_Success: 4549 llvm_unreachable("TDK_success while diagnosing bad deduction"); 4550 4551 case Sema::TDK_Incomplete: { 4552 NamedDecl *ParamD; 4553 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 4554 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 4555 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 4556 assert(ParamD && "no parameter found for incomplete deduction result"); 4557 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 4558 << ParamD->getDeclName(); 4559 return; 4560 } 4561 4562 // TODO: diagnose these individually, then kill off 4563 // note_ovl_candidate_bad_deduction, which is uselessly vague. 4564 case Sema::TDK_InstantiationDepth: 4565 case Sema::TDK_Inconsistent: 4566 case Sema::TDK_InconsistentQuals: 4567 case Sema::TDK_SubstitutionFailure: 4568 case Sema::TDK_NonDeducedMismatch: 4569 case Sema::TDK_TooManyArguments: 4570 case Sema::TDK_TooFewArguments: 4571 case Sema::TDK_InvalidExplicitArguments: 4572 case Sema::TDK_FailedOverloadResolution: 4573 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 4574 return; 4575 } 4576} 4577 4578/// Generates a 'note' diagnostic for an overload candidate. We've 4579/// already generated a primary error at the call site. 4580/// 4581/// It really does need to be a single diagnostic with its caret 4582/// pointed at the candidate declaration. Yes, this creates some 4583/// major challenges of technical writing. Yes, this makes pointing 4584/// out problems with specific arguments quite awkward. It's still 4585/// better than generating twenty screens of text for every failed 4586/// overload. 4587/// 4588/// It would be great to be able to express per-candidate problems 4589/// more richly for those diagnostic clients that cared, but we'd 4590/// still have to be just as careful with the default diagnostics. 4591void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 4592 Expr **Args, unsigned NumArgs) { 4593 FunctionDecl *Fn = Cand->Function; 4594 4595 // Note deleted candidates, but only if they're viable. 4596 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) { 4597 std::string FnDesc; 4598 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 4599 4600 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 4601 << FnKind << FnDesc << Fn->isDeleted(); 4602 return; 4603 } 4604 4605 // We don't really have anything else to say about viable candidates. 4606 if (Cand->Viable) { 4607 S.NoteOverloadCandidate(Fn); 4608 return; 4609 } 4610 4611 switch (Cand->FailureKind) { 4612 case ovl_fail_too_many_arguments: 4613 case ovl_fail_too_few_arguments: 4614 return DiagnoseArityMismatch(S, Cand, NumArgs); 4615 4616 case ovl_fail_bad_deduction: 4617 return DiagnoseBadDeduction(S, Cand, Args, NumArgs); 4618 4619 case ovl_fail_trivial_conversion: 4620 case ovl_fail_bad_final_conversion: 4621 return S.NoteOverloadCandidate(Fn); 4622 4623 case ovl_fail_bad_conversion: { 4624 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 4625 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 4626 if (Cand->Conversions[I].isBad()) 4627 return DiagnoseBadConversion(S, Cand, I); 4628 4629 // FIXME: this currently happens when we're called from SemaInit 4630 // when user-conversion overload fails. Figure out how to handle 4631 // those conditions and diagnose them well. 4632 return S.NoteOverloadCandidate(Fn); 4633 } 4634 } 4635} 4636 4637void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 4638 // Desugar the type of the surrogate down to a function type, 4639 // retaining as many typedefs as possible while still showing 4640 // the function type (and, therefore, its parameter types). 4641 QualType FnType = Cand->Surrogate->getConversionType(); 4642 bool isLValueReference = false; 4643 bool isRValueReference = false; 4644 bool isPointer = false; 4645 if (const LValueReferenceType *FnTypeRef = 4646 FnType->getAs<LValueReferenceType>()) { 4647 FnType = FnTypeRef->getPointeeType(); 4648 isLValueReference = true; 4649 } else if (const RValueReferenceType *FnTypeRef = 4650 FnType->getAs<RValueReferenceType>()) { 4651 FnType = FnTypeRef->getPointeeType(); 4652 isRValueReference = true; 4653 } 4654 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 4655 FnType = FnTypePtr->getPointeeType(); 4656 isPointer = true; 4657 } 4658 // Desugar down to a function type. 4659 FnType = QualType(FnType->getAs<FunctionType>(), 0); 4660 // Reconstruct the pointer/reference as appropriate. 4661 if (isPointer) FnType = S.Context.getPointerType(FnType); 4662 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 4663 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 4664 4665 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 4666 << FnType; 4667} 4668 4669void NoteBuiltinOperatorCandidate(Sema &S, 4670 const char *Opc, 4671 SourceLocation OpLoc, 4672 OverloadCandidate *Cand) { 4673 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 4674 std::string TypeStr("operator"); 4675 TypeStr += Opc; 4676 TypeStr += "("; 4677 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 4678 if (Cand->Conversions.size() == 1) { 4679 TypeStr += ")"; 4680 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 4681 } else { 4682 TypeStr += ", "; 4683 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 4684 TypeStr += ")"; 4685 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 4686 } 4687} 4688 4689void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 4690 OverloadCandidate *Cand) { 4691 unsigned NoOperands = Cand->Conversions.size(); 4692 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 4693 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 4694 if (ICS.isBad()) break; // all meaningless after first invalid 4695 if (!ICS.isAmbiguous()) continue; 4696 4697 S.DiagnoseAmbiguousConversion(ICS, OpLoc, 4698 PDiag(diag::note_ambiguous_type_conversion)); 4699 } 4700} 4701 4702SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 4703 if (Cand->Function) 4704 return Cand->Function->getLocation(); 4705 if (Cand->IsSurrogate) 4706 return Cand->Surrogate->getLocation(); 4707 return SourceLocation(); 4708} 4709 4710struct CompareOverloadCandidatesForDisplay { 4711 Sema &S; 4712 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 4713 4714 bool operator()(const OverloadCandidate *L, 4715 const OverloadCandidate *R) { 4716 // Fast-path this check. 4717 if (L == R) return false; 4718 4719 // Order first by viability. 4720 if (L->Viable) { 4721 if (!R->Viable) return true; 4722 4723 // TODO: introduce a tri-valued comparison for overload 4724 // candidates. Would be more worthwhile if we had a sort 4725 // that could exploit it. 4726 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true; 4727 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false; 4728 } else if (R->Viable) 4729 return false; 4730 4731 assert(L->Viable == R->Viable); 4732 4733 // Criteria by which we can sort non-viable candidates: 4734 if (!L->Viable) { 4735 // 1. Arity mismatches come after other candidates. 4736 if (L->FailureKind == ovl_fail_too_many_arguments || 4737 L->FailureKind == ovl_fail_too_few_arguments) 4738 return false; 4739 if (R->FailureKind == ovl_fail_too_many_arguments || 4740 R->FailureKind == ovl_fail_too_few_arguments) 4741 return true; 4742 4743 // 2. Bad conversions come first and are ordered by the number 4744 // of bad conversions and quality of good conversions. 4745 if (L->FailureKind == ovl_fail_bad_conversion) { 4746 if (R->FailureKind != ovl_fail_bad_conversion) 4747 return true; 4748 4749 // If there's any ordering between the defined conversions... 4750 // FIXME: this might not be transitive. 4751 assert(L->Conversions.size() == R->Conversions.size()); 4752 4753 int leftBetter = 0; 4754 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 4755 for (unsigned E = L->Conversions.size(); I != E; ++I) { 4756 switch (S.CompareImplicitConversionSequences(L->Conversions[I], 4757 R->Conversions[I])) { 4758 case ImplicitConversionSequence::Better: 4759 leftBetter++; 4760 break; 4761 4762 case ImplicitConversionSequence::Worse: 4763 leftBetter--; 4764 break; 4765 4766 case ImplicitConversionSequence::Indistinguishable: 4767 break; 4768 } 4769 } 4770 if (leftBetter > 0) return true; 4771 if (leftBetter < 0) return false; 4772 4773 } else if (R->FailureKind == ovl_fail_bad_conversion) 4774 return false; 4775 4776 // TODO: others? 4777 } 4778 4779 // Sort everything else by location. 4780 SourceLocation LLoc = GetLocationForCandidate(L); 4781 SourceLocation RLoc = GetLocationForCandidate(R); 4782 4783 // Put candidates without locations (e.g. builtins) at the end. 4784 if (LLoc.isInvalid()) return false; 4785 if (RLoc.isInvalid()) return true; 4786 4787 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 4788 } 4789}; 4790 4791/// CompleteNonViableCandidate - Normally, overload resolution only 4792/// computes up to the first 4793void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 4794 Expr **Args, unsigned NumArgs) { 4795 assert(!Cand->Viable); 4796 4797 // Don't do anything on failures other than bad conversion. 4798 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 4799 4800 // Skip forward to the first bad conversion. 4801 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 4802 unsigned ConvCount = Cand->Conversions.size(); 4803 while (true) { 4804 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 4805 ConvIdx++; 4806 if (Cand->Conversions[ConvIdx - 1].isBad()) 4807 break; 4808 } 4809 4810 if (ConvIdx == ConvCount) 4811 return; 4812 4813 assert(!Cand->Conversions[ConvIdx].isInitialized() && 4814 "remaining conversion is initialized?"); 4815 4816 // FIXME: these should probably be preserved from the overload 4817 // operation somehow. 4818 bool SuppressUserConversions = false; 4819 bool ForceRValue = false; 4820 4821 const FunctionProtoType* Proto; 4822 unsigned ArgIdx = ConvIdx; 4823 4824 if (Cand->IsSurrogate) { 4825 QualType ConvType 4826 = Cand->Surrogate->getConversionType().getNonReferenceType(); 4827 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 4828 ConvType = ConvPtrType->getPointeeType(); 4829 Proto = ConvType->getAs<FunctionProtoType>(); 4830 ArgIdx--; 4831 } else if (Cand->Function) { 4832 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 4833 if (isa<CXXMethodDecl>(Cand->Function) && 4834 !isa<CXXConstructorDecl>(Cand->Function)) 4835 ArgIdx--; 4836 } else { 4837 // Builtin binary operator with a bad first conversion. 4838 assert(ConvCount <= 3); 4839 for (; ConvIdx != ConvCount; ++ConvIdx) 4840 Cand->Conversions[ConvIdx] 4841 = S.TryCopyInitialization(Args[ConvIdx], 4842 Cand->BuiltinTypes.ParamTypes[ConvIdx], 4843 SuppressUserConversions, ForceRValue, 4844 /*InOverloadResolution*/ true); 4845 return; 4846 } 4847 4848 // Fill in the rest of the conversions. 4849 unsigned NumArgsInProto = Proto->getNumArgs(); 4850 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 4851 if (ArgIdx < NumArgsInProto) 4852 Cand->Conversions[ConvIdx] 4853 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx), 4854 SuppressUserConversions, ForceRValue, 4855 /*InOverloadResolution=*/true); 4856 else 4857 Cand->Conversions[ConvIdx].setEllipsis(); 4858 } 4859} 4860 4861} // end anonymous namespace 4862 4863/// PrintOverloadCandidates - When overload resolution fails, prints 4864/// diagnostic messages containing the candidates in the candidate 4865/// set. 4866void 4867Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet, 4868 OverloadCandidateDisplayKind OCD, 4869 Expr **Args, unsigned NumArgs, 4870 const char *Opc, 4871 SourceLocation OpLoc) { 4872 // Sort the candidates by viability and position. Sorting directly would 4873 // be prohibitive, so we make a set of pointers and sort those. 4874 llvm::SmallVector<OverloadCandidate*, 32> Cands; 4875 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size()); 4876 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 4877 LastCand = CandidateSet.end(); 4878 Cand != LastCand; ++Cand) { 4879 if (Cand->Viable) 4880 Cands.push_back(Cand); 4881 else if (OCD == OCD_AllCandidates) { 4882 CompleteNonViableCandidate(*this, Cand, Args, NumArgs); 4883 Cands.push_back(Cand); 4884 } 4885 } 4886 4887 std::sort(Cands.begin(), Cands.end(), 4888 CompareOverloadCandidatesForDisplay(*this)); 4889 4890 bool ReportedAmbiguousConversions = false; 4891 4892 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E; 4893 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 4894 OverloadCandidate *Cand = *I; 4895 4896 if (Cand->Function) 4897 NoteFunctionCandidate(*this, Cand, Args, NumArgs); 4898 else if (Cand->IsSurrogate) 4899 NoteSurrogateCandidate(*this, Cand); 4900 4901 // This a builtin candidate. We do not, in general, want to list 4902 // every possible builtin candidate. 4903 else if (Cand->Viable) { 4904 // Generally we only see ambiguities including viable builtin 4905 // operators if overload resolution got screwed up by an 4906 // ambiguous user-defined conversion. 4907 // 4908 // FIXME: It's quite possible for different conversions to see 4909 // different ambiguities, though. 4910 if (!ReportedAmbiguousConversions) { 4911 NoteAmbiguousUserConversions(*this, OpLoc, Cand); 4912 ReportedAmbiguousConversions = true; 4913 } 4914 4915 // If this is a viable builtin, print it. 4916 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand); 4917 } 4918 } 4919} 4920 4921static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) { 4922 if (isa<UnresolvedLookupExpr>(E)) 4923 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D); 4924 4925 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D); 4926} 4927 4928/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 4929/// an overloaded function (C++ [over.over]), where @p From is an 4930/// expression with overloaded function type and @p ToType is the type 4931/// we're trying to resolve to. For example: 4932/// 4933/// @code 4934/// int f(double); 4935/// int f(int); 4936/// 4937/// int (*pfd)(double) = f; // selects f(double) 4938/// @endcode 4939/// 4940/// This routine returns the resulting FunctionDecl if it could be 4941/// resolved, and NULL otherwise. When @p Complain is true, this 4942/// routine will emit diagnostics if there is an error. 4943FunctionDecl * 4944Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType, 4945 bool Complain) { 4946 QualType FunctionType = ToType; 4947 bool IsMember = false; 4948 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>()) 4949 FunctionType = ToTypePtr->getPointeeType(); 4950 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>()) 4951 FunctionType = ToTypeRef->getPointeeType(); 4952 else if (const MemberPointerType *MemTypePtr = 4953 ToType->getAs<MemberPointerType>()) { 4954 FunctionType = MemTypePtr->getPointeeType(); 4955 IsMember = true; 4956 } 4957 4958 // We only look at pointers or references to functions. 4959 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType(); 4960 if (!FunctionType->isFunctionType()) 4961 return 0; 4962 4963 // Find the actual overloaded function declaration. 4964 if (From->getType() != Context.OverloadTy) 4965 return 0; 4966 4967 // C++ [over.over]p1: 4968 // [...] [Note: any redundant set of parentheses surrounding the 4969 // overloaded function name is ignored (5.1). ] 4970 // C++ [over.over]p1: 4971 // [...] The overloaded function name can be preceded by the & 4972 // operator. 4973 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer(); 4974 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0; 4975 if (OvlExpr->hasExplicitTemplateArgs()) { 4976 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer); 4977 ExplicitTemplateArgs = &ETABuffer; 4978 } 4979 4980 // Look through all of the overloaded functions, searching for one 4981 // whose type matches exactly. 4982 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 4983 bool FoundNonTemplateFunction = false; 4984 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 4985 E = OvlExpr->decls_end(); I != E; ++I) { 4986 // Look through any using declarations to find the underlying function. 4987 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 4988 4989 // C++ [over.over]p3: 4990 // Non-member functions and static member functions match 4991 // targets of type "pointer-to-function" or "reference-to-function." 4992 // Nonstatic member functions match targets of 4993 // type "pointer-to-member-function." 4994 // Note that according to DR 247, the containing class does not matter. 4995 4996 if (FunctionTemplateDecl *FunctionTemplate 4997 = dyn_cast<FunctionTemplateDecl>(Fn)) { 4998 if (CXXMethodDecl *Method 4999 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 5000 // Skip non-static function templates when converting to pointer, and 5001 // static when converting to member pointer. 5002 if (Method->isStatic() == IsMember) 5003 continue; 5004 } else if (IsMember) 5005 continue; 5006 5007 // C++ [over.over]p2: 5008 // If the name is a function template, template argument deduction is 5009 // done (14.8.2.2), and if the argument deduction succeeds, the 5010 // resulting template argument list is used to generate a single 5011 // function template specialization, which is added to the set of 5012 // overloaded functions considered. 5013 // FIXME: We don't really want to build the specialization here, do we? 5014 FunctionDecl *Specialization = 0; 5015 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 5016 if (TemplateDeductionResult Result 5017 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 5018 FunctionType, Specialization, Info)) { 5019 // FIXME: make a note of the failed deduction for diagnostics. 5020 (void)Result; 5021 } else { 5022 // FIXME: If the match isn't exact, shouldn't we just drop this as 5023 // a candidate? Find a testcase before changing the code. 5024 assert(FunctionType 5025 == Context.getCanonicalType(Specialization->getType())); 5026 Matches.push_back(std::make_pair(I.getPair(), 5027 cast<FunctionDecl>(Specialization->getCanonicalDecl()))); 5028 } 5029 5030 continue; 5031 } 5032 5033 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 5034 // Skip non-static functions when converting to pointer, and static 5035 // when converting to member pointer. 5036 if (Method->isStatic() == IsMember) 5037 continue; 5038 5039 // If we have explicit template arguments, skip non-templates. 5040 if (OvlExpr->hasExplicitTemplateArgs()) 5041 continue; 5042 } else if (IsMember) 5043 continue; 5044 5045 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 5046 QualType ResultTy; 5047 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) || 5048 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType, 5049 ResultTy)) { 5050 Matches.push_back(std::make_pair(I.getPair(), 5051 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 5052 FoundNonTemplateFunction = true; 5053 } 5054 } 5055 } 5056 5057 // If there were 0 or 1 matches, we're done. 5058 if (Matches.empty()) 5059 return 0; 5060 else if (Matches.size() == 1) { 5061 FunctionDecl *Result = Matches[0].second; 5062 MarkDeclarationReferenced(From->getLocStart(), Result); 5063 if (Complain) 5064 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first); 5065 return Result; 5066 } 5067 5068 // C++ [over.over]p4: 5069 // If more than one function is selected, [...] 5070 if (!FoundNonTemplateFunction) { 5071 // [...] and any given function template specialization F1 is 5072 // eliminated if the set contains a second function template 5073 // specialization whose function template is more specialized 5074 // than the function template of F1 according to the partial 5075 // ordering rules of 14.5.5.2. 5076 5077 // The algorithm specified above is quadratic. We instead use a 5078 // two-pass algorithm (similar to the one used to identify the 5079 // best viable function in an overload set) that identifies the 5080 // best function template (if it exists). 5081 5082 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 5083 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 5084 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 5085 5086 UnresolvedSetIterator Result = 5087 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 5088 TPOC_Other, From->getLocStart(), 5089 PDiag(), 5090 PDiag(diag::err_addr_ovl_ambiguous) 5091 << Matches[0].second->getDeclName(), 5092 PDiag(diag::note_ovl_candidate) 5093 << (unsigned) oc_function_template); 5094 assert(Result != MatchesCopy.end() && "no most-specialized template"); 5095 MarkDeclarationReferenced(From->getLocStart(), *Result); 5096 if (Complain) { 5097 DeclAccessPair FoundDecl = Matches[Result - MatchesCopy.begin()].first; 5098 CheckUnresolvedAccess(*this, OvlExpr, FoundDecl); 5099 } 5100 return cast<FunctionDecl>(*Result); 5101 } 5102 5103 // [...] any function template specializations in the set are 5104 // eliminated if the set also contains a non-template function, [...] 5105 for (unsigned I = 0, N = Matches.size(); I != N; ) { 5106 if (Matches[I].second->getPrimaryTemplate() == 0) 5107 ++I; 5108 else { 5109 Matches[I] = Matches[--N]; 5110 Matches.set_size(N); 5111 } 5112 } 5113 5114 // [...] After such eliminations, if any, there shall remain exactly one 5115 // selected function. 5116 if (Matches.size() == 1) { 5117 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second); 5118 if (Complain) 5119 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first); 5120 return cast<FunctionDecl>(Matches[0].second); 5121 } 5122 5123 // FIXME: We should probably return the same thing that BestViableFunction 5124 // returns (even if we issue the diagnostics here). 5125 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous) 5126 << Matches[0].second->getDeclName(); 5127 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 5128 NoteOverloadCandidate(Matches[I].second); 5129 return 0; 5130} 5131 5132/// \brief Given an expression that refers to an overloaded function, try to 5133/// resolve that overloaded function expression down to a single function. 5134/// 5135/// This routine can only resolve template-ids that refer to a single function 5136/// template, where that template-id refers to a single template whose template 5137/// arguments are either provided by the template-id or have defaults, 5138/// as described in C++0x [temp.arg.explicit]p3. 5139FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) { 5140 // C++ [over.over]p1: 5141 // [...] [Note: any redundant set of parentheses surrounding the 5142 // overloaded function name is ignored (5.1). ] 5143 // C++ [over.over]p1: 5144 // [...] The overloaded function name can be preceded by the & 5145 // operator. 5146 5147 if (From->getType() != Context.OverloadTy) 5148 return 0; 5149 5150 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer(); 5151 5152 // If we didn't actually find any template-ids, we're done. 5153 if (!OvlExpr->hasExplicitTemplateArgs()) 5154 return 0; 5155 5156 TemplateArgumentListInfo ExplicitTemplateArgs; 5157 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 5158 5159 // Look through all of the overloaded functions, searching for one 5160 // whose type matches exactly. 5161 FunctionDecl *Matched = 0; 5162 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 5163 E = OvlExpr->decls_end(); I != E; ++I) { 5164 // C++0x [temp.arg.explicit]p3: 5165 // [...] In contexts where deduction is done and fails, or in contexts 5166 // where deduction is not done, if a template argument list is 5167 // specified and it, along with any default template arguments, 5168 // identifies a single function template specialization, then the 5169 // template-id is an lvalue for the function template specialization. 5170 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I); 5171 5172 // C++ [over.over]p2: 5173 // If the name is a function template, template argument deduction is 5174 // done (14.8.2.2), and if the argument deduction succeeds, the 5175 // resulting template argument list is used to generate a single 5176 // function template specialization, which is added to the set of 5177 // overloaded functions considered. 5178 FunctionDecl *Specialization = 0; 5179 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 5180 if (TemplateDeductionResult Result 5181 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 5182 Specialization, Info)) { 5183 // FIXME: make a note of the failed deduction for diagnostics. 5184 (void)Result; 5185 continue; 5186 } 5187 5188 // Multiple matches; we can't resolve to a single declaration. 5189 if (Matched) 5190 return 0; 5191 5192 Matched = Specialization; 5193 } 5194 5195 return Matched; 5196} 5197 5198/// \brief Add a single candidate to the overload set. 5199static void AddOverloadedCallCandidate(Sema &S, 5200 DeclAccessPair FoundDecl, 5201 const TemplateArgumentListInfo *ExplicitTemplateArgs, 5202 Expr **Args, unsigned NumArgs, 5203 OverloadCandidateSet &CandidateSet, 5204 bool PartialOverloading) { 5205 NamedDecl *Callee = FoundDecl.getDecl(); 5206 if (isa<UsingShadowDecl>(Callee)) 5207 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 5208 5209 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 5210 assert(!ExplicitTemplateArgs && "Explicit template arguments?"); 5211 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet, 5212 false, false, PartialOverloading); 5213 return; 5214 } 5215 5216 if (FunctionTemplateDecl *FuncTemplate 5217 = dyn_cast<FunctionTemplateDecl>(Callee)) { 5218 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 5219 ExplicitTemplateArgs, 5220 Args, NumArgs, CandidateSet); 5221 return; 5222 } 5223 5224 assert(false && "unhandled case in overloaded call candidate"); 5225 5226 // do nothing? 5227} 5228 5229/// \brief Add the overload candidates named by callee and/or found by argument 5230/// dependent lookup to the given overload set. 5231void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 5232 Expr **Args, unsigned NumArgs, 5233 OverloadCandidateSet &CandidateSet, 5234 bool PartialOverloading) { 5235 5236#ifndef NDEBUG 5237 // Verify that ArgumentDependentLookup is consistent with the rules 5238 // in C++0x [basic.lookup.argdep]p3: 5239 // 5240 // Let X be the lookup set produced by unqualified lookup (3.4.1) 5241 // and let Y be the lookup set produced by argument dependent 5242 // lookup (defined as follows). If X contains 5243 // 5244 // -- a declaration of a class member, or 5245 // 5246 // -- a block-scope function declaration that is not a 5247 // using-declaration, or 5248 // 5249 // -- a declaration that is neither a function or a function 5250 // template 5251 // 5252 // then Y is empty. 5253 5254 if (ULE->requiresADL()) { 5255 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 5256 E = ULE->decls_end(); I != E; ++I) { 5257 assert(!(*I)->getDeclContext()->isRecord()); 5258 assert(isa<UsingShadowDecl>(*I) || 5259 !(*I)->getDeclContext()->isFunctionOrMethod()); 5260 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 5261 } 5262 } 5263#endif 5264 5265 // It would be nice to avoid this copy. 5266 TemplateArgumentListInfo TABuffer; 5267 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 5268 if (ULE->hasExplicitTemplateArgs()) { 5269 ULE->copyTemplateArgumentsInto(TABuffer); 5270 ExplicitTemplateArgs = &TABuffer; 5271 } 5272 5273 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 5274 E = ULE->decls_end(); I != E; ++I) 5275 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, 5276 Args, NumArgs, CandidateSet, 5277 PartialOverloading); 5278 5279 if (ULE->requiresADL()) 5280 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 5281 Args, NumArgs, 5282 ExplicitTemplateArgs, 5283 CandidateSet, 5284 PartialOverloading); 5285} 5286 5287static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn, 5288 Expr **Args, unsigned NumArgs) { 5289 Fn->Destroy(SemaRef.Context); 5290 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) 5291 Args[Arg]->Destroy(SemaRef.Context); 5292 return SemaRef.ExprError(); 5293} 5294 5295/// Attempts to recover from a call where no functions were found. 5296/// 5297/// Returns true if new candidates were found. 5298static Sema::OwningExprResult 5299BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn, 5300 UnresolvedLookupExpr *ULE, 5301 SourceLocation LParenLoc, 5302 Expr **Args, unsigned NumArgs, 5303 SourceLocation *CommaLocs, 5304 SourceLocation RParenLoc) { 5305 5306 CXXScopeSpec SS; 5307 if (ULE->getQualifier()) { 5308 SS.setScopeRep(ULE->getQualifier()); 5309 SS.setRange(ULE->getQualifierRange()); 5310 } 5311 5312 TemplateArgumentListInfo TABuffer; 5313 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 5314 if (ULE->hasExplicitTemplateArgs()) { 5315 ULE->copyTemplateArgumentsInto(TABuffer); 5316 ExplicitTemplateArgs = &TABuffer; 5317 } 5318 5319 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 5320 Sema::LookupOrdinaryName); 5321 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R)) 5322 return Destroy(SemaRef, Fn, Args, NumArgs); 5323 5324 assert(!R.empty() && "lookup results empty despite recovery"); 5325 5326 // Build an implicit member call if appropriate. Just drop the 5327 // casts and such from the call, we don't really care. 5328 Sema::OwningExprResult NewFn = SemaRef.ExprError(); 5329 if ((*R.begin())->isCXXClassMember()) 5330 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs); 5331 else if (ExplicitTemplateArgs) 5332 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs); 5333 else 5334 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 5335 5336 if (NewFn.isInvalid()) 5337 return Destroy(SemaRef, Fn, Args, NumArgs); 5338 5339 Fn->Destroy(SemaRef.Context); 5340 5341 // This shouldn't cause an infinite loop because we're giving it 5342 // an expression with non-empty lookup results, which should never 5343 // end up here. 5344 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc, 5345 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs), 5346 CommaLocs, RParenLoc); 5347} 5348 5349/// ResolveOverloadedCallFn - Given the call expression that calls Fn 5350/// (which eventually refers to the declaration Func) and the call 5351/// arguments Args/NumArgs, attempt to resolve the function call down 5352/// to a specific function. If overload resolution succeeds, returns 5353/// the function declaration produced by overload 5354/// resolution. Otherwise, emits diagnostics, deletes all of the 5355/// arguments and Fn, and returns NULL. 5356Sema::OwningExprResult 5357Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE, 5358 SourceLocation LParenLoc, 5359 Expr **Args, unsigned NumArgs, 5360 SourceLocation *CommaLocs, 5361 SourceLocation RParenLoc) { 5362#ifndef NDEBUG 5363 if (ULE->requiresADL()) { 5364 // To do ADL, we must have found an unqualified name. 5365 assert(!ULE->getQualifier() && "qualified name with ADL"); 5366 5367 // We don't perform ADL for implicit declarations of builtins. 5368 // Verify that this was correctly set up. 5369 FunctionDecl *F; 5370 if (ULE->decls_begin() + 1 == ULE->decls_end() && 5371 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 5372 F->getBuiltinID() && F->isImplicit()) 5373 assert(0 && "performing ADL for builtin"); 5374 5375 // We don't perform ADL in C. 5376 assert(getLangOptions().CPlusPlus && "ADL enabled in C"); 5377 } 5378#endif 5379 5380 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 5381 5382 // Add the functions denoted by the callee to the set of candidate 5383 // functions, including those from argument-dependent lookup. 5384 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet); 5385 5386 // If we found nothing, try to recover. 5387 // AddRecoveryCallCandidates diagnoses the error itself, so we just 5388 // bailout out if it fails. 5389 if (CandidateSet.empty()) 5390 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs, 5391 CommaLocs, RParenLoc); 5392 5393 OverloadCandidateSet::iterator Best; 5394 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) { 5395 case OR_Success: { 5396 FunctionDecl *FDecl = Best->Function; 5397 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl); 5398 Fn = FixOverloadedFunctionReference(Fn, FDecl); 5399 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc); 5400 } 5401 5402 case OR_No_Viable_Function: 5403 Diag(Fn->getSourceRange().getBegin(), 5404 diag::err_ovl_no_viable_function_in_call) 5405 << ULE->getName() << Fn->getSourceRange(); 5406 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 5407 break; 5408 5409 case OR_Ambiguous: 5410 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 5411 << ULE->getName() << Fn->getSourceRange(); 5412 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs); 5413 break; 5414 5415 case OR_Deleted: 5416 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call) 5417 << Best->Function->isDeleted() 5418 << ULE->getName() 5419 << Fn->getSourceRange(); 5420 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 5421 break; 5422 } 5423 5424 // Overload resolution failed. Destroy all of the subexpressions and 5425 // return NULL. 5426 Fn->Destroy(Context); 5427 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) 5428 Args[Arg]->Destroy(Context); 5429 return ExprError(); 5430} 5431 5432static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 5433 return Functions.size() > 1 || 5434 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 5435} 5436 5437/// \brief Create a unary operation that may resolve to an overloaded 5438/// operator. 5439/// 5440/// \param OpLoc The location of the operator itself (e.g., '*'). 5441/// 5442/// \param OpcIn The UnaryOperator::Opcode that describes this 5443/// operator. 5444/// 5445/// \param Functions The set of non-member functions that will be 5446/// considered by overload resolution. The caller needs to build this 5447/// set based on the context using, e.g., 5448/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 5449/// set should not contain any member functions; those will be added 5450/// by CreateOverloadedUnaryOp(). 5451/// 5452/// \param input The input argument. 5453Sema::OwningExprResult 5454Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 5455 const UnresolvedSetImpl &Fns, 5456 ExprArg input) { 5457 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 5458 Expr *Input = (Expr *)input.get(); 5459 5460 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 5461 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 5462 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 5463 5464 Expr *Args[2] = { Input, 0 }; 5465 unsigned NumArgs = 1; 5466 5467 // For post-increment and post-decrement, add the implicit '0' as 5468 // the second argument, so that we know this is a post-increment or 5469 // post-decrement. 5470 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) { 5471 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 5472 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy, 5473 SourceLocation()); 5474 NumArgs = 2; 5475 } 5476 5477 if (Input->isTypeDependent()) { 5478 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 5479 UnresolvedLookupExpr *Fn 5480 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass, 5481 0, SourceRange(), OpName, OpLoc, 5482 /*ADL*/ true, IsOverloaded(Fns)); 5483 Fn->addDecls(Fns.begin(), Fns.end()); 5484 5485 input.release(); 5486 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 5487 &Args[0], NumArgs, 5488 Context.DependentTy, 5489 OpLoc)); 5490 } 5491 5492 // Build an empty overload set. 5493 OverloadCandidateSet CandidateSet(OpLoc); 5494 5495 // Add the candidates from the given function set. 5496 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false); 5497 5498 // Add operator candidates that are member functions. 5499 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 5500 5501 // Add candidates from ADL. 5502 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 5503 Args, NumArgs, 5504 /*ExplicitTemplateArgs*/ 0, 5505 CandidateSet); 5506 5507 // Add builtin operator candidates. 5508 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 5509 5510 // Perform overload resolution. 5511 OverloadCandidateSet::iterator Best; 5512 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 5513 case OR_Success: { 5514 // We found a built-in operator or an overloaded operator. 5515 FunctionDecl *FnDecl = Best->Function; 5516 5517 if (FnDecl) { 5518 // We matched an overloaded operator. Build a call to that 5519 // operator. 5520 5521 // Convert the arguments. 5522 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 5523 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 5524 5525 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, Method)) 5526 return ExprError(); 5527 } else { 5528 // Convert the arguments. 5529 OwningExprResult InputInit 5530 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 5531 FnDecl->getParamDecl(0)), 5532 SourceLocation(), 5533 move(input)); 5534 if (InputInit.isInvalid()) 5535 return ExprError(); 5536 5537 input = move(InputInit); 5538 Input = (Expr *)input.get(); 5539 } 5540 5541 // Determine the result type 5542 QualType ResultTy = FnDecl->getResultType().getNonReferenceType(); 5543 5544 // Build the actual expression node. 5545 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 5546 SourceLocation()); 5547 UsualUnaryConversions(FnExpr); 5548 5549 input.release(); 5550 Args[0] = Input; 5551 ExprOwningPtr<CallExpr> TheCall(this, 5552 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr, 5553 Args, NumArgs, ResultTy, OpLoc)); 5554 5555 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(), 5556 FnDecl)) 5557 return ExprError(); 5558 5559 return MaybeBindToTemporary(TheCall.release()); 5560 } else { 5561 // We matched a built-in operator. Convert the arguments, then 5562 // break out so that we will build the appropriate built-in 5563 // operator node. 5564 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 5565 Best->Conversions[0], AA_Passing)) 5566 return ExprError(); 5567 5568 break; 5569 } 5570 } 5571 5572 case OR_No_Viable_Function: 5573 // No viable function; fall through to handling this as a 5574 // built-in operator, which will produce an error message for us. 5575 break; 5576 5577 case OR_Ambiguous: 5578 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 5579 << UnaryOperator::getOpcodeStr(Opc) 5580 << Input->getSourceRange(); 5581 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs, 5582 UnaryOperator::getOpcodeStr(Opc), OpLoc); 5583 return ExprError(); 5584 5585 case OR_Deleted: 5586 Diag(OpLoc, diag::err_ovl_deleted_oper) 5587 << Best->Function->isDeleted() 5588 << UnaryOperator::getOpcodeStr(Opc) 5589 << Input->getSourceRange(); 5590 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 5591 return ExprError(); 5592 } 5593 5594 // Either we found no viable overloaded operator or we matched a 5595 // built-in operator. In either case, fall through to trying to 5596 // build a built-in operation. 5597 input.release(); 5598 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input)); 5599} 5600 5601/// \brief Create a binary operation that may resolve to an overloaded 5602/// operator. 5603/// 5604/// \param OpLoc The location of the operator itself (e.g., '+'). 5605/// 5606/// \param OpcIn The BinaryOperator::Opcode that describes this 5607/// operator. 5608/// 5609/// \param Functions The set of non-member functions that will be 5610/// considered by overload resolution. The caller needs to build this 5611/// set based on the context using, e.g., 5612/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 5613/// set should not contain any member functions; those will be added 5614/// by CreateOverloadedBinOp(). 5615/// 5616/// \param LHS Left-hand argument. 5617/// \param RHS Right-hand argument. 5618Sema::OwningExprResult 5619Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 5620 unsigned OpcIn, 5621 const UnresolvedSetImpl &Fns, 5622 Expr *LHS, Expr *RHS) { 5623 Expr *Args[2] = { LHS, RHS }; 5624 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 5625 5626 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 5627 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 5628 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 5629 5630 // If either side is type-dependent, create an appropriate dependent 5631 // expression. 5632 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 5633 if (Fns.empty()) { 5634 // If there are no functions to store, just build a dependent 5635 // BinaryOperator or CompoundAssignment. 5636 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign) 5637 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 5638 Context.DependentTy, OpLoc)); 5639 5640 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 5641 Context.DependentTy, 5642 Context.DependentTy, 5643 Context.DependentTy, 5644 OpLoc)); 5645 } 5646 5647 // FIXME: save results of ADL from here? 5648 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 5649 UnresolvedLookupExpr *Fn 5650 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass, 5651 0, SourceRange(), OpName, OpLoc, 5652 /*ADL*/ true, IsOverloaded(Fns)); 5653 5654 Fn->addDecls(Fns.begin(), Fns.end()); 5655 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 5656 Args, 2, 5657 Context.DependentTy, 5658 OpLoc)); 5659 } 5660 5661 // If this is the .* operator, which is not overloadable, just 5662 // create a built-in binary operator. 5663 if (Opc == BinaryOperator::PtrMemD) 5664 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 5665 5666 // If this is the assignment operator, we only perform overload resolution 5667 // if the left-hand side is a class or enumeration type. This is actually 5668 // a hack. The standard requires that we do overload resolution between the 5669 // various built-in candidates, but as DR507 points out, this can lead to 5670 // problems. So we do it this way, which pretty much follows what GCC does. 5671 // Note that we go the traditional code path for compound assignment forms. 5672 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType()) 5673 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 5674 5675 // Build an empty overload set. 5676 OverloadCandidateSet CandidateSet(OpLoc); 5677 5678 // Add the candidates from the given function set. 5679 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false); 5680 5681 // Add operator candidates that are member functions. 5682 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 5683 5684 // Add candidates from ADL. 5685 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 5686 Args, 2, 5687 /*ExplicitTemplateArgs*/ 0, 5688 CandidateSet); 5689 5690 // Add builtin operator candidates. 5691 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 5692 5693 // Perform overload resolution. 5694 OverloadCandidateSet::iterator Best; 5695 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 5696 case OR_Success: { 5697 // We found a built-in operator or an overloaded operator. 5698 FunctionDecl *FnDecl = Best->Function; 5699 5700 if (FnDecl) { 5701 // We matched an overloaded operator. Build a call to that 5702 // operator. 5703 5704 // Convert the arguments. 5705 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 5706 // Best->Access is only meaningful for class members. 5707 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 5708 5709 OwningExprResult Arg1 5710 = PerformCopyInitialization( 5711 InitializedEntity::InitializeParameter( 5712 FnDecl->getParamDecl(0)), 5713 SourceLocation(), 5714 Owned(Args[1])); 5715 if (Arg1.isInvalid()) 5716 return ExprError(); 5717 5718 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 5719 Method)) 5720 return ExprError(); 5721 5722 Args[1] = RHS = Arg1.takeAs<Expr>(); 5723 } else { 5724 // Convert the arguments. 5725 OwningExprResult Arg0 5726 = PerformCopyInitialization( 5727 InitializedEntity::InitializeParameter( 5728 FnDecl->getParamDecl(0)), 5729 SourceLocation(), 5730 Owned(Args[0])); 5731 if (Arg0.isInvalid()) 5732 return ExprError(); 5733 5734 OwningExprResult Arg1 5735 = PerformCopyInitialization( 5736 InitializedEntity::InitializeParameter( 5737 FnDecl->getParamDecl(1)), 5738 SourceLocation(), 5739 Owned(Args[1])); 5740 if (Arg1.isInvalid()) 5741 return ExprError(); 5742 Args[0] = LHS = Arg0.takeAs<Expr>(); 5743 Args[1] = RHS = Arg1.takeAs<Expr>(); 5744 } 5745 5746 // Determine the result type 5747 QualType ResultTy 5748 = FnDecl->getType()->getAs<FunctionType>()->getResultType(); 5749 ResultTy = ResultTy.getNonReferenceType(); 5750 5751 // Build the actual expression node. 5752 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 5753 OpLoc); 5754 UsualUnaryConversions(FnExpr); 5755 5756 ExprOwningPtr<CXXOperatorCallExpr> 5757 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr, 5758 Args, 2, ResultTy, 5759 OpLoc)); 5760 5761 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(), 5762 FnDecl)) 5763 return ExprError(); 5764 5765 return MaybeBindToTemporary(TheCall.release()); 5766 } else { 5767 // We matched a built-in operator. Convert the arguments, then 5768 // break out so that we will build the appropriate built-in 5769 // operator node. 5770 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 5771 Best->Conversions[0], AA_Passing) || 5772 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 5773 Best->Conversions[1], AA_Passing)) 5774 return ExprError(); 5775 5776 break; 5777 } 5778 } 5779 5780 case OR_No_Viable_Function: { 5781 // C++ [over.match.oper]p9: 5782 // If the operator is the operator , [...] and there are no 5783 // viable functions, then the operator is assumed to be the 5784 // built-in operator and interpreted according to clause 5. 5785 if (Opc == BinaryOperator::Comma) 5786 break; 5787 5788 // For class as left operand for assignment or compound assigment operator 5789 // do not fall through to handling in built-in, but report that no overloaded 5790 // assignment operator found 5791 OwningExprResult Result = ExprError(); 5792 if (Args[0]->getType()->isRecordType() && 5793 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) { 5794 Diag(OpLoc, diag::err_ovl_no_viable_oper) 5795 << BinaryOperator::getOpcodeStr(Opc) 5796 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 5797 } else { 5798 // No viable function; try to create a built-in operation, which will 5799 // produce an error. Then, show the non-viable candidates. 5800 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 5801 } 5802 assert(Result.isInvalid() && 5803 "C++ binary operator overloading is missing candidates!"); 5804 if (Result.isInvalid()) 5805 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2, 5806 BinaryOperator::getOpcodeStr(Opc), OpLoc); 5807 return move(Result); 5808 } 5809 5810 case OR_Ambiguous: 5811 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 5812 << BinaryOperator::getOpcodeStr(Opc) 5813 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 5814 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2, 5815 BinaryOperator::getOpcodeStr(Opc), OpLoc); 5816 return ExprError(); 5817 5818 case OR_Deleted: 5819 Diag(OpLoc, diag::err_ovl_deleted_oper) 5820 << Best->Function->isDeleted() 5821 << BinaryOperator::getOpcodeStr(Opc) 5822 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 5823 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2); 5824 return ExprError(); 5825 } 5826 5827 // We matched a built-in operator; build it. 5828 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 5829} 5830 5831Action::OwningExprResult 5832Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 5833 SourceLocation RLoc, 5834 ExprArg Base, ExprArg Idx) { 5835 Expr *Args[2] = { static_cast<Expr*>(Base.get()), 5836 static_cast<Expr*>(Idx.get()) }; 5837 DeclarationName OpName = 5838 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 5839 5840 // If either side is type-dependent, create an appropriate dependent 5841 // expression. 5842 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 5843 5844 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 5845 UnresolvedLookupExpr *Fn 5846 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass, 5847 0, SourceRange(), OpName, LLoc, 5848 /*ADL*/ true, /*Overloaded*/ false); 5849 // Can't add any actual overloads yet 5850 5851 Base.release(); 5852 Idx.release(); 5853 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 5854 Args, 2, 5855 Context.DependentTy, 5856 RLoc)); 5857 } 5858 5859 // Build an empty overload set. 5860 OverloadCandidateSet CandidateSet(LLoc); 5861 5862 // Subscript can only be overloaded as a member function. 5863 5864 // Add operator candidates that are member functions. 5865 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 5866 5867 // Add builtin operator candidates. 5868 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 5869 5870 // Perform overload resolution. 5871 OverloadCandidateSet::iterator Best; 5872 switch (BestViableFunction(CandidateSet, LLoc, Best)) { 5873 case OR_Success: { 5874 // We found a built-in operator or an overloaded operator. 5875 FunctionDecl *FnDecl = Best->Function; 5876 5877 if (FnDecl) { 5878 // We matched an overloaded operator. Build a call to that 5879 // operator. 5880 5881 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 5882 5883 // Convert the arguments. 5884 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 5885 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 5886 Method)) 5887 return ExprError(); 5888 5889 // Convert the arguments. 5890 OwningExprResult InputInit 5891 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 5892 FnDecl->getParamDecl(0)), 5893 SourceLocation(), 5894 Owned(Args[1])); 5895 if (InputInit.isInvalid()) 5896 return ExprError(); 5897 5898 Args[1] = InputInit.takeAs<Expr>(); 5899 5900 // Determine the result type 5901 QualType ResultTy 5902 = FnDecl->getType()->getAs<FunctionType>()->getResultType(); 5903 ResultTy = ResultTy.getNonReferenceType(); 5904 5905 // Build the actual expression node. 5906 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 5907 LLoc); 5908 UsualUnaryConversions(FnExpr); 5909 5910 Base.release(); 5911 Idx.release(); 5912 ExprOwningPtr<CXXOperatorCallExpr> 5913 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 5914 FnExpr, Args, 2, 5915 ResultTy, RLoc)); 5916 5917 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(), 5918 FnDecl)) 5919 return ExprError(); 5920 5921 return MaybeBindToTemporary(TheCall.release()); 5922 } else { 5923 // We matched a built-in operator. Convert the arguments, then 5924 // break out so that we will build the appropriate built-in 5925 // operator node. 5926 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 5927 Best->Conversions[0], AA_Passing) || 5928 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 5929 Best->Conversions[1], AA_Passing)) 5930 return ExprError(); 5931 5932 break; 5933 } 5934 } 5935 5936 case OR_No_Viable_Function: { 5937 if (CandidateSet.empty()) 5938 Diag(LLoc, diag::err_ovl_no_oper) 5939 << Args[0]->getType() << /*subscript*/ 0 5940 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 5941 else 5942 Diag(LLoc, diag::err_ovl_no_viable_subscript) 5943 << Args[0]->getType() 5944 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 5945 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2, 5946 "[]", LLoc); 5947 return ExprError(); 5948 } 5949 5950 case OR_Ambiguous: 5951 Diag(LLoc, diag::err_ovl_ambiguous_oper) 5952 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 5953 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2, 5954 "[]", LLoc); 5955 return ExprError(); 5956 5957 case OR_Deleted: 5958 Diag(LLoc, diag::err_ovl_deleted_oper) 5959 << Best->Function->isDeleted() << "[]" 5960 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 5961 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2, 5962 "[]", LLoc); 5963 return ExprError(); 5964 } 5965 5966 // We matched a built-in operator; build it. 5967 Base.release(); 5968 Idx.release(); 5969 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc, 5970 Owned(Args[1]), RLoc); 5971} 5972 5973/// BuildCallToMemberFunction - Build a call to a member 5974/// function. MemExpr is the expression that refers to the member 5975/// function (and includes the object parameter), Args/NumArgs are the 5976/// arguments to the function call (not including the object 5977/// parameter). The caller needs to validate that the member 5978/// expression refers to a member function or an overloaded member 5979/// function. 5980Sema::OwningExprResult 5981Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 5982 SourceLocation LParenLoc, Expr **Args, 5983 unsigned NumArgs, SourceLocation *CommaLocs, 5984 SourceLocation RParenLoc) { 5985 // Dig out the member expression. This holds both the object 5986 // argument and the member function we're referring to. 5987 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 5988 5989 MemberExpr *MemExpr; 5990 CXXMethodDecl *Method = 0; 5991 NestedNameSpecifier *Qualifier = 0; 5992 if (isa<MemberExpr>(NakedMemExpr)) { 5993 MemExpr = cast<MemberExpr>(NakedMemExpr); 5994 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 5995 Qualifier = MemExpr->getQualifier(); 5996 } else { 5997 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 5998 Qualifier = UnresExpr->getQualifier(); 5999 6000 QualType ObjectType = UnresExpr->getBaseType(); 6001 6002 // Add overload candidates 6003 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 6004 6005 // FIXME: avoid copy. 6006 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 6007 if (UnresExpr->hasExplicitTemplateArgs()) { 6008 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 6009 TemplateArgs = &TemplateArgsBuffer; 6010 } 6011 6012 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 6013 E = UnresExpr->decls_end(); I != E; ++I) { 6014 6015 NamedDecl *Func = *I; 6016 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 6017 if (isa<UsingShadowDecl>(Func)) 6018 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 6019 6020 if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 6021 // If explicit template arguments were provided, we can't call a 6022 // non-template member function. 6023 if (TemplateArgs) 6024 continue; 6025 6026 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 6027 Args, NumArgs, 6028 CandidateSet, /*SuppressUserConversions=*/false); 6029 } else { 6030 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 6031 I.getPair(), ActingDC, TemplateArgs, 6032 ObjectType, Args, NumArgs, 6033 CandidateSet, 6034 /*SuppressUsedConversions=*/false); 6035 } 6036 } 6037 6038 DeclarationName DeclName = UnresExpr->getMemberName(); 6039 6040 OverloadCandidateSet::iterator Best; 6041 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) { 6042 case OR_Success: 6043 Method = cast<CXXMethodDecl>(Best->Function); 6044 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 6045 break; 6046 6047 case OR_No_Viable_Function: 6048 Diag(UnresExpr->getMemberLoc(), 6049 diag::err_ovl_no_viable_member_function_in_call) 6050 << DeclName << MemExprE->getSourceRange(); 6051 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6052 // FIXME: Leaking incoming expressions! 6053 return ExprError(); 6054 6055 case OR_Ambiguous: 6056 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 6057 << DeclName << MemExprE->getSourceRange(); 6058 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6059 // FIXME: Leaking incoming expressions! 6060 return ExprError(); 6061 6062 case OR_Deleted: 6063 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 6064 << Best->Function->isDeleted() 6065 << DeclName << MemExprE->getSourceRange(); 6066 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6067 // FIXME: Leaking incoming expressions! 6068 return ExprError(); 6069 } 6070 6071 MemExprE = FixOverloadedFunctionReference(MemExprE, Method); 6072 6073 // If overload resolution picked a static member, build a 6074 // non-member call based on that function. 6075 if (Method->isStatic()) { 6076 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 6077 Args, NumArgs, RParenLoc); 6078 } 6079 6080 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 6081 } 6082 6083 assert(Method && "Member call to something that isn't a method?"); 6084 ExprOwningPtr<CXXMemberCallExpr> 6085 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 6086 NumArgs, 6087 Method->getResultType().getNonReferenceType(), 6088 RParenLoc)); 6089 6090 // Check for a valid return type. 6091 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 6092 TheCall.get(), Method)) 6093 return ExprError(); 6094 6095 // Convert the object argument (for a non-static member function call). 6096 Expr *ObjectArg = MemExpr->getBase(); 6097 if (!Method->isStatic() && 6098 PerformObjectArgumentInitialization(ObjectArg, Qualifier, Method)) 6099 return ExprError(); 6100 MemExpr->setBase(ObjectArg); 6101 6102 // Convert the rest of the arguments 6103 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType()); 6104 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs, 6105 RParenLoc)) 6106 return ExprError(); 6107 6108 if (CheckFunctionCall(Method, TheCall.get())) 6109 return ExprError(); 6110 6111 return MaybeBindToTemporary(TheCall.release()); 6112} 6113 6114/// BuildCallToObjectOfClassType - Build a call to an object of class 6115/// type (C++ [over.call.object]), which can end up invoking an 6116/// overloaded function call operator (@c operator()) or performing a 6117/// user-defined conversion on the object argument. 6118Sema::ExprResult 6119Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object, 6120 SourceLocation LParenLoc, 6121 Expr **Args, unsigned NumArgs, 6122 SourceLocation *CommaLocs, 6123 SourceLocation RParenLoc) { 6124 assert(Object->getType()->isRecordType() && "Requires object type argument"); 6125 const RecordType *Record = Object->getType()->getAs<RecordType>(); 6126 6127 // C++ [over.call.object]p1: 6128 // If the primary-expression E in the function call syntax 6129 // evaluates to a class object of type "cv T", then the set of 6130 // candidate functions includes at least the function call 6131 // operators of T. The function call operators of T are obtained by 6132 // ordinary lookup of the name operator() in the context of 6133 // (E).operator(). 6134 OverloadCandidateSet CandidateSet(LParenLoc); 6135 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 6136 6137 if (RequireCompleteType(LParenLoc, Object->getType(), 6138 PartialDiagnostic(diag::err_incomplete_object_call) 6139 << Object->getSourceRange())) 6140 return true; 6141 6142 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 6143 LookupQualifiedName(R, Record->getDecl()); 6144 R.suppressDiagnostics(); 6145 6146 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 6147 Oper != OperEnd; ++Oper) { 6148 AddMethodCandidate(Oper.getPair(), Object->getType(), 6149 Args, NumArgs, CandidateSet, 6150 /*SuppressUserConversions=*/ false); 6151 } 6152 6153 // C++ [over.call.object]p2: 6154 // In addition, for each conversion function declared in T of the 6155 // form 6156 // 6157 // operator conversion-type-id () cv-qualifier; 6158 // 6159 // where cv-qualifier is the same cv-qualification as, or a 6160 // greater cv-qualification than, cv, and where conversion-type-id 6161 // denotes the type "pointer to function of (P1,...,Pn) returning 6162 // R", or the type "reference to pointer to function of 6163 // (P1,...,Pn) returning R", or the type "reference to function 6164 // of (P1,...,Pn) returning R", a surrogate call function [...] 6165 // is also considered as a candidate function. Similarly, 6166 // surrogate call functions are added to the set of candidate 6167 // functions for each conversion function declared in an 6168 // accessible base class provided the function is not hidden 6169 // within T by another intervening declaration. 6170 const UnresolvedSetImpl *Conversions 6171 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 6172 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6173 E = Conversions->end(); I != E; ++I) { 6174 NamedDecl *D = *I; 6175 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 6176 if (isa<UsingShadowDecl>(D)) 6177 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6178 6179 // Skip over templated conversion functions; they aren't 6180 // surrogates. 6181 if (isa<FunctionTemplateDecl>(D)) 6182 continue; 6183 6184 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6185 6186 // Strip the reference type (if any) and then the pointer type (if 6187 // any) to get down to what might be a function type. 6188 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 6189 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 6190 ConvType = ConvPtrType->getPointeeType(); 6191 6192 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 6193 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 6194 Object->getType(), Args, NumArgs, 6195 CandidateSet); 6196 } 6197 6198 // Perform overload resolution. 6199 OverloadCandidateSet::iterator Best; 6200 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) { 6201 case OR_Success: 6202 // Overload resolution succeeded; we'll build the appropriate call 6203 // below. 6204 break; 6205 6206 case OR_No_Viable_Function: 6207 if (CandidateSet.empty()) 6208 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper) 6209 << Object->getType() << /*call*/ 1 6210 << Object->getSourceRange(); 6211 else 6212 Diag(Object->getSourceRange().getBegin(), 6213 diag::err_ovl_no_viable_object_call) 6214 << Object->getType() << Object->getSourceRange(); 6215 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6216 break; 6217 6218 case OR_Ambiguous: 6219 Diag(Object->getSourceRange().getBegin(), 6220 diag::err_ovl_ambiguous_object_call) 6221 << Object->getType() << Object->getSourceRange(); 6222 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs); 6223 break; 6224 6225 case OR_Deleted: 6226 Diag(Object->getSourceRange().getBegin(), 6227 diag::err_ovl_deleted_object_call) 6228 << Best->Function->isDeleted() 6229 << Object->getType() << Object->getSourceRange(); 6230 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs); 6231 break; 6232 } 6233 6234 if (Best == CandidateSet.end()) { 6235 // We had an error; delete all of the subexpressions and return 6236 // the error. 6237 Object->Destroy(Context); 6238 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 6239 Args[ArgIdx]->Destroy(Context); 6240 return true; 6241 } 6242 6243 if (Best->Function == 0) { 6244 // Since there is no function declaration, this is one of the 6245 // surrogate candidates. Dig out the conversion function. 6246 CXXConversionDecl *Conv 6247 = cast<CXXConversionDecl>( 6248 Best->Conversions[0].UserDefined.ConversionFunction); 6249 6250 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl); 6251 6252 // We selected one of the surrogate functions that converts the 6253 // object parameter to a function pointer. Perform the conversion 6254 // on the object argument, then let ActOnCallExpr finish the job. 6255 6256 // Create an implicit member expr to refer to the conversion operator. 6257 // and then call it. 6258 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv); 6259 6260 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc, 6261 MultiExprArg(*this, (ExprTy**)Args, NumArgs), 6262 CommaLocs, RParenLoc).release(); 6263 } 6264 6265 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl); 6266 6267 // We found an overloaded operator(). Build a CXXOperatorCallExpr 6268 // that calls this method, using Object for the implicit object 6269 // parameter and passing along the remaining arguments. 6270 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 6271 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>(); 6272 6273 unsigned NumArgsInProto = Proto->getNumArgs(); 6274 unsigned NumArgsToCheck = NumArgs; 6275 6276 // Build the full argument list for the method call (the 6277 // implicit object parameter is placed at the beginning of the 6278 // list). 6279 Expr **MethodArgs; 6280 if (NumArgs < NumArgsInProto) { 6281 NumArgsToCheck = NumArgsInProto; 6282 MethodArgs = new Expr*[NumArgsInProto + 1]; 6283 } else { 6284 MethodArgs = new Expr*[NumArgs + 1]; 6285 } 6286 MethodArgs[0] = Object; 6287 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 6288 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 6289 6290 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(), 6291 SourceLocation()); 6292 UsualUnaryConversions(NewFn); 6293 6294 // Once we've built TheCall, all of the expressions are properly 6295 // owned. 6296 QualType ResultTy = Method->getResultType().getNonReferenceType(); 6297 ExprOwningPtr<CXXOperatorCallExpr> 6298 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn, 6299 MethodArgs, NumArgs + 1, 6300 ResultTy, RParenLoc)); 6301 delete [] MethodArgs; 6302 6303 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(), 6304 Method)) 6305 return true; 6306 6307 // We may have default arguments. If so, we need to allocate more 6308 // slots in the call for them. 6309 if (NumArgs < NumArgsInProto) 6310 TheCall->setNumArgs(Context, NumArgsInProto + 1); 6311 else if (NumArgs > NumArgsInProto) 6312 NumArgsToCheck = NumArgsInProto; 6313 6314 bool IsError = false; 6315 6316 // Initialize the implicit object parameter. 6317 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0, 6318 Method); 6319 TheCall->setArg(0, Object); 6320 6321 6322 // Check the argument types. 6323 for (unsigned i = 0; i != NumArgsToCheck; i++) { 6324 Expr *Arg; 6325 if (i < NumArgs) { 6326 Arg = Args[i]; 6327 6328 // Pass the argument. 6329 6330 OwningExprResult InputInit 6331 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 6332 Method->getParamDecl(i)), 6333 SourceLocation(), Owned(Arg)); 6334 6335 IsError |= InputInit.isInvalid(); 6336 Arg = InputInit.takeAs<Expr>(); 6337 } else { 6338 OwningExprResult DefArg 6339 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 6340 if (DefArg.isInvalid()) { 6341 IsError = true; 6342 break; 6343 } 6344 6345 Arg = DefArg.takeAs<Expr>(); 6346 } 6347 6348 TheCall->setArg(i + 1, Arg); 6349 } 6350 6351 // If this is a variadic call, handle args passed through "...". 6352 if (Proto->isVariadic()) { 6353 // Promote the arguments (C99 6.5.2.2p7). 6354 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 6355 Expr *Arg = Args[i]; 6356 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod); 6357 TheCall->setArg(i + 1, Arg); 6358 } 6359 } 6360 6361 if (IsError) return true; 6362 6363 if (CheckFunctionCall(Method, TheCall.get())) 6364 return true; 6365 6366 return MaybeBindToTemporary(TheCall.release()).release(); 6367} 6368 6369/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 6370/// (if one exists), where @c Base is an expression of class type and 6371/// @c Member is the name of the member we're trying to find. 6372Sema::OwningExprResult 6373Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) { 6374 Expr *Base = static_cast<Expr *>(BaseIn.get()); 6375 assert(Base->getType()->isRecordType() && "left-hand side must have class type"); 6376 6377 SourceLocation Loc = Base->getExprLoc(); 6378 6379 // C++ [over.ref]p1: 6380 // 6381 // [...] An expression x->m is interpreted as (x.operator->())->m 6382 // for a class object x of type T if T::operator->() exists and if 6383 // the operator is selected as the best match function by the 6384 // overload resolution mechanism (13.3). 6385 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 6386 OverloadCandidateSet CandidateSet(Loc); 6387 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 6388 6389 if (RequireCompleteType(Loc, Base->getType(), 6390 PDiag(diag::err_typecheck_incomplete_tag) 6391 << Base->getSourceRange())) 6392 return ExprError(); 6393 6394 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 6395 LookupQualifiedName(R, BaseRecord->getDecl()); 6396 R.suppressDiagnostics(); 6397 6398 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 6399 Oper != OperEnd; ++Oper) { 6400 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet, 6401 /*SuppressUserConversions=*/false); 6402 } 6403 6404 // Perform overload resolution. 6405 OverloadCandidateSet::iterator Best; 6406 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 6407 case OR_Success: 6408 // Overload resolution succeeded; we'll build the call below. 6409 break; 6410 6411 case OR_No_Viable_Function: 6412 if (CandidateSet.empty()) 6413 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 6414 << Base->getType() << Base->getSourceRange(); 6415 else 6416 Diag(OpLoc, diag::err_ovl_no_viable_oper) 6417 << "operator->" << Base->getSourceRange(); 6418 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1); 6419 return ExprError(); 6420 6421 case OR_Ambiguous: 6422 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 6423 << "->" << Base->getSourceRange(); 6424 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1); 6425 return ExprError(); 6426 6427 case OR_Deleted: 6428 Diag(OpLoc, diag::err_ovl_deleted_oper) 6429 << Best->Function->isDeleted() 6430 << "->" << Base->getSourceRange(); 6431 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1); 6432 return ExprError(); 6433 } 6434 6435 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 6436 6437 // Convert the object parameter. 6438 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 6439 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, Method)) 6440 return ExprError(); 6441 6442 // No concerns about early exits now. 6443 BaseIn.release(); 6444 6445 // Build the operator call. 6446 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(), 6447 SourceLocation()); 6448 UsualUnaryConversions(FnExpr); 6449 6450 QualType ResultTy = Method->getResultType().getNonReferenceType(); 6451 ExprOwningPtr<CXXOperatorCallExpr> 6452 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, 6453 &Base, 1, ResultTy, OpLoc)); 6454 6455 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(), 6456 Method)) 6457 return ExprError(); 6458 return move(TheCall); 6459} 6460 6461/// FixOverloadedFunctionReference - E is an expression that refers to 6462/// a C++ overloaded function (possibly with some parentheses and 6463/// perhaps a '&' around it). We have resolved the overloaded function 6464/// to the function declaration Fn, so patch up the expression E to 6465/// refer (possibly indirectly) to Fn. Returns the new expr. 6466Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) { 6467 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 6468 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn); 6469 if (SubExpr == PE->getSubExpr()) 6470 return PE->Retain(); 6471 6472 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 6473 } 6474 6475 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6476 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn); 6477 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 6478 SubExpr->getType()) && 6479 "Implicit cast type cannot be determined from overload"); 6480 if (SubExpr == ICE->getSubExpr()) 6481 return ICE->Retain(); 6482 6483 return new (Context) ImplicitCastExpr(ICE->getType(), 6484 ICE->getCastKind(), 6485 SubExpr, 6486 ICE->isLvalueCast()); 6487 } 6488 6489 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 6490 assert(UnOp->getOpcode() == UnaryOperator::AddrOf && 6491 "Can only take the address of an overloaded function"); 6492 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 6493 if (Method->isStatic()) { 6494 // Do nothing: static member functions aren't any different 6495 // from non-member functions. 6496 } else { 6497 // Fix the sub expression, which really has to be an 6498 // UnresolvedLookupExpr holding an overloaded member function 6499 // or template. 6500 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn); 6501 if (SubExpr == UnOp->getSubExpr()) 6502 return UnOp->Retain(); 6503 6504 assert(isa<DeclRefExpr>(SubExpr) 6505 && "fixed to something other than a decl ref"); 6506 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 6507 && "fixed to a member ref with no nested name qualifier"); 6508 6509 // We have taken the address of a pointer to member 6510 // function. Perform the computation here so that we get the 6511 // appropriate pointer to member type. 6512 QualType ClassType 6513 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 6514 QualType MemPtrType 6515 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 6516 6517 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf, 6518 MemPtrType, UnOp->getOperatorLoc()); 6519 } 6520 } 6521 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn); 6522 if (SubExpr == UnOp->getSubExpr()) 6523 return UnOp->Retain(); 6524 6525 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf, 6526 Context.getPointerType(SubExpr->getType()), 6527 UnOp->getOperatorLoc()); 6528 } 6529 6530 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 6531 // FIXME: avoid copy. 6532 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 6533 if (ULE->hasExplicitTemplateArgs()) { 6534 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 6535 TemplateArgs = &TemplateArgsBuffer; 6536 } 6537 6538 return DeclRefExpr::Create(Context, 6539 ULE->getQualifier(), 6540 ULE->getQualifierRange(), 6541 Fn, 6542 ULE->getNameLoc(), 6543 Fn->getType(), 6544 TemplateArgs); 6545 } 6546 6547 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 6548 // FIXME: avoid copy. 6549 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 6550 if (MemExpr->hasExplicitTemplateArgs()) { 6551 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 6552 TemplateArgs = &TemplateArgsBuffer; 6553 } 6554 6555 Expr *Base; 6556 6557 // If we're filling in 6558 if (MemExpr->isImplicitAccess()) { 6559 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 6560 return DeclRefExpr::Create(Context, 6561 MemExpr->getQualifier(), 6562 MemExpr->getQualifierRange(), 6563 Fn, 6564 MemExpr->getMemberLoc(), 6565 Fn->getType(), 6566 TemplateArgs); 6567 } else { 6568 SourceLocation Loc = MemExpr->getMemberLoc(); 6569 if (MemExpr->getQualifier()) 6570 Loc = MemExpr->getQualifierRange().getBegin(); 6571 Base = new (Context) CXXThisExpr(Loc, 6572 MemExpr->getBaseType(), 6573 /*isImplicit=*/true); 6574 } 6575 } else 6576 Base = MemExpr->getBase()->Retain(); 6577 6578 return MemberExpr::Create(Context, Base, 6579 MemExpr->isArrow(), 6580 MemExpr->getQualifier(), 6581 MemExpr->getQualifierRange(), 6582 Fn, 6583 MemExpr->getMemberLoc(), 6584 TemplateArgs, 6585 Fn->getType()); 6586 } 6587 6588 assert(false && "Invalid reference to overloaded function"); 6589 return E->Retain(); 6590} 6591 6592Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E, 6593 FunctionDecl *Fn) { 6594 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn)); 6595} 6596 6597} // end namespace clang 6598