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