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