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