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