SemaOverload.cpp revision 6fd3557615e8e6e33456e147d060296282bfe7f1
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/Support/Compiler.h" 24#include <algorithm> 25 26namespace clang { 27 28/// GetConversionCategory - Retrieve the implicit conversion 29/// category corresponding to the given implicit conversion kind. 30ImplicitConversionCategory 31GetConversionCategory(ImplicitConversionKind Kind) { 32 static const ImplicitConversionCategory 33 Category[(int)ICK_Num_Conversion_Kinds] = { 34 ICC_Identity, 35 ICC_Lvalue_Transformation, 36 ICC_Lvalue_Transformation, 37 ICC_Lvalue_Transformation, 38 ICC_Qualification_Adjustment, 39 ICC_Promotion, 40 ICC_Promotion, 41 ICC_Conversion, 42 ICC_Conversion, 43 ICC_Conversion, 44 ICC_Conversion, 45 ICC_Conversion, 46 ICC_Conversion, 47 ICC_Conversion 48 }; 49 return Category[(int)Kind]; 50} 51 52/// GetConversionRank - Retrieve the implicit conversion rank 53/// corresponding to the given implicit conversion kind. 54ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 55 static const ImplicitConversionRank 56 Rank[(int)ICK_Num_Conversion_Kinds] = { 57 ICR_Exact_Match, 58 ICR_Exact_Match, 59 ICR_Exact_Match, 60 ICR_Exact_Match, 61 ICR_Exact_Match, 62 ICR_Promotion, 63 ICR_Promotion, 64 ICR_Conversion, 65 ICR_Conversion, 66 ICR_Conversion, 67 ICR_Conversion, 68 ICR_Conversion, 69 ICR_Conversion, 70 ICR_Conversion 71 }; 72 return Rank[(int)Kind]; 73} 74 75/// GetImplicitConversionName - Return the name of this kind of 76/// implicit conversion. 77const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 78 static const char* Name[(int)ICK_Num_Conversion_Kinds] = { 79 "No conversion", 80 "Lvalue-to-rvalue", 81 "Array-to-pointer", 82 "Function-to-pointer", 83 "Qualification", 84 "Integral promotion", 85 "Floating point promotion", 86 "Integral conversion", 87 "Floating conversion", 88 "Floating-integral conversion", 89 "Pointer conversion", 90 "Pointer-to-member conversion", 91 "Boolean conversion", 92 "Derived-to-base conversion" 93 }; 94 return Name[Kind]; 95} 96 97/// StandardConversionSequence - Set the standard conversion 98/// sequence to the identity conversion. 99void StandardConversionSequence::setAsIdentityConversion() { 100 First = ICK_Identity; 101 Second = ICK_Identity; 102 Third = ICK_Identity; 103 Deprecated = false; 104 ReferenceBinding = false; 105 DirectBinding = false; 106 CopyConstructor = 0; 107} 108 109/// getRank - Retrieve the rank of this standard conversion sequence 110/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 111/// implicit conversions. 112ImplicitConversionRank StandardConversionSequence::getRank() const { 113 ImplicitConversionRank Rank = ICR_Exact_Match; 114 if (GetConversionRank(First) > Rank) 115 Rank = GetConversionRank(First); 116 if (GetConversionRank(Second) > Rank) 117 Rank = GetConversionRank(Second); 118 if (GetConversionRank(Third) > Rank) 119 Rank = GetConversionRank(Third); 120 return Rank; 121} 122 123/// isPointerConversionToBool - Determines whether this conversion is 124/// a conversion of a pointer or pointer-to-member to bool. This is 125/// used as part of the ranking of standard conversion sequences 126/// (C++ 13.3.3.2p4). 127bool StandardConversionSequence::isPointerConversionToBool() const 128{ 129 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr); 130 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr); 131 132 // Note that FromType has not necessarily been transformed by the 133 // array-to-pointer or function-to-pointer implicit conversions, so 134 // check for their presence as well as checking whether FromType is 135 // a pointer. 136 if (ToType->isBooleanType() && 137 (FromType->isPointerType() || 138 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 139 return true; 140 141 return false; 142} 143 144/// isPointerConversionToVoidPointer - Determines whether this 145/// conversion is a conversion of a pointer to a void pointer. This is 146/// used as part of the ranking of standard conversion sequences (C++ 147/// 13.3.3.2p4). 148bool 149StandardConversionSequence:: 150isPointerConversionToVoidPointer(ASTContext& Context) const 151{ 152 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr); 153 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr); 154 155 // Note that FromType has not necessarily been transformed by the 156 // array-to-pointer implicit conversion, so check for its presence 157 // and redo the conversion to get a pointer. 158 if (First == ICK_Array_To_Pointer) 159 FromType = Context.getArrayDecayedType(FromType); 160 161 if (Second == ICK_Pointer_Conversion) 162 if (const PointerType* ToPtrType = ToType->getAsPointerType()) 163 return ToPtrType->getPointeeType()->isVoidType(); 164 165 return false; 166} 167 168/// DebugPrint - Print this standard conversion sequence to standard 169/// error. Useful for debugging overloading issues. 170void StandardConversionSequence::DebugPrint() const { 171 bool PrintedSomething = false; 172 if (First != ICK_Identity) { 173 fprintf(stderr, "%s", GetImplicitConversionName(First)); 174 PrintedSomething = true; 175 } 176 177 if (Second != ICK_Identity) { 178 if (PrintedSomething) { 179 fprintf(stderr, " -> "); 180 } 181 fprintf(stderr, "%s", GetImplicitConversionName(Second)); 182 183 if (CopyConstructor) { 184 fprintf(stderr, " (by copy constructor)"); 185 } else if (DirectBinding) { 186 fprintf(stderr, " (direct reference binding)"); 187 } else if (ReferenceBinding) { 188 fprintf(stderr, " (reference binding)"); 189 } 190 PrintedSomething = true; 191 } 192 193 if (Third != ICK_Identity) { 194 if (PrintedSomething) { 195 fprintf(stderr, " -> "); 196 } 197 fprintf(stderr, "%s", GetImplicitConversionName(Third)); 198 PrintedSomething = true; 199 } 200 201 if (!PrintedSomething) { 202 fprintf(stderr, "No conversions required"); 203 } 204} 205 206/// DebugPrint - Print this user-defined conversion sequence to standard 207/// error. Useful for debugging overloading issues. 208void UserDefinedConversionSequence::DebugPrint() const { 209 if (Before.First || Before.Second || Before.Third) { 210 Before.DebugPrint(); 211 fprintf(stderr, " -> "); 212 } 213 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str()); 214 if (After.First || After.Second || After.Third) { 215 fprintf(stderr, " -> "); 216 After.DebugPrint(); 217 } 218} 219 220/// DebugPrint - Print this implicit conversion sequence to standard 221/// error. Useful for debugging overloading issues. 222void ImplicitConversionSequence::DebugPrint() const { 223 switch (ConversionKind) { 224 case StandardConversion: 225 fprintf(stderr, "Standard conversion: "); 226 Standard.DebugPrint(); 227 break; 228 case UserDefinedConversion: 229 fprintf(stderr, "User-defined conversion: "); 230 UserDefined.DebugPrint(); 231 break; 232 case EllipsisConversion: 233 fprintf(stderr, "Ellipsis conversion"); 234 break; 235 case BadConversion: 236 fprintf(stderr, "Bad conversion"); 237 break; 238 } 239 240 fprintf(stderr, "\n"); 241} 242 243// IsOverload - Determine whether the given New declaration is an 244// overload of the Old declaration. This routine returns false if New 245// and Old cannot be overloaded, e.g., if they are functions with the 246// same signature (C++ 1.3.10) or if the Old declaration isn't a 247// function (or overload set). When it does return false and Old is an 248// OverloadedFunctionDecl, MatchedDecl will be set to point to the 249// FunctionDecl that New cannot be overloaded with. 250// 251// Example: Given the following input: 252// 253// void f(int, float); // #1 254// void f(int, int); // #2 255// int f(int, int); // #3 256// 257// When we process #1, there is no previous declaration of "f", 258// so IsOverload will not be used. 259// 260// When we process #2, Old is a FunctionDecl for #1. By comparing the 261// parameter types, we see that #1 and #2 are overloaded (since they 262// have different signatures), so this routine returns false; 263// MatchedDecl is unchanged. 264// 265// When we process #3, Old is an OverloadedFunctionDecl containing #1 266// and #2. We compare the signatures of #3 to #1 (they're overloaded, 267// so we do nothing) and then #3 to #2. Since the signatures of #3 and 268// #2 are identical (return types of functions are not part of the 269// signature), IsOverload returns false and MatchedDecl will be set to 270// point to the FunctionDecl for #2. 271bool 272Sema::IsOverload(FunctionDecl *New, Decl* OldD, 273 OverloadedFunctionDecl::function_iterator& MatchedDecl) 274{ 275 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) { 276 // Is this new function an overload of every function in the 277 // overload set? 278 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(), 279 FuncEnd = Ovl->function_end(); 280 for (; Func != FuncEnd; ++Func) { 281 if (!IsOverload(New, *Func, MatchedDecl)) { 282 MatchedDecl = Func; 283 return false; 284 } 285 } 286 287 // This function overloads every function in the overload set. 288 return true; 289 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) { 290 // Is the function New an overload of the function Old? 291 QualType OldQType = Context.getCanonicalType(Old->getType()); 292 QualType NewQType = Context.getCanonicalType(New->getType()); 293 294 // Compare the signatures (C++ 1.3.10) of the two functions to 295 // determine whether they are overloads. If we find any mismatch 296 // in the signature, they are overloads. 297 298 // If either of these functions is a K&R-style function (no 299 // prototype), then we consider them to have matching signatures. 300 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) || 301 isa<FunctionTypeNoProto>(NewQType.getTypePtr())) 302 return false; 303 304 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr()); 305 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr()); 306 307 // The signature of a function includes the types of its 308 // parameters (C++ 1.3.10), which includes the presence or absence 309 // of the ellipsis; see C++ DR 357). 310 if (OldQType != NewQType && 311 (OldType->getNumArgs() != NewType->getNumArgs() || 312 OldType->isVariadic() != NewType->isVariadic() || 313 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(), 314 NewType->arg_type_begin()))) 315 return true; 316 317 // If the function is a class member, its signature includes the 318 // cv-qualifiers (if any) on the function itself. 319 // 320 // As part of this, also check whether one of the member functions 321 // is static, in which case they are not overloads (C++ 322 // 13.1p2). While not part of the definition of the signature, 323 // this check is important to determine whether these functions 324 // can be overloaded. 325 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 326 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 327 if (OldMethod && NewMethod && 328 !OldMethod->isStatic() && !NewMethod->isStatic() && 329 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers()) 330 return true; 331 332 // The signatures match; this is not an overload. 333 return false; 334 } else { 335 // (C++ 13p1): 336 // Only function declarations can be overloaded; object and type 337 // declarations cannot be overloaded. 338 return false; 339 } 340} 341 342/// TryImplicitConversion - Attempt to perform an implicit conversion 343/// from the given expression (Expr) to the given type (ToType). This 344/// function returns an implicit conversion sequence that can be used 345/// to perform the initialization. Given 346/// 347/// void f(float f); 348/// void g(int i) { f(i); } 349/// 350/// this routine would produce an implicit conversion sequence to 351/// describe the initialization of f from i, which will be a standard 352/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 353/// 4.1) followed by a floating-integral conversion (C++ 4.9). 354// 355/// Note that this routine only determines how the conversion can be 356/// performed; it does not actually perform the conversion. As such, 357/// it will not produce any diagnostics if no conversion is available, 358/// but will instead return an implicit conversion sequence of kind 359/// "BadConversion". 360/// 361/// If @p SuppressUserConversions, then user-defined conversions are 362/// not permitted. 363ImplicitConversionSequence 364Sema::TryImplicitConversion(Expr* From, QualType ToType, 365 bool SuppressUserConversions) 366{ 367 ImplicitConversionSequence ICS; 368 if (IsStandardConversion(From, ToType, ICS.Standard)) 369 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 370 else if (!SuppressUserConversions && 371 IsUserDefinedConversion(From, ToType, ICS.UserDefined)) { 372 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion; 373 // C++ [over.ics.user]p4: 374 // A conversion of an expression of class type to the same class 375 // type is given Exact Match rank, and a conversion of an 376 // expression of class type to a base class of that type is 377 // given Conversion rank, in spite of the fact that a copy 378 // constructor (i.e., a user-defined conversion function) is 379 // called for those cases. 380 if (CXXConstructorDecl *Constructor 381 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 382 if (Constructor->isCopyConstructor(Context)) { 383 // Turn this into a "standard" conversion sequence, so that it 384 // gets ranked with standard conversion sequences. 385 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 386 ICS.Standard.setAsIdentityConversion(); 387 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr(); 388 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr(); 389 ICS.Standard.CopyConstructor = Constructor; 390 if (IsDerivedFrom(From->getType().getUnqualifiedType(), 391 ToType.getUnqualifiedType())) 392 ICS.Standard.Second = ICK_Derived_To_Base; 393 } 394 } 395 } else 396 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 397 398 return ICS; 399} 400 401/// IsStandardConversion - Determines whether there is a standard 402/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 403/// expression From to the type ToType. Standard conversion sequences 404/// only consider non-class types; for conversions that involve class 405/// types, use TryImplicitConversion. If a conversion exists, SCS will 406/// contain the standard conversion sequence required to perform this 407/// conversion and this routine will return true. Otherwise, this 408/// routine will return false and the value of SCS is unspecified. 409bool 410Sema::IsStandardConversion(Expr* From, QualType ToType, 411 StandardConversionSequence &SCS) 412{ 413 QualType FromType = From->getType(); 414 415 // There are no standard conversions for class types, so abort early. 416 if (FromType->isRecordType() || ToType->isRecordType()) 417 return false; 418 419 // Standard conversions (C++ [conv]) 420 SCS.setAsIdentityConversion(); 421 SCS.Deprecated = false; 422 SCS.IncompatibleObjC = false; 423 SCS.FromTypePtr = FromType.getAsOpaquePtr(); 424 SCS.CopyConstructor = 0; 425 426 // The first conversion can be an lvalue-to-rvalue conversion, 427 // array-to-pointer conversion, or function-to-pointer conversion 428 // (C++ 4p1). 429 430 // Lvalue-to-rvalue conversion (C++ 4.1): 431 // An lvalue (3.10) of a non-function, non-array type T can be 432 // converted to an rvalue. 433 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context); 434 if (argIsLvalue == Expr::LV_Valid && 435 !FromType->isFunctionType() && !FromType->isArrayType() && 436 !FromType->isOverloadType()) { 437 SCS.First = ICK_Lvalue_To_Rvalue; 438 439 // If T is a non-class type, the type of the rvalue is the 440 // cv-unqualified version of T. Otherwise, the type of the rvalue 441 // is T (C++ 4.1p1). 442 FromType = FromType.getUnqualifiedType(); 443 } 444 // Array-to-pointer conversion (C++ 4.2) 445 else if (FromType->isArrayType()) { 446 SCS.First = ICK_Array_To_Pointer; 447 448 // An lvalue or rvalue of type "array of N T" or "array of unknown 449 // bound of T" can be converted to an rvalue of type "pointer to 450 // T" (C++ 4.2p1). 451 FromType = Context.getArrayDecayedType(FromType); 452 453 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) { 454 // This conversion is deprecated. (C++ D.4). 455 SCS.Deprecated = true; 456 457 // For the purpose of ranking in overload resolution 458 // (13.3.3.1.1), this conversion is considered an 459 // array-to-pointer conversion followed by a qualification 460 // conversion (4.4). (C++ 4.2p2) 461 SCS.Second = ICK_Identity; 462 SCS.Third = ICK_Qualification; 463 SCS.ToTypePtr = ToType.getAsOpaquePtr(); 464 return true; 465 } 466 } 467 // Function-to-pointer conversion (C++ 4.3). 468 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) { 469 SCS.First = ICK_Function_To_Pointer; 470 471 // An lvalue of function type T can be converted to an rvalue of 472 // type "pointer to T." The result is a pointer to the 473 // function. (C++ 4.3p1). 474 FromType = Context.getPointerType(FromType); 475 } 476 // Address of overloaded function (C++ [over.over]). 477 else if (FunctionDecl *Fn 478 = ResolveAddressOfOverloadedFunction(From, ToType, false)) { 479 SCS.First = ICK_Function_To_Pointer; 480 481 // We were able to resolve the address of the overloaded function, 482 // so we can convert to the type of that function. 483 FromType = Fn->getType(); 484 if (ToType->isReferenceType()) 485 FromType = Context.getReferenceType(FromType); 486 else 487 FromType = Context.getPointerType(FromType); 488 } 489 // We don't require any conversions for the first step. 490 else { 491 SCS.First = ICK_Identity; 492 } 493 494 // The second conversion can be an integral promotion, floating 495 // point promotion, integral conversion, floating point conversion, 496 // floating-integral conversion, pointer conversion, 497 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 498 bool IncompatibleObjC = false; 499 if (Context.getCanonicalType(FromType).getUnqualifiedType() == 500 Context.getCanonicalType(ToType).getUnqualifiedType()) { 501 // The unqualified versions of the types are the same: there's no 502 // conversion to do. 503 SCS.Second = ICK_Identity; 504 } 505 // Integral promotion (C++ 4.5). 506 else if (IsIntegralPromotion(From, FromType, ToType)) { 507 SCS.Second = ICK_Integral_Promotion; 508 FromType = ToType.getUnqualifiedType(); 509 } 510 // Floating point promotion (C++ 4.6). 511 else if (IsFloatingPointPromotion(FromType, ToType)) { 512 SCS.Second = ICK_Floating_Promotion; 513 FromType = ToType.getUnqualifiedType(); 514 } 515 // Integral conversions (C++ 4.7). 516 // FIXME: isIntegralType shouldn't be true for enums in C++. 517 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) && 518 (ToType->isIntegralType() && !ToType->isEnumeralType())) { 519 SCS.Second = ICK_Integral_Conversion; 520 FromType = ToType.getUnqualifiedType(); 521 } 522 // Floating point conversions (C++ 4.8). 523 else if (FromType->isFloatingType() && ToType->isFloatingType()) { 524 SCS.Second = ICK_Floating_Conversion; 525 FromType = ToType.getUnqualifiedType(); 526 } 527 // Floating-integral conversions (C++ 4.9). 528 // FIXME: isIntegralType shouldn't be true for enums in C++. 529 else if ((FromType->isFloatingType() && 530 ToType->isIntegralType() && !ToType->isBooleanType() && 531 !ToType->isEnumeralType()) || 532 ((FromType->isIntegralType() || FromType->isEnumeralType()) && 533 ToType->isFloatingType())) { 534 SCS.Second = ICK_Floating_Integral; 535 FromType = ToType.getUnqualifiedType(); 536 } 537 // Pointer conversions (C++ 4.10). 538 else if (IsPointerConversion(From, FromType, ToType, FromType, 539 IncompatibleObjC)) { 540 SCS.Second = ICK_Pointer_Conversion; 541 SCS.IncompatibleObjC = IncompatibleObjC; 542 } 543 // FIXME: Pointer to member conversions (4.11). 544 // Boolean conversions (C++ 4.12). 545 // FIXME: pointer-to-member type 546 else if (ToType->isBooleanType() && 547 (FromType->isArithmeticType() || 548 FromType->isEnumeralType() || 549 FromType->isPointerType())) { 550 SCS.Second = ICK_Boolean_Conversion; 551 FromType = Context.BoolTy; 552 } else { 553 // No second conversion required. 554 SCS.Second = ICK_Identity; 555 } 556 557 QualType CanonFrom; 558 QualType CanonTo; 559 // The third conversion can be a qualification conversion (C++ 4p1). 560 if (IsQualificationConversion(FromType, ToType)) { 561 SCS.Third = ICK_Qualification; 562 FromType = ToType; 563 CanonFrom = Context.getCanonicalType(FromType); 564 CanonTo = Context.getCanonicalType(ToType); 565 } else { 566 // No conversion required 567 SCS.Third = ICK_Identity; 568 569 // C++ [over.best.ics]p6: 570 // [...] Any difference in top-level cv-qualification is 571 // subsumed by the initialization itself and does not constitute 572 // a conversion. [...] 573 CanonFrom = Context.getCanonicalType(FromType); 574 CanonTo = Context.getCanonicalType(ToType); 575 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() && 576 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) { 577 FromType = ToType; 578 CanonFrom = CanonTo; 579 } 580 } 581 582 // If we have not converted the argument type to the parameter type, 583 // this is a bad conversion sequence. 584 if (CanonFrom != CanonTo) 585 return false; 586 587 SCS.ToTypePtr = FromType.getAsOpaquePtr(); 588 return true; 589} 590 591/// IsIntegralPromotion - Determines whether the conversion from the 592/// expression From (whose potentially-adjusted type is FromType) to 593/// ToType is an integral promotion (C++ 4.5). If so, returns true and 594/// sets PromotedType to the promoted type. 595bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) 596{ 597 const BuiltinType *To = ToType->getAsBuiltinType(); 598 // All integers are built-in. 599 if (!To) { 600 return false; 601 } 602 603 // An rvalue of type char, signed char, unsigned char, short int, or 604 // unsigned short int can be converted to an rvalue of type int if 605 // int can represent all the values of the source type; otherwise, 606 // the source rvalue can be converted to an rvalue of type unsigned 607 // int (C++ 4.5p1). 608 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) { 609 if (// We can promote any signed, promotable integer type to an int 610 (FromType->isSignedIntegerType() || 611 // We can promote any unsigned integer type whose size is 612 // less than int to an int. 613 (!FromType->isSignedIntegerType() && 614 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 615 return To->getKind() == BuiltinType::Int; 616 } 617 618 return To->getKind() == BuiltinType::UInt; 619 } 620 621 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) 622 // can be converted to an rvalue of the first of the following types 623 // that can represent all the values of its underlying type: int, 624 // unsigned int, long, or unsigned long (C++ 4.5p2). 625 if ((FromType->isEnumeralType() || FromType->isWideCharType()) 626 && ToType->isIntegerType()) { 627 // Determine whether the type we're converting from is signed or 628 // unsigned. 629 bool FromIsSigned; 630 uint64_t FromSize = Context.getTypeSize(FromType); 631 if (const EnumType *FromEnumType = FromType->getAsEnumType()) { 632 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType(); 633 FromIsSigned = UnderlyingType->isSignedIntegerType(); 634 } else { 635 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now. 636 FromIsSigned = true; 637 } 638 639 // The types we'll try to promote to, in the appropriate 640 // order. Try each of these types. 641 QualType PromoteTypes[6] = { 642 Context.IntTy, Context.UnsignedIntTy, 643 Context.LongTy, Context.UnsignedLongTy , 644 Context.LongLongTy, Context.UnsignedLongLongTy 645 }; 646 for (int Idx = 0; Idx < 6; ++Idx) { 647 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 648 if (FromSize < ToSize || 649 (FromSize == ToSize && 650 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 651 // We found the type that we can promote to. If this is the 652 // type we wanted, we have a promotion. Otherwise, no 653 // promotion. 654 return Context.getCanonicalType(ToType).getUnqualifiedType() 655 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType(); 656 } 657 } 658 } 659 660 // An rvalue for an integral bit-field (9.6) can be converted to an 661 // rvalue of type int if int can represent all the values of the 662 // bit-field; otherwise, it can be converted to unsigned int if 663 // unsigned int can represent all the values of the bit-field. If 664 // the bit-field is larger yet, no integral promotion applies to 665 // it. If the bit-field has an enumerated type, it is treated as any 666 // other value of that type for promotion purposes (C++ 4.5p3). 667 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) { 668 using llvm::APSInt; 669 FieldDecl *MemberDecl = MemRef->getMemberDecl(); 670 APSInt BitWidth; 671 if (MemberDecl->isBitField() && 672 FromType->isIntegralType() && !FromType->isEnumeralType() && 673 From->isIntegerConstantExpr(BitWidth, Context)) { 674 APSInt ToSize(Context.getTypeSize(ToType)); 675 676 // Are we promoting to an int from a bitfield that fits in an int? 677 if (BitWidth < ToSize || 678 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 679 return To->getKind() == BuiltinType::Int; 680 } 681 682 // Are we promoting to an unsigned int from an unsigned bitfield 683 // that fits into an unsigned int? 684 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 685 return To->getKind() == BuiltinType::UInt; 686 } 687 688 return false; 689 } 690 } 691 692 // An rvalue of type bool can be converted to an rvalue of type int, 693 // with false becoming zero and true becoming one (C++ 4.5p4). 694 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 695 return true; 696 } 697 698 return false; 699} 700 701/// IsFloatingPointPromotion - Determines whether the conversion from 702/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 703/// returns true and sets PromotedType to the promoted type. 704bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) 705{ 706 /// An rvalue of type float can be converted to an rvalue of type 707 /// double. (C++ 4.6p1). 708 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType()) 709 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) 710 if (FromBuiltin->getKind() == BuiltinType::Float && 711 ToBuiltin->getKind() == BuiltinType::Double) 712 return true; 713 714 return false; 715} 716 717/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 718/// the pointer type FromPtr to a pointer to type ToPointee, with the 719/// same type qualifiers as FromPtr has on its pointee type. ToType, 720/// if non-empty, will be a pointer to ToType that may or may not have 721/// the right set of qualifiers on its pointee. 722static QualType 723BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr, 724 QualType ToPointee, QualType ToType, 725 ASTContext &Context) { 726 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType()); 727 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 728 unsigned Quals = CanonFromPointee.getCVRQualifiers(); 729 730 // Exact qualifier match -> return the pointer type we're converting to. 731 if (CanonToPointee.getCVRQualifiers() == Quals) { 732 // ToType is exactly what we need. Return it. 733 if (ToType.getTypePtr()) 734 return ToType; 735 736 // Build a pointer to ToPointee. It has the right qualifiers 737 // already. 738 return Context.getPointerType(ToPointee); 739 } 740 741 // Just build a canonical type that has the right qualifiers. 742 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals)); 743} 744 745/// IsPointerConversion - Determines whether the conversion of the 746/// expression From, which has the (possibly adjusted) type FromType, 747/// can be converted to the type ToType via a pointer conversion (C++ 748/// 4.10). If so, returns true and places the converted type (that 749/// might differ from ToType in its cv-qualifiers at some level) into 750/// ConvertedType. 751/// 752/// This routine also supports conversions to and from block pointers 753/// and conversions with Objective-C's 'id', 'id<protocols...>', and 754/// pointers to interfaces. FIXME: Once we've determined the 755/// appropriate overloading rules for Objective-C, we may want to 756/// split the Objective-C checks into a different routine; however, 757/// GCC seems to consider all of these conversions to be pointer 758/// conversions, so for now they live here. IncompatibleObjC will be 759/// set if the conversion is an allowed Objective-C conversion that 760/// should result in a warning. 761bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 762 QualType& ConvertedType, 763 bool &IncompatibleObjC) 764{ 765 IncompatibleObjC = false; 766 767 // Blocks: Block pointers can be converted to void*. 768 if (FromType->isBlockPointerType() && ToType->isPointerType() && 769 ToType->getAsPointerType()->getPointeeType()->isVoidType()) { 770 ConvertedType = ToType; 771 return true; 772 } 773 // Blocks: A null pointer constant can be converted to a block 774 // pointer type. 775 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) { 776 ConvertedType = ToType; 777 return true; 778 } 779 780 // Conversions with Objective-C's id<...>. 781 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) && 782 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) { 783 ConvertedType = ToType; 784 return true; 785 } 786 787 const PointerType* ToTypePtr = ToType->getAsPointerType(); 788 if (!ToTypePtr) 789 return false; 790 791 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 792 if (From->isNullPointerConstant(Context)) { 793 ConvertedType = ToType; 794 return true; 795 } 796 797 // Beyond this point, both types need to be pointers. 798 const PointerType *FromTypePtr = FromType->getAsPointerType(); 799 if (!FromTypePtr) 800 return false; 801 802 QualType FromPointeeType = FromTypePtr->getPointeeType(); 803 QualType ToPointeeType = ToTypePtr->getPointeeType(); 804 805 // An rvalue of type "pointer to cv T," where T is an object type, 806 // can be converted to an rvalue of type "pointer to cv void" (C++ 807 // 4.10p2). 808 if (FromPointeeType->isIncompleteOrObjectType() && ToPointeeType->isVoidType()) { 809 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 810 ToPointeeType, 811 ToType, Context); 812 return true; 813 } 814 815 // C++ [conv.ptr]p3: 816 // 817 // An rvalue of type "pointer to cv D," where D is a class type, 818 // can be converted to an rvalue of type "pointer to cv B," where 819 // B is a base class (clause 10) of D. If B is an inaccessible 820 // (clause 11) or ambiguous (10.2) base class of D, a program that 821 // necessitates this conversion is ill-formed. The result of the 822 // conversion is a pointer to the base class sub-object of the 823 // derived class object. The null pointer value is converted to 824 // the null pointer value of the destination type. 825 // 826 // Note that we do not check for ambiguity or inaccessibility 827 // here. That is handled by CheckPointerConversion. 828 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 829 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 830 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 831 ToPointeeType, 832 ToType, Context); 833 return true; 834 } 835 836 // Objective C++: We're able to convert from a pointer to an 837 // interface to a pointer to a different interface. 838 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType(); 839 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType(); 840 if (FromIface && ToIface && 841 Context.canAssignObjCInterfaces(ToIface, FromIface)) { 842 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 843 ToPointeeType, 844 ToType, Context); 845 return true; 846 } 847 848 if (FromIface && ToIface && 849 Context.canAssignObjCInterfaces(FromIface, ToIface)) { 850 // Okay: this is some kind of implicit downcast of Objective-C 851 // interfaces, which is permitted. However, we're going to 852 // complain about it. 853 IncompatibleObjC = true; 854 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 855 ToPointeeType, 856 ToType, Context); 857 return true; 858 } 859 860 // Objective C++: We're able to convert between "id" and a pointer 861 // to any interface (in both directions). 862 if ((FromIface && Context.isObjCIdType(ToPointeeType)) 863 || (ToIface && Context.isObjCIdType(FromPointeeType))) { 864 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 865 ToPointeeType, 866 ToType, Context); 867 return true; 868 } 869 870 // Objective C++: Allow conversions between the Objective-C "id" and 871 // "Class", in either direction. 872 if ((Context.isObjCIdType(FromPointeeType) && 873 Context.isObjCClassType(ToPointeeType)) || 874 (Context.isObjCClassType(FromPointeeType) && 875 Context.isObjCIdType(ToPointeeType))) { 876 ConvertedType = ToType; 877 return true; 878 } 879 880 return false; 881} 882 883/// CheckPointerConversion - Check the pointer conversion from the 884/// expression From to the type ToType. This routine checks for 885/// ambiguous (FIXME: or inaccessible) derived-to-base pointer 886/// conversions for which IsPointerConversion has already returned 887/// true. It returns true and produces a diagnostic if there was an 888/// error, or returns false otherwise. 889bool Sema::CheckPointerConversion(Expr *From, QualType ToType) { 890 QualType FromType = From->getType(); 891 892 if (const PointerType *FromPtrType = FromType->getAsPointerType()) 893 if (const PointerType *ToPtrType = ToType->getAsPointerType()) { 894 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 895 /*DetectVirtual=*/false); 896 QualType FromPointeeType = FromPtrType->getPointeeType(), 897 ToPointeeType = ToPtrType->getPointeeType(); 898 899 // Objective-C++ conversions are always okay. 900 // FIXME: We should have a different class of conversions for 901 // the Objective-C++ implicit conversions. 902 if (Context.isObjCIdType(FromPointeeType) || 903 Context.isObjCIdType(ToPointeeType) || 904 Context.isObjCClassType(FromPointeeType) || 905 Context.isObjCClassType(ToPointeeType)) 906 return false; 907 908 if (FromPointeeType->isRecordType() && 909 ToPointeeType->isRecordType()) { 910 // We must have a derived-to-base conversion. Check an 911 // ambiguous or inaccessible conversion. 912 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 913 From->getExprLoc(), 914 From->getSourceRange()); 915 } 916 } 917 918 return false; 919} 920 921/// IsQualificationConversion - Determines whether the conversion from 922/// an rvalue of type FromType to ToType is a qualification conversion 923/// (C++ 4.4). 924bool 925Sema::IsQualificationConversion(QualType FromType, QualType ToType) 926{ 927 FromType = Context.getCanonicalType(FromType); 928 ToType = Context.getCanonicalType(ToType); 929 930 // If FromType and ToType are the same type, this is not a 931 // qualification conversion. 932 if (FromType == ToType) 933 return false; 934 935 // (C++ 4.4p4): 936 // A conversion can add cv-qualifiers at levels other than the first 937 // in multi-level pointers, subject to the following rules: [...] 938 bool PreviousToQualsIncludeConst = true; 939 bool UnwrappedAnyPointer = false; 940 while (UnwrapSimilarPointerTypes(FromType, ToType)) { 941 // Within each iteration of the loop, we check the qualifiers to 942 // determine if this still looks like a qualification 943 // conversion. Then, if all is well, we unwrap one more level of 944 // pointers or pointers-to-members and do it all again 945 // until there are no more pointers or pointers-to-members left to 946 // unwrap. 947 UnwrappedAnyPointer = true; 948 949 // -- for every j > 0, if const is in cv 1,j then const is in cv 950 // 2,j, and similarly for volatile. 951 if (!ToType.isAtLeastAsQualifiedAs(FromType)) 952 return false; 953 954 // -- if the cv 1,j and cv 2,j are different, then const is in 955 // every cv for 0 < k < j. 956 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers() 957 && !PreviousToQualsIncludeConst) 958 return false; 959 960 // Keep track of whether all prior cv-qualifiers in the "to" type 961 // include const. 962 PreviousToQualsIncludeConst 963 = PreviousToQualsIncludeConst && ToType.isConstQualified(); 964 } 965 966 // We are left with FromType and ToType being the pointee types 967 // after unwrapping the original FromType and ToType the same number 968 // of types. If we unwrapped any pointers, and if FromType and 969 // ToType have the same unqualified type (since we checked 970 // qualifiers above), then this is a qualification conversion. 971 return UnwrappedAnyPointer && 972 FromType.getUnqualifiedType() == ToType.getUnqualifiedType(); 973} 974 975/// IsUserDefinedConversion - Determines whether there is a 976/// user-defined conversion sequence (C++ [over.ics.user]) that 977/// converts expression From to the type ToType. If such a conversion 978/// exists, User will contain the user-defined conversion sequence 979/// that performs such a conversion and this routine will return 980/// true. Otherwise, this routine returns false and User is 981/// unspecified. 982bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType, 983 UserDefinedConversionSequence& User) 984{ 985 OverloadCandidateSet CandidateSet; 986 if (const CXXRecordType *ToRecordType 987 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) { 988 // C++ [over.match.ctor]p1: 989 // When objects of class type are direct-initialized (8.5), or 990 // copy-initialized from an expression of the same or a 991 // derived class type (8.5), overload resolution selects the 992 // constructor. [...] For copy-initialization, the candidate 993 // functions are all the converting constructors (12.3.1) of 994 // that class. The argument list is the expression-list within 995 // the parentheses of the initializer. 996 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl(); 997 DeclarationName ConstructorName 998 = Context.DeclarationNames.getCXXConstructorName( 999 Context.getCanonicalType(ToType)); 1000 DeclContext::lookup_result Lookup 1001 = ToRecordDecl->lookup(Context, ConstructorName); 1002 if (Lookup.first == Lookup.second) 1003 /* No constructors. FIXME: Implicit copy constructor? */; 1004 else if (OverloadedFunctionDecl *Constructors 1005 = dyn_cast<OverloadedFunctionDecl>(*Lookup.first)) { 1006 for (OverloadedFunctionDecl::function_const_iterator func 1007 = Constructors->function_begin(); 1008 func != Constructors->function_end(); ++func) { 1009 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func); 1010 if (Constructor->isConvertingConstructor()) 1011 AddOverloadCandidate(Constructor, &From, 1, CandidateSet, 1012 /*SuppressUserConversions=*/true); 1013 } 1014 } else if (CXXConstructorDecl *Constructor 1015 = dyn_cast<CXXConstructorDecl>(*Lookup.first)) { 1016 if (Constructor->isConvertingConstructor()) 1017 AddOverloadCandidate(Constructor, &From, 1, CandidateSet, 1018 /*SuppressUserConversions=*/true); 1019 } 1020 } 1021 1022 if (const CXXRecordType *FromRecordType 1023 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) { 1024 // Add all of the conversion functions as candidates. 1025 // FIXME: Look for conversions in base classes! 1026 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl(); 1027 OverloadedFunctionDecl *Conversions 1028 = FromRecordDecl->getConversionFunctions(); 1029 for (OverloadedFunctionDecl::function_iterator Func 1030 = Conversions->function_begin(); 1031 Func != Conversions->function_end(); ++Func) { 1032 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 1033 AddConversionCandidate(Conv, From, ToType, CandidateSet); 1034 } 1035 } 1036 1037 OverloadCandidateSet::iterator Best; 1038 switch (BestViableFunction(CandidateSet, Best)) { 1039 case OR_Success: 1040 // Record the standard conversion we used and the conversion function. 1041 if (CXXConstructorDecl *Constructor 1042 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 1043 // C++ [over.ics.user]p1: 1044 // If the user-defined conversion is specified by a 1045 // constructor (12.3.1), the initial standard conversion 1046 // sequence converts the source type to the type required by 1047 // the argument of the constructor. 1048 // 1049 // FIXME: What about ellipsis conversions? 1050 QualType ThisType = Constructor->getThisType(Context); 1051 User.Before = Best->Conversions[0].Standard; 1052 User.ConversionFunction = Constructor; 1053 User.After.setAsIdentityConversion(); 1054 User.After.FromTypePtr 1055 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr(); 1056 User.After.ToTypePtr = ToType.getAsOpaquePtr(); 1057 return true; 1058 } else if (CXXConversionDecl *Conversion 1059 = dyn_cast<CXXConversionDecl>(Best->Function)) { 1060 // C++ [over.ics.user]p1: 1061 // 1062 // [...] If the user-defined conversion is specified by a 1063 // conversion function (12.3.2), the initial standard 1064 // conversion sequence converts the source type to the 1065 // implicit object parameter of the conversion function. 1066 User.Before = Best->Conversions[0].Standard; 1067 User.ConversionFunction = Conversion; 1068 1069 // C++ [over.ics.user]p2: 1070 // The second standard conversion sequence converts the 1071 // result of the user-defined conversion to the target type 1072 // for the sequence. Since an implicit conversion sequence 1073 // is an initialization, the special rules for 1074 // initialization by user-defined conversion apply when 1075 // selecting the best user-defined conversion for a 1076 // user-defined conversion sequence (see 13.3.3 and 1077 // 13.3.3.1). 1078 User.After = Best->FinalConversion; 1079 return true; 1080 } else { 1081 assert(false && "Not a constructor or conversion function?"); 1082 return false; 1083 } 1084 1085 case OR_No_Viable_Function: 1086 // No conversion here! We're done. 1087 return false; 1088 1089 case OR_Ambiguous: 1090 // FIXME: See C++ [over.best.ics]p10 for the handling of 1091 // ambiguous conversion sequences. 1092 return false; 1093 } 1094 1095 return false; 1096} 1097 1098/// CompareImplicitConversionSequences - Compare two implicit 1099/// conversion sequences to determine whether one is better than the 1100/// other or if they are indistinguishable (C++ 13.3.3.2). 1101ImplicitConversionSequence::CompareKind 1102Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1, 1103 const ImplicitConversionSequence& ICS2) 1104{ 1105 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 1106 // conversion sequences (as defined in 13.3.3.1) 1107 // -- a standard conversion sequence (13.3.3.1.1) is a better 1108 // conversion sequence than a user-defined conversion sequence or 1109 // an ellipsis conversion sequence, and 1110 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 1111 // conversion sequence than an ellipsis conversion sequence 1112 // (13.3.3.1.3). 1113 // 1114 if (ICS1.ConversionKind < ICS2.ConversionKind) 1115 return ImplicitConversionSequence::Better; 1116 else if (ICS2.ConversionKind < ICS1.ConversionKind) 1117 return ImplicitConversionSequence::Worse; 1118 1119 // Two implicit conversion sequences of the same form are 1120 // indistinguishable conversion sequences unless one of the 1121 // following rules apply: (C++ 13.3.3.2p3): 1122 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion) 1123 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard); 1124 else if (ICS1.ConversionKind == 1125 ImplicitConversionSequence::UserDefinedConversion) { 1126 // User-defined conversion sequence U1 is a better conversion 1127 // sequence than another user-defined conversion sequence U2 if 1128 // they contain the same user-defined conversion function or 1129 // constructor and if the second standard conversion sequence of 1130 // U1 is better than the second standard conversion sequence of 1131 // U2 (C++ 13.3.3.2p3). 1132 if (ICS1.UserDefined.ConversionFunction == 1133 ICS2.UserDefined.ConversionFunction) 1134 return CompareStandardConversionSequences(ICS1.UserDefined.After, 1135 ICS2.UserDefined.After); 1136 } 1137 1138 return ImplicitConversionSequence::Indistinguishable; 1139} 1140 1141/// CompareStandardConversionSequences - Compare two standard 1142/// conversion sequences to determine whether one is better than the 1143/// other or if they are indistinguishable (C++ 13.3.3.2p3). 1144ImplicitConversionSequence::CompareKind 1145Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1, 1146 const StandardConversionSequence& SCS2) 1147{ 1148 // Standard conversion sequence S1 is a better conversion sequence 1149 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 1150 1151 // -- S1 is a proper subsequence of S2 (comparing the conversion 1152 // sequences in the canonical form defined by 13.3.3.1.1, 1153 // excluding any Lvalue Transformation; the identity conversion 1154 // sequence is considered to be a subsequence of any 1155 // non-identity conversion sequence) or, if not that, 1156 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third) 1157 // Neither is a proper subsequence of the other. Do nothing. 1158 ; 1159 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) || 1160 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) || 1161 (SCS1.Second == ICK_Identity && 1162 SCS1.Third == ICK_Identity)) 1163 // SCS1 is a proper subsequence of SCS2. 1164 return ImplicitConversionSequence::Better; 1165 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) || 1166 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) || 1167 (SCS2.Second == ICK_Identity && 1168 SCS2.Third == ICK_Identity)) 1169 // SCS2 is a proper subsequence of SCS1. 1170 return ImplicitConversionSequence::Worse; 1171 1172 // -- the rank of S1 is better than the rank of S2 (by the rules 1173 // defined below), or, if not that, 1174 ImplicitConversionRank Rank1 = SCS1.getRank(); 1175 ImplicitConversionRank Rank2 = SCS2.getRank(); 1176 if (Rank1 < Rank2) 1177 return ImplicitConversionSequence::Better; 1178 else if (Rank2 < Rank1) 1179 return ImplicitConversionSequence::Worse; 1180 1181 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 1182 // are indistinguishable unless one of the following rules 1183 // applies: 1184 1185 // A conversion that is not a conversion of a pointer, or 1186 // pointer to member, to bool is better than another conversion 1187 // that is such a conversion. 1188 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 1189 return SCS2.isPointerConversionToBool() 1190 ? ImplicitConversionSequence::Better 1191 : ImplicitConversionSequence::Worse; 1192 1193 // C++ [over.ics.rank]p4b2: 1194 // 1195 // If class B is derived directly or indirectly from class A, 1196 // conversion of B* to A* is better than conversion of B* to 1197 // void*, and conversion of A* to void* is better than conversion 1198 // of B* to void*. 1199 bool SCS1ConvertsToVoid 1200 = SCS1.isPointerConversionToVoidPointer(Context); 1201 bool SCS2ConvertsToVoid 1202 = SCS2.isPointerConversionToVoidPointer(Context); 1203 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 1204 // Exactly one of the conversion sequences is a conversion to 1205 // a void pointer; it's the worse conversion. 1206 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 1207 : ImplicitConversionSequence::Worse; 1208 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 1209 // Neither conversion sequence converts to a void pointer; compare 1210 // their derived-to-base conversions. 1211 if (ImplicitConversionSequence::CompareKind DerivedCK 1212 = CompareDerivedToBaseConversions(SCS1, SCS2)) 1213 return DerivedCK; 1214 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) { 1215 // Both conversion sequences are conversions to void 1216 // pointers. Compare the source types to determine if there's an 1217 // inheritance relationship in their sources. 1218 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1219 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1220 1221 // Adjust the types we're converting from via the array-to-pointer 1222 // conversion, if we need to. 1223 if (SCS1.First == ICK_Array_To_Pointer) 1224 FromType1 = Context.getArrayDecayedType(FromType1); 1225 if (SCS2.First == ICK_Array_To_Pointer) 1226 FromType2 = Context.getArrayDecayedType(FromType2); 1227 1228 QualType FromPointee1 1229 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1230 QualType FromPointee2 1231 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1232 1233 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1234 return ImplicitConversionSequence::Better; 1235 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1236 return ImplicitConversionSequence::Worse; 1237 1238 // Objective-C++: If one interface is more specific than the 1239 // other, it is the better one. 1240 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType(); 1241 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType(); 1242 if (FromIface1 && FromIface1) { 1243 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 1244 return ImplicitConversionSequence::Better; 1245 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 1246 return ImplicitConversionSequence::Worse; 1247 } 1248 } 1249 1250 // Compare based on qualification conversions (C++ 13.3.3.2p3, 1251 // bullet 3). 1252 if (ImplicitConversionSequence::CompareKind QualCK 1253 = CompareQualificationConversions(SCS1, SCS2)) 1254 return QualCK; 1255 1256 // C++ [over.ics.rank]p3b4: 1257 // -- S1 and S2 are reference bindings (8.5.3), and the types to 1258 // which the references refer are the same type except for 1259 // top-level cv-qualifiers, and the type to which the reference 1260 // initialized by S2 refers is more cv-qualified than the type 1261 // to which the reference initialized by S1 refers. 1262 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 1263 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1264 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1265 T1 = Context.getCanonicalType(T1); 1266 T2 = Context.getCanonicalType(T2); 1267 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) { 1268 if (T2.isMoreQualifiedThan(T1)) 1269 return ImplicitConversionSequence::Better; 1270 else if (T1.isMoreQualifiedThan(T2)) 1271 return ImplicitConversionSequence::Worse; 1272 } 1273 } 1274 1275 return ImplicitConversionSequence::Indistinguishable; 1276} 1277 1278/// CompareQualificationConversions - Compares two standard conversion 1279/// sequences to determine whether they can be ranked based on their 1280/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 1281ImplicitConversionSequence::CompareKind 1282Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1, 1283 const StandardConversionSequence& SCS2) 1284{ 1285 // C++ 13.3.3.2p3: 1286 // -- S1 and S2 differ only in their qualification conversion and 1287 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 1288 // cv-qualification signature of type T1 is a proper subset of 1289 // the cv-qualification signature of type T2, and S1 is not the 1290 // deprecated string literal array-to-pointer conversion (4.2). 1291 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 1292 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 1293 return ImplicitConversionSequence::Indistinguishable; 1294 1295 // FIXME: the example in the standard doesn't use a qualification 1296 // conversion (!) 1297 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1298 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1299 T1 = Context.getCanonicalType(T1); 1300 T2 = Context.getCanonicalType(T2); 1301 1302 // If the types are the same, we won't learn anything by unwrapped 1303 // them. 1304 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1305 return ImplicitConversionSequence::Indistinguishable; 1306 1307 ImplicitConversionSequence::CompareKind Result 1308 = ImplicitConversionSequence::Indistinguishable; 1309 while (UnwrapSimilarPointerTypes(T1, T2)) { 1310 // Within each iteration of the loop, we check the qualifiers to 1311 // determine if this still looks like a qualification 1312 // conversion. Then, if all is well, we unwrap one more level of 1313 // pointers or pointers-to-members and do it all again 1314 // until there are no more pointers or pointers-to-members left 1315 // to unwrap. This essentially mimics what 1316 // IsQualificationConversion does, but here we're checking for a 1317 // strict subset of qualifiers. 1318 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1319 // The qualifiers are the same, so this doesn't tell us anything 1320 // about how the sequences rank. 1321 ; 1322 else if (T2.isMoreQualifiedThan(T1)) { 1323 // T1 has fewer qualifiers, so it could be the better sequence. 1324 if (Result == ImplicitConversionSequence::Worse) 1325 // Neither has qualifiers that are a subset of the other's 1326 // qualifiers. 1327 return ImplicitConversionSequence::Indistinguishable; 1328 1329 Result = ImplicitConversionSequence::Better; 1330 } else if (T1.isMoreQualifiedThan(T2)) { 1331 // T2 has fewer qualifiers, so it could be the better sequence. 1332 if (Result == ImplicitConversionSequence::Better) 1333 // Neither has qualifiers that are a subset of the other's 1334 // qualifiers. 1335 return ImplicitConversionSequence::Indistinguishable; 1336 1337 Result = ImplicitConversionSequence::Worse; 1338 } else { 1339 // Qualifiers are disjoint. 1340 return ImplicitConversionSequence::Indistinguishable; 1341 } 1342 1343 // If the types after this point are equivalent, we're done. 1344 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1345 break; 1346 } 1347 1348 // Check that the winning standard conversion sequence isn't using 1349 // the deprecated string literal array to pointer conversion. 1350 switch (Result) { 1351 case ImplicitConversionSequence::Better: 1352 if (SCS1.Deprecated) 1353 Result = ImplicitConversionSequence::Indistinguishable; 1354 break; 1355 1356 case ImplicitConversionSequence::Indistinguishable: 1357 break; 1358 1359 case ImplicitConversionSequence::Worse: 1360 if (SCS2.Deprecated) 1361 Result = ImplicitConversionSequence::Indistinguishable; 1362 break; 1363 } 1364 1365 return Result; 1366} 1367 1368/// CompareDerivedToBaseConversions - Compares two standard conversion 1369/// sequences to determine whether they can be ranked based on their 1370/// various kinds of derived-to-base conversions (C++ 1371/// [over.ics.rank]p4b3). As part of these checks, we also look at 1372/// conversions between Objective-C interface types. 1373ImplicitConversionSequence::CompareKind 1374Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1, 1375 const StandardConversionSequence& SCS2) { 1376 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1377 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1378 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1379 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1380 1381 // Adjust the types we're converting from via the array-to-pointer 1382 // conversion, if we need to. 1383 if (SCS1.First == ICK_Array_To_Pointer) 1384 FromType1 = Context.getArrayDecayedType(FromType1); 1385 if (SCS2.First == ICK_Array_To_Pointer) 1386 FromType2 = Context.getArrayDecayedType(FromType2); 1387 1388 // Canonicalize all of the types. 1389 FromType1 = Context.getCanonicalType(FromType1); 1390 ToType1 = Context.getCanonicalType(ToType1); 1391 FromType2 = Context.getCanonicalType(FromType2); 1392 ToType2 = Context.getCanonicalType(ToType2); 1393 1394 // C++ [over.ics.rank]p4b3: 1395 // 1396 // If class B is derived directly or indirectly from class A and 1397 // class C is derived directly or indirectly from B, 1398 // 1399 // For Objective-C, we let A, B, and C also be Objective-C 1400 // interfaces. 1401 1402 // Compare based on pointer conversions. 1403 if (SCS1.Second == ICK_Pointer_Conversion && 1404 SCS2.Second == ICK_Pointer_Conversion && 1405 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 1406 FromType1->isPointerType() && FromType2->isPointerType() && 1407 ToType1->isPointerType() && ToType2->isPointerType()) { 1408 QualType FromPointee1 1409 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1410 QualType ToPointee1 1411 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1412 QualType FromPointee2 1413 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1414 QualType ToPointee2 1415 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1416 1417 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType(); 1418 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType(); 1419 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType(); 1420 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType(); 1421 1422 // -- conversion of C* to B* is better than conversion of C* to A*, 1423 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 1424 if (IsDerivedFrom(ToPointee1, ToPointee2)) 1425 return ImplicitConversionSequence::Better; 1426 else if (IsDerivedFrom(ToPointee2, ToPointee1)) 1427 return ImplicitConversionSequence::Worse; 1428 1429 if (ToIface1 && ToIface2) { 1430 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1)) 1431 return ImplicitConversionSequence::Better; 1432 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2)) 1433 return ImplicitConversionSequence::Worse; 1434 } 1435 } 1436 1437 // -- conversion of B* to A* is better than conversion of C* to A*, 1438 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 1439 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1440 return ImplicitConversionSequence::Better; 1441 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1442 return ImplicitConversionSequence::Worse; 1443 1444 if (FromIface1 && FromIface2) { 1445 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 1446 return ImplicitConversionSequence::Better; 1447 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 1448 return ImplicitConversionSequence::Worse; 1449 } 1450 } 1451 } 1452 1453 // Compare based on reference bindings. 1454 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding && 1455 SCS1.Second == ICK_Derived_To_Base) { 1456 // -- binding of an expression of type C to a reference of type 1457 // B& is better than binding an expression of type C to a 1458 // reference of type A&, 1459 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1460 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1461 if (IsDerivedFrom(ToType1, ToType2)) 1462 return ImplicitConversionSequence::Better; 1463 else if (IsDerivedFrom(ToType2, ToType1)) 1464 return ImplicitConversionSequence::Worse; 1465 } 1466 1467 // -- binding of an expression of type B to a reference of type 1468 // A& is better than binding an expression of type C to a 1469 // reference of type A&, 1470 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1471 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1472 if (IsDerivedFrom(FromType2, FromType1)) 1473 return ImplicitConversionSequence::Better; 1474 else if (IsDerivedFrom(FromType1, FromType2)) 1475 return ImplicitConversionSequence::Worse; 1476 } 1477 } 1478 1479 1480 // FIXME: conversion of A::* to B::* is better than conversion of 1481 // A::* to C::*, 1482 1483 // FIXME: conversion of B::* to C::* is better than conversion of 1484 // A::* to C::*, and 1485 1486 if (SCS1.CopyConstructor && SCS2.CopyConstructor && 1487 SCS1.Second == ICK_Derived_To_Base) { 1488 // -- conversion of C to B is better than conversion of C to A, 1489 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1490 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1491 if (IsDerivedFrom(ToType1, ToType2)) 1492 return ImplicitConversionSequence::Better; 1493 else if (IsDerivedFrom(ToType2, ToType1)) 1494 return ImplicitConversionSequence::Worse; 1495 } 1496 1497 // -- conversion of B to A is better than conversion of C to A. 1498 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1499 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1500 if (IsDerivedFrom(FromType2, FromType1)) 1501 return ImplicitConversionSequence::Better; 1502 else if (IsDerivedFrom(FromType1, FromType2)) 1503 return ImplicitConversionSequence::Worse; 1504 } 1505 } 1506 1507 return ImplicitConversionSequence::Indistinguishable; 1508} 1509 1510/// TryCopyInitialization - Try to copy-initialize a value of type 1511/// ToType from the expression From. Return the implicit conversion 1512/// sequence required to pass this argument, which may be a bad 1513/// conversion sequence (meaning that the argument cannot be passed to 1514/// a parameter of this type). If @p SuppressUserConversions, then we 1515/// do not permit any user-defined conversion sequences. 1516ImplicitConversionSequence 1517Sema::TryCopyInitialization(Expr *From, QualType ToType, 1518 bool SuppressUserConversions) { 1519 if (!getLangOptions().CPlusPlus) { 1520 // In C, copy initialization is the same as performing an assignment. 1521 AssignConvertType ConvTy = 1522 CheckSingleAssignmentConstraints(ToType, From); 1523 ImplicitConversionSequence ICS; 1524 if (getLangOptions().NoExtensions? ConvTy != Compatible 1525 : ConvTy == Incompatible) 1526 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1527 else 1528 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 1529 return ICS; 1530 } else if (ToType->isReferenceType()) { 1531 ImplicitConversionSequence ICS; 1532 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions); 1533 return ICS; 1534 } else { 1535 return TryImplicitConversion(From, ToType, SuppressUserConversions); 1536 } 1537} 1538 1539/// PerformArgumentPassing - Pass the argument Arg into a parameter of 1540/// type ToType. Returns true (and emits a diagnostic) if there was 1541/// an error, returns false if the initialization succeeded. 1542bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType, 1543 const char* Flavor) { 1544 if (!getLangOptions().CPlusPlus) { 1545 // In C, argument passing is the same as performing an assignment. 1546 QualType FromType = From->getType(); 1547 AssignConvertType ConvTy = 1548 CheckSingleAssignmentConstraints(ToType, From); 1549 1550 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType, 1551 FromType, From, Flavor); 1552 } 1553 1554 if (ToType->isReferenceType()) 1555 return CheckReferenceInit(From, ToType); 1556 1557 if (!PerformImplicitConversion(From, ToType, Flavor)) 1558 return false; 1559 1560 return Diag(From->getSourceRange().getBegin(), 1561 diag::err_typecheck_convert_incompatible) 1562 << ToType << From->getType() << Flavor << From->getSourceRange(); 1563} 1564 1565/// TryObjectArgumentInitialization - Try to initialize the object 1566/// parameter of the given member function (@c Method) from the 1567/// expression @p From. 1568ImplicitConversionSequence 1569Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) { 1570 QualType ClassType = Context.getTypeDeclType(Method->getParent()); 1571 unsigned MethodQuals = Method->getTypeQualifiers(); 1572 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals); 1573 1574 // Set up the conversion sequence as a "bad" conversion, to allow us 1575 // to exit early. 1576 ImplicitConversionSequence ICS; 1577 ICS.Standard.setAsIdentityConversion(); 1578 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1579 1580 // We need to have an object of class type. 1581 QualType FromType = From->getType(); 1582 if (!FromType->isRecordType()) 1583 return ICS; 1584 1585 // The implicit object parmeter is has the type "reference to cv X", 1586 // where X is the class of which the function is a member 1587 // (C++ [over.match.funcs]p4). However, when finding an implicit 1588 // conversion sequence for the argument, we are not allowed to 1589 // create temporaries or perform user-defined conversions 1590 // (C++ [over.match.funcs]p5). We perform a simplified version of 1591 // reference binding here, that allows class rvalues to bind to 1592 // non-constant references. 1593 1594 // First check the qualifiers. We don't care about lvalue-vs-rvalue 1595 // with the implicit object parameter (C++ [over.match.funcs]p5). 1596 QualType FromTypeCanon = Context.getCanonicalType(FromType); 1597 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() && 1598 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType)) 1599 return ICS; 1600 1601 // Check that we have either the same type or a derived type. It 1602 // affects the conversion rank. 1603 QualType ClassTypeCanon = Context.getCanonicalType(ClassType); 1604 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType()) 1605 ICS.Standard.Second = ICK_Identity; 1606 else if (IsDerivedFrom(FromType, ClassType)) 1607 ICS.Standard.Second = ICK_Derived_To_Base; 1608 else 1609 return ICS; 1610 1611 // Success. Mark this as a reference binding. 1612 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 1613 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr(); 1614 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr(); 1615 ICS.Standard.ReferenceBinding = true; 1616 ICS.Standard.DirectBinding = true; 1617 return ICS; 1618} 1619 1620/// PerformObjectArgumentInitialization - Perform initialization of 1621/// the implicit object parameter for the given Method with the given 1622/// expression. 1623bool 1624Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) { 1625 QualType ImplicitParamType 1626 = Method->getThisType(Context)->getAsPointerType()->getPointeeType(); 1627 ImplicitConversionSequence ICS 1628 = TryObjectArgumentInitialization(From, Method); 1629 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) 1630 return Diag(From->getSourceRange().getBegin(), 1631 diag::err_implicit_object_parameter_init) 1632 << ImplicitParamType << From->getType() << From->getSourceRange(); 1633 1634 if (ICS.Standard.Second == ICK_Derived_To_Base && 1635 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType, 1636 From->getSourceRange().getBegin(), 1637 From->getSourceRange())) 1638 return true; 1639 1640 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true); 1641 return false; 1642} 1643 1644/// AddOverloadCandidate - Adds the given function to the set of 1645/// candidate functions, using the given function call arguments. If 1646/// @p SuppressUserConversions, then don't allow user-defined 1647/// conversions via constructors or conversion operators. 1648void 1649Sema::AddOverloadCandidate(FunctionDecl *Function, 1650 Expr **Args, unsigned NumArgs, 1651 OverloadCandidateSet& CandidateSet, 1652 bool SuppressUserConversions) 1653{ 1654 const FunctionTypeProto* Proto 1655 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType()); 1656 assert(Proto && "Functions without a prototype cannot be overloaded"); 1657 assert(!isa<CXXConversionDecl>(Function) && 1658 "Use AddConversionCandidate for conversion functions"); 1659 1660 // Add this candidate 1661 CandidateSet.push_back(OverloadCandidate()); 1662 OverloadCandidate& Candidate = CandidateSet.back(); 1663 Candidate.Function = Function; 1664 Candidate.IsSurrogate = false; 1665 1666 unsigned NumArgsInProto = Proto->getNumArgs(); 1667 1668 // (C++ 13.3.2p2): A candidate function having fewer than m 1669 // parameters is viable only if it has an ellipsis in its parameter 1670 // list (8.3.5). 1671 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 1672 Candidate.Viable = false; 1673 return; 1674 } 1675 1676 // (C++ 13.3.2p2): A candidate function having more than m parameters 1677 // is viable only if the (m+1)st parameter has a default argument 1678 // (8.3.6). For the purposes of overload resolution, the 1679 // parameter list is truncated on the right, so that there are 1680 // exactly m parameters. 1681 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 1682 if (NumArgs < MinRequiredArgs) { 1683 // Not enough arguments. 1684 Candidate.Viable = false; 1685 return; 1686 } 1687 1688 // Determine the implicit conversion sequences for each of the 1689 // arguments. 1690 Candidate.Viable = true; 1691 Candidate.Conversions.resize(NumArgs); 1692 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1693 if (ArgIdx < NumArgsInProto) { 1694 // (C++ 13.3.2p3): for F to be a viable function, there shall 1695 // exist for each argument an implicit conversion sequence 1696 // (13.3.3.1) that converts that argument to the corresponding 1697 // parameter of F. 1698 QualType ParamType = Proto->getArgType(ArgIdx); 1699 Candidate.Conversions[ArgIdx] 1700 = TryCopyInitialization(Args[ArgIdx], ParamType, 1701 SuppressUserConversions); 1702 if (Candidate.Conversions[ArgIdx].ConversionKind 1703 == ImplicitConversionSequence::BadConversion) { 1704 Candidate.Viable = false; 1705 break; 1706 } 1707 } else { 1708 // (C++ 13.3.2p2): For the purposes of overload resolution, any 1709 // argument for which there is no corresponding parameter is 1710 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 1711 Candidate.Conversions[ArgIdx].ConversionKind 1712 = ImplicitConversionSequence::EllipsisConversion; 1713 } 1714 } 1715} 1716 1717/// AddMethodCandidate - Adds the given C++ member function to the set 1718/// of candidate functions, using the given function call arguments 1719/// and the object argument (@c Object). For example, in a call 1720/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 1721/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 1722/// allow user-defined conversions via constructors or conversion 1723/// operators. 1724void 1725Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object, 1726 Expr **Args, unsigned NumArgs, 1727 OverloadCandidateSet& CandidateSet, 1728 bool SuppressUserConversions) 1729{ 1730 const FunctionTypeProto* Proto 1731 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType()); 1732 assert(Proto && "Methods without a prototype cannot be overloaded"); 1733 assert(!isa<CXXConversionDecl>(Method) && 1734 "Use AddConversionCandidate for conversion functions"); 1735 1736 // Add this candidate 1737 CandidateSet.push_back(OverloadCandidate()); 1738 OverloadCandidate& Candidate = CandidateSet.back(); 1739 Candidate.Function = Method; 1740 Candidate.IsSurrogate = false; 1741 1742 unsigned NumArgsInProto = Proto->getNumArgs(); 1743 1744 // (C++ 13.3.2p2): A candidate function having fewer than m 1745 // parameters is viable only if it has an ellipsis in its parameter 1746 // list (8.3.5). 1747 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 1748 Candidate.Viable = false; 1749 return; 1750 } 1751 1752 // (C++ 13.3.2p2): A candidate function having more than m parameters 1753 // is viable only if the (m+1)st parameter has a default argument 1754 // (8.3.6). For the purposes of overload resolution, the 1755 // parameter list is truncated on the right, so that there are 1756 // exactly m parameters. 1757 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 1758 if (NumArgs < MinRequiredArgs) { 1759 // Not enough arguments. 1760 Candidate.Viable = false; 1761 return; 1762 } 1763 1764 Candidate.Viable = true; 1765 Candidate.Conversions.resize(NumArgs + 1); 1766 1767 // Determine the implicit conversion sequence for the object 1768 // parameter. 1769 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method); 1770 if (Candidate.Conversions[0].ConversionKind 1771 == ImplicitConversionSequence::BadConversion) { 1772 Candidate.Viable = false; 1773 return; 1774 } 1775 1776 // Determine the implicit conversion sequences for each of the 1777 // arguments. 1778 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1779 if (ArgIdx < NumArgsInProto) { 1780 // (C++ 13.3.2p3): for F to be a viable function, there shall 1781 // exist for each argument an implicit conversion sequence 1782 // (13.3.3.1) that converts that argument to the corresponding 1783 // parameter of F. 1784 QualType ParamType = Proto->getArgType(ArgIdx); 1785 Candidate.Conversions[ArgIdx + 1] 1786 = TryCopyInitialization(Args[ArgIdx], ParamType, 1787 SuppressUserConversions); 1788 if (Candidate.Conversions[ArgIdx + 1].ConversionKind 1789 == ImplicitConversionSequence::BadConversion) { 1790 Candidate.Viable = false; 1791 break; 1792 } 1793 } else { 1794 // (C++ 13.3.2p2): For the purposes of overload resolution, any 1795 // argument for which there is no corresponding parameter is 1796 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 1797 Candidate.Conversions[ArgIdx + 1].ConversionKind 1798 = ImplicitConversionSequence::EllipsisConversion; 1799 } 1800 } 1801} 1802 1803/// AddConversionCandidate - Add a C++ conversion function as a 1804/// candidate in the candidate set (C++ [over.match.conv], 1805/// C++ [over.match.copy]). From is the expression we're converting from, 1806/// and ToType is the type that we're eventually trying to convert to 1807/// (which may or may not be the same type as the type that the 1808/// conversion function produces). 1809void 1810Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 1811 Expr *From, QualType ToType, 1812 OverloadCandidateSet& CandidateSet) { 1813 // Add this candidate 1814 CandidateSet.push_back(OverloadCandidate()); 1815 OverloadCandidate& Candidate = CandidateSet.back(); 1816 Candidate.Function = Conversion; 1817 Candidate.IsSurrogate = false; 1818 Candidate.FinalConversion.setAsIdentityConversion(); 1819 Candidate.FinalConversion.FromTypePtr 1820 = Conversion->getConversionType().getAsOpaquePtr(); 1821 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr(); 1822 1823 // Determine the implicit conversion sequence for the implicit 1824 // object parameter. 1825 Candidate.Viable = true; 1826 Candidate.Conversions.resize(1); 1827 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion); 1828 1829 if (Candidate.Conversions[0].ConversionKind 1830 == ImplicitConversionSequence::BadConversion) { 1831 Candidate.Viable = false; 1832 return; 1833 } 1834 1835 // To determine what the conversion from the result of calling the 1836 // conversion function to the type we're eventually trying to 1837 // convert to (ToType), we need to synthesize a call to the 1838 // conversion function and attempt copy initialization from it. This 1839 // makes sure that we get the right semantics with respect to 1840 // lvalues/rvalues and the type. Fortunately, we can allocate this 1841 // call on the stack and we don't need its arguments to be 1842 // well-formed. 1843 DeclRefExpr ConversionRef(Conversion, Conversion->getType(), 1844 SourceLocation()); 1845 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()), 1846 &ConversionRef, false); 1847 CallExpr Call(&ConversionFn, 0, 0, 1848 Conversion->getConversionType().getNonReferenceType(), 1849 SourceLocation()); 1850 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true); 1851 switch (ICS.ConversionKind) { 1852 case ImplicitConversionSequence::StandardConversion: 1853 Candidate.FinalConversion = ICS.Standard; 1854 break; 1855 1856 case ImplicitConversionSequence::BadConversion: 1857 Candidate.Viable = false; 1858 break; 1859 1860 default: 1861 assert(false && 1862 "Can only end up with a standard conversion sequence or failure"); 1863 } 1864} 1865 1866/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 1867/// converts the given @c Object to a function pointer via the 1868/// conversion function @c Conversion, and then attempts to call it 1869/// with the given arguments (C++ [over.call.object]p2-4). Proto is 1870/// the type of function that we'll eventually be calling. 1871void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 1872 const FunctionTypeProto *Proto, 1873 Expr *Object, Expr **Args, unsigned NumArgs, 1874 OverloadCandidateSet& CandidateSet) { 1875 CandidateSet.push_back(OverloadCandidate()); 1876 OverloadCandidate& Candidate = CandidateSet.back(); 1877 Candidate.Function = 0; 1878 Candidate.Surrogate = Conversion; 1879 Candidate.Viable = true; 1880 Candidate.IsSurrogate = true; 1881 Candidate.Conversions.resize(NumArgs + 1); 1882 1883 // Determine the implicit conversion sequence for the implicit 1884 // object parameter. 1885 ImplicitConversionSequence ObjectInit 1886 = TryObjectArgumentInitialization(Object, Conversion); 1887 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) { 1888 Candidate.Viable = false; 1889 return; 1890 } 1891 1892 // The first conversion is actually a user-defined conversion whose 1893 // first conversion is ObjectInit's standard conversion (which is 1894 // effectively a reference binding). Record it as such. 1895 Candidate.Conversions[0].ConversionKind 1896 = ImplicitConversionSequence::UserDefinedConversion; 1897 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 1898 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 1899 Candidate.Conversions[0].UserDefined.After 1900 = Candidate.Conversions[0].UserDefined.Before; 1901 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 1902 1903 // Find the 1904 unsigned NumArgsInProto = Proto->getNumArgs(); 1905 1906 // (C++ 13.3.2p2): A candidate function having fewer than m 1907 // parameters is viable only if it has an ellipsis in its parameter 1908 // list (8.3.5). 1909 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 1910 Candidate.Viable = false; 1911 return; 1912 } 1913 1914 // Function types don't have any default arguments, so just check if 1915 // we have enough arguments. 1916 if (NumArgs < NumArgsInProto) { 1917 // Not enough arguments. 1918 Candidate.Viable = false; 1919 return; 1920 } 1921 1922 // Determine the implicit conversion sequences for each of the 1923 // arguments. 1924 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1925 if (ArgIdx < NumArgsInProto) { 1926 // (C++ 13.3.2p3): for F to be a viable function, there shall 1927 // exist for each argument an implicit conversion sequence 1928 // (13.3.3.1) that converts that argument to the corresponding 1929 // parameter of F. 1930 QualType ParamType = Proto->getArgType(ArgIdx); 1931 Candidate.Conversions[ArgIdx + 1] 1932 = TryCopyInitialization(Args[ArgIdx], ParamType, 1933 /*SuppressUserConversions=*/false); 1934 if (Candidate.Conversions[ArgIdx + 1].ConversionKind 1935 == ImplicitConversionSequence::BadConversion) { 1936 Candidate.Viable = false; 1937 break; 1938 } 1939 } else { 1940 // (C++ 13.3.2p2): For the purposes of overload resolution, any 1941 // argument for which there is no corresponding parameter is 1942 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 1943 Candidate.Conversions[ArgIdx + 1].ConversionKind 1944 = ImplicitConversionSequence::EllipsisConversion; 1945 } 1946 } 1947} 1948 1949/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 1950/// an acceptable non-member overloaded operator for a call whose 1951/// arguments have types T1 (and, if non-empty, T2). This routine 1952/// implements the check in C++ [over.match.oper]p3b2 concerning 1953/// enumeration types. 1954static bool 1955IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn, 1956 QualType T1, QualType T2, 1957 ASTContext &Context) { 1958 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 1959 return true; 1960 1961 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto(); 1962 if (Proto->getNumArgs() < 1) 1963 return false; 1964 1965 if (T1->isEnumeralType()) { 1966 QualType ArgType = Proto->getArgType(0).getNonReferenceType(); 1967 if (Context.getCanonicalType(T1).getUnqualifiedType() 1968 == Context.getCanonicalType(ArgType).getUnqualifiedType()) 1969 return true; 1970 } 1971 1972 if (Proto->getNumArgs() < 2) 1973 return false; 1974 1975 if (!T2.isNull() && T2->isEnumeralType()) { 1976 QualType ArgType = Proto->getArgType(1).getNonReferenceType(); 1977 if (Context.getCanonicalType(T2).getUnqualifiedType() 1978 == Context.getCanonicalType(ArgType).getUnqualifiedType()) 1979 return true; 1980 } 1981 1982 return false; 1983} 1984 1985/// AddOperatorCandidates - Add the overloaded operator candidates for 1986/// the operator Op that was used in an operator expression such as "x 1987/// Op y". S is the scope in which the expression occurred (used for 1988/// name lookup of the operator), Args/NumArgs provides the operator 1989/// arguments, and CandidateSet will store the added overload 1990/// candidates. (C++ [over.match.oper]). 1991void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S, 1992 Expr **Args, unsigned NumArgs, 1993 OverloadCandidateSet& CandidateSet) { 1994 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 1995 1996 // C++ [over.match.oper]p3: 1997 // For a unary operator @ with an operand of a type whose 1998 // cv-unqualified version is T1, and for a binary operator @ with 1999 // a left operand of a type whose cv-unqualified version is T1 and 2000 // a right operand of a type whose cv-unqualified version is T2, 2001 // three sets of candidate functions, designated member 2002 // candidates, non-member candidates and built-in candidates, are 2003 // constructed as follows: 2004 QualType T1 = Args[0]->getType(); 2005 QualType T2; 2006 if (NumArgs > 1) 2007 T2 = Args[1]->getType(); 2008 2009 // -- If T1 is a class type, the set of member candidates is the 2010 // result of the qualified lookup of T1::operator@ 2011 // (13.3.1.1.1); otherwise, the set of member candidates is 2012 // empty. 2013 if (const RecordType *T1Rec = T1->getAsRecordType()) { 2014 DeclContext::lookup_const_result Lookup 2015 = T1Rec->getDecl()->lookup(Context, OpName); 2016 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first; 2017 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps)) 2018 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet, 2019 /*SuppressUserConversions=*/false); 2020 else if (OverloadedFunctionDecl *Ovl 2021 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) { 2022 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 2023 FEnd = Ovl->function_end(); 2024 F != FEnd; ++F) { 2025 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F)) 2026 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet, 2027 /*SuppressUserConversions=*/false); 2028 } 2029 } 2030 } 2031 2032 // -- The set of non-member candidates is the result of the 2033 // unqualified lookup of operator@ in the context of the 2034 // expression according to the usual rules for name lookup in 2035 // unqualified function calls (3.4.2) except that all member 2036 // functions are ignored. However, if no operand has a class 2037 // type, only those non-member functions in the lookup set 2038 // that have a first parameter of type T1 or “reference to 2039 // (possibly cv-qualified) T1”, when T1 is an enumeration 2040 // type, or (if there is a right operand) a second parameter 2041 // of type T2 or “reference to (possibly cv-qualified) T2”, 2042 // when T2 is an enumeration type, are candidate functions. 2043 { 2044 NamedDecl *NonMemberOps = 0; 2045 for (IdentifierResolver::iterator I 2046 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/); 2047 I != IdResolver.end(); ++I) { 2048 // We don't need to check the identifier namespace, because 2049 // operator names can only be ordinary identifiers. 2050 2051 // Ignore member functions. 2052 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) { 2053 if (SD->getDeclContext()->isCXXRecord()) 2054 continue; 2055 } 2056 2057 // We found something with this name. We're done. 2058 NonMemberOps = *I; 2059 break; 2060 } 2061 2062 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) { 2063 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context)) 2064 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet, 2065 /*SuppressUserConversions=*/false); 2066 } else if (OverloadedFunctionDecl *Ovl 2067 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) { 2068 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 2069 FEnd = Ovl->function_end(); 2070 F != FEnd; ++F) { 2071 if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context)) 2072 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet, 2073 /*SuppressUserConversions=*/false); 2074 } 2075 } 2076 } 2077 2078 // Add builtin overload candidates (C++ [over.built]). 2079 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet); 2080} 2081 2082/// AddBuiltinCandidate - Add a candidate for a built-in 2083/// operator. ResultTy and ParamTys are the result and parameter types 2084/// of the built-in candidate, respectively. Args and NumArgs are the 2085/// arguments being passed to the candidate. 2086void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 2087 Expr **Args, unsigned NumArgs, 2088 OverloadCandidateSet& CandidateSet) { 2089 // Add this candidate 2090 CandidateSet.push_back(OverloadCandidate()); 2091 OverloadCandidate& Candidate = CandidateSet.back(); 2092 Candidate.Function = 0; 2093 Candidate.IsSurrogate = false; 2094 Candidate.BuiltinTypes.ResultTy = ResultTy; 2095 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 2096 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 2097 2098 // Determine the implicit conversion sequences for each of the 2099 // arguments. 2100 Candidate.Viable = true; 2101 Candidate.Conversions.resize(NumArgs); 2102 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2103 Candidate.Conversions[ArgIdx] 2104 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false); 2105 if (Candidate.Conversions[ArgIdx].ConversionKind 2106 == ImplicitConversionSequence::BadConversion) { 2107 Candidate.Viable = false; 2108 break; 2109 } 2110 } 2111} 2112 2113/// BuiltinCandidateTypeSet - A set of types that will be used for the 2114/// candidate operator functions for built-in operators (C++ 2115/// [over.built]). The types are separated into pointer types and 2116/// enumeration types. 2117class BuiltinCandidateTypeSet { 2118 /// TypeSet - A set of types. 2119 typedef llvm::SmallPtrSet<void*, 8> TypeSet; 2120 2121 /// PointerTypes - The set of pointer types that will be used in the 2122 /// built-in candidates. 2123 TypeSet PointerTypes; 2124 2125 /// EnumerationTypes - The set of enumeration types that will be 2126 /// used in the built-in candidates. 2127 TypeSet EnumerationTypes; 2128 2129 /// Context - The AST context in which we will build the type sets. 2130 ASTContext &Context; 2131 2132 bool AddWithMoreQualifiedTypeVariants(QualType Ty); 2133 2134public: 2135 /// iterator - Iterates through the types that are part of the set. 2136 class iterator { 2137 TypeSet::iterator Base; 2138 2139 public: 2140 typedef QualType value_type; 2141 typedef QualType reference; 2142 typedef QualType pointer; 2143 typedef std::ptrdiff_t difference_type; 2144 typedef std::input_iterator_tag iterator_category; 2145 2146 iterator(TypeSet::iterator B) : Base(B) { } 2147 2148 iterator& operator++() { 2149 ++Base; 2150 return *this; 2151 } 2152 2153 iterator operator++(int) { 2154 iterator tmp(*this); 2155 ++(*this); 2156 return tmp; 2157 } 2158 2159 reference operator*() const { 2160 return QualType::getFromOpaquePtr(*Base); 2161 } 2162 2163 pointer operator->() const { 2164 return **this; 2165 } 2166 2167 friend bool operator==(iterator LHS, iterator RHS) { 2168 return LHS.Base == RHS.Base; 2169 } 2170 2171 friend bool operator!=(iterator LHS, iterator RHS) { 2172 return LHS.Base != RHS.Base; 2173 } 2174 }; 2175 2176 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { } 2177 2178 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true); 2179 2180 /// pointer_begin - First pointer type found; 2181 iterator pointer_begin() { return PointerTypes.begin(); } 2182 2183 /// pointer_end - Last pointer type found; 2184 iterator pointer_end() { return PointerTypes.end(); } 2185 2186 /// enumeration_begin - First enumeration type found; 2187 iterator enumeration_begin() { return EnumerationTypes.begin(); } 2188 2189 /// enumeration_end - Last enumeration type found; 2190 iterator enumeration_end() { return EnumerationTypes.end(); } 2191}; 2192 2193/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 2194/// the set of pointer types along with any more-qualified variants of 2195/// that type. For example, if @p Ty is "int const *", this routine 2196/// will add "int const *", "int const volatile *", "int const 2197/// restrict *", and "int const volatile restrict *" to the set of 2198/// pointer types. Returns true if the add of @p Ty itself succeeded, 2199/// false otherwise. 2200bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) { 2201 // Insert this type. 2202 if (!PointerTypes.insert(Ty.getAsOpaquePtr())) 2203 return false; 2204 2205 if (const PointerType *PointerTy = Ty->getAsPointerType()) { 2206 QualType PointeeTy = PointerTy->getPointeeType(); 2207 // FIXME: Optimize this so that we don't keep trying to add the same types. 2208 2209 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal 2210 // with all pointer conversions that don't cast away constness? 2211 if (!PointeeTy.isConstQualified()) 2212 AddWithMoreQualifiedTypeVariants 2213 (Context.getPointerType(PointeeTy.withConst())); 2214 if (!PointeeTy.isVolatileQualified()) 2215 AddWithMoreQualifiedTypeVariants 2216 (Context.getPointerType(PointeeTy.withVolatile())); 2217 if (!PointeeTy.isRestrictQualified()) 2218 AddWithMoreQualifiedTypeVariants 2219 (Context.getPointerType(PointeeTy.withRestrict())); 2220 } 2221 2222 return true; 2223} 2224 2225/// AddTypesConvertedFrom - Add each of the types to which the type @p 2226/// Ty can be implicit converted to the given set of @p Types. We're 2227/// primarily interested in pointer types, enumeration types, 2228void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 2229 bool AllowUserConversions) { 2230 // Only deal with canonical types. 2231 Ty = Context.getCanonicalType(Ty); 2232 2233 // Look through reference types; they aren't part of the type of an 2234 // expression for the purposes of conversions. 2235 if (const ReferenceType *RefTy = Ty->getAsReferenceType()) 2236 Ty = RefTy->getPointeeType(); 2237 2238 // We don't care about qualifiers on the type. 2239 Ty = Ty.getUnqualifiedType(); 2240 2241 if (const PointerType *PointerTy = Ty->getAsPointerType()) { 2242 QualType PointeeTy = PointerTy->getPointeeType(); 2243 2244 // Insert our type, and its more-qualified variants, into the set 2245 // of types. 2246 if (!AddWithMoreQualifiedTypeVariants(Ty)) 2247 return; 2248 2249 // Add 'cv void*' to our set of types. 2250 if (!Ty->isVoidType()) { 2251 QualType QualVoid 2252 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers()); 2253 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid)); 2254 } 2255 2256 // If this is a pointer to a class type, add pointers to its bases 2257 // (with the same level of cv-qualification as the original 2258 // derived class, of course). 2259 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) { 2260 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl()); 2261 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2262 Base != ClassDecl->bases_end(); ++Base) { 2263 QualType BaseTy = Context.getCanonicalType(Base->getType()); 2264 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers()); 2265 2266 // Add the pointer type, recursively, so that we get all of 2267 // the indirect base classes, too. 2268 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false); 2269 } 2270 } 2271 } else if (Ty->isEnumeralType()) { 2272 EnumerationTypes.insert(Ty.getAsOpaquePtr()); 2273 } else if (AllowUserConversions) { 2274 if (const RecordType *TyRec = Ty->getAsRecordType()) { 2275 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 2276 // FIXME: Visit conversion functions in the base classes, too. 2277 OverloadedFunctionDecl *Conversions 2278 = ClassDecl->getConversionFunctions(); 2279 for (OverloadedFunctionDecl::function_iterator Func 2280 = Conversions->function_begin(); 2281 Func != Conversions->function_end(); ++Func) { 2282 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 2283 AddTypesConvertedFrom(Conv->getConversionType(), false); 2284 } 2285 } 2286 } 2287} 2288 2289/// AddBuiltinOperatorCandidates - Add the appropriate built-in 2290/// operator overloads to the candidate set (C++ [over.built]), based 2291/// on the operator @p Op and the arguments given. For example, if the 2292/// operator is a binary '+', this routine might add "int 2293/// operator+(int, int)" to cover integer addition. 2294void 2295Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 2296 Expr **Args, unsigned NumArgs, 2297 OverloadCandidateSet& CandidateSet) { 2298 // The set of "promoted arithmetic types", which are the arithmetic 2299 // types are that preserved by promotion (C++ [over.built]p2). Note 2300 // that the first few of these types are the promoted integral 2301 // types; these types need to be first. 2302 // FIXME: What about complex? 2303 const unsigned FirstIntegralType = 0; 2304 const unsigned LastIntegralType = 13; 2305 const unsigned FirstPromotedIntegralType = 7, 2306 LastPromotedIntegralType = 13; 2307 const unsigned FirstPromotedArithmeticType = 7, 2308 LastPromotedArithmeticType = 16; 2309 const unsigned NumArithmeticTypes = 16; 2310 QualType ArithmeticTypes[NumArithmeticTypes] = { 2311 Context.BoolTy, Context.CharTy, Context.WCharTy, 2312 Context.SignedCharTy, Context.ShortTy, 2313 Context.UnsignedCharTy, Context.UnsignedShortTy, 2314 Context.IntTy, Context.LongTy, Context.LongLongTy, 2315 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy, 2316 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy 2317 }; 2318 2319 // Find all of the types that the arguments can convert to, but only 2320 // if the operator we're looking at has built-in operator candidates 2321 // that make use of these types. 2322 BuiltinCandidateTypeSet CandidateTypes(Context); 2323 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual || 2324 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual || 2325 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal || 2326 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript || 2327 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus || 2328 (Op == OO_Star && NumArgs == 1)) { 2329 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 2330 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType()); 2331 } 2332 2333 bool isComparison = false; 2334 switch (Op) { 2335 case OO_None: 2336 case NUM_OVERLOADED_OPERATORS: 2337 assert(false && "Expected an overloaded operator"); 2338 break; 2339 2340 case OO_Star: // '*' is either unary or binary 2341 if (NumArgs == 1) 2342 goto UnaryStar; 2343 else 2344 goto BinaryStar; 2345 break; 2346 2347 case OO_Plus: // '+' is either unary or binary 2348 if (NumArgs == 1) 2349 goto UnaryPlus; 2350 else 2351 goto BinaryPlus; 2352 break; 2353 2354 case OO_Minus: // '-' is either unary or binary 2355 if (NumArgs == 1) 2356 goto UnaryMinus; 2357 else 2358 goto BinaryMinus; 2359 break; 2360 2361 case OO_Amp: // '&' is either unary or binary 2362 if (NumArgs == 1) 2363 goto UnaryAmp; 2364 else 2365 goto BinaryAmp; 2366 2367 case OO_PlusPlus: 2368 case OO_MinusMinus: 2369 // C++ [over.built]p3: 2370 // 2371 // For every pair (T, VQ), where T is an arithmetic type, and VQ 2372 // is either volatile or empty, there exist candidate operator 2373 // functions of the form 2374 // 2375 // VQ T& operator++(VQ T&); 2376 // T operator++(VQ T&, int); 2377 // 2378 // C++ [over.built]p4: 2379 // 2380 // For every pair (T, VQ), where T is an arithmetic type other 2381 // than bool, and VQ is either volatile or empty, there exist 2382 // candidate operator functions of the form 2383 // 2384 // VQ T& operator--(VQ T&); 2385 // T operator--(VQ T&, int); 2386 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 2387 Arith < NumArithmeticTypes; ++Arith) { 2388 QualType ArithTy = ArithmeticTypes[Arith]; 2389 QualType ParamTypes[2] 2390 = { Context.getReferenceType(ArithTy), Context.IntTy }; 2391 2392 // Non-volatile version. 2393 if (NumArgs == 1) 2394 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2395 else 2396 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 2397 2398 // Volatile version 2399 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile()); 2400 if (NumArgs == 1) 2401 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2402 else 2403 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 2404 } 2405 2406 // C++ [over.built]p5: 2407 // 2408 // For every pair (T, VQ), where T is a cv-qualified or 2409 // cv-unqualified object type, and VQ is either volatile or 2410 // empty, there exist candidate operator functions of the form 2411 // 2412 // T*VQ& operator++(T*VQ&); 2413 // T*VQ& operator--(T*VQ&); 2414 // T* operator++(T*VQ&, int); 2415 // T* operator--(T*VQ&, int); 2416 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2417 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2418 // Skip pointer types that aren't pointers to object types. 2419 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType()) 2420 continue; 2421 2422 QualType ParamTypes[2] = { 2423 Context.getReferenceType(*Ptr), Context.IntTy 2424 }; 2425 2426 // Without volatile 2427 if (NumArgs == 1) 2428 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2429 else 2430 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2431 2432 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) { 2433 // With volatile 2434 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile()); 2435 if (NumArgs == 1) 2436 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2437 else 2438 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2439 } 2440 } 2441 break; 2442 2443 UnaryStar: 2444 // C++ [over.built]p6: 2445 // For every cv-qualified or cv-unqualified object type T, there 2446 // exist candidate operator functions of the form 2447 // 2448 // T& operator*(T*); 2449 // 2450 // C++ [over.built]p7: 2451 // For every function type T, there exist candidate operator 2452 // functions of the form 2453 // T& operator*(T*); 2454 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2455 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2456 QualType ParamTy = *Ptr; 2457 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType(); 2458 AddBuiltinCandidate(Context.getReferenceType(PointeeTy), 2459 &ParamTy, Args, 1, CandidateSet); 2460 } 2461 break; 2462 2463 UnaryPlus: 2464 // C++ [over.built]p8: 2465 // For every type T, there exist candidate operator functions of 2466 // the form 2467 // 2468 // T* operator+(T*); 2469 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2470 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2471 QualType ParamTy = *Ptr; 2472 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 2473 } 2474 2475 // Fall through 2476 2477 UnaryMinus: 2478 // C++ [over.built]p9: 2479 // For every promoted arithmetic type T, there exist candidate 2480 // operator functions of the form 2481 // 2482 // T operator+(T); 2483 // T operator-(T); 2484 for (unsigned Arith = FirstPromotedArithmeticType; 2485 Arith < LastPromotedArithmeticType; ++Arith) { 2486 QualType ArithTy = ArithmeticTypes[Arith]; 2487 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 2488 } 2489 break; 2490 2491 case OO_Tilde: 2492 // C++ [over.built]p10: 2493 // For every promoted integral type T, there exist candidate 2494 // operator functions of the form 2495 // 2496 // T operator~(T); 2497 for (unsigned Int = FirstPromotedIntegralType; 2498 Int < LastPromotedIntegralType; ++Int) { 2499 QualType IntTy = ArithmeticTypes[Int]; 2500 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 2501 } 2502 break; 2503 2504 case OO_New: 2505 case OO_Delete: 2506 case OO_Array_New: 2507 case OO_Array_Delete: 2508 case OO_Call: 2509 assert(false && "Special operators don't use AddBuiltinOperatorCandidates"); 2510 break; 2511 2512 case OO_Comma: 2513 UnaryAmp: 2514 case OO_Arrow: 2515 // C++ [over.match.oper]p3: 2516 // -- For the operator ',', the unary operator '&', or the 2517 // operator '->', the built-in candidates set is empty. 2518 break; 2519 2520 case OO_Less: 2521 case OO_Greater: 2522 case OO_LessEqual: 2523 case OO_GreaterEqual: 2524 case OO_EqualEqual: 2525 case OO_ExclaimEqual: 2526 // C++ [over.built]p15: 2527 // 2528 // For every pointer or enumeration type T, there exist 2529 // candidate operator functions of the form 2530 // 2531 // bool operator<(T, T); 2532 // bool operator>(T, T); 2533 // bool operator<=(T, T); 2534 // bool operator>=(T, T); 2535 // bool operator==(T, T); 2536 // bool operator!=(T, T); 2537 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2538 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2539 QualType ParamTypes[2] = { *Ptr, *Ptr }; 2540 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2541 } 2542 for (BuiltinCandidateTypeSet::iterator Enum 2543 = CandidateTypes.enumeration_begin(); 2544 Enum != CandidateTypes.enumeration_end(); ++Enum) { 2545 QualType ParamTypes[2] = { *Enum, *Enum }; 2546 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2547 } 2548 2549 // Fall through. 2550 isComparison = true; 2551 2552 BinaryPlus: 2553 BinaryMinus: 2554 if (!isComparison) { 2555 // We didn't fall through, so we must have OO_Plus or OO_Minus. 2556 2557 // C++ [over.built]p13: 2558 // 2559 // For every cv-qualified or cv-unqualified object type T 2560 // there exist candidate operator functions of the form 2561 // 2562 // T* operator+(T*, ptrdiff_t); 2563 // T& operator[](T*, ptrdiff_t); [BELOW] 2564 // T* operator-(T*, ptrdiff_t); 2565 // T* operator+(ptrdiff_t, T*); 2566 // T& operator[](ptrdiff_t, T*); [BELOW] 2567 // 2568 // C++ [over.built]p14: 2569 // 2570 // For every T, where T is a pointer to object type, there 2571 // exist candidate operator functions of the form 2572 // 2573 // ptrdiff_t operator-(T, T); 2574 for (BuiltinCandidateTypeSet::iterator Ptr 2575 = CandidateTypes.pointer_begin(); 2576 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2577 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 2578 2579 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 2580 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2581 2582 if (Op == OO_Plus) { 2583 // T* operator+(ptrdiff_t, T*); 2584 ParamTypes[0] = ParamTypes[1]; 2585 ParamTypes[1] = *Ptr; 2586 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2587 } else { 2588 // ptrdiff_t operator-(T, T); 2589 ParamTypes[1] = *Ptr; 2590 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes, 2591 Args, 2, CandidateSet); 2592 } 2593 } 2594 } 2595 // Fall through 2596 2597 case OO_Slash: 2598 BinaryStar: 2599 // C++ [over.built]p12: 2600 // 2601 // For every pair of promoted arithmetic types L and R, there 2602 // exist candidate operator functions of the form 2603 // 2604 // LR operator*(L, R); 2605 // LR operator/(L, R); 2606 // LR operator+(L, R); 2607 // LR operator-(L, R); 2608 // bool operator<(L, R); 2609 // bool operator>(L, R); 2610 // bool operator<=(L, R); 2611 // bool operator>=(L, R); 2612 // bool operator==(L, R); 2613 // bool operator!=(L, R); 2614 // 2615 // where LR is the result of the usual arithmetic conversions 2616 // between types L and R. 2617 for (unsigned Left = FirstPromotedArithmeticType; 2618 Left < LastPromotedArithmeticType; ++Left) { 2619 for (unsigned Right = FirstPromotedArithmeticType; 2620 Right < LastPromotedArithmeticType; ++Right) { 2621 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 2622 QualType Result 2623 = isComparison? Context.BoolTy 2624 : UsualArithmeticConversionsType(LandR[0], LandR[1]); 2625 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 2626 } 2627 } 2628 break; 2629 2630 case OO_Percent: 2631 BinaryAmp: 2632 case OO_Caret: 2633 case OO_Pipe: 2634 case OO_LessLess: 2635 case OO_GreaterGreater: 2636 // C++ [over.built]p17: 2637 // 2638 // For every pair of promoted integral types L and R, there 2639 // exist candidate operator functions of the form 2640 // 2641 // LR operator%(L, R); 2642 // LR operator&(L, R); 2643 // LR operator^(L, R); 2644 // LR operator|(L, R); 2645 // L operator<<(L, R); 2646 // L operator>>(L, R); 2647 // 2648 // where LR is the result of the usual arithmetic conversions 2649 // between types L and R. 2650 for (unsigned Left = FirstPromotedIntegralType; 2651 Left < LastPromotedIntegralType; ++Left) { 2652 for (unsigned Right = FirstPromotedIntegralType; 2653 Right < LastPromotedIntegralType; ++Right) { 2654 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 2655 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 2656 ? LandR[0] 2657 : UsualArithmeticConversionsType(LandR[0], LandR[1]); 2658 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 2659 } 2660 } 2661 break; 2662 2663 case OO_Equal: 2664 // C++ [over.built]p20: 2665 // 2666 // For every pair (T, VQ), where T is an enumeration or 2667 // (FIXME:) pointer to member type and VQ is either volatile or 2668 // empty, there exist candidate operator functions of the form 2669 // 2670 // VQ T& operator=(VQ T&, T); 2671 for (BuiltinCandidateTypeSet::iterator Enum 2672 = CandidateTypes.enumeration_begin(); 2673 Enum != CandidateTypes.enumeration_end(); ++Enum) { 2674 QualType ParamTypes[2]; 2675 2676 // T& operator=(T&, T) 2677 ParamTypes[0] = Context.getReferenceType(*Enum); 2678 ParamTypes[1] = *Enum; 2679 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2680 2681 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) { 2682 // volatile T& operator=(volatile T&, T) 2683 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile()); 2684 ParamTypes[1] = *Enum; 2685 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2686 } 2687 } 2688 // Fall through. 2689 2690 case OO_PlusEqual: 2691 case OO_MinusEqual: 2692 // C++ [over.built]p19: 2693 // 2694 // For every pair (T, VQ), where T is any type and VQ is either 2695 // volatile or empty, there exist candidate operator functions 2696 // of the form 2697 // 2698 // T*VQ& operator=(T*VQ&, T*); 2699 // 2700 // C++ [over.built]p21: 2701 // 2702 // For every pair (T, VQ), where T is a cv-qualified or 2703 // cv-unqualified object type and VQ is either volatile or 2704 // empty, there exist candidate operator functions of the form 2705 // 2706 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 2707 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 2708 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2709 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2710 QualType ParamTypes[2]; 2711 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType(); 2712 2713 // non-volatile version 2714 ParamTypes[0] = Context.getReferenceType(*Ptr); 2715 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2716 2717 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) { 2718 // volatile version 2719 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile()); 2720 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2721 } 2722 } 2723 // Fall through. 2724 2725 case OO_StarEqual: 2726 case OO_SlashEqual: 2727 // C++ [over.built]p18: 2728 // 2729 // For every triple (L, VQ, R), where L is an arithmetic type, 2730 // VQ is either volatile or empty, and R is a promoted 2731 // arithmetic type, there exist candidate operator functions of 2732 // the form 2733 // 2734 // VQ L& operator=(VQ L&, R); 2735 // VQ L& operator*=(VQ L&, R); 2736 // VQ L& operator/=(VQ L&, R); 2737 // VQ L& operator+=(VQ L&, R); 2738 // VQ L& operator-=(VQ L&, R); 2739 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 2740 for (unsigned Right = FirstPromotedArithmeticType; 2741 Right < LastPromotedArithmeticType; ++Right) { 2742 QualType ParamTypes[2]; 2743 ParamTypes[1] = ArithmeticTypes[Right]; 2744 2745 // Add this built-in operator as a candidate (VQ is empty). 2746 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]); 2747 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2748 2749 // Add this built-in operator as a candidate (VQ is 'volatile'). 2750 ParamTypes[0] = ArithmeticTypes[Left].withVolatile(); 2751 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]); 2752 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2753 } 2754 } 2755 break; 2756 2757 case OO_PercentEqual: 2758 case OO_LessLessEqual: 2759 case OO_GreaterGreaterEqual: 2760 case OO_AmpEqual: 2761 case OO_CaretEqual: 2762 case OO_PipeEqual: 2763 // C++ [over.built]p22: 2764 // 2765 // For every triple (L, VQ, R), where L is an integral type, VQ 2766 // is either volatile or empty, and R is a promoted integral 2767 // type, there exist candidate operator functions of the form 2768 // 2769 // VQ L& operator%=(VQ L&, R); 2770 // VQ L& operator<<=(VQ L&, R); 2771 // VQ L& operator>>=(VQ L&, R); 2772 // VQ L& operator&=(VQ L&, R); 2773 // VQ L& operator^=(VQ L&, R); 2774 // VQ L& operator|=(VQ L&, R); 2775 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 2776 for (unsigned Right = FirstPromotedIntegralType; 2777 Right < LastPromotedIntegralType; ++Right) { 2778 QualType ParamTypes[2]; 2779 ParamTypes[1] = ArithmeticTypes[Right]; 2780 2781 // Add this built-in operator as a candidate (VQ is empty). 2782 // FIXME: We should be caching these declarations somewhere, 2783 // rather than re-building them every time. 2784 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]); 2785 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2786 2787 // Add this built-in operator as a candidate (VQ is 'volatile'). 2788 ParamTypes[0] = ArithmeticTypes[Left]; 2789 ParamTypes[0].addVolatile(); 2790 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]); 2791 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2792 } 2793 } 2794 break; 2795 2796 case OO_Exclaim: { 2797 // C++ [over.operator]p23: 2798 // 2799 // There also exist candidate operator functions of the form 2800 // 2801 // bool operator!(bool); 2802 // bool operator&&(bool, bool); [BELOW] 2803 // bool operator||(bool, bool); [BELOW] 2804 QualType ParamTy = Context.BoolTy; 2805 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 2806 break; 2807 } 2808 2809 case OO_AmpAmp: 2810 case OO_PipePipe: { 2811 // C++ [over.operator]p23: 2812 // 2813 // There also exist candidate operator functions of the form 2814 // 2815 // bool operator!(bool); [ABOVE] 2816 // bool operator&&(bool, bool); 2817 // bool operator||(bool, bool); 2818 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy }; 2819 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2820 break; 2821 } 2822 2823 case OO_Subscript: 2824 // C++ [over.built]p13: 2825 // 2826 // For every cv-qualified or cv-unqualified object type T there 2827 // exist candidate operator functions of the form 2828 // 2829 // T* operator+(T*, ptrdiff_t); [ABOVE] 2830 // T& operator[](T*, ptrdiff_t); 2831 // T* operator-(T*, ptrdiff_t); [ABOVE] 2832 // T* operator+(ptrdiff_t, T*); [ABOVE] 2833 // T& operator[](ptrdiff_t, T*); 2834 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2835 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2836 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 2837 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType(); 2838 QualType ResultTy = Context.getReferenceType(PointeeType); 2839 2840 // T& operator[](T*, ptrdiff_t) 2841 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 2842 2843 // T& operator[](ptrdiff_t, T*); 2844 ParamTypes[0] = ParamTypes[1]; 2845 ParamTypes[1] = *Ptr; 2846 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 2847 } 2848 break; 2849 2850 case OO_ArrowStar: 2851 // FIXME: No support for pointer-to-members yet. 2852 break; 2853 } 2854} 2855 2856/// AddOverloadCandidates - Add all of the function overloads in Ovl 2857/// to the candidate set. 2858void 2859Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl, 2860 Expr **Args, unsigned NumArgs, 2861 OverloadCandidateSet& CandidateSet, 2862 bool SuppressUserConversions) 2863{ 2864 for (OverloadedFunctionDecl::function_const_iterator Func 2865 = Ovl->function_begin(); 2866 Func != Ovl->function_end(); ++Func) 2867 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet, 2868 SuppressUserConversions); 2869} 2870 2871/// isBetterOverloadCandidate - Determines whether the first overload 2872/// candidate is a better candidate than the second (C++ 13.3.3p1). 2873bool 2874Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1, 2875 const OverloadCandidate& Cand2) 2876{ 2877 // Define viable functions to be better candidates than non-viable 2878 // functions. 2879 if (!Cand2.Viable) 2880 return Cand1.Viable; 2881 else if (!Cand1.Viable) 2882 return false; 2883 2884 // FIXME: Deal with the implicit object parameter for static member 2885 // functions. (C++ 13.3.3p1). 2886 2887 // (C++ 13.3.3p1): a viable function F1 is defined to be a better 2888 // function than another viable function F2 if for all arguments i, 2889 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and 2890 // then... 2891 unsigned NumArgs = Cand1.Conversions.size(); 2892 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 2893 bool HasBetterConversion = false; 2894 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2895 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx], 2896 Cand2.Conversions[ArgIdx])) { 2897 case ImplicitConversionSequence::Better: 2898 // Cand1 has a better conversion sequence. 2899 HasBetterConversion = true; 2900 break; 2901 2902 case ImplicitConversionSequence::Worse: 2903 // Cand1 can't be better than Cand2. 2904 return false; 2905 2906 case ImplicitConversionSequence::Indistinguishable: 2907 // Do nothing. 2908 break; 2909 } 2910 } 2911 2912 if (HasBetterConversion) 2913 return true; 2914 2915 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be 2916 // implemented, but they require template support. 2917 2918 // C++ [over.match.best]p1b4: 2919 // 2920 // -- the context is an initialization by user-defined conversion 2921 // (see 8.5, 13.3.1.5) and the standard conversion sequence 2922 // from the return type of F1 to the destination type (i.e., 2923 // the type of the entity being initialized) is a better 2924 // conversion sequence than the standard conversion sequence 2925 // from the return type of F2 to the destination type. 2926 if (Cand1.Function && Cand2.Function && 2927 isa<CXXConversionDecl>(Cand1.Function) && 2928 isa<CXXConversionDecl>(Cand2.Function)) { 2929 switch (CompareStandardConversionSequences(Cand1.FinalConversion, 2930 Cand2.FinalConversion)) { 2931 case ImplicitConversionSequence::Better: 2932 // Cand1 has a better conversion sequence. 2933 return true; 2934 2935 case ImplicitConversionSequence::Worse: 2936 // Cand1 can't be better than Cand2. 2937 return false; 2938 2939 case ImplicitConversionSequence::Indistinguishable: 2940 // Do nothing 2941 break; 2942 } 2943 } 2944 2945 return false; 2946} 2947 2948/// BestViableFunction - Computes the best viable function (C++ 13.3.3) 2949/// within an overload candidate set. If overloading is successful, 2950/// the result will be OR_Success and Best will be set to point to the 2951/// best viable function within the candidate set. Otherwise, one of 2952/// several kinds of errors will be returned; see 2953/// Sema::OverloadingResult. 2954Sema::OverloadingResult 2955Sema::BestViableFunction(OverloadCandidateSet& CandidateSet, 2956 OverloadCandidateSet::iterator& Best) 2957{ 2958 // Find the best viable function. 2959 Best = CandidateSet.end(); 2960 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 2961 Cand != CandidateSet.end(); ++Cand) { 2962 if (Cand->Viable) { 2963 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best)) 2964 Best = Cand; 2965 } 2966 } 2967 2968 // If we didn't find any viable functions, abort. 2969 if (Best == CandidateSet.end()) 2970 return OR_No_Viable_Function; 2971 2972 // Make sure that this function is better than every other viable 2973 // function. If not, we have an ambiguity. 2974 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 2975 Cand != CandidateSet.end(); ++Cand) { 2976 if (Cand->Viable && 2977 Cand != Best && 2978 !isBetterOverloadCandidate(*Best, *Cand)) { 2979 Best = CandidateSet.end(); 2980 return OR_Ambiguous; 2981 } 2982 } 2983 2984 // Best is the best viable function. 2985 return OR_Success; 2986} 2987 2988/// PrintOverloadCandidates - When overload resolution fails, prints 2989/// diagnostic messages containing the candidates in the candidate 2990/// set. If OnlyViable is true, only viable candidates will be printed. 2991void 2992Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet, 2993 bool OnlyViable) 2994{ 2995 OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 2996 LastCand = CandidateSet.end(); 2997 for (; Cand != LastCand; ++Cand) { 2998 if (Cand->Viable || !OnlyViable) { 2999 if (Cand->Function) { 3000 // Normal function 3001 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate); 3002 } else if (Cand->IsSurrogate) { 3003 // Desugar the type of the surrogate down to a function type, 3004 // retaining as many typedefs as possible while still showing 3005 // the function type (and, therefore, its parameter types). 3006 QualType FnType = Cand->Surrogate->getConversionType(); 3007 bool isReference = false; 3008 bool isPointer = false; 3009 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) { 3010 FnType = FnTypeRef->getPointeeType(); 3011 isReference = true; 3012 } 3013 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) { 3014 FnType = FnTypePtr->getPointeeType(); 3015 isPointer = true; 3016 } 3017 // Desugar down to a function type. 3018 FnType = QualType(FnType->getAsFunctionType(), 0); 3019 // Reconstruct the pointer/reference as appropriate. 3020 if (isPointer) FnType = Context.getPointerType(FnType); 3021 if (isReference) FnType = Context.getReferenceType(FnType); 3022 3023 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand) 3024 << FnType; 3025 } else { 3026 // FIXME: We need to get the identifier in here 3027 // FIXME: Do we want the error message to point at the 3028 // operator? (built-ins won't have a location) 3029 QualType FnType 3030 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy, 3031 Cand->BuiltinTypes.ParamTypes, 3032 Cand->Conversions.size(), 3033 false, 0); 3034 3035 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType; 3036 } 3037 } 3038 } 3039} 3040 3041/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 3042/// an overloaded function (C++ [over.over]), where @p From is an 3043/// expression with overloaded function type and @p ToType is the type 3044/// we're trying to resolve to. For example: 3045/// 3046/// @code 3047/// int f(double); 3048/// int f(int); 3049/// 3050/// int (*pfd)(double) = f; // selects f(double) 3051/// @endcode 3052/// 3053/// This routine returns the resulting FunctionDecl if it could be 3054/// resolved, and NULL otherwise. When @p Complain is true, this 3055/// routine will emit diagnostics if there is an error. 3056FunctionDecl * 3057Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType, 3058 bool Complain) { 3059 QualType FunctionType = ToType; 3060 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType()) 3061 FunctionType = ToTypePtr->getPointeeType(); 3062 3063 // We only look at pointers or references to functions. 3064 if (!FunctionType->isFunctionType()) 3065 return 0; 3066 3067 // Find the actual overloaded function declaration. 3068 OverloadedFunctionDecl *Ovl = 0; 3069 3070 // C++ [over.over]p1: 3071 // [...] [Note: any redundant set of parentheses surrounding the 3072 // overloaded function name is ignored (5.1). ] 3073 Expr *OvlExpr = From->IgnoreParens(); 3074 3075 // C++ [over.over]p1: 3076 // [...] The overloaded function name can be preceded by the & 3077 // operator. 3078 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) { 3079 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 3080 OvlExpr = UnOp->getSubExpr()->IgnoreParens(); 3081 } 3082 3083 // Try to dig out the overloaded function. 3084 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) 3085 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl()); 3086 3087 // If there's no overloaded function declaration, we're done. 3088 if (!Ovl) 3089 return 0; 3090 3091 // Look through all of the overloaded functions, searching for one 3092 // whose type matches exactly. 3093 // FIXME: When templates or using declarations come along, we'll actually 3094 // have to deal with duplicates, partial ordering, etc. For now, we 3095 // can just do a simple search. 3096 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType()); 3097 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin(); 3098 Fun != Ovl->function_end(); ++Fun) { 3099 // C++ [over.over]p3: 3100 // Non-member functions and static member functions match 3101 // targets of type “pointer-to-function”or 3102 // “reference-to-function.” 3103 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) 3104 if (!Method->isStatic()) 3105 continue; 3106 3107 if (FunctionType == Context.getCanonicalType((*Fun)->getType())) 3108 return *Fun; 3109 } 3110 3111 return 0; 3112} 3113 3114/// ResolveOverloadedCallFn - Given the call expression that calls Fn 3115/// (which eventually refers to the set of overloaded functions in 3116/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the 3117/// function call down to a specific function. If overload resolution 3118/// succeeds, returns the function declaration produced by overload 3119/// resolution. Otherwise, emits diagnostics, deletes all of the 3120/// arguments and Fn, and returns NULL. 3121FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl, 3122 SourceLocation LParenLoc, 3123 Expr **Args, unsigned NumArgs, 3124 SourceLocation *CommaLocs, 3125 SourceLocation RParenLoc) { 3126 OverloadCandidateSet CandidateSet; 3127 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet); 3128 OverloadCandidateSet::iterator Best; 3129 switch (BestViableFunction(CandidateSet, Best)) { 3130 case OR_Success: 3131 return Best->Function; 3132 3133 case OR_No_Viable_Function: 3134 Diag(Fn->getSourceRange().getBegin(), 3135 diag::err_ovl_no_viable_function_in_call) 3136 << Ovl->getDeclName() << (unsigned)CandidateSet.size() 3137 << Fn->getSourceRange(); 3138 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3139 break; 3140 3141 case OR_Ambiguous: 3142 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 3143 << Ovl->getDeclName() << Fn->getSourceRange(); 3144 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3145 break; 3146 } 3147 3148 // Overload resolution failed. Destroy all of the subexpressions and 3149 // return NULL. 3150 Fn->Destroy(Context); 3151 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) 3152 Args[Arg]->Destroy(Context); 3153 return 0; 3154} 3155 3156/// BuildCallToObjectOfClassType - Build a call to an object of class 3157/// type (C++ [over.call.object]), which can end up invoking an 3158/// overloaded function call operator (@c operator()) or performing a 3159/// user-defined conversion on the object argument. 3160Action::ExprResult 3161Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object, 3162 SourceLocation LParenLoc, 3163 Expr **Args, unsigned NumArgs, 3164 SourceLocation *CommaLocs, 3165 SourceLocation RParenLoc) { 3166 assert(Object->getType()->isRecordType() && "Requires object type argument"); 3167 const RecordType *Record = Object->getType()->getAsRecordType(); 3168 3169 // C++ [over.call.object]p1: 3170 // If the primary-expression E in the function call syntax 3171 // evaluates to a class object of type “cv T”, then the set of 3172 // candidate functions includes at least the function call 3173 // operators of T. The function call operators of T are obtained by 3174 // ordinary lookup of the name operator() in the context of 3175 // (E).operator(). 3176 OverloadCandidateSet CandidateSet; 3177 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 3178 DeclContext::lookup_const_result Lookup 3179 = Record->getDecl()->lookup(Context, OpName); 3180 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first; 3181 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps)) 3182 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet, 3183 /*SuppressUserConversions=*/false); 3184 else if (OverloadedFunctionDecl *Ovl 3185 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) { 3186 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 3187 FEnd = Ovl->function_end(); 3188 F != FEnd; ++F) { 3189 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F)) 3190 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet, 3191 /*SuppressUserConversions=*/false); 3192 } 3193 } 3194 3195 // C++ [over.call.object]p2: 3196 // In addition, for each conversion function declared in T of the 3197 // form 3198 // 3199 // operator conversion-type-id () cv-qualifier; 3200 // 3201 // where cv-qualifier is the same cv-qualification as, or a 3202 // greater cv-qualification than, cv, and where conversion-type-id 3203 // denotes the type "pointer to function of (P1,...,Pn) returning 3204 // R", or the type "reference to pointer to function of 3205 // (P1,...,Pn) returning R", or the type "reference to function 3206 // of (P1,...,Pn) returning R", a surrogate call function [...] 3207 // is also considered as a candidate function. Similarly, 3208 // surrogate call functions are added to the set of candidate 3209 // functions for each conversion function declared in an 3210 // accessible base class provided the function is not hidden 3211 // within T by another intervening declaration. 3212 // 3213 // FIXME: Look in base classes for more conversion operators! 3214 OverloadedFunctionDecl *Conversions 3215 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions(); 3216 for (OverloadedFunctionDecl::function_iterator 3217 Func = Conversions->function_begin(), 3218 FuncEnd = Conversions->function_end(); 3219 Func != FuncEnd; ++Func) { 3220 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 3221 3222 // Strip the reference type (if any) and then the pointer type (if 3223 // any) to get down to what might be a function type. 3224 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 3225 if (const PointerType *ConvPtrType = ConvType->getAsPointerType()) 3226 ConvType = ConvPtrType->getPointeeType(); 3227 3228 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto()) 3229 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet); 3230 } 3231 3232 // Perform overload resolution. 3233 OverloadCandidateSet::iterator Best; 3234 switch (BestViableFunction(CandidateSet, Best)) { 3235 case OR_Success: 3236 // Overload resolution succeeded; we'll build the appropriate call 3237 // below. 3238 break; 3239 3240 case OR_No_Viable_Function: 3241 Diag(Object->getSourceRange().getBegin(), 3242 diag::err_ovl_no_viable_object_call) 3243 << Object->getType() << (unsigned)CandidateSet.size() 3244 << Object->getSourceRange(); 3245 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3246 break; 3247 3248 case OR_Ambiguous: 3249 Diag(Object->getSourceRange().getBegin(), 3250 diag::err_ovl_ambiguous_object_call) 3251 << Object->getType() << Object->getSourceRange(); 3252 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3253 break; 3254 } 3255 3256 if (Best == CandidateSet.end()) { 3257 // We had an error; delete all of the subexpressions and return 3258 // the error. 3259 delete Object; 3260 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 3261 delete Args[ArgIdx]; 3262 return true; 3263 } 3264 3265 if (Best->Function == 0) { 3266 // Since there is no function declaration, this is one of the 3267 // surrogate candidates. Dig out the conversion function. 3268 CXXConversionDecl *Conv 3269 = cast<CXXConversionDecl>( 3270 Best->Conversions[0].UserDefined.ConversionFunction); 3271 3272 // We selected one of the surrogate functions that converts the 3273 // object parameter to a function pointer. Perform the conversion 3274 // on the object argument, then let ActOnCallExpr finish the job. 3275 // FIXME: Represent the user-defined conversion in the AST! 3276 ImpCastExprToType(Object, 3277 Conv->getConversionType().getNonReferenceType(), 3278 Conv->getConversionType()->isReferenceType()); 3279 return ActOnCallExpr(S, (ExprTy*)Object, LParenLoc, (ExprTy**)Args, NumArgs, 3280 CommaLocs, RParenLoc); 3281 } 3282 3283 // We found an overloaded operator(). Build a CXXOperatorCallExpr 3284 // that calls this method, using Object for the implicit object 3285 // parameter and passing along the remaining arguments. 3286 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 3287 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto(); 3288 3289 unsigned NumArgsInProto = Proto->getNumArgs(); 3290 unsigned NumArgsToCheck = NumArgs; 3291 3292 // Build the full argument list for the method call (the 3293 // implicit object parameter is placed at the beginning of the 3294 // list). 3295 Expr **MethodArgs; 3296 if (NumArgs < NumArgsInProto) { 3297 NumArgsToCheck = NumArgsInProto; 3298 MethodArgs = new Expr*[NumArgsInProto + 1]; 3299 } else { 3300 MethodArgs = new Expr*[NumArgs + 1]; 3301 } 3302 MethodArgs[0] = Object; 3303 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 3304 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 3305 3306 Expr *NewFn = new DeclRefExpr(Method, Method->getType(), 3307 SourceLocation()); 3308 UsualUnaryConversions(NewFn); 3309 3310 // Once we've built TheCall, all of the expressions are properly 3311 // owned. 3312 QualType ResultTy = Method->getResultType().getNonReferenceType(); 3313 llvm::OwningPtr<CXXOperatorCallExpr> 3314 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1, 3315 ResultTy, RParenLoc)); 3316 delete [] MethodArgs; 3317 3318 // Initialize the implicit object parameter. 3319 if (!PerformObjectArgumentInitialization(Object, Method)) 3320 return true; 3321 TheCall->setArg(0, Object); 3322 3323 // Check the argument types. 3324 for (unsigned i = 0; i != NumArgsToCheck; i++) { 3325 QualType ProtoArgType = Proto->getArgType(i); 3326 3327 Expr *Arg; 3328 if (i < NumArgs) 3329 Arg = Args[i]; 3330 else 3331 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i)); 3332 QualType ArgType = Arg->getType(); 3333 3334 // Pass the argument. 3335 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 3336 return true; 3337 3338 TheCall->setArg(i + 1, Arg); 3339 } 3340 3341 // If this is a variadic call, handle args passed through "...". 3342 if (Proto->isVariadic()) { 3343 // Promote the arguments (C99 6.5.2.2p7). 3344 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 3345 Expr *Arg = Args[i]; 3346 DefaultArgumentPromotion(Arg); 3347 TheCall->setArg(i + 1, Arg); 3348 } 3349 } 3350 3351 return CheckFunctionCall(Method, TheCall.take()); 3352} 3353 3354/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 3355/// (if one exists), where @c Base is an expression of class type and 3356/// @c Member is the name of the member we're trying to find. 3357Action::ExprResult 3358Sema::BuildOverloadedArrowExpr(Expr *Base, SourceLocation OpLoc, 3359 SourceLocation MemberLoc, 3360 IdentifierInfo &Member) { 3361 assert(Base->getType()->isRecordType() && "left-hand side must have class type"); 3362 3363 // C++ [over.ref]p1: 3364 // 3365 // [...] An expression x->m is interpreted as (x.operator->())->m 3366 // for a class object x of type T if T::operator->() exists and if 3367 // the operator is selected as the best match function by the 3368 // overload resolution mechanism (13.3). 3369 // FIXME: look in base classes. 3370 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 3371 OverloadCandidateSet CandidateSet; 3372 const RecordType *BaseRecord = Base->getType()->getAsRecordType(); 3373 DeclContext::lookup_const_result Lookup 3374 = BaseRecord->getDecl()->lookup(Context, OpName); 3375 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first; 3376 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps)) 3377 AddMethodCandidate(Method, Base, 0, 0, CandidateSet, 3378 /*SuppressUserConversions=*/false); 3379 else if (OverloadedFunctionDecl *Ovl 3380 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) { 3381 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 3382 FEnd = Ovl->function_end(); 3383 F != FEnd; ++F) { 3384 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F)) 3385 AddMethodCandidate(Method, Base, 0, 0, CandidateSet, 3386 /*SuppressUserConversions=*/false); 3387 } 3388 } 3389 3390 llvm::OwningPtr<Expr> BasePtr(Base); 3391 3392 // Perform overload resolution. 3393 OverloadCandidateSet::iterator Best; 3394 switch (BestViableFunction(CandidateSet, Best)) { 3395 case OR_Success: 3396 // Overload resolution succeeded; we'll build the call below. 3397 break; 3398 3399 case OR_No_Viable_Function: 3400 if (CandidateSet.empty()) 3401 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 3402 << BasePtr->getType() << BasePtr->getSourceRange(); 3403 else 3404 Diag(OpLoc, diag::err_ovl_no_viable_oper) 3405 << "operator->" << (unsigned)CandidateSet.size() 3406 << BasePtr->getSourceRange(); 3407 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3408 return true; 3409 3410 case OR_Ambiguous: 3411 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 3412 << "operator->" << BasePtr->getSourceRange(); 3413 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3414 return true; 3415 } 3416 3417 // Convert the object parameter. 3418 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 3419 if (PerformObjectArgumentInitialization(Base, Method)) 3420 return true; 3421 3422 // No concerns about early exits now. 3423 BasePtr.take(); 3424 3425 // Build the operator call. 3426 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation()); 3427 UsualUnaryConversions(FnExpr); 3428 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1, 3429 Method->getResultType().getNonReferenceType(), 3430 OpLoc); 3431 return ActOnMemberReferenceExpr(Base, OpLoc, tok::arrow, MemberLoc, Member); 3432} 3433 3434/// FixOverloadedFunctionReference - E is an expression that refers to 3435/// a C++ overloaded function (possibly with some parentheses and 3436/// perhaps a '&' around it). We have resolved the overloaded function 3437/// to the function declaration Fn, so patch up the expression E to 3438/// refer (possibly indirectly) to Fn. 3439void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) { 3440 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 3441 FixOverloadedFunctionReference(PE->getSubExpr(), Fn); 3442 E->setType(PE->getSubExpr()->getType()); 3443 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 3444 assert(UnOp->getOpcode() == UnaryOperator::AddrOf && 3445 "Can only take the address of an overloaded function"); 3446 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn); 3447 E->setType(Context.getPointerType(E->getType())); 3448 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 3449 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) && 3450 "Expected overloaded function"); 3451 DR->setDecl(Fn); 3452 E->setType(Fn->getType()); 3453 } else { 3454 assert(false && "Invalid reference to overloaded function"); 3455 } 3456} 3457 3458} // end namespace clang 3459