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