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