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