SemaOverload.cpp revision f6778cab8aa6004205ed04418f9fba6fa8b0b5b5
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, /*ExplicitArgs*/ 0, 1423 &From, 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 // Overload resolution is always an unevaluated context. 2244 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 2245 2246 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 2247 // C++ [class.copy]p3: 2248 // A member function template is never instantiated to perform the copy 2249 // of a class object to an object of its class type. 2250 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 2251 if (NumArgs == 1 && 2252 Constructor->isCopyConstructorLikeSpecialization() && 2253 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType())) 2254 return; 2255 } 2256 2257 // Add this candidate 2258 CandidateSet.push_back(OverloadCandidate()); 2259 OverloadCandidate& Candidate = CandidateSet.back(); 2260 Candidate.Function = Function; 2261 Candidate.Viable = true; 2262 Candidate.IsSurrogate = false; 2263 Candidate.IgnoreObjectArgument = false; 2264 2265 unsigned NumArgsInProto = Proto->getNumArgs(); 2266 2267 // (C++ 13.3.2p2): A candidate function having fewer than m 2268 // parameters is viable only if it has an ellipsis in its parameter 2269 // list (8.3.5). 2270 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto && 2271 !Proto->isVariadic()) { 2272 Candidate.Viable = false; 2273 return; 2274 } 2275 2276 // (C++ 13.3.2p2): A candidate function having more than m parameters 2277 // is viable only if the (m+1)st parameter has a default argument 2278 // (8.3.6). For the purposes of overload resolution, the 2279 // parameter list is truncated on the right, so that there are 2280 // exactly m parameters. 2281 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 2282 if (NumArgs < MinRequiredArgs && !PartialOverloading) { 2283 // Not enough arguments. 2284 Candidate.Viable = false; 2285 return; 2286 } 2287 2288 // Determine the implicit conversion sequences for each of the 2289 // arguments. 2290 Candidate.Conversions.resize(NumArgs); 2291 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2292 if (ArgIdx < NumArgsInProto) { 2293 // (C++ 13.3.2p3): for F to be a viable function, there shall 2294 // exist for each argument an implicit conversion sequence 2295 // (13.3.3.1) that converts that argument to the corresponding 2296 // parameter of F. 2297 QualType ParamType = Proto->getArgType(ArgIdx); 2298 Candidate.Conversions[ArgIdx] 2299 = TryCopyInitialization(Args[ArgIdx], ParamType, 2300 SuppressUserConversions, ForceRValue, 2301 /*InOverloadResolution=*/true); 2302 if (Candidate.Conversions[ArgIdx].ConversionKind 2303 == ImplicitConversionSequence::BadConversion) { 2304 // 13.3.3.1-p10 If several different sequences of conversions exist that 2305 // each convert the argument to the parameter type, the implicit conversion 2306 // sequence associated with the parameter is defined to be the unique conversion 2307 // sequence designated the ambiguous conversion sequence. For the purpose of 2308 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous 2309 // conversion sequence is treated as a user-defined sequence that is 2310 // indistinguishable from any other user-defined conversion sequence 2311 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) { 2312 Candidate.Conversions[ArgIdx].ConversionKind = 2313 ImplicitConversionSequence::UserDefinedConversion; 2314 // Set the conversion function to one of them. As due to ambiguity, 2315 // they carry the same weight and is needed for overload resolution 2316 // later. 2317 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction = 2318 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0]; 2319 } 2320 else { 2321 Candidate.Viable = false; 2322 break; 2323 } 2324 } 2325 } else { 2326 // (C++ 13.3.2p2): For the purposes of overload resolution, any 2327 // argument for which there is no corresponding parameter is 2328 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 2329 Candidate.Conversions[ArgIdx].ConversionKind 2330 = ImplicitConversionSequence::EllipsisConversion; 2331 } 2332 } 2333} 2334 2335/// \brief Add all of the function declarations in the given function set to 2336/// the overload canddiate set. 2337void Sema::AddFunctionCandidates(const FunctionSet &Functions, 2338 Expr **Args, unsigned NumArgs, 2339 OverloadCandidateSet& CandidateSet, 2340 bool SuppressUserConversions) { 2341 for (FunctionSet::const_iterator F = Functions.begin(), 2342 FEnd = Functions.end(); 2343 F != FEnd; ++F) { 2344 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) { 2345 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2346 AddMethodCandidate(cast<CXXMethodDecl>(FD), 2347 Args[0], Args + 1, NumArgs - 1, 2348 CandidateSet, SuppressUserConversions); 2349 else 2350 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet, 2351 SuppressUserConversions); 2352 } else { 2353 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F); 2354 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 2355 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 2356 AddMethodTemplateCandidate(FunTmpl, 2357 /*FIXME: explicit args */ 0, 2358 Args[0], Args + 1, NumArgs - 1, 2359 CandidateSet, 2360 SuppressUserConversions); 2361 else 2362 AddTemplateOverloadCandidate(FunTmpl, 2363 /*FIXME: explicit args */ 0, 2364 Args, NumArgs, CandidateSet, 2365 SuppressUserConversions); 2366 } 2367 } 2368} 2369 2370/// AddMethodCandidate - Adds a named decl (which is some kind of 2371/// method) as a method candidate to the given overload set. 2372void Sema::AddMethodCandidate(NamedDecl *Decl, Expr *Object, 2373 Expr **Args, unsigned NumArgs, 2374 OverloadCandidateSet& CandidateSet, 2375 bool SuppressUserConversions, bool ForceRValue) { 2376 2377 // FIXME: use this 2378 //DeclContext *ActingContext = Decl->getDeclContext(); 2379 2380 if (isa<UsingShadowDecl>(Decl)) 2381 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 2382 2383 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 2384 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 2385 "Expected a member function template"); 2386 AddMethodTemplateCandidate(TD, /*ExplicitArgs*/ 0, 2387 Object, Args, NumArgs, 2388 CandidateSet, 2389 SuppressUserConversions, 2390 ForceRValue); 2391 } else { 2392 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Object, Args, NumArgs, 2393 CandidateSet, SuppressUserConversions, ForceRValue); 2394 } 2395} 2396 2397/// AddMethodCandidate - Adds the given C++ member function to the set 2398/// of candidate functions, using the given function call arguments 2399/// and the object argument (@c Object). For example, in a call 2400/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 2401/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 2402/// allow user-defined conversions via constructors or conversion 2403/// operators. If @p ForceRValue, treat all arguments as rvalues. This is 2404/// a slightly hacky way to implement the overloading rules for elidable copy 2405/// initialization in C++0x (C++0x 12.8p15). 2406void 2407Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object, 2408 Expr **Args, unsigned NumArgs, 2409 OverloadCandidateSet& CandidateSet, 2410 bool SuppressUserConversions, bool ForceRValue) { 2411 const FunctionProtoType* Proto 2412 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 2413 assert(Proto && "Methods without a prototype cannot be overloaded"); 2414 assert(!isa<CXXConversionDecl>(Method) && 2415 "Use AddConversionCandidate for conversion functions"); 2416 assert(!isa<CXXConstructorDecl>(Method) && 2417 "Use AddOverloadCandidate for constructors"); 2418 2419 if (!CandidateSet.isNewCandidate(Method)) 2420 return; 2421 2422 // Overload resolution is always an unevaluated context. 2423 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 2424 2425 // Add this candidate 2426 CandidateSet.push_back(OverloadCandidate()); 2427 OverloadCandidate& Candidate = CandidateSet.back(); 2428 Candidate.Function = Method; 2429 Candidate.IsSurrogate = false; 2430 Candidate.IgnoreObjectArgument = false; 2431 2432 unsigned NumArgsInProto = Proto->getNumArgs(); 2433 2434 // (C++ 13.3.2p2): A candidate function having fewer than m 2435 // parameters is viable only if it has an ellipsis in its parameter 2436 // list (8.3.5). 2437 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 2438 Candidate.Viable = false; 2439 return; 2440 } 2441 2442 // (C++ 13.3.2p2): A candidate function having more than m parameters 2443 // is viable only if the (m+1)st parameter has a default argument 2444 // (8.3.6). For the purposes of overload resolution, the 2445 // parameter list is truncated on the right, so that there are 2446 // exactly m parameters. 2447 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 2448 if (NumArgs < MinRequiredArgs) { 2449 // Not enough arguments. 2450 Candidate.Viable = false; 2451 return; 2452 } 2453 2454 Candidate.Viable = true; 2455 Candidate.Conversions.resize(NumArgs + 1); 2456 2457 if (Method->isStatic() || !Object) 2458 // The implicit object argument is ignored. 2459 Candidate.IgnoreObjectArgument = true; 2460 else { 2461 // Determine the implicit conversion sequence for the object 2462 // parameter. 2463 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method); 2464 if (Candidate.Conversions[0].ConversionKind 2465 == ImplicitConversionSequence::BadConversion) { 2466 Candidate.Viable = false; 2467 return; 2468 } 2469 } 2470 2471 // Determine the implicit conversion sequences for each of the 2472 // arguments. 2473 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2474 if (ArgIdx < NumArgsInProto) { 2475 // (C++ 13.3.2p3): for F to be a viable function, there shall 2476 // exist for each argument an implicit conversion sequence 2477 // (13.3.3.1) that converts that argument to the corresponding 2478 // parameter of F. 2479 QualType ParamType = Proto->getArgType(ArgIdx); 2480 Candidate.Conversions[ArgIdx + 1] 2481 = TryCopyInitialization(Args[ArgIdx], ParamType, 2482 SuppressUserConversions, ForceRValue, 2483 /*InOverloadResolution=*/true); 2484 if (Candidate.Conversions[ArgIdx + 1].ConversionKind 2485 == ImplicitConversionSequence::BadConversion) { 2486 Candidate.Viable = false; 2487 break; 2488 } 2489 } else { 2490 // (C++ 13.3.2p2): For the purposes of overload resolution, any 2491 // argument for which there is no corresponding parameter is 2492 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 2493 Candidate.Conversions[ArgIdx + 1].ConversionKind 2494 = ImplicitConversionSequence::EllipsisConversion; 2495 } 2496 } 2497} 2498 2499/// \brief Add a C++ member function template as a candidate to the candidate 2500/// set, using template argument deduction to produce an appropriate member 2501/// function template specialization. 2502void 2503Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 2504 const TemplateArgumentListInfo *ExplicitTemplateArgs, 2505 Expr *Object, Expr **Args, unsigned NumArgs, 2506 OverloadCandidateSet& CandidateSet, 2507 bool SuppressUserConversions, 2508 bool ForceRValue) { 2509 if (!CandidateSet.isNewCandidate(MethodTmpl)) 2510 return; 2511 2512 // C++ [over.match.funcs]p7: 2513 // In each case where a candidate is a function template, candidate 2514 // function template specializations are generated using template argument 2515 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 2516 // candidate functions in the usual way.113) A given name can refer to one 2517 // or more function templates and also to a set of overloaded non-template 2518 // functions. In such a case, the candidate functions generated from each 2519 // function template are combined with the set of non-template candidate 2520 // functions. 2521 TemplateDeductionInfo Info(Context); 2522 FunctionDecl *Specialization = 0; 2523 if (TemplateDeductionResult Result 2524 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, 2525 Args, NumArgs, Specialization, Info)) { 2526 // FIXME: Record what happened with template argument deduction, so 2527 // that we can give the user a beautiful diagnostic. 2528 (void)Result; 2529 return; 2530 } 2531 2532 // Add the function template specialization produced by template argument 2533 // deduction as a candidate. 2534 assert(Specialization && "Missing member function template specialization?"); 2535 assert(isa<CXXMethodDecl>(Specialization) && 2536 "Specialization is not a member function?"); 2537 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs, 2538 CandidateSet, SuppressUserConversions, ForceRValue); 2539} 2540 2541/// \brief Add a C++ function template specialization as a candidate 2542/// in the candidate set, using template argument deduction to produce 2543/// an appropriate function template specialization. 2544void 2545Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 2546 const TemplateArgumentListInfo *ExplicitTemplateArgs, 2547 Expr **Args, unsigned NumArgs, 2548 OverloadCandidateSet& CandidateSet, 2549 bool SuppressUserConversions, 2550 bool ForceRValue) { 2551 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 2552 return; 2553 2554 // C++ [over.match.funcs]p7: 2555 // In each case where a candidate is a function template, candidate 2556 // function template specializations are generated using template argument 2557 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 2558 // candidate functions in the usual way.113) A given name can refer to one 2559 // or more function templates and also to a set of overloaded non-template 2560 // functions. In such a case, the candidate functions generated from each 2561 // function template are combined with the set of non-template candidate 2562 // functions. 2563 TemplateDeductionInfo Info(Context); 2564 FunctionDecl *Specialization = 0; 2565 if (TemplateDeductionResult Result 2566 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 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 // Overload resolution is always an unevaluated context. 2598 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 2599 2600 // Add this candidate 2601 CandidateSet.push_back(OverloadCandidate()); 2602 OverloadCandidate& Candidate = CandidateSet.back(); 2603 Candidate.Function = Conversion; 2604 Candidate.IsSurrogate = false; 2605 Candidate.IgnoreObjectArgument = false; 2606 Candidate.FinalConversion.setAsIdentityConversion(); 2607 Candidate.FinalConversion.FromTypePtr 2608 = Conversion->getConversionType().getAsOpaquePtr(); 2609 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr(); 2610 2611 // Determine the implicit conversion sequence for the implicit 2612 // object parameter. 2613 Candidate.Viable = true; 2614 Candidate.Conversions.resize(1); 2615 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion); 2616 // Conversion functions to a different type in the base class is visible in 2617 // the derived class. So, a derived to base conversion should not participate 2618 // in overload resolution. 2619 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base) 2620 Candidate.Conversions[0].Standard.Second = ICK_Identity; 2621 if (Candidate.Conversions[0].ConversionKind 2622 == ImplicitConversionSequence::BadConversion) { 2623 Candidate.Viable = false; 2624 return; 2625 } 2626 2627 // We won't go through a user-define type conversion function to convert a 2628 // derived to base as such conversions are given Conversion Rank. They only 2629 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 2630 QualType FromCanon 2631 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 2632 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 2633 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 2634 Candidate.Viable = false; 2635 return; 2636 } 2637 2638 2639 // To determine what the conversion from the result of calling the 2640 // conversion function to the type we're eventually trying to 2641 // convert to (ToType), we need to synthesize a call to the 2642 // conversion function and attempt copy initialization from it. This 2643 // makes sure that we get the right semantics with respect to 2644 // lvalues/rvalues and the type. Fortunately, we can allocate this 2645 // call on the stack and we don't need its arguments to be 2646 // well-formed. 2647 DeclRefExpr ConversionRef(Conversion, Conversion->getType(), 2648 From->getLocStart()); 2649 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()), 2650 CastExpr::CK_FunctionToPointerDecay, 2651 &ConversionRef, false); 2652 2653 // Note that it is safe to allocate CallExpr on the stack here because 2654 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 2655 // allocator). 2656 CallExpr Call(Context, &ConversionFn, 0, 0, 2657 Conversion->getConversionType().getNonReferenceType(), 2658 From->getLocStart()); 2659 ImplicitConversionSequence ICS = 2660 TryCopyInitialization(&Call, ToType, 2661 /*SuppressUserConversions=*/true, 2662 /*ForceRValue=*/false, 2663 /*InOverloadResolution=*/false); 2664 2665 switch (ICS.ConversionKind) { 2666 case ImplicitConversionSequence::StandardConversion: 2667 Candidate.FinalConversion = ICS.Standard; 2668 break; 2669 2670 case ImplicitConversionSequence::BadConversion: 2671 Candidate.Viable = false; 2672 break; 2673 2674 default: 2675 assert(false && 2676 "Can only end up with a standard conversion sequence or failure"); 2677 } 2678} 2679 2680/// \brief Adds a conversion function template specialization 2681/// candidate to the overload set, using template argument deduction 2682/// to deduce the template arguments of the conversion function 2683/// template from the type that we are converting to (C++ 2684/// [temp.deduct.conv]). 2685void 2686Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 2687 Expr *From, QualType ToType, 2688 OverloadCandidateSet &CandidateSet) { 2689 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 2690 "Only conversion function templates permitted here"); 2691 2692 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 2693 return; 2694 2695 TemplateDeductionInfo Info(Context); 2696 CXXConversionDecl *Specialization = 0; 2697 if (TemplateDeductionResult Result 2698 = DeduceTemplateArguments(FunctionTemplate, ToType, 2699 Specialization, Info)) { 2700 // FIXME: Record what happened with template argument deduction, so 2701 // that we can give the user a beautiful diagnostic. 2702 (void)Result; 2703 return; 2704 } 2705 2706 // Add the conversion function template specialization produced by 2707 // template argument deduction as a candidate. 2708 assert(Specialization && "Missing function template specialization?"); 2709 AddConversionCandidate(Specialization, From, ToType, CandidateSet); 2710} 2711 2712/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 2713/// converts the given @c Object to a function pointer via the 2714/// conversion function @c Conversion, and then attempts to call it 2715/// with the given arguments (C++ [over.call.object]p2-4). Proto is 2716/// the type of function that we'll eventually be calling. 2717void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 2718 const FunctionProtoType *Proto, 2719 Expr *Object, Expr **Args, unsigned NumArgs, 2720 OverloadCandidateSet& CandidateSet) { 2721 if (!CandidateSet.isNewCandidate(Conversion)) 2722 return; 2723 2724 // Overload resolution is always an unevaluated context. 2725 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 2726 2727 CandidateSet.push_back(OverloadCandidate()); 2728 OverloadCandidate& Candidate = CandidateSet.back(); 2729 Candidate.Function = 0; 2730 Candidate.Surrogate = Conversion; 2731 Candidate.Viable = true; 2732 Candidate.IsSurrogate = true; 2733 Candidate.IgnoreObjectArgument = false; 2734 Candidate.Conversions.resize(NumArgs + 1); 2735 2736 // Determine the implicit conversion sequence for the implicit 2737 // object parameter. 2738 ImplicitConversionSequence ObjectInit 2739 = TryObjectArgumentInitialization(Object, Conversion); 2740 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) { 2741 Candidate.Viable = false; 2742 return; 2743 } 2744 2745 // The first conversion is actually a user-defined conversion whose 2746 // first conversion is ObjectInit's standard conversion (which is 2747 // effectively a reference binding). Record it as such. 2748 Candidate.Conversions[0].ConversionKind 2749 = ImplicitConversionSequence::UserDefinedConversion; 2750 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 2751 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 2752 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 2753 Candidate.Conversions[0].UserDefined.After 2754 = Candidate.Conversions[0].UserDefined.Before; 2755 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 2756 2757 // Find the 2758 unsigned NumArgsInProto = Proto->getNumArgs(); 2759 2760 // (C++ 13.3.2p2): A candidate function having fewer than m 2761 // parameters is viable only if it has an ellipsis in its parameter 2762 // list (8.3.5). 2763 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 2764 Candidate.Viable = false; 2765 return; 2766 } 2767 2768 // Function types don't have any default arguments, so just check if 2769 // we have enough arguments. 2770 if (NumArgs < NumArgsInProto) { 2771 // Not enough arguments. 2772 Candidate.Viable = false; 2773 return; 2774 } 2775 2776 // Determine the implicit conversion sequences for each of the 2777 // arguments. 2778 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2779 if (ArgIdx < NumArgsInProto) { 2780 // (C++ 13.3.2p3): for F to be a viable function, there shall 2781 // exist for each argument an implicit conversion sequence 2782 // (13.3.3.1) that converts that argument to the corresponding 2783 // parameter of F. 2784 QualType ParamType = Proto->getArgType(ArgIdx); 2785 Candidate.Conversions[ArgIdx + 1] 2786 = TryCopyInitialization(Args[ArgIdx], ParamType, 2787 /*SuppressUserConversions=*/false, 2788 /*ForceRValue=*/false, 2789 /*InOverloadResolution=*/false); 2790 if (Candidate.Conversions[ArgIdx + 1].ConversionKind 2791 == ImplicitConversionSequence::BadConversion) { 2792 Candidate.Viable = false; 2793 break; 2794 } 2795 } else { 2796 // (C++ 13.3.2p2): For the purposes of overload resolution, any 2797 // argument for which there is no corresponding parameter is 2798 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 2799 Candidate.Conversions[ArgIdx + 1].ConversionKind 2800 = ImplicitConversionSequence::EllipsisConversion; 2801 } 2802 } 2803} 2804 2805// FIXME: This will eventually be removed, once we've migrated all of the 2806// operator overloading logic over to the scheme used by binary operators, which 2807// works for template instantiation. 2808void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S, 2809 SourceLocation OpLoc, 2810 Expr **Args, unsigned NumArgs, 2811 OverloadCandidateSet& CandidateSet, 2812 SourceRange OpRange) { 2813 FunctionSet Functions; 2814 2815 QualType T1 = Args[0]->getType(); 2816 QualType T2; 2817 if (NumArgs > 1) 2818 T2 = Args[1]->getType(); 2819 2820 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 2821 if (S) 2822 LookupOverloadedOperatorName(Op, S, T1, T2, Functions); 2823 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions); 2824 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet); 2825 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange); 2826 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet); 2827} 2828 2829/// \brief Add overload candidates for overloaded operators that are 2830/// member functions. 2831/// 2832/// Add the overloaded operator candidates that are member functions 2833/// for the operator Op that was used in an operator expression such 2834/// as "x Op y". , Args/NumArgs provides the operator arguments, and 2835/// CandidateSet will store the added overload candidates. (C++ 2836/// [over.match.oper]). 2837void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 2838 SourceLocation OpLoc, 2839 Expr **Args, unsigned NumArgs, 2840 OverloadCandidateSet& CandidateSet, 2841 SourceRange OpRange) { 2842 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 2843 2844 // C++ [over.match.oper]p3: 2845 // For a unary operator @ with an operand of a type whose 2846 // cv-unqualified version is T1, and for a binary operator @ with 2847 // a left operand of a type whose cv-unqualified version is T1 and 2848 // a right operand of a type whose cv-unqualified version is T2, 2849 // three sets of candidate functions, designated member 2850 // candidates, non-member candidates and built-in candidates, are 2851 // constructed as follows: 2852 QualType T1 = Args[0]->getType(); 2853 QualType T2; 2854 if (NumArgs > 1) 2855 T2 = Args[1]->getType(); 2856 2857 // -- If T1 is a class type, the set of member candidates is the 2858 // result of the qualified lookup of T1::operator@ 2859 // (13.3.1.1.1); otherwise, the set of member candidates is 2860 // empty. 2861 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 2862 // Complete the type if it can be completed. Otherwise, we're done. 2863 if (RequireCompleteType(OpLoc, T1, PDiag())) 2864 return; 2865 2866 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 2867 LookupQualifiedName(Operators, T1Rec->getDecl()); 2868 Operators.suppressDiagnostics(); 2869 2870 for (LookupResult::iterator Oper = Operators.begin(), 2871 OperEnd = Operators.end(); 2872 Oper != OperEnd; 2873 ++Oper) 2874 AddMethodCandidate(*Oper, Args[0], Args + 1, NumArgs - 1, CandidateSet, 2875 /* SuppressUserConversions = */ false); 2876 } 2877} 2878 2879/// AddBuiltinCandidate - Add a candidate for a built-in 2880/// operator. ResultTy and ParamTys are the result and parameter types 2881/// of the built-in candidate, respectively. Args and NumArgs are the 2882/// arguments being passed to the candidate. IsAssignmentOperator 2883/// should be true when this built-in candidate is an assignment 2884/// operator. NumContextualBoolArguments is the number of arguments 2885/// (at the beginning of the argument list) that will be contextually 2886/// converted to bool. 2887void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 2888 Expr **Args, unsigned NumArgs, 2889 OverloadCandidateSet& CandidateSet, 2890 bool IsAssignmentOperator, 2891 unsigned NumContextualBoolArguments) { 2892 // Overload resolution is always an unevaluated context. 2893 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated); 2894 2895 // Add this candidate 2896 CandidateSet.push_back(OverloadCandidate()); 2897 OverloadCandidate& Candidate = CandidateSet.back(); 2898 Candidate.Function = 0; 2899 Candidate.IsSurrogate = false; 2900 Candidate.IgnoreObjectArgument = false; 2901 Candidate.BuiltinTypes.ResultTy = ResultTy; 2902 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 2903 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 2904 2905 // Determine the implicit conversion sequences for each of the 2906 // arguments. 2907 Candidate.Viable = true; 2908 Candidate.Conversions.resize(NumArgs); 2909 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2910 // C++ [over.match.oper]p4: 2911 // For the built-in assignment operators, conversions of the 2912 // left operand are restricted as follows: 2913 // -- no temporaries are introduced to hold the left operand, and 2914 // -- no user-defined conversions are applied to the left 2915 // operand to achieve a type match with the left-most 2916 // parameter of a built-in candidate. 2917 // 2918 // We block these conversions by turning off user-defined 2919 // conversions, since that is the only way that initialization of 2920 // a reference to a non-class type can occur from something that 2921 // is not of the same type. 2922 if (ArgIdx < NumContextualBoolArguments) { 2923 assert(ParamTys[ArgIdx] == Context.BoolTy && 2924 "Contextual conversion to bool requires bool type"); 2925 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]); 2926 } else { 2927 Candidate.Conversions[ArgIdx] 2928 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], 2929 ArgIdx == 0 && IsAssignmentOperator, 2930 /*ForceRValue=*/false, 2931 /*InOverloadResolution=*/false); 2932 } 2933 if (Candidate.Conversions[ArgIdx].ConversionKind 2934 == ImplicitConversionSequence::BadConversion) { 2935 Candidate.Viable = false; 2936 break; 2937 } 2938 } 2939} 2940 2941/// BuiltinCandidateTypeSet - A set of types that will be used for the 2942/// candidate operator functions for built-in operators (C++ 2943/// [over.built]). The types are separated into pointer types and 2944/// enumeration types. 2945class BuiltinCandidateTypeSet { 2946 /// TypeSet - A set of types. 2947 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 2948 2949 /// PointerTypes - The set of pointer types that will be used in the 2950 /// built-in candidates. 2951 TypeSet PointerTypes; 2952 2953 /// MemberPointerTypes - The set of member pointer types that will be 2954 /// used in the built-in candidates. 2955 TypeSet MemberPointerTypes; 2956 2957 /// EnumerationTypes - The set of enumeration types that will be 2958 /// used in the built-in candidates. 2959 TypeSet EnumerationTypes; 2960 2961 /// Sema - The semantic analysis instance where we are building the 2962 /// candidate type set. 2963 Sema &SemaRef; 2964 2965 /// Context - The AST context in which we will build the type sets. 2966 ASTContext &Context; 2967 2968 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 2969 const Qualifiers &VisibleQuals); 2970 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 2971 2972public: 2973 /// iterator - Iterates through the types that are part of the set. 2974 typedef TypeSet::iterator iterator; 2975 2976 BuiltinCandidateTypeSet(Sema &SemaRef) 2977 : SemaRef(SemaRef), Context(SemaRef.Context) { } 2978 2979 void AddTypesConvertedFrom(QualType Ty, 2980 SourceLocation Loc, 2981 bool AllowUserConversions, 2982 bool AllowExplicitConversions, 2983 const Qualifiers &VisibleTypeConversionsQuals); 2984 2985 /// pointer_begin - First pointer type found; 2986 iterator pointer_begin() { return PointerTypes.begin(); } 2987 2988 /// pointer_end - Past the last pointer type found; 2989 iterator pointer_end() { return PointerTypes.end(); } 2990 2991 /// member_pointer_begin - First member pointer type found; 2992 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 2993 2994 /// member_pointer_end - Past the last member pointer type found; 2995 iterator member_pointer_end() { return MemberPointerTypes.end(); } 2996 2997 /// enumeration_begin - First enumeration type found; 2998 iterator enumeration_begin() { return EnumerationTypes.begin(); } 2999 3000 /// enumeration_end - Past the last enumeration type found; 3001 iterator enumeration_end() { return EnumerationTypes.end(); } 3002}; 3003 3004/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 3005/// the set of pointer types along with any more-qualified variants of 3006/// that type. For example, if @p Ty is "int const *", this routine 3007/// will add "int const *", "int const volatile *", "int const 3008/// restrict *", and "int const volatile restrict *" to the set of 3009/// pointer types. Returns true if the add of @p Ty itself succeeded, 3010/// false otherwise. 3011/// 3012/// FIXME: what to do about extended qualifiers? 3013bool 3014BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 3015 const Qualifiers &VisibleQuals) { 3016 3017 // Insert this type. 3018 if (!PointerTypes.insert(Ty)) 3019 return false; 3020 3021 const PointerType *PointerTy = Ty->getAs<PointerType>(); 3022 assert(PointerTy && "type was not a pointer type!"); 3023 3024 QualType PointeeTy = PointerTy->getPointeeType(); 3025 // Don't add qualified variants of arrays. For one, they're not allowed 3026 // (the qualifier would sink to the element type), and for another, the 3027 // only overload situation where it matters is subscript or pointer +- int, 3028 // and those shouldn't have qualifier variants anyway. 3029 if (PointeeTy->isArrayType()) 3030 return true; 3031 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 3032 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy)) 3033 BaseCVR = Array->getElementType().getCVRQualifiers(); 3034 bool hasVolatile = VisibleQuals.hasVolatile(); 3035 bool hasRestrict = VisibleQuals.hasRestrict(); 3036 3037 // Iterate through all strict supersets of BaseCVR. 3038 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 3039 if ((CVR | BaseCVR) != CVR) continue; 3040 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere 3041 // in the types. 3042 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 3043 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue; 3044 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 3045 PointerTypes.insert(Context.getPointerType(QPointeeTy)); 3046 } 3047 3048 return true; 3049} 3050 3051/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 3052/// to the set of pointer types along with any more-qualified variants of 3053/// that type. For example, if @p Ty is "int const *", this routine 3054/// will add "int const *", "int const volatile *", "int const 3055/// restrict *", and "int const volatile restrict *" to the set of 3056/// pointer types. Returns true if the add of @p Ty itself succeeded, 3057/// false otherwise. 3058/// 3059/// FIXME: what to do about extended qualifiers? 3060bool 3061BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 3062 QualType Ty) { 3063 // Insert this type. 3064 if (!MemberPointerTypes.insert(Ty)) 3065 return false; 3066 3067 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 3068 assert(PointerTy && "type was not a member pointer type!"); 3069 3070 QualType PointeeTy = PointerTy->getPointeeType(); 3071 // Don't add qualified variants of arrays. For one, they're not allowed 3072 // (the qualifier would sink to the element type), and for another, the 3073 // only overload situation where it matters is subscript or pointer +- int, 3074 // and those shouldn't have qualifier variants anyway. 3075 if (PointeeTy->isArrayType()) 3076 return true; 3077 const Type *ClassTy = PointerTy->getClass(); 3078 3079 // Iterate through all strict supersets of the pointee type's CVR 3080 // qualifiers. 3081 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 3082 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 3083 if ((CVR | BaseCVR) != CVR) continue; 3084 3085 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 3086 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy)); 3087 } 3088 3089 return true; 3090} 3091 3092/// AddTypesConvertedFrom - Add each of the types to which the type @p 3093/// Ty can be implicit converted to the given set of @p Types. We're 3094/// primarily interested in pointer types and enumeration types. We also 3095/// take member pointer types, for the conditional operator. 3096/// AllowUserConversions is true if we should look at the conversion 3097/// functions of a class type, and AllowExplicitConversions if we 3098/// should also include the explicit conversion functions of a class 3099/// type. 3100void 3101BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 3102 SourceLocation Loc, 3103 bool AllowUserConversions, 3104 bool AllowExplicitConversions, 3105 const Qualifiers &VisibleQuals) { 3106 // Only deal with canonical types. 3107 Ty = Context.getCanonicalType(Ty); 3108 3109 // Look through reference types; they aren't part of the type of an 3110 // expression for the purposes of conversions. 3111 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 3112 Ty = RefTy->getPointeeType(); 3113 3114 // We don't care about qualifiers on the type. 3115 Ty = Ty.getLocalUnqualifiedType(); 3116 3117 // If we're dealing with an array type, decay to the pointer. 3118 if (Ty->isArrayType()) 3119 Ty = SemaRef.Context.getArrayDecayedType(Ty); 3120 3121 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) { 3122 QualType PointeeTy = PointerTy->getPointeeType(); 3123 3124 // Insert our type, and its more-qualified variants, into the set 3125 // of types. 3126 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 3127 return; 3128 } else if (Ty->isMemberPointerType()) { 3129 // Member pointers are far easier, since the pointee can't be converted. 3130 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 3131 return; 3132 } else if (Ty->isEnumeralType()) { 3133 EnumerationTypes.insert(Ty); 3134 } else if (AllowUserConversions) { 3135 if (const RecordType *TyRec = Ty->getAs<RecordType>()) { 3136 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) { 3137 // No conversion functions in incomplete types. 3138 return; 3139 } 3140 3141 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 3142 const UnresolvedSet *Conversions 3143 = ClassDecl->getVisibleConversionFunctions(); 3144 for (UnresolvedSet::iterator I = Conversions->begin(), 3145 E = Conversions->end(); I != E; ++I) { 3146 3147 // Skip conversion function templates; they don't tell us anything 3148 // about which builtin types we can convert to. 3149 if (isa<FunctionTemplateDecl>(*I)) 3150 continue; 3151 3152 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I); 3153 if (AllowExplicitConversions || !Conv->isExplicit()) { 3154 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 3155 VisibleQuals); 3156 } 3157 } 3158 } 3159 } 3160} 3161 3162/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 3163/// the volatile- and non-volatile-qualified assignment operators for the 3164/// given type to the candidate set. 3165static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 3166 QualType T, 3167 Expr **Args, 3168 unsigned NumArgs, 3169 OverloadCandidateSet &CandidateSet) { 3170 QualType ParamTypes[2]; 3171 3172 // T& operator=(T&, T) 3173 ParamTypes[0] = S.Context.getLValueReferenceType(T); 3174 ParamTypes[1] = T; 3175 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3176 /*IsAssignmentOperator=*/true); 3177 3178 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 3179 // volatile T& operator=(volatile T&, T) 3180 ParamTypes[0] 3181 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 3182 ParamTypes[1] = T; 3183 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3184 /*IsAssignmentOperator=*/true); 3185 } 3186} 3187 3188/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 3189/// if any, found in visible type conversion functions found in ArgExpr's type. 3190static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 3191 Qualifiers VRQuals; 3192 const RecordType *TyRec; 3193 if (const MemberPointerType *RHSMPType = 3194 ArgExpr->getType()->getAs<MemberPointerType>()) 3195 TyRec = cast<RecordType>(RHSMPType->getClass()); 3196 else 3197 TyRec = ArgExpr->getType()->getAs<RecordType>(); 3198 if (!TyRec) { 3199 // Just to be safe, assume the worst case. 3200 VRQuals.addVolatile(); 3201 VRQuals.addRestrict(); 3202 return VRQuals; 3203 } 3204 3205 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 3206 const UnresolvedSet *Conversions = 3207 ClassDecl->getVisibleConversionFunctions(); 3208 3209 for (UnresolvedSet::iterator I = Conversions->begin(), 3210 E = Conversions->end(); I != E; ++I) { 3211 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) { 3212 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 3213 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 3214 CanTy = ResTypeRef->getPointeeType(); 3215 // Need to go down the pointer/mempointer chain and add qualifiers 3216 // as see them. 3217 bool done = false; 3218 while (!done) { 3219 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 3220 CanTy = ResTypePtr->getPointeeType(); 3221 else if (const MemberPointerType *ResTypeMPtr = 3222 CanTy->getAs<MemberPointerType>()) 3223 CanTy = ResTypeMPtr->getPointeeType(); 3224 else 3225 done = true; 3226 if (CanTy.isVolatileQualified()) 3227 VRQuals.addVolatile(); 3228 if (CanTy.isRestrictQualified()) 3229 VRQuals.addRestrict(); 3230 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 3231 return VRQuals; 3232 } 3233 } 3234 } 3235 return VRQuals; 3236} 3237 3238/// AddBuiltinOperatorCandidates - Add the appropriate built-in 3239/// operator overloads to the candidate set (C++ [over.built]), based 3240/// on the operator @p Op and the arguments given. For example, if the 3241/// operator is a binary '+', this routine might add "int 3242/// operator+(int, int)" to cover integer addition. 3243void 3244Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 3245 SourceLocation OpLoc, 3246 Expr **Args, unsigned NumArgs, 3247 OverloadCandidateSet& CandidateSet) { 3248 // The set of "promoted arithmetic types", which are the arithmetic 3249 // types are that preserved by promotion (C++ [over.built]p2). Note 3250 // that the first few of these types are the promoted integral 3251 // types; these types need to be first. 3252 // FIXME: What about complex? 3253 const unsigned FirstIntegralType = 0; 3254 const unsigned LastIntegralType = 13; 3255 const unsigned FirstPromotedIntegralType = 7, 3256 LastPromotedIntegralType = 13; 3257 const unsigned FirstPromotedArithmeticType = 7, 3258 LastPromotedArithmeticType = 16; 3259 const unsigned NumArithmeticTypes = 16; 3260 QualType ArithmeticTypes[NumArithmeticTypes] = { 3261 Context.BoolTy, Context.CharTy, Context.WCharTy, 3262// FIXME: Context.Char16Ty, Context.Char32Ty, 3263 Context.SignedCharTy, Context.ShortTy, 3264 Context.UnsignedCharTy, Context.UnsignedShortTy, 3265 Context.IntTy, Context.LongTy, Context.LongLongTy, 3266 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy, 3267 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy 3268 }; 3269 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy && 3270 "Invalid first promoted integral type"); 3271 assert(ArithmeticTypes[LastPromotedIntegralType - 1] 3272 == Context.UnsignedLongLongTy && 3273 "Invalid last promoted integral type"); 3274 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy && 3275 "Invalid first promoted arithmetic type"); 3276 assert(ArithmeticTypes[LastPromotedArithmeticType - 1] 3277 == Context.LongDoubleTy && 3278 "Invalid last promoted arithmetic type"); 3279 3280 // Find all of the types that the arguments can convert to, but only 3281 // if the operator we're looking at has built-in operator candidates 3282 // that make use of these types. 3283 Qualifiers VisibleTypeConversionsQuals; 3284 VisibleTypeConversionsQuals.addConst(); 3285 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 3286 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 3287 3288 BuiltinCandidateTypeSet CandidateTypes(*this); 3289 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual || 3290 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual || 3291 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal || 3292 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript || 3293 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus || 3294 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) { 3295 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 3296 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(), 3297 OpLoc, 3298 true, 3299 (Op == OO_Exclaim || 3300 Op == OO_AmpAmp || 3301 Op == OO_PipePipe), 3302 VisibleTypeConversionsQuals); 3303 } 3304 3305 bool isComparison = false; 3306 switch (Op) { 3307 case OO_None: 3308 case NUM_OVERLOADED_OPERATORS: 3309 assert(false && "Expected an overloaded operator"); 3310 break; 3311 3312 case OO_Star: // '*' is either unary or binary 3313 if (NumArgs == 1) 3314 goto UnaryStar; 3315 else 3316 goto BinaryStar; 3317 break; 3318 3319 case OO_Plus: // '+' is either unary or binary 3320 if (NumArgs == 1) 3321 goto UnaryPlus; 3322 else 3323 goto BinaryPlus; 3324 break; 3325 3326 case OO_Minus: // '-' is either unary or binary 3327 if (NumArgs == 1) 3328 goto UnaryMinus; 3329 else 3330 goto BinaryMinus; 3331 break; 3332 3333 case OO_Amp: // '&' is either unary or binary 3334 if (NumArgs == 1) 3335 goto UnaryAmp; 3336 else 3337 goto BinaryAmp; 3338 3339 case OO_PlusPlus: 3340 case OO_MinusMinus: 3341 // C++ [over.built]p3: 3342 // 3343 // For every pair (T, VQ), where T is an arithmetic type, and VQ 3344 // is either volatile or empty, there exist candidate operator 3345 // functions of the form 3346 // 3347 // VQ T& operator++(VQ T&); 3348 // T operator++(VQ T&, int); 3349 // 3350 // C++ [over.built]p4: 3351 // 3352 // For every pair (T, VQ), where T is an arithmetic type other 3353 // than bool, and VQ is either volatile or empty, there exist 3354 // candidate operator functions of the form 3355 // 3356 // VQ T& operator--(VQ T&); 3357 // T operator--(VQ T&, int); 3358 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 3359 Arith < NumArithmeticTypes; ++Arith) { 3360 QualType ArithTy = ArithmeticTypes[Arith]; 3361 QualType ParamTypes[2] 3362 = { Context.getLValueReferenceType(ArithTy), Context.IntTy }; 3363 3364 // Non-volatile version. 3365 if (NumArgs == 1) 3366 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 3367 else 3368 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 3369 // heuristic to reduce number of builtin candidates in the set. 3370 // Add volatile version only if there are conversions to a volatile type. 3371 if (VisibleTypeConversionsQuals.hasVolatile()) { 3372 // Volatile version 3373 ParamTypes[0] 3374 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy)); 3375 if (NumArgs == 1) 3376 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 3377 else 3378 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 3379 } 3380 } 3381 3382 // C++ [over.built]p5: 3383 // 3384 // For every pair (T, VQ), where T is a cv-qualified or 3385 // cv-unqualified object type, and VQ is either volatile or 3386 // empty, there exist candidate operator functions of the form 3387 // 3388 // T*VQ& operator++(T*VQ&); 3389 // T*VQ& operator--(T*VQ&); 3390 // T* operator++(T*VQ&, int); 3391 // T* operator--(T*VQ&, int); 3392 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 3393 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3394 // Skip pointer types that aren't pointers to object types. 3395 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType()) 3396 continue; 3397 3398 QualType ParamTypes[2] = { 3399 Context.getLValueReferenceType(*Ptr), Context.IntTy 3400 }; 3401 3402 // Without volatile 3403 if (NumArgs == 1) 3404 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 3405 else 3406 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 3407 3408 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() && 3409 VisibleTypeConversionsQuals.hasVolatile()) { 3410 // With volatile 3411 ParamTypes[0] 3412 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr)); 3413 if (NumArgs == 1) 3414 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 3415 else 3416 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 3417 } 3418 } 3419 break; 3420 3421 UnaryStar: 3422 // C++ [over.built]p6: 3423 // For every cv-qualified or cv-unqualified object type T, there 3424 // exist candidate operator functions of the form 3425 // 3426 // T& operator*(T*); 3427 // 3428 // C++ [over.built]p7: 3429 // For every function type T, there exist candidate operator 3430 // functions of the form 3431 // T& operator*(T*); 3432 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 3433 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3434 QualType ParamTy = *Ptr; 3435 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType(); 3436 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy), 3437 &ParamTy, Args, 1, CandidateSet); 3438 } 3439 break; 3440 3441 UnaryPlus: 3442 // C++ [over.built]p8: 3443 // For every type T, there exist candidate operator functions of 3444 // the form 3445 // 3446 // T* operator+(T*); 3447 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 3448 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3449 QualType ParamTy = *Ptr; 3450 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 3451 } 3452 3453 // Fall through 3454 3455 UnaryMinus: 3456 // C++ [over.built]p9: 3457 // For every promoted arithmetic type T, there exist candidate 3458 // operator functions of the form 3459 // 3460 // T operator+(T); 3461 // T operator-(T); 3462 for (unsigned Arith = FirstPromotedArithmeticType; 3463 Arith < LastPromotedArithmeticType; ++Arith) { 3464 QualType ArithTy = ArithmeticTypes[Arith]; 3465 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 3466 } 3467 break; 3468 3469 case OO_Tilde: 3470 // C++ [over.built]p10: 3471 // For every promoted integral type T, there exist candidate 3472 // operator functions of the form 3473 // 3474 // T operator~(T); 3475 for (unsigned Int = FirstPromotedIntegralType; 3476 Int < LastPromotedIntegralType; ++Int) { 3477 QualType IntTy = ArithmeticTypes[Int]; 3478 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 3479 } 3480 break; 3481 3482 case OO_New: 3483 case OO_Delete: 3484 case OO_Array_New: 3485 case OO_Array_Delete: 3486 case OO_Call: 3487 assert(false && "Special operators don't use AddBuiltinOperatorCandidates"); 3488 break; 3489 3490 case OO_Comma: 3491 UnaryAmp: 3492 case OO_Arrow: 3493 // C++ [over.match.oper]p3: 3494 // -- For the operator ',', the unary operator '&', or the 3495 // operator '->', the built-in candidates set is empty. 3496 break; 3497 3498 case OO_EqualEqual: 3499 case OO_ExclaimEqual: 3500 // C++ [over.match.oper]p16: 3501 // For every pointer to member type T, there exist candidate operator 3502 // functions of the form 3503 // 3504 // bool operator==(T,T); 3505 // bool operator!=(T,T); 3506 for (BuiltinCandidateTypeSet::iterator 3507 MemPtr = CandidateTypes.member_pointer_begin(), 3508 MemPtrEnd = CandidateTypes.member_pointer_end(); 3509 MemPtr != MemPtrEnd; 3510 ++MemPtr) { 3511 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 3512 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 3513 } 3514 3515 // Fall through 3516 3517 case OO_Less: 3518 case OO_Greater: 3519 case OO_LessEqual: 3520 case OO_GreaterEqual: 3521 // C++ [over.built]p15: 3522 // 3523 // For every pointer or enumeration type T, there exist 3524 // candidate operator functions of the form 3525 // 3526 // bool operator<(T, T); 3527 // bool operator>(T, T); 3528 // bool operator<=(T, T); 3529 // bool operator>=(T, T); 3530 // bool operator==(T, T); 3531 // bool operator!=(T, T); 3532 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 3533 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3534 QualType ParamTypes[2] = { *Ptr, *Ptr }; 3535 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 3536 } 3537 for (BuiltinCandidateTypeSet::iterator Enum 3538 = CandidateTypes.enumeration_begin(); 3539 Enum != CandidateTypes.enumeration_end(); ++Enum) { 3540 QualType ParamTypes[2] = { *Enum, *Enum }; 3541 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 3542 } 3543 3544 // Fall through. 3545 isComparison = true; 3546 3547 BinaryPlus: 3548 BinaryMinus: 3549 if (!isComparison) { 3550 // We didn't fall through, so we must have OO_Plus or OO_Minus. 3551 3552 // C++ [over.built]p13: 3553 // 3554 // For every cv-qualified or cv-unqualified object type T 3555 // there exist candidate operator functions of the form 3556 // 3557 // T* operator+(T*, ptrdiff_t); 3558 // T& operator[](T*, ptrdiff_t); [BELOW] 3559 // T* operator-(T*, ptrdiff_t); 3560 // T* operator+(ptrdiff_t, T*); 3561 // T& operator[](ptrdiff_t, T*); [BELOW] 3562 // 3563 // C++ [over.built]p14: 3564 // 3565 // For every T, where T is a pointer to object type, there 3566 // exist candidate operator functions of the form 3567 // 3568 // ptrdiff_t operator-(T, T); 3569 for (BuiltinCandidateTypeSet::iterator Ptr 3570 = CandidateTypes.pointer_begin(); 3571 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3572 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 3573 3574 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 3575 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 3576 3577 if (Op == OO_Plus) { 3578 // T* operator+(ptrdiff_t, T*); 3579 ParamTypes[0] = ParamTypes[1]; 3580 ParamTypes[1] = *Ptr; 3581 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 3582 } else { 3583 // ptrdiff_t operator-(T, T); 3584 ParamTypes[1] = *Ptr; 3585 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes, 3586 Args, 2, CandidateSet); 3587 } 3588 } 3589 } 3590 // Fall through 3591 3592 case OO_Slash: 3593 BinaryStar: 3594 Conditional: 3595 // C++ [over.built]p12: 3596 // 3597 // For every pair of promoted arithmetic types L and R, there 3598 // exist candidate operator functions of the form 3599 // 3600 // LR operator*(L, R); 3601 // LR operator/(L, R); 3602 // LR operator+(L, R); 3603 // LR operator-(L, R); 3604 // bool operator<(L, R); 3605 // bool operator>(L, R); 3606 // bool operator<=(L, R); 3607 // bool operator>=(L, R); 3608 // bool operator==(L, R); 3609 // bool operator!=(L, R); 3610 // 3611 // where LR is the result of the usual arithmetic conversions 3612 // between types L and R. 3613 // 3614 // C++ [over.built]p24: 3615 // 3616 // For every pair of promoted arithmetic types L and R, there exist 3617 // candidate operator functions of the form 3618 // 3619 // LR operator?(bool, L, R); 3620 // 3621 // where LR is the result of the usual arithmetic conversions 3622 // between types L and R. 3623 // Our candidates ignore the first parameter. 3624 for (unsigned Left = FirstPromotedArithmeticType; 3625 Left < LastPromotedArithmeticType; ++Left) { 3626 for (unsigned Right = FirstPromotedArithmeticType; 3627 Right < LastPromotedArithmeticType; ++Right) { 3628 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 3629 QualType Result 3630 = isComparison 3631 ? Context.BoolTy 3632 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]); 3633 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 3634 } 3635 } 3636 break; 3637 3638 case OO_Percent: 3639 BinaryAmp: 3640 case OO_Caret: 3641 case OO_Pipe: 3642 case OO_LessLess: 3643 case OO_GreaterGreater: 3644 // C++ [over.built]p17: 3645 // 3646 // For every pair of promoted integral types L and R, there 3647 // exist candidate operator functions of the form 3648 // 3649 // LR operator%(L, R); 3650 // LR operator&(L, R); 3651 // LR operator^(L, R); 3652 // LR operator|(L, R); 3653 // L operator<<(L, R); 3654 // L operator>>(L, R); 3655 // 3656 // where LR is the result of the usual arithmetic conversions 3657 // between types L and R. 3658 for (unsigned Left = FirstPromotedIntegralType; 3659 Left < LastPromotedIntegralType; ++Left) { 3660 for (unsigned Right = FirstPromotedIntegralType; 3661 Right < LastPromotedIntegralType; ++Right) { 3662 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 3663 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 3664 ? LandR[0] 3665 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]); 3666 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 3667 } 3668 } 3669 break; 3670 3671 case OO_Equal: 3672 // C++ [over.built]p20: 3673 // 3674 // For every pair (T, VQ), where T is an enumeration or 3675 // pointer to member type and VQ is either volatile or 3676 // empty, there exist candidate operator functions of the form 3677 // 3678 // VQ T& operator=(VQ T&, T); 3679 for (BuiltinCandidateTypeSet::iterator 3680 Enum = CandidateTypes.enumeration_begin(), 3681 EnumEnd = CandidateTypes.enumeration_end(); 3682 Enum != EnumEnd; ++Enum) 3683 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2, 3684 CandidateSet); 3685 for (BuiltinCandidateTypeSet::iterator 3686 MemPtr = CandidateTypes.member_pointer_begin(), 3687 MemPtrEnd = CandidateTypes.member_pointer_end(); 3688 MemPtr != MemPtrEnd; ++MemPtr) 3689 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2, 3690 CandidateSet); 3691 // Fall through. 3692 3693 case OO_PlusEqual: 3694 case OO_MinusEqual: 3695 // C++ [over.built]p19: 3696 // 3697 // For every pair (T, VQ), where T is any type and VQ is either 3698 // volatile or empty, there exist candidate operator functions 3699 // of the form 3700 // 3701 // T*VQ& operator=(T*VQ&, T*); 3702 // 3703 // C++ [over.built]p21: 3704 // 3705 // For every pair (T, VQ), where T is a cv-qualified or 3706 // cv-unqualified object type and VQ is either volatile or 3707 // empty, there exist candidate operator functions of the form 3708 // 3709 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 3710 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 3711 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 3712 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3713 QualType ParamTypes[2]; 3714 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType(); 3715 3716 // non-volatile version 3717 ParamTypes[0] = Context.getLValueReferenceType(*Ptr); 3718 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3719 /*IsAssigmentOperator=*/Op == OO_Equal); 3720 3721 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() && 3722 VisibleTypeConversionsQuals.hasVolatile()) { 3723 // volatile version 3724 ParamTypes[0] 3725 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr)); 3726 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3727 /*IsAssigmentOperator=*/Op == OO_Equal); 3728 } 3729 } 3730 // Fall through. 3731 3732 case OO_StarEqual: 3733 case OO_SlashEqual: 3734 // C++ [over.built]p18: 3735 // 3736 // For every triple (L, VQ, R), where L is an arithmetic type, 3737 // VQ is either volatile or empty, and R is a promoted 3738 // arithmetic type, there exist candidate operator functions of 3739 // the form 3740 // 3741 // VQ L& operator=(VQ L&, R); 3742 // VQ L& operator*=(VQ L&, R); 3743 // VQ L& operator/=(VQ L&, R); 3744 // VQ L& operator+=(VQ L&, R); 3745 // VQ L& operator-=(VQ L&, R); 3746 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 3747 for (unsigned Right = FirstPromotedArithmeticType; 3748 Right < LastPromotedArithmeticType; ++Right) { 3749 QualType ParamTypes[2]; 3750 ParamTypes[1] = ArithmeticTypes[Right]; 3751 3752 // Add this built-in operator as a candidate (VQ is empty). 3753 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]); 3754 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3755 /*IsAssigmentOperator=*/Op == OO_Equal); 3756 3757 // Add this built-in operator as a candidate (VQ is 'volatile'). 3758 if (VisibleTypeConversionsQuals.hasVolatile()) { 3759 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]); 3760 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]); 3761 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 3762 /*IsAssigmentOperator=*/Op == OO_Equal); 3763 } 3764 } 3765 } 3766 break; 3767 3768 case OO_PercentEqual: 3769 case OO_LessLessEqual: 3770 case OO_GreaterGreaterEqual: 3771 case OO_AmpEqual: 3772 case OO_CaretEqual: 3773 case OO_PipeEqual: 3774 // C++ [over.built]p22: 3775 // 3776 // For every triple (L, VQ, R), where L is an integral type, VQ 3777 // is either volatile or empty, and R is a promoted integral 3778 // type, there exist candidate operator functions of the form 3779 // 3780 // VQ L& operator%=(VQ L&, R); 3781 // VQ L& operator<<=(VQ L&, R); 3782 // VQ L& operator>>=(VQ L&, R); 3783 // VQ L& operator&=(VQ L&, R); 3784 // VQ L& operator^=(VQ L&, R); 3785 // VQ L& operator|=(VQ L&, R); 3786 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 3787 for (unsigned Right = FirstPromotedIntegralType; 3788 Right < LastPromotedIntegralType; ++Right) { 3789 QualType ParamTypes[2]; 3790 ParamTypes[1] = ArithmeticTypes[Right]; 3791 3792 // Add this built-in operator as a candidate (VQ is empty). 3793 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]); 3794 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 3795 if (VisibleTypeConversionsQuals.hasVolatile()) { 3796 // Add this built-in operator as a candidate (VQ is 'volatile'). 3797 ParamTypes[0] = ArithmeticTypes[Left]; 3798 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]); 3799 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]); 3800 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 3801 } 3802 } 3803 } 3804 break; 3805 3806 case OO_Exclaim: { 3807 // C++ [over.operator]p23: 3808 // 3809 // There also exist candidate operator functions of the form 3810 // 3811 // bool operator!(bool); 3812 // bool operator&&(bool, bool); [BELOW] 3813 // bool operator||(bool, bool); [BELOW] 3814 QualType ParamTy = Context.BoolTy; 3815 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 3816 /*IsAssignmentOperator=*/false, 3817 /*NumContextualBoolArguments=*/1); 3818 break; 3819 } 3820 3821 case OO_AmpAmp: 3822 case OO_PipePipe: { 3823 // C++ [over.operator]p23: 3824 // 3825 // There also exist candidate operator functions of the form 3826 // 3827 // bool operator!(bool); [ABOVE] 3828 // bool operator&&(bool, bool); 3829 // bool operator||(bool, bool); 3830 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy }; 3831 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 3832 /*IsAssignmentOperator=*/false, 3833 /*NumContextualBoolArguments=*/2); 3834 break; 3835 } 3836 3837 case OO_Subscript: 3838 // C++ [over.built]p13: 3839 // 3840 // For every cv-qualified or cv-unqualified object type T there 3841 // exist candidate operator functions of the form 3842 // 3843 // T* operator+(T*, ptrdiff_t); [ABOVE] 3844 // T& operator[](T*, ptrdiff_t); 3845 // T* operator-(T*, ptrdiff_t); [ABOVE] 3846 // T* operator+(ptrdiff_t, T*); [ABOVE] 3847 // T& operator[](ptrdiff_t, T*); 3848 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 3849 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3850 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 3851 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType(); 3852 QualType ResultTy = Context.getLValueReferenceType(PointeeType); 3853 3854 // T& operator[](T*, ptrdiff_t) 3855 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 3856 3857 // T& operator[](ptrdiff_t, T*); 3858 ParamTypes[0] = ParamTypes[1]; 3859 ParamTypes[1] = *Ptr; 3860 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 3861 } 3862 break; 3863 3864 case OO_ArrowStar: 3865 // C++ [over.built]p11: 3866 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 3867 // C1 is the same type as C2 or is a derived class of C2, T is an object 3868 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 3869 // there exist candidate operator functions of the form 3870 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 3871 // where CV12 is the union of CV1 and CV2. 3872 { 3873 for (BuiltinCandidateTypeSet::iterator Ptr = 3874 CandidateTypes.pointer_begin(); 3875 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 3876 QualType C1Ty = (*Ptr); 3877 QualType C1; 3878 QualifierCollector Q1; 3879 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) { 3880 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0); 3881 if (!isa<RecordType>(C1)) 3882 continue; 3883 // heuristic to reduce number of builtin candidates in the set. 3884 // Add volatile/restrict version only if there are conversions to a 3885 // volatile/restrict type. 3886 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 3887 continue; 3888 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 3889 continue; 3890 } 3891 for (BuiltinCandidateTypeSet::iterator 3892 MemPtr = CandidateTypes.member_pointer_begin(), 3893 MemPtrEnd = CandidateTypes.member_pointer_end(); 3894 MemPtr != MemPtrEnd; ++MemPtr) { 3895 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 3896 QualType C2 = QualType(mptr->getClass(), 0); 3897 C2 = C2.getUnqualifiedType(); 3898 if (C1 != C2 && !IsDerivedFrom(C1, C2)) 3899 break; 3900 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 3901 // build CV12 T& 3902 QualType T = mptr->getPointeeType(); 3903 if (!VisibleTypeConversionsQuals.hasVolatile() && 3904 T.isVolatileQualified()) 3905 continue; 3906 if (!VisibleTypeConversionsQuals.hasRestrict() && 3907 T.isRestrictQualified()) 3908 continue; 3909 T = Q1.apply(T); 3910 QualType ResultTy = Context.getLValueReferenceType(T); 3911 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 3912 } 3913 } 3914 } 3915 break; 3916 3917 case OO_Conditional: 3918 // Note that we don't consider the first argument, since it has been 3919 // contextually converted to bool long ago. The candidates below are 3920 // therefore added as binary. 3921 // 3922 // C++ [over.built]p24: 3923 // For every type T, where T is a pointer or pointer-to-member type, 3924 // there exist candidate operator functions of the form 3925 // 3926 // T operator?(bool, T, T); 3927 // 3928 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(), 3929 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) { 3930 QualType ParamTypes[2] = { *Ptr, *Ptr }; 3931 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 3932 } 3933 for (BuiltinCandidateTypeSet::iterator Ptr = 3934 CandidateTypes.member_pointer_begin(), 3935 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) { 3936 QualType ParamTypes[2] = { *Ptr, *Ptr }; 3937 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 3938 } 3939 goto Conditional; 3940 } 3941} 3942 3943/// \brief Add function candidates found via argument-dependent lookup 3944/// to the set of overloading candidates. 3945/// 3946/// This routine performs argument-dependent name lookup based on the 3947/// given function name (which may also be an operator name) and adds 3948/// all of the overload candidates found by ADL to the overload 3949/// candidate set (C++ [basic.lookup.argdep]). 3950void 3951Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 3952 Expr **Args, unsigned NumArgs, 3953 const TemplateArgumentListInfo *ExplicitTemplateArgs, 3954 OverloadCandidateSet& CandidateSet, 3955 bool PartialOverloading) { 3956 FunctionSet Functions; 3957 3958 // FIXME: Should we be trafficking in canonical function decls throughout? 3959 3960 // Record all of the function candidates that we've already 3961 // added to the overload set, so that we don't add those same 3962 // candidates a second time. 3963 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 3964 CandEnd = CandidateSet.end(); 3965 Cand != CandEnd; ++Cand) 3966 if (Cand->Function) { 3967 Functions.insert(Cand->Function); 3968 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 3969 Functions.insert(FunTmpl); 3970 } 3971 3972 // FIXME: Pass in the explicit template arguments? 3973 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions); 3974 3975 // Erase all of the candidates we already knew about. 3976 // FIXME: This is suboptimal. Is there a better way? 3977 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 3978 CandEnd = CandidateSet.end(); 3979 Cand != CandEnd; ++Cand) 3980 if (Cand->Function) { 3981 Functions.erase(Cand->Function); 3982 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 3983 Functions.erase(FunTmpl); 3984 } 3985 3986 // For each of the ADL candidates we found, add it to the overload 3987 // set. 3988 for (FunctionSet::iterator Func = Functions.begin(), 3989 FuncEnd = Functions.end(); 3990 Func != FuncEnd; ++Func) { 3991 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) { 3992 if (ExplicitTemplateArgs) 3993 continue; 3994 3995 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet, 3996 false, false, PartialOverloading); 3997 } else 3998 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func), 3999 ExplicitTemplateArgs, 4000 Args, NumArgs, CandidateSet); 4001 } 4002} 4003 4004/// isBetterOverloadCandidate - Determines whether the first overload 4005/// candidate is a better candidate than the second (C++ 13.3.3p1). 4006bool 4007Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1, 4008 const OverloadCandidate& Cand2) { 4009 // Define viable functions to be better candidates than non-viable 4010 // functions. 4011 if (!Cand2.Viable) 4012 return Cand1.Viable; 4013 else if (!Cand1.Viable) 4014 return false; 4015 4016 // C++ [over.match.best]p1: 4017 // 4018 // -- if F is a static member function, ICS1(F) is defined such 4019 // that ICS1(F) is neither better nor worse than ICS1(G) for 4020 // any function G, and, symmetrically, ICS1(G) is neither 4021 // better nor worse than ICS1(F). 4022 unsigned StartArg = 0; 4023 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 4024 StartArg = 1; 4025 4026 // C++ [over.match.best]p1: 4027 // A viable function F1 is defined to be a better function than another 4028 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 4029 // conversion sequence than ICSi(F2), and then... 4030 unsigned NumArgs = Cand1.Conversions.size(); 4031 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 4032 bool HasBetterConversion = false; 4033 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 4034 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx], 4035 Cand2.Conversions[ArgIdx])) { 4036 case ImplicitConversionSequence::Better: 4037 // Cand1 has a better conversion sequence. 4038 HasBetterConversion = true; 4039 break; 4040 4041 case ImplicitConversionSequence::Worse: 4042 // Cand1 can't be better than Cand2. 4043 return false; 4044 4045 case ImplicitConversionSequence::Indistinguishable: 4046 // Do nothing. 4047 break; 4048 } 4049 } 4050 4051 // -- for some argument j, ICSj(F1) is a better conversion sequence than 4052 // ICSj(F2), or, if not that, 4053 if (HasBetterConversion) 4054 return true; 4055 4056 // - F1 is a non-template function and F2 is a function template 4057 // specialization, or, if not that, 4058 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() && 4059 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 4060 return true; 4061 4062 // -- F1 and F2 are function template specializations, and the function 4063 // template for F1 is more specialized than the template for F2 4064 // according to the partial ordering rules described in 14.5.5.2, or, 4065 // if not that, 4066 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 4067 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 4068 if (FunctionTemplateDecl *BetterTemplate 4069 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 4070 Cand2.Function->getPrimaryTemplate(), 4071 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 4072 : TPOC_Call)) 4073 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 4074 4075 // -- the context is an initialization by user-defined conversion 4076 // (see 8.5, 13.3.1.5) and the standard conversion sequence 4077 // from the return type of F1 to the destination type (i.e., 4078 // the type of the entity being initialized) is a better 4079 // conversion sequence than the standard conversion sequence 4080 // from the return type of F2 to the destination type. 4081 if (Cand1.Function && Cand2.Function && 4082 isa<CXXConversionDecl>(Cand1.Function) && 4083 isa<CXXConversionDecl>(Cand2.Function)) { 4084 switch (CompareStandardConversionSequences(Cand1.FinalConversion, 4085 Cand2.FinalConversion)) { 4086 case ImplicitConversionSequence::Better: 4087 // Cand1 has a better conversion sequence. 4088 return true; 4089 4090 case ImplicitConversionSequence::Worse: 4091 // Cand1 can't be better than Cand2. 4092 return false; 4093 4094 case ImplicitConversionSequence::Indistinguishable: 4095 // Do nothing 4096 break; 4097 } 4098 } 4099 4100 return false; 4101} 4102 4103/// \brief Computes the best viable function (C++ 13.3.3) 4104/// within an overload candidate set. 4105/// 4106/// \param CandidateSet the set of candidate functions. 4107/// 4108/// \param Loc the location of the function name (or operator symbol) for 4109/// which overload resolution occurs. 4110/// 4111/// \param Best f overload resolution was successful or found a deleted 4112/// function, Best points to the candidate function found. 4113/// 4114/// \returns The result of overload resolution. 4115Sema::OverloadingResult 4116Sema::BestViableFunction(OverloadCandidateSet& CandidateSet, 4117 SourceLocation Loc, 4118 OverloadCandidateSet::iterator& Best) { 4119 // Find the best viable function. 4120 Best = CandidateSet.end(); 4121 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4122 Cand != CandidateSet.end(); ++Cand) { 4123 if (Cand->Viable) { 4124 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best)) 4125 Best = Cand; 4126 } 4127 } 4128 4129 // If we didn't find any viable functions, abort. 4130 if (Best == CandidateSet.end()) 4131 return OR_No_Viable_Function; 4132 4133 // Make sure that this function is better than every other viable 4134 // function. If not, we have an ambiguity. 4135 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4136 Cand != CandidateSet.end(); ++Cand) { 4137 if (Cand->Viable && 4138 Cand != Best && 4139 !isBetterOverloadCandidate(*Best, *Cand)) { 4140 Best = CandidateSet.end(); 4141 return OR_Ambiguous; 4142 } 4143 } 4144 4145 // Best is the best viable function. 4146 if (Best->Function && 4147 (Best->Function->isDeleted() || 4148 Best->Function->getAttr<UnavailableAttr>())) 4149 return OR_Deleted; 4150 4151 // C++ [basic.def.odr]p2: 4152 // An overloaded function is used if it is selected by overload resolution 4153 // when referred to from a potentially-evaluated expression. [Note: this 4154 // covers calls to named functions (5.2.2), operator overloading 4155 // (clause 13), user-defined conversions (12.3.2), allocation function for 4156 // placement new (5.3.4), as well as non-default initialization (8.5). 4157 if (Best->Function) 4158 MarkDeclarationReferenced(Loc, Best->Function); 4159 return OR_Success; 4160} 4161 4162/// PrintOverloadCandidates - When overload resolution fails, prints 4163/// diagnostic messages containing the candidates in the candidate 4164/// set. If OnlyViable is true, only viable candidates will be printed. 4165void 4166Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet, 4167 bool OnlyViable, 4168 const char *Opc, 4169 SourceLocation OpLoc) { 4170 OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 4171 LastCand = CandidateSet.end(); 4172 bool Reported = false; 4173 for (; Cand != LastCand; ++Cand) { 4174 if (Cand->Viable || !OnlyViable) { 4175 if (Cand->Function) { 4176 if (Cand->Function->isDeleted() || 4177 Cand->Function->getAttr<UnavailableAttr>()) { 4178 // Deleted or "unavailable" function. 4179 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted) 4180 << Cand->Function->isDeleted(); 4181 } else if (FunctionTemplateDecl *FunTmpl 4182 = Cand->Function->getPrimaryTemplate()) { 4183 // Function template specialization 4184 // FIXME: Give a better reason! 4185 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate) 4186 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(), 4187 *Cand->Function->getTemplateSpecializationArgs()); 4188 } else { 4189 // Normal function 4190 bool errReported = false; 4191 if (!Cand->Viable && Cand->Conversions.size() > 0) { 4192 for (int i = Cand->Conversions.size()-1; i >= 0; i--) { 4193 const ImplicitConversionSequence &Conversion = 4194 Cand->Conversions[i]; 4195 if ((Conversion.ConversionKind != 4196 ImplicitConversionSequence::BadConversion) || 4197 Conversion.ConversionFunctionSet.size() == 0) 4198 continue; 4199 Diag(Cand->Function->getLocation(), 4200 diag::err_ovl_candidate_not_viable) << (i+1); 4201 errReported = true; 4202 for (int j = Conversion.ConversionFunctionSet.size()-1; 4203 j >= 0; j--) { 4204 FunctionDecl *Func = Conversion.ConversionFunctionSet[j]; 4205 Diag(Func->getLocation(), diag::err_ovl_candidate); 4206 } 4207 } 4208 } 4209 if (!errReported) 4210 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate); 4211 } 4212 } else if (Cand->IsSurrogate) { 4213 // Desugar the type of the surrogate down to a function type, 4214 // retaining as many typedefs as possible while still showing 4215 // the function type (and, therefore, its parameter types). 4216 QualType FnType = Cand->Surrogate->getConversionType(); 4217 bool isLValueReference = false; 4218 bool isRValueReference = false; 4219 bool isPointer = false; 4220 if (const LValueReferenceType *FnTypeRef = 4221 FnType->getAs<LValueReferenceType>()) { 4222 FnType = FnTypeRef->getPointeeType(); 4223 isLValueReference = true; 4224 } else if (const RValueReferenceType *FnTypeRef = 4225 FnType->getAs<RValueReferenceType>()) { 4226 FnType = FnTypeRef->getPointeeType(); 4227 isRValueReference = true; 4228 } 4229 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 4230 FnType = FnTypePtr->getPointeeType(); 4231 isPointer = true; 4232 } 4233 // Desugar down to a function type. 4234 FnType = QualType(FnType->getAs<FunctionType>(), 0); 4235 // Reconstruct the pointer/reference as appropriate. 4236 if (isPointer) FnType = Context.getPointerType(FnType); 4237 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType); 4238 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType); 4239 4240 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand) 4241 << FnType; 4242 } else if (OnlyViable) { 4243 assert(Cand->Conversions.size() <= 2 && 4244 "builtin-binary-operator-not-binary"); 4245 std::string TypeStr("operator"); 4246 TypeStr += Opc; 4247 TypeStr += "("; 4248 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 4249 if (Cand->Conversions.size() == 1) { 4250 TypeStr += ")"; 4251 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr; 4252 } 4253 else { 4254 TypeStr += ", "; 4255 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 4256 TypeStr += ")"; 4257 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr; 4258 } 4259 } 4260 else if (!Cand->Viable && !Reported) { 4261 // Non-viability might be due to ambiguous user-defined conversions, 4262 // needed for built-in operators. Report them as well, but only once 4263 // as we have typically many built-in candidates. 4264 unsigned NoOperands = Cand->Conversions.size(); 4265 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 4266 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 4267 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion || 4268 ICS.ConversionFunctionSet.empty()) 4269 continue; 4270 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>( 4271 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) { 4272 QualType FromTy = 4273 QualType( 4274 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0); 4275 Diag(OpLoc,diag::note_ambiguous_type_conversion) 4276 << FromTy << Func->getConversionType(); 4277 } 4278 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) { 4279 FunctionDecl *Func = 4280 Cand->Conversions[ArgIdx].ConversionFunctionSet[j]; 4281 Diag(Func->getLocation(),diag::err_ovl_candidate); 4282 } 4283 } 4284 Reported = true; 4285 } 4286 } 4287 } 4288} 4289 4290/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 4291/// an overloaded function (C++ [over.over]), where @p From is an 4292/// expression with overloaded function type and @p ToType is the type 4293/// we're trying to resolve to. For example: 4294/// 4295/// @code 4296/// int f(double); 4297/// int f(int); 4298/// 4299/// int (*pfd)(double) = f; // selects f(double) 4300/// @endcode 4301/// 4302/// This routine returns the resulting FunctionDecl if it could be 4303/// resolved, and NULL otherwise. When @p Complain is true, this 4304/// routine will emit diagnostics if there is an error. 4305FunctionDecl * 4306Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType, 4307 bool Complain) { 4308 QualType FunctionType = ToType; 4309 bool IsMember = false; 4310 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>()) 4311 FunctionType = ToTypePtr->getPointeeType(); 4312 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>()) 4313 FunctionType = ToTypeRef->getPointeeType(); 4314 else if (const MemberPointerType *MemTypePtr = 4315 ToType->getAs<MemberPointerType>()) { 4316 FunctionType = MemTypePtr->getPointeeType(); 4317 IsMember = true; 4318 } 4319 4320 // We only look at pointers or references to functions. 4321 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType(); 4322 if (!FunctionType->isFunctionType()) 4323 return 0; 4324 4325 // Find the actual overloaded function declaration. 4326 4327 // C++ [over.over]p1: 4328 // [...] [Note: any redundant set of parentheses surrounding the 4329 // overloaded function name is ignored (5.1). ] 4330 Expr *OvlExpr = From->IgnoreParens(); 4331 4332 // C++ [over.over]p1: 4333 // [...] The overloaded function name can be preceded by the & 4334 // operator. 4335 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) { 4336 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 4337 OvlExpr = UnOp->getSubExpr()->IgnoreParens(); 4338 } 4339 4340 bool HasExplicitTemplateArgs = false; 4341 TemplateArgumentListInfo ExplicitTemplateArgs; 4342 4343 llvm::SmallVector<NamedDecl*,8> Fns; 4344 4345 // Try to dig out the overloaded function. 4346 OverloadedFunctionDecl *Ovl = 0; 4347 FunctionTemplateDecl *FunctionTemplate = 0; 4348 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) { 4349 assert(!isa<OverloadedFunctionDecl>(DR->getDecl())); 4350 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl()); 4351 HasExplicitTemplateArgs = DR->hasExplicitTemplateArgumentList(); 4352 if (HasExplicitTemplateArgs) 4353 DR->copyTemplateArgumentsInto(ExplicitTemplateArgs); 4354 } else if (UnresolvedLookupExpr *UL 4355 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) { 4356 Fns.append(UL->decls_begin(), UL->decls_end()); 4357 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) { 4358 Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl()); 4359 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl()); 4360 HasExplicitTemplateArgs = ME->hasExplicitTemplateArgumentList(); 4361 if (HasExplicitTemplateArgs) 4362 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs); 4363 } else if (TemplateIdRefExpr *TIRE = dyn_cast<TemplateIdRefExpr>(OvlExpr)) { 4364 TemplateName Name = TIRE->getTemplateName(); 4365 Ovl = Name.getAsOverloadedFunctionDecl(); 4366 FunctionTemplate = 4367 dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl()); 4368 4369 HasExplicitTemplateArgs = true; 4370 TIRE->copyTemplateArgumentsInto(ExplicitTemplateArgs); 4371 } 4372 4373 if (Ovl) Fns.append(Ovl->function_begin(), Ovl->function_end()); 4374 if (FunctionTemplate) Fns.push_back(FunctionTemplate); 4375 4376 // If we didn't actually find anything, we're done. 4377 if (Fns.empty()) 4378 return 0; 4379 4380 // Look through all of the overloaded functions, searching for one 4381 // whose type matches exactly. 4382 llvm::SmallPtrSet<FunctionDecl *, 4> Matches; 4383 bool FoundNonTemplateFunction = false; 4384 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(), 4385 E = Fns.end(); I != E; ++I) { 4386 // C++ [over.over]p3: 4387 // Non-member functions and static member functions match 4388 // targets of type "pointer-to-function" or "reference-to-function." 4389 // Nonstatic member functions match targets of 4390 // type "pointer-to-member-function." 4391 // Note that according to DR 247, the containing class does not matter. 4392 4393 if (FunctionTemplateDecl *FunctionTemplate 4394 = dyn_cast<FunctionTemplateDecl>(*I)) { 4395 if (CXXMethodDecl *Method 4396 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 4397 // Skip non-static function templates when converting to pointer, and 4398 // static when converting to member pointer. 4399 if (Method->isStatic() == IsMember) 4400 continue; 4401 } else if (IsMember) 4402 continue; 4403 4404 // C++ [over.over]p2: 4405 // If the name is a function template, template argument deduction is 4406 // done (14.8.2.2), and if the argument deduction succeeds, the 4407 // resulting template argument list is used to generate a single 4408 // function template specialization, which is added to the set of 4409 // overloaded functions considered. 4410 // FIXME: We don't really want to build the specialization here, do we? 4411 FunctionDecl *Specialization = 0; 4412 TemplateDeductionInfo Info(Context); 4413 if (TemplateDeductionResult Result 4414 = DeduceTemplateArguments(FunctionTemplate, 4415 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0), 4416 FunctionType, Specialization, Info)) { 4417 // FIXME: make a note of the failed deduction for diagnostics. 4418 (void)Result; 4419 } else { 4420 // FIXME: If the match isn't exact, shouldn't we just drop this as 4421 // a candidate? Find a testcase before changing the code. 4422 assert(FunctionType 4423 == Context.getCanonicalType(Specialization->getType())); 4424 Matches.insert( 4425 cast<FunctionDecl>(Specialization->getCanonicalDecl())); 4426 } 4427 4428 continue; 4429 } 4430 4431 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) { 4432 // Skip non-static functions when converting to pointer, and static 4433 // when converting to member pointer. 4434 if (Method->isStatic() == IsMember) 4435 continue; 4436 4437 // If we have explicit template arguments, skip non-templates. 4438 if (HasExplicitTemplateArgs) 4439 continue; 4440 } else if (IsMember) 4441 continue; 4442 4443 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) { 4444 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) { 4445 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl())); 4446 FoundNonTemplateFunction = true; 4447 } 4448 } 4449 } 4450 4451 // If there were 0 or 1 matches, we're done. 4452 if (Matches.empty()) 4453 return 0; 4454 else if (Matches.size() == 1) { 4455 FunctionDecl *Result = *Matches.begin(); 4456 MarkDeclarationReferenced(From->getLocStart(), Result); 4457 return Result; 4458 } 4459 4460 // C++ [over.over]p4: 4461 // If more than one function is selected, [...] 4462 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter; 4463 if (!FoundNonTemplateFunction) { 4464 // [...] and any given function template specialization F1 is 4465 // eliminated if the set contains a second function template 4466 // specialization whose function template is more specialized 4467 // than the function template of F1 according to the partial 4468 // ordering rules of 14.5.5.2. 4469 4470 // The algorithm specified above is quadratic. We instead use a 4471 // two-pass algorithm (similar to the one used to identify the 4472 // best viable function in an overload set) that identifies the 4473 // best function template (if it exists). 4474 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(), 4475 Matches.end()); 4476 FunctionDecl *Result = 4477 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(), 4478 TPOC_Other, From->getLocStart(), 4479 PDiag(), 4480 PDiag(diag::err_addr_ovl_ambiguous) 4481 << TemplateMatches[0]->getDeclName(), 4482 PDiag(diag::err_ovl_template_candidate)); 4483 MarkDeclarationReferenced(From->getLocStart(), Result); 4484 return Result; 4485 } 4486 4487 // [...] any function template specializations in the set are 4488 // eliminated if the set also contains a non-template function, [...] 4489 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches; 4490 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M) 4491 if ((*M)->getPrimaryTemplate() == 0) 4492 RemainingMatches.push_back(*M); 4493 4494 // [...] After such eliminations, if any, there shall remain exactly one 4495 // selected function. 4496 if (RemainingMatches.size() == 1) { 4497 FunctionDecl *Result = RemainingMatches.front(); 4498 MarkDeclarationReferenced(From->getLocStart(), Result); 4499 return Result; 4500 } 4501 4502 // FIXME: We should probably return the same thing that BestViableFunction 4503 // returns (even if we issue the diagnostics here). 4504 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous) 4505 << RemainingMatches[0]->getDeclName(); 4506 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I) 4507 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate); 4508 return 0; 4509} 4510 4511/// \brief Add a single candidate to the overload set. 4512static void AddOverloadedCallCandidate(Sema &S, 4513 NamedDecl *Callee, 4514 const TemplateArgumentListInfo *ExplicitTemplateArgs, 4515 Expr **Args, unsigned NumArgs, 4516 OverloadCandidateSet &CandidateSet, 4517 bool PartialOverloading) { 4518 if (isa<UsingShadowDecl>(Callee)) 4519 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 4520 4521 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 4522 assert(!ExplicitTemplateArgs && "Explicit template arguments?"); 4523 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false, 4524 PartialOverloading); 4525 return; 4526 } 4527 4528 if (FunctionTemplateDecl *FuncTemplate 4529 = dyn_cast<FunctionTemplateDecl>(Callee)) { 4530 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs, 4531 Args, NumArgs, CandidateSet); 4532 return; 4533 } 4534 4535 assert(false && "unhandled case in overloaded call candidate"); 4536 4537 // do nothing? 4538} 4539 4540/// \brief Add the overload candidates named by callee and/or found by argument 4541/// dependent lookup to the given overload set. 4542void Sema::AddOverloadedCallCandidates(llvm::SmallVectorImpl<NamedDecl*> &Fns, 4543 DeclarationName &UnqualifiedName, 4544 bool ArgumentDependentLookup, 4545 const TemplateArgumentListInfo *ExplicitTemplateArgs, 4546 Expr **Args, unsigned NumArgs, 4547 OverloadCandidateSet &CandidateSet, 4548 bool PartialOverloading) { 4549 4550#ifndef NDEBUG 4551 // Verify that ArgumentDependentLookup is consistent with the rules 4552 // in C++0x [basic.lookup.argdep]p3: 4553 // 4554 // Let X be the lookup set produced by unqualified lookup (3.4.1) 4555 // and let Y be the lookup set produced by argument dependent 4556 // lookup (defined as follows). If X contains 4557 // 4558 // -- a declaration of a class member, or 4559 // 4560 // -- a block-scope function declaration that is not a 4561 // using-declaration, or 4562 // 4563 // -- a declaration that is neither a function or a function 4564 // template 4565 // 4566 // then Y is empty. 4567 4568 if (ArgumentDependentLookup) { 4569 for (unsigned I = 0; I < Fns.size(); ++I) { 4570 assert(!Fns[I]->getDeclContext()->isRecord()); 4571 assert(isa<UsingShadowDecl>(Fns[I]) || 4572 !Fns[I]->getDeclContext()->isFunctionOrMethod()); 4573 assert(Fns[I]->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 4574 } 4575 } 4576#endif 4577 4578 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(), 4579 E = Fns.end(); I != E; ++I) 4580 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs, 4581 Args, NumArgs, CandidateSet, 4582 PartialOverloading); 4583 4584 if (ArgumentDependentLookup) 4585 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs, 4586 ExplicitTemplateArgs, 4587 CandidateSet, 4588 PartialOverloading); 4589} 4590 4591/// ResolveOverloadedCallFn - Given the call expression that calls Fn 4592/// (which eventually refers to the declaration Func) and the call 4593/// arguments Args/NumArgs, attempt to resolve the function call down 4594/// to a specific function. If overload resolution succeeds, returns 4595/// the function declaration produced by overload 4596/// resolution. Otherwise, emits diagnostics, deletes all of the 4597/// arguments and Fn, and returns NULL. 4598FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, 4599 llvm::SmallVectorImpl<NamedDecl*> &Fns, 4600 DeclarationName UnqualifiedName, 4601 const TemplateArgumentListInfo *ExplicitTemplateArgs, 4602 SourceLocation LParenLoc, 4603 Expr **Args, unsigned NumArgs, 4604 SourceLocation *CommaLocs, 4605 SourceLocation RParenLoc, 4606 bool ArgumentDependentLookup) { 4607 OverloadCandidateSet CandidateSet; 4608 4609 // Add the functions denoted by Callee to the set of candidate 4610 // functions. 4611 AddOverloadedCallCandidates(Fns, UnqualifiedName, ArgumentDependentLookup, 4612 ExplicitTemplateArgs, Args, NumArgs, 4613 CandidateSet); 4614 OverloadCandidateSet::iterator Best; 4615 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) { 4616 case OR_Success: 4617 return Best->Function; 4618 4619 case OR_No_Viable_Function: 4620 Diag(Fn->getSourceRange().getBegin(), 4621 diag::err_ovl_no_viable_function_in_call) 4622 << UnqualifiedName << Fn->getSourceRange(); 4623 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 4624 break; 4625 4626 case OR_Ambiguous: 4627 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 4628 << UnqualifiedName << Fn->getSourceRange(); 4629 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4630 break; 4631 4632 case OR_Deleted: 4633 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call) 4634 << Best->Function->isDeleted() 4635 << UnqualifiedName 4636 << Fn->getSourceRange(); 4637 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4638 break; 4639 } 4640 4641 // Overload resolution failed. Destroy all of the subexpressions and 4642 // return NULL. 4643 Fn->Destroy(Context); 4644 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) 4645 Args[Arg]->Destroy(Context); 4646 return 0; 4647} 4648 4649static bool IsOverloaded(const Sema::FunctionSet &Functions) { 4650 return Functions.size() > 1 || 4651 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 4652} 4653 4654/// \brief Create a unary operation that may resolve to an overloaded 4655/// operator. 4656/// 4657/// \param OpLoc The location of the operator itself (e.g., '*'). 4658/// 4659/// \param OpcIn The UnaryOperator::Opcode that describes this 4660/// operator. 4661/// 4662/// \param Functions The set of non-member functions that will be 4663/// considered by overload resolution. The caller needs to build this 4664/// set based on the context using, e.g., 4665/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 4666/// set should not contain any member functions; those will be added 4667/// by CreateOverloadedUnaryOp(). 4668/// 4669/// \param input The input argument. 4670Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, 4671 unsigned OpcIn, 4672 FunctionSet &Functions, 4673 ExprArg input) { 4674 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 4675 Expr *Input = (Expr *)input.get(); 4676 4677 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 4678 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 4679 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 4680 4681 Expr *Args[2] = { Input, 0 }; 4682 unsigned NumArgs = 1; 4683 4684 // For post-increment and post-decrement, add the implicit '0' as 4685 // the second argument, so that we know this is a post-increment or 4686 // post-decrement. 4687 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) { 4688 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 4689 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy, 4690 SourceLocation()); 4691 NumArgs = 2; 4692 } 4693 4694 if (Input->isTypeDependent()) { 4695 UnresolvedLookupExpr *Fn 4696 = UnresolvedLookupExpr::Create(Context, 0, SourceRange(), OpName, OpLoc, 4697 /*ADL*/ true, IsOverloaded(Functions)); 4698 for (FunctionSet::iterator Func = Functions.begin(), 4699 FuncEnd = Functions.end(); 4700 Func != FuncEnd; ++Func) 4701 Fn->addDecl(*Func); 4702 4703 input.release(); 4704 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 4705 &Args[0], NumArgs, 4706 Context.DependentTy, 4707 OpLoc)); 4708 } 4709 4710 // Build an empty overload set. 4711 OverloadCandidateSet CandidateSet; 4712 4713 // Add the candidates from the given function set. 4714 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false); 4715 4716 // Add operator candidates that are member functions. 4717 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 4718 4719 // Add builtin operator candidates. 4720 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 4721 4722 // Perform overload resolution. 4723 OverloadCandidateSet::iterator Best; 4724 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 4725 case OR_Success: { 4726 // We found a built-in operator or an overloaded operator. 4727 FunctionDecl *FnDecl = Best->Function; 4728 4729 if (FnDecl) { 4730 // We matched an overloaded operator. Build a call to that 4731 // operator. 4732 4733 // Convert the arguments. 4734 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 4735 if (PerformObjectArgumentInitialization(Input, Method)) 4736 return ExprError(); 4737 } else { 4738 // Convert the arguments. 4739 if (PerformCopyInitialization(Input, 4740 FnDecl->getParamDecl(0)->getType(), 4741 "passing")) 4742 return ExprError(); 4743 } 4744 4745 // Determine the result type 4746 QualType ResultTy = FnDecl->getResultType().getNonReferenceType(); 4747 4748 // Build the actual expression node. 4749 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 4750 SourceLocation()); 4751 UsualUnaryConversions(FnExpr); 4752 4753 input.release(); 4754 Args[0] = Input; 4755 ExprOwningPtr<CallExpr> TheCall(this, 4756 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr, 4757 Args, NumArgs, ResultTy, OpLoc)); 4758 4759 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(), 4760 FnDecl)) 4761 return ExprError(); 4762 4763 return MaybeBindToTemporary(TheCall.release()); 4764 } else { 4765 // We matched a built-in operator. Convert the arguments, then 4766 // break out so that we will build the appropriate built-in 4767 // operator node. 4768 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 4769 Best->Conversions[0], "passing")) 4770 return ExprError(); 4771 4772 break; 4773 } 4774 } 4775 4776 case OR_No_Viable_Function: 4777 // No viable function; fall through to handling this as a 4778 // built-in operator, which will produce an error message for us. 4779 break; 4780 4781 case OR_Ambiguous: 4782 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 4783 << UnaryOperator::getOpcodeStr(Opc) 4784 << Input->getSourceRange(); 4785 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true, 4786 UnaryOperator::getOpcodeStr(Opc), OpLoc); 4787 return ExprError(); 4788 4789 case OR_Deleted: 4790 Diag(OpLoc, diag::err_ovl_deleted_oper) 4791 << Best->Function->isDeleted() 4792 << UnaryOperator::getOpcodeStr(Opc) 4793 << Input->getSourceRange(); 4794 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4795 return ExprError(); 4796 } 4797 4798 // Either we found no viable overloaded operator or we matched a 4799 // built-in operator. In either case, fall through to trying to 4800 // build a built-in operation. 4801 input.release(); 4802 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input)); 4803} 4804 4805/// \brief Create a binary operation that may resolve to an overloaded 4806/// operator. 4807/// 4808/// \param OpLoc The location of the operator itself (e.g., '+'). 4809/// 4810/// \param OpcIn The BinaryOperator::Opcode that describes this 4811/// operator. 4812/// 4813/// \param Functions The set of non-member functions that will be 4814/// considered by overload resolution. The caller needs to build this 4815/// set based on the context using, e.g., 4816/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 4817/// set should not contain any member functions; those will be added 4818/// by CreateOverloadedBinOp(). 4819/// 4820/// \param LHS Left-hand argument. 4821/// \param RHS Right-hand argument. 4822Sema::OwningExprResult 4823Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 4824 unsigned OpcIn, 4825 FunctionSet &Functions, 4826 Expr *LHS, Expr *RHS) { 4827 Expr *Args[2] = { LHS, RHS }; 4828 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 4829 4830 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 4831 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 4832 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 4833 4834 // If either side is type-dependent, create an appropriate dependent 4835 // expression. 4836 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 4837 if (Functions.empty()) { 4838 // If there are no functions to store, just build a dependent 4839 // BinaryOperator or CompoundAssignment. 4840 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign) 4841 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 4842 Context.DependentTy, OpLoc)); 4843 4844 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 4845 Context.DependentTy, 4846 Context.DependentTy, 4847 Context.DependentTy, 4848 OpLoc)); 4849 } 4850 4851 UnresolvedLookupExpr *Fn 4852 = UnresolvedLookupExpr::Create(Context, 0, SourceRange(), OpName, OpLoc, 4853 /* ADL */ true, IsOverloaded(Functions)); 4854 4855 for (FunctionSet::iterator Func = Functions.begin(), 4856 FuncEnd = Functions.end(); 4857 Func != FuncEnd; ++Func) 4858 Fn->addDecl(*Func); 4859 4860 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 4861 Args, 2, 4862 Context.DependentTy, 4863 OpLoc)); 4864 } 4865 4866 // If this is the .* operator, which is not overloadable, just 4867 // create a built-in binary operator. 4868 if (Opc == BinaryOperator::PtrMemD) 4869 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 4870 4871 // If this is the assignment operator, we only perform overload resolution 4872 // if the left-hand side is a class or enumeration type. This is actually 4873 // a hack. The standard requires that we do overload resolution between the 4874 // various built-in candidates, but as DR507 points out, this can lead to 4875 // problems. So we do it this way, which pretty much follows what GCC does. 4876 // Note that we go the traditional code path for compound assignment forms. 4877 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType()) 4878 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 4879 4880 // Build an empty overload set. 4881 OverloadCandidateSet CandidateSet; 4882 4883 // Add the candidates from the given function set. 4884 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false); 4885 4886 // Add operator candidates that are member functions. 4887 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 4888 4889 // Add builtin operator candidates. 4890 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 4891 4892 // Perform overload resolution. 4893 OverloadCandidateSet::iterator Best; 4894 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 4895 case OR_Success: { 4896 // We found a built-in operator or an overloaded operator. 4897 FunctionDecl *FnDecl = Best->Function; 4898 4899 if (FnDecl) { 4900 // We matched an overloaded operator. Build a call to that 4901 // operator. 4902 4903 // Convert the arguments. 4904 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 4905 if (PerformObjectArgumentInitialization(Args[0], Method) || 4906 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(), 4907 "passing")) 4908 return ExprError(); 4909 } else { 4910 // Convert the arguments. 4911 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(), 4912 "passing") || 4913 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(), 4914 "passing")) 4915 return ExprError(); 4916 } 4917 4918 // Determine the result type 4919 QualType ResultTy 4920 = FnDecl->getType()->getAs<FunctionType>()->getResultType(); 4921 ResultTy = ResultTy.getNonReferenceType(); 4922 4923 // Build the actual expression node. 4924 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 4925 OpLoc); 4926 UsualUnaryConversions(FnExpr); 4927 4928 ExprOwningPtr<CXXOperatorCallExpr> 4929 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr, 4930 Args, 2, ResultTy, 4931 OpLoc)); 4932 4933 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(), 4934 FnDecl)) 4935 return ExprError(); 4936 4937 return MaybeBindToTemporary(TheCall.release()); 4938 } else { 4939 // We matched a built-in operator. Convert the arguments, then 4940 // break out so that we will build the appropriate built-in 4941 // operator node. 4942 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 4943 Best->Conversions[0], "passing") || 4944 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 4945 Best->Conversions[1], "passing")) 4946 return ExprError(); 4947 4948 break; 4949 } 4950 } 4951 4952 case OR_No_Viable_Function: { 4953 // C++ [over.match.oper]p9: 4954 // If the operator is the operator , [...] and there are no 4955 // viable functions, then the operator is assumed to be the 4956 // built-in operator and interpreted according to clause 5. 4957 if (Opc == BinaryOperator::Comma) 4958 break; 4959 4960 // For class as left operand for assignment or compound assigment operator 4961 // do not fall through to handling in built-in, but report that no overloaded 4962 // assignment operator found 4963 OwningExprResult Result = ExprError(); 4964 if (Args[0]->getType()->isRecordType() && 4965 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) { 4966 Diag(OpLoc, diag::err_ovl_no_viable_oper) 4967 << BinaryOperator::getOpcodeStr(Opc) 4968 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 4969 } else { 4970 // No viable function; try to create a built-in operation, which will 4971 // produce an error. Then, show the non-viable candidates. 4972 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 4973 } 4974 assert(Result.isInvalid() && 4975 "C++ binary operator overloading is missing candidates!"); 4976 if (Result.isInvalid()) 4977 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false, 4978 BinaryOperator::getOpcodeStr(Opc), OpLoc); 4979 return move(Result); 4980 } 4981 4982 case OR_Ambiguous: 4983 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 4984 << BinaryOperator::getOpcodeStr(Opc) 4985 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 4986 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true, 4987 BinaryOperator::getOpcodeStr(Opc), OpLoc); 4988 return ExprError(); 4989 4990 case OR_Deleted: 4991 Diag(OpLoc, diag::err_ovl_deleted_oper) 4992 << Best->Function->isDeleted() 4993 << BinaryOperator::getOpcodeStr(Opc) 4994 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 4995 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 4996 return ExprError(); 4997 } 4998 4999 // We matched a built-in operator; build it. 5000 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 5001} 5002 5003Action::OwningExprResult 5004Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 5005 SourceLocation RLoc, 5006 ExprArg Base, ExprArg Idx) { 5007 Expr *Args[2] = { static_cast<Expr*>(Base.get()), 5008 static_cast<Expr*>(Idx.get()) }; 5009 DeclarationName OpName = 5010 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 5011 5012 // If either side is type-dependent, create an appropriate dependent 5013 // expression. 5014 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 5015 5016 UnresolvedLookupExpr *Fn 5017 = UnresolvedLookupExpr::Create(Context, 0, SourceRange(), OpName, LLoc, 5018 /*ADL*/ true, /*Overloaded*/ false); 5019 // Can't add an actual overloads yet 5020 5021 Base.release(); 5022 Idx.release(); 5023 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 5024 Args, 2, 5025 Context.DependentTy, 5026 RLoc)); 5027 } 5028 5029 // Build an empty overload set. 5030 OverloadCandidateSet CandidateSet; 5031 5032 // Subscript can only be overloaded as a member function. 5033 5034 // Add operator candidates that are member functions. 5035 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 5036 5037 // Add builtin operator candidates. 5038 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 5039 5040 // Perform overload resolution. 5041 OverloadCandidateSet::iterator Best; 5042 switch (BestViableFunction(CandidateSet, LLoc, Best)) { 5043 case OR_Success: { 5044 // We found a built-in operator or an overloaded operator. 5045 FunctionDecl *FnDecl = Best->Function; 5046 5047 if (FnDecl) { 5048 // We matched an overloaded operator. Build a call to that 5049 // operator. 5050 5051 // Convert the arguments. 5052 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 5053 if (PerformObjectArgumentInitialization(Args[0], Method) || 5054 PerformCopyInitialization(Args[1], 5055 FnDecl->getParamDecl(0)->getType(), 5056 "passing")) 5057 return ExprError(); 5058 5059 // Determine the result type 5060 QualType ResultTy 5061 = FnDecl->getType()->getAs<FunctionType>()->getResultType(); 5062 ResultTy = ResultTy.getNonReferenceType(); 5063 5064 // Build the actual expression node. 5065 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(), 5066 LLoc); 5067 UsualUnaryConversions(FnExpr); 5068 5069 Base.release(); 5070 Idx.release(); 5071 ExprOwningPtr<CXXOperatorCallExpr> 5072 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 5073 FnExpr, Args, 2, 5074 ResultTy, RLoc)); 5075 5076 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(), 5077 FnDecl)) 5078 return ExprError(); 5079 5080 return MaybeBindToTemporary(TheCall.release()); 5081 } else { 5082 // We matched a built-in operator. Convert the arguments, then 5083 // break out so that we will build the appropriate built-in 5084 // operator node. 5085 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 5086 Best->Conversions[0], "passing") || 5087 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 5088 Best->Conversions[1], "passing")) 5089 return ExprError(); 5090 5091 break; 5092 } 5093 } 5094 5095 case OR_No_Viable_Function: { 5096 // No viable function; try to create a built-in operation, which will 5097 // produce an error. Then, show the non-viable candidates. 5098 OwningExprResult Result = 5099 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc); 5100 assert(Result.isInvalid() && 5101 "C++ subscript operator overloading is missing candidates!"); 5102 if (Result.isInvalid()) 5103 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false, 5104 "[]", LLoc); 5105 return move(Result); 5106 } 5107 5108 case OR_Ambiguous: 5109 Diag(LLoc, diag::err_ovl_ambiguous_oper) 5110 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 5111 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true, 5112 "[]", LLoc); 5113 return ExprError(); 5114 5115 case OR_Deleted: 5116 Diag(LLoc, diag::err_ovl_deleted_oper) 5117 << Best->Function->isDeleted() << "[]" 5118 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 5119 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 5120 return ExprError(); 5121 } 5122 5123 // We matched a built-in operator; build it. 5124 Base.release(); 5125 Idx.release(); 5126 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc, 5127 Owned(Args[1]), RLoc); 5128} 5129 5130/// BuildCallToMemberFunction - Build a call to a member 5131/// function. MemExpr is the expression that refers to the member 5132/// function (and includes the object parameter), Args/NumArgs are the 5133/// arguments to the function call (not including the object 5134/// parameter). The caller needs to validate that the member 5135/// expression refers to a member function or an overloaded member 5136/// function. 5137Sema::ExprResult 5138Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 5139 SourceLocation LParenLoc, Expr **Args, 5140 unsigned NumArgs, SourceLocation *CommaLocs, 5141 SourceLocation RParenLoc) { 5142 // Dig out the member expression. This holds both the object 5143 // argument and the member function we're referring to. 5144 MemberExpr *MemExpr = 0; 5145 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE)) 5146 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr()); 5147 else 5148 MemExpr = dyn_cast<MemberExpr>(MemExprE); 5149 assert(MemExpr && "Building member call without member expression"); 5150 5151 // Extract the object argument. 5152 Expr *ObjectArg = MemExpr->getBase(); 5153 5154 CXXMethodDecl *Method = 0; 5155 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) || 5156 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) { 5157 // Add overload candidates 5158 OverloadCandidateSet CandidateSet; 5159 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName(); 5160 5161 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd; 5162 Func != FuncEnd; ++Func) { 5163 if ((Method = dyn_cast<CXXMethodDecl>(*Func))) { 5164 // If explicit template arguments were provided, we can't call a 5165 // non-template member function. 5166 if (MemExpr->hasExplicitTemplateArgumentList()) 5167 continue; 5168 5169 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet, 5170 /*SuppressUserConversions=*/false); 5171 } else { 5172 // FIXME: avoid copy. 5173 TemplateArgumentListInfo TemplateArgs; 5174 if (MemExpr->hasExplicitTemplateArgumentList()) 5175 MemExpr->copyTemplateArgumentsInto(TemplateArgs); 5176 5177 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func), 5178 (MemExpr->hasExplicitTemplateArgumentList() 5179 ? &TemplateArgs : 0), 5180 ObjectArg, Args, NumArgs, 5181 CandidateSet, 5182 /*SuppressUsedConversions=*/false); 5183 } 5184 } 5185 5186 OverloadCandidateSet::iterator Best; 5187 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) { 5188 case OR_Success: 5189 Method = cast<CXXMethodDecl>(Best->Function); 5190 break; 5191 5192 case OR_No_Viable_Function: 5193 Diag(MemExpr->getSourceRange().getBegin(), 5194 diag::err_ovl_no_viable_member_function_in_call) 5195 << DeclName << MemExprE->getSourceRange(); 5196 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 5197 // FIXME: Leaking incoming expressions! 5198 return true; 5199 5200 case OR_Ambiguous: 5201 Diag(MemExpr->getSourceRange().getBegin(), 5202 diag::err_ovl_ambiguous_member_call) 5203 << DeclName << MemExprE->getSourceRange(); 5204 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 5205 // FIXME: Leaking incoming expressions! 5206 return true; 5207 5208 case OR_Deleted: 5209 Diag(MemExpr->getSourceRange().getBegin(), 5210 diag::err_ovl_deleted_member_call) 5211 << Best->Function->isDeleted() 5212 << DeclName << MemExprE->getSourceRange(); 5213 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 5214 // FIXME: Leaking incoming expressions! 5215 return true; 5216 } 5217 5218 MemExprE = FixOverloadedFunctionReference(MemExprE, Method); 5219 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE)) 5220 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr()); 5221 else 5222 MemExpr = dyn_cast<MemberExpr>(MemExprE); 5223 5224 } else { 5225 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 5226 } 5227 5228 assert(Method && "Member call to something that isn't a method?"); 5229 ExprOwningPtr<CXXMemberCallExpr> 5230 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args, 5231 NumArgs, 5232 Method->getResultType().getNonReferenceType(), 5233 RParenLoc)); 5234 5235 // Check for a valid return type. 5236 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 5237 TheCall.get(), Method)) 5238 return true; 5239 5240 // Convert the object argument (for a non-static member function call). 5241 if (!Method->isStatic() && 5242 PerformObjectArgumentInitialization(ObjectArg, Method)) 5243 return true; 5244 MemExpr->setBase(ObjectArg); 5245 5246 // Convert the rest of the arguments 5247 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType()); 5248 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs, 5249 RParenLoc)) 5250 return true; 5251 5252 if (CheckFunctionCall(Method, TheCall.get())) 5253 return true; 5254 5255 return MaybeBindToTemporary(TheCall.release()).release(); 5256} 5257 5258/// BuildCallToObjectOfClassType - Build a call to an object of class 5259/// type (C++ [over.call.object]), which can end up invoking an 5260/// overloaded function call operator (@c operator()) or performing a 5261/// user-defined conversion on the object argument. 5262Sema::ExprResult 5263Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object, 5264 SourceLocation LParenLoc, 5265 Expr **Args, unsigned NumArgs, 5266 SourceLocation *CommaLocs, 5267 SourceLocation RParenLoc) { 5268 assert(Object->getType()->isRecordType() && "Requires object type argument"); 5269 const RecordType *Record = Object->getType()->getAs<RecordType>(); 5270 5271 // C++ [over.call.object]p1: 5272 // If the primary-expression E in the function call syntax 5273 // evaluates to a class object of type "cv T", then the set of 5274 // candidate functions includes at least the function call 5275 // operators of T. The function call operators of T are obtained by 5276 // ordinary lookup of the name operator() in the context of 5277 // (E).operator(). 5278 OverloadCandidateSet CandidateSet; 5279 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 5280 5281 if (RequireCompleteType(LParenLoc, Object->getType(), 5282 PartialDiagnostic(diag::err_incomplete_object_call) 5283 << Object->getSourceRange())) 5284 return true; 5285 5286 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 5287 LookupQualifiedName(R, Record->getDecl()); 5288 R.suppressDiagnostics(); 5289 5290 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 5291 Oper != OperEnd; ++Oper) { 5292 AddMethodCandidate(*Oper, Object, Args, NumArgs, CandidateSet, 5293 /*SuppressUserConversions=*/ false); 5294 } 5295 5296 // C++ [over.call.object]p2: 5297 // In addition, for each conversion function declared in T of the 5298 // form 5299 // 5300 // operator conversion-type-id () cv-qualifier; 5301 // 5302 // where cv-qualifier is the same cv-qualification as, or a 5303 // greater cv-qualification than, cv, and where conversion-type-id 5304 // denotes the type "pointer to function of (P1,...,Pn) returning 5305 // R", or the type "reference to pointer to function of 5306 // (P1,...,Pn) returning R", or the type "reference to function 5307 // of (P1,...,Pn) returning R", a surrogate call function [...] 5308 // is also considered as a candidate function. Similarly, 5309 // surrogate call functions are added to the set of candidate 5310 // functions for each conversion function declared in an 5311 // accessible base class provided the function is not hidden 5312 // within T by another intervening declaration. 5313 // FIXME: Look in base classes for more conversion operators! 5314 const UnresolvedSet *Conversions 5315 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions(); 5316 for (UnresolvedSet::iterator I = Conversions->begin(), 5317 E = Conversions->end(); I != E; ++I) { 5318 // Skip over templated conversion functions; they aren't 5319 // surrogates. 5320 if (isa<FunctionTemplateDecl>(*I)) 5321 continue; 5322 5323 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I); 5324 5325 // Strip the reference type (if any) and then the pointer type (if 5326 // any) to get down to what might be a function type. 5327 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 5328 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 5329 ConvType = ConvPtrType->getPointeeType(); 5330 5331 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 5332 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet); 5333 } 5334 5335 // Perform overload resolution. 5336 OverloadCandidateSet::iterator Best; 5337 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) { 5338 case OR_Success: 5339 // Overload resolution succeeded; we'll build the appropriate call 5340 // below. 5341 break; 5342 5343 case OR_No_Viable_Function: 5344 Diag(Object->getSourceRange().getBegin(), 5345 diag::err_ovl_no_viable_object_call) 5346 << Object->getType() << Object->getSourceRange(); 5347 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 5348 break; 5349 5350 case OR_Ambiguous: 5351 Diag(Object->getSourceRange().getBegin(), 5352 diag::err_ovl_ambiguous_object_call) 5353 << Object->getType() << Object->getSourceRange(); 5354 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 5355 break; 5356 5357 case OR_Deleted: 5358 Diag(Object->getSourceRange().getBegin(), 5359 diag::err_ovl_deleted_object_call) 5360 << Best->Function->isDeleted() 5361 << Object->getType() << Object->getSourceRange(); 5362 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 5363 break; 5364 } 5365 5366 if (Best == CandidateSet.end()) { 5367 // We had an error; delete all of the subexpressions and return 5368 // the error. 5369 Object->Destroy(Context); 5370 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 5371 Args[ArgIdx]->Destroy(Context); 5372 return true; 5373 } 5374 5375 if (Best->Function == 0) { 5376 // Since there is no function declaration, this is one of the 5377 // surrogate candidates. Dig out the conversion function. 5378 CXXConversionDecl *Conv 5379 = cast<CXXConversionDecl>( 5380 Best->Conversions[0].UserDefined.ConversionFunction); 5381 5382 // We selected one of the surrogate functions that converts the 5383 // object parameter to a function pointer. Perform the conversion 5384 // on the object argument, then let ActOnCallExpr finish the job. 5385 5386 // Create an implicit member expr to refer to the conversion operator. 5387 // and then call it. 5388 CXXMemberCallExpr *CE = 5389 BuildCXXMemberCallExpr(Object, Conv); 5390 5391 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc, 5392 MultiExprArg(*this, (ExprTy**)Args, NumArgs), 5393 CommaLocs, RParenLoc).release(); 5394 } 5395 5396 // We found an overloaded operator(). Build a CXXOperatorCallExpr 5397 // that calls this method, using Object for the implicit object 5398 // parameter and passing along the remaining arguments. 5399 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 5400 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>(); 5401 5402 unsigned NumArgsInProto = Proto->getNumArgs(); 5403 unsigned NumArgsToCheck = NumArgs; 5404 5405 // Build the full argument list for the method call (the 5406 // implicit object parameter is placed at the beginning of the 5407 // list). 5408 Expr **MethodArgs; 5409 if (NumArgs < NumArgsInProto) { 5410 NumArgsToCheck = NumArgsInProto; 5411 MethodArgs = new Expr*[NumArgsInProto + 1]; 5412 } else { 5413 MethodArgs = new Expr*[NumArgs + 1]; 5414 } 5415 MethodArgs[0] = Object; 5416 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 5417 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 5418 5419 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(), 5420 SourceLocation()); 5421 UsualUnaryConversions(NewFn); 5422 5423 // Once we've built TheCall, all of the expressions are properly 5424 // owned. 5425 QualType ResultTy = Method->getResultType().getNonReferenceType(); 5426 ExprOwningPtr<CXXOperatorCallExpr> 5427 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn, 5428 MethodArgs, NumArgs + 1, 5429 ResultTy, RParenLoc)); 5430 delete [] MethodArgs; 5431 5432 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(), 5433 Method)) 5434 return true; 5435 5436 // We may have default arguments. If so, we need to allocate more 5437 // slots in the call for them. 5438 if (NumArgs < NumArgsInProto) 5439 TheCall->setNumArgs(Context, NumArgsInProto + 1); 5440 else if (NumArgs > NumArgsInProto) 5441 NumArgsToCheck = NumArgsInProto; 5442 5443 bool IsError = false; 5444 5445 // Initialize the implicit object parameter. 5446 IsError |= PerformObjectArgumentInitialization(Object, Method); 5447 TheCall->setArg(0, Object); 5448 5449 5450 // Check the argument types. 5451 for (unsigned i = 0; i != NumArgsToCheck; i++) { 5452 Expr *Arg; 5453 if (i < NumArgs) { 5454 Arg = Args[i]; 5455 5456 // Pass the argument. 5457 QualType ProtoArgType = Proto->getArgType(i); 5458 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing"); 5459 } else { 5460 OwningExprResult DefArg 5461 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 5462 if (DefArg.isInvalid()) { 5463 IsError = true; 5464 break; 5465 } 5466 5467 Arg = DefArg.takeAs<Expr>(); 5468 } 5469 5470 TheCall->setArg(i + 1, Arg); 5471 } 5472 5473 // If this is a variadic call, handle args passed through "...". 5474 if (Proto->isVariadic()) { 5475 // Promote the arguments (C99 6.5.2.2p7). 5476 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 5477 Expr *Arg = Args[i]; 5478 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod); 5479 TheCall->setArg(i + 1, Arg); 5480 } 5481 } 5482 5483 if (IsError) return true; 5484 5485 if (CheckFunctionCall(Method, TheCall.get())) 5486 return true; 5487 5488 return MaybeBindToTemporary(TheCall.release()).release(); 5489} 5490 5491/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 5492/// (if one exists), where @c Base is an expression of class type and 5493/// @c Member is the name of the member we're trying to find. 5494Sema::OwningExprResult 5495Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) { 5496 Expr *Base = static_cast<Expr *>(BaseIn.get()); 5497 assert(Base->getType()->isRecordType() && "left-hand side must have class type"); 5498 5499 // C++ [over.ref]p1: 5500 // 5501 // [...] An expression x->m is interpreted as (x.operator->())->m 5502 // for a class object x of type T if T::operator->() exists and if 5503 // the operator is selected as the best match function by the 5504 // overload resolution mechanism (13.3). 5505 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 5506 OverloadCandidateSet CandidateSet; 5507 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 5508 5509 if (RequireCompleteType(Base->getLocStart(), Base->getType(), 5510 PDiag(diag::err_typecheck_incomplete_tag) 5511 << Base->getSourceRange())) 5512 return ExprError(); 5513 5514 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 5515 LookupQualifiedName(R, BaseRecord->getDecl()); 5516 R.suppressDiagnostics(); 5517 5518 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 5519 Oper != OperEnd; ++Oper) 5520 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet, 5521 /*SuppressUserConversions=*/false); 5522 5523 // Perform overload resolution. 5524 OverloadCandidateSet::iterator Best; 5525 switch (BestViableFunction(CandidateSet, OpLoc, Best)) { 5526 case OR_Success: 5527 // Overload resolution succeeded; we'll build the call below. 5528 break; 5529 5530 case OR_No_Viable_Function: 5531 if (CandidateSet.empty()) 5532 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 5533 << Base->getType() << Base->getSourceRange(); 5534 else 5535 Diag(OpLoc, diag::err_ovl_no_viable_oper) 5536 << "operator->" << Base->getSourceRange(); 5537 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 5538 return ExprError(); 5539 5540 case OR_Ambiguous: 5541 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 5542 << "->" << Base->getSourceRange(); 5543 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 5544 return ExprError(); 5545 5546 case OR_Deleted: 5547 Diag(OpLoc, diag::err_ovl_deleted_oper) 5548 << Best->Function->isDeleted() 5549 << "->" << Base->getSourceRange(); 5550 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 5551 return ExprError(); 5552 } 5553 5554 // Convert the object parameter. 5555 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 5556 if (PerformObjectArgumentInitialization(Base, Method)) 5557 return ExprError(); 5558 5559 // No concerns about early exits now. 5560 BaseIn.release(); 5561 5562 // Build the operator call. 5563 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(), 5564 SourceLocation()); 5565 UsualUnaryConversions(FnExpr); 5566 5567 QualType ResultTy = Method->getResultType().getNonReferenceType(); 5568 ExprOwningPtr<CXXOperatorCallExpr> 5569 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, 5570 &Base, 1, ResultTy, OpLoc)); 5571 5572 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(), 5573 Method)) 5574 return ExprError(); 5575 return move(TheCall); 5576} 5577 5578/// FixOverloadedFunctionReference - E is an expression that refers to 5579/// a C++ overloaded function (possibly with some parentheses and 5580/// perhaps a '&' around it). We have resolved the overloaded function 5581/// to the function declaration Fn, so patch up the expression E to 5582/// refer (possibly indirectly) to Fn. Returns the new expr. 5583Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) { 5584 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 5585 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn); 5586 if (SubExpr == PE->getSubExpr()) 5587 return PE->Retain(); 5588 5589 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 5590 } 5591 5592 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5593 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn); 5594 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 5595 SubExpr->getType()) && 5596 "Implicit cast type cannot be determined from overload"); 5597 if (SubExpr == ICE->getSubExpr()) 5598 return ICE->Retain(); 5599 5600 return new (Context) ImplicitCastExpr(ICE->getType(), 5601 ICE->getCastKind(), 5602 SubExpr, 5603 ICE->isLvalueCast()); 5604 } 5605 5606 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 5607 assert(UnOp->getOpcode() == UnaryOperator::AddrOf && 5608 "Can only take the address of an overloaded function"); 5609 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 5610 if (Method->isStatic()) { 5611 // Do nothing: static member functions aren't any different 5612 // from non-member functions. 5613 } else { 5614 // Fix the sub expression, which really has to be one of: 5615 // * a DeclRefExpr holding a member function template 5616 // * a TemplateIdRefExpr, also holding a member function template 5617 // * an UnresolvedLookupExpr holding an overloaded member function 5618 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn); 5619 if (SubExpr == UnOp->getSubExpr()) 5620 return UnOp->Retain(); 5621 5622 assert(isa<DeclRefExpr>(SubExpr) 5623 && "fixed to something other than a decl ref"); 5624 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 5625 && "fixed to a member ref with no nested name qualifier"); 5626 5627 // We have taken the address of a pointer to member 5628 // function. Perform the computation here so that we get the 5629 // appropriate pointer to member type. 5630 QualType ClassType 5631 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 5632 QualType MemPtrType 5633 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 5634 5635 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf, 5636 MemPtrType, UnOp->getOperatorLoc()); 5637 } 5638 5639 // FIXME: TemplateIdRefExpr referring to a member function template 5640 // specialization! 5641 } 5642 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn); 5643 if (SubExpr == UnOp->getSubExpr()) 5644 return UnOp->Retain(); 5645 5646 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf, 5647 Context.getPointerType(SubExpr->getType()), 5648 UnOp->getOperatorLoc()); 5649 } 5650 5651 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 5652 assert((isa<FunctionTemplateDecl>(DRE->getDecl()) || 5653 isa<FunctionDecl>(DRE->getDecl())) && 5654 "Expected function or function template"); 5655 // FIXME: avoid copy. 5656 TemplateArgumentListInfo TemplateArgs; 5657 if (DRE->hasExplicitTemplateArgumentList()) 5658 DRE->copyTemplateArgumentsInto(TemplateArgs); 5659 5660 return DeclRefExpr::Create(Context, 5661 DRE->getQualifier(), 5662 DRE->getQualifierRange(), 5663 Fn, 5664 DRE->getLocation(), 5665 Fn->getType(), 5666 (DRE->hasExplicitTemplateArgumentList() 5667 ? &TemplateArgs : 0)); 5668 } 5669 5670 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 5671 return DeclRefExpr::Create(Context, 5672 ULE->getQualifier(), 5673 ULE->getQualifierRange(), 5674 Fn, 5675 ULE->getNameLoc(), 5676 Fn->getType()); 5677 } 5678 5679 5680 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) { 5681 assert((isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) || 5682 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl()) || 5683 isa<FunctionDecl>(MemExpr->getMemberDecl())) && 5684 "Expected member function or member function template"); 5685 // FIXME: avoid copy. 5686 TemplateArgumentListInfo TemplateArgs; 5687 if (MemExpr->hasExplicitTemplateArgumentList()) 5688 MemExpr->copyTemplateArgumentsInto(TemplateArgs); 5689 5690 return MemberExpr::Create(Context, MemExpr->getBase()->Retain(), 5691 MemExpr->isArrow(), 5692 MemExpr->getQualifier(), 5693 MemExpr->getQualifierRange(), 5694 Fn, 5695 MemExpr->getMemberLoc(), 5696 (MemExpr->hasExplicitTemplateArgumentList() 5697 ? &TemplateArgs : 0), 5698 Fn->getType()); 5699 } 5700 5701 if (TemplateIdRefExpr *TID = dyn_cast<TemplateIdRefExpr>(E)) { 5702 // FIXME: Don't destroy TID here, since we need its template arguments 5703 // to survive. 5704 // TID->Destroy(Context); 5705 5706 // FIXME: avoid copy. 5707 TemplateArgumentListInfo TemplateArgs; 5708 TID->copyTemplateArgumentsInto(TemplateArgs); 5709 5710 return DeclRefExpr::Create(Context, 5711 TID->getQualifier(), TID->getQualifierRange(), 5712 Fn, TID->getTemplateNameLoc(), 5713 Fn->getType(), 5714 &TemplateArgs); 5715 } 5716 5717 assert(false && "Invalid reference to overloaded function"); 5718 return E->Retain(); 5719} 5720 5721} // end namespace clang 5722