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