SemaOverload.cpp revision 932778b2665a59d2c1ace605906beebb07170abf
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 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC)) 767 return true; 768 769 // Blocks: Block pointers can be converted to void*. 770 if (FromType->isBlockPointerType() && ToType->isPointerType() && 771 ToType->getAsPointerType()->getPointeeType()->isVoidType()) { 772 ConvertedType = ToType; 773 return true; 774 } 775 // Blocks: A null pointer constant can be converted to a block 776 // pointer type. 777 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) { 778 ConvertedType = ToType; 779 return true; 780 } 781 782 const PointerType* ToTypePtr = ToType->getAsPointerType(); 783 if (!ToTypePtr) 784 return false; 785 786 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 787 if (From->isNullPointerConstant(Context)) { 788 ConvertedType = ToType; 789 return true; 790 } 791 792 // Beyond this point, both types need to be pointers. 793 const PointerType *FromTypePtr = FromType->getAsPointerType(); 794 if (!FromTypePtr) 795 return false; 796 797 QualType FromPointeeType = FromTypePtr->getPointeeType(); 798 QualType ToPointeeType = ToTypePtr->getPointeeType(); 799 800 // An rvalue of type "pointer to cv T," where T is an object type, 801 // can be converted to an rvalue of type "pointer to cv void" (C++ 802 // 4.10p2). 803 if (FromPointeeType->isIncompleteOrObjectType() && 804 ToPointeeType->isVoidType()) { 805 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 806 ToPointeeType, 807 ToType, Context); 808 return true; 809 } 810 811 // C++ [conv.ptr]p3: 812 // 813 // An rvalue of type "pointer to cv D," where D is a class type, 814 // can be converted to an rvalue of type "pointer to cv B," where 815 // B is a base class (clause 10) of D. If B is an inaccessible 816 // (clause 11) or ambiguous (10.2) base class of D, a program that 817 // necessitates this conversion is ill-formed. The result of the 818 // conversion is a pointer to the base class sub-object of the 819 // derived class object. The null pointer value is converted to 820 // the null pointer value of the destination type. 821 // 822 // Note that we do not check for ambiguity or inaccessibility 823 // here. That is handled by CheckPointerConversion. 824 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 825 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 826 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 827 ToPointeeType, 828 ToType, Context); 829 return true; 830 } 831 832 return false; 833} 834 835/// isObjCPointerConversion - Determines whether this is an 836/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 837/// with the same arguments and return values. 838bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 839 QualType& ConvertedType, 840 bool &IncompatibleObjC) { 841 if (!getLangOptions().ObjC1) 842 return false; 843 844 // Conversions with Objective-C's id<...>. 845 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) && 846 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) { 847 ConvertedType = ToType; 848 return true; 849 } 850 851 const PointerType* ToTypePtr = ToType->getAsPointerType(); 852 if (!ToTypePtr) 853 return false; 854 855 // Beyond this point, both types need to be pointers. 856 const PointerType *FromTypePtr = FromType->getAsPointerType(); 857 if (!FromTypePtr) 858 return false; 859 860 QualType FromPointeeType = FromTypePtr->getPointeeType(); 861 QualType ToPointeeType = ToTypePtr->getPointeeType(); 862 863 // Objective C++: We're able to convert from a pointer to an 864 // interface to a pointer to a different interface. 865 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType(); 866 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType(); 867 if (FromIface && ToIface && 868 Context.canAssignObjCInterfaces(ToIface, FromIface)) { 869 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 870 ToPointeeType, 871 ToType, Context); 872 return true; 873 } 874 875 if (FromIface && ToIface && 876 Context.canAssignObjCInterfaces(FromIface, ToIface)) { 877 // Okay: this is some kind of implicit downcast of Objective-C 878 // interfaces, which is permitted. However, we're going to 879 // complain about it. 880 IncompatibleObjC = true; 881 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 882 ToPointeeType, 883 ToType, Context); 884 return true; 885 } 886 887 // Objective C++: We're able to convert between "id" and a pointer 888 // to any interface (in both directions). 889 if ((FromIface && Context.isObjCIdType(ToPointeeType)) 890 || (ToIface && Context.isObjCIdType(FromPointeeType))) { 891 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 892 ToPointeeType, 893 ToType, Context); 894 return true; 895 } 896 897 // Objective C++: Allow conversions between the Objective-C "id" and 898 // "Class", in either direction. 899 if ((Context.isObjCIdType(FromPointeeType) && 900 Context.isObjCClassType(ToPointeeType)) || 901 (Context.isObjCClassType(FromPointeeType) && 902 Context.isObjCIdType(ToPointeeType))) { 903 ConvertedType = ToType; 904 return true; 905 } 906 907 // If we have pointers to pointers, recursively check whether this 908 // is an Objective-C conversion. 909 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 910 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 911 IncompatibleObjC)) { 912 // We always complain about this conversion. 913 IncompatibleObjC = true; 914 ConvertedType = ToType; 915 return true; 916 } 917 918 // If we have pointers to functions, check whether the only 919 // differences in the argument and result types are in Objective-C 920 // pointer conversions. If so, we permit the conversion (but 921 // complain about it). 922 const FunctionTypeProto *FromFunctionType 923 = FromPointeeType->getAsFunctionTypeProto(); 924 const FunctionTypeProto *ToFunctionType 925 = ToPointeeType->getAsFunctionTypeProto(); 926 if (FromFunctionType && ToFunctionType) { 927 // If the function types are exactly the same, this isn't an 928 // Objective-C pointer conversion. 929 if (Context.getCanonicalType(FromPointeeType) 930 == Context.getCanonicalType(ToPointeeType)) 931 return false; 932 933 // Perform the quick checks that will tell us whether these 934 // function types are obviously different. 935 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 936 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 937 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 938 return false; 939 940 bool HasObjCConversion = false; 941 if (Context.getCanonicalType(FromFunctionType->getResultType()) 942 == Context.getCanonicalType(ToFunctionType->getResultType())) { 943 // Okay, the types match exactly. Nothing to do. 944 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 945 ToFunctionType->getResultType(), 946 ConvertedType, IncompatibleObjC)) { 947 // Okay, we have an Objective-C pointer conversion. 948 HasObjCConversion = true; 949 } else { 950 // Function types are too different. Abort. 951 return false; 952 } 953 954 // Check argument types. 955 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 956 ArgIdx != NumArgs; ++ArgIdx) { 957 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 958 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 959 if (Context.getCanonicalType(FromArgType) 960 == Context.getCanonicalType(ToArgType)) { 961 // Okay, the types match exactly. Nothing to do. 962 } else if (isObjCPointerConversion(FromArgType, ToArgType, 963 ConvertedType, IncompatibleObjC)) { 964 // Okay, we have an Objective-C pointer conversion. 965 HasObjCConversion = true; 966 } else { 967 // Argument types are too different. Abort. 968 return false; 969 } 970 } 971 972 if (HasObjCConversion) { 973 // We had an Objective-C conversion. Allow this pointer 974 // conversion, but complain about it. 975 ConvertedType = ToType; 976 IncompatibleObjC = true; 977 return true; 978 } 979 } 980 981 return false; 982} 983 984/// CheckPointerConversion - Check the pointer conversion from the 985/// expression From to the type ToType. This routine checks for 986/// ambiguous (FIXME: or inaccessible) derived-to-base pointer 987/// conversions for which IsPointerConversion has already returned 988/// true. It returns true and produces a diagnostic if there was an 989/// error, or returns false otherwise. 990bool Sema::CheckPointerConversion(Expr *From, QualType ToType) { 991 QualType FromType = From->getType(); 992 993 if (const PointerType *FromPtrType = FromType->getAsPointerType()) 994 if (const PointerType *ToPtrType = ToType->getAsPointerType()) { 995 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 996 /*DetectVirtual=*/false); 997 QualType FromPointeeType = FromPtrType->getPointeeType(), 998 ToPointeeType = ToPtrType->getPointeeType(); 999 1000 // Objective-C++ conversions are always okay. 1001 // FIXME: We should have a different class of conversions for 1002 // the Objective-C++ implicit conversions. 1003 if (Context.isObjCIdType(FromPointeeType) || 1004 Context.isObjCIdType(ToPointeeType) || 1005 Context.isObjCClassType(FromPointeeType) || 1006 Context.isObjCClassType(ToPointeeType)) 1007 return false; 1008 1009 if (FromPointeeType->isRecordType() && 1010 ToPointeeType->isRecordType()) { 1011 // We must have a derived-to-base conversion. Check an 1012 // ambiguous or inaccessible conversion. 1013 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 1014 From->getExprLoc(), 1015 From->getSourceRange()); 1016 } 1017 } 1018 1019 return false; 1020} 1021 1022/// IsQualificationConversion - Determines whether the conversion from 1023/// an rvalue of type FromType to ToType is a qualification conversion 1024/// (C++ 4.4). 1025bool 1026Sema::IsQualificationConversion(QualType FromType, QualType ToType) 1027{ 1028 FromType = Context.getCanonicalType(FromType); 1029 ToType = Context.getCanonicalType(ToType); 1030 1031 // If FromType and ToType are the same type, this is not a 1032 // qualification conversion. 1033 if (FromType == ToType) 1034 return false; 1035 1036 // (C++ 4.4p4): 1037 // A conversion can add cv-qualifiers at levels other than the first 1038 // in multi-level pointers, subject to the following rules: [...] 1039 bool PreviousToQualsIncludeConst = true; 1040 bool UnwrappedAnyPointer = false; 1041 while (UnwrapSimilarPointerTypes(FromType, ToType)) { 1042 // Within each iteration of the loop, we check the qualifiers to 1043 // determine if this still looks like a qualification 1044 // conversion. Then, if all is well, we unwrap one more level of 1045 // pointers or pointers-to-members and do it all again 1046 // until there are no more pointers or pointers-to-members left to 1047 // unwrap. 1048 UnwrappedAnyPointer = true; 1049 1050 // -- for every j > 0, if const is in cv 1,j then const is in cv 1051 // 2,j, and similarly for volatile. 1052 if (!ToType.isAtLeastAsQualifiedAs(FromType)) 1053 return false; 1054 1055 // -- if the cv 1,j and cv 2,j are different, then const is in 1056 // every cv for 0 < k < j. 1057 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers() 1058 && !PreviousToQualsIncludeConst) 1059 return false; 1060 1061 // Keep track of whether all prior cv-qualifiers in the "to" type 1062 // include const. 1063 PreviousToQualsIncludeConst 1064 = PreviousToQualsIncludeConst && ToType.isConstQualified(); 1065 } 1066 1067 // We are left with FromType and ToType being the pointee types 1068 // after unwrapping the original FromType and ToType the same number 1069 // of types. If we unwrapped any pointers, and if FromType and 1070 // ToType have the same unqualified type (since we checked 1071 // qualifiers above), then this is a qualification conversion. 1072 return UnwrappedAnyPointer && 1073 FromType.getUnqualifiedType() == ToType.getUnqualifiedType(); 1074} 1075 1076/// IsUserDefinedConversion - Determines whether there is a 1077/// user-defined conversion sequence (C++ [over.ics.user]) that 1078/// converts expression From to the type ToType. If such a conversion 1079/// exists, User will contain the user-defined conversion sequence 1080/// that performs such a conversion and this routine will return 1081/// true. Otherwise, this routine returns false and User is 1082/// unspecified. 1083bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType, 1084 UserDefinedConversionSequence& User) 1085{ 1086 OverloadCandidateSet CandidateSet; 1087 if (const CXXRecordType *ToRecordType 1088 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) { 1089 // C++ [over.match.ctor]p1: 1090 // When objects of class type are direct-initialized (8.5), or 1091 // copy-initialized from an expression of the same or a 1092 // derived class type (8.5), overload resolution selects the 1093 // constructor. [...] For copy-initialization, the candidate 1094 // functions are all the converting constructors (12.3.1) of 1095 // that class. The argument list is the expression-list within 1096 // the parentheses of the initializer. 1097 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl(); 1098 DeclarationName ConstructorName 1099 = Context.DeclarationNames.getCXXConstructorName( 1100 Context.getCanonicalType(ToType)); 1101 DeclContext::lookup_result Lookup 1102 = ToRecordDecl->lookup(Context, ConstructorName); 1103 if (Lookup.first == Lookup.second) 1104 /* No constructors. FIXME: Implicit copy constructor? */; 1105 else if (OverloadedFunctionDecl *Constructors 1106 = dyn_cast<OverloadedFunctionDecl>(*Lookup.first)) { 1107 for (OverloadedFunctionDecl::function_const_iterator func 1108 = Constructors->function_begin(); 1109 func != Constructors->function_end(); ++func) { 1110 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func); 1111 if (Constructor->isConvertingConstructor()) 1112 AddOverloadCandidate(Constructor, &From, 1, CandidateSet, 1113 /*SuppressUserConversions=*/true); 1114 } 1115 } else if (CXXConstructorDecl *Constructor 1116 = dyn_cast<CXXConstructorDecl>(*Lookup.first)) { 1117 if (Constructor->isConvertingConstructor()) 1118 AddOverloadCandidate(Constructor, &From, 1, CandidateSet, 1119 /*SuppressUserConversions=*/true); 1120 } 1121 } 1122 1123 if (const CXXRecordType *FromRecordType 1124 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) { 1125 // Add all of the conversion functions as candidates. 1126 // FIXME: Look for conversions in base classes! 1127 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl(); 1128 OverloadedFunctionDecl *Conversions 1129 = FromRecordDecl->getConversionFunctions(); 1130 for (OverloadedFunctionDecl::function_iterator Func 1131 = Conversions->function_begin(); 1132 Func != Conversions->function_end(); ++Func) { 1133 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 1134 AddConversionCandidate(Conv, From, ToType, CandidateSet); 1135 } 1136 } 1137 1138 OverloadCandidateSet::iterator Best; 1139 switch (BestViableFunction(CandidateSet, Best)) { 1140 case OR_Success: 1141 // Record the standard conversion we used and the conversion function. 1142 if (CXXConstructorDecl *Constructor 1143 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 1144 // C++ [over.ics.user]p1: 1145 // If the user-defined conversion is specified by a 1146 // constructor (12.3.1), the initial standard conversion 1147 // sequence converts the source type to the type required by 1148 // the argument of the constructor. 1149 // 1150 // FIXME: What about ellipsis conversions? 1151 QualType ThisType = Constructor->getThisType(Context); 1152 User.Before = Best->Conversions[0].Standard; 1153 User.ConversionFunction = Constructor; 1154 User.After.setAsIdentityConversion(); 1155 User.After.FromTypePtr 1156 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr(); 1157 User.After.ToTypePtr = ToType.getAsOpaquePtr(); 1158 return true; 1159 } else if (CXXConversionDecl *Conversion 1160 = dyn_cast<CXXConversionDecl>(Best->Function)) { 1161 // C++ [over.ics.user]p1: 1162 // 1163 // [...] If the user-defined conversion is specified by a 1164 // conversion function (12.3.2), the initial standard 1165 // conversion sequence converts the source type to the 1166 // implicit object parameter of the conversion function. 1167 User.Before = Best->Conversions[0].Standard; 1168 User.ConversionFunction = Conversion; 1169 1170 // C++ [over.ics.user]p2: 1171 // The second standard conversion sequence converts the 1172 // result of the user-defined conversion to the target type 1173 // for the sequence. Since an implicit conversion sequence 1174 // is an initialization, the special rules for 1175 // initialization by user-defined conversion apply when 1176 // selecting the best user-defined conversion for a 1177 // user-defined conversion sequence (see 13.3.3 and 1178 // 13.3.3.1). 1179 User.After = Best->FinalConversion; 1180 return true; 1181 } else { 1182 assert(false && "Not a constructor or conversion function?"); 1183 return false; 1184 } 1185 1186 case OR_No_Viable_Function: 1187 // No conversion here! We're done. 1188 return false; 1189 1190 case OR_Ambiguous: 1191 // FIXME: See C++ [over.best.ics]p10 for the handling of 1192 // ambiguous conversion sequences. 1193 return false; 1194 } 1195 1196 return false; 1197} 1198 1199/// CompareImplicitConversionSequences - Compare two implicit 1200/// conversion sequences to determine whether one is better than the 1201/// other or if they are indistinguishable (C++ 13.3.3.2). 1202ImplicitConversionSequence::CompareKind 1203Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1, 1204 const ImplicitConversionSequence& ICS2) 1205{ 1206 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 1207 // conversion sequences (as defined in 13.3.3.1) 1208 // -- a standard conversion sequence (13.3.3.1.1) is a better 1209 // conversion sequence than a user-defined conversion sequence or 1210 // an ellipsis conversion sequence, and 1211 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 1212 // conversion sequence than an ellipsis conversion sequence 1213 // (13.3.3.1.3). 1214 // 1215 if (ICS1.ConversionKind < ICS2.ConversionKind) 1216 return ImplicitConversionSequence::Better; 1217 else if (ICS2.ConversionKind < ICS1.ConversionKind) 1218 return ImplicitConversionSequence::Worse; 1219 1220 // Two implicit conversion sequences of the same form are 1221 // indistinguishable conversion sequences unless one of the 1222 // following rules apply: (C++ 13.3.3.2p3): 1223 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion) 1224 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard); 1225 else if (ICS1.ConversionKind == 1226 ImplicitConversionSequence::UserDefinedConversion) { 1227 // User-defined conversion sequence U1 is a better conversion 1228 // sequence than another user-defined conversion sequence U2 if 1229 // they contain the same user-defined conversion function or 1230 // constructor and if the second standard conversion sequence of 1231 // U1 is better than the second standard conversion sequence of 1232 // U2 (C++ 13.3.3.2p3). 1233 if (ICS1.UserDefined.ConversionFunction == 1234 ICS2.UserDefined.ConversionFunction) 1235 return CompareStandardConversionSequences(ICS1.UserDefined.After, 1236 ICS2.UserDefined.After); 1237 } 1238 1239 return ImplicitConversionSequence::Indistinguishable; 1240} 1241 1242/// CompareStandardConversionSequences - Compare two standard 1243/// conversion sequences to determine whether one is better than the 1244/// other or if they are indistinguishable (C++ 13.3.3.2p3). 1245ImplicitConversionSequence::CompareKind 1246Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1, 1247 const StandardConversionSequence& SCS2) 1248{ 1249 // Standard conversion sequence S1 is a better conversion sequence 1250 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 1251 1252 // -- S1 is a proper subsequence of S2 (comparing the conversion 1253 // sequences in the canonical form defined by 13.3.3.1.1, 1254 // excluding any Lvalue Transformation; the identity conversion 1255 // sequence is considered to be a subsequence of any 1256 // non-identity conversion sequence) or, if not that, 1257 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third) 1258 // Neither is a proper subsequence of the other. Do nothing. 1259 ; 1260 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) || 1261 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) || 1262 (SCS1.Second == ICK_Identity && 1263 SCS1.Third == ICK_Identity)) 1264 // SCS1 is a proper subsequence of SCS2. 1265 return ImplicitConversionSequence::Better; 1266 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) || 1267 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) || 1268 (SCS2.Second == ICK_Identity && 1269 SCS2.Third == ICK_Identity)) 1270 // SCS2 is a proper subsequence of SCS1. 1271 return ImplicitConversionSequence::Worse; 1272 1273 // -- the rank of S1 is better than the rank of S2 (by the rules 1274 // defined below), or, if not that, 1275 ImplicitConversionRank Rank1 = SCS1.getRank(); 1276 ImplicitConversionRank Rank2 = SCS2.getRank(); 1277 if (Rank1 < Rank2) 1278 return ImplicitConversionSequence::Better; 1279 else if (Rank2 < Rank1) 1280 return ImplicitConversionSequence::Worse; 1281 1282 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 1283 // are indistinguishable unless one of the following rules 1284 // applies: 1285 1286 // A conversion that is not a conversion of a pointer, or 1287 // pointer to member, to bool is better than another conversion 1288 // that is such a conversion. 1289 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 1290 return SCS2.isPointerConversionToBool() 1291 ? ImplicitConversionSequence::Better 1292 : ImplicitConversionSequence::Worse; 1293 1294 // C++ [over.ics.rank]p4b2: 1295 // 1296 // If class B is derived directly or indirectly from class A, 1297 // conversion of B* to A* is better than conversion of B* to 1298 // void*, and conversion of A* to void* is better than conversion 1299 // of B* to void*. 1300 bool SCS1ConvertsToVoid 1301 = SCS1.isPointerConversionToVoidPointer(Context); 1302 bool SCS2ConvertsToVoid 1303 = SCS2.isPointerConversionToVoidPointer(Context); 1304 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 1305 // Exactly one of the conversion sequences is a conversion to 1306 // a void pointer; it's the worse conversion. 1307 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 1308 : ImplicitConversionSequence::Worse; 1309 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 1310 // Neither conversion sequence converts to a void pointer; compare 1311 // their derived-to-base conversions. 1312 if (ImplicitConversionSequence::CompareKind DerivedCK 1313 = CompareDerivedToBaseConversions(SCS1, SCS2)) 1314 return DerivedCK; 1315 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) { 1316 // Both conversion sequences are conversions to void 1317 // pointers. Compare the source types to determine if there's an 1318 // inheritance relationship in their sources. 1319 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1320 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1321 1322 // Adjust the types we're converting from via the array-to-pointer 1323 // conversion, if we need to. 1324 if (SCS1.First == ICK_Array_To_Pointer) 1325 FromType1 = Context.getArrayDecayedType(FromType1); 1326 if (SCS2.First == ICK_Array_To_Pointer) 1327 FromType2 = Context.getArrayDecayedType(FromType2); 1328 1329 QualType FromPointee1 1330 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1331 QualType FromPointee2 1332 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1333 1334 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1335 return ImplicitConversionSequence::Better; 1336 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1337 return ImplicitConversionSequence::Worse; 1338 1339 // Objective-C++: If one interface is more specific than the 1340 // other, it is the better one. 1341 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType(); 1342 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType(); 1343 if (FromIface1 && FromIface1) { 1344 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 1345 return ImplicitConversionSequence::Better; 1346 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 1347 return ImplicitConversionSequence::Worse; 1348 } 1349 } 1350 1351 // Compare based on qualification conversions (C++ 13.3.3.2p3, 1352 // bullet 3). 1353 if (ImplicitConversionSequence::CompareKind QualCK 1354 = CompareQualificationConversions(SCS1, SCS2)) 1355 return QualCK; 1356 1357 // C++ [over.ics.rank]p3b4: 1358 // -- S1 and S2 are reference bindings (8.5.3), and the types to 1359 // which the references refer are the same type except for 1360 // top-level cv-qualifiers, and the type to which the reference 1361 // initialized by S2 refers is more cv-qualified than the type 1362 // to which the reference initialized by S1 refers. 1363 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 1364 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1365 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1366 T1 = Context.getCanonicalType(T1); 1367 T2 = Context.getCanonicalType(T2); 1368 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) { 1369 if (T2.isMoreQualifiedThan(T1)) 1370 return ImplicitConversionSequence::Better; 1371 else if (T1.isMoreQualifiedThan(T2)) 1372 return ImplicitConversionSequence::Worse; 1373 } 1374 } 1375 1376 return ImplicitConversionSequence::Indistinguishable; 1377} 1378 1379/// CompareQualificationConversions - Compares two standard conversion 1380/// sequences to determine whether they can be ranked based on their 1381/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 1382ImplicitConversionSequence::CompareKind 1383Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1, 1384 const StandardConversionSequence& SCS2) 1385{ 1386 // C++ 13.3.3.2p3: 1387 // -- S1 and S2 differ only in their qualification conversion and 1388 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 1389 // cv-qualification signature of type T1 is a proper subset of 1390 // the cv-qualification signature of type T2, and S1 is not the 1391 // deprecated string literal array-to-pointer conversion (4.2). 1392 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 1393 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 1394 return ImplicitConversionSequence::Indistinguishable; 1395 1396 // FIXME: the example in the standard doesn't use a qualification 1397 // conversion (!) 1398 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1399 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1400 T1 = Context.getCanonicalType(T1); 1401 T2 = Context.getCanonicalType(T2); 1402 1403 // If the types are the same, we won't learn anything by unwrapped 1404 // them. 1405 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1406 return ImplicitConversionSequence::Indistinguishable; 1407 1408 ImplicitConversionSequence::CompareKind Result 1409 = ImplicitConversionSequence::Indistinguishable; 1410 while (UnwrapSimilarPointerTypes(T1, T2)) { 1411 // Within each iteration of the loop, we check the qualifiers to 1412 // determine if this still looks like a qualification 1413 // conversion. Then, if all is well, we unwrap one more level of 1414 // pointers or pointers-to-members and do it all again 1415 // until there are no more pointers or pointers-to-members left 1416 // to unwrap. This essentially mimics what 1417 // IsQualificationConversion does, but here we're checking for a 1418 // strict subset of qualifiers. 1419 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1420 // The qualifiers are the same, so this doesn't tell us anything 1421 // about how the sequences rank. 1422 ; 1423 else if (T2.isMoreQualifiedThan(T1)) { 1424 // T1 has fewer qualifiers, so it could be the better sequence. 1425 if (Result == ImplicitConversionSequence::Worse) 1426 // Neither has qualifiers that are a subset of the other's 1427 // qualifiers. 1428 return ImplicitConversionSequence::Indistinguishable; 1429 1430 Result = ImplicitConversionSequence::Better; 1431 } else if (T1.isMoreQualifiedThan(T2)) { 1432 // T2 has fewer qualifiers, so it could be the better sequence. 1433 if (Result == ImplicitConversionSequence::Better) 1434 // Neither has qualifiers that are a subset of the other's 1435 // qualifiers. 1436 return ImplicitConversionSequence::Indistinguishable; 1437 1438 Result = ImplicitConversionSequence::Worse; 1439 } else { 1440 // Qualifiers are disjoint. 1441 return ImplicitConversionSequence::Indistinguishable; 1442 } 1443 1444 // If the types after this point are equivalent, we're done. 1445 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1446 break; 1447 } 1448 1449 // Check that the winning standard conversion sequence isn't using 1450 // the deprecated string literal array to pointer conversion. 1451 switch (Result) { 1452 case ImplicitConversionSequence::Better: 1453 if (SCS1.Deprecated) 1454 Result = ImplicitConversionSequence::Indistinguishable; 1455 break; 1456 1457 case ImplicitConversionSequence::Indistinguishable: 1458 break; 1459 1460 case ImplicitConversionSequence::Worse: 1461 if (SCS2.Deprecated) 1462 Result = ImplicitConversionSequence::Indistinguishable; 1463 break; 1464 } 1465 1466 return Result; 1467} 1468 1469/// CompareDerivedToBaseConversions - Compares two standard conversion 1470/// sequences to determine whether they can be ranked based on their 1471/// various kinds of derived-to-base conversions (C++ 1472/// [over.ics.rank]p4b3). As part of these checks, we also look at 1473/// conversions between Objective-C interface types. 1474ImplicitConversionSequence::CompareKind 1475Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1, 1476 const StandardConversionSequence& SCS2) { 1477 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1478 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1479 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1480 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1481 1482 // Adjust the types we're converting from via the array-to-pointer 1483 // conversion, if we need to. 1484 if (SCS1.First == ICK_Array_To_Pointer) 1485 FromType1 = Context.getArrayDecayedType(FromType1); 1486 if (SCS2.First == ICK_Array_To_Pointer) 1487 FromType2 = Context.getArrayDecayedType(FromType2); 1488 1489 // Canonicalize all of the types. 1490 FromType1 = Context.getCanonicalType(FromType1); 1491 ToType1 = Context.getCanonicalType(ToType1); 1492 FromType2 = Context.getCanonicalType(FromType2); 1493 ToType2 = Context.getCanonicalType(ToType2); 1494 1495 // C++ [over.ics.rank]p4b3: 1496 // 1497 // If class B is derived directly or indirectly from class A and 1498 // class C is derived directly or indirectly from B, 1499 // 1500 // For Objective-C, we let A, B, and C also be Objective-C 1501 // interfaces. 1502 1503 // Compare based on pointer conversions. 1504 if (SCS1.Second == ICK_Pointer_Conversion && 1505 SCS2.Second == ICK_Pointer_Conversion && 1506 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 1507 FromType1->isPointerType() && FromType2->isPointerType() && 1508 ToType1->isPointerType() && ToType2->isPointerType()) { 1509 QualType FromPointee1 1510 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1511 QualType ToPointee1 1512 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1513 QualType FromPointee2 1514 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1515 QualType ToPointee2 1516 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1517 1518 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType(); 1519 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType(); 1520 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType(); 1521 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType(); 1522 1523 // -- conversion of C* to B* is better than conversion of C* to A*, 1524 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 1525 if (IsDerivedFrom(ToPointee1, ToPointee2)) 1526 return ImplicitConversionSequence::Better; 1527 else if (IsDerivedFrom(ToPointee2, ToPointee1)) 1528 return ImplicitConversionSequence::Worse; 1529 1530 if (ToIface1 && ToIface2) { 1531 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1)) 1532 return ImplicitConversionSequence::Better; 1533 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2)) 1534 return ImplicitConversionSequence::Worse; 1535 } 1536 } 1537 1538 // -- conversion of B* to A* is better than conversion of C* to A*, 1539 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 1540 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1541 return ImplicitConversionSequence::Better; 1542 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1543 return ImplicitConversionSequence::Worse; 1544 1545 if (FromIface1 && FromIface2) { 1546 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 1547 return ImplicitConversionSequence::Better; 1548 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 1549 return ImplicitConversionSequence::Worse; 1550 } 1551 } 1552 } 1553 1554 // Compare based on reference bindings. 1555 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding && 1556 SCS1.Second == ICK_Derived_To_Base) { 1557 // -- binding of an expression of type C to a reference of type 1558 // B& is better than binding an expression of type C to a 1559 // reference of type A&, 1560 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1561 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1562 if (IsDerivedFrom(ToType1, ToType2)) 1563 return ImplicitConversionSequence::Better; 1564 else if (IsDerivedFrom(ToType2, ToType1)) 1565 return ImplicitConversionSequence::Worse; 1566 } 1567 1568 // -- binding of an expression of type B to a reference of type 1569 // A& is better than binding an expression of type C to a 1570 // reference of type A&, 1571 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1572 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1573 if (IsDerivedFrom(FromType2, FromType1)) 1574 return ImplicitConversionSequence::Better; 1575 else if (IsDerivedFrom(FromType1, FromType2)) 1576 return ImplicitConversionSequence::Worse; 1577 } 1578 } 1579 1580 1581 // FIXME: conversion of A::* to B::* is better than conversion of 1582 // A::* to C::*, 1583 1584 // FIXME: conversion of B::* to C::* is better than conversion of 1585 // A::* to C::*, and 1586 1587 if (SCS1.CopyConstructor && SCS2.CopyConstructor && 1588 SCS1.Second == ICK_Derived_To_Base) { 1589 // -- conversion of C to B is better than conversion of C to A, 1590 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1591 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1592 if (IsDerivedFrom(ToType1, ToType2)) 1593 return ImplicitConversionSequence::Better; 1594 else if (IsDerivedFrom(ToType2, ToType1)) 1595 return ImplicitConversionSequence::Worse; 1596 } 1597 1598 // -- conversion of B to A is better than conversion of C to A. 1599 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1600 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1601 if (IsDerivedFrom(FromType2, FromType1)) 1602 return ImplicitConversionSequence::Better; 1603 else if (IsDerivedFrom(FromType1, FromType2)) 1604 return ImplicitConversionSequence::Worse; 1605 } 1606 } 1607 1608 return ImplicitConversionSequence::Indistinguishable; 1609} 1610 1611/// TryCopyInitialization - Try to copy-initialize a value of type 1612/// ToType from the expression From. Return the implicit conversion 1613/// sequence required to pass this argument, which may be a bad 1614/// conversion sequence (meaning that the argument cannot be passed to 1615/// a parameter of this type). If @p SuppressUserConversions, then we 1616/// do not permit any user-defined conversion sequences. 1617ImplicitConversionSequence 1618Sema::TryCopyInitialization(Expr *From, QualType ToType, 1619 bool SuppressUserConversions) { 1620 if (!getLangOptions().CPlusPlus) { 1621 // In C, copy initialization is the same as performing an assignment. 1622 AssignConvertType ConvTy = 1623 CheckSingleAssignmentConstraints(ToType, From); 1624 ImplicitConversionSequence ICS; 1625 if (getLangOptions().NoExtensions? ConvTy != Compatible 1626 : ConvTy == Incompatible) 1627 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1628 else 1629 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 1630 return ICS; 1631 } else if (ToType->isReferenceType()) { 1632 ImplicitConversionSequence ICS; 1633 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions); 1634 return ICS; 1635 } else { 1636 return TryImplicitConversion(From, ToType, SuppressUserConversions); 1637 } 1638} 1639 1640/// PerformArgumentPassing - Pass the argument Arg into a parameter of 1641/// type ToType. Returns true (and emits a diagnostic) if there was 1642/// an error, returns false if the initialization succeeded. 1643bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType, 1644 const char* Flavor) { 1645 if (!getLangOptions().CPlusPlus) { 1646 // In C, argument passing is the same as performing an assignment. 1647 QualType FromType = From->getType(); 1648 AssignConvertType ConvTy = 1649 CheckSingleAssignmentConstraints(ToType, From); 1650 1651 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType, 1652 FromType, From, Flavor); 1653 } 1654 1655 if (ToType->isReferenceType()) 1656 return CheckReferenceInit(From, ToType); 1657 1658 if (!PerformImplicitConversion(From, ToType, Flavor)) 1659 return false; 1660 1661 return Diag(From->getSourceRange().getBegin(), 1662 diag::err_typecheck_convert_incompatible) 1663 << ToType << From->getType() << Flavor << From->getSourceRange(); 1664} 1665 1666/// TryObjectArgumentInitialization - Try to initialize the object 1667/// parameter of the given member function (@c Method) from the 1668/// expression @p From. 1669ImplicitConversionSequence 1670Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) { 1671 QualType ClassType = Context.getTypeDeclType(Method->getParent()); 1672 unsigned MethodQuals = Method->getTypeQualifiers(); 1673 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals); 1674 1675 // Set up the conversion sequence as a "bad" conversion, to allow us 1676 // to exit early. 1677 ImplicitConversionSequence ICS; 1678 ICS.Standard.setAsIdentityConversion(); 1679 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1680 1681 // We need to have an object of class type. 1682 QualType FromType = From->getType(); 1683 if (!FromType->isRecordType()) 1684 return ICS; 1685 1686 // The implicit object parmeter is has the type "reference to cv X", 1687 // where X is the class of which the function is a member 1688 // (C++ [over.match.funcs]p4). However, when finding an implicit 1689 // conversion sequence for the argument, we are not allowed to 1690 // create temporaries or perform user-defined conversions 1691 // (C++ [over.match.funcs]p5). We perform a simplified version of 1692 // reference binding here, that allows class rvalues to bind to 1693 // non-constant references. 1694 1695 // First check the qualifiers. We don't care about lvalue-vs-rvalue 1696 // with the implicit object parameter (C++ [over.match.funcs]p5). 1697 QualType FromTypeCanon = Context.getCanonicalType(FromType); 1698 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() && 1699 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType)) 1700 return ICS; 1701 1702 // Check that we have either the same type or a derived type. It 1703 // affects the conversion rank. 1704 QualType ClassTypeCanon = Context.getCanonicalType(ClassType); 1705 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType()) 1706 ICS.Standard.Second = ICK_Identity; 1707 else if (IsDerivedFrom(FromType, ClassType)) 1708 ICS.Standard.Second = ICK_Derived_To_Base; 1709 else 1710 return ICS; 1711 1712 // Success. Mark this as a reference binding. 1713 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 1714 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr(); 1715 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr(); 1716 ICS.Standard.ReferenceBinding = true; 1717 ICS.Standard.DirectBinding = true; 1718 return ICS; 1719} 1720 1721/// PerformObjectArgumentInitialization - Perform initialization of 1722/// the implicit object parameter for the given Method with the given 1723/// expression. 1724bool 1725Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) { 1726 QualType ImplicitParamType 1727 = Method->getThisType(Context)->getAsPointerType()->getPointeeType(); 1728 ImplicitConversionSequence ICS 1729 = TryObjectArgumentInitialization(From, Method); 1730 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) 1731 return Diag(From->getSourceRange().getBegin(), 1732 diag::err_implicit_object_parameter_init) 1733 << ImplicitParamType << From->getType() << From->getSourceRange(); 1734 1735 if (ICS.Standard.Second == ICK_Derived_To_Base && 1736 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType, 1737 From->getSourceRange().getBegin(), 1738 From->getSourceRange())) 1739 return true; 1740 1741 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true); 1742 return false; 1743} 1744 1745/// AddOverloadCandidate - Adds the given function to the set of 1746/// candidate functions, using the given function call arguments. If 1747/// @p SuppressUserConversions, then don't allow user-defined 1748/// conversions via constructors or conversion operators. 1749void 1750Sema::AddOverloadCandidate(FunctionDecl *Function, 1751 Expr **Args, unsigned NumArgs, 1752 OverloadCandidateSet& CandidateSet, 1753 bool SuppressUserConversions) 1754{ 1755 const FunctionTypeProto* Proto 1756 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType()); 1757 assert(Proto && "Functions without a prototype cannot be overloaded"); 1758 assert(!isa<CXXConversionDecl>(Function) && 1759 "Use AddConversionCandidate for conversion functions"); 1760 1761 // Add this candidate 1762 CandidateSet.push_back(OverloadCandidate()); 1763 OverloadCandidate& Candidate = CandidateSet.back(); 1764 Candidate.Function = Function; 1765 Candidate.IsSurrogate = false; 1766 1767 unsigned NumArgsInProto = Proto->getNumArgs(); 1768 1769 // (C++ 13.3.2p2): A candidate function having fewer than m 1770 // parameters is viable only if it has an ellipsis in its parameter 1771 // list (8.3.5). 1772 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 1773 Candidate.Viable = false; 1774 return; 1775 } 1776 1777 // (C++ 13.3.2p2): A candidate function having more than m parameters 1778 // is viable only if the (m+1)st parameter has a default argument 1779 // (8.3.6). For the purposes of overload resolution, the 1780 // parameter list is truncated on the right, so that there are 1781 // exactly m parameters. 1782 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 1783 if (NumArgs < MinRequiredArgs) { 1784 // Not enough arguments. 1785 Candidate.Viable = false; 1786 return; 1787 } 1788 1789 // Determine the implicit conversion sequences for each of the 1790 // arguments. 1791 Candidate.Viable = true; 1792 Candidate.Conversions.resize(NumArgs); 1793 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1794 if (ArgIdx < NumArgsInProto) { 1795 // (C++ 13.3.2p3): for F to be a viable function, there shall 1796 // exist for each argument an implicit conversion sequence 1797 // (13.3.3.1) that converts that argument to the corresponding 1798 // parameter of F. 1799 QualType ParamType = Proto->getArgType(ArgIdx); 1800 Candidate.Conversions[ArgIdx] 1801 = TryCopyInitialization(Args[ArgIdx], ParamType, 1802 SuppressUserConversions); 1803 if (Candidate.Conversions[ArgIdx].ConversionKind 1804 == ImplicitConversionSequence::BadConversion) { 1805 Candidate.Viable = false; 1806 break; 1807 } 1808 } else { 1809 // (C++ 13.3.2p2): For the purposes of overload resolution, any 1810 // argument for which there is no corresponding parameter is 1811 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 1812 Candidate.Conversions[ArgIdx].ConversionKind 1813 = ImplicitConversionSequence::EllipsisConversion; 1814 } 1815 } 1816} 1817 1818/// AddMethodCandidate - Adds the given C++ member function to the set 1819/// of candidate functions, using the given function call arguments 1820/// and the object argument (@c Object). For example, in a call 1821/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 1822/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 1823/// allow user-defined conversions via constructors or conversion 1824/// operators. 1825void 1826Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object, 1827 Expr **Args, unsigned NumArgs, 1828 OverloadCandidateSet& CandidateSet, 1829 bool SuppressUserConversions) 1830{ 1831 const FunctionTypeProto* Proto 1832 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType()); 1833 assert(Proto && "Methods without a prototype cannot be overloaded"); 1834 assert(!isa<CXXConversionDecl>(Method) && 1835 "Use AddConversionCandidate for conversion functions"); 1836 1837 // Add this candidate 1838 CandidateSet.push_back(OverloadCandidate()); 1839 OverloadCandidate& Candidate = CandidateSet.back(); 1840 Candidate.Function = Method; 1841 Candidate.IsSurrogate = false; 1842 1843 unsigned NumArgsInProto = Proto->getNumArgs(); 1844 1845 // (C++ 13.3.2p2): A candidate function having fewer than m 1846 // parameters is viable only if it has an ellipsis in its parameter 1847 // list (8.3.5). 1848 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 1849 Candidate.Viable = false; 1850 return; 1851 } 1852 1853 // (C++ 13.3.2p2): A candidate function having more than m parameters 1854 // is viable only if the (m+1)st parameter has a default argument 1855 // (8.3.6). For the purposes of overload resolution, the 1856 // parameter list is truncated on the right, so that there are 1857 // exactly m parameters. 1858 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 1859 if (NumArgs < MinRequiredArgs) { 1860 // Not enough arguments. 1861 Candidate.Viable = false; 1862 return; 1863 } 1864 1865 Candidate.Viable = true; 1866 Candidate.Conversions.resize(NumArgs + 1); 1867 1868 // Determine the implicit conversion sequence for the object 1869 // parameter. 1870 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method); 1871 if (Candidate.Conversions[0].ConversionKind 1872 == ImplicitConversionSequence::BadConversion) { 1873 Candidate.Viable = false; 1874 return; 1875 } 1876 1877 // Determine the implicit conversion sequences for each of the 1878 // arguments. 1879 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1880 if (ArgIdx < NumArgsInProto) { 1881 // (C++ 13.3.2p3): for F to be a viable function, there shall 1882 // exist for each argument an implicit conversion sequence 1883 // (13.3.3.1) that converts that argument to the corresponding 1884 // parameter of F. 1885 QualType ParamType = Proto->getArgType(ArgIdx); 1886 Candidate.Conversions[ArgIdx + 1] 1887 = TryCopyInitialization(Args[ArgIdx], ParamType, 1888 SuppressUserConversions); 1889 if (Candidate.Conversions[ArgIdx + 1].ConversionKind 1890 == ImplicitConversionSequence::BadConversion) { 1891 Candidate.Viable = false; 1892 break; 1893 } 1894 } else { 1895 // (C++ 13.3.2p2): For the purposes of overload resolution, any 1896 // argument for which there is no corresponding parameter is 1897 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 1898 Candidate.Conversions[ArgIdx + 1].ConversionKind 1899 = ImplicitConversionSequence::EllipsisConversion; 1900 } 1901 } 1902} 1903 1904/// AddConversionCandidate - Add a C++ conversion function as a 1905/// candidate in the candidate set (C++ [over.match.conv], 1906/// C++ [over.match.copy]). From is the expression we're converting from, 1907/// and ToType is the type that we're eventually trying to convert to 1908/// (which may or may not be the same type as the type that the 1909/// conversion function produces). 1910void 1911Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 1912 Expr *From, QualType ToType, 1913 OverloadCandidateSet& CandidateSet) { 1914 // Add this candidate 1915 CandidateSet.push_back(OverloadCandidate()); 1916 OverloadCandidate& Candidate = CandidateSet.back(); 1917 Candidate.Function = Conversion; 1918 Candidate.IsSurrogate = false; 1919 Candidate.FinalConversion.setAsIdentityConversion(); 1920 Candidate.FinalConversion.FromTypePtr 1921 = Conversion->getConversionType().getAsOpaquePtr(); 1922 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr(); 1923 1924 // Determine the implicit conversion sequence for the implicit 1925 // object parameter. 1926 Candidate.Viable = true; 1927 Candidate.Conversions.resize(1); 1928 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion); 1929 1930 if (Candidate.Conversions[0].ConversionKind 1931 == ImplicitConversionSequence::BadConversion) { 1932 Candidate.Viable = false; 1933 return; 1934 } 1935 1936 // To determine what the conversion from the result of calling the 1937 // conversion function to the type we're eventually trying to 1938 // convert to (ToType), we need to synthesize a call to the 1939 // conversion function and attempt copy initialization from it. This 1940 // makes sure that we get the right semantics with respect to 1941 // lvalues/rvalues and the type. Fortunately, we can allocate this 1942 // call on the stack and we don't need its arguments to be 1943 // well-formed. 1944 DeclRefExpr ConversionRef(Conversion, Conversion->getType(), 1945 SourceLocation()); 1946 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()), 1947 &ConversionRef, false); 1948 CallExpr Call(&ConversionFn, 0, 0, 1949 Conversion->getConversionType().getNonReferenceType(), 1950 SourceLocation()); 1951 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true); 1952 switch (ICS.ConversionKind) { 1953 case ImplicitConversionSequence::StandardConversion: 1954 Candidate.FinalConversion = ICS.Standard; 1955 break; 1956 1957 case ImplicitConversionSequence::BadConversion: 1958 Candidate.Viable = false; 1959 break; 1960 1961 default: 1962 assert(false && 1963 "Can only end up with a standard conversion sequence or failure"); 1964 } 1965} 1966 1967/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 1968/// converts the given @c Object to a function pointer via the 1969/// conversion function @c Conversion, and then attempts to call it 1970/// with the given arguments (C++ [over.call.object]p2-4). Proto is 1971/// the type of function that we'll eventually be calling. 1972void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 1973 const FunctionTypeProto *Proto, 1974 Expr *Object, Expr **Args, unsigned NumArgs, 1975 OverloadCandidateSet& CandidateSet) { 1976 CandidateSet.push_back(OverloadCandidate()); 1977 OverloadCandidate& Candidate = CandidateSet.back(); 1978 Candidate.Function = 0; 1979 Candidate.Surrogate = Conversion; 1980 Candidate.Viable = true; 1981 Candidate.IsSurrogate = true; 1982 Candidate.Conversions.resize(NumArgs + 1); 1983 1984 // Determine the implicit conversion sequence for the implicit 1985 // object parameter. 1986 ImplicitConversionSequence ObjectInit 1987 = TryObjectArgumentInitialization(Object, Conversion); 1988 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) { 1989 Candidate.Viable = false; 1990 return; 1991 } 1992 1993 // The first conversion is actually a user-defined conversion whose 1994 // first conversion is ObjectInit's standard conversion (which is 1995 // effectively a reference binding). Record it as such. 1996 Candidate.Conversions[0].ConversionKind 1997 = ImplicitConversionSequence::UserDefinedConversion; 1998 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 1999 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 2000 Candidate.Conversions[0].UserDefined.After 2001 = Candidate.Conversions[0].UserDefined.Before; 2002 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 2003 2004 // Find the 2005 unsigned NumArgsInProto = Proto->getNumArgs(); 2006 2007 // (C++ 13.3.2p2): A candidate function having fewer than m 2008 // parameters is viable only if it has an ellipsis in its parameter 2009 // list (8.3.5). 2010 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 2011 Candidate.Viable = false; 2012 return; 2013 } 2014 2015 // Function types don't have any default arguments, so just check if 2016 // we have enough arguments. 2017 if (NumArgs < NumArgsInProto) { 2018 // Not enough arguments. 2019 Candidate.Viable = false; 2020 return; 2021 } 2022 2023 // Determine the implicit conversion sequences for each of the 2024 // arguments. 2025 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2026 if (ArgIdx < NumArgsInProto) { 2027 // (C++ 13.3.2p3): for F to be a viable function, there shall 2028 // exist for each argument an implicit conversion sequence 2029 // (13.3.3.1) that converts that argument to the corresponding 2030 // parameter of F. 2031 QualType ParamType = Proto->getArgType(ArgIdx); 2032 Candidate.Conversions[ArgIdx + 1] 2033 = TryCopyInitialization(Args[ArgIdx], ParamType, 2034 /*SuppressUserConversions=*/false); 2035 if (Candidate.Conversions[ArgIdx + 1].ConversionKind 2036 == ImplicitConversionSequence::BadConversion) { 2037 Candidate.Viable = false; 2038 break; 2039 } 2040 } else { 2041 // (C++ 13.3.2p2): For the purposes of overload resolution, any 2042 // argument for which there is no corresponding parameter is 2043 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 2044 Candidate.Conversions[ArgIdx + 1].ConversionKind 2045 = ImplicitConversionSequence::EllipsisConversion; 2046 } 2047 } 2048} 2049 2050/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 2051/// an acceptable non-member overloaded operator for a call whose 2052/// arguments have types T1 (and, if non-empty, T2). This routine 2053/// implements the check in C++ [over.match.oper]p3b2 concerning 2054/// enumeration types. 2055static bool 2056IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn, 2057 QualType T1, QualType T2, 2058 ASTContext &Context) { 2059 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 2060 return true; 2061 2062 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto(); 2063 if (Proto->getNumArgs() < 1) 2064 return false; 2065 2066 if (T1->isEnumeralType()) { 2067 QualType ArgType = Proto->getArgType(0).getNonReferenceType(); 2068 if (Context.getCanonicalType(T1).getUnqualifiedType() 2069 == Context.getCanonicalType(ArgType).getUnqualifiedType()) 2070 return true; 2071 } 2072 2073 if (Proto->getNumArgs() < 2) 2074 return false; 2075 2076 if (!T2.isNull() && T2->isEnumeralType()) { 2077 QualType ArgType = Proto->getArgType(1).getNonReferenceType(); 2078 if (Context.getCanonicalType(T2).getUnqualifiedType() 2079 == Context.getCanonicalType(ArgType).getUnqualifiedType()) 2080 return true; 2081 } 2082 2083 return false; 2084} 2085 2086/// AddOperatorCandidates - Add the overloaded operator candidates for 2087/// the operator Op that was used in an operator expression such as "x 2088/// Op y". S is the scope in which the expression occurred (used for 2089/// name lookup of the operator), Args/NumArgs provides the operator 2090/// arguments, and CandidateSet will store the added overload 2091/// candidates. (C++ [over.match.oper]). 2092void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S, 2093 Expr **Args, unsigned NumArgs, 2094 OverloadCandidateSet& CandidateSet) { 2095 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 2096 2097 // C++ [over.match.oper]p3: 2098 // For a unary operator @ with an operand of a type whose 2099 // cv-unqualified version is T1, and for a binary operator @ with 2100 // a left operand of a type whose cv-unqualified version is T1 and 2101 // a right operand of a type whose cv-unqualified version is T2, 2102 // three sets of candidate functions, designated member 2103 // candidates, non-member candidates and built-in candidates, are 2104 // constructed as follows: 2105 QualType T1 = Args[0]->getType(); 2106 QualType T2; 2107 if (NumArgs > 1) 2108 T2 = Args[1]->getType(); 2109 2110 // -- If T1 is a class type, the set of member candidates is the 2111 // result of the qualified lookup of T1::operator@ 2112 // (13.3.1.1.1); otherwise, the set of member candidates is 2113 // empty. 2114 if (const RecordType *T1Rec = T1->getAsRecordType()) { 2115 DeclContext::lookup_const_result Lookup 2116 = T1Rec->getDecl()->lookup(Context, OpName); 2117 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first; 2118 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps)) 2119 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet, 2120 /*SuppressUserConversions=*/false); 2121 else if (OverloadedFunctionDecl *Ovl 2122 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) { 2123 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 2124 FEnd = Ovl->function_end(); 2125 F != FEnd; ++F) { 2126 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F)) 2127 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet, 2128 /*SuppressUserConversions=*/false); 2129 } 2130 } 2131 } 2132 2133 // -- The set of non-member candidates is the result of the 2134 // unqualified lookup of operator@ in the context of the 2135 // expression according to the usual rules for name lookup in 2136 // unqualified function calls (3.4.2) except that all member 2137 // functions are ignored. However, if no operand has a class 2138 // type, only those non-member functions in the lookup set 2139 // that have a first parameter of type T1 or “reference to 2140 // (possibly cv-qualified) T1”, when T1 is an enumeration 2141 // type, or (if there is a right operand) a second parameter 2142 // of type T2 or “reference to (possibly cv-qualified) T2”, 2143 // when T2 is an enumeration type, are candidate functions. 2144 { 2145 NamedDecl *NonMemberOps = 0; 2146 for (IdentifierResolver::iterator I 2147 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/); 2148 I != IdResolver.end(); ++I) { 2149 // We don't need to check the identifier namespace, because 2150 // operator names can only be ordinary identifiers. 2151 2152 // Ignore member functions. 2153 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) { 2154 if (SD->getDeclContext()->isCXXRecord()) 2155 continue; 2156 } 2157 2158 // We found something with this name. We're done. 2159 NonMemberOps = *I; 2160 break; 2161 } 2162 2163 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) { 2164 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context)) 2165 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet, 2166 /*SuppressUserConversions=*/false); 2167 } else if (OverloadedFunctionDecl *Ovl 2168 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) { 2169 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 2170 FEnd = Ovl->function_end(); 2171 F != FEnd; ++F) { 2172 if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context)) 2173 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet, 2174 /*SuppressUserConversions=*/false); 2175 } 2176 } 2177 } 2178 2179 // Add builtin overload candidates (C++ [over.built]). 2180 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet); 2181} 2182 2183/// AddBuiltinCandidate - Add a candidate for a built-in 2184/// operator. ResultTy and ParamTys are the result and parameter types 2185/// of the built-in candidate, respectively. Args and NumArgs are the 2186/// arguments being passed to the candidate. 2187void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 2188 Expr **Args, unsigned NumArgs, 2189 OverloadCandidateSet& CandidateSet) { 2190 // Add this candidate 2191 CandidateSet.push_back(OverloadCandidate()); 2192 OverloadCandidate& Candidate = CandidateSet.back(); 2193 Candidate.Function = 0; 2194 Candidate.IsSurrogate = false; 2195 Candidate.BuiltinTypes.ResultTy = ResultTy; 2196 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 2197 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 2198 2199 // Determine the implicit conversion sequences for each of the 2200 // arguments. 2201 Candidate.Viable = true; 2202 Candidate.Conversions.resize(NumArgs); 2203 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2204 Candidate.Conversions[ArgIdx] 2205 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false); 2206 if (Candidate.Conversions[ArgIdx].ConversionKind 2207 == ImplicitConversionSequence::BadConversion) { 2208 Candidate.Viable = false; 2209 break; 2210 } 2211 } 2212} 2213 2214/// BuiltinCandidateTypeSet - A set of types that will be used for the 2215/// candidate operator functions for built-in operators (C++ 2216/// [over.built]). The types are separated into pointer types and 2217/// enumeration types. 2218class BuiltinCandidateTypeSet { 2219 /// TypeSet - A set of types. 2220 typedef llvm::SmallPtrSet<void*, 8> TypeSet; 2221 2222 /// PointerTypes - The set of pointer types that will be used in the 2223 /// built-in candidates. 2224 TypeSet PointerTypes; 2225 2226 /// EnumerationTypes - The set of enumeration types that will be 2227 /// used in the built-in candidates. 2228 TypeSet EnumerationTypes; 2229 2230 /// Context - The AST context in which we will build the type sets. 2231 ASTContext &Context; 2232 2233 bool AddWithMoreQualifiedTypeVariants(QualType Ty); 2234 2235public: 2236 /// iterator - Iterates through the types that are part of the set. 2237 class iterator { 2238 TypeSet::iterator Base; 2239 2240 public: 2241 typedef QualType value_type; 2242 typedef QualType reference; 2243 typedef QualType pointer; 2244 typedef std::ptrdiff_t difference_type; 2245 typedef std::input_iterator_tag iterator_category; 2246 2247 iterator(TypeSet::iterator B) : Base(B) { } 2248 2249 iterator& operator++() { 2250 ++Base; 2251 return *this; 2252 } 2253 2254 iterator operator++(int) { 2255 iterator tmp(*this); 2256 ++(*this); 2257 return tmp; 2258 } 2259 2260 reference operator*() const { 2261 return QualType::getFromOpaquePtr(*Base); 2262 } 2263 2264 pointer operator->() const { 2265 return **this; 2266 } 2267 2268 friend bool operator==(iterator LHS, iterator RHS) { 2269 return LHS.Base == RHS.Base; 2270 } 2271 2272 friend bool operator!=(iterator LHS, iterator RHS) { 2273 return LHS.Base != RHS.Base; 2274 } 2275 }; 2276 2277 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { } 2278 2279 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true); 2280 2281 /// pointer_begin - First pointer type found; 2282 iterator pointer_begin() { return PointerTypes.begin(); } 2283 2284 /// pointer_end - Last pointer type found; 2285 iterator pointer_end() { return PointerTypes.end(); } 2286 2287 /// enumeration_begin - First enumeration type found; 2288 iterator enumeration_begin() { return EnumerationTypes.begin(); } 2289 2290 /// enumeration_end - Last enumeration type found; 2291 iterator enumeration_end() { return EnumerationTypes.end(); } 2292}; 2293 2294/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 2295/// the set of pointer types along with any more-qualified variants of 2296/// that type. For example, if @p Ty is "int const *", this routine 2297/// will add "int const *", "int const volatile *", "int const 2298/// restrict *", and "int const volatile restrict *" to the set of 2299/// pointer types. Returns true if the add of @p Ty itself succeeded, 2300/// false otherwise. 2301bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) { 2302 // Insert this type. 2303 if (!PointerTypes.insert(Ty.getAsOpaquePtr())) 2304 return false; 2305 2306 if (const PointerType *PointerTy = Ty->getAsPointerType()) { 2307 QualType PointeeTy = PointerTy->getPointeeType(); 2308 // FIXME: Optimize this so that we don't keep trying to add the same types. 2309 2310 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal 2311 // with all pointer conversions that don't cast away constness? 2312 if (!PointeeTy.isConstQualified()) 2313 AddWithMoreQualifiedTypeVariants 2314 (Context.getPointerType(PointeeTy.withConst())); 2315 if (!PointeeTy.isVolatileQualified()) 2316 AddWithMoreQualifiedTypeVariants 2317 (Context.getPointerType(PointeeTy.withVolatile())); 2318 if (!PointeeTy.isRestrictQualified()) 2319 AddWithMoreQualifiedTypeVariants 2320 (Context.getPointerType(PointeeTy.withRestrict())); 2321 } 2322 2323 return true; 2324} 2325 2326/// AddTypesConvertedFrom - Add each of the types to which the type @p 2327/// Ty can be implicit converted to the given set of @p Types. We're 2328/// primarily interested in pointer types, enumeration types, 2329void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 2330 bool AllowUserConversions) { 2331 // Only deal with canonical types. 2332 Ty = Context.getCanonicalType(Ty); 2333 2334 // Look through reference types; they aren't part of the type of an 2335 // expression for the purposes of conversions. 2336 if (const ReferenceType *RefTy = Ty->getAsReferenceType()) 2337 Ty = RefTy->getPointeeType(); 2338 2339 // We don't care about qualifiers on the type. 2340 Ty = Ty.getUnqualifiedType(); 2341 2342 if (const PointerType *PointerTy = Ty->getAsPointerType()) { 2343 QualType PointeeTy = PointerTy->getPointeeType(); 2344 2345 // Insert our type, and its more-qualified variants, into the set 2346 // of types. 2347 if (!AddWithMoreQualifiedTypeVariants(Ty)) 2348 return; 2349 2350 // Add 'cv void*' to our set of types. 2351 if (!Ty->isVoidType()) { 2352 QualType QualVoid 2353 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers()); 2354 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid)); 2355 } 2356 2357 // If this is a pointer to a class type, add pointers to its bases 2358 // (with the same level of cv-qualification as the original 2359 // derived class, of course). 2360 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) { 2361 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl()); 2362 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2363 Base != ClassDecl->bases_end(); ++Base) { 2364 QualType BaseTy = Context.getCanonicalType(Base->getType()); 2365 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers()); 2366 2367 // Add the pointer type, recursively, so that we get all of 2368 // the indirect base classes, too. 2369 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false); 2370 } 2371 } 2372 } else if (Ty->isEnumeralType()) { 2373 EnumerationTypes.insert(Ty.getAsOpaquePtr()); 2374 } else if (AllowUserConversions) { 2375 if (const RecordType *TyRec = Ty->getAsRecordType()) { 2376 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 2377 // FIXME: Visit conversion functions in the base classes, too. 2378 OverloadedFunctionDecl *Conversions 2379 = ClassDecl->getConversionFunctions(); 2380 for (OverloadedFunctionDecl::function_iterator Func 2381 = Conversions->function_begin(); 2382 Func != Conversions->function_end(); ++Func) { 2383 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 2384 AddTypesConvertedFrom(Conv->getConversionType(), false); 2385 } 2386 } 2387 } 2388} 2389 2390/// AddBuiltinOperatorCandidates - Add the appropriate built-in 2391/// operator overloads to the candidate set (C++ [over.built]), based 2392/// on the operator @p Op and the arguments given. For example, if the 2393/// operator is a binary '+', this routine might add "int 2394/// operator+(int, int)" to cover integer addition. 2395void 2396Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 2397 Expr **Args, unsigned NumArgs, 2398 OverloadCandidateSet& CandidateSet) { 2399 // The set of "promoted arithmetic types", which are the arithmetic 2400 // types are that preserved by promotion (C++ [over.built]p2). Note 2401 // that the first few of these types are the promoted integral 2402 // types; these types need to be first. 2403 // FIXME: What about complex? 2404 const unsigned FirstIntegralType = 0; 2405 const unsigned LastIntegralType = 13; 2406 const unsigned FirstPromotedIntegralType = 7, 2407 LastPromotedIntegralType = 13; 2408 const unsigned FirstPromotedArithmeticType = 7, 2409 LastPromotedArithmeticType = 16; 2410 const unsigned NumArithmeticTypes = 16; 2411 QualType ArithmeticTypes[NumArithmeticTypes] = { 2412 Context.BoolTy, Context.CharTy, Context.WCharTy, 2413 Context.SignedCharTy, Context.ShortTy, 2414 Context.UnsignedCharTy, Context.UnsignedShortTy, 2415 Context.IntTy, Context.LongTy, Context.LongLongTy, 2416 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy, 2417 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy 2418 }; 2419 2420 // Find all of the types that the arguments can convert to, but only 2421 // if the operator we're looking at has built-in operator candidates 2422 // that make use of these types. 2423 BuiltinCandidateTypeSet CandidateTypes(Context); 2424 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual || 2425 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual || 2426 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal || 2427 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript || 2428 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus || 2429 (Op == OO_Star && NumArgs == 1)) { 2430 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 2431 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType()); 2432 } 2433 2434 bool isComparison = false; 2435 switch (Op) { 2436 case OO_None: 2437 case NUM_OVERLOADED_OPERATORS: 2438 assert(false && "Expected an overloaded operator"); 2439 break; 2440 2441 case OO_Star: // '*' is either unary or binary 2442 if (NumArgs == 1) 2443 goto UnaryStar; 2444 else 2445 goto BinaryStar; 2446 break; 2447 2448 case OO_Plus: // '+' is either unary or binary 2449 if (NumArgs == 1) 2450 goto UnaryPlus; 2451 else 2452 goto BinaryPlus; 2453 break; 2454 2455 case OO_Minus: // '-' is either unary or binary 2456 if (NumArgs == 1) 2457 goto UnaryMinus; 2458 else 2459 goto BinaryMinus; 2460 break; 2461 2462 case OO_Amp: // '&' is either unary or binary 2463 if (NumArgs == 1) 2464 goto UnaryAmp; 2465 else 2466 goto BinaryAmp; 2467 2468 case OO_PlusPlus: 2469 case OO_MinusMinus: 2470 // C++ [over.built]p3: 2471 // 2472 // For every pair (T, VQ), where T is an arithmetic type, and VQ 2473 // is either volatile or empty, there exist candidate operator 2474 // functions of the form 2475 // 2476 // VQ T& operator++(VQ T&); 2477 // T operator++(VQ T&, int); 2478 // 2479 // C++ [over.built]p4: 2480 // 2481 // For every pair (T, VQ), where T is an arithmetic type other 2482 // than bool, and VQ is either volatile or empty, there exist 2483 // candidate operator functions of the form 2484 // 2485 // VQ T& operator--(VQ T&); 2486 // T operator--(VQ T&, int); 2487 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 2488 Arith < NumArithmeticTypes; ++Arith) { 2489 QualType ArithTy = ArithmeticTypes[Arith]; 2490 QualType ParamTypes[2] 2491 = { Context.getReferenceType(ArithTy), Context.IntTy }; 2492 2493 // Non-volatile version. 2494 if (NumArgs == 1) 2495 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2496 else 2497 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 2498 2499 // Volatile version 2500 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile()); 2501 if (NumArgs == 1) 2502 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2503 else 2504 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 2505 } 2506 2507 // C++ [over.built]p5: 2508 // 2509 // For every pair (T, VQ), where T is a cv-qualified or 2510 // cv-unqualified object type, and VQ is either volatile or 2511 // empty, there exist candidate operator functions of the form 2512 // 2513 // T*VQ& operator++(T*VQ&); 2514 // T*VQ& operator--(T*VQ&); 2515 // T* operator++(T*VQ&, int); 2516 // T* operator--(T*VQ&, int); 2517 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2518 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2519 // Skip pointer types that aren't pointers to object types. 2520 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType()) 2521 continue; 2522 2523 QualType ParamTypes[2] = { 2524 Context.getReferenceType(*Ptr), Context.IntTy 2525 }; 2526 2527 // Without volatile 2528 if (NumArgs == 1) 2529 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2530 else 2531 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2532 2533 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) { 2534 // With volatile 2535 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile()); 2536 if (NumArgs == 1) 2537 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2538 else 2539 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2540 } 2541 } 2542 break; 2543 2544 UnaryStar: 2545 // C++ [over.built]p6: 2546 // For every cv-qualified or cv-unqualified object type T, there 2547 // exist candidate operator functions of the form 2548 // 2549 // T& operator*(T*); 2550 // 2551 // C++ [over.built]p7: 2552 // For every function type T, there exist candidate operator 2553 // functions of the form 2554 // T& operator*(T*); 2555 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2556 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2557 QualType ParamTy = *Ptr; 2558 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType(); 2559 AddBuiltinCandidate(Context.getReferenceType(PointeeTy), 2560 &ParamTy, Args, 1, CandidateSet); 2561 } 2562 break; 2563 2564 UnaryPlus: 2565 // C++ [over.built]p8: 2566 // For every type T, there exist candidate operator functions of 2567 // the form 2568 // 2569 // T* operator+(T*); 2570 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2571 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2572 QualType ParamTy = *Ptr; 2573 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 2574 } 2575 2576 // Fall through 2577 2578 UnaryMinus: 2579 // C++ [over.built]p9: 2580 // For every promoted arithmetic type T, there exist candidate 2581 // operator functions of the form 2582 // 2583 // T operator+(T); 2584 // T operator-(T); 2585 for (unsigned Arith = FirstPromotedArithmeticType; 2586 Arith < LastPromotedArithmeticType; ++Arith) { 2587 QualType ArithTy = ArithmeticTypes[Arith]; 2588 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 2589 } 2590 break; 2591 2592 case OO_Tilde: 2593 // C++ [over.built]p10: 2594 // For every promoted integral type T, there exist candidate 2595 // operator functions of the form 2596 // 2597 // T operator~(T); 2598 for (unsigned Int = FirstPromotedIntegralType; 2599 Int < LastPromotedIntegralType; ++Int) { 2600 QualType IntTy = ArithmeticTypes[Int]; 2601 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 2602 } 2603 break; 2604 2605 case OO_New: 2606 case OO_Delete: 2607 case OO_Array_New: 2608 case OO_Array_Delete: 2609 case OO_Call: 2610 assert(false && "Special operators don't use AddBuiltinOperatorCandidates"); 2611 break; 2612 2613 case OO_Comma: 2614 UnaryAmp: 2615 case OO_Arrow: 2616 // C++ [over.match.oper]p3: 2617 // -- For the operator ',', the unary operator '&', or the 2618 // operator '->', the built-in candidates set is empty. 2619 break; 2620 2621 case OO_Less: 2622 case OO_Greater: 2623 case OO_LessEqual: 2624 case OO_GreaterEqual: 2625 case OO_EqualEqual: 2626 case OO_ExclaimEqual: 2627 // C++ [over.built]p15: 2628 // 2629 // For every pointer or enumeration type T, there exist 2630 // candidate operator functions of the form 2631 // 2632 // bool operator<(T, T); 2633 // bool operator>(T, T); 2634 // bool operator<=(T, T); 2635 // bool operator>=(T, T); 2636 // bool operator==(T, T); 2637 // bool operator!=(T, T); 2638 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2639 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2640 QualType ParamTypes[2] = { *Ptr, *Ptr }; 2641 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2642 } 2643 for (BuiltinCandidateTypeSet::iterator Enum 2644 = CandidateTypes.enumeration_begin(); 2645 Enum != CandidateTypes.enumeration_end(); ++Enum) { 2646 QualType ParamTypes[2] = { *Enum, *Enum }; 2647 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2648 } 2649 2650 // Fall through. 2651 isComparison = true; 2652 2653 BinaryPlus: 2654 BinaryMinus: 2655 if (!isComparison) { 2656 // We didn't fall through, so we must have OO_Plus or OO_Minus. 2657 2658 // C++ [over.built]p13: 2659 // 2660 // For every cv-qualified or cv-unqualified object type T 2661 // there exist candidate operator functions of the form 2662 // 2663 // T* operator+(T*, ptrdiff_t); 2664 // T& operator[](T*, ptrdiff_t); [BELOW] 2665 // T* operator-(T*, ptrdiff_t); 2666 // T* operator+(ptrdiff_t, T*); 2667 // T& operator[](ptrdiff_t, T*); [BELOW] 2668 // 2669 // C++ [over.built]p14: 2670 // 2671 // For every T, where T is a pointer to object type, there 2672 // exist candidate operator functions of the form 2673 // 2674 // ptrdiff_t operator-(T, T); 2675 for (BuiltinCandidateTypeSet::iterator Ptr 2676 = CandidateTypes.pointer_begin(); 2677 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2678 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 2679 2680 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 2681 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2682 2683 if (Op == OO_Plus) { 2684 // T* operator+(ptrdiff_t, T*); 2685 ParamTypes[0] = ParamTypes[1]; 2686 ParamTypes[1] = *Ptr; 2687 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2688 } else { 2689 // ptrdiff_t operator-(T, T); 2690 ParamTypes[1] = *Ptr; 2691 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes, 2692 Args, 2, CandidateSet); 2693 } 2694 } 2695 } 2696 // Fall through 2697 2698 case OO_Slash: 2699 BinaryStar: 2700 // C++ [over.built]p12: 2701 // 2702 // For every pair of promoted arithmetic types L and R, there 2703 // exist candidate operator functions of the form 2704 // 2705 // LR operator*(L, R); 2706 // LR operator/(L, R); 2707 // LR operator+(L, R); 2708 // LR operator-(L, R); 2709 // bool operator<(L, R); 2710 // bool operator>(L, R); 2711 // bool operator<=(L, R); 2712 // bool operator>=(L, R); 2713 // bool operator==(L, R); 2714 // bool operator!=(L, R); 2715 // 2716 // where LR is the result of the usual arithmetic conversions 2717 // between types L and R. 2718 for (unsigned Left = FirstPromotedArithmeticType; 2719 Left < LastPromotedArithmeticType; ++Left) { 2720 for (unsigned Right = FirstPromotedArithmeticType; 2721 Right < LastPromotedArithmeticType; ++Right) { 2722 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 2723 QualType Result 2724 = isComparison? Context.BoolTy 2725 : UsualArithmeticConversionsType(LandR[0], LandR[1]); 2726 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 2727 } 2728 } 2729 break; 2730 2731 case OO_Percent: 2732 BinaryAmp: 2733 case OO_Caret: 2734 case OO_Pipe: 2735 case OO_LessLess: 2736 case OO_GreaterGreater: 2737 // C++ [over.built]p17: 2738 // 2739 // For every pair of promoted integral types L and R, there 2740 // exist candidate operator functions of the form 2741 // 2742 // LR operator%(L, R); 2743 // LR operator&(L, R); 2744 // LR operator^(L, R); 2745 // LR operator|(L, R); 2746 // L operator<<(L, R); 2747 // L operator>>(L, R); 2748 // 2749 // where LR is the result of the usual arithmetic conversions 2750 // between types L and R. 2751 for (unsigned Left = FirstPromotedIntegralType; 2752 Left < LastPromotedIntegralType; ++Left) { 2753 for (unsigned Right = FirstPromotedIntegralType; 2754 Right < LastPromotedIntegralType; ++Right) { 2755 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 2756 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 2757 ? LandR[0] 2758 : UsualArithmeticConversionsType(LandR[0], LandR[1]); 2759 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 2760 } 2761 } 2762 break; 2763 2764 case OO_Equal: 2765 // C++ [over.built]p20: 2766 // 2767 // For every pair (T, VQ), where T is an enumeration or 2768 // (FIXME:) pointer to member type and VQ is either volatile or 2769 // empty, there exist candidate operator functions of the form 2770 // 2771 // VQ T& operator=(VQ T&, T); 2772 for (BuiltinCandidateTypeSet::iterator Enum 2773 = CandidateTypes.enumeration_begin(); 2774 Enum != CandidateTypes.enumeration_end(); ++Enum) { 2775 QualType ParamTypes[2]; 2776 2777 // T& operator=(T&, T) 2778 ParamTypes[0] = Context.getReferenceType(*Enum); 2779 ParamTypes[1] = *Enum; 2780 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2781 2782 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) { 2783 // volatile T& operator=(volatile T&, T) 2784 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile()); 2785 ParamTypes[1] = *Enum; 2786 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2787 } 2788 } 2789 // Fall through. 2790 2791 case OO_PlusEqual: 2792 case OO_MinusEqual: 2793 // C++ [over.built]p19: 2794 // 2795 // For every pair (T, VQ), where T is any type and VQ is either 2796 // volatile or empty, there exist candidate operator functions 2797 // of the form 2798 // 2799 // T*VQ& operator=(T*VQ&, T*); 2800 // 2801 // C++ [over.built]p21: 2802 // 2803 // For every pair (T, VQ), where T is a cv-qualified or 2804 // cv-unqualified object type and VQ is either volatile or 2805 // empty, there exist candidate operator functions of the form 2806 // 2807 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 2808 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 2809 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2810 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2811 QualType ParamTypes[2]; 2812 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType(); 2813 2814 // non-volatile version 2815 ParamTypes[0] = Context.getReferenceType(*Ptr); 2816 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2817 2818 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) { 2819 // volatile version 2820 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile()); 2821 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2822 } 2823 } 2824 // Fall through. 2825 2826 case OO_StarEqual: 2827 case OO_SlashEqual: 2828 // C++ [over.built]p18: 2829 // 2830 // For every triple (L, VQ, R), where L is an arithmetic type, 2831 // VQ is either volatile or empty, and R is a promoted 2832 // arithmetic type, there exist candidate operator functions of 2833 // the form 2834 // 2835 // VQ L& operator=(VQ L&, R); 2836 // VQ L& operator*=(VQ L&, R); 2837 // VQ L& operator/=(VQ L&, R); 2838 // VQ L& operator+=(VQ L&, R); 2839 // VQ L& operator-=(VQ L&, R); 2840 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 2841 for (unsigned Right = FirstPromotedArithmeticType; 2842 Right < LastPromotedArithmeticType; ++Right) { 2843 QualType ParamTypes[2]; 2844 ParamTypes[1] = ArithmeticTypes[Right]; 2845 2846 // Add this built-in operator as a candidate (VQ is empty). 2847 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]); 2848 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2849 2850 // Add this built-in operator as a candidate (VQ is 'volatile'). 2851 ParamTypes[0] = ArithmeticTypes[Left].withVolatile(); 2852 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]); 2853 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2854 } 2855 } 2856 break; 2857 2858 case OO_PercentEqual: 2859 case OO_LessLessEqual: 2860 case OO_GreaterGreaterEqual: 2861 case OO_AmpEqual: 2862 case OO_CaretEqual: 2863 case OO_PipeEqual: 2864 // C++ [over.built]p22: 2865 // 2866 // For every triple (L, VQ, R), where L is an integral type, VQ 2867 // is either volatile or empty, and R is a promoted integral 2868 // type, there exist candidate operator functions of the form 2869 // 2870 // VQ L& operator%=(VQ L&, R); 2871 // VQ L& operator<<=(VQ L&, R); 2872 // VQ L& operator>>=(VQ L&, R); 2873 // VQ L& operator&=(VQ L&, R); 2874 // VQ L& operator^=(VQ L&, R); 2875 // VQ L& operator|=(VQ L&, R); 2876 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 2877 for (unsigned Right = FirstPromotedIntegralType; 2878 Right < LastPromotedIntegralType; ++Right) { 2879 QualType ParamTypes[2]; 2880 ParamTypes[1] = ArithmeticTypes[Right]; 2881 2882 // Add this built-in operator as a candidate (VQ is empty). 2883 // FIXME: We should be caching these declarations somewhere, 2884 // rather than re-building them every time. 2885 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]); 2886 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2887 2888 // Add this built-in operator as a candidate (VQ is 'volatile'). 2889 ParamTypes[0] = ArithmeticTypes[Left]; 2890 ParamTypes[0].addVolatile(); 2891 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]); 2892 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2893 } 2894 } 2895 break; 2896 2897 case OO_Exclaim: { 2898 // C++ [over.operator]p23: 2899 // 2900 // There also exist candidate operator functions of the form 2901 // 2902 // bool operator!(bool); 2903 // bool operator&&(bool, bool); [BELOW] 2904 // bool operator||(bool, bool); [BELOW] 2905 QualType ParamTy = Context.BoolTy; 2906 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 2907 break; 2908 } 2909 2910 case OO_AmpAmp: 2911 case OO_PipePipe: { 2912 // C++ [over.operator]p23: 2913 // 2914 // There also exist candidate operator functions of the form 2915 // 2916 // bool operator!(bool); [ABOVE] 2917 // bool operator&&(bool, bool); 2918 // bool operator||(bool, bool); 2919 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy }; 2920 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2921 break; 2922 } 2923 2924 case OO_Subscript: 2925 // C++ [over.built]p13: 2926 // 2927 // For every cv-qualified or cv-unqualified object type T there 2928 // exist candidate operator functions of the form 2929 // 2930 // T* operator+(T*, ptrdiff_t); [ABOVE] 2931 // T& operator[](T*, ptrdiff_t); 2932 // T* operator-(T*, ptrdiff_t); [ABOVE] 2933 // T* operator+(ptrdiff_t, T*); [ABOVE] 2934 // T& operator[](ptrdiff_t, T*); 2935 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2936 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2937 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 2938 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType(); 2939 QualType ResultTy = Context.getReferenceType(PointeeType); 2940 2941 // T& operator[](T*, ptrdiff_t) 2942 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 2943 2944 // T& operator[](ptrdiff_t, T*); 2945 ParamTypes[0] = ParamTypes[1]; 2946 ParamTypes[1] = *Ptr; 2947 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 2948 } 2949 break; 2950 2951 case OO_ArrowStar: 2952 // FIXME: No support for pointer-to-members yet. 2953 break; 2954 } 2955} 2956 2957/// AddOverloadCandidates - Add all of the function overloads in Ovl 2958/// to the candidate set. 2959void 2960Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl, 2961 Expr **Args, unsigned NumArgs, 2962 OverloadCandidateSet& CandidateSet, 2963 bool SuppressUserConversions) 2964{ 2965 for (OverloadedFunctionDecl::function_const_iterator Func 2966 = Ovl->function_begin(); 2967 Func != Ovl->function_end(); ++Func) 2968 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet, 2969 SuppressUserConversions); 2970} 2971 2972/// isBetterOverloadCandidate - Determines whether the first overload 2973/// candidate is a better candidate than the second (C++ 13.3.3p1). 2974bool 2975Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1, 2976 const OverloadCandidate& Cand2) 2977{ 2978 // Define viable functions to be better candidates than non-viable 2979 // functions. 2980 if (!Cand2.Viable) 2981 return Cand1.Viable; 2982 else if (!Cand1.Viable) 2983 return false; 2984 2985 // FIXME: Deal with the implicit object parameter for static member 2986 // functions. (C++ 13.3.3p1). 2987 2988 // (C++ 13.3.3p1): a viable function F1 is defined to be a better 2989 // function than another viable function F2 if for all arguments i, 2990 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and 2991 // then... 2992 unsigned NumArgs = Cand1.Conversions.size(); 2993 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 2994 bool HasBetterConversion = false; 2995 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2996 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx], 2997 Cand2.Conversions[ArgIdx])) { 2998 case ImplicitConversionSequence::Better: 2999 // Cand1 has a better conversion sequence. 3000 HasBetterConversion = true; 3001 break; 3002 3003 case ImplicitConversionSequence::Worse: 3004 // Cand1 can't be better than Cand2. 3005 return false; 3006 3007 case ImplicitConversionSequence::Indistinguishable: 3008 // Do nothing. 3009 break; 3010 } 3011 } 3012 3013 if (HasBetterConversion) 3014 return true; 3015 3016 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be 3017 // implemented, but they require template support. 3018 3019 // C++ [over.match.best]p1b4: 3020 // 3021 // -- the context is an initialization by user-defined conversion 3022 // (see 8.5, 13.3.1.5) and the standard conversion sequence 3023 // from the return type of F1 to the destination type (i.e., 3024 // the type of the entity being initialized) is a better 3025 // conversion sequence than the standard conversion sequence 3026 // from the return type of F2 to the destination type. 3027 if (Cand1.Function && Cand2.Function && 3028 isa<CXXConversionDecl>(Cand1.Function) && 3029 isa<CXXConversionDecl>(Cand2.Function)) { 3030 switch (CompareStandardConversionSequences(Cand1.FinalConversion, 3031 Cand2.FinalConversion)) { 3032 case ImplicitConversionSequence::Better: 3033 // Cand1 has a better conversion sequence. 3034 return true; 3035 3036 case ImplicitConversionSequence::Worse: 3037 // Cand1 can't be better than Cand2. 3038 return false; 3039 3040 case ImplicitConversionSequence::Indistinguishable: 3041 // Do nothing 3042 break; 3043 } 3044 } 3045 3046 return false; 3047} 3048 3049/// BestViableFunction - Computes the best viable function (C++ 13.3.3) 3050/// within an overload candidate set. If overloading is successful, 3051/// the result will be OR_Success and Best will be set to point to the 3052/// best viable function within the candidate set. Otherwise, one of 3053/// several kinds of errors will be returned; see 3054/// Sema::OverloadingResult. 3055Sema::OverloadingResult 3056Sema::BestViableFunction(OverloadCandidateSet& CandidateSet, 3057 OverloadCandidateSet::iterator& Best) 3058{ 3059 // Find the best viable function. 3060 Best = CandidateSet.end(); 3061 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 3062 Cand != CandidateSet.end(); ++Cand) { 3063 if (Cand->Viable) { 3064 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best)) 3065 Best = Cand; 3066 } 3067 } 3068 3069 // If we didn't find any viable functions, abort. 3070 if (Best == CandidateSet.end()) 3071 return OR_No_Viable_Function; 3072 3073 // Make sure that this function is better than every other viable 3074 // function. If not, we have an ambiguity. 3075 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 3076 Cand != CandidateSet.end(); ++Cand) { 3077 if (Cand->Viable && 3078 Cand != Best && 3079 !isBetterOverloadCandidate(*Best, *Cand)) { 3080 Best = CandidateSet.end(); 3081 return OR_Ambiguous; 3082 } 3083 } 3084 3085 // Best is the best viable function. 3086 return OR_Success; 3087} 3088 3089/// PrintOverloadCandidates - When overload resolution fails, prints 3090/// diagnostic messages containing the candidates in the candidate 3091/// set. If OnlyViable is true, only viable candidates will be printed. 3092void 3093Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet, 3094 bool OnlyViable) 3095{ 3096 OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 3097 LastCand = CandidateSet.end(); 3098 for (; Cand != LastCand; ++Cand) { 3099 if (Cand->Viable || !OnlyViable) { 3100 if (Cand->Function) { 3101 // Normal function 3102 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate); 3103 } else if (Cand->IsSurrogate) { 3104 // Desugar the type of the surrogate down to a function type, 3105 // retaining as many typedefs as possible while still showing 3106 // the function type (and, therefore, its parameter types). 3107 QualType FnType = Cand->Surrogate->getConversionType(); 3108 bool isReference = false; 3109 bool isPointer = false; 3110 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) { 3111 FnType = FnTypeRef->getPointeeType(); 3112 isReference = true; 3113 } 3114 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) { 3115 FnType = FnTypePtr->getPointeeType(); 3116 isPointer = true; 3117 } 3118 // Desugar down to a function type. 3119 FnType = QualType(FnType->getAsFunctionType(), 0); 3120 // Reconstruct the pointer/reference as appropriate. 3121 if (isPointer) FnType = Context.getPointerType(FnType); 3122 if (isReference) FnType = Context.getReferenceType(FnType); 3123 3124 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand) 3125 << FnType; 3126 } else { 3127 // FIXME: We need to get the identifier in here 3128 // FIXME: Do we want the error message to point at the 3129 // operator? (built-ins won't have a location) 3130 QualType FnType 3131 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy, 3132 Cand->BuiltinTypes.ParamTypes, 3133 Cand->Conversions.size(), 3134 false, 0); 3135 3136 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType; 3137 } 3138 } 3139 } 3140} 3141 3142/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 3143/// an overloaded function (C++ [over.over]), where @p From is an 3144/// expression with overloaded function type and @p ToType is the type 3145/// we're trying to resolve to. For example: 3146/// 3147/// @code 3148/// int f(double); 3149/// int f(int); 3150/// 3151/// int (*pfd)(double) = f; // selects f(double) 3152/// @endcode 3153/// 3154/// This routine returns the resulting FunctionDecl if it could be 3155/// resolved, and NULL otherwise. When @p Complain is true, this 3156/// routine will emit diagnostics if there is an error. 3157FunctionDecl * 3158Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType, 3159 bool Complain) { 3160 QualType FunctionType = ToType; 3161 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType()) 3162 FunctionType = ToTypePtr->getPointeeType(); 3163 3164 // We only look at pointers or references to functions. 3165 if (!FunctionType->isFunctionType()) 3166 return 0; 3167 3168 // Find the actual overloaded function declaration. 3169 OverloadedFunctionDecl *Ovl = 0; 3170 3171 // C++ [over.over]p1: 3172 // [...] [Note: any redundant set of parentheses surrounding the 3173 // overloaded function name is ignored (5.1). ] 3174 Expr *OvlExpr = From->IgnoreParens(); 3175 3176 // C++ [over.over]p1: 3177 // [...] The overloaded function name can be preceded by the & 3178 // operator. 3179 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) { 3180 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 3181 OvlExpr = UnOp->getSubExpr()->IgnoreParens(); 3182 } 3183 3184 // Try to dig out the overloaded function. 3185 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) 3186 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl()); 3187 3188 // If there's no overloaded function declaration, we're done. 3189 if (!Ovl) 3190 return 0; 3191 3192 // Look through all of the overloaded functions, searching for one 3193 // whose type matches exactly. 3194 // FIXME: When templates or using declarations come along, we'll actually 3195 // have to deal with duplicates, partial ordering, etc. For now, we 3196 // can just do a simple search. 3197 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType()); 3198 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin(); 3199 Fun != Ovl->function_end(); ++Fun) { 3200 // C++ [over.over]p3: 3201 // Non-member functions and static member functions match 3202 // targets of type “pointer-to-function”or 3203 // “reference-to-function.” 3204 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) 3205 if (!Method->isStatic()) 3206 continue; 3207 3208 if (FunctionType == Context.getCanonicalType((*Fun)->getType())) 3209 return *Fun; 3210 } 3211 3212 return 0; 3213} 3214 3215/// ResolveOverloadedCallFn - Given the call expression that calls Fn 3216/// (which eventually refers to the set of overloaded functions in 3217/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the 3218/// function call down to a specific function. If overload resolution 3219/// succeeds, returns the function declaration produced by overload 3220/// resolution. Otherwise, emits diagnostics, deletes all of the 3221/// arguments and Fn, and returns NULL. 3222FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl, 3223 SourceLocation LParenLoc, 3224 Expr **Args, unsigned NumArgs, 3225 SourceLocation *CommaLocs, 3226 SourceLocation RParenLoc) { 3227 OverloadCandidateSet CandidateSet; 3228 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet); 3229 OverloadCandidateSet::iterator Best; 3230 switch (BestViableFunction(CandidateSet, Best)) { 3231 case OR_Success: 3232 return Best->Function; 3233 3234 case OR_No_Viable_Function: 3235 Diag(Fn->getSourceRange().getBegin(), 3236 diag::err_ovl_no_viable_function_in_call) 3237 << Ovl->getDeclName() << (unsigned)CandidateSet.size() 3238 << Fn->getSourceRange(); 3239 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3240 break; 3241 3242 case OR_Ambiguous: 3243 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 3244 << Ovl->getDeclName() << Fn->getSourceRange(); 3245 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3246 break; 3247 } 3248 3249 // Overload resolution failed. Destroy all of the subexpressions and 3250 // return NULL. 3251 Fn->Destroy(Context); 3252 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) 3253 Args[Arg]->Destroy(Context); 3254 return 0; 3255} 3256 3257/// BuildCallToObjectOfClassType - Build a call to an object of class 3258/// type (C++ [over.call.object]), which can end up invoking an 3259/// overloaded function call operator (@c operator()) or performing a 3260/// user-defined conversion on the object argument. 3261Action::ExprResult 3262Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object, 3263 SourceLocation LParenLoc, 3264 Expr **Args, unsigned NumArgs, 3265 SourceLocation *CommaLocs, 3266 SourceLocation RParenLoc) { 3267 assert(Object->getType()->isRecordType() && "Requires object type argument"); 3268 const RecordType *Record = Object->getType()->getAsRecordType(); 3269 3270 // C++ [over.call.object]p1: 3271 // If the primary-expression E in the function call syntax 3272 // evaluates to a class object of type “cv T”, then the set of 3273 // candidate functions includes at least the function call 3274 // operators of T. The function call operators of T are obtained by 3275 // ordinary lookup of the name operator() in the context of 3276 // (E).operator(). 3277 OverloadCandidateSet CandidateSet; 3278 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 3279 DeclContext::lookup_const_result Lookup 3280 = Record->getDecl()->lookup(Context, OpName); 3281 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first; 3282 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps)) 3283 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet, 3284 /*SuppressUserConversions=*/false); 3285 else if (OverloadedFunctionDecl *Ovl 3286 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) { 3287 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 3288 FEnd = Ovl->function_end(); 3289 F != FEnd; ++F) { 3290 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F)) 3291 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet, 3292 /*SuppressUserConversions=*/false); 3293 } 3294 } 3295 3296 // C++ [over.call.object]p2: 3297 // In addition, for each conversion function declared in T of the 3298 // form 3299 // 3300 // operator conversion-type-id () cv-qualifier; 3301 // 3302 // where cv-qualifier is the same cv-qualification as, or a 3303 // greater cv-qualification than, cv, and where conversion-type-id 3304 // denotes the type "pointer to function of (P1,...,Pn) returning 3305 // R", or the type "reference to pointer to function of 3306 // (P1,...,Pn) returning R", or the type "reference to function 3307 // of (P1,...,Pn) returning R", a surrogate call function [...] 3308 // is also considered as a candidate function. Similarly, 3309 // surrogate call functions are added to the set of candidate 3310 // functions for each conversion function declared in an 3311 // accessible base class provided the function is not hidden 3312 // within T by another intervening declaration. 3313 // 3314 // FIXME: Look in base classes for more conversion operators! 3315 OverloadedFunctionDecl *Conversions 3316 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions(); 3317 for (OverloadedFunctionDecl::function_iterator 3318 Func = Conversions->function_begin(), 3319 FuncEnd = Conversions->function_end(); 3320 Func != FuncEnd; ++Func) { 3321 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 3322 3323 // Strip the reference type (if any) and then the pointer type (if 3324 // any) to get down to what might be a function type. 3325 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 3326 if (const PointerType *ConvPtrType = ConvType->getAsPointerType()) 3327 ConvType = ConvPtrType->getPointeeType(); 3328 3329 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto()) 3330 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet); 3331 } 3332 3333 // Perform overload resolution. 3334 OverloadCandidateSet::iterator Best; 3335 switch (BestViableFunction(CandidateSet, Best)) { 3336 case OR_Success: 3337 // Overload resolution succeeded; we'll build the appropriate call 3338 // below. 3339 break; 3340 3341 case OR_No_Viable_Function: 3342 Diag(Object->getSourceRange().getBegin(), 3343 diag::err_ovl_no_viable_object_call) 3344 << Object->getType() << (unsigned)CandidateSet.size() 3345 << Object->getSourceRange(); 3346 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3347 break; 3348 3349 case OR_Ambiguous: 3350 Diag(Object->getSourceRange().getBegin(), 3351 diag::err_ovl_ambiguous_object_call) 3352 << Object->getType() << Object->getSourceRange(); 3353 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3354 break; 3355 } 3356 3357 if (Best == CandidateSet.end()) { 3358 // We had an error; delete all of the subexpressions and return 3359 // the error. 3360 delete Object; 3361 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 3362 delete Args[ArgIdx]; 3363 return true; 3364 } 3365 3366 if (Best->Function == 0) { 3367 // Since there is no function declaration, this is one of the 3368 // surrogate candidates. Dig out the conversion function. 3369 CXXConversionDecl *Conv 3370 = cast<CXXConversionDecl>( 3371 Best->Conversions[0].UserDefined.ConversionFunction); 3372 3373 // We selected one of the surrogate functions that converts the 3374 // object parameter to a function pointer. Perform the conversion 3375 // on the object argument, then let ActOnCallExpr finish the job. 3376 // FIXME: Represent the user-defined conversion in the AST! 3377 ImpCastExprToType(Object, 3378 Conv->getConversionType().getNonReferenceType(), 3379 Conv->getConversionType()->isReferenceType()); 3380 return ActOnCallExpr(S, (ExprTy*)Object, LParenLoc, (ExprTy**)Args, NumArgs, 3381 CommaLocs, RParenLoc); 3382 } 3383 3384 // We found an overloaded operator(). Build a CXXOperatorCallExpr 3385 // that calls this method, using Object for the implicit object 3386 // parameter and passing along the remaining arguments. 3387 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 3388 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto(); 3389 3390 unsigned NumArgsInProto = Proto->getNumArgs(); 3391 unsigned NumArgsToCheck = NumArgs; 3392 3393 // Build the full argument list for the method call (the 3394 // implicit object parameter is placed at the beginning of the 3395 // list). 3396 Expr **MethodArgs; 3397 if (NumArgs < NumArgsInProto) { 3398 NumArgsToCheck = NumArgsInProto; 3399 MethodArgs = new Expr*[NumArgsInProto + 1]; 3400 } else { 3401 MethodArgs = new Expr*[NumArgs + 1]; 3402 } 3403 MethodArgs[0] = Object; 3404 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 3405 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 3406 3407 Expr *NewFn = new DeclRefExpr(Method, Method->getType(), 3408 SourceLocation()); 3409 UsualUnaryConversions(NewFn); 3410 3411 // Once we've built TheCall, all of the expressions are properly 3412 // owned. 3413 QualType ResultTy = Method->getResultType().getNonReferenceType(); 3414 llvm::OwningPtr<CXXOperatorCallExpr> 3415 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1, 3416 ResultTy, RParenLoc)); 3417 delete [] MethodArgs; 3418 3419 // Initialize the implicit object parameter. 3420 if (!PerformObjectArgumentInitialization(Object, Method)) 3421 return true; 3422 TheCall->setArg(0, Object); 3423 3424 // Check the argument types. 3425 for (unsigned i = 0; i != NumArgsToCheck; i++) { 3426 QualType ProtoArgType = Proto->getArgType(i); 3427 3428 Expr *Arg; 3429 if (i < NumArgs) 3430 Arg = Args[i]; 3431 else 3432 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i)); 3433 QualType ArgType = Arg->getType(); 3434 3435 // Pass the argument. 3436 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 3437 return true; 3438 3439 TheCall->setArg(i + 1, Arg); 3440 } 3441 3442 // If this is a variadic call, handle args passed through "...". 3443 if (Proto->isVariadic()) { 3444 // Promote the arguments (C99 6.5.2.2p7). 3445 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 3446 Expr *Arg = Args[i]; 3447 DefaultArgumentPromotion(Arg); 3448 TheCall->setArg(i + 1, Arg); 3449 } 3450 } 3451 3452 return CheckFunctionCall(Method, TheCall.take()); 3453} 3454 3455/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 3456/// (if one exists), where @c Base is an expression of class type and 3457/// @c Member is the name of the member we're trying to find. 3458Action::ExprResult 3459Sema::BuildOverloadedArrowExpr(Expr *Base, SourceLocation OpLoc, 3460 SourceLocation MemberLoc, 3461 IdentifierInfo &Member) { 3462 assert(Base->getType()->isRecordType() && "left-hand side must have class type"); 3463 3464 // C++ [over.ref]p1: 3465 // 3466 // [...] An expression x->m is interpreted as (x.operator->())->m 3467 // for a class object x of type T if T::operator->() exists and if 3468 // the operator is selected as the best match function by the 3469 // overload resolution mechanism (13.3). 3470 // FIXME: look in base classes. 3471 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 3472 OverloadCandidateSet CandidateSet; 3473 const RecordType *BaseRecord = Base->getType()->getAsRecordType(); 3474 DeclContext::lookup_const_result Lookup 3475 = BaseRecord->getDecl()->lookup(Context, OpName); 3476 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first; 3477 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps)) 3478 AddMethodCandidate(Method, Base, 0, 0, CandidateSet, 3479 /*SuppressUserConversions=*/false); 3480 else if (OverloadedFunctionDecl *Ovl 3481 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) { 3482 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 3483 FEnd = Ovl->function_end(); 3484 F != FEnd; ++F) { 3485 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F)) 3486 AddMethodCandidate(Method, Base, 0, 0, CandidateSet, 3487 /*SuppressUserConversions=*/false); 3488 } 3489 } 3490 3491 llvm::OwningPtr<Expr> BasePtr(Base); 3492 3493 // Perform overload resolution. 3494 OverloadCandidateSet::iterator Best; 3495 switch (BestViableFunction(CandidateSet, Best)) { 3496 case OR_Success: 3497 // Overload resolution succeeded; we'll build the call below. 3498 break; 3499 3500 case OR_No_Viable_Function: 3501 if (CandidateSet.empty()) 3502 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 3503 << BasePtr->getType() << BasePtr->getSourceRange(); 3504 else 3505 Diag(OpLoc, diag::err_ovl_no_viable_oper) 3506 << "operator->" << (unsigned)CandidateSet.size() 3507 << BasePtr->getSourceRange(); 3508 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3509 return true; 3510 3511 case OR_Ambiguous: 3512 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 3513 << "operator->" << BasePtr->getSourceRange(); 3514 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3515 return true; 3516 } 3517 3518 // Convert the object parameter. 3519 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 3520 if (PerformObjectArgumentInitialization(Base, Method)) 3521 return true; 3522 3523 // No concerns about early exits now. 3524 BasePtr.take(); 3525 3526 // Build the operator call. 3527 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation()); 3528 UsualUnaryConversions(FnExpr); 3529 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1, 3530 Method->getResultType().getNonReferenceType(), 3531 OpLoc); 3532 return ActOnMemberReferenceExpr(Base, OpLoc, tok::arrow, MemberLoc, Member); 3533} 3534 3535/// FixOverloadedFunctionReference - E is an expression that refers to 3536/// a C++ overloaded function (possibly with some parentheses and 3537/// perhaps a '&' around it). We have resolved the overloaded function 3538/// to the function declaration Fn, so patch up the expression E to 3539/// refer (possibly indirectly) to Fn. 3540void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) { 3541 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 3542 FixOverloadedFunctionReference(PE->getSubExpr(), Fn); 3543 E->setType(PE->getSubExpr()->getType()); 3544 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 3545 assert(UnOp->getOpcode() == UnaryOperator::AddrOf && 3546 "Can only take the address of an overloaded function"); 3547 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn); 3548 E->setType(Context.getPointerType(E->getType())); 3549 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 3550 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) && 3551 "Expected overloaded function"); 3552 DR->setDecl(Fn); 3553 E->setType(Fn->getType()); 3554 } else { 3555 assert(false && "Invalid reference to overloaded function"); 3556 } 3557} 3558 3559} // end namespace clang 3560