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