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